

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







			def      UpperCamelCase		(    self       )  ->						List[Any]:
							'''simple docstring'''






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

											A__        =			[t[-1] for t in os.walk(os.path.join(lowercase      ,      os.listdir(lowercase       )[0]      ,      "snapshots"       )       )]
											A__        =			[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			):
			"""simple docstring"""







			def      UpperCamelCase		(    self       )  ->						Optional[int]:
							'''simple docstring'''






							A__    ,				A__        =			FlaxStableDiffusionPipeline.from_pretrained(
							    "hf-internal-testing/tiny-stable-diffusion-pipe"      ,      safety_checker=lowercase       )

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

							A__        =			jax.random.PRNGKey(0       )
							A__        =			4

							A__        =			jax.device_count()
							A__        =			num_samples * [prompt]
							A__        =			pipeline.prepare_inputs(lowercase       )

							# shard inputs and rng
							A__        =			replicate(lowercase       )
							A__        =			jax.random.split(lowercase      ,      lowercase       )
							A__        =			shard(lowercase       )

							A__        =			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.151_4745       ) < 1e-3
											assert np.abs(np.abs(lowercase      ,      dtype=np.floataa       ).sum() - 4_9947.875       ) < 5e-1

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


			def      UpperCamelCase		(    self       )  ->						Optional[Any]:
							'''simple docstring'''






							A__    ,				A__        =			FlaxStableDiffusionPipeline.from_pretrained(
							    "CompVis/stable-diffusion-v1-4"      ,      revision="flax"      ,      safety_checker=lowercase       )

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

							A__        =			jax.random.PRNGKey(0       )
							A__        =			50

							A__        =			jax.device_count()
							A__        =			num_samples * [prompt]
							A__        =			pipeline.prepare_inputs(lowercase       )

							# shard inputs and rng
							A__        =			replicate(lowercase       )
							A__        =			jax.random.split(lowercase      ,      lowercase       )
							A__        =			shard(lowercase       )

							A__        =			pipeline(lowercase      ,      lowercase      ,      lowercase      ,      lowercase      ,      jit=lowercase       ).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(lowercase      ,      dtype=np.floataa       ).sum() - 238_3808.2)       ) < 5e-1


			def      UpperCamelCase		(    self       )  ->						Dict:
							'''simple docstring'''






							A__    ,				A__        =			FlaxStableDiffusionPipeline.from_pretrained(
							    "CompVis/stable-diffusion-v1-4"      ,      revision="bf16"      ,      dtype=jnp.bfloataa      ,      safety_checker=lowercase       )

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

							A__        =			jax.random.PRNGKey(0       )
							A__        =			50

							A__        =			jax.device_count()
							A__        =			num_samples * [prompt]
							A__        =			pipeline.prepare_inputs(lowercase       )

							# shard inputs and rng
							A__        =			replicate(lowercase       )
							A__        =			jax.random.split(lowercase      ,      lowercase       )
							A__        =			shard(lowercase       )

							A__        =			pipeline(lowercase      ,      lowercase      ,      lowercase      ,      lowercase      ,      jit=lowercase       ).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(lowercase      ,      dtype=np.floataa       ).sum() - 237_3516.75)       ) < 5e-1


			def      UpperCamelCase		(    self       )  ->						Any:
							'''simple docstring'''






							A__    ,				A__        =			FlaxStableDiffusionPipeline.from_pretrained(
							    "CompVis/stable-diffusion-v1-4"      ,      revision="bf16"      ,      dtype=jnp.bfloataa       )

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

							A__        =			jax.random.PRNGKey(0       )
							A__        =			50

							A__        =			jax.device_count()
							A__        =			num_samples * [prompt]
							A__        =			pipeline.prepare_inputs(lowercase       )

							# shard inputs and rng
							A__        =			replicate(lowercase       )
							A__        =			jax.random.split(lowercase      ,      lowercase       )
							A__        =			shard(lowercase       )

							A__        =			pipeline(lowercase      ,      lowercase      ,      lowercase      ,      lowercase      ,      jit=lowercase       ).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(lowercase      ,      dtype=np.floataa       ).sum() - 237_3516.75)       ) < 5e-1


			def      UpperCamelCase		(    self       )  ->						List[str]:
							'''simple docstring'''






							A__        =			FlaxDDIMScheduler(
							    beta_start=0.0_0085      ,      beta_end=0.012      ,      beta_schedule="scaled_linear"      ,      set_alpha_to_one=lowercase      ,      steps_offset=1      ,      )

							A__    ,				A__        =			FlaxStableDiffusionPipeline.from_pretrained(
							    "CompVis/stable-diffusion-v1-4"      ,      revision="bf16"      ,      dtype=jnp.bfloataa      ,      scheduler=lowercase      ,      safety_checker=lowercase      ,      )
							A__        =			scheduler.create_state()

							A__        =			scheduler_state

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

							A__        =			jax.random.PRNGKey(0       )
							A__        =			50

							A__        =			jax.device_count()
							A__        =			num_samples * [prompt]
							A__        =			pipeline.prepare_inputs(lowercase       )

							# shard inputs and rng
							A__        =			replicate(lowercase       )
							A__        =			jax.random.split(lowercase      ,      lowercase       )
							A__        =			shard(lowercase       )

							A__        =			pipeline(lowercase      ,      lowercase      ,      lowercase      ,      lowercase      ,      jit=lowercase       ).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(lowercase      ,      dtype=np.floataa       ).sum() - 234_7693.5)       ) < 5e-1


			def      UpperCamelCase		(    self       )  ->						Any:
							'''simple docstring'''






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

							A__        =			jax.device_count()
							A__        =			num_samples * [prompt]
							A__        =			jax.random.split(jax.random.PRNGKey(0       )      ,      lowercase       )

							A__    ,				A__        =			FlaxStableDiffusionPipeline.from_pretrained(
							    "CompVis/stable-diffusion-v1-4"      ,      revision="bf16"      ,      dtype=jnp.bfloataa      ,      safety_checker=lowercase      ,      )

							A__        =			replicate(lowercase       )
							A__        =			pipeline.prepare_inputs(lowercase       )
							A__        =			shard(lowercase       )
							A__        =			pipeline(lowercase      ,      lowercase      ,      lowercase      ,      jit=lowercase       ).images
							assert images.shape == (num_samples, 1, 512, 512, 3)
							A__        =			images[2, 0, 256, 10:17, 1]

							# With memory efficient attention
							A__    ,				A__        =			FlaxStableDiffusionPipeline.from_pretrained(
							    "CompVis/stable-diffusion-v1-4"      ,      revision="bf16"      ,      dtype=jnp.bfloataa      ,      safety_checker=lowercase      ,      use_memory_efficient_attention=lowercase      ,      )

							A__        =			replicate(lowercase       )
							A__        =			pipeline.prepare_inputs(lowercase       )
							A__        =			shard(lowercase       )
							A__        =			pipeline(lowercase      ,      lowercase      ,      lowercase      ,      jit=lowercase       ).images
							assert images_eff.shape == (num_samples, 1, 512, 512, 3)
							A__        =			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 __future__ import annotations

