




import numpy




class 						__lowercase		:




      """simple docstring"""





      def __init__(				self    ,				A    ,				A     )		->    None:
         snake_case				:    List[Any]           =	input_array

         # Random initial weights are assigned where first argument is the
         # number of nodes in previous layer and second argument is the
         # number of nodes in the next layer.

         # Random initial weights are assigned.
         # self.input_array.shape[1] is used to represent number of nodes in input layer.
         # First hidden layer consists of 4 nodes.
         snake_case				:    Dict           =	numpy.random.rand(
             self.input_array.shape[1]    ,				4     )

         # Random initial values for the first hidden layer.
         # First hidden layer has 4 nodes.
         # Second hidden layer has 3 nodes.
         snake_case				:    Optional[Any]           =	numpy.random.rand(
             4    ,				3     )

         # Random initial values for the second hidden layer.
         # Second hidden layer has 3 nodes.
         # Output layer has 1 node.
         snake_case				:    int           =	numpy.random.rand(3    ,				1     )

         # Real output values provided.
         snake_case				:    List[str]           =	output_array

         # Predicted output values by the neural network.
         # Predicted_output array initially consists of zeroes.
         snake_case				:    Union[str, Any]           =	numpy.zeros(output_array.shape     )

      def      UpperCAmelCase				(				self     )		->    numpy.ndarray:
         snake_case				:    List[Any]           =	sigmoid(
             numpy.dot(self.input_array    ,				self.input_layer_and_first_hidden_layer_weights     )     )

         # layer_between_first_hidden_layer_and_second_hidden_layer is the layer
         # connecting the first hidden set of nodes with the second hidden set of nodes.
         snake_case				:    Any           =	sigmoid(
             numpy.dot(
                 self.layer_between_input_and_first_hidden_layer    ,				self.first_hidden_layer_and_second_hidden_layer_weights    ,				)     )

         # layer_between_second_hidden_layer_and_output is the layer connecting
         # second hidden layer with the output node.
         snake_case				:    int           =	sigmoid(
             numpy.dot(
                 self.layer_between_first_hidden_layer_and_second_hidden_layer    ,				self.second_hidden_layer_and_output_layer_weights    ,				)     )

         return self.layer_between_second_hidden_layer_and_output

      def      UpperCAmelCase				(				self     )		->    None:
         snake_case				:    Tuple           =	numpy.dot(
             self.layer_between_first_hidden_layer_and_second_hidden_layer.T    ,				2
             * (self.output_array - self.predicted_output)
             * sigmoid_derivative(self.predicted_output     )    ,				)
         snake_case				:    Dict           =	numpy.dot(
             self.layer_between_input_and_first_hidden_layer.T    ,				numpy.dot(
                 2
                 * (self.output_array - self.predicted_output)
                 * sigmoid_derivative(self.predicted_output     )    ,				self.second_hidden_layer_and_output_layer_weights.T    ,				)
             * sigmoid_derivative(
                 self.layer_between_first_hidden_layer_and_second_hidden_layer     )    ,				)
         snake_case				:    Union[str, Any]           =	numpy.dot(
             self.input_array.T    ,				numpy.dot(
                 numpy.dot(
                     2
                     * (self.output_array - self.predicted_output)
                     * sigmoid_derivative(self.predicted_output     )    ,				self.second_hidden_layer_and_output_layer_weights.T    ,				)
                 * sigmoid_derivative(
                     self.layer_between_first_hidden_layer_and_second_hidden_layer     )    ,				self.first_hidden_layer_and_second_hidden_layer_weights.T    ,				)
             * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer     )    ,				)

         self.input_layer_and_first_hidden_layer_weights += (
             updated_input_layer_and_first_hidden_layer_weights
         )
         self.first_hidden_layer_and_second_hidden_layer_weights += (
             updated_first_hidden_layer_and_second_hidden_layer_weights
         )
         self.second_hidden_layer_and_output_layer_weights += (
             updated_second_hidden_layer_and_output_layer_weights
         )

      def      UpperCAmelCase				(				self    ,				A    ,				A    ,				A     )		->    None:
         for iteration in range(1    ,				iterations + 1     ):
            snake_case				:    Any           =	self.feedforward()
            self.back_propagation()
            if give_loss:
               snake_case				:    Optional[int]           =	numpy.mean(numpy.square(output - self.feedforward()     )     )
               print(f"""Iteration {iteration} Loss: {loss}"""     )

      def      UpperCAmelCase				(				self    ,				A     )		->    int:
         snake_case				:    Optional[Any]           =	input_arr

         snake_case				:    Optional[int]           =	sigmoid(
             numpy.dot(self.array    ,				self.input_layer_and_first_hidden_layer_weights     )     )

         snake_case				:    Optional[Any]           =	sigmoid(
             numpy.dot(
                 self.layer_between_input_and_first_hidden_layer    ,				self.first_hidden_layer_and_second_hidden_layer_weights    ,				)     )

         snake_case				:    Dict           =	sigmoid(
             numpy.dot(
                 self.layer_between_first_hidden_layer_and_second_hidden_layer    ,				self.second_hidden_layer_and_output_layer_weights    ,				)     )

         return int(self.layer_between_second_hidden_layer_and_output > 0.6     )




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       numpy.ndarray:
   return 1 / (1 + numpy.exp(-value					))




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       numpy.ndarray:
   return (value) * (1 - (value))




