



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        _snake_case    (self				):
						with tempfile.TemporaryDirectory() as tmpdirname:
									# pipeline has Flax weights
									lowerCamelCase__ :      List[Any]								=		FlaxDiffusionPipeline.from_pretrained(
									    """hf-internal-testing/tiny-stable-diffusion-pipe"""							,    safety_checker=__magic_name__							,    cache_dir=__magic_name__				)

									lowerCamelCase__ :      Tuple								=		[t[-1] for t in os.walk(os.path.join(__magic_name__							,    os.listdir(__magic_name__				)[0]							,    """snapshots"""				)				)]
									lowerCamelCase__ :      Union[str, 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 				__A					( unittest.TestCase      ):





			def        _snake_case    (self				):
						lowerCamelCase__							,lowerCamelCase__ :      Optional[int]								=		FlaxStableDiffusionPipeline.from_pretrained(
						    """hf-internal-testing/tiny-stable-diffusion-pipe"""							,    safety_checker=__magic_name__				)

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

						lowerCamelCase__ :      Union[str, Any]								=		jax.random.PRNGKey(0				)
						lowerCamelCase__ :      str								=		4

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

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

						lowerCamelCase__ :      List[Any]								=		pipeline(__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    jit=__magic_name__				).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_51_47_45				) < 1E-3
									assert np.abs(np.abs(__magic_name__							,    dtype=np.floataa				).sum() - 4_99_47.8_75				) < 5E-1

						lowerCamelCase__ :      Union[str, Any]								=		pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]				)				)				)
						assert len(__magic_name__				) == num_samples





			def        _snake_case    (self				):
						lowerCamelCase__							,lowerCamelCase__ :      Union[str, Any]								=		FlaxStableDiffusionPipeline.from_pretrained(
						    """CompVis/stable-diffusion-v1-4"""							,    revision="""flax"""							,    safety_checker=__magic_name__				)

						lowerCamelCase__ :      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__ :      Dict								=		jax.random.PRNGKey(0				)
						lowerCamelCase__ :      List[str]								=		50

						lowerCamelCase__ :      str								=		jax.device_count()
						lowerCamelCase__ :      str								=		num_samples * [prompt]
						lowerCamelCase__ :      List[str]								=		pipeline.prepare_inputs(__magic_name__				)

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

						lowerCamelCase__ :      Optional[int]								=		pipeline(__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    jit=__magic_name__				).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_65_24_01)				) < 1E-3
									assert np.abs((np.abs(__magic_name__							,    dtype=np.floataa				).sum() - 2_38_38_08.2)				) < 5E-1





			def        _snake_case    (self				):
						lowerCamelCase__							,lowerCamelCase__ :      Optional[Any]								=		FlaxStableDiffusionPipeline.from_pretrained(
						    """CompVis/stable-diffusion-v1-4"""							,    revision="""bf16"""							,    dtype=jnp.bfloataa							,    safety_checker=__magic_name__				)

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

						lowerCamelCase__ :      Union[str, Any]								=		jax.device_count()
						lowerCamelCase__ :      Tuple								=		num_samples * [prompt]
						lowerCamelCase__ :      Optional[Any]								=		pipeline.prepare_inputs(__magic_name__				)

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

						lowerCamelCase__ :      int								=		pipeline(__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    jit=__magic_name__				).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_00_39_06)				) < 1E-3
									assert np.abs((np.abs(__magic_name__							,    dtype=np.floataa				).sum() - 2_37_35_16.75)				) < 5E-1





			def        _snake_case    (self				):
						lowerCamelCase__							,lowerCamelCase__ :      Optional[Any]								=		FlaxStableDiffusionPipeline.from_pretrained(
						    """CompVis/stable-diffusion-v1-4"""							,    revision="""bf16"""							,    dtype=jnp.bfloataa				)

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

						lowerCamelCase__ :      List[str]								=		jax.device_count()
						lowerCamelCase__ :      List[Any]								=		num_samples * [prompt]
						lowerCamelCase__ :      int								=		pipeline.prepare_inputs(__magic_name__				)

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

						lowerCamelCase__ :      Optional[Any]								=		pipeline(__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    jit=__magic_name__				).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_00_39_06)				) < 1E-3
									assert np.abs((np.abs(__magic_name__							,    dtype=np.floataa				).sum() - 2_37_35_16.75)				) < 5E-1





			def        _snake_case    (self				):
						lowerCamelCase__ :      str								=		FlaxDDIMScheduler(
						    beta_start=0.0_00_85							,    beta_end=0.0_12							,    beta_schedule="""scaled_linear"""							,    set_alpha_to_one=__magic_name__							,    steps_offset=1							,    )

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

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

						lowerCamelCase__ :      Optional[int]								=		jax.device_count()
						lowerCamelCase__ :      Optional[Any]								=		num_samples * [prompt]
						lowerCamelCase__ :      List[Any]								=		pipeline.prepare_inputs(__magic_name__				)

						# shard inputs and rng
						lowerCamelCase__ :      Dict								=		replicate(__magic_name__				)
						lowerCamelCase__ :      Optional[int]								=		jax.random.split(__magic_name__							,    __magic_name__				)
						lowerCamelCase__ :      Tuple								=		shard(__magic_name__				)

						lowerCamelCase__ :      List[Any]								=		pipeline(__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    jit=__magic_name__				).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_45_04_39_45)				) < 1E-3
									assert np.abs((np.abs(__magic_name__							,    dtype=np.floataa				).sum() - 2_34_76_93.5)				) < 5E-1





			def        _snake_case    (self				):
						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__ :      Tuple								=		jax.device_count()
						lowerCamelCase__ :      Optional[int]								=		num_samples * [prompt]
						lowerCamelCase__ :      List[str]								=		jax.random.split(jax.random.PRNGKey(0				)							,    __magic_name__				)

						lowerCamelCase__							,lowerCamelCase__ :      Dict								=		FlaxStableDiffusionPipeline.from_pretrained(
						    """CompVis/stable-diffusion-v1-4"""							,    revision="""bf16"""							,    dtype=jnp.bfloataa							,    safety_checker=__magic_name__							,    )

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

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

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