from collections.abc import Iterator
from typing import Any

class 					a__						:
			"""simple docstring"""







			def __init__(    self      ,      lowercase       )  ->						int:
							'''simple docstring'''






							A__        =			data
							A__        =			None

class 					a__						:
			"""simple docstring"""







			def __init__(    self       )  ->						List[Any]:
							'''simple docstring'''






							A__        =			None
							A__        =			None


			def __iter__(    self       )  ->						Iterator[Any]:
							'''simple docstring'''






							A__        =			self.head
							while self.head:
											yield node.data
											A__        =			node.next
											if node == self.head:
															break


			def __len__(    self       )  ->						int:
							'''simple docstring'''






							return sum(1 for _ in self       )


			def __repr__(    self       )  ->						List[Any]:
							'''simple docstring'''






							return "->".join(str(lowercase       ) for item in iter(self       )       )


			def      UpperCamelCase		(    self      ,      lowercase       )  ->						None:
							'''simple docstring'''






							self.insert_nth(len(self       )      ,      lowercase       )


			def      UpperCamelCase		(    self      ,      lowercase       )  ->						None:
							'''simple docstring'''






							self.insert_nth(0      ,      lowercase       )


			def      UpperCamelCase		(    self      ,      lowercase      ,      lowercase       )  ->						None:
							'''simple docstring'''






							if index < 0 or index > len(self       ):
											raise IndexError("list index out of range."       )
							A__        =			Node(lowercase       )
							if self.head is None:
											A__        =			new_node  # first node points itself
											A__        =			A__        =			new_node
							elif index == 0:  # insert at head
											A__        =			self.head
											A__        =			A__        =			new_node
							else:
											A__        =			self.head
											for _ in range(index - 1       ):
															A__        =			temp.next
											A__        =			temp.next
											A__        =			new_node
											if index == len(self       ) - 1:  # insert at tail
															A__        =			new_node


			def      UpperCamelCase		(    self       )  ->						List[Any]:
							'''simple docstring'''






							return self.delete_nth(0       )


			def      UpperCamelCase		(    self       )  ->						Any:
							'''simple docstring'''






							return self.delete_nth(len(self       ) - 1       )


			def      UpperCamelCase		(    self      ,      lowercase = 0       )  ->						Any:
							'''simple docstring'''






							if not 0 <= index < len(self       ):
											raise IndexError("list index out of range."       )
							A__        =			self.head
							if self.head == self.tail:  # just one node
											A__        =			A__        =			None
							elif index == 0:  # delete head node
											A__        =			self.tail.next.next
											A__        =			self.head.next
							else:
											A__        =			self.head
											for _ in range(index - 1       ):
															A__        =			temp.next
											A__        =			temp.next
											A__        =			temp.next.next
											if index == len(self       ) - 1:  # delete at tail
															A__        =			temp
							return delete_node.data


			def      UpperCamelCase		(    self       )  ->						bool:
							'''simple docstring'''






							return len(self       ) == 0



