




"""simple docstring"""




import math
from typing import Any, Callable, List, Optional, Tuple, Union

import numpy as np
import torch

from ...models import TaFilmDecoder
from ...schedulers import DDPMScheduler
from ...utils import is_onnx_available, logging, randn_tensor


if is_onnx_available():
					from ..onnx_utils import OnnxRuntimeModel

from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline
from .continous_encoder import SpectrogramContEncoder
from .notes_encoder import SpectrogramNotesEncoder


lowerCAmelCase							:			str     							=							logging.get_logger(__name__)  # pylint: disable=invalid-name

lowerCAmelCase							:			Tuple     							=							256






class     __magic_name__							(       UpperCAmelCase__				):






				'''simple docstring'''
				__UpperCamelCase			  =						["melgan"]





				def __init__(       self		, _a		, _a		, _a		, _a		, _a		, ):





							"""simple docstring"""
							super().__init__()

							# From MELGAN
							lowerCamelCase			      =					math.log(1e-5 )  # Matches MelGAN training.
							lowerCamelCase			      =					4.0  # Largest value for most examples
							lowerCamelCase			      =					128

							self.register_modules(
							    notes_encoder=_a		, continuous_encoder=_a		, decoder=_a		, scheduler=_a		, melgan=_a		, )





				def    _lowerCAmelCase				(       self		, _a		, _a=(-1.0, 1.0)		, _a=False ):





							"""simple docstring"""
							lowerCamelCase      ,   lowerCamelCase			      =					output_range
							if clip:
										lowerCamelCase			      =					torch.clip(_a		, self.min_value		, self.max_value )
							# Scale to [0, 1].
							lowerCamelCase			      =					(features - self.min_value) / (self.max_value - self.min_value)
							# Scale to [min_out, max_out].
							return zero_one * (max_out - min_out) + min_out





				def    _lowerCAmelCase				(       self		, _a		, _a=(-1.0, 1.0)		, _a=False ):





							"""simple docstring"""
							lowerCamelCase      ,   lowerCamelCase			      =					input_range
							lowerCamelCase			      =					torch.clip(_a		, _a		, _a ) if clip else outputs
							# Scale to [0, 1].
							lowerCamelCase			      =					(outputs - min_out) / (max_out - min_out)
							# Scale to [self.min_value, self.max_value].
							return zero_one * (self.max_value - self.min_value) + self.min_value





				def    _lowerCAmelCase				(       self		, _a		, _a		, _a ):





							"""simple docstring"""
							lowerCamelCase			      =					input_tokens > 0
							lowerCamelCase      ,   lowerCamelCase			      =					self.notes_encoder(
							    encoder_input_tokens=_a		, encoder_inputs_mask=_a )

							lowerCamelCase      ,   lowerCamelCase			      =					self.continuous_encoder(
							    encoder_inputs=_a		, encoder_inputs_mask=_a )

							return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)]





				def    _lowerCAmelCase				(       self		, _a		, _a		, _a ):





							"""simple docstring"""
							lowerCamelCase			      =					noise_time
							if not torch.is_tensor(_a ):
										lowerCamelCase			      =					torch.tensor([timesteps]		, dtype=torch.long		, device=input_tokens.device )
							elif torch.is_tensor(_a ) and len(timesteps.shape ) == 0:
										lowerCamelCase			      =					timesteps[None].to(input_tokens.device )

							# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
							lowerCamelCase			      =					timesteps * torch.ones(input_tokens.shape[0]		, dtype=timesteps.dtype		, device=timesteps.device )

							lowerCamelCase			      =					self.decoder(
							    encodings_and_masks=_a		, decoder_input_tokens=_a		, decoder_noise_time=_a )
							return logits





				@torch.no_grad()
				def __call__(       self		, _a		, _a = None		, _a = 100		, _a = True		, _a = "numpy"		, _a = None		, _a = 1		, ):





							"""simple docstring"""
							if (callback_steps is None) or (
							    callback_steps is not None and (not isinstance(_a		, _a ) or callback_steps <= 0)
							):
										raise ValueError(
										    f'`callback_steps` has to be a positive integer but is {callback_steps} of type'
										    f' {type(_a )}.' )

							lowerCamelCase			      =					np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims]		, dtype=np.floataa )
							lowerCamelCase			      =					np.zeros([1, 0, self.n_dims]		, np.floataa )
							lowerCamelCase			      =					torch.ones((1, TARGET_FEATURE_LENGTH)		, dtype=_a		, device=self.device )

							for i, encoder_input_tokens in enumerate(_a ):
										if i == 0:
													lowerCamelCase			      =					torch.from_numpy(pred_mel[:1].copy() ).to(
													    device=self.device		, dtype=self.decoder.dtype )
													# The first chunk has no previous context.
													lowerCamelCase			      =					torch.zeros((1, TARGET_FEATURE_LENGTH)		, dtype=_a		, device=self.device )
										else:
													# The full song pipeline does not feed in a context feature, so the mask
													# will be all 0s after the feature converter. Because we know we're
													# feeding in a full context chunk from the previous prediction, set it
													# to all 1s.
													lowerCamelCase			      =					ones

										lowerCamelCase			      =					self.scale_features(
										    _a		, output_range=[-1.0, 1.0]		, clip=_a )

										lowerCamelCase			      =					self.encode(
										    input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device )		, continuous_inputs=_a		, continuous_mask=_a		, )

										# Sample encoder_continuous_inputs shaped gaussian noise to begin loop
										lowerCamelCase			      =					randn_tensor(
										    shape=encoder_continuous_inputs.shape		, generator=_a		, device=self.device		, dtype=self.decoder.dtype		, )

										# set step values
										self.scheduler.set_timesteps(_a )

										# Denoising diffusion loop
										for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ):
													lowerCamelCase			      =					self.decode(
													    encodings_and_masks=_a		, input_tokens=_a		, noise_time=t / self.scheduler.config.num_train_timesteps		, )

													# Compute previous output: x_t -> x_t-1
													lowerCamelCase			      =					self.scheduler.step(_a		, _a		, _a		, generator=_a ).prev_sample

										lowerCamelCase			      =					self.scale_to_features(_a		, input_range=[-1.0, 1.0] )
										lowerCamelCase			      =					mel[:1]
										lowerCamelCase			      =					mel.cpu().float().numpy()

										lowerCamelCase			      =					np.concatenate([full_pred_mel, pred_mel[:1]]		, axis=1 )

										# call the callback, if provided
										if callback is not None and i % callback_steps == 0:
													callback(_a		, _a )

										logger.info("""Generated segment"""		, _a )

							if output_type == "numpy" and not is_onnx_available():
										raise ValueError(
										    """Cannot return output in 'np' format if ONNX is not available. Make sure to have ONNX installed or set 'output_type' to 'mel'.""" )
							elif output_type == "numpy" and self.melgan is None:
										raise ValueError(
										    """Cannot return output in 'np' format if melgan component is not defined. Make sure to define `self.melgan` or set 'output_type' to 'mel'.""" )

							if output_type == "numpy":
										lowerCamelCase			      =					self.melgan(input_features=full_pred_mel.astype(np.floataa ) )
							else:
										lowerCamelCase			      =					full_pred_mel

							if not return_dict:
										return (output,)

							return AudioPipelineOutput(audios=_a )









