






import inspect
import logging
import os
import random
import shutil
import tempfile
import unittest

import pytest
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

from accelerate import Accelerator
from accelerate.test_utils import execute_subprocess_async, require_cuda
from accelerate.utils import ProjectConfiguration, set_seed


__UpperCamelCase      :      Optional[Any]     						=						logging.getLogger(__name__)





def 				snake_case  (     lowerCamelCase=2				,  lowerCamelCase=3				,  lowerCamelCase=16				,  lowerCamelCase = 10				,  lowerCamelCase = 2					):




	'''simple docstring'''







	def get_dataset(lowerCamelCase					):
		__lowercase             =  torch.randn(batch_size * n_batches				,  1					)
		return TensorDataset(lowerCamelCase				,  a * x + b + 0.1 * torch.randn(batch_size * n_batches				,  1					)					)

	__lowercase             =  get_dataset(lowerCamelCase					)
	__lowercase             =  get_dataset(lowerCamelCase					)
	__lowercase             =  DataLoader(lowerCamelCase				,  shuffle=lowerCamelCase				,  batch_size=lowerCamelCase				,  num_workers=4					)
	__lowercase             =  DataLoader(lowerCamelCase				,  shuffle=lowerCamelCase				,  batch_size=lowerCamelCase				,  num_workers=4					)
	return (train_dataloader, valid_dataloader)





def 				snake_case  (     lowerCamelCase				,  lowerCamelCase				,  lowerCamelCase				,  lowerCamelCase				,  lowerCamelCase				,  lowerCamelCase=None					):




	'''simple docstring'''







	__lowercase             =  []
	for epoch in range(lowerCamelCase					):
		# Train quickly
		model.train()
		for batch in dataloader:
			__lowercase       ,						__lowercase             =  batch
			__lowercase             =  model(lowerCamelCase					)
			__lowercase             =  torch.nn.functional.mse_loss(lowerCamelCase				,  lowerCamelCase					)
			accelerator.backward(lowerCamelCase					)
			optimizer.step()
			optimizer.zero_grad()
		rands.append(random.random()					)  # Introduce some randomness
		if scheduler is not None:
			scheduler.step()
	return rands


class        __UpperCamelCase    (     nn.Module   ):







	def __init__(  self      :							int			)		-> Union[str, Any]:
		"""simple docstring"""







		super().__init__()
		__lowercase             =  nn.Parameter(torch.randn(1			)			)
		__lowercase             =  nn.Parameter(torch.randn(1			)			)







	def  _a   (  self      :							Tuple       ,				_lowerCAmelCase      :							Optional[int]			)		-> List[str]:
		"""simple docstring"""







		return x * self.a + self.b