def 						SCREAMING_SNAKE_CASE__ (   )  ->       int:
   snake_case				:    int           =	numpy.array(
       (
           [0, 0, 0],
           [0, 0, 1],
           [0, 1, 0],
           [0, 1, 1],
           [1, 0, 0],
           [1, 0, 1],
           [1, 1, 0],
           [1, 1, 1],
       )						,dtype=numpy.floataa						,)

   # True output values for the given input values.
   snake_case				:    List[Any]           =	numpy.array(([0], [1], [1], [0], [1], [0], [0], [1])						,dtype=numpy.floataa					)

   # Calling neural network class.
   snake_case				:    Any           =	TwoHiddenLayerNeuralNetwork(
       input_array=lowercase						,output_array=lowercase					)

   # Calling training function.
   # Set give_loss to True if you want to see loss in every iteration.
   neural_network.train(output=lowercase						,iterations=10						,give_loss=lowercase					)

   return neural_network.predict(numpy.array(([1, 1, 1])						,dtype=numpy.floataa					)					)


if __name__ == "__main__":
       example()











import gc
import unittest

import numpy as np
import torch
from torch.backends.cuda import sdp_kernel

from diffusers import (
    CMStochasticIterativeScheduler,
    ConsistencyModelPipeline,
    UNetaDModel,
)
from diffusers.utils import randn_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu

from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()




