




'''simple docstring'''







import unittest

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

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers import (
       MPNetForMaskedLM,
       MPNetForMultipleChoice,
       MPNetForQuestionAnswering,
       MPNetForSequenceClassification,
       MPNetForTokenClassification,
       MPNetModel,
   )


class 			_a  :
       def __init__(	self						:	Dict   ,				lowercase						:	Tuple   ,				lowercase						:	Dict=13   ,				lowercase						:	Tuple=7   ,				lowercase						:	Optional[Any]=True   ,				lowercase						:	Dict=True   ,				lowercase						:	Tuple=False   ,				lowercase						:	Any=True   ,				lowercase						:	str=99   ,				lowercase						:	Any=64   ,				lowercase						:	Union[str, Any]=5   ,				lowercase						:	Optional[Any]=4   ,				lowercase						:	str=64   ,				lowercase						:	Any="gelu"   ,				lowercase						:	Union[str, Any]=0.1   ,				lowercase						:	Tuple=0.1   ,				lowercase						:	int=512   ,				lowercase						:	List[Any]=16   ,				lowercase						:	int=2   ,				lowercase						:	Optional[Any]=0.02   ,				lowercase						:	int=3   ,				lowercase						:	str=4   ,				lowercase						:	Tuple=None   ,				):



           '''simple docstring'''

           UpperCAmelCase			       =		parent
           UpperCAmelCase			       =		batch_size
           UpperCAmelCase			       =		seq_length
           UpperCAmelCase			       =		is_training
           UpperCAmelCase			       =		use_input_mask
           UpperCAmelCase			       =		use_token_type_ids
           UpperCAmelCase			       =		use_labels
           UpperCAmelCase			       =		vocab_size
           UpperCAmelCase			       =		hidden_size
           UpperCAmelCase			       =		num_hidden_layers
           UpperCAmelCase			       =		num_attention_heads
           UpperCAmelCase			       =		intermediate_size
           UpperCAmelCase			       =		hidden_act
           UpperCAmelCase			       =		hidden_dropout_prob
           UpperCAmelCase			       =		attention_probs_dropout_prob
           UpperCAmelCase			       =		max_position_embeddings
           UpperCAmelCase			       =		type_vocab_size
           UpperCAmelCase			       =		type_sequence_label_size
           UpperCAmelCase			       =		initializer_range
           UpperCAmelCase			       =		num_labels
           UpperCAmelCase			       =		num_choices
           UpperCAmelCase			       =		scope
       def     A      (	self						:	Optional[Any]				):



           '''simple docstring'''

           return MPNetConfig.from_pretrained('''microsoft/mpnet-base'''				)
       def     A      (	self						:	Union[str, Any]				):



           '''simple docstring'''

           UpperCAmelCase			       =		ids_tensor([self.batch_size, self.seq_length]   ,				self.vocab_size				)

           UpperCAmelCase			       =		None
           if self.use_input_mask:
               UpperCAmelCase			       =		random_attention_mask([self.batch_size, self.seq_length]				)

           UpperCAmelCase			       =		None
           UpperCAmelCase			       =		None
           UpperCAmelCase			       =		None
           if self.use_labels:
               UpperCAmelCase			       =		ids_tensor([self.batch_size]   ,				self.type_sequence_label_size				)
               UpperCAmelCase			       =		ids_tensor([self.batch_size, self.seq_length]   ,				self.num_labels				)
               UpperCAmelCase			       =		ids_tensor([self.batch_size]   ,				self.num_choices				)

           UpperCAmelCase			       =		self.get_config()
           return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
       def     A      (	self						:	Optional[Any]				):



           '''simple docstring'''

           return MPNetConfig(
               vocab_size=self.vocab_size   ,				hidden_size=self.hidden_size   ,				num_hidden_layers=self.num_hidden_layers   ,				num_attention_heads=self.num_attention_heads   ,				intermediate_size=self.intermediate_size   ,				hidden_act=self.hidden_act   ,				hidden_dropout_prob=self.hidden_dropout_prob   ,				attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,				max_position_embeddings=self.max_position_embeddings   ,				initializer_range=self.initializer_range   ,				)
       def     A      (	self						:	str   ,				lowercase						:	Optional[Any]   ,				lowercase						:	Union[str, Any]   ,				lowercase						:	Any   ,				lowercase						:	Union[str, Any]   ,				lowercase						:	List[str]   ,				lowercase						:	str				):



           '''simple docstring'''

           UpperCAmelCase			       =		MPNetModel(config=lowercase				)
           model.to(lowercase				)
           model.eval()
           UpperCAmelCase			       =		model(lowercase   ,				lowercase				)
           UpperCAmelCase			       =		model(lowercase				)
           self.parent.assertEqual(result.last_hidden_state.shape   ,				(self.batch_size, self.seq_length, self.hidden_size)				)
           self.parent.assertEqual(result.pooler_output.shape   ,				(self.batch_size, self.hidden_size)				)
       def     A      (	self						:	str   ,				lowercase						:	Tuple   ,				lowercase						:	Optional[int]   ,				lowercase						:	Optional[int]   ,				lowercase						:	Tuple   ,				lowercase						:	Any   ,				lowercase						:	Optional[int]				):



           '''simple docstring'''

           UpperCAmelCase			       =		MPNetForQuestionAnswering(config=lowercase				)
           model.to(lowercase				)
           model.eval()
           UpperCAmelCase			       =		model(
               lowercase   ,				attention_mask=lowercase   ,				start_positions=lowercase   ,				end_positions=lowercase   ,				)
           self.parent.assertEqual(result.start_logits.shape   ,				(self.batch_size, self.seq_length)				)
           self.parent.assertEqual(result.end_logits.shape   ,				(self.batch_size, self.seq_length)				)
       def     A      (	self						:	Optional[Any]   ,				lowercase						:	int   ,				lowercase						:	Optional[Any]   ,				lowercase						:	Union[str, Any]   ,				lowercase						:	Any   ,				lowercase						:	str   ,				lowercase						:	Union[str, Any]				):



           '''simple docstring'''

           UpperCAmelCase			       =		self.num_labels
           UpperCAmelCase			       =		MPNetForSequenceClassification(lowercase				)
           model.to(lowercase				)
           model.eval()
           UpperCAmelCase			       =		model(lowercase   ,				attention_mask=lowercase   ,				labels=lowercase				)
           self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.num_labels)				)
       def     A      (	self						:	Tuple   ,				lowercase						:	Any   ,				lowercase						:	Union[str, Any]   ,				lowercase						:	Optional[int]   ,				lowercase						:	Tuple   ,				lowercase						:	str   ,				lowercase						:	Dict				):



           '''simple docstring'''

           UpperCAmelCase			       =		self.num_choices
           UpperCAmelCase			       =		MPNetForMultipleChoice(config=lowercase				)
           model.to(lowercase				)
           model.eval()
           UpperCAmelCase			       =		input_ids.unsqueeze(1				).expand(-1   ,				self.num_choices   ,				-1				).contiguous()
           UpperCAmelCase			       =		input_mask.unsqueeze(1				).expand(-1   ,				self.num_choices   ,				-1				).contiguous()
           UpperCAmelCase			       =		model(
               lowercase   ,				attention_mask=lowercase   ,				labels=lowercase   ,				)
           self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.num_choices)				)
       def     A      (	self						:	Dict   ,				lowercase						:	str   ,				lowercase						:	int   ,				lowercase						:	List[str]   ,				lowercase						:	Optional[Any]   ,				lowercase						:	Optional[int]   ,				lowercase						:	List[str]				):



           '''simple docstring'''

           UpperCAmelCase			       =		self.num_labels
           UpperCAmelCase			       =		MPNetForTokenClassification(config=lowercase				)
           model.to(lowercase				)
           model.eval()
           UpperCAmelCase			       =		model(lowercase   ,				attention_mask=lowercase   ,				labels=lowercase				)
           self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.seq_length, self.num_labels)				)







       def     A      (	self						:	str				):



           '''simple docstring'''

           UpperCAmelCase			       =		self.prepare_config_and_inputs()
           ((UpperCAmelCase)       ,     (UpperCAmelCase)       ,     (UpperCAmelCase)       ,     (UpperCAmelCase)       ,     (UpperCAmelCase)       ,     (UpperCAmelCase))			       =		config_and_inputs
           UpperCAmelCase			       =		{'''input_ids''': input_ids, '''attention_mask''': input_mask}
           return config, inputs_dict