class        __UpperCamelCase    (     unittest.TestCase   ):







	def  _a   (  self      :							Union[str, Any]			)		-> Tuple:
		"""simple docstring"""







		with tempfile.TemporaryDirectory() as tmpdir:
			set_seed(42			)
			__lowercase             =  DummyModel()
			__lowercase             =  torch.optim.Adam(params=model.parameters()       ,				lr=1e-3			)
			__lowercase       ,						__lowercase             =  dummy_dataloaders()
			__lowercase             =  ProjectConfiguration(total_limit=1       ,				project_dir=_lowerCAmelCase       ,				automatic_checkpoint_naming=_lowerCAmelCase			)
			# Train baseline
			__lowercase             =  Accelerator(project_config=_lowerCAmelCase			)
			__lowercase       ,						__lowercase       ,						__lowercase       ,						__lowercase             =  accelerator.prepare(
			    _lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)
			# Save initial
			accelerator.save_state()

			# Save second state
			accelerator.save_state()
			self.assertEqual(len(os.listdir(accelerator.project_dir			)			)       ,				1			)







	def  _a   (  self      :							str			)		-> Optional[int]:
		"""simple docstring"""







		with tempfile.TemporaryDirectory() as tmpdir:
			set_seed(42			)
			__lowercase             =  DummyModel()
			__lowercase             =  torch.optim.Adam(params=model.parameters()       ,				lr=1e-3			)
			__lowercase       ,						__lowercase             =  dummy_dataloaders()
			# Train baseline
			__lowercase             =  Accelerator()
			__lowercase       ,						__lowercase       ,						__lowercase       ,						__lowercase             =  accelerator.prepare(
			    _lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)
			# Save initial
			__lowercase             =  os.path.join(_lowerCAmelCase       ,				"""initial"""			)
			accelerator.save_state(_lowerCAmelCase			)
			((__lowercase)       ,						(__lowercase))             =  model.a.item(), model.b.item()
			__lowercase             =  optimizer.state_dict()
			__lowercase             =  train(3       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)
			((__lowercase)       ,						(__lowercase))             =  model.a.item(), model.b.item()
			__lowercase             =  optimizer.state_dict()

			# Train partially
			set_seed(42			)
			__lowercase             =  DummyModel()
			__lowercase             =  torch.optim.Adam(params=model.parameters()       ,				lr=1e-3			)
			__lowercase       ,						__lowercase             =  dummy_dataloaders()
			__lowercase             =  Accelerator()
			__lowercase       ,						__lowercase       ,						__lowercase       ,						__lowercase             =  accelerator.prepare(
			    _lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)
			accelerator.load_state(_lowerCAmelCase			)
			((__lowercase)       ,						(__lowercase))             =  model.a.item(), model.b.item()
			__lowercase             =  optimizer.state_dict()
			self.assertEqual(_lowerCAmelCase       ,				_lowerCAmelCase			)
			self.assertEqual(_lowerCAmelCase       ,				_lowerCAmelCase			)
			self.assertEqual(_lowerCAmelCase       ,				_lowerCAmelCase			)

			__lowercase             =  train(2       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)
			# Save everything
			__lowercase             =  os.path.join(_lowerCAmelCase       ,				"""checkpoint"""			)
			accelerator.save_state(_lowerCAmelCase			)

			# Load everything back in and make sure all states work
			accelerator.load_state(_lowerCAmelCase			)
			test_rands += train(1       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)
			((__lowercase)       ,						(__lowercase))             =  model.a.item(), model.b.item()
			__lowercase             =  optimizer.state_dict()
			self.assertEqual(_lowerCAmelCase       ,				_lowerCAmelCase			)
			self.assertEqual(_lowerCAmelCase       ,				_lowerCAmelCase			)
			self.assertEqual(_lowerCAmelCase       ,				_lowerCAmelCase			)
			self.assertEqual(_lowerCAmelCase       ,				_lowerCAmelCase			)







	def  _a   (  self      :							Union[str, Any]			)		-> int:
		"""simple docstring"""







		with tempfile.TemporaryDirectory() as tmpdir:
			set_seed(42			)
			__lowercase             =  DummyModel()
			__lowercase             =  torch.optim.Adam(params=model.parameters()       ,				lr=1e-3			)
			__lowercase       ,						__lowercase             =  dummy_dataloaders()
			__lowercase             =  ProjectConfiguration(automatic_checkpoint_naming=_lowerCAmelCase			)

			# Train baseline
			__lowercase             =  Accelerator(project_dir=_lowerCAmelCase       ,				project_config=_lowerCAmelCase			)
			__lowercase       ,						__lowercase       ,						__lowercase       ,						__lowercase             =  accelerator.prepare(
			    _lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)
			# Save initial
			accelerator.save_state()
			((__lowercase)       ,						(__lowercase))             =  model.a.item(), model.b.item()
			__lowercase             =  optimizer.state_dict()
			__lowercase             =  train(3       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)
			((__lowercase)       ,						(__lowercase))             =  model.a.item(), model.b.item()
			__lowercase             =  optimizer.state_dict()

			# Train partially
			set_seed(42			)
			__lowercase             =  DummyModel()
			__lowercase             =  torch.optim.Adam(params=model.parameters()       ,				lr=1e-3			)
			__lowercase       ,						__lowercase             =  dummy_dataloaders()
			__lowercase             =  ProjectConfiguration(iteration=1       ,				automatic_checkpoint_naming=_lowerCAmelCase			)
			__lowercase             =  Accelerator(project_dir=_lowerCAmelCase       ,				project_config=_lowerCAmelCase			)
			__lowercase       ,						__lowercase       ,						__lowercase       ,						__lowercase             =  accelerator.prepare(
			    _lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)
			accelerator.load_state(os.path.join(_lowerCAmelCase       ,				"""checkpoints"""       ,				"""checkpoint_0"""			)			)
			((__lowercase)       ,						(__lowercase))             =  model.a.item(), model.b.item()
			__lowercase             =  optimizer.state_dict()
			self.assertEqual(_lowerCAmelCase       ,				_lowerCAmelCase			)
			self.assertEqual(_lowerCAmelCase       ,				_lowerCAmelCase			)
			self.assertEqual(_lowerCAmelCase       ,				_lowerCAmelCase			)

			__lowercase             =  train(2       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)
			# Save everything
			accelerator.save_state()

			# Load everything back in and make sure all states work
			accelerator.load_state(os.path.join(_lowerCAmelCase       ,				"""checkpoints"""       ,				"""checkpoint_1"""			)			)
			test_rands += train(1       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)
			((__lowercase)       ,						(__lowercase))             =  model.a.item(), model.b.item()
			__lowercase             =  optimizer.state_dict()
			self.assertEqual(_lowerCAmelCase       ,				_lowerCAmelCase			)
			self.assertEqual(_lowerCAmelCase       ,				_lowerCAmelCase			)
			self.assertEqual(_lowerCAmelCase       ,				_lowerCAmelCase			)
			self.assertEqual(_lowerCAmelCase       ,				_lowerCAmelCase			)







	def  _a   (  self      :							Optional[int]			)		-> Any:
		"""simple docstring"""







		__lowercase             =  torch.tensor([1, 2, 3]			)
		__lowercase             =  torch.tensor([2, 3, 4]			)
		__lowercase             =  DummyModel()
		__lowercase             =  torch.optim.Adam(net.parameters()			)
		__lowercase             =  Accelerator()
		with self.assertRaises(_lowerCAmelCase			) as ve:
			accelerator.register_for_checkpointing(_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)
		__lowercase             =  str(ve.exception			)
		self.assertTrue("""Item at index 0""" in message			)
		self.assertTrue("""Item at index 1""" in message			)
		self.assertFalse("""Item at index 2""" in message			)
		self.assertFalse("""Item at index 3""" in message			)







	def  _a   (  self      :							str			)		-> Union[str, Any]:
		"""simple docstring"""







		with tempfile.TemporaryDirectory() as tmpdir:
			set_seed(42			)
			__lowercase             =  DummyModel()
			__lowercase             =  torch.optim.Adam(params=model.parameters()       ,				lr=1e-3			)
			__lowercase             =  torch.optim.lr_scheduler.StepLR(_lowerCAmelCase       ,				step_size=1       ,				gamma=0.99			)
			__lowercase       ,						__lowercase             =  dummy_dataloaders()
			__lowercase             =  ProjectConfiguration(automatic_checkpoint_naming=_lowerCAmelCase			)
			# Train baseline
			__lowercase             =  Accelerator(project_dir=_lowerCAmelCase       ,				project_config=_lowerCAmelCase			)
			__lowercase       ,						__lowercase       ,						__lowercase       ,						__lowercase       ,						__lowercase             =  accelerator.prepare(
			    _lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)
			# Save initial
			accelerator.save_state()
			__lowercase             =  scheduler.state_dict()
			train(3       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)
			self.assertNotEqual(_lowerCAmelCase       ,				scheduler.state_dict()			)

			# Load everything back in and make sure all states work
			accelerator.load_state(os.path.join(_lowerCAmelCase       ,				"""checkpoints"""       ,				"""checkpoint_0"""			)			)
			self.assertEqual(_lowerCAmelCase       ,				scheduler.state_dict()			)







	def  _a   (  self      :							Tuple			)		-> Optional[Any]:
		"""simple docstring"""







		with tempfile.TemporaryDirectory() as tmpdir:
			set_seed(42			)
			__lowercase             =  DummyModel()
			__lowercase             =  ProjectConfiguration(automatic_checkpoint_naming=_lowerCAmelCase       ,				total_limit=2			)
			# Train baseline
			__lowercase             =  Accelerator(project_dir=_lowerCAmelCase       ,				project_config=_lowerCAmelCase			)
			__lowercase             =  accelerator.prepare(_lowerCAmelCase			)
			# Save 3 states:
			for _ in range(11			):
				accelerator.save_state()
			self.assertTrue(not os.path.exists(os.path.join(_lowerCAmelCase       ,				"""checkpoints"""       ,				"""checkpoint_0"""			)			)			)
			self.assertTrue(os.path.exists(os.path.join(_lowerCAmelCase       ,				"""checkpoints"""       ,				"""checkpoint_9"""			)			)			)
			self.assertTrue(os.path.exists(os.path.join(_lowerCAmelCase       ,				"""checkpoints"""       ,				"""checkpoint_10"""			)			)			)







	@require_cuda
	def  _a   (  self      :							Union[str, Any]			)		-> Optional[Any]:
		"""simple docstring"""







		__lowercase             =  ["""torchrun""", F'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__			)]
		execute_subprocess_async(_lowerCAmelCase       ,				env=os.environ.copy()			)


if __name__ == "__main__":
						__UpperCamelCase      :      Dict     						=						"""/tmp/accelerate/state_checkpointing"""
						__UpperCamelCase      :      str     						=						DummyModel()
						__UpperCamelCase      :      int     						=						torch.optim.Adam(params=model.parameters(), lr=1e-3)
						__UpperCamelCase      :      List[str]     						=						torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.9_9)
						__UpperCamelCase						,					__UpperCamelCase      :      Optional[int]     						=						dummy_dataloaders()
						__UpperCamelCase      :      str     						=						ProjectConfiguration(automatic_checkpoint_naming=True)
						# Train baseline
						__UpperCamelCase      :      List[Any]     						=						Accelerator(project_dir=savedir, project_config=project_config, mixed_precision="""no""")
						if accelerator.process_index == 0:
												if os.path.exists(savedir):
																		shutil.rmtree(savedir)
												os.makedirs(savedir)
						__UpperCamelCase						,					__UpperCamelCase						,					__UpperCamelCase						,					__UpperCamelCase						,					__UpperCamelCase      :      str     						=						accelerator.prepare(
						    model, optimizer, train_dataloader, valid_dataloader, scheduler
						)
						__UpperCamelCase						,					__UpperCamelCase      :      Any     						=						accelerator.prepare(model, optimizer)
						train(3, model, train_dataloader, optimizer, accelerator, scheduler)
						# Check that the intial optimizer is loaded on the GPU
						for group in optimizer.param_groups:
												__UpperCamelCase      :      Optional[int]     						=						group["""params"""][0].device
												break
						assert param_device.type == accelerator.device.type
						__UpperCamelCase      :      int     						=						model.cpu()
						accelerator.wait_for_everyone()
						accelerator.save_state()
						accelerator.wait_for_everyone()

						# Check CPU state
						accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""cpu""")
						for group in optimizer.param_groups:
												__UpperCamelCase      :      Optional[Any]     						=						group["""params"""][0].device
												break
						assert (
						    param_device.type == torch.device("""cpu""").type
						), F"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}"

						# Check device state
						model.to(accelerator.device)
						accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""on_device""")
						for group in optimizer.param_groups:
												__UpperCamelCase      :      str     						=						group["""params"""][0].device
												break
						assert (
						    param_device.type == accelerator.device.type
						), F"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}"

						# Check error
						with pytest.raises(TypeError, match="""Unsupported optimizer map location passed"""):
												accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""invalid""")
						accelerator.wait_for_everyone()
						if accelerator.process_index == 0:
												shutil.rmtree(savedir)
						accelerator.wait_for_everyone()









import tempfile
import unittest

import numpy as np

from diffusers import (
    DDIMScheduler,
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionPipeline,
    PNDMScheduler,
)
from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
						import onnxruntime as ort


class        __UpperCamelCase    (     _lowerCAmelCase   ,			unittest.TestCase   ):
	__snake_case	:Union[str, Any]   =       'hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'







	def  _a   (  self      :							Any       ,				_lowerCAmelCase      :							str=0			)		-> str:
		"""simple docstring"""







		__lowercase             =  np.random.RandomState(_lowerCAmelCase			)
		__lowercase             =  {
		    """prompt""": """A painting of a squirrel eating a burger""",
		    """generator""": generator,
		    """num_inference_steps""": 2,
		    """guidance_scale""": 7.5,
		    """output_type""": """numpy""",
		}
		return inputs







	def  _a   (  self      :							int			)		-> List[Any]:
		"""simple docstring"""







		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint       ,				provider="""CPUExecutionProvider"""			)
		pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

		__lowercase             =  self.get_dummy_inputs()
		__lowercase             =  pipe(**_lowerCAmelCase			).images
		__lowercase             =  image[0, -3:, -3:, -1]

		assert image.shape == (1, 128, 128, 3)
		__lowercase             =  np.array([0.65_072, 0.58_492, 0.48_219, 0.55_521, 0.53_180, 0.55_939, 0.50_697, 0.39_800, 0.46_455]			)

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







	def  _a   (  self      :							Union[str, Any]			)		-> str:
		"""simple docstring"""







		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint       ,				provider="""CPUExecutionProvider"""			)
		__lowercase             =  PNDMScheduler.from_config(pipe.scheduler.config       ,				skip_prk_steps=_lowerCAmelCase			)
		pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

		__lowercase             =  self.get_dummy_inputs()
		__lowercase             =  pipe(**_lowerCAmelCase			).images
		__lowercase             =  image[0, -3:, -3:, -1]

		assert image.shape == (1, 128, 128, 3)
		__lowercase             =  np.array([0.65_863, 0.59_425, 0.49_326, 0.56_313, 0.53_875, 0.56_627, 0.51_065, 0.39_777, 0.46_330]			)

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







	def  _a   (  self      :							Optional[int]			)		-> Optional[int]:
		"""simple docstring"""







		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint       ,				provider="""CPUExecutionProvider"""			)
		__lowercase             =  LMSDiscreteScheduler.from_config(pipe.scheduler.config			)
		pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

		__lowercase             =  self.get_dummy_inputs()
		__lowercase             =  pipe(**_lowerCAmelCase			).images
		__lowercase             =  image[0, -3:, -3:, -1]

		assert image.shape == (1, 128, 128, 3)
		__lowercase             =  np.array([0.53_755, 0.60_786, 0.47_402, 0.49_488, 0.51_869, 0.49_819, 0.47_985, 0.38_957, 0.44_279]			)

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







	def  _a   (  self      :							Tuple			)		-> int:
		"""simple docstring"""







		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint       ,				provider="""CPUExecutionProvider"""			)
		__lowercase             =  EulerDiscreteScheduler.from_config(pipe.scheduler.config			)
		pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

		__lowercase             =  self.get_dummy_inputs()
		__lowercase             =  pipe(**_lowerCAmelCase			).images
		__lowercase             =  image[0, -3:, -3:, -1]

		assert image.shape == (1, 128, 128, 3)
		__lowercase             =  np.array([0.53_755, 0.60_786, 0.47_402, 0.49_488, 0.51_869, 0.49_819, 0.47_985, 0.38_957, 0.44_279]			)

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







	def  _a   (  self      :							Tuple			)		-> Union[str, Any]:
		"""simple docstring"""







		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint       ,				provider="""CPUExecutionProvider"""			)
		__lowercase             =  EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config			)
		pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

		__lowercase             =  self.get_dummy_inputs()
		__lowercase             =  pipe(**_lowerCAmelCase			).images
		__lowercase             =  image[0, -3:, -3:, -1]

		assert image.shape == (1, 128, 128, 3)
		__lowercase             =  np.array([0.53_817, 0.60_812, 0.47_384, 0.49_530, 0.51_894, 0.49_814, 0.47_984, 0.38_958, 0.44_271]			)

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







	def  _a   (  self      :							Union[str, Any]			)		-> List[str]:
		"""simple docstring"""







		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint       ,				provider="""CPUExecutionProvider"""			)
		__lowercase             =  DPMSolverMultistepScheduler.from_config(pipe.scheduler.config			)
		pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

		__lowercase             =  self.get_dummy_inputs()
		__lowercase             =  pipe(**_lowerCAmelCase			).images
		__lowercase             =  image[0, -3:, -3:, -1]

		assert image.shape == (1, 128, 128, 3)
		__lowercase             =  np.array([0.53_895, 0.60_808, 0.47_933, 0.49_608, 0.51_886, 0.49_950, 0.48_053, 0.38_957, 0.44_200]			)

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







	def  _a   (  self      :							List[str]			)		-> List[str]:
		"""simple docstring"""







		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint       ,				provider="""CPUExecutionProvider"""			)
		pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

		__lowercase             =  self.get_dummy_inputs()
		__lowercase             =  3 * [inputs["""prompt"""]]

		# forward
		__lowercase             =  pipe(**_lowerCAmelCase			)
		__lowercase             =  output.images[0, -3:, -3:, -1]

		__lowercase             =  self.get_dummy_inputs()
		__lowercase             =  3 * [inputs.pop("""prompt"""			)]

		__lowercase             =  pipe.tokenizer(
		    _lowerCAmelCase       ,				padding="""max_length"""       ,				max_length=pipe.tokenizer.model_max_length       ,				truncation=_lowerCAmelCase       ,				return_tensors="""np"""       ,				)
		__lowercase             =  text_inputs["""input_ids"""]

		__lowercase             =  pipe.text_encoder(input_ids=text_inputs.astype(np.intaa			)			)[0]

		__lowercase             =  prompt_embeds

		# forward
		__lowercase             =  pipe(**_lowerCAmelCase			)
		__lowercase             =  output.images[0, -3:, -3:, -1]

		assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()			).max() < 1e-4







	def  _a   (  self      :							int			)		-> str:
		"""simple docstring"""







		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint       ,				provider="""CPUExecutionProvider"""			)
		pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

		__lowercase             =  self.get_dummy_inputs()
		__lowercase             =  3 * ["""this is a negative prompt"""]
		__lowercase             =  negative_prompt
		__lowercase             =  3 * [inputs["""prompt"""]]

		# forward
		__lowercase             =  pipe(**_lowerCAmelCase			)
		__lowercase             =  output.images[0, -3:, -3:, -1]

		__lowercase             =  self.get_dummy_inputs()
		__lowercase             =  3 * [inputs.pop("""prompt"""			)]

		__lowercase             =  []
		for p in [prompt, negative_prompt]:
			__lowercase             =  pipe.tokenizer(
			    _lowerCAmelCase       ,				padding="""max_length"""       ,				max_length=pipe.tokenizer.model_max_length       ,				truncation=_lowerCAmelCase       ,				return_tensors="""np"""       ,				)
			__lowercase             =  text_inputs["""input_ids"""]

			embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa			)			)[0]			)

		__lowercase       ,						__lowercase             =  embeds

		# forward
		__lowercase             =  pipe(**_lowerCAmelCase			)
		__lowercase             =  output.images[0, -3:, -3:, -1]

		assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()			).max() < 1e-4


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







	@property
	def  _a   (  self      :							Dict			)		-> str:
		"""simple docstring"""







		return (
		    "CUDAExecutionProvider",
		    {
		        "gpu_mem_limit": "15000000000",  # 15GB
		        "arena_extend_strategy": "kSameAsRequested",
		    },
		)







	@property
	def  _a   (  self      :							Optional[Any]			)		-> Optional[Any]:
		"""simple docstring"""







		__lowercase             =  ort.SessionOptions()
		__lowercase             =  False
		return options







	def  _a   (  self      :							List[Any]			)		-> Union[str, Any]:
		"""simple docstring"""







		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(
		    """CompVis/stable-diffusion-v1-4"""       ,				revision="""onnx"""       ,				safety_checker=_lowerCAmelCase       ,				feature_extractor=_lowerCAmelCase       ,				provider=self.gpu_provider       ,				sess_options=self.gpu_options       ,				)
		sd_pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

		__lowercase             =  """A painting of a squirrel eating a burger"""
		np.random.seed(0			)
		__lowercase             =  sd_pipe([prompt]       ,				guidance_scale=6.0       ,				num_inference_steps=10       ,				output_type="""np"""			)
		__lowercase             =  output.images

		__lowercase             =  image[0, -3:, -3:, -1]

		assert image.shape == (1, 512, 512, 3)
		__lowercase             =  np.array([0.0_452, 0.0_390, 0.0_087, 0.0_350, 0.0_617, 0.0_364, 0.0_544, 0.0_523, 0.0_720]			)

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







	def  _a   (  self      :							Tuple			)		-> Any:
		"""simple docstring"""







		__lowercase             =  DDIMScheduler.from_pretrained(
		    """runwayml/stable-diffusion-v1-5"""       ,				subfolder="""scheduler"""       ,				revision="""onnx"""			)
		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(
		    """runwayml/stable-diffusion-v1-5"""       ,				revision="""onnx"""       ,				scheduler=_lowerCAmelCase       ,				safety_checker=_lowerCAmelCase       ,				feature_extractor=_lowerCAmelCase       ,				provider=self.gpu_provider       ,				sess_options=self.gpu_options       ,				)
		sd_pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

		__lowercase             =  """open neural network exchange"""
		__lowercase             =  np.random.RandomState(0			)
		__lowercase             =  sd_pipe([prompt]       ,				guidance_scale=7.5       ,				num_inference_steps=10       ,				generator=_lowerCAmelCase       ,				output_type="""np"""			)
		__lowercase             =  output.images
		__lowercase             =  image[0, -3:, -3:, -1]

		assert image.shape == (1, 512, 512, 3)
		__lowercase             =  np.array([0.2_867, 0.1_974, 0.1_481, 0.7_294, 0.7_251, 0.6_667, 0.4_194, 0.5_642, 0.6_486]			)

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







	def  _a   (  self      :							Dict			)		-> Dict:
		"""simple docstring"""







		__lowercase             =  LMSDiscreteScheduler.from_pretrained(
		    """runwayml/stable-diffusion-v1-5"""       ,				subfolder="""scheduler"""       ,				revision="""onnx"""			)
		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(
		    """runwayml/stable-diffusion-v1-5"""       ,				revision="""onnx"""       ,				scheduler=_lowerCAmelCase       ,				safety_checker=_lowerCAmelCase       ,				feature_extractor=_lowerCAmelCase       ,				provider=self.gpu_provider       ,				sess_options=self.gpu_options       ,				)
		sd_pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

		__lowercase             =  """open neural network exchange"""
		__lowercase             =  np.random.RandomState(0			)
		__lowercase             =  sd_pipe([prompt]       ,				guidance_scale=7.5       ,				num_inference_steps=10       ,				generator=_lowerCAmelCase       ,				output_type="""np"""			)
		__lowercase             =  output.images
		__lowercase             =  image[0, -3:, -3:, -1]

		assert image.shape == (1, 512, 512, 3)
		__lowercase             =  np.array([0.2_306, 0.1_959, 0.1_593, 0.6_549, 0.6_394, 0.5_408, 0.5_065, 0.6_010, 0.6_161]			)

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







	def  _a   (  self      :							str			)		-> List[str]:
		"""simple docstring"""







		__lowercase             =  0

		def test_callback_fn(_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							np.ndarray			) -> None:
			__lowercase             =  True
			nonlocal number_of_steps
			number_of_steps += 1
			if step == 0:
				assert latents.shape == (1, 4, 64, 64)
				__lowercase             =  latents[0, -3:, -3:, -1]
				__lowercase             =  np.array(
				    [-0.6_772, -0.3_835, -1.2_456, 0.1_905, -1.0_974, 0.6_967, -1.9_353, 0.0_178, 1.0_167]			)

				assert np.abs(latents_slice.flatten() - expected_slice			).max() < 1e-3
			elif step == 5:
				assert latents.shape == (1, 4, 64, 64)
				__lowercase             =  latents[0, -3:, -3:, -1]
				__lowercase             =  np.array(
				    [-0.3_351, 0.2_241, -0.1_837, -0.2_325, -0.6_577, 0.3_393, -0.0_241, 0.5_899, 1.3_875]			)

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

		__lowercase             =  False

		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(
		    """runwayml/stable-diffusion-v1-5"""       ,				revision="""onnx"""       ,				safety_checker=_lowerCAmelCase       ,				feature_extractor=_lowerCAmelCase       ,				provider=self.gpu_provider       ,				sess_options=self.gpu_options       ,				)
		pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

		__lowercase             =  """Andromeda galaxy in a bottle"""

		__lowercase             =  np.random.RandomState(0			)
		pipe(
		    prompt=_lowerCAmelCase       ,				num_inference_steps=5       ,				guidance_scale=7.5       ,				generator=_lowerCAmelCase       ,				callback=_lowerCAmelCase       ,				callback_steps=1       ,				)
		assert test_callback_fn.has_been_called
		assert number_of_steps == 6







	def  _a   (  self      :							Union[str, Any]			)		-> Tuple:
		"""simple docstring"""







		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(
		    """runwayml/stable-diffusion-v1-5"""       ,				revision="""onnx"""       ,				safety_checker=_lowerCAmelCase       ,				feature_extractor=_lowerCAmelCase       ,				provider=self.gpu_provider       ,				sess_options=self.gpu_options       ,				)
		assert isinstance(_lowerCAmelCase       ,				_lowerCAmelCase			)
		assert pipe.safety_checker is None

		__lowercase             =  pipe("""example prompt"""       ,				num_inference_steps=2			).images[0]
		assert image is not None

		# check that there's no error when saving a pipeline with one of the models being None
		with tempfile.TemporaryDirectory() as tmpdirname:
			pipe.save_pretrained(_lowerCAmelCase			)
			__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(_lowerCAmelCase			)

		# sanity check that the pipeline still works
		assert pipe.safety_checker is None
		__lowercase             =  pipe("""example prompt"""       ,				num_inference_steps=2			).images[0]
		assert image is not None

