






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  SCREAMING_SNAKE_CASE			(			unittest.TestCase					):
     '''simple docstring'''


     def 				_A       (				self       :	Optional[Any]      ):
       with tempfile.TemporaryDirectory() as tmpdirname:
         # pipeline has Flax weights
         SCREAMING_SNAKE_CASE       :      Tuple							=    FlaxDiffusionPipeline.from_pretrained(
             "hf-internal-testing/tiny-stable-diffusion-pipe"					, safety_checker=UpperCAmelCase_					, cache_dir=UpperCAmelCase_      )

         SCREAMING_SNAKE_CASE       :      List[Any]							=    [t[-1] for t in os.walk(os.path.join(UpperCAmelCase_					, os.listdir(UpperCAmelCase_      )[0]					, "snapshots"      )      )]
         SCREAMING_SNAKE_CASE       :      Any							=    [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  SCREAMING_SNAKE_CASE			(			unittest.TestCase					):
     '''simple docstring'''


     def 				_A       (				self       :	Dict      ):
       SCREAMING_SNAKE_CASE						,  SCREAMING_SNAKE_CASE       :      Tuple							=    FlaxStableDiffusionPipeline.from_pretrained(
           "hf-internal-testing/tiny-stable-diffusion-pipe"					, safety_checker=UpperCAmelCase_      )

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

       SCREAMING_SNAKE_CASE       :      Optional[Any]							=    jax.random.PRNGKey(0      )
       SCREAMING_SNAKE_CASE       :      List[str]							=    4

       SCREAMING_SNAKE_CASE       :      Tuple							=    jax.device_count()
       SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    num_samples * [prompt]
       SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    pipeline.prepare_inputs(UpperCAmelCase_      )

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

       SCREAMING_SNAKE_CASE       :      str							=    pipeline(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, jit=UpperCAmelCase_      ).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(UpperCAmelCase_					, dtype=np.floataa      ).sum() - 49_947.875      ) < 5E-1

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


     def 				_A       (				self       :	Dict      ):
       SCREAMING_SNAKE_CASE						,  SCREAMING_SNAKE_CASE       :      Any							=    FlaxStableDiffusionPipeline.from_pretrained(
           "CompVis/stable-diffusion-v1-4"					, revision="flax"					, safety_checker=UpperCAmelCase_      )

       SCREAMING_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"
       )

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

       SCREAMING_SNAKE_CASE       :      Dict							=    jax.device_count()
       SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    num_samples * [prompt]
       SCREAMING_SNAKE_CASE       :      List[Any]							=    pipeline.prepare_inputs(UpperCAmelCase_      )

       # shard inputs and rng
       SCREAMING_SNAKE_CASE       :      Optional[int]							=    replicate(UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      str							=    jax.random.split(UpperCAmelCase_					, UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      List[str]							=    shard(UpperCAmelCase_      )

       SCREAMING_SNAKE_CASE       :      Optional[Any]							=    pipeline(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, jit=UpperCAmelCase_      ).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.05_652_401)      ) < 1E-3
         assert np.abs((np.abs(UpperCAmelCase_					, dtype=np.floataa      ).sum() - 2_383_808.2)      ) < 5E-1


     def 				_A       (				self       :	Union[str, Any]      ):
       SCREAMING_SNAKE_CASE						,  SCREAMING_SNAKE_CASE       :      Optional[Any]							=    FlaxStableDiffusionPipeline.from_pretrained(
           "CompVis/stable-diffusion-v1-4"					, revision="bf16"					, dtype=jnp.bfloataa					, safety_checker=UpperCAmelCase_      )

       SCREAMING_SNAKE_CASE       :      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"
       )

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

       SCREAMING_SNAKE_CASE       :      Any							=    jax.device_count()
       SCREAMING_SNAKE_CASE       :      Dict							=    num_samples * [prompt]
       SCREAMING_SNAKE_CASE       :      List[str]							=    pipeline.prepare_inputs(UpperCAmelCase_      )

       # shard inputs and rng
       SCREAMING_SNAKE_CASE       :      Any							=    replicate(UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      Dict							=    jax.random.split(UpperCAmelCase_					, UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      str							=    shard(UpperCAmelCase_      )

       SCREAMING_SNAKE_CASE       :      str							=    pipeline(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, jit=UpperCAmelCase_      ).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.04_003_906)      ) < 1E-3
         assert np.abs((np.abs(UpperCAmelCase_					, dtype=np.floataa      ).sum() - 2_373_516.75)      ) < 5E-1


     def 				_A       (				self       :	Any      ):
       SCREAMING_SNAKE_CASE						,  SCREAMING_SNAKE_CASE       :      int							=    FlaxStableDiffusionPipeline.from_pretrained(
           "CompVis/stable-diffusion-v1-4"					, revision="bf16"					, dtype=jnp.bfloataa      )

       SCREAMING_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"
       )

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

       SCREAMING_SNAKE_CASE       :      int							=    jax.device_count()
       SCREAMING_SNAKE_CASE       :      List[str]							=    num_samples * [prompt]
       SCREAMING_SNAKE_CASE       :      Optional[int]							=    pipeline.prepare_inputs(UpperCAmelCase_      )

       # shard inputs and rng
       SCREAMING_SNAKE_CASE       :      Tuple							=    replicate(UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      Dict							=    jax.random.split(UpperCAmelCase_					, UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    shard(UpperCAmelCase_      )

       SCREAMING_SNAKE_CASE       :      Any							=    pipeline(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, jit=UpperCAmelCase_      ).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.04_003_906)      ) < 1E-3
         assert np.abs((np.abs(UpperCAmelCase_					, dtype=np.floataa      ).sum() - 2_373_516.75)      ) < 5E-1


     def 				_A       (				self       :	Tuple      ):
       SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    FlaxDDIMScheduler(
           beta_start=0.00_085					, beta_end=0.012					, beta_schedule="scaled_linear"					, set_alpha_to_one=UpperCAmelCase_					, steps_offset=1					, )

       SCREAMING_SNAKE_CASE						,  SCREAMING_SNAKE_CASE       :      str							=    FlaxStableDiffusionPipeline.from_pretrained(
           "CompVis/stable-diffusion-v1-4"					, revision="bf16"					, dtype=jnp.bfloataa					, scheduler=UpperCAmelCase_					, safety_checker=UpperCAmelCase_					, )
       SCREAMING_SNAKE_CASE       :      Optional[int]							=    scheduler.create_state()

       SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    scheduler_state

       SCREAMING_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"
       )

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

       SCREAMING_SNAKE_CASE       :      List[str]							=    jax.device_count()
       SCREAMING_SNAKE_CASE       :      int							=    num_samples * [prompt]
       SCREAMING_SNAKE_CASE       :      Optional[int]							=    pipeline.prepare_inputs(UpperCAmelCase_      )

       # shard inputs and rng
       SCREAMING_SNAKE_CASE       :      Tuple							=    replicate(UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      int							=    jax.random.split(UpperCAmelCase_					, UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      Tuple							=    shard(UpperCAmelCase_      )

       SCREAMING_SNAKE_CASE       :      List[str]							=    pipeline(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, jit=UpperCAmelCase_      ).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.045_043_945)      ) < 1E-3
         assert np.abs((np.abs(UpperCAmelCase_					, dtype=np.floataa      ).sum() - 2_347_693.5)      ) < 5E-1






     def 				_A       (				self       :	Dict      ):
       SCREAMING_SNAKE_CASE       :      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"
       )

       SCREAMING_SNAKE_CASE       :      Tuple							=    jax.device_count()
       SCREAMING_SNAKE_CASE       :      str							=    num_samples * [prompt]
       SCREAMING_SNAKE_CASE       :      List[Any]							=    jax.random.split(jax.random.PRNGKey(0      )					, UpperCAmelCase_      )

       SCREAMING_SNAKE_CASE						,  SCREAMING_SNAKE_CASE       :      Optional[Any]							=    FlaxStableDiffusionPipeline.from_pretrained(
           "CompVis/stable-diffusion-v1-4"					, revision="bf16"					, dtype=jnp.bfloataa					, safety_checker=UpperCAmelCase_					, )

       SCREAMING_SNAKE_CASE       :      str							=    replicate(UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      List[Any]							=    pipeline.prepare_inputs(UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    shard(UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      Tuple							=    pipeline(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, jit=UpperCAmelCase_      ).images
       assert images.shape == (num_samples, 1, 512, 512, 3)
       SCREAMING_SNAKE_CASE       :      Dict							=    images[2, 0, 256, 10:17, 1]

       # With memory efficient attention
       SCREAMING_SNAKE_CASE						,  SCREAMING_SNAKE_CASE       :      Optional[Any]							=    FlaxStableDiffusionPipeline.from_pretrained(
           "CompVis/stable-diffusion-v1-4"					, revision="bf16"					, dtype=jnp.bfloataa					, safety_checker=UpperCAmelCase_					, use_memory_efficient_attention=UpperCAmelCase_					, )

       SCREAMING_SNAKE_CASE       :      Optional[int]							=    replicate(UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      Optional[Any]							=    pipeline.prepare_inputs(UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      int							=    shard(UpperCAmelCase_      )
       SCREAMING_SNAKE_CASE       :      List[Any]							=    pipeline(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, jit=UpperCAmelCase_      ).images
       assert images_eff.shape == (num_samples, 1, 512, 512, 3)
       SCREAMING_SNAKE_CASE       :      Optional[int]							=    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














def   lowerCamelCase__			(     lowercase				):

  """simple docstring"""






  SCREAMING_SNAKE_CASE       :      Dict							=    [0] * len(lowercase				)
  SCREAMING_SNAKE_CASE       :      List[str]							=    []
  SCREAMING_SNAKE_CASE       :      Optional[Any]							=    []
  SCREAMING_SNAKE_CASE       :      Any							=    0

  for values in graph.values():
    for i in values:
      indegree[i] += 1

  for i in range(len(lowercase				)				):
    if indegree[i] == 0:
      queue.append(lowercase				)

  while queue:
    SCREAMING_SNAKE_CASE       :      Optional[Any]							=    queue.pop(0				)
    cnt += 1
    topo.append(lowercase				)
    for x in graph[vertex]:
      indegree[x] -= 1
      if indegree[x] == 0:
        queue.append(lowercase				)

  if cnt != len(lowercase				):
    print("Cycle exists"				)
  else:
    print(lowercase				)


# Adjacency List of Graph
snake_case    				=		{0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}

topological_sort(graph)






