





'''simple docstring'''






import gc
import unittest

from parameterized import parameterized

from diffusers import FlaxUNetaDConditionModel
from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import load_hf_numpy, require_flax, slow


if is_flax_available():
      import jax
      import jax.numpy as jnp







@slow
@require_flax
class 		UpperCAmelCase   (				unittest.TestCase):


  """simple docstring"""







  def   UpperCamelCase__      (				self    :					List[Any]							,	UpperCamelCase__    :					Optional[Any]							,	UpperCamelCase__    :					List[Any]  )     ->						Optional[int]:
    return F'''gaussian_noise_s={seed}_shape={'_'.join([str(UpperCamelCase__  ) for s in shape]  )}.npy'''


  def   UpperCamelCase__      (				self    :					int  )     ->						str:
    # clean up the VRAM after each test
    super().tearDown()
    gc.collect()


  def   UpperCamelCase__      (				self    :					str							,	UpperCamelCase__    :					Optional[int]=0							,	UpperCamelCase__    :					Tuple=(4, 4, 64, 64)							,	UpperCamelCase__    :					Tuple=False  )     ->						Union[str, Any]:
    _UpperCamelCase       			=jnp.bfloataa if fpaa else jnp.floataa
    _UpperCamelCase       			=jnp.array(load_hf_numpy(self.get_file_format(UpperCamelCase__							,	UpperCamelCase__  )  )							,	dtype=UpperCamelCase__  )
    return image


  def   UpperCamelCase__      (				self    :					List[Any]							,	UpperCamelCase__    :					List[Any]=False							,	UpperCamelCase__    :					Optional[Any]="CompVis/stable-diffusion-v1-4"  )     ->						Union[str, Any]:
    _UpperCamelCase       			=jnp.bfloataa if fpaa else jnp.floataa
    _UpperCamelCase       			='''bf16''' if fpaa else None

    _UpperCamelCase			,     _UpperCamelCase       			=FlaxUNetaDConditionModel.from_pretrained(
        UpperCamelCase__							,	subfolder='''unet'''							,	dtype=UpperCamelCase__							,	revision=UpperCamelCase__  )
    return model, params


  def   UpperCamelCase__      (				self    :					Optional[int]							,	UpperCamelCase__    :					Dict=0							,	UpperCamelCase__    :					Optional[Any]=(4, 77, 768)							,	UpperCamelCase__    :					str=False  )     ->						Tuple:
    _UpperCamelCase       			=jnp.bfloataa if fpaa else jnp.floataa
    _UpperCamelCase       			=jnp.array(load_hf_numpy(self.get_file_format(UpperCamelCase__							,	UpperCamelCase__  )  )							,	dtype=UpperCamelCase__  )
    return hidden_states


  @parameterized.expand(
      [
          # fmt: off
          [83, 4, [-0.2323, -0.1304, 0.0813, -0.3093, -0.0919, -0.1571, -0.1125, -0.5806]],
          [17, 0.55, [-0.0831, -0.2443, 0.0901, -0.0919, 0.3396, 0.0103, -0.3743, 0.0701]],
          [8, 0.89, [-0.4863, 0.0859, 0.0875, -0.1658, 0.9199, -0.0114, 0.4839, 0.4639]],
          [3, 1000, [-0.5649, 0.2402, -0.5518, 0.1248, 1.1328, -0.2443, -0.0325, -1.0078]],
          # fmt: on
      ]  )
  def   UpperCamelCase__      (				self    :					Union[str, Any]							,	UpperCamelCase__    :					Dict							,	UpperCamelCase__    :					int							,	UpperCamelCase__    :					List[str]  )     ->						Optional[int]:
    _UpperCamelCase			,     _UpperCamelCase       			=self.get_unet_model(model_id='''CompVis/stable-diffusion-v1-4'''							,	fpaa=UpperCamelCase__  )
    _UpperCamelCase       			=self.get_latents(UpperCamelCase__							,	fpaa=UpperCamelCase__  )
    _UpperCamelCase       			=self.get_encoder_hidden_states(UpperCamelCase__							,	fpaa=UpperCamelCase__  )

    _UpperCamelCase       			=model.apply(
        {'''params''': params}							,	UpperCamelCase__							,	jnp.array(UpperCamelCase__							,	dtype=jnp.intaa  )							,	encoder_hidden_states=UpperCamelCase__							,	).sample

    assert sample.shape == latents.shape

    _UpperCamelCase       			=jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten())  )							,	dtype=jnp.floataa  )
    _UpperCamelCase       			=jnp.array(UpperCamelCase__							,	dtype=jnp.floataa  )

    # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, in the same hardware
    assert jnp.allclose(UpperCamelCase__							,	UpperCamelCase__							,	atol=1E-2  )




  @parameterized.expand(
      [
          # fmt: off
          [83, 4, [0.1514, 0.0807, 0.1624, 0.1016, -0.1896, 0.0263, 0.0677, 0.2310]],
          [17, 0.55, [0.1164, -0.0216, 0.0170, 0.1589, -0.3120, 0.1005, -0.0581, -0.1458]],
          [8, 0.89, [-0.1758, -0.0169, 0.1004, -0.1411, 0.1312, 0.1103, -0.1996, 0.2139]],
          [3, 1000, [0.1214, 0.0352, -0.0731, -0.1562, -0.0994, -0.0906, -0.2340, -0.0539]],
          # fmt: on
      ]  )
  def   UpperCamelCase__      (				self    :					Optional[int]							,	UpperCamelCase__    :					Optional[int]							,	UpperCamelCase__    :					int							,	UpperCamelCase__    :					Optional[Any]  )     ->						Union[str, Any]:
    _UpperCamelCase			,     _UpperCamelCase       			=self.get_unet_model(model_id='''stabilityai/stable-diffusion-2'''							,	fpaa=UpperCamelCase__  )
    _UpperCamelCase       			=self.get_latents(UpperCamelCase__							,	shape=(4, 4, 96, 96)							,	fpaa=UpperCamelCase__  )
    _UpperCamelCase       			=self.get_encoder_hidden_states(UpperCamelCase__							,	shape=(4, 77, 1024)							,	fpaa=UpperCamelCase__  )

    _UpperCamelCase       			=model.apply(
        {'''params''': params}							,	UpperCamelCase__							,	jnp.array(UpperCamelCase__							,	dtype=jnp.intaa  )							,	encoder_hidden_states=UpperCamelCase__							,	).sample

    assert sample.shape == latents.shape

    _UpperCamelCase       			=jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten())  )							,	dtype=jnp.floataa  )
    _UpperCamelCase       			=jnp.array(UpperCamelCase__							,	dtype=jnp.floataa  )

    # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, on the same hardware
    assert jnp.allclose(UpperCamelCase__							,	UpperCamelCase__							,	atol=1E-2  )













