'''simple docstring'''

import random
import unittest

import numpy as np

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionImgaImgPipeline,
    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 				_lowercase	(      lowerCAmelCase		,unittest.TestCase   ):
      '''simple docstring'''


      UpperCAmelCase_      :      List[str]      							=   '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'''




      def 		lowerCAmelCase__					(				self					,lowerCamelCase_=0							)			->			int:



         '''simple docstring'''



         UpperCAmelCase__							:				int   				=  floats_tensor((1, 3, 128, 128)					,rng=random.Random(lowerCamelCase_							)							)
         UpperCAmelCase__							:				str   				=  np.random.RandomState(lowerCamelCase_							)
         UpperCAmelCase__							:				Any   				=  {
             '''prompt''': '''A painting of a squirrel eating a burger''',
             '''image''': image,
             '''generator''': generator,
             '''num_inference_steps''': 3,
             '''strength''': 0.75,
             '''guidance_scale''': 7.5,
             '''output_type''': '''numpy''',
         }
         return inputs




      def 		lowerCAmelCase__					(				self							)			->			List[Any]:



         '''simple docstring'''



         UpperCAmelCase__							:				str   				=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint					,provider='''CPUExecutionProvider'''							)
         pipe.set_progress_bar_config(disable=lowerCamelCase_							)

         UpperCAmelCase__							:				Any   				=  self.get_dummy_inputs()
         UpperCAmelCase__							:				str   				=  pipe(**lowerCamelCase_							).images
         UpperCAmelCase__							:				Tuple   				=  image[0, -3:, -3:, -1].flatten()

         assert image.shape == (1, 128, 128, 3)
         UpperCAmelCase__							:				Union[str, Any]   				=  np.array([0.6_9643, 0.5_8484, 0.5_0314, 0.5_8760, 0.5_5368, 0.5_9643, 0.5_1529, 0.4_1217, 0.4_9087]							)
         assert np.abs(image_slice - expected_slice							).max() < 1e-1




      def 		lowerCAmelCase__					(				self							)			->			Union[str, Any]:



         '''simple docstring'''



         UpperCAmelCase__							:				List[str]   				=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint					,provider='''CPUExecutionProvider'''							)
         UpperCAmelCase__							:				str   				=  PNDMScheduler.from_config(pipe.scheduler.config					,skip_prk_steps=lowerCamelCase_							)
         pipe.set_progress_bar_config(disable=lowerCamelCase_							)

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

         assert image.shape == (1, 128, 128, 3)
         UpperCAmelCase__							:				int   				=  np.array([0.6_1737, 0.5_4642, 0.5_3183, 0.5_4465, 0.5_2742, 0.6_0525, 0.4_9969, 0.4_0655, 0.4_8154]							)

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




      def 		lowerCAmelCase__					(				self							)			->			List[Any]:



         '''simple docstring'''



         UpperCAmelCase__							:				Optional[Any]   				=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint					,provider='''CPUExecutionProvider'''							)
         UpperCAmelCase__							:				Optional[Any]   				=  LMSDiscreteScheduler.from_config(pipe.scheduler.config							)
         pipe.set_progress_bar_config(disable=lowerCamelCase_							)

         # warmup pass to apply optimizations
         UpperCAmelCase__							:				int   				=  pipe(**self.get_dummy_inputs()							)

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

         assert image.shape == (1, 128, 128, 3)
         UpperCAmelCase__							:				List[Any]   				=  np.array([0.5_2761, 0.5_9977, 0.4_9033, 0.4_9619, 0.5_4282, 0.5_0311, 0.4_7600, 0.4_0918, 0.4_5203]							)

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




      def 		lowerCAmelCase__					(				self							)			->			int:



         '''simple docstring'''



         UpperCAmelCase__							:				Any   				=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint					,provider='''CPUExecutionProvider'''							)
         UpperCAmelCase__							:				Union[str, Any]   				=  EulerDiscreteScheduler.from_config(pipe.scheduler.config							)
         pipe.set_progress_bar_config(disable=lowerCamelCase_							)

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

         assert image.shape == (1, 128, 128, 3)
         UpperCAmelCase__							:				Union[str, Any]   				=  np.array([0.5_2911, 0.6_0004, 0.4_9229, 0.4_9805, 0.5_4502, 0.5_0680, 0.4_7777, 0.4_1028, 0.4_5304]							)

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




      def 		lowerCAmelCase__					(				self							)			->			int:



         '''simple docstring'''



         UpperCAmelCase__							:				Dict   				=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint					,provider='''CPUExecutionProvider'''							)
         UpperCAmelCase__							:				Dict   				=  EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config							)
         pipe.set_progress_bar_config(disable=lowerCamelCase_							)

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

         assert image.shape == (1, 128, 128, 3)
         UpperCAmelCase__							:				Optional[Any]   				=  np.array([0.5_2911, 0.6_0004, 0.4_9229, 0.4_9805, 0.5_4502, 0.5_0680, 0.4_7777, 0.4_1028, 0.4_5304]							)

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




      def 		lowerCAmelCase__					(				self							)			->			Any:



         '''simple docstring'''



         UpperCAmelCase__							:				str   				=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint					,provider='''CPUExecutionProvider'''							)
         UpperCAmelCase__							:				Tuple   				=  DPMSolverMultistepScheduler.from_config(pipe.scheduler.config							)
         pipe.set_progress_bar_config(disable=lowerCamelCase_							)

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

         assert image.shape == (1, 128, 128, 3)
         UpperCAmelCase__							:				str   				=  np.array([0.6_5331, 0.5_8277, 0.4_8204, 0.5_6059, 0.5_3665, 0.5_6235, 0.5_0969, 0.4_0009, 0.4_6552]							)

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




