


import os
import tempfile
import unittest

import numpy as np

from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import require_flax, slow


if is_flax_available():
 import jax
 import jax.numpy as jnp
 from flax.jax_utils import replicate
 from flax.training.common_utils import shard

 from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline






@require_flax
class   __lowercase				(  unittest.TestCase  ):





      def        _lowercase				(		self						:					List[Any]       )    ->   Dict:






         """simple docstring"""







         with tempfile.TemporaryDirectory() as tmpdirname:
            # pipeline has Flax weights
            UpperCAmelCase							=     FlaxDiffusionPipeline.from_pretrained(
                """hf-internal-testing/tiny-stable-diffusion-pipe"""					,       safety_checker=__lowerCamelCase					,       cache_dir=__lowerCamelCase       )

            UpperCAmelCase							=     [t[-1] for t in os.walk(os.path.join(__lowerCamelCase					,       os.listdir(__lowerCamelCase       )[0]					,       """snapshots"""       )       )]
            UpperCAmelCase							=     [item for sublist in all_root_files for item in sublist]

            # None of the downloaded files should be a PyTorch file even if we have some here:
            # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin
            assert not any(f.endswith(""".bin"""       ) for f in files       )






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





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






         """simple docstring"""







         UpperCAmelCase				,  UpperCAmelCase							=     FlaxStableDiffusionPipeline.from_pretrained(
             """hf-internal-testing/tiny-stable-diffusion-pipe"""					,       safety_checker=__lowerCamelCase       )

         UpperCAmelCase							=     (
             """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
             """ field, close up, split lighting, cinematic"""
         )

         UpperCAmelCase							=     jax.random.PRNGKey(0       )
         UpperCAmelCase							=     4

         UpperCAmelCase							=     jax.device_count()
         UpperCAmelCase							=     num_samples * [prompt]
         UpperCAmelCase							=     pipeline.prepare_inputs(__lowerCamelCase       )

         # shard inputs and rng
         UpperCAmelCase							=     replicate(__lowerCamelCase       )
         UpperCAmelCase							=     jax.random.split(__lowerCamelCase					,       __lowerCamelCase       )
         UpperCAmelCase							=     shard(__lowerCamelCase       )

         UpperCAmelCase							=     pipeline(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       jit=__lowerCamelCase       ).images

         assert images.shape == (num_samples, 1, 6_4, 6_4, 3)
         if jax.device_count() == 8:
            assert np.abs(np.abs(images[0, 0, :2, :2, -2:]					,       dtype=np.floataa       ).sum() - 4.1_514_745       ) < 1e-3
            assert np.abs(np.abs(__lowerCamelCase					,       dtype=np.floataa       ).sum() - 49_947.875       ) < 5e-1

         UpperCAmelCase							=     pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]       )       )       )
         assert len(__lowerCamelCase       ) == num_samples





      def        _lowercase				(		self						:					Tuple       )    ->   Dict:






         """simple docstring"""







         UpperCAmelCase				,  UpperCAmelCase							=     FlaxStableDiffusionPipeline.from_pretrained(
             """CompVis/stable-diffusion-v1-4"""					,       revision="""flax"""					,       safety_checker=__lowerCamelCase       )

         UpperCAmelCase							=     (
             """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
             """ field, close up, split lighting, cinematic"""
         )

         UpperCAmelCase							=     jax.random.PRNGKey(0       )
         UpperCAmelCase							=     5_0

         UpperCAmelCase							=     jax.device_count()
         UpperCAmelCase							=     num_samples * [prompt]
         UpperCAmelCase							=     pipeline.prepare_inputs(__lowerCamelCase       )

         # shard inputs and rng
         UpperCAmelCase							=     replicate(__lowerCamelCase       )
         UpperCAmelCase							=     jax.random.split(__lowerCamelCase					,       __lowerCamelCase       )
         UpperCAmelCase							=     shard(__lowerCamelCase       )

         UpperCAmelCase							=     pipeline(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       jit=__lowerCamelCase       ).images

         assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
         if jax.device_count() == 8:
            assert np.abs((np.abs(images[0, 0, :2, :2, -2:]					,       dtype=np.floataa       ).sum() - 0.05_652_401)       ) < 1e-3
            assert np.abs((np.abs(__lowerCamelCase					,       dtype=np.floataa       ).sum() - 2_383_808.2)       ) < 5e-1





      def        _lowercase				(		self						:					int       )    ->   List[Any]:






         """simple docstring"""







         UpperCAmelCase				,  UpperCAmelCase							=     FlaxStableDiffusionPipeline.from_pretrained(
             """CompVis/stable-diffusion-v1-4"""					,       revision="""bf16"""					,       dtype=jnp.bfloataa					,       safety_checker=__lowerCamelCase       )

         UpperCAmelCase							=     (
             """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
             """ field, close up, split lighting, cinematic"""
         )

         UpperCAmelCase							=     jax.random.PRNGKey(0       )
         UpperCAmelCase							=     5_0

         UpperCAmelCase							=     jax.device_count()
         UpperCAmelCase							=     num_samples * [prompt]
         UpperCAmelCase							=     pipeline.prepare_inputs(__lowerCamelCase       )

         # shard inputs and rng
         UpperCAmelCase							=     replicate(__lowerCamelCase       )
         UpperCAmelCase							=     jax.random.split(__lowerCamelCase					,       __lowerCamelCase       )
         UpperCAmelCase							=     shard(__lowerCamelCase       )

         UpperCAmelCase							=     pipeline(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       jit=__lowerCamelCase       ).images

         assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
         if jax.device_count() == 8:
            assert np.abs((np.abs(images[0, 0, :2, :2, -2:]					,       dtype=np.floataa       ).sum() - 0.04_003_906)       ) < 1e-3
            assert np.abs((np.abs(__lowerCamelCase					,       dtype=np.floataa       ).sum() - 2_373_516.75)       ) < 5e-1





      def        _lowercase				(		self						:					Optional[Any]       )    ->   List[str]:






         """simple docstring"""







         UpperCAmelCase				,  UpperCAmelCase							=     FlaxStableDiffusionPipeline.from_pretrained(
             """CompVis/stable-diffusion-v1-4"""					,       revision="""bf16"""					,       dtype=jnp.bfloataa       )

         UpperCAmelCase							=     (
             """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
             """ field, close up, split lighting, cinematic"""
         )

         UpperCAmelCase							=     jax.random.PRNGKey(0       )
         UpperCAmelCase							=     5_0

         UpperCAmelCase							=     jax.device_count()
         UpperCAmelCase							=     num_samples * [prompt]
         UpperCAmelCase							=     pipeline.prepare_inputs(__lowerCamelCase       )

         # shard inputs and rng
         UpperCAmelCase							=     replicate(__lowerCamelCase       )
         UpperCAmelCase							=     jax.random.split(__lowerCamelCase					,       __lowerCamelCase       )
         UpperCAmelCase							=     shard(__lowerCamelCase       )

         UpperCAmelCase							=     pipeline(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       jit=__lowerCamelCase       ).images

         assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
         if jax.device_count() == 8:
            assert np.abs((np.abs(images[0, 0, :2, :2, -2:]					,       dtype=np.floataa       ).sum() - 0.04_003_906)       ) < 1e-3
            assert np.abs((np.abs(__lowerCamelCase					,       dtype=np.floataa       ).sum() - 2_373_516.75)       ) < 5e-1





      def        _lowercase				(		self						:					int       )    ->   List[str]:






         """simple docstring"""







         UpperCAmelCase							=     FlaxDDIMScheduler(
             beta_start=0.00_085					,       beta_end=0.012					,       beta_schedule="""scaled_linear"""					,       set_alpha_to_one=__lowerCamelCase					,       steps_offset=1					,       )

         UpperCAmelCase				,  UpperCAmelCase							=     FlaxStableDiffusionPipeline.from_pretrained(
             """CompVis/stable-diffusion-v1-4"""					,       revision="""bf16"""					,       dtype=jnp.bfloataa					,       scheduler=__lowerCamelCase					,       safety_checker=__lowerCamelCase					,       )
         UpperCAmelCase							=     scheduler.create_state()

         UpperCAmelCase							=     scheduler_state

         UpperCAmelCase							=     (
             """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
             """ field, close up, split lighting, cinematic"""
         )

         UpperCAmelCase							=     jax.random.PRNGKey(0       )
         UpperCAmelCase							=     5_0

         UpperCAmelCase							=     jax.device_count()
         UpperCAmelCase							=     num_samples * [prompt]
         UpperCAmelCase							=     pipeline.prepare_inputs(__lowerCamelCase       )

         # shard inputs and rng
         UpperCAmelCase							=     replicate(__lowerCamelCase       )
         UpperCAmelCase							=     jax.random.split(__lowerCamelCase					,       __lowerCamelCase       )
         UpperCAmelCase							=     shard(__lowerCamelCase       )

         UpperCAmelCase							=     pipeline(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       jit=__lowerCamelCase       ).images

         assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
         if jax.device_count() == 8:
            assert np.abs((np.abs(images[0, 0, :2, :2, -2:]					,       dtype=np.floataa       ).sum() - 0.045_043_945)       ) < 1e-3
            assert np.abs((np.abs(__lowerCamelCase					,       dtype=np.floataa       ).sum() - 2_347_693.5)       ) < 5e-1





      def        _lowercase				(		self						:					Dict       )    ->   List[str]:






         """simple docstring"""







         UpperCAmelCase							=     (
             """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
             """ field, close up, split lighting, cinematic"""
         )

         UpperCAmelCase							=     jax.device_count()
         UpperCAmelCase							=     num_samples * [prompt]
         UpperCAmelCase							=     jax.random.split(jax.random.PRNGKey(0       )					,       __lowerCamelCase       )

         UpperCAmelCase				,  UpperCAmelCase							=     FlaxStableDiffusionPipeline.from_pretrained(
             """CompVis/stable-diffusion-v1-4"""					,       revision="""bf16"""					,       dtype=jnp.bfloataa					,       safety_checker=__lowerCamelCase					,       )

         UpperCAmelCase							=     replicate(__lowerCamelCase       )
         UpperCAmelCase							=     pipeline.prepare_inputs(__lowerCamelCase       )
         UpperCAmelCase							=     shard(__lowerCamelCase       )
         UpperCAmelCase							=     pipeline(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       jit=__lowerCamelCase       ).images
         assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
         UpperCAmelCase							=     images[2, 0, 2_5_6, 1_0:1_7, 1]

         # With memory efficient attention
         UpperCAmelCase				,  UpperCAmelCase							=     FlaxStableDiffusionPipeline.from_pretrained(
             """CompVis/stable-diffusion-v1-4"""					,       revision="""bf16"""					,       dtype=jnp.bfloataa					,       safety_checker=__lowerCamelCase					,       use_memory_efficient_attention=__lowerCamelCase					,       )

         UpperCAmelCase							=     replicate(__lowerCamelCase       )
         UpperCAmelCase							=     pipeline.prepare_inputs(__lowerCamelCase       )
         UpperCAmelCase							=     shard(__lowerCamelCase       )
         UpperCAmelCase							=     pipeline(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       jit=__lowerCamelCase       ).images
         assert images_eff.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
         UpperCAmelCase							=     images[2, 0, 2_5_6, 1_0:1_7, 1]

         # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum`
         # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now.
         assert abs(slice_eff - slice       ).max() < 1e-2







