



'''simple docstring'''





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  snake_case__						(    unittest.TestCase				):
 def A_   (   self						:							Optional[int]  )      ->   str:







       '''simple docstring'''
       with tempfile.TemporaryDirectory() as tmpdirname:
             # pipeline has Flax weights
             __snake_case :   List[Any]													=    FlaxDiffusionPipeline.from_pretrained(
                 'hf-internal-testing/tiny-stable-diffusion-pipe'      ,     safety_checker=__a      ,     cache_dir=__a  )

             __snake_case :   Tuple													=    [t[-1] for t in os.walk(os.path.join(__a      ,     os.listdir(__a  )[0]      ,     'snapshots'  )  )]
             __snake_case :   List[str]													=    [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  snake_case__						(    unittest.TestCase				):
 def A_   (   self						:							Union[str, Any]  )      ->   List[str]:







       '''simple docstring'''
       __snake_case							,     __snake_case :   List[str]													=    FlaxStableDiffusionPipeline.from_pretrained(
           'hf-internal-testing/tiny-stable-diffusion-pipe'      ,     safety_checker=__a  )

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

       __snake_case :   Dict													=    jax.random.PRNGKey(0  )
       __snake_case :   Optional[int]													=    4

       __snake_case :   List[Any]													=    jax.device_count()
       __snake_case :   Optional[int]													=    num_samples * [prompt]
       __snake_case :   Optional[int]													=    pipeline.prepare_inputs(__a  )

       # shard inputs and rng
       __snake_case :   Dict													=    replicate(__a  )
       __snake_case :   Tuple													=    jax.random.split(__a      ,     __a  )
       __snake_case :   Any													=    shard(__a  )

       __snake_case :   str													=    pipeline(__a      ,     __a      ,     __a      ,     __a      ,     jit=__a  ).images

       assert images.shape == (num_samples, 1, 64, 64, 3)
       if jax.device_count() == 8:
             assert np.abs(np.abs(images[0, 0, :2, :2, -2:]      ,     dtype=np.floataa  ).sum() - 4.1_5_1_4_7_4_5  ) < 1e-3
             assert np.abs(np.abs(__a      ,     dtype=np.floataa  ).sum() - 49947.875  ) < 5e-1

       __snake_case :   int													=    pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]  )  )  )
       assert len(__a  ) == num_samples
 def A_   (   self						:							Any  )      ->   Tuple:







       '''simple docstring'''
       __snake_case							,     __snake_case :   Tuple													=    FlaxStableDiffusionPipeline.from_pretrained(
           'CompVis/stable-diffusion-v1-4'      ,     revision='flax'      ,     safety_checker=__a  )

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

       __snake_case :   Union[str, Any]													=    jax.random.PRNGKey(0  )
       __snake_case :   int													=    50

       __snake_case :   Optional[Any]													=    jax.device_count()
       __snake_case :   int													=    num_samples * [prompt]
       __snake_case :   List[str]													=    pipeline.prepare_inputs(__a  )

       # shard inputs and rng
       __snake_case :   Dict													=    replicate(__a  )
       __snake_case :   Optional[Any]													=    jax.random.split(__a      ,     __a  )
       __snake_case :   List[str]													=    shard(__a  )

       __snake_case :   Optional[Any]													=    pipeline(__a      ,     __a      ,     __a      ,     __a      ,     jit=__a  ).images

       assert images.shape == (num_samples, 1, 512, 512, 3)
       if jax.device_count() == 8:
             assert np.abs((np.abs(images[0, 0, :2, :2, -2:]      ,     dtype=np.floataa  ).sum() - 0.0_5_6_5_2_4_0_1)  ) < 1e-3
             assert np.abs((np.abs(__a      ,     dtype=np.floataa  ).sum() - 2383808.2)  ) < 5e-1
 def A_   (   self						:							Dict  )      ->   Tuple:







       '''simple docstring'''
       __snake_case							,     __snake_case :   int													=    FlaxStableDiffusionPipeline.from_pretrained(
           'CompVis/stable-diffusion-v1-4'      ,     revision='bf16'      ,     dtype=jnp.bfloataa      ,     safety_checker=__a  )

       __snake_case :   Optional[int]													=    (
           'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of'
           ' field, close up, split lighting, cinematic'
       )

       __snake_case :   Optional[Any]													=    jax.random.PRNGKey(0  )
       __snake_case :   Optional[Any]													=    50

       __snake_case :   int													=    jax.device_count()
       __snake_case :   Dict													=    num_samples * [prompt]
       __snake_case :   int													=    pipeline.prepare_inputs(__a  )

       # shard inputs and rng
       __snake_case :   Union[str, Any]													=    replicate(__a  )
       __snake_case :   str													=    jax.random.split(__a      ,     __a  )
       __snake_case :   Any													=    shard(__a  )

       __snake_case :   Tuple													=    pipeline(__a      ,     __a      ,     __a      ,     __a      ,     jit=__a  ).images

       assert images.shape == (num_samples, 1, 512, 512, 3)
       if jax.device_count() == 8:
             assert np.abs((np.abs(images[0, 0, :2, :2, -2:]      ,     dtype=np.floataa  ).sum() - 0.0_4_0_0_3_9_0_6)  ) < 1e-3
             assert np.abs((np.abs(__a      ,     dtype=np.floataa  ).sum() - 2373516.75)  ) < 5e-1
 def A_   (   self						:							List[str]  )      ->   Dict:







       '''simple docstring'''
       __snake_case							,     __snake_case :   Any													=    FlaxStableDiffusionPipeline.from_pretrained(
           'CompVis/stable-diffusion-v1-4'      ,     revision='bf16'      ,     dtype=jnp.bfloataa  )

       __snake_case :   Union[str, Any]													=    (
           'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of'
           ' field, close up, split lighting, cinematic'
       )

       __snake_case :   Dict													=    jax.random.PRNGKey(0  )
       __snake_case :   Tuple													=    50

       __snake_case :   Union[str, Any]													=    jax.device_count()
       __snake_case :   Union[str, Any]													=    num_samples * [prompt]
       __snake_case :   Optional[Any]													=    pipeline.prepare_inputs(__a  )

       # shard inputs and rng
       __snake_case :   str													=    replicate(__a  )
       __snake_case :   Optional[Any]													=    jax.random.split(__a      ,     __a  )
       __snake_case :   Union[str, Any]													=    shard(__a  )

       __snake_case :   str													=    pipeline(__a      ,     __a      ,     __a      ,     __a      ,     jit=__a  ).images

       assert images.shape == (num_samples, 1, 512, 512, 3)
       if jax.device_count() == 8:
             assert np.abs((np.abs(images[0, 0, :2, :2, -2:]      ,     dtype=np.floataa  ).sum() - 0.0_4_0_0_3_9_0_6)  ) < 1e-3
             assert np.abs((np.abs(__a      ,     dtype=np.floataa  ).sum() - 2373516.75)  ) < 5e-1
 def A_   (   self						:							List[Any]  )      ->   str:







       '''simple docstring'''
       __snake_case :   Any													=    FlaxDDIMScheduler(
           beta_start=0.0_0_0_8_5      ,     beta_end=0.0_1_2      ,     beta_schedule='scaled_linear'      ,     set_alpha_to_one=__a      ,     steps_offset=1      ,     )

       __snake_case							,     __snake_case :   List[str]													=    FlaxStableDiffusionPipeline.from_pretrained(
           'CompVis/stable-diffusion-v1-4'      ,     revision='bf16'      ,     dtype=jnp.bfloataa      ,     scheduler=__a      ,     safety_checker=__a      ,     )
       __snake_case :   str													=    scheduler.create_state()

       __snake_case :   Optional[int]													=    scheduler_state

       __snake_case :   List[Any]													=    (
           'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of'
           ' field, close up, split lighting, cinematic'
       )

       __snake_case :   Optional[Any]													=    jax.random.PRNGKey(0  )
       __snake_case :   Optional[int]													=    50

       __snake_case :   List[str]													=    jax.device_count()
       __snake_case :   List[Any]													=    num_samples * [prompt]
       __snake_case :   List[Any]													=    pipeline.prepare_inputs(__a  )

       # shard inputs and rng
       __snake_case :   Tuple													=    replicate(__a  )
       __snake_case :   int													=    jax.random.split(__a      ,     __a  )
       __snake_case :   List[str]													=    shard(__a  )

       __snake_case :   List[Any]													=    pipeline(__a      ,     __a      ,     __a      ,     __a      ,     jit=__a  ).images

       assert images.shape == (num_samples, 1, 512, 512, 3)
       if jax.device_count() == 8:
             assert np.abs((np.abs(images[0, 0, :2, :2, -2:]      ,     dtype=np.floataa  ).sum() - 0.0_4_5_0_4_3_9_4_5)  ) < 1e-3
             assert np.abs((np.abs(__a      ,     dtype=np.floataa  ).sum() - 2347693.5)  ) < 5e-1





 def A_   (   self						:							Tuple  )      ->   int:







       '''simple docstring'''
       __snake_case :   Dict													=    (
           'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of'
           ' field, close up, split lighting, cinematic'
       )

       __snake_case :   Dict													=    jax.device_count()
       __snake_case :   Union[str, Any]													=    num_samples * [prompt]
       __snake_case :   Any													=    jax.random.split(jax.random.PRNGKey(0  )      ,     __a  )

       __snake_case							,     __snake_case :   Any													=    FlaxStableDiffusionPipeline.from_pretrained(
           'CompVis/stable-diffusion-v1-4'      ,     revision='bf16'      ,     dtype=jnp.bfloataa      ,     safety_checker=__a      ,     )

       __snake_case :   List[str]													=    replicate(__a  )
       __snake_case :   int													=    pipeline.prepare_inputs(__a  )
       __snake_case :   Tuple													=    shard(__a  )
       __snake_case :   List[str]													=    pipeline(__a      ,     __a      ,     __a      ,     jit=__a  ).images
       assert images.shape == (num_samples, 1, 512, 512, 3)
       __snake_case :   Optional[int]													=    images[2, 0, 256, 10:17, 1]

       # With memory efficient attention
       __snake_case							,     __snake_case :   Tuple													=    FlaxStableDiffusionPipeline.from_pretrained(
           'CompVis/stable-diffusion-v1-4'      ,     revision='bf16'      ,     dtype=jnp.bfloataa      ,     safety_checker=__a      ,     use_memory_efficient_attention=__a      ,     )

       __snake_case :   Optional[int]													=    replicate(__a  )
       __snake_case :   List[Any]													=    pipeline.prepare_inputs(__a  )
       __snake_case :   str													=    shard(__a  )
       __snake_case :   Tuple													=    pipeline(__a      ,     __a      ,     __a      ,     jit=__a  ).images
       assert images_eff.shape == (num_samples, 1, 512, 512, 3)
       __snake_case :   Any													=    images[2, 0, 256, 10:17, 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







'''simple docstring'''
__SCREAMING_SNAKE_CASE					:				Optional[int]									=		{
    '''a''': '''AAAAA''',
    '''b''': '''AAAAB''',
    '''c''': '''AAABA''',
    '''d''': '''AAABB''',
    '''e''': '''AABAA''',
    '''f''': '''AABAB''',
    '''g''': '''AABBA''',
    '''h''': '''AABBB''',
    '''i''': '''ABAAA''',
    '''j''': '''BBBAA''',
    '''k''': '''ABAAB''',
    '''l''': '''ABABA''',
    '''m''': '''ABABB''',
    '''n''': '''ABBAA''',
    '''o''': '''ABBAB''',
    '''p''': '''ABBBA''',
    '''q''': '''ABBBB''',
    '''r''': '''BAAAA''',
    '''s''': '''BAAAB''',
    '''t''': '''BAABA''',
    '''u''': '''BAABB''',
    '''v''': '''BBBAB''',
    '''w''': '''BABAA''',
    '''x''': '''BABAB''',
    '''y''': '''BABBA''',
    '''z''': '''BABBB''',
    ''' ''': ''' ''',
}


__SCREAMING_SNAKE_CASE					:				Tuple									=		{value: key for key, value in encode_dict.items()}







def       a_				(	UpperCamelCase_ ):
							A_			    =		""
							for letter in word.lower():
														if letter.isalpha() or letter == " ":
																					encoded += encode_dict[letter]
														else:
																					raise Exception("encode() accepts only letters of the alphabet and spaces" )
							return encoded







def       a_				(	UpperCamelCase_ ):
							if set(UpperCamelCase_ ) - {"A", "B", " "} != set():
														raise Exception("decode() accepts only 'A', 'B' and spaces" )
							A_			    =		""
							for word in coded.split():
														while len(UpperCamelCase_ ) != 0:
																					decoded += decode_dict[word[:5]]
																					A_			    =		word[5:]
														decoded += " "
							return decoded.strip()


if __name__ == "__main__":
							from doctest import testmod

							testmod()





