

"""simple docstring"""






import random
import unittest

import numpy as np

import transformers
from transformers import is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax


if is_flax_available():
 import os

 import jax.numpy as jnp
 from jax import jit

 from transformers import AutoTokenizer, FlaxAutoModelForCausalLM
 from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model

 _lowerCAmelCase						=		"""0.12"""  # assumed parallelism: 8


if is_torch_available():
 import torch

def 		lowerCamelCase__		(					_lowerCamelCase ,   _lowerCamelCase ,   _lowerCamelCase=None   ):

    '''simple docstring'''



    if rng is None:
        _lowerCAmelCase       :   List[Any]  =    random.Random()

    _lowerCAmelCase       :   Dict  =    1
    for dim in shape:
        total_dims *= dim

    _lowerCAmelCase       :   Optional[Any]  =    []
    for _ in range(_lowerCamelCase   ):
        values.append(rng.randint(0 ,   vocab_size - 1   )   )

    _lowerCAmelCase       :   int  =    np.array(_lowerCamelCase ,   dtype=jnp.intaa   ).reshape(_lowerCamelCase   )

    return output

def 		lowerCamelCase__		(					_lowerCamelCase ,   _lowerCamelCase=None   ):

    '''simple docstring'''



    _lowerCAmelCase       :   Tuple  =    ids_tensor(_lowerCamelCase ,   vocab_size=2 ,   rng=_lowerCamelCase   )
    # make sure that at least one token is attended to for each batch
    _lowerCAmelCase       :   str  =    1
    return attn_mask







