
"""simple docstring"""





import gc
import unittest

import numpy as np
import torch

from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

from ..pipeline_params import UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS, UNCONDITIONAL_AUDIO_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()
class 						SCREAMING_SNAKE_CASE_ (						__a     ,				unittest.TestCase ):




		"""simple docstring"""





		__lowercase							:  List[Any]						   =		DanceDiffusionPipeline
		__lowercase							:  Dict						   =		UNCONDITIONAL_AUDIO_GENERATION_PARAMS
		__lowercase							:  Optional[int]						   =		PipelineTesterMixin.required_optional_params - {
		    '''callback''',
		    '''latents''',
		    '''callback_steps''',
		    '''output_type''',
		    '''num_images_per_prompt''',
		}
		__lowercase							:  str						   =		UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS
		__lowercase							:  List[Any]						   =		False
		__lowercase							:  str						   =		False




		def 	snake_case_     (     self):
				torch.manual_seed(0)
				__SCREAMING_SNAKE_CASE            = UNetaDModel(
				    block_out_channels=(3_2, 3_2, 6_4)							,  extra_in_channels=1_6							,  sample_size=5_1_2							,  sample_rate=1_6_0_0_0							,  in_channels=2							,  out_channels=2							,  flip_sin_to_cos=lowerCAmelCase__							,  use_timestep_embedding=lowerCAmelCase__							,  time_embedding_type="""fourier"""							,  mid_block_type="""UNetMidBlock1D"""							,  down_block_types=("""DownBlock1DNoSkip""", """DownBlock1D""", """AttnDownBlock1D""")							,  up_block_types=("""AttnUpBlock1D""", """UpBlock1D""", """UpBlock1DNoSkip""")							,  )
				__SCREAMING_SNAKE_CASE            = IPNDMScheduler()

				__SCREAMING_SNAKE_CASE            = {
				    """unet""": unet,
				    """scheduler""": scheduler,
				}
				return components




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__=0):
				if str(lowerCAmelCase__).startswith("""mps"""):
						__SCREAMING_SNAKE_CASE            = torch.manual_seed(lowerCAmelCase__)
				else:
						__SCREAMING_SNAKE_CASE            = torch.Generator(device=lowerCAmelCase__).manual_seed(lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = {
				    """batch_size""": 1,
				    """generator""": generator,
				    """num_inference_steps""": 4,
				}
				return inputs




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = """cpu"""  # ensure determinism for the device-dependent torch.Generator
				__SCREAMING_SNAKE_CASE            = self.get_dummy_components()
				__SCREAMING_SNAKE_CASE            = DanceDiffusionPipeline(**lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = pipe.to(lowerCAmelCase__)
				pipe.set_progress_bar_config(disable=lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = self.get_dummy_inputs(lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = pipe(**lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = output.audios

				__SCREAMING_SNAKE_CASE            = audio[0, -3:, -3:]

				assert audio.shape == (1, 2, components["unet"].sample_size)
				__SCREAMING_SNAKE_CASE            = np.array([-0.72_65, 1.00_00, -0.83_88, 0.11_75, 0.94_98, -1.00_00])
				assert np.abs(audio_slice.flatten() - expected_slice).max() < 1E-2




		@skip_mps
		def 	snake_case_     (     self):
				return super().test_save_load_local()




		@skip_mps
		def 	snake_case_     (     self):
				return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3)




		@skip_mps
		def 	snake_case_     (     self):
				return super().test_save_load_optional_components()




		@skip_mps
		def 	snake_case_     (     self):
				return super().test_attention_slicing_forward_pass()




		def 	snake_case_     (     self):
				super().test_inference_batch_single_identical(expected_max_diff=3E-3)



@slow
@require_torch_gpu
class 						SCREAMING_SNAKE_CASE_ (						unittest.TestCase ):




		"""simple docstring"""





		def 	snake_case_     (     self):
				# clean up the VRAM after each test
				super().tearDown()
				gc.collect()
				torch.cuda.empty_cache()




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = torch_device

				__SCREAMING_SNAKE_CASE            = DanceDiffusionPipeline.from_pretrained("""harmonai/maestro-150k""")
				__SCREAMING_SNAKE_CASE            = pipe.to(lowerCAmelCase__)
				pipe.set_progress_bar_config(disable=lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = torch.manual_seed(0)
				__SCREAMING_SNAKE_CASE            = pipe(generator=lowerCAmelCase__							,  num_inference_steps=1_0_0							,  audio_length_in_s=4.0_96)
				__SCREAMING_SNAKE_CASE            = output.audios

				__SCREAMING_SNAKE_CASE            = audio[0, -3:, -3:]

				assert audio.shape == (1, 2, pipe.unet.sample_size)
				__SCREAMING_SNAKE_CASE            = np.array([-0.01_92, -0.02_31, -0.03_18, -0.00_59, 0.00_02, -0.00_20])

				assert np.abs(audio_slice.flatten() - expected_slice).max() < 1E-2




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = torch_device

				__SCREAMING_SNAKE_CASE            = DanceDiffusionPipeline.from_pretrained("""harmonai/maestro-150k"""							,  torch_dtype=torch.floataa)
				__SCREAMING_SNAKE_CASE            = pipe.to(lowerCAmelCase__)
				pipe.set_progress_bar_config(disable=lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = torch.manual_seed(0)
				__SCREAMING_SNAKE_CASE            = pipe(generator=lowerCAmelCase__							,  num_inference_steps=1_0_0							,  audio_length_in_s=4.0_96)
				__SCREAMING_SNAKE_CASE            = output.audios

				__SCREAMING_SNAKE_CASE            = audio[0, -3:, -3:]

				assert audio.shape == (1, 2, pipe.unet.sample_size)
				__SCREAMING_SNAKE_CASE            = np.array([-0.03_67, -0.04_88, -0.07_71, -0.05_25, -0.04_44, -0.03_41])

				assert np.abs(audio_slice.flatten() - expected_slice).max() < 1E-2






"""simple docstring"""





from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
							import tensorflow as tf

							from ..tf_utils import stable_softmax


if is_torch_available():
							import torch


__magic_name__       =			logging.get_logger(__name__)
@add_end_docstrings(
    __a     ,				R'''
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    '''     ,				)
class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





		def 	snake_case_     (     self							,  lowerCAmelCase__):
				if self.framework == "tf":
						__SCREAMING_SNAKE_CASE            = tf.where(input_ids == self.tokenizer.mask_token_id).numpy()
				elif self.framework == "pt":
						__SCREAMING_SNAKE_CASE            = torch.nonzero(input_ids == self.tokenizer.mask_token_id							,  as_tuple=lowerCAmelCase__)
				else:
						raise ValueError("""Unsupported framework""")
				return masked_index




		def 	snake_case_     (     self							,  lowerCAmelCase__):
				__SCREAMING_SNAKE_CASE            = self.get_masked_index(lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = np.prod(masked_index.shape)
				if numel < 1:
						raise PipelineException(
						    """fill-mask"""							,  self.model.base_model_prefix							,  f"No mask_token ({self.tokenizer.mask_token}) found on the input"							,  )




		def 	snake_case_     (     self							,  lowerCAmelCase__):
				if isinstance(lowerCAmelCase__							,  lowerCAmelCase__):
						for model_input in model_inputs:
								self._ensure_exactly_one_mask_token(model_input["""input_ids"""][0])
				else:
						for input_ids in model_inputs["input_ids"]:
								self._ensure_exactly_one_mask_token(lowerCAmelCase__)




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__=None							,  **lowerCAmelCase__):
				if return_tensors is None:
						__SCREAMING_SNAKE_CASE            = self.framework
				__SCREAMING_SNAKE_CASE            = self.tokenizer(lowerCAmelCase__							,  return_tensors=lowerCAmelCase__)
				self.ensure_exactly_one_mask_token(lowerCAmelCase__)
				return model_inputs




		def 	snake_case_     (     self							,  lowerCAmelCase__):
				__SCREAMING_SNAKE_CASE            = self.model(**lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = model_inputs["""input_ids"""]
				return model_outputs




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__=5							,  lowerCAmelCase__=None):
				# Cap top_k if there are targets
				if target_ids is not None and target_ids.shape[0] < top_k:
						__SCREAMING_SNAKE_CASE            = target_ids.shape[0]
				__SCREAMING_SNAKE_CASE            = model_outputs["""input_ids"""][0]
				__SCREAMING_SNAKE_CASE            = model_outputs["""logits"""]

				if self.framework == "tf":
						__SCREAMING_SNAKE_CASE            = tf.where(input_ids == self.tokenizer.mask_token_id).numpy()[:, 0]

						__SCREAMING_SNAKE_CASE            = outputs.numpy()

						__SCREAMING_SNAKE_CASE            = outputs[0, masked_index, :]
						__SCREAMING_SNAKE_CASE            = stable_softmax(lowerCAmelCase__							,  axis=-1)
						if target_ids is not None:
								__SCREAMING_SNAKE_CASE            = tf.gather_nd(tf.squeeze(lowerCAmelCase__							,  0)							,  target_ids.reshape(-1							,  1))
								__SCREAMING_SNAKE_CASE            = tf.expand_dims(lowerCAmelCase__							,  0)

						__SCREAMING_SNAKE_CASE            = tf.math.top_k(lowerCAmelCase__							,  k=lowerCAmelCase__)
						__SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE            = topk.values.numpy(), topk.indices.numpy()
				else:
						__SCREAMING_SNAKE_CASE            = torch.nonzero(input_ids == self.tokenizer.mask_token_id							,  as_tuple=lowerCAmelCase__).squeeze(-1)
						# Fill mask pipeline supports only one ${mask_token} per sample

						__SCREAMING_SNAKE_CASE            = outputs[0, masked_index, :]
						__SCREAMING_SNAKE_CASE            = logits.softmax(dim=-1)
						if target_ids is not None:
								__SCREAMING_SNAKE_CASE            = probs[..., target_ids]

						__SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE            = probs.topk(lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = []
				__SCREAMING_SNAKE_CASE            = values.shape[0] == 1
				for i, (_values, _predictions) in enumerate(zip(values.tolist()							,  predictions.tolist())):
						__SCREAMING_SNAKE_CASE            = []
						for v, p in zip(_values							,  _predictions):
								# Copy is important since we're going to modify this array in place
								__SCREAMING_SNAKE_CASE            = input_ids.numpy().copy()
								if target_ids is not None:
										__SCREAMING_SNAKE_CASE            = target_ids[p].tolist()

								__SCREAMING_SNAKE_CASE            = p
								# Filter padding out:
								__SCREAMING_SNAKE_CASE            = tokens[np.where(tokens != self.tokenizer.pad_token_id)]
								# Originally we skip special tokens to give readable output.
								# For multi masks though, the other [MASK] would be removed otherwise
								# making the output look odd, so we add them back
								__SCREAMING_SNAKE_CASE            = self.tokenizer.decode(lowerCAmelCase__							,  skip_special_tokens=lowerCAmelCase__)
								__SCREAMING_SNAKE_CASE            = {"""score""": v, """token""": p, """token_str""": self.tokenizer.decode([p]), """sequence""": sequence}
								row.append(lowerCAmelCase__)
						result.append(lowerCAmelCase__)
				if single_mask:
						return result[0]
				return result




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__=None):
				if isinstance(lowerCAmelCase__							,  lowerCAmelCase__):
						__SCREAMING_SNAKE_CASE            = [targets]
				try:
						__SCREAMING_SNAKE_CASE            = self.tokenizer.get_vocab()
				except Exception:
						__SCREAMING_SNAKE_CASE            = {}
				__SCREAMING_SNAKE_CASE            = []
				for target in targets:
						__SCREAMING_SNAKE_CASE            = vocab.get(lowerCAmelCase__							,  lowerCAmelCase__)
						if id_ is None:
								__SCREAMING_SNAKE_CASE            = self.tokenizer(
								    lowerCAmelCase__							,  add_special_tokens=lowerCAmelCase__							,  return_attention_mask=lowerCAmelCase__							,  return_token_type_ids=lowerCAmelCase__							,  max_length=1							,  truncation=lowerCAmelCase__							,  )["""input_ids"""]
								if len(lowerCAmelCase__) == 0:
										logger.warning(
										    f"The specified target token `{target}` does not exist in the model vocabulary. "
										    """We cannot replace it with anything meaningful, ignoring it""")
										continue
								__SCREAMING_SNAKE_CASE            = input_ids[0]
								# XXX: If users encounter this pass
								# it becomes pretty slow, so let's make sure
								# The warning enables them to fix the input to
								# get faster performance.
								logger.warning(
								    f"The specified target token `{target}` does not exist in the model vocabulary. "
								    f"Replacing with `{self.tokenizer.convert_ids_to_tokens(id_)}`.")
						target_ids.append(id_)
				__SCREAMING_SNAKE_CASE            = list(set(lowerCAmelCase__))
				if len(lowerCAmelCase__) == 0:
						raise ValueError("""At least one target must be provided when passed.""")
				__SCREAMING_SNAKE_CASE            = np.array(lowerCAmelCase__)
				return target_ids




		def 	snake_case_     (     self							,  lowerCAmelCase__=None							,  lowerCAmelCase__=None):
				__SCREAMING_SNAKE_CASE            = {}

				if targets is not None:
						__SCREAMING_SNAKE_CASE            = self.get_target_ids(lowerCAmelCase__							,  lowerCAmelCase__)
						__SCREAMING_SNAKE_CASE            = target_ids

				if top_k is not None:
						__SCREAMING_SNAKE_CASE            = top_k

				if self.tokenizer.mask_token_id is None:
						raise PipelineException(
						    """fill-mask"""							,  self.model.base_model_prefix							,  """The tokenizer does not define a `mask_token`.""")
				return {}, {}, postprocess_params




		def __call__(     self							,  lowerCAmelCase__							,  *lowerCAmelCase__							,  **lowerCAmelCase__):
				__SCREAMING_SNAKE_CASE            = super().__call__(lowerCAmelCase__							,  **lowerCAmelCase__)
				if isinstance(lowerCAmelCase__							,  lowerCAmelCase__) and len(lowerCAmelCase__) == 1:
						return outputs[0]
				return outputs