@nightly
@require_onnxruntime
@require_torch_gpu
class 				_lowercase	(      unittest.TestCase   ):
      '''simple docstring'''


      @property
      def 		lowerCAmelCase__					(				self							)			->			List[Any]:



         '''simple docstring'''



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




      @property
      def 		lowerCAmelCase__					(				self							)			->			str:



         '''simple docstring'''



         UpperCAmelCase__							:				Optional[Any]   				=  ort.SessionOptions()
         UpperCAmelCase__							:				Tuple   				=  False
         return options




      def 		lowerCAmelCase__					(				self							)			->			Tuple:



         '''simple docstring'''



         UpperCAmelCase__							:				List[Any]   				=  load_image(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
             '''/img2img/sketch-mountains-input.jpg'''							)
         UpperCAmelCase__							:				Union[str, Any]   				=  init_image.resize((768, 512)							)
         # using the PNDM scheduler by default
         UpperCAmelCase__							:				List[Any]   				=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(
             '''CompVis/stable-diffusion-v1-4'''					,revision='''onnx'''					,safety_checker=lowerCamelCase_					,feature_extractor=lowerCamelCase_					,provider=self.gpu_provider					,sess_options=self.gpu_options					,)
         pipe.set_progress_bar_config(disable=lowerCamelCase_							)

         UpperCAmelCase__							:				List[Any]   				=  '''A fantasy landscape, trending on artstation'''

         UpperCAmelCase__							:				List[str]   				=  np.random.RandomState(0							)
         UpperCAmelCase__							:				Optional[Any]   				=  pipe(
             prompt=lowerCamelCase_					,image=lowerCamelCase_					,strength=0.75					,guidance_scale=7.5					,num_inference_steps=10					,generator=lowerCamelCase_					,output_type='''np'''					,)
         UpperCAmelCase__							:				List[str]   				=  output.images
         UpperCAmelCase__							:				str   				=  images[0, 255:258, 383:386, -1]

         assert images.shape == (1, 512, 768, 3)
         UpperCAmelCase__							:				str   				=  np.array([0.4909, 0.5059, 0.5372, 0.4623, 0.4876, 0.5049, 0.4820, 0.4956, 0.5019]							)
         # 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							)			->			Optional[int]:



         '''simple docstring'''



         UpperCAmelCase__							:				Any   				=  load_image(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
             '''/img2img/sketch-mountains-input.jpg'''							)
         UpperCAmelCase__							:				Dict   				=  init_image.resize((768, 512)							)
         UpperCAmelCase__							:				List[str]   				=  LMSDiscreteScheduler.from_pretrained(
             '''runwayml/stable-diffusion-v1-5'''					,subfolder='''scheduler'''					,revision='''onnx'''							)
         UpperCAmelCase__							:				Dict   				=  OnnxStableDiffusionImgaImgPipeline.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					,)
         pipe.set_progress_bar_config(disable=lowerCamelCase_							)

         UpperCAmelCase__							:				str   				=  '''A fantasy landscape, trending on artstation'''

         UpperCAmelCase__							:				int   				=  np.random.RandomState(0							)
         UpperCAmelCase__							:				Union[str, Any]   				=  pipe(
             prompt=lowerCamelCase_					,image=lowerCamelCase_					,strength=0.75					,guidance_scale=7.5					,num_inference_steps=20					,generator=lowerCamelCase_					,output_type='''np'''					,)
         UpperCAmelCase__							:				Any   				=  output.images
         UpperCAmelCase__							:				Tuple   				=  images[0, 255:258, 383:386, -1]

         assert images.shape == (1, 512, 768, 3)
         UpperCAmelCase__							:				Tuple   				=  np.array([0.8043, 0.926, 0.9581, 0.8119, 0.8954, 0.913, 0.7209, 0.7463, 0.7431]							)
         # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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





