





"""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  _SCREAMING_SNAKE_CASE(       unittest.TestCase  ):




       def    _UpperCamelCase					(						self							)      ->				Tuple:





             """simple docstring"""






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

                   __SCREAMING_SNAKE_CASE       :int		    =  [t[-1] for t in os.walk(os.path.join(_lowercase		,os.listdir(_lowercase							)[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  ):




       def    _UpperCamelCase					(						self							)      ->				Dict:





             """simple docstring"""






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

             __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       :Optional[Any]		    =  jax.random.PRNGKey(0							)
             __SCREAMING_SNAKE_CASE       :Dict		    =  4

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

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

             __SCREAMING_SNAKE_CASE       :Any		    =  pipeline(_lowercase		,_lowercase		,_lowercase		,_lowercase		,jit=_lowercase							).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(_lowercase		,dtype=np.floataa							).sum() - 4_99_47.8_75							) < 5E-1

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




       def    _UpperCamelCase					(						self							)      ->				Union[str, Any]:





             """simple docstring"""






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

             __SCREAMING_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'''
             )

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

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

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

             __SCREAMING_SNAKE_CASE       :Tuple		    =  pipeline(_lowercase		,_lowercase		,_lowercase		,_lowercase		,jit=_lowercase							).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.0_5_6_5_2_4_0_1)							) < 1E-3
                   assert np.abs((np.abs(_lowercase		,dtype=np.floataa							).sum() - 2_38_38_08.2)							) < 5E-1




       def    _UpperCamelCase					(						self							)      ->				List[str]:





             """simple docstring"""






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

             __SCREAMING_SNAKE_CASE       :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       :Dict		    =  jax.random.PRNGKey(0							)
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  50

             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  jax.device_count()
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  num_samples * [prompt]
             __SCREAMING_SNAKE_CASE       :str		    =  pipeline.prepare_inputs(_lowercase							)

             # shard inputs and rng
             __SCREAMING_SNAKE_CASE       :int		    =  replicate(_lowercase							)
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  jax.random.split(_lowercase		,_lowercase							)
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  shard(_lowercase							)

             __SCREAMING_SNAKE_CASE       :str		    =  pipeline(_lowercase		,_lowercase		,_lowercase		,_lowercase		,jit=_lowercase							).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.0_4_0_0_3_9_0_6)							) < 1E-3
                   assert np.abs((np.abs(_lowercase		,dtype=np.floataa							).sum() - 2_37_35_16.75)							) < 5E-1




       def    _UpperCamelCase					(						self							)      ->				List[Any]:





             """simple docstring"""






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

             __SCREAMING_SNAKE_CASE       :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       :Union[str, Any]		    =  jax.random.PRNGKey(0							)
             __SCREAMING_SNAKE_CASE       :List[str]		    =  50

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

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

             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  pipeline(_lowercase		,_lowercase		,_lowercase		,_lowercase		,jit=_lowercase							).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.0_4_0_0_3_9_0_6)							) < 1E-3
                   assert np.abs((np.abs(_lowercase		,dtype=np.floataa							).sum() - 2_37_35_16.75)							) < 5E-1




       def    _UpperCamelCase					(						self							)      ->				Any:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :List[Any]		    =  FlaxDDIMScheduler(
                 beta_start=0.0_0_0_8_5		,beta_end=0.0_1_2		,beta_schedule='''scaled_linear'''		,set_alpha_to_one=_lowercase		,steps_offset=1		,)

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

             __SCREAMING_SNAKE_CASE       :Any		    =  scheduler_state

             __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       :Optional[Any]		    =  jax.random.PRNGKey(0							)
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  50

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

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

             __SCREAMING_SNAKE_CASE       :List[str]		    =  pipeline(_lowercase		,_lowercase		,_lowercase		,_lowercase		,jit=_lowercase							).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.0_4_5_0_4_3_9_4_5)							) < 1E-3
                   assert np.abs((np.abs(_lowercase		,dtype=np.floataa							).sum() - 2_34_76_93.5)							) < 5E-1




       def    _UpperCamelCase					(						self							)      ->				Dict:





             """simple docstring"""






             __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       :Any		    =  jax.device_count()
             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  num_samples * [prompt]
             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  jax.random.split(jax.random.PRNGKey(0							)		,_lowercase							)

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

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

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

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








"""simple docstring"""
from itertools import product



def 					__lowerCamelCase       (							a_					:		int			,       a_					:		int							)      ->				list[int]:
      __SCREAMING_SNAKE_CASE       :Tuple		    =  sides_number
      __SCREAMING_SNAKE_CASE       :List[Any]		    =  max_face_number * dice_number
      __SCREAMING_SNAKE_CASE       :List[Any]		    =  [0] * (max_total + 1)

      __SCREAMING_SNAKE_CASE       :Optional[int]		    =  1
      __SCREAMING_SNAKE_CASE       :Tuple		    =  range(a_			,       max_face_number + 1							)
      for dice_numbers in product(a_			,       repeat=a_							):
            __SCREAMING_SNAKE_CASE       :Any		    =  sum(a_							)
            totals_frequencies[total] += 1

      return totals_frequencies



def 					__lowerCamelCase       (							)      ->				float:
      __SCREAMING_SNAKE_CASE       :Dict		    =  total_frequency_distribution(
          sides_number=4			,       dice_number=9							)
      __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  total_frequency_distribution(
          sides_number=6			,       dice_number=6							)

      __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  0
      __SCREAMING_SNAKE_CASE       :Any		    =  9
      __SCREAMING_SNAKE_CASE       :List[str]		    =  4 * 9
      __SCREAMING_SNAKE_CASE       :Dict		    =  6
      for peter_total in range(a_			,       max_peter_total + 1							):
            peter_wins_count += peter_totals_frequencies[peter_total] * sum(
                colin_totals_frequencies[min_colin_total:peter_total]							)

      __SCREAMING_SNAKE_CASE       :List[str]		    =  (4**9) * (6**6)
      __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  peter_wins_count / total_games_number

      __SCREAMING_SNAKE_CASE       :str		    =  round(a_			,       ndigits=7							)

      return rounded_peter_win_probability


if __name__ == "__main__":
  print(f'{solution() = }')