




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






     def     _lowercase     (			self   )							->      Dict:
          with tempfile.TemporaryDirectory() as tmpdirname:
               # pipeline has Flax weights
               _snake_case							=				FlaxDiffusionPipeline.from_pretrained(
                   "hf-internal-testing/tiny-stable-diffusion-pipe" ,safety_checker=_SCREAMING_SNAKE_CASE ,cache_dir=_SCREAMING_SNAKE_CASE   )

               _snake_case							=				[t[-1] for t in os.walk(os.path.join(_SCREAMING_SNAKE_CASE ,os.listdir(_SCREAMING_SNAKE_CASE   )[0] ,"snapshots"   )   )]
               _snake_case							=				[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        _a    (						unittest.TestCase							):






     def     _lowercase     (			self   )							->      List[str]:
          _snake_case							, _snake_case							=				FlaxStableDiffusionPipeline.from_pretrained(
              "hf-internal-testing/tiny-stable-diffusion-pipe" ,safety_checker=_SCREAMING_SNAKE_CASE   )

          _snake_case							=				(
              "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							=				jax.random.PRNGKey(0   )
          _snake_case							=				4

          _snake_case							=				jax.device_count()
          _snake_case							=				num_samples * [prompt]
          _snake_case							=				pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE   )

          # shard inputs and rng
          _snake_case							=				replicate(_SCREAMING_SNAKE_CASE   )
          _snake_case							=				jax.random.split(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )
          _snake_case							=				shard(_SCREAMING_SNAKE_CASE   )

          _snake_case							=				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_5_1_4_7_4_5   ) < 1e-3
               assert np.abs(np.abs(_SCREAMING_SNAKE_CASE ,dtype=np.floataa   ).sum() - 49_947.875   ) < 5e-1

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






     def     _lowercase     (			self   )							->      Any:
          _snake_case							, _snake_case							=				FlaxStableDiffusionPipeline.from_pretrained(
              "CompVis/stable-diffusion-v1-4" ,revision="flax" ,safety_checker=_SCREAMING_SNAKE_CASE   )

          _snake_case							=				(
              "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							=				jax.random.PRNGKey(0   )
          _snake_case							=				50

          _snake_case							=				jax.device_count()
          _snake_case							=				num_samples * [prompt]
          _snake_case							=				pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE   )

          # shard inputs and rng
          _snake_case							=				replicate(_SCREAMING_SNAKE_CASE   )
          _snake_case							=				jax.random.split(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )
          _snake_case							=				shard(_SCREAMING_SNAKE_CASE   )

          _snake_case							=				pipeline(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,jit=_SCREAMING_SNAKE_CASE   ).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(_SCREAMING_SNAKE_CASE ,dtype=np.floataa   ).sum() - 2_383_808.2)   ) < 5e-1






     def     _lowercase     (			self   )							->      str:
          _snake_case							, _snake_case							=				FlaxStableDiffusionPipeline.from_pretrained(
              "CompVis/stable-diffusion-v1-4" ,revision="bf16" ,dtype=jnp.bfloataa ,safety_checker=_SCREAMING_SNAKE_CASE   )

          _snake_case							=				(
              "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							=				jax.random.PRNGKey(0   )
          _snake_case							=				50

          _snake_case							=				jax.device_count()
          _snake_case							=				num_samples * [prompt]
          _snake_case							=				pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE   )

          # shard inputs and rng
          _snake_case							=				replicate(_SCREAMING_SNAKE_CASE   )
          _snake_case							=				jax.random.split(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )
          _snake_case							=				shard(_SCREAMING_SNAKE_CASE   )

          _snake_case							=				pipeline(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,jit=_SCREAMING_SNAKE_CASE   ).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(_SCREAMING_SNAKE_CASE ,dtype=np.floataa   ).sum() - 2_373_516.75)   ) < 5e-1






     def     _lowercase     (			self   )							->      Dict:
          _snake_case							, _snake_case							=				FlaxStableDiffusionPipeline.from_pretrained(
              "CompVis/stable-diffusion-v1-4" ,revision="bf16" ,dtype=jnp.bfloataa   )

          _snake_case							=				(
              "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							=				jax.random.PRNGKey(0   )
          _snake_case							=				50

          _snake_case							=				jax.device_count()
          _snake_case							=				num_samples * [prompt]
          _snake_case							=				pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE   )

          # shard inputs and rng
          _snake_case							=				replicate(_SCREAMING_SNAKE_CASE   )
          _snake_case							=				jax.random.split(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )
          _snake_case							=				shard(_SCREAMING_SNAKE_CASE   )

          _snake_case							=				pipeline(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,jit=_SCREAMING_SNAKE_CASE   ).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(_SCREAMING_SNAKE_CASE ,dtype=np.floataa   ).sum() - 2_373_516.75)   ) < 5e-1






     def     _lowercase     (			self   )							->      Optional[Any]:
          _snake_case							=				FlaxDDIMScheduler(
              beta_start=0.0_0_0_8_5 ,beta_end=0.0_1_2 ,beta_schedule="scaled_linear" ,set_alpha_to_one=_SCREAMING_SNAKE_CASE ,steps_offset=1 ,)

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

          _snake_case							=				scheduler_state

          _snake_case							=				(
              "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							=				jax.random.PRNGKey(0   )
          _snake_case							=				50

          _snake_case							=				jax.device_count()
          _snake_case							=				num_samples * [prompt]
          _snake_case							=				pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE   )

          # shard inputs and rng
          _snake_case							=				replicate(_SCREAMING_SNAKE_CASE   )
          _snake_case							=				jax.random.split(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )
          _snake_case							=				shard(_SCREAMING_SNAKE_CASE   )

          _snake_case							=				pipeline(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,jit=_SCREAMING_SNAKE_CASE   ).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(_SCREAMING_SNAKE_CASE ,dtype=np.floataa   ).sum() - 2_347_693.5)   ) < 5e-1






     def     _lowercase     (			self   )							->      int:
          _snake_case							=				(
              "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							=				jax.device_count()
          _snake_case							=				num_samples * [prompt]
          _snake_case							=				jax.random.split(jax.random.PRNGKey(0   ) ,_SCREAMING_SNAKE_CASE   )

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

          _snake_case							=				replicate(_SCREAMING_SNAKE_CASE   )
          _snake_case							=				pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE   )
          _snake_case							=				shard(_SCREAMING_SNAKE_CASE   )
          _snake_case							=				pipeline(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,jit=_SCREAMING_SNAKE_CASE   ).images
          assert images.shape == (num_samples, 1, 512, 512, 3)
          _snake_case							=				images[2, 0, 256, 10:17, 1]

          # With memory efficient attention
          _snake_case							, _snake_case							=				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 ,)

          _snake_case							=				replicate(_SCREAMING_SNAKE_CASE   )
          _snake_case							=				pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE   )
          _snake_case							=				shard(_SCREAMING_SNAKE_CASE   )
          _snake_case							=				pipeline(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,jit=_SCREAMING_SNAKE_CASE   ).images
          assert images_eff.shape == (num_samples, 1, 512, 512, 3)
          _snake_case							=				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'''





from __future__ import annotations

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

UpperCamelCase_						:      int       =						TypeVar('''T''')
UpperCamelCase_						:      Dict       =						TypeVar('''U''')

class        _a    (						Generic[T, U]							):






     def __init__(			self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )							->      Dict:
          _snake_case							=				key
          _snake_case							=				val
          _snake_case							=				None
          _snake_case							=				None






     def __repr__(			self   )							->      str:
          return (
              f"""Node: key: {self.key}, val: {self.val}, """
              f"""has next: {bool(self.next   )}, has prev: {bool(self.prev   )}"""
          )







class        _a    (						Generic[T, U]							):






     def __init__(			self   )							->      None:
          _snake_case							=				DoubleLinkedListNode(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )
          _snake_case							=				DoubleLinkedListNode(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )
          _snake_case							, _snake_case							=				self.rear, self.head






     def __repr__(			self   )							->      str:
          _snake_case							=				["DoubleLinkedList"]
          _snake_case							=				self.head
          while node.next is not None:
               rep.append(str(_SCREAMING_SNAKE_CASE   )   )
               _snake_case							=				node.next
          rep.append(str(self.rear   )   )
          return ",\n    ".join(_SCREAMING_SNAKE_CASE   )






     def     _lowercase     (			self ,_SCREAMING_SNAKE_CASE   )							->      None:
          _snake_case							=				self.rear.prev

          # All nodes other than self.head are guaranteed to have non-None previous
          assert previous is not None

          _snake_case							=				node
          _snake_case							=				previous
          _snake_case							=				node
          _snake_case							=				self.rear






     def     _lowercase     (			self ,_SCREAMING_SNAKE_CASE   )							->      DoubleLinkedListNode[T, U] | None:

          if node.prev is None or node.next is None:
               return None

          _snake_case							=				node.next
          _snake_case							=				node.prev
          _snake_case							=				None
          _snake_case							=				None
          return node







class        _a    (						Generic[T, U]							):
     SCREAMING_SNAKE_CASE_							:   dict[Callable[[T], U], LRUCache[T, U]]       =						{}






     def __init__(			self ,_SCREAMING_SNAKE_CASE   )							->      str:
          _snake_case							=				DoubleLinkedList()
          _snake_case							=				capacity
          _snake_case							=				0
          _snake_case							=				0
          _snake_case							=				0
          _snake_case							=				{}






     def __repr__(			self   )							->      str:
          return (
              f"""CacheInfo(hits={self.hits}, misses={self.miss}, """
              f"""capacity={self.capacity}, current size={self.num_keys})"""
          )






     def __contains__(			self ,_SCREAMING_SNAKE_CASE   )							->      bool:
          return key in self.cache






     def     _lowercase     (			self ,_SCREAMING_SNAKE_CASE   )							->      U | None:
          # Note: pythonic interface would throw KeyError rather than return None

          if key in self.cache:
               self.hits += 1
               _snake_case							=				self.cache[key]
               _snake_case							=				self.list.remove(self.cache[key]   )
               assert node == value_node

               # node is guaranteed not None because it is in self.cache
               assert node is not None
               self.list.add(_SCREAMING_SNAKE_CASE   )
               return node.val
          self.miss += 1
          return None






     def     _lowercase     (			self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )							->      None:

          if key not in self.cache:
               if self.num_keys >= self.capacity:
                    # delete first node (oldest) when over capacity
                    _snake_case							=				self.list.head.next

                    # guaranteed to have a non-None first node when num_keys > 0
                    # explain to type checker via assertions
                    assert first_node is not None
                    assert first_node.key is not None
                    assert (
                        self.list.remove(_SCREAMING_SNAKE_CASE   ) is not None
                    )  # node guaranteed to be in list assert node.key is not None

                    del self.cache[first_node.key]
                    self.num_keys -= 1
               _snake_case							=				DoubleLinkedListNode(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )
               self.list.add(self.cache[key]   )
               self.num_keys += 1

          else:
               # bump node to the end of the list, update value
               _snake_case							=				self.list.remove(self.cache[key]   )
               assert node is not None  # node guaranteed to be in list
               _snake_case							=				value
               self.list.add(_SCREAMING_SNAKE_CASE   )






     @classmethod
     def     _lowercase     (			cls ,_SCREAMING_SNAKE_CASE = 128   )							->      Callable[[Callable[[T], U]], Callable[..., U]]:

          def cache_decorator_inner(_SCREAMING_SNAKE_CASE   ) -> Callable[..., U]:
               def cache_decorator_wrapper(*_SCREAMING_SNAKE_CASE   ) -> U:
                    if func not in cls.decorator_function_to_instance_map:
                         _snake_case							=				LRUCache(_SCREAMING_SNAKE_CASE   )

                    _snake_case							=				cls.decorator_function_to_instance_map[func].get(args[0]   )
                    if result is None:
                         _snake_case							=				func(*_SCREAMING_SNAKE_CASE   )
                         cls.decorator_function_to_instance_map[func].put(args[0] ,_SCREAMING_SNAKE_CASE   )
                    return result

               def cache_info() -> LRUCache[T, U]:
                    return cls.decorator_function_to_instance_map[func]

               setattr(_SCREAMING_SNAKE_CASE ,"cache_info" ,_SCREAMING_SNAKE_CASE   )  # noqa: B010

               return cache_decorator_wrapper

          return cache_decorator_inner


if __name__ == "__main__":
   import doctest

   doctest.testmod()