'''simple docstring'''

# Logistic Regression from scratch

# In[62]:

# In[63]:

# importing all the required libraries

import numpy as np
from matplotlib import pyplot as plt
from sklearn import datasets







def __UpperCamelCase(   _A					:				str    ):
   '''simple docstring'''
   return 1 / (1 + np.exp(-z    ))







def __UpperCamelCase(   _A					:				int  ,			_A					:				str    ):
   '''simple docstring'''
   return (-y * np.log(_A    ) - (1 - y) * np.log(1 - h    )).mean()







def __UpperCamelCase(   _A					:				Optional[Any]  ,			_A					:				Tuple  ,			_A					:				Any    ):
   '''simple docstring'''
   UpperCAmelCase__							:				Union[str, Any]   				=  np.dot(_A  ,			_A    )
   return np.sum(y * scores - np.log(1 + np.exp(_A    )    )    )







def __UpperCamelCase(   _A					:				Dict  ,			_A					:				Optional[int]  ,			_A					:				List[Any]  ,			_A					:				str=7_00_00    ):
   '''simple docstring'''
   UpperCAmelCase__							:				List[Any]   				=  np.zeros(x.shape[1]    )

   for iterations in range(_A    ):
      UpperCAmelCase__							:				Tuple   				=  np.dot(_A  ,			_A    )
      UpperCAmelCase__							:				Optional[Any]   				=  sigmoid_function(_A    )
      UpperCAmelCase__							:				Optional[int]   				=  np.dot(x.T  ,			h - y    ) / y.size
      UpperCAmelCase__							:				List[Any]   				=  theta - alpha * gradient  # updating the weights
      UpperCAmelCase__							:				Tuple   				=  np.dot(_A  ,			_A    )
      UpperCAmelCase__							:				Tuple   				=  sigmoid_function(_A    )
      UpperCAmelCase__							:				Optional[int]   				=  cost_function(_A  ,			_A    )
      if iterations % 1_00 == 0:
         print(F'''loss: {j} \t'''    )  # printing the loss after every 100 iterations
   return theta


# In[68]:

if __name__ == "__main__":
  UpperCamelCase__     :	str				=			datasets.load_iris()
  UpperCamelCase__     :	Tuple				=			iris.data[:, :2]
  UpperCamelCase__     :	str				=			(iris.target != 0) * 1

  UpperCamelCase__     :	Any				=			0.1
  UpperCamelCase__     :	List[str]				=			logistic_reg(alpha, x, y, max_iterations=70_000)
  print('theta: ', theta)  # printing the theta i.e our weights vector







  def __UpperCamelCase(   _A					:				Any    ):
     '''simple docstring'''
     return sigmoid_function(
         np.dot(_A  ,			_A    )    )  # predicting the value of probability from the logistic regression algorithm

  plt.figure(figsize=(10, 6))
  plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color='b', label='0')
  plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color='r', label='1')
  ((UpperCamelCase__)				,     (UpperCamelCase__))     :	Any				=			(x[:, 0].min(), x[:, 0].max())
  ((UpperCamelCase__)				,     (UpperCamelCase__))     :	Optional[Any]				=			(x[:, 1].min(), x[:, 1].max())
  ((UpperCamelCase__)				,     (UpperCamelCase__))     :	Any				=			np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max))
  UpperCamelCase__     :	str				=			np.c_[xxa.ravel(), xxa.ravel()]
  UpperCamelCase__     :	Union[str, Any]				=			predict_prob(grid).reshape(xxa.shape)
  plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors='black')

  plt.legend()
  plt.show()