@require_torch
class 			_a  (	__a							,							__a							,							unittest.TestCase ):
       __a				:     Union[str, Any]   				=					(
           (
               MPNetForMaskedLM,
               MPNetForMultipleChoice,
               MPNetForQuestionAnswering,
               MPNetForSequenceClassification,
               MPNetForTokenClassification,
               MPNetModel,
           )
           if is_torch_available()
           else ()
       )
       __a				:     Any   				=					(
           {
               """feature-extraction""": MPNetModel,
               """fill-mask""": MPNetForMaskedLM,
               """question-answering""": MPNetForQuestionAnswering,
               """text-classification""": MPNetForSequenceClassification,
               """token-classification""": MPNetForTokenClassification,
               """zero-shot""": MPNetForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )
       __a				:     Optional[Any]   				=					False
       __a				:     Optional[int]   				=					True
       def     A      (	self						:	str				):



           '''simple docstring'''

           UpperCAmelCase			       =		MPNetModelTester(self				)
           UpperCAmelCase			       =		ConfigTester(self   ,				config_class=lowercase   ,				hidden_size=37				)
       def     A      (	self						:	Any				):



           '''simple docstring'''

           self.config_tester.run_common_tests()
       def     A      (	self						:	Optional[Any]				):



           '''simple docstring'''

           UpperCAmelCase			       =		self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_mpnet_model(*lowercase				)
       def     A      (	self						:	Any				):



           '''simple docstring'''

           UpperCAmelCase			       =		self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_mpnet_for_sequence_classification(*lowercase				)
       def     A      (	self						:	Tuple				):



           '''simple docstring'''

           UpperCAmelCase			       =		self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_mpnet_for_multiple_choice(*lowercase				)
       def     A      (	self						:	Any				):



           '''simple docstring'''

           UpperCAmelCase			       =		self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_mpnet_for_token_classification(*lowercase				)







       def     A      (	self						:	str				):



           '''simple docstring'''

           UpperCAmelCase			       =		self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_mpnet_for_question_answering(*lowercase				)






@require_torch
class 			_a  (	unittest.TestCase ):
       @slow
       def     A      (	self						:	int				):



           '''simple docstring'''

           UpperCAmelCase			       =		MPNetModel.from_pretrained('''microsoft/mpnet-base'''				)
           UpperCAmelCase			       =		torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]]				)
           UpperCAmelCase			       =		model(lowercase				)[0]
           UpperCAmelCase			       =		torch.Size((1, 11, 768)				)
           self.assertEqual(output.shape   ,				lowercase				)
           UpperCAmelCase			       =		torch.tensor(
               [[[-0.0550, 0.1943, -0.0740], [-0.0562, 0.2211, -0.0579], [-0.0437, 0.3337, -0.0641]]]				)
           # compare the actual values for a slice.
           self.assertTrue(torch.allclose(output[:, :3, :3]   ,				lowercase   ,				atol=1E-4				)				)