import numpy






class   __lowercase				:





      def __init__(		self						:					Union[str, Any]					,       __lowerCamelCase						:					numpy.ndarray					,       __lowerCamelCase						:					numpy.ndarray       )    ->   None:






         """simple docstring"""







         UpperCAmelCase							=     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.
         UpperCAmelCase							=     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.
         UpperCAmelCase							=     numpy.random.rand(
             4					,       3       )

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

         # Real output values provided.
         UpperCAmelCase							=     output_array

         # Predicted output values by the neural network.
         # Predicted_output array initially consists of zeroes.
         UpperCAmelCase							=     numpy.zeros(output_array.shape       )





      def        _lowercase				(		self						:					List[str]       )    ->   numpy.ndarray:






         """simple docstring"""







         UpperCAmelCase							=     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.
         UpperCAmelCase							=     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.
         UpperCAmelCase							=     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        _lowercase				(		self						:					Optional[Any]       )    ->   None:






         """simple docstring"""







         UpperCAmelCase							=     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       )					,       )
         UpperCAmelCase							=     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       )					,       )
         UpperCAmelCase							=     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        _lowercase				(		self						:					Any					,       __lowerCamelCase						:					numpy.ndarray					,       __lowerCamelCase						:					int					,       __lowerCamelCase						:					bool       )    ->   None:






         """simple docstring"""







         for iteration in range(1					,       iterations + 1       ):
            UpperCAmelCase							=     self.feedforward()
            self.back_propagation()
            if give_loss:
               UpperCAmelCase							=     numpy.mean(numpy.square(output - self.feedforward()       )       )
               print(F"""Iteration {iteration} Loss: {loss}"""       )





      def        _lowercase				(		self						:					List[str]					,       __lowerCamelCase						:					numpy.ndarray       )    ->   int:






         """simple docstring"""







         UpperCAmelCase							=     input_arr

         UpperCAmelCase							=     sigmoid(
             numpy.dot(self.array					,       self.input_layer_and_first_hidden_layer_weights       )       )

         UpperCAmelCase							=     sigmoid(
             numpy.dot(
                 self.layer_between_input_and_first_hidden_layer					,       self.first_hidden_layer_and_second_hidden_layer_weights					,       )       )

         UpperCAmelCase							=     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   _UpperCamelCase				(						lowerCAmelCase_   )						->numpy.ndarray:
   return 1 / (1 + numpy.exp(-value   ))
def   _UpperCamelCase				(						lowerCAmelCase_   )						->numpy.ndarray:
   return (value) * (1 - (value))
def   _UpperCamelCase				(						)						->int:
   UpperCAmelCase							=     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.
   UpperCAmelCase							=     numpy.array(([0], [1], [1], [0], [1], [0], [0], [1])  ,						dtype=numpy.floataa   )

   # Calling neural network class.
   UpperCAmelCase							=     TwoHiddenLayerNeuralNetwork(
       input_array=lowerCAmelCase_  ,						output_array=lowerCAmelCase_   )

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

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


if __name__ == "__main__":
 example()