def 					lowerCAmelCase__							(	)			->      None:




				'''simple docstring'''





				A__        =			CircularLinkedList()
				assert len(SCREAMING_SNAKE_CASE_      ) == 0
				assert circular_linked_list.is_empty() is True
				assert str(SCREAMING_SNAKE_CASE_      ) == ""

				try:
								circular_linked_list.delete_front()
								raise AssertionError  # This should not happen
				except IndexError:
								assert True  # This should happen

				try:
								circular_linked_list.delete_tail()
								raise AssertionError  # This should not happen
				except IndexError:
								assert True  # This should happen

				try:
								circular_linked_list.delete_nth(-1      )
								raise AssertionError
				except IndexError:
								assert True

				try:
								circular_linked_list.delete_nth(0      )
								raise AssertionError
				except IndexError:
								assert True

				assert circular_linked_list.is_empty() is True
				for i in range(5      ):
								assert len(SCREAMING_SNAKE_CASE_      ) == i
								circular_linked_list.insert_nth(SCREAMING_SNAKE_CASE_	,       i + 1      )
				assert str(SCREAMING_SNAKE_CASE_      ) == "->".join(str(SCREAMING_SNAKE_CASE_      ) for i in range(1	,       6      )      )

				circular_linked_list.insert_tail(6      )
				assert str(SCREAMING_SNAKE_CASE_      ) == "->".join(str(SCREAMING_SNAKE_CASE_      ) for i in range(1	,       7      )      )
				circular_linked_list.insert_head(0      )
				assert str(SCREAMING_SNAKE_CASE_      ) == "->".join(str(SCREAMING_SNAKE_CASE_      ) for i in range(0	,       7      )      )

				assert circular_linked_list.delete_front() == 0
				assert circular_linked_list.delete_tail() == 6
				assert str(SCREAMING_SNAKE_CASE_      ) == "->".join(str(SCREAMING_SNAKE_CASE_      ) for i in range(1	,       6      )      )
				assert circular_linked_list.delete_nth(2      ) == 3

				circular_linked_list.insert_nth(2	,       3      )
				assert str(SCREAMING_SNAKE_CASE_      ) == "->".join(str(SCREAMING_SNAKE_CASE_      ) for i in range(1	,       6      )      )

				assert circular_linked_list.is_empty() is False


if __name__ == "__main__":
	import doctest

	doctest.testmod()