'''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 			_a  (	__a ):
       __a				:     str   				=					["""vqvae"""]
       def __init__(	self						:	str   ,				lowercase						:	AutoencoderKL   ,				lowercase						:	UNetaDConditionModel   ,				lowercase						:	Mel   ,				lowercase						:	Union[DDIMScheduler, DDPMScheduler]   ,				):



           '''simple docstring'''

           super().__init__()
           self.register_modules(unet=lowercase   ,				scheduler=lowercase   ,				mel=lowercase   ,				vqvae=lowercase				)
       def     A      (	self						:	Optional[Any]				):



           '''simple docstring'''

           return 50 if isinstance(self.scheduler   ,				lowercase				) else 1_000
       @torch.no_grad()
       def __call__(	self						:	Optional[Any]   ,				lowercase						:	int = 1   ,				lowercase						:	str = None   ,				lowercase						:	np.ndarray = None   ,				lowercase						:	int = 0   ,				lowercase						:	int = 0   ,				lowercase						:	int = None   ,				lowercase						:	torch.Generator = None   ,				lowercase						:	float = 0   ,				lowercase						:	float = 0   ,				lowercase						:	torch.Generator = None   ,				lowercase						:	float = 0   ,				lowercase						:	torch.Tensor = None   ,				lowercase						:	torch.Tensor = None   ,				lowercase						:	Tuple=True   ,				):



           '''simple docstring'''

           UpperCAmelCase			       =		steps or self.get_default_steps()
           self.scheduler.set_timesteps(lowercase				)
           UpperCAmelCase			       =		step_generator or generator
           # For backwards compatibility
           if type(self.unet.config.sample_size				) == int:
               UpperCAmelCase			       =		(self.unet.config.sample_size, self.unet.config.sample_size)
           if noise is None:
               UpperCAmelCase			       =		randn_tensor(
                   (
                       batch_size,
                       self.unet.config.in_channels,
                       self.unet.config.sample_size[0],
                       self.unet.config.sample_size[1],
                   )   ,				generator=lowercase   ,				device=self.device   ,				)
           UpperCAmelCase			       =		noise
           UpperCAmelCase			       =		None

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

               if self.vqvae is not None:
                   UpperCAmelCase			       =		self.vqvae.encode(torch.unsqueeze(lowercase   ,				0				)				).latent_dist.sample(
                       generator=lowercase				)[0]
                   UpperCAmelCase			       =		self.vqvae.config.scaling_factor * input_images

               if start_step > 0:
                   UpperCAmelCase			       =		self.scheduler.add_noise(lowercase   ,				lowercase   ,				self.scheduler.timesteps[start_step - 1]				)

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

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

               if isinstance(self.scheduler   ,				lowercase				):
                   UpperCAmelCase			       =		self.scheduler.step(
                       model_output=lowercase   ,				timestep=lowercase   ,				sample=lowercase   ,				eta=lowercase   ,				generator=lowercase   ,				)['''prev_sample''']
               else:
                   UpperCAmelCase			       =		self.scheduler.step(
                       model_output=lowercase   ,				timestep=lowercase   ,				sample=lowercase   ,				generator=lowercase   ,				)['''prev_sample''']

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

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

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

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

           return BaseOutput(**AudioPipelineOutput(np.array(lowercase				)[:, np.newaxis, :]				)   ,				**ImagePipelineOutput(lowercase				)				)
       @torch.no_grad()
       def     A      (	self						:	Dict   ,				lowercase						:	List[Image.Image]   ,				lowercase						:	int = 50				):



           '''simple docstring'''

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

           for t in self.progress_bar(torch.flip(self.scheduler.timesteps   ,				(0,)				)				):
               UpperCAmelCase			       =		t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
               UpperCAmelCase			       =		self.scheduler.alphas_cumprod[t]
               UpperCAmelCase			       =		(
                   self.scheduler.alphas_cumprod[prev_timestep]
                   if prev_timestep >= 0
                   else self.scheduler.final_alpha_cumprod
               )
               UpperCAmelCase			       =		1 - alpha_prod_t
               UpperCAmelCase			       =		self.unet(lowercase   ,				lowercase				)['''sample''']
               UpperCAmelCase			       =		(1 - alpha_prod_t_prev) ** 0.5 * model_output
               UpperCAmelCase			       =		(sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5)
               UpperCAmelCase			       =		sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output

           return sample







       @staticmethod
       def     A      (	lowercase						:	torch.Tensor   ,				lowercase						:	torch.Tensor   ,				lowercase						:	float				):



           '''simple docstring'''

           UpperCAmelCase			       =		acos(torch.dot(torch.flatten(lowercase				)   ,				torch.flatten(lowercase				)				) / torch.norm(lowercase				) / torch.norm(lowercase				)				)
           return sin((1 - alpha) * theta				) * xa / sin(lowercase				) + sin(alpha * theta				) * xa / sin(lowercase				)