"""simple docstring"""




import operator as op


lowerCAmelCase							:			Dict     							=							"""scaler.pt"""
lowerCAmelCase							:			Tuple     							=							"""pytorch_model"""
lowerCAmelCase							:			Union[str, Any]     							=							"""random_states"""
lowerCAmelCase							:			Union[str, Any]     							=							"""optimizer"""
lowerCAmelCase							:			Dict     							=							"""scheduler"""
lowerCAmelCase							:			int     							=							"""pytorch_model.bin"""
lowerCAmelCase							:			str     							=							"""pytorch_model.bin.index.json"""
lowerCAmelCase							:			Union[str, Any]     							=							"""model.safetensors"""
lowerCAmelCase							:			List[Any]     							=							"""model.safetensors.index.json"""
lowerCAmelCase							:			List[Any]     							=							"""1.10.2"""
lowerCAmelCase							:			Any     							=							"""py38"""
lowerCAmelCase							:			Optional[int]     							=							"""4.17.0"""
lowerCAmelCase							:			str     							=							["""ml.p3.16xlarge""", """ml.p3dn.24xlarge""", """ml.p4dn.24xlarge"""]
lowerCAmelCase							:			Tuple     							=							["""FULL_SHARD""", """SHARD_GRAD_OP""", """NO_SHARD""", """HYBRID_SHARD""", """HYBRID_SHARD_ZERO2"""]
lowerCAmelCase							:			List[Any]     							=							["""TRANSFORMER_BASED_WRAP""", """SIZE_BASED_WRAP""", """NO_WRAP"""]
lowerCAmelCase							:			List[str]     							=							["""BACKWARD_PRE""", """BACKWARD_POST""", """NO_PREFETCH"""]
lowerCAmelCase							:			List[str]     							=							["""FULL_STATE_DICT""", """LOCAL_STATE_DICT""", """SHARDED_STATE_DICT"""]
lowerCAmelCase							:			Any     							=							"""2.0.1"""
lowerCAmelCase							:			List[Any]     							=							["""pdsh""", """standard""", """openmpi""", """mvapich"""]
lowerCAmelCase							:			Union[str, Any]     							=							["""default""", """reduce-overhead""", """max-autotune"""]

lowerCAmelCase							:			Optional[int]     							=							{""">""": op.gt, """>=""": op.ge, """==""": op.eq, """!=""": op.ne, """<=""": op.le, """<""": op.lt}

# These are the args for `torch.distributed.launch` for pytorch < 1.9
lowerCAmelCase							:			Union[str, Any]     							=							[
    """nnodes""",
    """nproc_per_node""",
    """rdzv_backend""",
    """rdzv_endpoint""",
    """rdzv_id""",
    """rdzv_conf""",
    """standalone""",
    """max_restarts""",
    """monitor_interval""",
    """start_method""",
    """role""",
    """module""",
    """m""",
    """no_python""",
    """run_path""",
    """log_dir""",
    """r""",
    """redirects""",
    """t""",
    """tee""",
    """node_rank""",
    """master_addr""",
    """master_port""",
]

lowerCAmelCase							:			List[str]     							=							["""DEEPSPEED""", """MULTI_GPU""", """FSDP""", """MEGATRON_LM"""]
lowerCAmelCase							:			Optional[Any]     							=							["""DEEPSPEED""", """MULTI_XPU""", """FSDP"""]



