


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



     """simple docstring"""






     def a	( self   ):

            '''simple docstring'''

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

                   _lowerCAmelCase    :							Union[str, Any]   			=       [t[-1] for t in os.walk(os.path.join(snake_case__      ,	os.listdir(snake_case__   )[0]      ,	'snapshots'   )   )]
                   _lowerCAmelCase    :							Tuple   			=       [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 	UpperCamelCase__					( unittest.TestCase	):



     """simple docstring"""






     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase			,     _lowerCAmelCase    :							Tuple   			=       FlaxStableDiffusionPipeline.from_pretrained(
                'hf-internal-testing/tiny-stable-diffusion-pipe'      ,	safety_checker=snake_case__   )

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

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

            _lowerCAmelCase    :							str   			=       jax.device_count()
            _lowerCAmelCase    :							Union[str, Any]   			=       num_samples * [prompt]
            _lowerCAmelCase    :							List[Any]   			=       pipeline.prepare_inputs(snake_case__   )

            # shard inputs and rng
            _lowerCAmelCase    :							List[Any]   			=       replicate(snake_case__   )
            _lowerCAmelCase    :							Tuple   			=       jax.random.split(snake_case__      ,	snake_case__   )
            _lowerCAmelCase    :							int   			=       shard(snake_case__   )

            _lowerCAmelCase    :							List[str]   			=       pipeline(snake_case__      ,	snake_case__      ,	snake_case__      ,	snake_case__      ,	jit=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.151_4745   ) < 1E-3
                   assert np.abs(np.abs(snake_case__      ,	dtype=np.floataa   ).sum() - 4_9947.875   ) < 5E-1

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







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase			,     _lowerCAmelCase    :							Optional[Any]   			=       FlaxStableDiffusionPipeline.from_pretrained(
                'CompVis/stable-diffusion-v1-4'      ,	revision='flax'      ,	safety_checker=snake_case__   )

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

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

            _lowerCAmelCase    :							List[str]   			=       jax.device_count()
            _lowerCAmelCase    :							Union[str, Any]   			=       num_samples * [prompt]
            _lowerCAmelCase    :							str   			=       pipeline.prepare_inputs(snake_case__   )

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

            _lowerCAmelCase    :							Optional[Any]   			=       pipeline(snake_case__      ,	snake_case__      ,	snake_case__      ,	snake_case__      ,	jit=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.0565_2401)   ) < 1E-3
                   assert np.abs((np.abs(snake_case__      ,	dtype=np.floataa   ).sum() - 238_3808.2)   ) < 5E-1







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase			,     _lowerCAmelCase    :							str   			=       FlaxStableDiffusionPipeline.from_pretrained(
                'CompVis/stable-diffusion-v1-4'      ,	revision='bf16'      ,	dtype=jnp.bfloataa      ,	safety_checker=snake_case__   )

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

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

            _lowerCAmelCase    :							Optional[Any]   			=       jax.device_count()
            _lowerCAmelCase    :							Optional[Any]   			=       num_samples * [prompt]
            _lowerCAmelCase    :							Optional[Any]   			=       pipeline.prepare_inputs(snake_case__   )

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

            _lowerCAmelCase    :							List[Any]   			=       pipeline(snake_case__      ,	snake_case__      ,	snake_case__      ,	snake_case__      ,	jit=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.0400_3906)   ) < 1E-3
                   assert np.abs((np.abs(snake_case__      ,	dtype=np.floataa   ).sum() - 237_3516.75)   ) < 5E-1







     def a	( self   ):

            '''simple docstring'''

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

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

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

            _lowerCAmelCase    :							Optional[Any]   			=       jax.device_count()
            _lowerCAmelCase    :							List[Any]   			=       num_samples * [prompt]
            _lowerCAmelCase    :							Dict   			=       pipeline.prepare_inputs(snake_case__   )

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

            _lowerCAmelCase    :							Dict   			=       pipeline(snake_case__      ,	snake_case__      ,	snake_case__      ,	snake_case__      ,	jit=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.0400_3906)   ) < 1E-3
                   assert np.abs((np.abs(snake_case__      ,	dtype=np.floataa   ).sum() - 237_3516.75)   ) < 5E-1







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Tuple   			=       FlaxDDIMScheduler(
                beta_start=0.0_0085      ,	beta_end=0.012      ,	beta_schedule='scaled_linear'      ,	set_alpha_to_one=snake_case__      ,	steps_offset=1      ,	)

            _lowerCAmelCase			,     _lowerCAmelCase    :							Union[str, Any]   			=       FlaxStableDiffusionPipeline.from_pretrained(
                'CompVis/stable-diffusion-v1-4'      ,	revision='bf16'      ,	dtype=jnp.bfloataa      ,	scheduler=snake_case__      ,	safety_checker=snake_case__      ,	)
            _lowerCAmelCase    :							Tuple   			=       scheduler.create_state()

            _lowerCAmelCase    :							str   			=       scheduler_state

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

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

            _lowerCAmelCase    :							str   			=       jax.device_count()
            _lowerCAmelCase    :							List[str]   			=       num_samples * [prompt]
            _lowerCAmelCase    :							Union[str, Any]   			=       pipeline.prepare_inputs(snake_case__   )

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

            _lowerCAmelCase    :							Tuple   			=       pipeline(snake_case__      ,	snake_case__      ,	snake_case__      ,	snake_case__      ,	jit=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_4504_3945)   ) < 1E-3
                   assert np.abs((np.abs(snake_case__      ,	dtype=np.floataa   ).sum() - 234_7693.5)   ) < 5E-1







     def a	( self   ):

            '''simple docstring'''

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

            _lowerCAmelCase    :							List[str]   			=       jax.device_count()
            _lowerCAmelCase    :							List[str]   			=       num_samples * [prompt]
            _lowerCAmelCase    :							List[str]   			=       jax.random.split(jax.random.PRNGKey(0   )      ,	snake_case__   )

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

            _lowerCAmelCase    :							str   			=       replicate(snake_case__   )
            _lowerCAmelCase    :							int   			=       pipeline.prepare_inputs(snake_case__   )
            _lowerCAmelCase    :							Any   			=       shard(snake_case__   )
            _lowerCAmelCase    :							List[str]   			=       pipeline(snake_case__      ,	snake_case__      ,	snake_case__      ,	jit=snake_case__   ).images
            assert images.shape == (num_samples, 1, 512, 512, 3)
            _lowerCAmelCase    :							Optional[Any]   			=       images[2, 0, 256, 10:17, 1]

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

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