'''simple docstring'''






from collections.abc import Generator
from math import sin


def 					_a   (__SCREAMING_SNAKE_CASE   ):


  """simple docstring"""

  if len(__SCREAMING_SNAKE_CASE   ) != 32:
    raise ValueError('''Input must be of length 32'''   )

  _UpperCamelCase       			=b''''''
  for i in [3, 2, 1, 0]:
    little_endian += string_aa[8 * i : 8 * i + 8]
  return little_endian


def 					_a   (__SCREAMING_SNAKE_CASE   ):


  """simple docstring"""

  if i < 0:
    raise ValueError('''Input must be non-negative'''   )

  _UpperCamelCase       			=format(__SCREAMING_SNAKE_CASE  ,      '''08x'''   )[-8:]
  _UpperCamelCase       			=b''''''
  for i in [3, 2, 1, 0]:
    little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode('''utf-8'''   )
  return little_endian_hex


def 					_a   (__SCREAMING_SNAKE_CASE   ):


  """simple docstring"""

  _UpperCamelCase       			=b''''''
  for char in message:
    bit_string += format(__SCREAMING_SNAKE_CASE  ,      '''08b'''   ).encode('''utf-8'''   )
  _UpperCamelCase       			=format(len(__SCREAMING_SNAKE_CASE   )  ,      '''064b'''   ).encode('''utf-8'''   )

  # Pad bit_string to a multiple of 512 chars
  bit_string += b"1"
  while len(__SCREAMING_SNAKE_CASE   ) % 512 != 448:
    bit_string += b"0"
  bit_string += to_little_endian(start_len[32:]   ) + to_little_endian(start_len[:32]   )

  return bit_string


