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


						def  __A ( self			:       Optional[int]		):





												'''simple docstring'''





												with tempfile.TemporaryDirectory() as tmpdirname:
																		# pipeline has Flax weights
																		SCREAMING_SNAKE_CASE							:					Any           =							FlaxDiffusionPipeline.from_pretrained(
																		    '''hf-internal-testing/tiny-stable-diffusion-pipe'''					,	safety_checker=UpperCamelCase__					,	cache_dir=UpperCamelCase__		)

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


						def  __A ( self			:       Any		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					List[Any]           =							FlaxStableDiffusionPipeline.from_pretrained(
												    '''hf-internal-testing/tiny-stable-diffusion-pipe'''					,	safety_checker=UpperCamelCase__		)

												SCREAMING_SNAKE_CASE							:					str           =							(
												    '''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.random.PRNGKey(0		)
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							4

												SCREAMING_SNAKE_CASE							:					Optional[int]           =							jax.device_count()
												SCREAMING_SNAKE_CASE							:					Dict           =							num_samples * [prompt]
												SCREAMING_SNAKE_CASE							:					Any           =							pipeline.prepare_inputs(UpperCamelCase__		)

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

												SCREAMING_SNAKE_CASE							:					List[str]           =							pipeline(UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	jit=UpperCamelCase__		).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(UpperCamelCase__					,	dtype=np.floataa		).sum() - 4_9947.875		) < 5E-1

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


						def  __A ( self			:       Optional[Any]		):





												'''simple docstring'''





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

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

												SCREAMING_SNAKE_CASE							:					str           =							jax.device_count()
												SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							num_samples * [prompt]
												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							pipeline.prepare_inputs(UpperCamelCase__		)

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

												SCREAMING_SNAKE_CASE							:					Dict           =							pipeline(UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	jit=UpperCamelCase__		).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(UpperCamelCase__					,	dtype=np.floataa		).sum() - 238_3808.2)		) < 5E-1


						def  __A ( self			:       Optional[Any]		):





												'''simple docstring'''





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

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

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

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

												SCREAMING_SNAKE_CASE							:					Tuple           =							pipeline(UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	jit=UpperCamelCase__		).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(UpperCamelCase__					,	dtype=np.floataa		).sum() - 237_3516.75)		) < 5E-1


						def  __A ( self			:       Dict		):





												'''simple docstring'''





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

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

												SCREAMING_SNAKE_CASE							:					Optional[int]           =							jax.device_count()
												SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							num_samples * [prompt]
												SCREAMING_SNAKE_CASE							:					str           =							pipeline.prepare_inputs(UpperCamelCase__		)

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

												SCREAMING_SNAKE_CASE							:					Optional[int]           =							pipeline(UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	jit=UpperCamelCase__		).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(UpperCamelCase__					,	dtype=np.floataa		).sum() - 237_3516.75)		) < 5E-1


						def  __A ( self			:       int		):





												'''simple docstring'''





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

												SCREAMING_SNAKE_CASE							:					Any           =							FlaxStableDiffusionPipeline.from_pretrained(
												    '''CompVis/stable-diffusion-v1-4'''					,	revision='''bf16'''					,	dtype=jnp.bfloataa					,	scheduler=UpperCamelCase__					,	safety_checker=UpperCamelCase__					,	)
												SCREAMING_SNAKE_CASE							:					Any           =							scheduler.create_state()

												SCREAMING_SNAKE_CASE							:					Tuple           =							scheduler_state

												SCREAMING_SNAKE_CASE							:					Union[str, 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							:					str           =							50

												SCREAMING_SNAKE_CASE							:					Tuple           =							jax.device_count()
												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							num_samples * [prompt]
												SCREAMING_SNAKE_CASE							:					str           =							pipeline.prepare_inputs(UpperCamelCase__		)

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

												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							pipeline(UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	jit=UpperCamelCase__		).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(UpperCamelCase__					,	dtype=np.floataa		).sum() - 234_7693.5)		) < 5E-1



						def  __A ( self			:       Optional[int]		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					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							:					int           =							jax.device_count()
												SCREAMING_SNAKE_CASE							:					Any           =							num_samples * [prompt]
												SCREAMING_SNAKE_CASE							:					List[str]           =							jax.random.split(jax.random.PRNGKey(0		)					,	UpperCamelCase__		)

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

												SCREAMING_SNAKE_CASE							:					str           =							replicate(UpperCamelCase__		)
												SCREAMING_SNAKE_CASE							:					List[str]           =							pipeline.prepare_inputs(UpperCamelCase__		)
												SCREAMING_SNAKE_CASE							:					Dict           =							shard(UpperCamelCase__		)
												SCREAMING_SNAKE_CASE							:					Tuple           =							pipeline(UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	jit=UpperCamelCase__		).images
												assert images.shape == (num_samples, 1, 512, 512, 3)
												SCREAMING_SNAKE_CASE							:					Any           =							images[2, 0, 256, 10:17, 1]

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

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

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


__UpperCamelCase	: Tuple    		=  {
    'configuration_maskformer': ['MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MaskFormerConfig'],
    'configuration_maskformer_swin': ['MaskFormerSwinConfig'],
}

try:
					if not is_vision_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					__UpperCamelCase	: Optional[Any]    		=  ['MaskFormerFeatureExtractor']
					__UpperCamelCase	: List[Any]    		=  ['MaskFormerImageProcessor']


try:
					if not is_torch_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					__UpperCamelCase	: Optional[int]    		=  [
					    'MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
					    'MaskFormerForInstanceSegmentation',
					    'MaskFormerModel',
					    'MaskFormerPreTrainedModel',
					]
					__UpperCamelCase	: Union[str, Any]    		=  [
					    'MaskFormerSwinBackbone',
					    'MaskFormerSwinModel',
					    'MaskFormerSwinPreTrainedModel',
					]

if TYPE_CHECKING:
					from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig
					from .configuration_maskformer_swin import MaskFormerSwinConfig

					try:
										if not is_vision_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .feature_extraction_maskformer import MaskFormerFeatureExtractor
										from .image_processing_maskformer import MaskFormerImageProcessor
					try:
										if not is_torch_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_maskformer import (
										    MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
										    MaskFormerForInstanceSegmentation,
										    MaskFormerModel,
										    MaskFormerPreTrainedModel,
										)
										from .modeling_maskformer_swin import (
										    MaskFormerSwinBackbone,
										    MaskFormerSwinModel,
										    MaskFormerSwinPreTrainedModel,
										)


else:
					import sys

					__UpperCamelCase	: List[str]    		=  _LazyModule(__name__, globals()['__file__'], _import_structure)