class 						__lowercase		(UpperCamelCase__					,		unittest.TestCase							):




      """simple docstring"""





      _snake_case												=						ConsistencyModelPipeline
      _snake_case												=						UNCONDITIONAL_IMAGE_GENERATION_PARAMS
      _snake_case												=						UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS

      # Override required_optional_params to remove num_images_per_prompt
      _snake_case												=						frozenset(
          [
              """num_inference_steps""",
              """generator""",
              """latents""",
              """output_type""",
              """return_dict""",
              """callback""",
              """callback_steps""",
          ]							)

      @property
      def      UpperCAmelCase				(				self     )		->    List[str]:
         snake_case				:    Dict           =	UNetaDModel.from_pretrained(
             """diffusers/consistency-models-test"""    ,				subfolder="""test_unet"""    ,				)
         return unet

      @property
      def      UpperCAmelCase				(				self     )		->    Any:
         snake_case				:    Optional[int]           =	UNetaDModel.from_pretrained(
             """diffusers/consistency-models-test"""    ,				subfolder="""test_unet_class_cond"""    ,				)
         return unet

      def      UpperCAmelCase				(				self    ,				A=False     )		->    Optional[Any]:
         if class_cond:
            snake_case				:    List[str]           =	self.dummy_cond_unet
         else:
            snake_case				:    Optional[Any]           =	self.dummy_uncond_unet

         # Default to CM multistep sampler
         snake_case				:    Optional[Any]           =	CMStochasticIterativeScheduler(
             num_train_timesteps=4_0    ,				sigma_min=0.0_02    ,				sigma_max=80.0    ,				)

         snake_case				:    Dict           =	{
             """unet""": unet,
             """scheduler""": scheduler,
         }

         return components

      def      UpperCAmelCase				(				self    ,				A    ,				A=0     )		->    Optional[int]:
         if str(A     ).startswith("""mps"""     ):
            snake_case				:    Union[str, Any]           =	torch.manual_seed(A     )
         else:
            snake_case				:    Dict           =	torch.Generator(device=A     ).manual_seed(A     )

         snake_case				:    Tuple           =	{
             """batch_size""": 1,
             """num_inference_steps""": None,
             """timesteps""": [2_2, 0],
             """generator""": generator,
             """output_type""": """np""",
         }

         return inputs

      def      UpperCAmelCase				(				self     )		->    List[Any]:
         snake_case				:    Union[str, Any]           =	"""cpu"""  # ensure determinism for the device-dependent torch.Generator
         snake_case				:    List[Any]           =	self.get_dummy_components()
         snake_case				:    Dict           =	ConsistencyModelPipeline(**A     )
         snake_case				:    int           =	pipe.to(A     )
         pipe.set_progress_bar_config(disable=A     )

         snake_case				:    Any           =	self.get_dummy_inputs(A     )
         snake_case				:    Tuple           =	pipe(**A     ).images
         assert image.shape == (1, 3_2, 3_2, 3)

         snake_case				:    Dict           =	image[0, -3:, -3:, -1]
         snake_case				:    Tuple           =	np.array([0.35_72, 0.62_73, 0.40_31, 0.39_61, 0.43_21, 0.57_30, 0.52_66, 0.47_80, 0.50_04]     )

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

      def      UpperCAmelCase				(				self     )		->    List[Any]:
         snake_case				:    Optional[int]           =	"""cpu"""  # ensure determinism for the device-dependent torch.Generator
         snake_case				:    Tuple           =	self.get_dummy_components(class_cond=A     )
         snake_case				:    Dict           =	ConsistencyModelPipeline(**A     )
         snake_case				:    List[Any]           =	pipe.to(A     )
         pipe.set_progress_bar_config(disable=A     )

         snake_case				:    str           =	self.get_dummy_inputs(A     )
         snake_case				:    Optional[int]           =	0
         snake_case				:    List[Any]           =	pipe(**A     ).images
         assert image.shape == (1, 3_2, 3_2, 3)

         snake_case				:    Optional[int]           =	image[0, -3:, -3:, -1]
         snake_case				:    Dict           =	np.array([0.35_72, 0.62_73, 0.40_31, 0.39_61, 0.43_21, 0.57_30, 0.52_66, 0.47_80, 0.50_04]     )

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

      def      UpperCAmelCase				(				self     )		->    Dict:
         snake_case				:    str           =	"""cpu"""  # ensure determinism for the device-dependent torch.Generator
         snake_case				:    Optional[int]           =	self.get_dummy_components()
         snake_case				:    List[str]           =	ConsistencyModelPipeline(**A     )
         snake_case				:    Dict           =	pipe.to(A     )
         pipe.set_progress_bar_config(disable=A     )

         snake_case				:    Dict           =	self.get_dummy_inputs(A     )
         snake_case				:    Tuple           =	1
         snake_case				:    Optional[Any]           =	None
         snake_case				:    List[Any]           =	pipe(**A     ).images
         assert image.shape == (1, 3_2, 3_2, 3)

         snake_case				:    Optional[Any]           =	image[0, -3:, -3:, -1]
         snake_case				:    List[str]           =	np.array([0.50_04, 0.50_04, 0.49_94, 0.50_08, 0.49_76, 0.50_18, 0.49_90, 0.49_82, 0.49_87]     )

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

      def      UpperCAmelCase				(				self     )		->    Optional[Any]:
         snake_case				:    Optional[int]           =	"""cpu"""  # ensure determinism for the device-dependent torch.Generator
         snake_case				:    Dict           =	self.get_dummy_components(class_cond=A     )
         snake_case				:    List[Any]           =	ConsistencyModelPipeline(**A     )
         snake_case				:    List[Any]           =	pipe.to(A     )
         pipe.set_progress_bar_config(disable=A     )

         snake_case				:    Optional[Any]           =	self.get_dummy_inputs(A     )
         snake_case				:    Optional[Any]           =	1
         snake_case				:    Any           =	None
         snake_case				:    Optional[int]           =	0
         snake_case				:    List[Any]           =	pipe(**A     ).images
         assert image.shape == (1, 3_2, 3_2, 3)

         snake_case				:    Optional[int]           =	image[0, -3:, -3:, -1]
         snake_case				:    List[str]           =	np.array([0.50_04, 0.50_04, 0.49_94, 0.50_08, 0.49_76, 0.50_18, 0.49_90, 0.49_82, 0.49_87]     )

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




