


'''simple docstring'''






import itertools
import random
import unittest

import numpy as np

from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor
from transformers.testing_utils import require_torch, slow

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


__A					:  str											=      random.Random()







def 				UpperCamelCase_			(    A__					:   List[Any]							,    A__					:   Optional[int]=1.0							,    A__					:   List[str]=None							,    A__					:   Dict=None					):
  '''simple docstring'''





  if rng is None:
    lowerCAmelCase_			:      Optional[int]			=   global_rng

  lowerCAmelCase_			:      int			=   []
  for batch_idx in range(shape[0]					):
    values.append([]					)
    for _ in range(shape[1]					):
      values[-1].append(rng.random() * scale					)

  return values






class    __snake_case       (   unittest.TestCase):







    """simple docstring"""



    def __init__(   self    :  Optional[int]    ,						lowerCamelCase    :  Union[str, Any]    ,						lowerCamelCase    :  Any=7    ,						lowerCamelCase    :  List[str]=4_00    ,						lowerCamelCase    :  Dict=20_00    ,						lowerCamelCase    :  List[str]=1    ,						lowerCamelCase    :  Union[str, Any]=0.0    ,						lowerCamelCase    :  str=1_60_00    ,						lowerCamelCase    :  List[Any]=True    ,						lowerCamelCase    :  List[str]=True    ,						)   ->  Optional[Any]:
      lowerCAmelCase_			:      List[str]			=   parent
      lowerCAmelCase_			:      Dict			=   batch_size
      lowerCAmelCase_			:      Union[str, Any]			=   min_seq_length
      lowerCAmelCase_			:      Union[str, Any]			=   max_seq_length
      lowerCAmelCase_			:      Union[str, Any]			=   (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
      lowerCAmelCase_			:      List[str]			=   feature_size
      lowerCAmelCase_			:      List[str]			=   padding_value
      lowerCAmelCase_			:      Optional[Any]			=   sampling_rate
      lowerCAmelCase_			:      Optional[int]			=   return_attention_mask
      lowerCAmelCase_			:      List[Any]			=   do_normalize

    def __lowercase   (   self    :  List[Any]		)   ->  List[str]:
      return {
          "feature_size": self.feature_size,
          "padding_value": self.padding_value,
          "sampling_rate": self.sampling_rate,
          "return_attention_mask": self.return_attention_mask,
          "do_normalize": self.do_normalize,
      }





    def __lowercase   (   self    :  Union[str, Any]    ,						lowerCamelCase    :  int=False    ,						lowerCamelCase    :  int=False		)   ->  Dict:
      def _flatten(lowerCamelCase    :  List[str]		):
        return list(itertools.chain(*lowerCamelCase		)		)

      if equal_length:
        lowerCAmelCase_			:      str			=   floats_list((self.batch_size, self.max_seq_length)		)
      else:
        # make sure that inputs increase in size
        lowerCAmelCase_			:      int			=   [
            _flatten(floats_list((x, self.feature_size)		)		)
            for x in range(self.min_seq_length    ,						self.max_seq_length    ,						self.seq_length_diff		)
        ]

      if numpify:
        lowerCAmelCase_			:      Union[str, Any]			=   [np.asarray(lowerCamelCase		) for x in speech_inputs]

      return speech_inputs







class    __snake_case       (   _SCREAMING_SNAKE_CASE	,unittest.TestCase):







    """simple docstring"""



    lowercase    =					WavaVecaFeatureExtractor

    def __lowercase   (   self    :  Union[str, Any]		)   ->  Optional[int]:
      lowerCAmelCase_			:      Union[str, Any]			=   WavaVecaFeatureExtractionTester(self		)

    def __lowercase   (   self    :  Any    ,						lowerCamelCase    :  Dict		)   ->  Optional[Any]:
      self.assertTrue(np.all(np.mean(lowerCamelCase    ,						axis=0		) < 1E-3		)		)
      self.assertTrue(np.all(np.abs(np.var(lowerCamelCase    ,						axis=0		) - 1		) < 1E-3		)		)

    def __lowercase   (   self    :  Union[str, Any]		)   ->  str:
      # Tests that all call wrap to encode_plus and batch_encode_plus
      lowerCAmelCase_			:      List[str]			=   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
      # create three inputs of length 800, 1000, and 1200
      lowerCAmelCase_			:      Optional[Any]			=   [floats_list((1, x)		)[0] for x in range(8_00    ,						14_00    ,						2_00		)]
      lowerCAmelCase_			:      Tuple			=   [np.asarray(lowerCamelCase		) for speech_input in speech_inputs]

      # Test not batched input
      lowerCAmelCase_			:      int			=   feat_extract(speech_inputs[0]    ,						return_tensors="""np"""		).input_values
      lowerCAmelCase_			:      Optional[Any]			=   feat_extract(np_speech_inputs[0]    ,						return_tensors="""np"""		).input_values
      self.assertTrue(np.allclose(lowerCamelCase    ,						lowerCamelCase    ,						atol=1E-3		)		)

      # Test batched
      lowerCAmelCase_			:      Any			=   feat_extract(lowerCamelCase    ,						return_tensors="""np"""		).input_values
      lowerCAmelCase_			:      Tuple			=   feat_extract(lowerCamelCase    ,						return_tensors="""np"""		).input_values
      for enc_seq_a, enc_seq_a in zip(lowerCamelCase    ,						lowerCamelCase		):
        self.assertTrue(np.allclose(lowerCamelCase    ,						lowerCamelCase    ,						atol=1E-3		)		)

      # Test 2-D numpy arrays are batched.
      lowerCAmelCase_			:      Dict			=   [floats_list((1, x)		)[0] for x in (8_00, 8_00, 8_00)]
      lowerCAmelCase_			:      Dict			=   np.asarray(lowerCamelCase		)
      lowerCAmelCase_			:      str			=   feat_extract(lowerCamelCase    ,						return_tensors="""np"""		).input_values
      lowerCAmelCase_			:      List[Any]			=   feat_extract(lowerCamelCase    ,						return_tensors="""np"""		).input_values
      for enc_seq_a, enc_seq_a in zip(lowerCamelCase    ,						lowerCamelCase		):
        self.assertTrue(np.allclose(lowerCamelCase    ,						lowerCamelCase    ,						atol=1E-3		)		)

    def __lowercase   (   self    :  Any		)   ->  List[str]:
      lowerCAmelCase_			:      List[str]			=   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
      lowerCAmelCase_			:      Optional[Any]			=   [floats_list((1, x)		)[0] for x in range(8_00    ,						14_00    ,						2_00		)]

      lowerCAmelCase_			:      List[Any]			=   ["""longest""", """max_length""", """do_not_pad"""]
      lowerCAmelCase_			:      List[str]			=   [None, 16_00, None]
      for max_length, padding in zip(lowerCamelCase    ,						lowerCamelCase		):
        lowerCAmelCase_			:      int			=   feat_extract(lowerCamelCase    ,						padding=lowerCamelCase    ,						max_length=lowerCamelCase    ,						return_tensors="""np"""		)
        lowerCAmelCase_			:      Optional[int]			=   processed.input_values

        self._check_zero_mean_unit_variance(input_values[0][:8_00]		)
        self.assertTrue(input_values[0][8_00:].sum() < 1E-6		)
        self._check_zero_mean_unit_variance(input_values[1][:10_00]		)
        self.assertTrue(input_values[0][10_00:].sum() < 1E-6		)
        self._check_zero_mean_unit_variance(input_values[2][:12_00]		)

    def __lowercase   (   self    :  List[str]		)   ->  List[str]:
      lowerCAmelCase_			:      Optional[Any]			=   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
      lowerCAmelCase_			:      Tuple			=   range(8_00    ,						14_00    ,						2_00		)
      lowerCAmelCase_			:      str			=   [floats_list((1, x)		)[0] for x in lengths]

      lowerCAmelCase_			:      Optional[Any]			=   ["""longest""", """max_length""", """do_not_pad"""]
      lowerCAmelCase_			:      Optional[Any]			=   [None, 16_00, None]

      for max_length, padding in zip(lowerCamelCase    ,						lowerCamelCase		):
        lowerCAmelCase_			:      str			=   feat_extract(lowerCamelCase    ,						max_length=lowerCamelCase    ,						padding=lowerCamelCase		)
        lowerCAmelCase_			:      int			=   processed.input_values

        self._check_zero_mean_unit_variance(input_values[0][:8_00]		)
        self._check_zero_mean_unit_variance(input_values[1][:10_00]		)
        self._check_zero_mean_unit_variance(input_values[2][:12_00]		)

    def __lowercase   (   self    :  List[str]		)   ->  Optional[int]:
      lowerCAmelCase_			:      str			=   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
      lowerCAmelCase_			:      Optional[int]			=   [floats_list((1, x)		)[0] for x in range(8_00    ,						14_00    ,						2_00		)]
      lowerCAmelCase_			:      Optional[Any]			=   feat_extract(
          lowerCamelCase    ,						truncation=lowerCamelCase    ,						max_length=10_00    ,						padding="""max_length"""    ,						return_tensors="""np"""		)
      lowerCAmelCase_			:      Optional[int]			=   processed.input_values

      self._check_zero_mean_unit_variance(input_values[0, :8_00]		)
      self._check_zero_mean_unit_variance(input_values[1]		)
      self._check_zero_mean_unit_variance(input_values[2]		)

    def __lowercase   (   self    :  Tuple		)   ->  Tuple:
      lowerCAmelCase_			:      Tuple			=   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
      lowerCAmelCase_			:      List[str]			=   [floats_list((1, x)		)[0] for x in range(8_00    ,						14_00    ,						2_00		)]
      lowerCAmelCase_			:      str			=   feat_extract(
          lowerCamelCase    ,						truncation=lowerCamelCase    ,						max_length=10_00    ,						padding="""longest"""    ,						return_tensors="""np"""		)
      lowerCAmelCase_			:      Dict			=   processed.input_values

      self._check_zero_mean_unit_variance(input_values[0, :8_00]		)
      self._check_zero_mean_unit_variance(input_values[1, :10_00]		)
      self._check_zero_mean_unit_variance(input_values[2]		)

      # make sure that if max_length < longest -> then pad to max_length
      self.assertTrue(input_values.shape == (3, 10_00)		)

      lowerCAmelCase_			:      List[Any]			=   [floats_list((1, x)		)[0] for x in range(8_00    ,						14_00    ,						2_00		)]
      lowerCAmelCase_			:      Optional[int]			=   feat_extract(
          lowerCamelCase    ,						truncation=lowerCamelCase    ,						max_length=20_00    ,						padding="""longest"""    ,						return_tensors="""np"""		)
      lowerCAmelCase_			:      Dict			=   processed.input_values

      self._check_zero_mean_unit_variance(input_values[0, :8_00]		)
      self._check_zero_mean_unit_variance(input_values[1, :10_00]		)
      self._check_zero_mean_unit_variance(input_values[2]		)

      # make sure that if max_length > longest -> then pad to longest
      self.assertTrue(input_values.shape == (3, 12_00)		)

    @require_torch
    def __lowercase   (   self    :  List[str]		)   ->  str:
      import torch

      lowerCAmelCase_			:      Union[str, Any]			=   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
      lowerCAmelCase_			:      str			=   np.random.rand(1_00		).astype(np.floataa		)
      lowerCAmelCase_			:      Union[str, Any]			=   np_speech_inputs.tolist()

      for inputs in [py_speech_inputs, np_speech_inputs]:
        lowerCAmelCase_			:      List[Any]			=   feature_extractor.pad([{"""input_values""": inputs}]    ,						return_tensors="""np"""		)
        self.assertTrue(np_processed.input_values.dtype == np.floataa		)
        lowerCAmelCase_			:      List[str]			=   feature_extractor.pad([{"""input_values""": inputs}]    ,						return_tensors="""pt"""		)
        self.assertTrue(pt_processed.input_values.dtype == torch.floataa		)





    @slow
    @require_torch
    def __lowercase   (   self    :  Any		)   ->  Any:
      # this test makes sure that models that are using
      # group norm don't have their feature extractor return the
      # attention_mask
      for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST:
        lowerCAmelCase_			:      Union[str, Any]			=   WavaVecaConfig.from_pretrained(lowerCamelCase		)
        lowerCAmelCase_			:      List[str]			=   WavaVecaFeatureExtractor.from_pretrained(lowerCamelCase		)

        # only "layer" feature extraction norm should make use of
        # attention_mask
        self.assertEqual(feat_extract.return_attention_mask    ,						config.feat_extract_norm == """layer"""		)







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







    """simple docstring"""



    def __lowercase   (   self    :  str		)   ->  Any:
      with tempfile.TemporaryDirectory() as tmpdirname:
        # pipeline has Flax weights
        lowerCAmelCase_			:      int			=   FlaxDiffusionPipeline.from_pretrained(
            """hf-internal-testing/tiny-stable-diffusion-pipe"""    ,						safety_checker=lowerCamelCase    ,						cache_dir=lowerCamelCase		)

        lowerCAmelCase_			:      Dict			=   [t[-1] for t in os.walk(os.path.join(lowerCamelCase    ,						os.listdir(lowerCamelCase		)[0]    ,						"""snapshots"""		)		)]
        lowerCAmelCase_			:      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    __snake_case       (   unittest.TestCase):







    """simple docstring"""



    def __lowercase   (   self    :  Any		)   ->  Optional[int]:
      lowerCAmelCase_,							lowerCAmelCase_			:      Union[str, Any]			=   FlaxStableDiffusionPipeline.from_pretrained(
          """hf-internal-testing/tiny-stable-diffusion-pipe"""    ,						safety_checker=lowerCamelCase		)

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

      lowerCAmelCase_			:      Dict			=   jax.device_count()
      lowerCAmelCase_			:      Tuple			=   num_samples * [prompt]
      lowerCAmelCase_			:      Optional[int]			=   pipeline.prepare_inputs(lowerCamelCase		)

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

      lowerCAmelCase_			:      str			=   pipeline(lowerCamelCase    ,						lowerCamelCase    ,						lowerCamelCase    ,						lowerCamelCase    ,						jit=lowerCamelCase		).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_514_745		) < 1E-3
        assert np.abs(np.abs(lowerCamelCase    ,						dtype=np.floataa		).sum() - 49_947.875		) < 5E-1

      lowerCAmelCase_			:      List[Any]			=   pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]		)		)		)
      assert len(lowerCamelCase		) == num_samples

    def __lowercase   (   self    :  Optional[int]		)   ->  List[str]:
      lowerCAmelCase_,							lowerCAmelCase_			:      Tuple			=   FlaxStableDiffusionPipeline.from_pretrained(
          """CompVis/stable-diffusion-v1-4"""    ,						revision="""flax"""    ,						safety_checker=lowerCamelCase		)

      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_			:      List[Any]			=   50

      lowerCAmelCase_			:      str			=   jax.device_count()
      lowerCAmelCase_			:      Optional[Any]			=   num_samples * [prompt]
      lowerCAmelCase_			:      Dict			=   pipeline.prepare_inputs(lowerCamelCase		)

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

      lowerCAmelCase_			:      Optional[int]			=   pipeline(lowerCamelCase    ,						lowerCamelCase    ,						lowerCamelCase    ,						lowerCamelCase    ,						jit=lowerCamelCase		).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_652_401)		) < 1E-3
        assert np.abs((np.abs(lowerCamelCase    ,						dtype=np.floataa		).sum() - 2_383_808.2)		) < 5E-1

    def __lowercase   (   self    :  List[Any]		)   ->  List[Any]:
      lowerCAmelCase_,							lowerCAmelCase_			:      Optional[Any]			=   FlaxStableDiffusionPipeline.from_pretrained(
          """CompVis/stable-diffusion-v1-4"""    ,						revision="""bf16"""    ,						dtype=jnp.bfloataa    ,						safety_checker=lowerCamelCase		)

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

      lowerCAmelCase_			:      Dict			=   jax.device_count()
      lowerCAmelCase_			:      List[Any]			=   num_samples * [prompt]
      lowerCAmelCase_			:      Tuple			=   pipeline.prepare_inputs(lowerCamelCase		)

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

      lowerCAmelCase_			:      Any			=   pipeline(lowerCamelCase    ,						lowerCamelCase    ,						lowerCamelCase    ,						lowerCamelCase    ,						jit=lowerCamelCase		).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_003_906)		) < 1E-3
        assert np.abs((np.abs(lowerCamelCase    ,						dtype=np.floataa		).sum() - 2_373_516.75)		) < 5E-1

    def __lowercase   (   self    :  int		)   ->  Optional[int]:
      lowerCAmelCase_,							lowerCAmelCase_			:      int			=   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_			:      str			=   jax.random.PRNGKey(0		)
      lowerCAmelCase_			:      List[Any]			=   50

      lowerCAmelCase_			:      Union[str, Any]			=   jax.device_count()
      lowerCAmelCase_			:      Optional[Any]			=   num_samples * [prompt]
      lowerCAmelCase_			:      List[Any]			=   pipeline.prepare_inputs(lowerCamelCase		)

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

      lowerCAmelCase_			:      Tuple			=   pipeline(lowerCamelCase    ,						lowerCamelCase    ,						lowerCamelCase    ,						lowerCamelCase    ,						jit=lowerCamelCase		).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_003_906)		) < 1E-3
        assert np.abs((np.abs(lowerCamelCase    ,						dtype=np.floataa		).sum() - 2_373_516.75)		) < 5E-1

    def __lowercase   (   self    :  List[str]		)   ->  Any:
      lowerCAmelCase_			:      List[Any]			=   FlaxDDIMScheduler(
          beta_start=0.00_085    ,						beta_end=0.012    ,						beta_schedule="""scaled_linear"""    ,						set_alpha_to_one=lowerCamelCase    ,						steps_offset=1    ,						)

      lowerCAmelCase_,							lowerCAmelCase_			:      List[str]			=   FlaxStableDiffusionPipeline.from_pretrained(
          """CompVis/stable-diffusion-v1-4"""    ,						revision="""bf16"""    ,						dtype=jnp.bfloataa    ,						scheduler=lowerCamelCase    ,						safety_checker=lowerCamelCase    ,						)
      lowerCAmelCase_			:      Any			=   scheduler.create_state()

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

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

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

      lowerCAmelCase_			:      Tuple			=   pipeline(lowerCamelCase    ,						lowerCamelCase    ,						lowerCamelCase    ,						lowerCamelCase    ,						jit=lowerCamelCase		).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.045_043_945)		) < 1E-3
        assert np.abs((np.abs(lowerCamelCase    ,						dtype=np.floataa		).sum() - 2_347_693.5)		) < 5E-1





    def __lowercase   (   self    :  Any		)   ->  Union[str, Any]:
      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_			:      Any			=   jax.device_count()
      lowerCAmelCase_			:      Optional[Any]			=   num_samples * [prompt]
      lowerCAmelCase_			:      Union[str, Any]			=   jax.random.split(jax.random.PRNGKey(0		)    ,						lowerCamelCase		)

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

      lowerCAmelCase_			:      Optional[int]			=   replicate(lowerCamelCase		)
      lowerCAmelCase_			:      Optional[int]			=   pipeline.prepare_inputs(lowerCamelCase		)
      lowerCAmelCase_			:      Optional[int]			=   shard(lowerCamelCase		)
      lowerCAmelCase_			:      Tuple			=   pipeline(lowerCamelCase    ,						lowerCamelCase    ,						lowerCamelCase    ,						jit=lowerCamelCase		).images
      assert images.shape == (num_samples, 1, 5_12, 5_12, 3)
      lowerCAmelCase_			:      Dict			=   images[2, 0, 2_56, 10:17, 1]

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

      lowerCAmelCase_			:      List[str]			=   replicate(lowerCamelCase		)
      lowerCAmelCase_			:      Dict			=   pipeline.prepare_inputs(lowerCamelCase		)
      lowerCAmelCase_			:      Union[str, Any]			=   shard(lowerCamelCase		)
      lowerCAmelCase_			:      Optional[int]			=   pipeline(lowerCamelCase    ,						lowerCamelCase    ,						lowerCamelCase    ,						jit=lowerCamelCase		).images
      assert images_eff.shape == (num_samples, 1, 5_12, 5_12, 3)
      lowerCAmelCase_			:      List[Any]			=   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