from math import factorial, pi






def      _A				(UpperCamelCase		:      float      ,			UpperCamelCase		:      int = 30 )  ->float:



			'''simple docstring'''







			if not isinstance(UpperCamelCase      ,			(int, float) ):
						raise ValueError("""maclaurin_sin() requires either an int or float for theta""" )

			if not isinstance(UpperCamelCase      ,			UpperCamelCase ) or accuracy <= 0:
						raise ValueError("""maclaurin_sin() requires a positive int for accuracy""" )

			lowerCamelCase__ :      Dict								=		float(UpperCamelCase )
			lowerCamelCase__ :      int								=		theta // (2 * pi)
			theta -= 2 * div * pi
			return sum(
			    (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(UpperCamelCase ) )






def      _A				(UpperCamelCase		:      float      ,			UpperCamelCase		:      int = 30 )  ->float:



			'''simple docstring'''







			if not isinstance(UpperCamelCase      ,			(int, float) ):
						raise ValueError("""maclaurin_cos() requires either an int or float for theta""" )

			if not isinstance(UpperCamelCase      ,			UpperCamelCase ) or accuracy <= 0:
						raise ValueError("""maclaurin_cos() requires a positive int for accuracy""" )

			lowerCamelCase__ :      int								=		float(UpperCamelCase )
			lowerCamelCase__ :      Optional[int]								=		theta // (2 * pi)
			theta -= 2 * div * pi
			return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(UpperCamelCase ) )


if __name__ == "__main__":
				import doctest

				doctest.testmod()

				print(maclaurin_sin(10))
				print(maclaurin_sin(-10))
				print(maclaurin_sin(10, 15))
				print(maclaurin_sin(-10, 15))

				print(maclaurin_cos(5))
				print(maclaurin_cos(-5))
				print(maclaurin_cos(10, 15))
				print(maclaurin_cos(-10, 15))



