




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







   """simple docstring"""




   def   UpperCAmelCase__			(		self)				->   Optional[Any]:
       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 				snake_case_			(					unittest.TestCase			):







   """simple docstring"""




   def   UpperCAmelCase__			(		self)				->   Any:
       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.151_4745) < 1e-3
           assert np.abs(np.abs(lowerCamelCase_       ,					dtype=np.floataa).sum() - 4_9947.875) < 5e-1

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







   def   UpperCAmelCase__			(		self)				->   Tuple:
       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.0565_2401)) < 1e-3
           assert np.abs((np.abs(lowerCamelCase_       ,					dtype=np.floataa).sum() - 238_3808.2)) < 5e-1







   def   UpperCAmelCase__			(		self)				->   Any:
       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.0400_3906)) < 1e-3
           assert np.abs((np.abs(lowerCamelCase_       ,					dtype=np.floataa).sum() - 237_3516.75)) < 5e-1







   def   UpperCAmelCase__			(		self)				->   str:
       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.0400_3906)) < 1e-3
           assert np.abs((np.abs(lowerCamelCase_       ,					dtype=np.floataa).sum() - 237_3516.75)) < 5e-1







   def   UpperCAmelCase__			(		self)				->   str:
       UpperCamelCase              =	FlaxDDIMScheduler(
           beta_start=0.0_0085       ,					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.0_4504_3945)) < 1e-3
           assert np.abs((np.abs(lowerCamelCase_       ,					dtype=np.floataa).sum() - 234_7693.5)) < 5e-1







   def   UpperCAmelCase__			(		self)				->   List[Any]:
       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



class   SCREAMING_SNAKE_CASE_			:




       '''simple docstring'''



       def __init__(						self				:				List[Any]							)					->Tuple:
          lowerCamelCase_						:   Optional[Any]		= """"""
          lowerCamelCase_						:   Dict		= """"""
          lowerCamelCase_						:   Optional[Any]		= []



       def 				_lowerCAmelCase							(						self				:				Optional[Any]		,				__a				:				int		,				__a				:				int							)					->int:
          if m == -1:
             return n + 1
          elif n == -1:
             return m + 1
          elif self.dp[m][n] > -1:
             return self.dp[m][n]
          else:
             if self.worda[m] == self.worda[n]:
                lowerCamelCase_						:   Optional[Any]		= self.__min_dist_top_down_dp(m - 1		,				n - 1							)
             else:
                lowerCamelCase_						:   List[Any]		= self.__min_dist_top_down_dp(__a		,				n - 1							)
                lowerCamelCase_						:   Union[str, Any]		= self.__min_dist_top_down_dp(m - 1		,				__a							)
                lowerCamelCase_						:   Any		= self.__min_dist_top_down_dp(m - 1		,				n - 1							)
                lowerCamelCase_						:   Tuple		= 1 + min(__a		,				__a		,				__a							)

             return self.dp[m][n]



       def 				_lowerCAmelCase							(						self				:				Any		,				__a				:				str		,				__a				:				str							)					->int:
          lowerCamelCase_						:   Dict		= worda
          lowerCamelCase_						:   str		= worda
          lowerCamelCase_						:   Union[str, Any]		= [[-1 for _ in range(len(__a							)							)] for _ in range(len(__a							)							)]

          return self.__min_dist_top_down_dp(len(__a							) - 1		,				len(__a							) - 1							)




       def 				_lowerCAmelCase							(						self				:				int		,				__a				:				str		,				__a				:				str							)					->int:
          lowerCamelCase_						:   Tuple		= worda
          lowerCamelCase_						:   Optional[Any]		= worda
          lowerCamelCase_						:   Tuple		= len(__a							)
          lowerCamelCase_						:   Optional[Any]		= len(__a							)
          lowerCamelCase_						:   List[Any]		= [[0 for _ in range(n + 1							)] for _ in range(m + 1							)]

          for i in range(m + 1							):
             for j in range(n + 1							):
                if i == 0:  # first string is empty
                   lowerCamelCase_						:   Optional[Any]		= j
                elif j == 0:  # second string is empty
                   lowerCamelCase_						:   Any		= i
                elif worda[i - 1] == worda[j - 1]:  # last characters are equal
                   lowerCamelCase_						:   Tuple		= self.dp[i - 1][j - 1]
                else:
                   lowerCamelCase_						:   Dict		= self.dp[i][j - 1]
                   lowerCamelCase_						:   Union[str, Any]		= self.dp[i - 1][j]
                   lowerCamelCase_						:   Any		= self.dp[i - 1][j - 1]
                   lowerCamelCase_						:   Optional[int]		= 1 + min(__a		,				__a		,				__a							)
          return self.dp[m][n]


if __name__ == "__main__":
      snake_case__				:	Optional[Any]					       =					EditDistance()

      print('****************** Testing Edit Distance DP Algorithm ******************')
      print()

      snake_case__				:	Union[str, Any]					       =					input('Enter the first string: ').strip()
      snake_case__				:	List[Any]					       =					input('Enter the second string: ').strip()

      print()
      print(F'The minimum edit distance is: {solver.min_dist_top_down(Sa, Sa)}')
      print(F'The minimum edit distance is: {solver.min_dist_bottom_up(Sa, Sa)}')
      print()
      print('*************** End of Testing Edit Distance DP Algorithm ***************')