def 					_a   (__SCREAMING_SNAKE_CASE   ):


  """simple docstring"""

  if len(__SCREAMING_SNAKE_CASE   ) % 512 != 0:
    raise ValueError('''Input must have length that\'s a multiple of 512'''   )

  for pos in range(0  ,      len(__SCREAMING_SNAKE_CASE   )  ,      512   ):
    _UpperCamelCase       			=bit_string[pos : pos + 512]
    _UpperCamelCase       			=[]
    for i in range(0  ,      512  ,      32   ):
      block_words.append(int(to_little_endian(block[i : i + 32]   )  ,      2   )   )
    yield block_words


def 					_a   (__SCREAMING_SNAKE_CASE   ):


  """simple docstring"""

  if i < 0:
    raise ValueError('''Input must be non-negative'''   )

  _UpperCamelCase       			=format(__SCREAMING_SNAKE_CASE  ,      '''032b'''   )
  _UpperCamelCase       			=''''''
  for c in i_str:
    new_str += "1" if c == "0" else "0"
  return int(__SCREAMING_SNAKE_CASE  ,      2   )


def 					_a   (__SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE   ):


  """simple docstring"""

  return (a + b) % 2**32


def 					_a   (__SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE   ):


  """simple docstring"""

  if i < 0:
    raise ValueError('''Input must be non-negative'''   )
  if shift < 0:
    raise ValueError('''Shift must be non-negative'''   )
  return ((i << shift) ^ (i >> (32 - shift))) % 2**32


def 					_a   (__SCREAMING_SNAKE_CASE   ):


  """simple docstring"""

  _UpperCamelCase       			=preprocess(__SCREAMING_SNAKE_CASE   )

  _UpperCamelCase       			=[int(2**32 * abs(sin(i + 1   )   )   ) for i in range(64   )]

  # Starting states
  _UpperCamelCase       			=0X6745_2301
  _UpperCamelCase       			=0Xefcd_ab89
  _UpperCamelCase       			=0X98ba_dcfe
  _UpperCamelCase       			=0X1032_5476

  _UpperCamelCase       			=[
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
  ]

  # Process bit string in chunks, each with 16 32-char words
  for block_words in get_block_words(__SCREAMING_SNAKE_CASE   ):
    _UpperCamelCase       			=aa
    _UpperCamelCase       			=ba
    _UpperCamelCase       			=ca
    _UpperCamelCase       			=da

    # Hash current chunk
    for i in range(64   ):
      if i <= 15:
        # f = (b & c) | (not_32(b) & d)     # Alternate definition for f
        _UpperCamelCase       			=d ^ (b & (c ^ d))
        _UpperCamelCase       			=i
      elif i <= 31:
        # f = (d & b) | (not_32(d) & c)     # Alternate definition for f
        _UpperCamelCase       			=c ^ (d & (b ^ c))
        _UpperCamelCase       			=(5 * i + 1) % 16
      elif i <= 47:
        _UpperCamelCase       			=b ^ c ^ d
        _UpperCamelCase       			=(3 * i + 5) % 16
      else:
        _UpperCamelCase       			=c ^ (b | not_aa(__SCREAMING_SNAKE_CASE   ))
        _UpperCamelCase       			=(7 * i) % 16
      _UpperCamelCase       			=(f + a + added_consts[i] + block_words[g]) % 2**32
      _UpperCamelCase       			=d
      _UpperCamelCase       			=c
      _UpperCamelCase       			=b
      _UpperCamelCase       			=sum_aa(__SCREAMING_SNAKE_CASE  ,      left_rotate_aa(__SCREAMING_SNAKE_CASE  ,      shift_amounts[i]   )   )

    # Add hashed chunk to running total
    _UpperCamelCase       			=sum_aa(__SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE   )
    _UpperCamelCase       			=sum_aa(__SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE   )
    _UpperCamelCase       			=sum_aa(__SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE   )
    _UpperCamelCase       			=sum_aa(__SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE   )

  _UpperCamelCase       			=reformat_hex(__SCREAMING_SNAKE_CASE   ) + reformat_hex(__SCREAMING_SNAKE_CASE   ) + reformat_hex(__SCREAMING_SNAKE_CASE   ) + reformat_hex(__SCREAMING_SNAKE_CASE   )
  return digest


if __name__ == "__main__":
      import doctest

      doctest.testmod()






