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






     def        SCREAMING_SNAKE_CASE__       (			self		:		Tuple   ):





         """simple docstring"""



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

             __lowerCamelCase          =  [t[-1] for t in os.walk(os.path.join(a  ,    os.listdir(a   )[0]  ,    '''snapshots'''   )   )]
             __lowerCamelCase          =  [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        SCREAMING_SNAKE_CASE__       (			self		:		str   ):





         """simple docstring"""



         __lowerCamelCase     ,  __lowerCamelCase          =  FlaxStableDiffusionPipeline.from_pretrained(
             '''hf-internal-testing/tiny-stable-diffusion-pipe'''  ,    safety_checker=a   )

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

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

         __lowerCamelCase          =  jax.device_count()
         __lowerCamelCase          =  num_samples * [prompt]
         __lowerCamelCase          =  pipeline.prepare_inputs(a   )

         # shard inputs and rng
         __lowerCamelCase          =  replicate(a   )
         __lowerCamelCase          =  jax.random.split(a  ,    a   )
         __lowerCamelCase          =  shard(a   )

         __lowerCamelCase          =  pipeline(a  ,    a  ,    a  ,    a  ,    jit=a   ).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(a  ,    dtype=np.floataa   ).sum() - 4_99_47.8_75   ) < 5e-1

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






     def        SCREAMING_SNAKE_CASE__       (			self		:		str   ):





         """simple docstring"""



         __lowerCamelCase     ,  __lowerCamelCase          =  FlaxStableDiffusionPipeline.from_pretrained(
             '''CompVis/stable-diffusion-v1-4'''  ,    revision='''flax'''  ,    safety_checker=a   )

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

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

         __lowerCamelCase          =  jax.device_count()
         __lowerCamelCase          =  num_samples * [prompt]
         __lowerCamelCase          =  pipeline.prepare_inputs(a   )

         # shard inputs and rng
         __lowerCamelCase          =  replicate(a   )
         __lowerCamelCase          =  jax.random.split(a  ,    a   )
         __lowerCamelCase          =  shard(a   )

         __lowerCamelCase          =  pipeline(a  ,    a  ,    a  ,    a  ,    jit=a   ).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.05_65_24_01)   ) < 1e-3
             assert np.abs((np.abs(a  ,    dtype=np.floataa   ).sum() - 2_38_38_08.2)   ) < 5e-1






     def        SCREAMING_SNAKE_CASE__       (			self		:		int   ):





         """simple docstring"""



         __lowerCamelCase     ,  __lowerCamelCase          =  FlaxStableDiffusionPipeline.from_pretrained(
             '''CompVis/stable-diffusion-v1-4'''  ,    revision='''bf16'''  ,    dtype=jnp.bfloataa  ,    safety_checker=a   )

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

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

         __lowerCamelCase          =  jax.device_count()
         __lowerCamelCase          =  num_samples * [prompt]
         __lowerCamelCase          =  pipeline.prepare_inputs(a   )

         # shard inputs and rng
         __lowerCamelCase          =  replicate(a   )
         __lowerCamelCase          =  jax.random.split(a  ,    a   )
         __lowerCamelCase          =  shard(a   )

         __lowerCamelCase          =  pipeline(a  ,    a  ,    a  ,    a  ,    jit=a   ).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.04_00_39_06)   ) < 1e-3
             assert np.abs((np.abs(a  ,    dtype=np.floataa   ).sum() - 2_37_35_16.75)   ) < 5e-1






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[str]   ):





         """simple docstring"""



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

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

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

         __lowerCamelCase          =  jax.device_count()
         __lowerCamelCase          =  num_samples * [prompt]
         __lowerCamelCase          =  pipeline.prepare_inputs(a   )

         # shard inputs and rng
         __lowerCamelCase          =  replicate(a   )
         __lowerCamelCase          =  jax.random.split(a  ,    a   )
         __lowerCamelCase          =  shard(a   )

         __lowerCamelCase          =  pipeline(a  ,    a  ,    a  ,    a  ,    jit=a   ).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.04_00_39_06)   ) < 1e-3
             assert np.abs((np.abs(a  ,    dtype=np.floataa   ).sum() - 2_37_35_16.75)   ) < 5e-1






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[Any]   ):





         """simple docstring"""



         __lowerCamelCase          =  FlaxDDIMScheduler(
             beta_start=0.0_00_85  ,    beta_end=0.0_12  ,    beta_schedule='''scaled_linear'''  ,    set_alpha_to_one=a  ,    steps_offset=1  ,    )

         __lowerCamelCase     ,  __lowerCamelCase          =  FlaxStableDiffusionPipeline.from_pretrained(
             '''CompVis/stable-diffusion-v1-4'''  ,    revision='''bf16'''  ,    dtype=jnp.bfloataa  ,    scheduler=a  ,    safety_checker=a  ,    )
         __lowerCamelCase          =  scheduler.create_state()

         __lowerCamelCase          =  scheduler_state

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

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

         __lowerCamelCase          =  jax.device_count()
         __lowerCamelCase          =  num_samples * [prompt]
         __lowerCamelCase          =  pipeline.prepare_inputs(a   )

         # shard inputs and rng
         __lowerCamelCase          =  replicate(a   )
         __lowerCamelCase          =  jax.random.split(a  ,    a   )
         __lowerCamelCase          =  shard(a   )

         __lowerCamelCase          =  pipeline(a  ,    a  ,    a  ,    a  ,    jit=a   ).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_45_04_39_45)   ) < 1e-3
             assert np.abs((np.abs(a  ,    dtype=np.floataa   ).sum() - 2_34_76_93.5)   ) < 5e-1






     def        SCREAMING_SNAKE_CASE__       (			self		:		Union[str, Any]   ):





         """simple docstring"""



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

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

         __lowerCamelCase     ,  __lowerCamelCase          =  FlaxStableDiffusionPipeline.from_pretrained(
             '''CompVis/stable-diffusion-v1-4'''  ,    revision='''bf16'''  ,    dtype=jnp.bfloataa  ,    safety_checker=a  ,    )

         __lowerCamelCase          =  replicate(a   )
         __lowerCamelCase          =  pipeline.prepare_inputs(a   )
         __lowerCamelCase          =  shard(a   )
         __lowerCamelCase          =  pipeline(a  ,    a  ,    a  ,    jit=a   ).images
         assert images.shape == (num_samples, 1, 5_12, 5_12, 3)
         __lowerCamelCase          =  images[2, 0, 2_56, 10:17, 1]

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

         __lowerCamelCase          =  replicate(a   )
         __lowerCamelCase          =  pipeline.prepare_inputs(a   )
         __lowerCamelCase          =  shard(a   )
         __lowerCamelCase          =  pipeline(a  ,    a  ,    a  ,    jit=a   ).images
         assert images_eff.shape == (num_samples, 1, 5_12, 5_12, 3)
         __lowerCamelCase          =  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'''




import time
import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, torch_device

from ..test_modeling_common import ids_tensor


if is_torch_available():
  import torch

  from transformers.generation import (
      MaxLengthCriteria,
      MaxNewTokensCriteria,
      MaxTimeCriteria,
      StoppingCriteriaList,
      validate_stopping_criteria,
  )




@require_torch
class    a__				(       unittest.TestCase			):






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[int]  ,    a		:		int   ):





         """simple docstring"""



         __lowerCamelCase          =  3
         __lowerCamelCase          =  2_50

         __lowerCamelCase          =  ids_tensor((batch_size, length)  ,    a   )
         __lowerCamelCase          =  torch.ones((batch_size, length)  ,    device=a  ,    dtype=torch.float   ) / length
         return input_ids, scores






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[Any]   ):





         """simple docstring"""



         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(5   )

         __lowerCamelCase          =  StoppingCriteriaList(
             [
                 MaxLengthCriteria(max_length=10   ),
                 MaxTimeCriteria(max_time=0.1   ),
             ]   )

         self.assertFalse(criteria(a  ,    a   )   )

         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(9   )
         self.assertFalse(criteria(a  ,    a   )   )

         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(10   )
         self.assertTrue(criteria(a  ,    a   )   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		Union[str, Any]   ):





         """simple docstring"""



         __lowerCamelCase          =  MaxLengthCriteria(max_length=10   )

         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(5   )
         self.assertFalse(criteria(a  ,    a   )   )

         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(9   )
         self.assertFalse(criteria(a  ,    a   )   )

         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(10   )
         self.assertTrue(criteria(a  ,    a   )   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[Any]   ):





         """simple docstring"""



         __lowerCamelCase          =  MaxNewTokensCriteria(start_length=5  ,    max_new_tokens=5   )

         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(5   )
         self.assertFalse(criteria(a  ,    a   )   )

         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(9   )
         self.assertFalse(criteria(a  ,    a   )   )

         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(10   )
         self.assertTrue(criteria(a  ,    a   )   )

         __lowerCamelCase          =  StoppingCriteriaList([criteria]   )
         self.assertEqual(criteria_list.max_length  ,    10   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		int   ):





         """simple docstring"""



         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(5   )

         __lowerCamelCase          =  MaxTimeCriteria(max_time=0.1   )
         self.assertFalse(criteria(a  ,    a   )   )

         __lowerCamelCase          =  MaxTimeCriteria(max_time=0.1  ,    initial_timestamp=time.time() - 0.2   )
         self.assertTrue(criteria(a  ,    a   )   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[Any]   ):





         """simple docstring"""



         validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10   )]   )  ,    10   )

         with self.assertWarns(a   ):
             validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10   )]   )  ,    11   )

         __lowerCamelCase          =  validate_stopping_criteria(StoppingCriteriaList()  ,    11   )

         self.assertEqual(len(a   )  ,    1   )