@slow
@require_torch_gpu
class 						__lowercase		(unittest.TestCase							):




      """simple docstring"""





      def      UpperCAmelCase				(				self     )		->    Dict:
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()

      def      UpperCAmelCase				(				self    ,				A=0    ,				A=False    ,				A="cpu"    ,				A=torch.floataa    ,				A=(1, 3, 6_4, 6_4)     )		->    int:
         snake_case				:    Union[str, Any]           =	torch.manual_seed(A     )

         snake_case				:    Tuple           =	{
             """num_inference_steps""": None,
             """timesteps""": [2_2, 0],
             """class_labels""": 0,
             """generator""": generator,
             """output_type""": """np""",
         }

         if get_fixed_latents:
            snake_case				:    Optional[int]           =	self.get_fixed_latents(seed=A    ,				device=A    ,				dtype=A    ,				shape=A     )
            snake_case				:    int           =	latents

         return inputs

      def      UpperCAmelCase				(				self    ,				A=0    ,				A="cpu"    ,				A=torch.floataa    ,				A=(1, 3, 6_4, 6_4)     )		->    Any:
         if type(A     ) == str:
            snake_case				:    List[str]           =	torch.device(A     )
         snake_case				:    Any           =	torch.Generator(device=A     ).manual_seed(A     )
         snake_case				:    Dict           =	randn_tensor(A    ,				generator=A    ,				device=A    ,				dtype=A     )
         return latents

      def      UpperCAmelCase				(				self     )		->    Dict:
         snake_case				:    List[Any]           =	UNetaDModel.from_pretrained("""diffusers/consistency_models"""    ,				subfolder="""diffusers_cd_imagenet64_l2"""     )
         snake_case				:    Optional[int]           =	CMStochasticIterativeScheduler(
             num_train_timesteps=4_0    ,				sigma_min=0.0_02    ,				sigma_max=80.0    ,				)
         snake_case				:    Any           =	ConsistencyModelPipeline(unet=A    ,				scheduler=A     )
         pipe.to(torch_device=A     )
         pipe.set_progress_bar_config(disable=A     )

         snake_case				:    Tuple           =	self.get_inputs()
         snake_case				:    List[str]           =	pipe(**A     ).images
         assert image.shape == (1, 6_4, 6_4, 3)

         snake_case				:    Optional[Any]           =	image[0, -3:, -3:, -1]

         snake_case				:    Union[str, Any]           =	np.array([0.08_88, 0.08_81, 0.06_66, 0.04_79, 0.02_92, 0.01_95, 0.02_01, 0.01_63, 0.02_54]     )

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

      def      UpperCAmelCase				(				self     )		->    Tuple:
         snake_case				:    Tuple           =	UNetaDModel.from_pretrained("""diffusers/consistency_models"""    ,				subfolder="""diffusers_cd_imagenet64_l2"""     )
         snake_case				:    int           =	CMStochasticIterativeScheduler(
             num_train_timesteps=4_0    ,				sigma_min=0.0_02    ,				sigma_max=80.0    ,				)
         snake_case				:    List[str]           =	ConsistencyModelPipeline(unet=A    ,				scheduler=A     )
         pipe.to(torch_device=A     )
         pipe.set_progress_bar_config(disable=A     )

         snake_case				:    Union[str, Any]           =	self.get_inputs()
         snake_case				:    Tuple           =	1
         snake_case				:    List[str]           =	None
         snake_case				:    Any           =	pipe(**A     ).images
         assert image.shape == (1, 6_4, 6_4, 3)

         snake_case				:    List[Any]           =	image[0, -3:, -3:, -1]

         snake_case				:    Union[str, Any]           =	np.array([0.03_40, 0.01_52, 0.00_63, 0.02_67, 0.02_21, 0.01_07, 0.04_16, 0.01_86, 0.02_17]     )

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

      @require_torch_a
      def      UpperCAmelCase				(				self     )		->    Optional[int]:
         snake_case				:    List[Any]           =	UNetaDModel.from_pretrained("""diffusers/consistency_models"""    ,				subfolder="""diffusers_cd_imagenet64_l2"""     )
         snake_case				:    Optional[Any]           =	CMStochasticIterativeScheduler(
             num_train_timesteps=4_0    ,				sigma_min=0.0_02    ,				sigma_max=80.0    ,				)
         snake_case				:    List[Any]           =	ConsistencyModelPipeline(unet=A    ,				scheduler=A     )
         pipe.to(torch_device=A    ,				torch_dtype=torch.floataa     )
         pipe.set_progress_bar_config(disable=A     )

         snake_case				:    List[str]           =	self.get_inputs(get_fixed_latents=A    ,				device=A     )
         # Ensure usage of flash attention in torch 2.0
         with sdp_kernel(enable_flash=A    ,				enable_math=A    ,				enable_mem_efficient=A     ):
            snake_case				:    Tuple           =	pipe(**A     ).images
         assert image.shape == (1, 6_4, 6_4, 3)

         snake_case				:    Union[str, Any]           =	image[0, -3:, -3:, -1]

         snake_case				:    int           =	np.array([0.18_75, 0.14_28, 0.12_89, 0.21_51, 0.20_92, 0.14_77, 0.18_77, 0.16_41, 0.13_53]     )

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

      @require_torch_a
      def      UpperCAmelCase				(				self     )		->    Optional[Any]:
         snake_case				:    Optional[Any]           =	UNetaDModel.from_pretrained("""diffusers/consistency_models"""    ,				subfolder="""diffusers_cd_imagenet64_l2"""     )
         snake_case				:    Any           =	CMStochasticIterativeScheduler(
             num_train_timesteps=4_0    ,				sigma_min=0.0_02    ,				sigma_max=80.0    ,				)
         snake_case				:    Dict           =	ConsistencyModelPipeline(unet=A    ,				scheduler=A     )
         pipe.to(torch_device=A    ,				torch_dtype=torch.floataa     )
         pipe.set_progress_bar_config(disable=A     )

         snake_case				:    Optional[int]           =	self.get_inputs(get_fixed_latents=A    ,				device=A     )
         snake_case				:    Union[str, Any]           =	1
         snake_case				:    Dict           =	None
         # Ensure usage of flash attention in torch 2.0
         with sdp_kernel(enable_flash=A    ,				enable_math=A    ,				enable_mem_efficient=A     ):
            snake_case				:    List[Any]           =	pipe(**A     ).images
         assert image.shape == (1, 6_4, 6_4, 3)

         snake_case				:    List[Any]           =	image[0, -3:, -3:, -1]

         snake_case				:    Dict           =	np.array([0.16_63, 0.19_48, 0.22_75, 0.16_80, 0.12_04, 0.12_45, 0.18_58, 0.13_38, 0.20_95]     )

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





