
'''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  lowerCAmelCase__   (  unittest.TestCase     ):






					def 	_snake_case    (   self		):


											"""simple docstring"""





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

																	lowercase_	:     int													=       [t[-1] for t in os.walk(os.path.join(__SCREAMING_SNAKE_CASE				,							os.listdir(__SCREAMING_SNAKE_CASE		)[0]				,							'''snapshots'''		)		)]
																	lowercase_	:     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  lowerCAmelCase__   (  unittest.TestCase     ):






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_						, lowercase_	:     Optional[int]													=       FlaxStableDiffusionPipeline.from_pretrained(
											    '''hf-internal-testing/tiny-stable-diffusion-pipe'''				,							safety_checker=__SCREAMING_SNAKE_CASE		)

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

											lowercase_	:     Tuple													=       jax.random.PRNGKey(0		)
											lowercase_	:     Any													=       4

											lowercase_	:     Union[str, Any]													=       jax.device_count()
											lowercase_	:     Dict													=       num_samples * [prompt]
											lowercase_	:     Tuple													=       pipeline.prepare_inputs(__SCREAMING_SNAKE_CASE		)

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

											lowercase_	:     Any													=       pipeline(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							jit=__SCREAMING_SNAKE_CASE		).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_514_745		) < 1E-3
																	assert np.abs(np.abs(__SCREAMING_SNAKE_CASE				,							dtype=np.floataa		).sum() - 49_947.875		) < 5E-1

											lowercase_	:     List[Any]													=       pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]		)		)		)
											assert len(__SCREAMING_SNAKE_CASE		) == num_samples






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_						, lowercase_	:     int													=       FlaxStableDiffusionPipeline.from_pretrained(
											    '''CompVis/stable-diffusion-v1-4'''				,							revision='''flax'''				,							safety_checker=__SCREAMING_SNAKE_CASE		)

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

											lowercase_	:     Any													=       jax.random.PRNGKey(0		)
											lowercase_	:     List[str]													=       50

											lowercase_	:     Any													=       jax.device_count()
											lowercase_	:     Tuple													=       num_samples * [prompt]
											lowercase_	:     str													=       pipeline.prepare_inputs(__SCREAMING_SNAKE_CASE		)

											# shard inputs and rng
											lowercase_	:     Optional[Any]													=       replicate(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Dict													=       jax.random.split(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Dict													=       shard(__SCREAMING_SNAKE_CASE		)

											lowercase_	:     Optional[Any]													=       pipeline(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							jit=__SCREAMING_SNAKE_CASE		).images

											assert images.shape == (num_samples, 1, 5_12, 5_12, 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(__SCREAMING_SNAKE_CASE				,							dtype=np.floataa		).sum() - 2_383_808.2)		) < 5E-1






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_						, lowercase_	:     Union[str, Any]													=       FlaxStableDiffusionPipeline.from_pretrained(
											    '''CompVis/stable-diffusion-v1-4'''				,							revision='''bf16'''				,							dtype=jnp.bfloataa				,							safety_checker=__SCREAMING_SNAKE_CASE		)

											lowercase_	:     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'''
											)

											lowercase_	:     Optional[int]													=       jax.random.PRNGKey(0		)
											lowercase_	:     str													=       50

											lowercase_	:     int													=       jax.device_count()
											lowercase_	:     str													=       num_samples * [prompt]
											lowercase_	:     List[str]													=       pipeline.prepare_inputs(__SCREAMING_SNAKE_CASE		)

											# shard inputs and rng
											lowercase_	:     int													=       replicate(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Any													=       jax.random.split(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE		)
											lowercase_	:     int													=       shard(__SCREAMING_SNAKE_CASE		)

											lowercase_	:     str													=       pipeline(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							jit=__SCREAMING_SNAKE_CASE		).images

											assert images.shape == (num_samples, 1, 5_12, 5_12, 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(__SCREAMING_SNAKE_CASE				,							dtype=np.floataa		).sum() - 2_373_516.75)		) < 5E-1






					def 	_snake_case    (   self		):


											"""simple docstring"""





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

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

											lowercase_	:     int													=       jax.random.PRNGKey(0		)
											lowercase_	:     List[Any]													=       50

											lowercase_	:     Tuple													=       jax.device_count()
											lowercase_	:     Any													=       num_samples * [prompt]
											lowercase_	:     int													=       pipeline.prepare_inputs(__SCREAMING_SNAKE_CASE		)

											# shard inputs and rng
											lowercase_	:     Dict													=       replicate(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Optional[int]													=       jax.random.split(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Union[str, Any]													=       shard(__SCREAMING_SNAKE_CASE		)

											lowercase_	:     int													=       pipeline(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							jit=__SCREAMING_SNAKE_CASE		).images

											assert images.shape == (num_samples, 1, 5_12, 5_12, 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(__SCREAMING_SNAKE_CASE				,							dtype=np.floataa		).sum() - 2_373_516.75)		) < 5E-1






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     Union[str, Any]													=       FlaxDDIMScheduler(
											    beta_start=0.00_085				,							beta_end=0.012				,							beta_schedule='''scaled_linear'''				,							set_alpha_to_one=__SCREAMING_SNAKE_CASE				,							steps_offset=1				,							)

											lowercase_						, lowercase_	:     str													=       FlaxStableDiffusionPipeline.from_pretrained(
											    '''CompVis/stable-diffusion-v1-4'''				,							revision='''bf16'''				,							dtype=jnp.bfloataa				,							scheduler=__SCREAMING_SNAKE_CASE				,							safety_checker=__SCREAMING_SNAKE_CASE				,							)
											lowercase_	:     str													=       scheduler.create_state()

											lowercase_	:     Optional[int]													=       scheduler_state

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

											lowercase_	:     Tuple													=       jax.random.PRNGKey(0		)
											lowercase_	:     int													=       50

											lowercase_	:     str													=       jax.device_count()
											lowercase_	:     List[Any]													=       num_samples * [prompt]
											lowercase_	:     Tuple													=       pipeline.prepare_inputs(__SCREAMING_SNAKE_CASE		)

											# shard inputs and rng
											lowercase_	:     Tuple													=       replicate(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     List[Any]													=       jax.random.split(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE		)
											lowercase_	:     List[str]													=       shard(__SCREAMING_SNAKE_CASE		)

											lowercase_	:     int													=       pipeline(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							jit=__SCREAMING_SNAKE_CASE		).images

											assert images.shape == (num_samples, 1, 5_12, 5_12, 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(__SCREAMING_SNAKE_CASE				,							dtype=np.floataa		).sum() - 2_347_693.5)		) < 5E-1






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     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'''
											)

											lowercase_	:     List[Any]													=       jax.device_count()
											lowercase_	:     List[Any]													=       num_samples * [prompt]
											lowercase_	:     Optional[Any]													=       jax.random.split(jax.random.PRNGKey(0		)				,							__SCREAMING_SNAKE_CASE		)

											lowercase_						, lowercase_	:     Dict													=       FlaxStableDiffusionPipeline.from_pretrained(
											    '''CompVis/stable-diffusion-v1-4'''				,							revision='''bf16'''				,							dtype=jnp.bfloataa				,							safety_checker=__SCREAMING_SNAKE_CASE				,							)

											lowercase_	:     List[str]													=       replicate(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     str													=       pipeline.prepare_inputs(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Tuple													=       shard(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Union[str, Any]													=       pipeline(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							jit=__SCREAMING_SNAKE_CASE		).images
											assert images.shape == (num_samples, 1, 5_12, 5_12, 3)
											lowercase_	:     Union[str, Any]													=       images[2, 0, 2_56, 10:17, 1]

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

											lowercase_	:     Optional[Any]													=       replicate(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     List[str]													=       pipeline.prepare_inputs(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Dict													=       shard(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     List[str]													=       pipeline(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							jit=__SCREAMING_SNAKE_CASE		).images
											assert images_eff.shape == (num_samples, 1, 5_12, 5_12, 3)
											lowercase_	:     Tuple													=       images[2, 0, 2_56, 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










from collections.abc import Iterable
from typing import Generic, TypeVar

lowercase      :       Any									=  TypeVar("""_T""")





class  A__    (							Generic[_T]	):




   """simple docstring"""



   def __init__(					self					,  lowercase = None)			->						None:







          '''simple docstring'''

          a__						:	list[_T] =				list(iterable or [])
          a__						:	list[_T] =				[]

   def __len__(					self)			->						int:







          '''simple docstring'''

          return len(self._stacka) + len(self._stacka)

   def __repr__(					self)			->						str:







          '''simple docstring'''

          return F'Queue({tuple(self._stacka[::-1] + self._stacka)})'

   def 							__lowercase		(					self					,  lowercase)			->						None:







          '''simple docstring'''

          self._stacka.append(lowercase)

   def 							__lowercase		(					self)			->						_T:







          '''simple docstring'''

          a__						:	List[str] =				self._stacka.pop
          a__						:	Optional[int] =				self._stacka.append

          if not self._stacka:
                 while self._stacka:
                        stacka_append(stacka_pop())

          if not self._stacka:
                 raise IndexError('Queue is empty')
          return self._stacka.pop()


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

    testmod()