@require_flax
class 	__UpperCamelCase    :
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		()

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   str  =    self.model_tester.prepare_config_and_inputs_for_common()

      # cut to half length & take max batch_size 3
      _lowerCAmelCase       :   Union[str, Any]  =    2
      _lowerCAmelCase       :   Union[str, Any]  =    inputs['input_ids'].shape[-1] // 2
      _lowerCAmelCase       :   Tuple  =    inputs['input_ids'][:max_batch_size, :sequence_length]

      _lowerCAmelCase       :   int  =    jnp.ones_like(_A      )
      _lowerCAmelCase       :   List[Any]  =    attention_mask[:max_batch_size, :sequence_length]

      # generate max 5 tokens
      _lowerCAmelCase       :   List[Any]  =    input_ids.shape[-1] + 5
      if config.eos_token_id is not None and config.pad_token_id is None:
          # hack to allow generate for models such as GPT2 as is done in `generate()`
          _lowerCAmelCase       :   Union[str, Any]  =    config.eos_token_id
      return config, input_ids, attention_mask, max_length

  @is_pt_flax_cross_test
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Tuple  =    self._get_input_ids_and_config()
      _lowerCAmelCase       :   Dict  =    False
      _lowerCAmelCase       :   Dict  =    max_length
      _lowerCAmelCase       :   Tuple  =    0

      for model_class in self.all_generative_model_classes:
          _lowerCAmelCase       :   Dict  =    model_class(_A      )

          _lowerCAmelCase       :   Any  =    model_class.__name__[4:]  # Skip the "Flax" at the beginning
          _lowerCAmelCase       :   List[str]  =    getattr(_A    ,_A      )
          _lowerCAmelCase       :   Union[str, Any]  =    pt_model_class(_A      ).eval()
          _lowerCAmelCase       :   Tuple  =    load_flax_weights_in_pytorch_model(_A    ,flax_model.params      )

          _lowerCAmelCase       :   Union[str, Any]  =    flax_model.generate(_A      ).sequences
          _lowerCAmelCase       :   str  =    pt_model.generate(torch.tensor(_A    ,dtype=torch.long      )      )

          if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]:
              _lowerCAmelCase       :   int  =    flax_generation_outputs[:, : pt_generation_outputs.shape[-1]]

          self.assertListEqual(pt_generation_outputs.numpy().tolist()    ,flax_generation_outputs.tolist()      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[int]  =    self._get_input_ids_and_config()
      _lowerCAmelCase       :   str  =    False
      _lowerCAmelCase       :   Optional[Any]  =    max_length

      for model_class in self.all_generative_model_classes:
          _lowerCAmelCase       :   Union[str, Any]  =    model_class(_A      )

          _lowerCAmelCase       :   Union[str, Any]  =    model.generate(_A      ).sequences
          self.assertEqual(generation_outputs.shape[-1]    ,_A      )

          _lowerCAmelCase       :   Any  =    jit(model.generate      )
          _lowerCAmelCase       :   Dict  =    jit_generate(_A      ).sequences

          self.assertListEqual(generation_outputs.tolist()    ,jit_generation_outputs.tolist()      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Any  =    self._get_input_ids_and_config()
      _lowerCAmelCase       :   Union[str, Any]  =    True
      _lowerCAmelCase       :   Union[str, Any]  =    max_length

      for model_class in self.all_generative_model_classes:
          _lowerCAmelCase       :   Tuple  =    model_class(_A      )

          _lowerCAmelCase       :   Any  =    model.generate(_A      ).sequences
          self.assertEqual(generation_outputs.shape[-1]    ,_A      )

          _lowerCAmelCase       :   Optional[Any]  =    jit(model.generate      )
          _lowerCAmelCase       :   Tuple  =    jit_generate(_A      ).sequences

          self.assertListEqual(generation_outputs.tolist()    ,jit_generation_outputs.tolist()      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Tuple  =    self._get_input_ids_and_config()
      _lowerCAmelCase       :   str  =    False
      _lowerCAmelCase       :   List[str]  =    max_length
      _lowerCAmelCase       :   int  =    2

      for model_class in self.all_generative_model_classes:
          _lowerCAmelCase       :   List[Any]  =    model_class(_A      )

          _lowerCAmelCase       :   Tuple  =    model.generate(_A      ).sequences
          self.assertEqual(generation_outputs.shape[-1]    ,_A      )

          _lowerCAmelCase       :   List[str]  =    jit(model.generate      )
          _lowerCAmelCase       :   Optional[Any]  =    jit_generate(_A      ).sequences

          self.assertListEqual(generation_outputs.tolist()    ,jit_generation_outputs.tolist()      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Union[str, Any]  =    self._get_input_ids_and_config()
      _lowerCAmelCase       :   int  =    False
      _lowerCAmelCase       :   Dict  =    max_length
      _lowerCAmelCase       :   Optional[Any]  =    2
      _lowerCAmelCase       :   List[str]  =    2

      for model_class in self.all_generative_model_classes:
          _lowerCAmelCase       :   Optional[Any]  =    model_class(_A      )

          _lowerCAmelCase       :   str  =    model.generate(_A      ).sequences
          self.assertEqual(generation_outputs.shape[0]    ,input_ids.shape[0] * config.num_return_sequences      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Any  =    self._get_input_ids_and_config()
      _lowerCAmelCase       :   Optional[int]  =    True
      _lowerCAmelCase       :   int  =    max_length
      _lowerCAmelCase       :   str  =    0.8
      _lowerCAmelCase       :   List[Any]  =    10
      _lowerCAmelCase       :   Any  =    0.3
      _lowerCAmelCase       :   int  =    1
      _lowerCAmelCase       :   int  =    8
      _lowerCAmelCase       :   Tuple  =    9

      for model_class in self.all_generative_model_classes:
          _lowerCAmelCase       :   List[Any]  =    model_class(_A      )

          _lowerCAmelCase       :   Any  =    model.generate(_A      ).sequences
          self.assertEqual(generation_outputs.shape[-1]    ,_A      )

          _lowerCAmelCase       :   Any  =    jit(model.generate      )
          _lowerCAmelCase       :   Optional[int]  =    jit_generate(_A      ).sequences

          self.assertListEqual(generation_outputs.tolist()    ,jit_generation_outputs.tolist()      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[Any]  =    self._get_input_ids_and_config()
      _lowerCAmelCase       :   Dict  =    max_length
      _lowerCAmelCase       :   int  =    1
      _lowerCAmelCase       :   str  =    8
      _lowerCAmelCase       :   Optional[int]  =    9

      for model_class in self.all_generative_model_classes:
          _lowerCAmelCase       :   int  =    model_class(_A      )

          _lowerCAmelCase       :   Union[str, Any]  =    model.generate(_A      ).sequences
          self.assertEqual(generation_outputs.shape[-1]    ,_A      )

          _lowerCAmelCase       :   str  =    jit(model.generate      )
          _lowerCAmelCase       :   Union[str, Any]  =    jit_generate(_A      ).sequences

          self.assertListEqual(generation_outputs.tolist()    ,jit_generation_outputs.tolist()      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   int  =    self._get_input_ids_and_config()
      _lowerCAmelCase       :   Optional[Any]  =    max_length
      _lowerCAmelCase       :   Dict  =    2
      _lowerCAmelCase       :   Optional[Any]  =    1
      _lowerCAmelCase       :   List[Any]  =    8
      _lowerCAmelCase       :   List[str]  =    9

      for model_class in self.all_generative_model_classes:
          _lowerCAmelCase       :   List[str]  =    model_class(_A      )

          _lowerCAmelCase       :   List[Any]  =    model.generate(_A      ).sequences
          self.assertEqual(generation_outputs.shape[-1]    ,_A      )

          _lowerCAmelCase       :   str  =    jit(model.generate      )
          _lowerCAmelCase       :   str  =    jit_generate(_A      ).sequences

          self.assertListEqual(generation_outputs.tolist()    ,jit_generation_outputs.tolist()      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Union[str, Any]  =    self._get_input_ids_and_config()

      # pad attention mask on the left
      _lowerCAmelCase       :   Union[str, Any]  =    attention_mask.at[(0, 0)].set(0      )

      _lowerCAmelCase       :   Optional[Any]  =    False
      _lowerCAmelCase       :   Optional[int]  =    max_length

      for model_class in self.all_generative_model_classes:
          _lowerCAmelCase       :   List[str]  =    model_class(_A      )

          _lowerCAmelCase       :   Optional[int]  =    model.generate(_A    ,attention_mask=_A      ).sequences
          self.assertEqual(generation_outputs.shape[-1]    ,_A      )

          _lowerCAmelCase       :   Optional[int]  =    jit(model.generate      )
          _lowerCAmelCase       :   Optional[Any]  =    jit_generate(_A    ,attention_mask=_A      ).sequences

          self.assertListEqual(generation_outputs.tolist()    ,jit_generation_outputs.tolist()      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[Any]  =    self._get_input_ids_and_config()

      # pad attention mask on the left
      _lowerCAmelCase       :   Dict  =    attention_mask.at[(0, 0)].set(0      )

      _lowerCAmelCase       :   List[Any]  =    True
      _lowerCAmelCase       :   Any  =    max_length

      for model_class in self.all_generative_model_classes:
          _lowerCAmelCase       :   str  =    model_class(_A      )

          _lowerCAmelCase       :   Any  =    model.generate(_A    ,attention_mask=_A      ).sequences
          self.assertEqual(generation_outputs.shape[-1]    ,_A      )

          _lowerCAmelCase       :   Any  =    jit(model.generate      )
          _lowerCAmelCase       :   Dict  =    jit_generate(_A    ,attention_mask=_A      ).sequences

          self.assertListEqual(generation_outputs.tolist()    ,jit_generation_outputs.tolist()      )







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[int]  =    self._get_input_ids_and_config()

      # pad attention mask on the left
      _lowerCAmelCase       :   Optional[int]  =    attention_mask.at[(0, 0)].set(0      )

      _lowerCAmelCase       :   Dict  =    2
      _lowerCAmelCase       :   Any  =    max_length

      for model_class in self.all_generative_model_classes:
          _lowerCAmelCase       :   List[Any]  =    model_class(_A      )

          _lowerCAmelCase       :   Union[str, Any]  =    model.generate(_A    ,attention_mask=_A      ).sequences
          self.assertEqual(generation_outputs.shape[-1]    ,_A      )

          _lowerCAmelCase       :   Any  =    jit(model.generate      )
          _lowerCAmelCase       :   Any  =    jit_generate(_A    ,attention_mask=_A      ).sequences

          self.assertListEqual(generation_outputs.tolist()    ,jit_generation_outputs.tolist()      )







@require_flax
class 	__UpperCamelCase    (    unittest.TestCase						):

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    AutoTokenizer.from_pretrained('hf-internal-testing/tiny-bert'      )
      _lowerCAmelCase       :   List[Any]  =    FlaxAutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-bert-flax-only'      )

      _lowerCAmelCase       :   Any  =    'Hello world'
      _lowerCAmelCase       :   Tuple  =    tokenizer(_A    ,return_tensors='np'      ).input_ids

      # typos are quickly detected (the correct argument is `do_sample`)
      with self.assertRaisesRegex(_A    ,'do_samples'      ):
          model.generate(_A    ,do_samples=_A      )

      # arbitrary arguments that will not be used anywhere are also not accepted
      with self.assertRaisesRegex(_A    ,'foo'      ):
          _lowerCAmelCase       :   List[Any]  =    {'foo': 'bar'}
          model.generate(_A    ,**_A      )







"""simple docstring"""






from math import acos, sin
from typing import List, Tuple, Union

import numpy as np
import torch
from PIL import Image

from ...models import AutoencoderKL, UNetaDConditionModel
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput
from .mel import Mel







class 	__UpperCamelCase    (    a__						):
  _UpperCAmelCase          =		["vqvae"]

  def __init__(		self    ,_A    ,_A    ,_A    ,_A    ,):
      '''simple docstring'''

      super().__init__()
      self.register_modules(unet=_A    ,scheduler=_A    ,mel=_A    ,vqvae=_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      return 50 if isinstance(self.scheduler    ,_A      ) else 1000

  @torch.no_grad()
  def __call__(		self    ,_A = 1    ,_A = None    ,_A = None    ,_A = 0    ,_A = 0    ,_A = None    ,_A = None    ,_A = 0    ,_A = 0    ,_A = None    ,_A = 0    ,_A = None    ,_A = None    ,_A=True    ,):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    steps or self.get_default_steps()
      self.scheduler.set_timesteps(_A      )
      _lowerCAmelCase       :   Optional[Any]  =    step_generator or generator
      # For backwards compatibility
      if type(self.unet.config.sample_size      ) == int:
          _lowerCAmelCase       :   Tuple  =    (self.unet.config.sample_size, self.unet.config.sample_size)
      if noise is None:
          _lowerCAmelCase       :   Optional[Any]  =    randn_tensor(
              (
                  batch_size,
                  self.unet.config.in_channels,
                  self.unet.config.sample_size[0],
                  self.unet.config.sample_size[1],
              )    ,generator=_A    ,device=self.device    ,)
      _lowerCAmelCase       :   Dict  =    noise
      _lowerCAmelCase       :   Optional[Any]  =    None

      if audio_file is not None or raw_audio is not None:
          self.mel.load_audio(_A    ,_A      )
          _lowerCAmelCase       :   Union[str, Any]  =    self.mel.audio_slice_to_image(_A      )
          _lowerCAmelCase       :   int  =    np.frombuffer(input_image.tobytes()    ,dtype='uint8'      ).reshape(
              (input_image.height, input_image.width)      )
          _lowerCAmelCase       :   int  =    (input_image / 255) * 2 - 1
          _lowerCAmelCase       :   str  =    torch.tensor(input_image[np.newaxis, :, :]    ,dtype=torch.float      ).to(self.device      )

          if self.vqvae is not None:
              _lowerCAmelCase       :   List[Any]  =    self.vqvae.encode(torch.unsqueeze(_A    ,0      )      ).latent_dist.sample(
                  generator=_A      )[0]
              _lowerCAmelCase       :   Tuple  =    self.vqvae.config.scaling_factor * input_images

          if start_step > 0:
              _lowerCAmelCase       :   List[Any]  =    self.scheduler.add_noise(_A    ,_A    ,self.scheduler.timesteps[start_step - 1]      )

          _lowerCAmelCase       :   Optional[Any]  =    (
              self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
          )
          _lowerCAmelCase       :   Optional[Any]  =    int(mask_start_secs * pixels_per_second      )
          _lowerCAmelCase       :   Optional[int]  =    int(mask_end_secs * pixels_per_second      )
          _lowerCAmelCase       :   int  =    self.scheduler.add_noise(_A    ,_A    ,torch.tensor(self.scheduler.timesteps[start_step:]      )      )

      for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:]      )      ):
          if isinstance(self.unet    ,_A      ):
              _lowerCAmelCase       :   str  =    self.unet(_A    ,_A    ,_A      )['sample']
          else:
              _lowerCAmelCase       :   Any  =    self.unet(_A    ,_A      )['sample']

          if isinstance(self.scheduler    ,_A      ):
              _lowerCAmelCase       :   Union[str, Any]  =    self.scheduler.step(
                  model_output=_A    ,timestep=_A    ,sample=_A    ,eta=_A    ,generator=_A    ,)['prev_sample']
          else:
              _lowerCAmelCase       :   Any  =    self.scheduler.step(
                  model_output=_A    ,timestep=_A    ,sample=_A    ,generator=_A    ,)['prev_sample']

          if mask is not None:
              if mask_start > 0:
                  _lowerCAmelCase       :   Any  =    mask[:, step, :, :mask_start]
              if mask_end > 0:
                  _lowerCAmelCase       :   Optional[Any]  =    mask[:, step, :, -mask_end:]

      if self.vqvae is not None:
          # 0.18215 was scaling factor used in training to ensure unit variance
          _lowerCAmelCase       :   Union[str, Any]  =    1 / self.vqvae.config.scaling_factor * images
          _lowerCAmelCase       :   Any  =    self.vqvae.decode(_A      )['sample']

      _lowerCAmelCase       :   Any  =    (images / 2 + 0.5).clamp(0    ,1      )
      _lowerCAmelCase       :   Tuple  =    images.cpu().permute(0    ,2    ,3    ,1      ).numpy()
      _lowerCAmelCase       :   Any  =    (images * 255).round().astype('uint8'      )
      _lowerCAmelCase       :   Any  =    list(
          (Image.fromarray(_[:, :, 0]      ) for _ in images)
          if images.shape[3] == 1
          else (Image.fromarray(_A    ,mode='RGB'      ).convert('L'      ) for _ in images)      )

      _lowerCAmelCase       :   Dict  =    [self.mel.image_to_audio(_A      ) for _ in images]
      if not return_dict:
          return images, (self.mel.get_sample_rate(), audios)

      return BaseOutput(**AudioPipelineOutput(np.array(_A      )[:, np.newaxis, :]      )    ,**ImagePipelineOutput(_A      )      )

  @torch.no_grad()
  def __lowerCamelCase		(		self    ,_A    ,_A = 50      ):
      '''simple docstring'''

      assert isinstance(self.scheduler    ,_A      )
      self.scheduler.set_timesteps(_A      )
      _lowerCAmelCase       :   Dict  =    np.array(
          [np.frombuffer(image.tobytes()    ,dtype='uint8'      ).reshape((1, image.height, image.width)      ) for image in images]      )
      _lowerCAmelCase       :   Dict  =    (sample / 255) * 2 - 1
      _lowerCAmelCase       :   List[str]  =    torch.Tensor(_A      ).to(self.device      )

      for t in self.progress_bar(torch.flip(self.scheduler.timesteps    ,(0,)      )      ):
          _lowerCAmelCase       :   Tuple  =    t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
          _lowerCAmelCase       :   Optional[int]  =    self.scheduler.alphas_cumprod[t]
          _lowerCAmelCase       :   Dict  =    (
              self.scheduler.alphas_cumprod[prev_timestep]
              if prev_timestep >= 0
              else self.scheduler.final_alpha_cumprod
          )
          _lowerCAmelCase       :   Union[str, Any]  =    1 - alpha_prod_t
          _lowerCAmelCase       :   Union[str, Any]  =    self.unet(_A    ,_A      )['sample']
          _lowerCAmelCase       :   Optional[int]  =    (1 - alpha_prod_t_prev) ** 0.5 * model_output
          _lowerCAmelCase       :   Any  =    (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5)
          _lowerCAmelCase       :   Dict  =    sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output

      return sample







  @staticmethod
  def __lowerCamelCase		(		_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   int  =    acos(torch.dot(torch.flatten(_A      )    ,torch.flatten(_A      )      ) / torch.norm(_A      ) / torch.norm(_A      )      )
      return sin((1 - alpha) * theta      ) * xa / sin(_A      ) + sin(alpha * theta      ) * xa / sin(_A      )