lowerCAmelCase    :     Optional[int]					=						[sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(10_00_00)]






def 			lowercase				(_A					):







       """simple docstring"""







       _lowerCAmelCase    :							str   			=       0
       while number:
              # Increased Speed Slightly by checking every 5 digits together.
              sum_of_digits_squared += DIGITS_SQUARED[number % 1_0_0_0_0_0]
              number //= 1_0_0_0_0_0

       return sum_of_digits_squared


# There are 2 Chains made,
# One ends with 89 with the chain member 58 being the one which when declared first,
# there will be the least number of iterations for all the members to be checked.

# The other one ends with 1 and has only one element 1.

# So 58 and 1 are chosen to be declared at the starting.

# Changed dictionary to an array to quicken the solution
lowerCAmelCase    :     list[bool | None]					=						[None] * 10_00_00_00
lowerCAmelCase    :     List[str]					=						True
lowerCAmelCase    :     Union[str, Any]					=						False






def 			lowercase				(_A					):







       """simple docstring"""







       if CHAINS[number - 1] is not None:
              return CHAINS[number - 1]  # type: ignore

       _lowerCAmelCase    :							Any   			=       chain(next_number(_A					)					)
       _lowerCAmelCase    :							List[str]   			=       number_chain

       while number < 1_0_0_0_0_0_0_0:
              _lowerCAmelCase    :							Tuple   			=       number_chain
              number *= 1_0

       return number_chain






def 			lowercase				(_A = 1_0_0_0_0_0_0_0					):







       """simple docstring"""







       for i in range(1   ,						_A					):
              if CHAINS[i] is None:
                     chain(i + 1					)

       return CHAINS[:number].count(_A					)


if __name__ == "__main__":
       import doctest

       doctest.testmod()
       print(F'''{solution() = }''')

