




import json
import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import evaluate
import numpy as np
import torch
from datasets import load_dataset
from huggingface_hub import hf_hub_download
from PIL import Image
from torch import nn
from torchvision import transforms
from torchvision.transforms import functional

import transformers
from transformers import (
    AutoConfig,
    AutoImageProcessor,
    AutoModelForSemanticSegmentation,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
lowercase_		=							logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('''4.31.0''')

require_version('''datasets>=2.0.0''', '''To fix: pip install -r examples/pytorch/semantic-segmentation/requirements.txt''')







def 			lowerCAmelCase  (     UpperCAmelCase,     UpperCAmelCase,     UpperCAmelCase=0	)  ->List[Any]:






     """simple docstring"""






     __magic_name__ :							Dict		       =							(size, size) if isinstance(UpperCAmelCase,     UpperCAmelCase	) else size
     __magic_name__ :							List[str]		       =							img.size
     __magic_name__ :							Optional[Any]		       =							size[1] - original_height if original_height < size[1] else 0
     __magic_name__ :							Optional[int]		       =							size[0] - original_width if original_width < size[0] else 0
     __magic_name__ :							List[str]		       =							functional.pad(UpperCAmelCase,     (0, 0, pad_width, pad_height),     fill=UpperCAmelCase	)
     return img





class 		A__    :






 def __init__(     self    ,					lowerCamelCase						)				->       List[Any]:




      """simple docstring"""






      __magic_name__ :							List[str]		       =							transforms






 def __call__(     self    ,					lowerCamelCase    ,					lowerCamelCase						)				->       Dict:




      """simple docstring"""






      for t in self.transforms:
           __magic_name__ :							int		       =							t(SCREAMING_SNAKE_CASE__    ,					SCREAMING_SNAKE_CASE__						)
      return image, target





class 		A__    :






 def __init__(     self						)				->       Union[str, Any]:




      """simple docstring"""






      pass






 def __call__(     self    ,					lowerCamelCase    ,					lowerCamelCase						)				->       Union[str, Any]:




      """simple docstring"""






      return image, target





class 		A__    :






 def __init__(     self    ,					lowerCamelCase						)				->       Union[str, Any]:




      """simple docstring"""






      __magic_name__ :							Optional[int]		       =							size






 def __call__(     self    ,					lowerCamelCase    ,					lowerCamelCase						)				->       Optional[Any]:




      """simple docstring"""






      __magic_name__ :							List[str]		       =							functional.resize(SCREAMING_SNAKE_CASE__    ,					self.size						)
      __magic_name__ :							List[str]		       =							functional.resize(SCREAMING_SNAKE_CASE__    ,					self.size    ,					interpolation=transforms.InterpolationMode.NEAREST						)
      return image, target





class 		A__    :






 def __init__(     self    ,					lowerCamelCase    ,					lowerCamelCase=None						)				->       Tuple:




      """simple docstring"""






      __magic_name__ :							Optional[int]		       =							min_size
      if max_size is None:
           __magic_name__ :							Tuple		       =							min_size
      __magic_name__ :							str		       =							max_size






 def __call__(     self    ,					lowerCamelCase    ,					lowerCamelCase						)				->       List[str]:




      """simple docstring"""






      __magic_name__ :							Union[str, Any]		       =							random.randint(self.min_size    ,					self.max_size						)
      __magic_name__ :							List[str]		       =							functional.resize(SCREAMING_SNAKE_CASE__    ,					SCREAMING_SNAKE_CASE__						)
      __magic_name__ :							Optional[int]		       =							functional.resize(SCREAMING_SNAKE_CASE__    ,					SCREAMING_SNAKE_CASE__    ,					interpolation=transforms.InterpolationMode.NEAREST						)
      return image, target





class 		A__    :






 def __init__(     self    ,					lowerCamelCase						)				->       Tuple:




      """simple docstring"""






      __magic_name__ :							List[str]		       =							size if isinstance(SCREAMING_SNAKE_CASE__    ,					SCREAMING_SNAKE_CASE__						) else (size, size)






 def __call__(     self    ,					lowerCamelCase    ,					lowerCamelCase						)				->       List[str]:




      """simple docstring"""






      __magic_name__ :							Optional[Any]		       =							pad_if_smaller(SCREAMING_SNAKE_CASE__    ,					self.size						)
      __magic_name__ :							List[Any]		       =							pad_if_smaller(SCREAMING_SNAKE_CASE__    ,					self.size    ,					fill=255						)
      __magic_name__ :							Dict		       =							transforms.RandomCrop.get_params(SCREAMING_SNAKE_CASE__    ,					self.size						)
      __magic_name__ :							int		       =							functional.crop(SCREAMING_SNAKE_CASE__    ,					*SCREAMING_SNAKE_CASE__						)
      __magic_name__ :							int		       =							functional.crop(SCREAMING_SNAKE_CASE__    ,					*SCREAMING_SNAKE_CASE__						)
      return image, target





class 		A__    :






 def __init__(     self    ,					lowerCamelCase						)				->       Optional[int]:




      """simple docstring"""






      __magic_name__ :							str		       =							flip_prob






 def __call__(     self    ,					lowerCamelCase    ,					lowerCamelCase						)				->       int:




      """simple docstring"""






      if random.random() < self.flip_prob:
           __magic_name__ :							Optional[int]		       =							functional.hflip(SCREAMING_SNAKE_CASE__						)
           __magic_name__ :							Union[str, Any]		       =							functional.hflip(SCREAMING_SNAKE_CASE__						)
      return image, target





class 		A__    :






 def __call__(     self    ,					lowerCamelCase    ,					lowerCamelCase						)				->       Optional[int]:




      """simple docstring"""






      __magic_name__ :							Optional[Any]		       =							functional.pil_to_tensor(SCREAMING_SNAKE_CASE__						)
      __magic_name__ :							int		       =							torch.as_tensor(np.array(SCREAMING_SNAKE_CASE__						)    ,					dtype=torch.intaa						)
      return image, target





class 		A__    :






 def __init__(     self    ,					lowerCamelCase						)				->       List[Any]:




      """simple docstring"""






      __magic_name__ :							Any		       =							dtype






 def __call__(     self    ,					lowerCamelCase    ,					lowerCamelCase						)				->       Any:




      """simple docstring"""






      __magic_name__ :							Optional[int]		       =							functional.convert_image_dtype(SCREAMING_SNAKE_CASE__    ,					self.dtype						)
      return image, target





class 		A__    :






 def __init__(     self    ,					lowerCamelCase    ,					lowerCamelCase						)				->       Optional[Any]:




      """simple docstring"""






      __magic_name__ :							List[str]		       =							mean
      __magic_name__ :							Dict		       =							std






 def __call__(     self    ,					lowerCamelCase    ,					lowerCamelCase						)				->       Optional[int]:




      """simple docstring"""






      __magic_name__ :							Dict		       =							functional.normalize(SCREAMING_SNAKE_CASE__    ,					mean=self.mean    ,					std=self.std						)
      return image, target





class 		A__    :






 def __call__(     self    ,					lowerCamelCase    ,					lowerCamelCase						)				->       List[str]:




      """simple docstring"""






      if not isinstance(SCREAMING_SNAKE_CASE__    ,					np.ndarray						):
           __magic_name__ :							Any		       =							np.array(SCREAMING_SNAKE_CASE__						).astype(np.uinta						)
      # avoid using underflow conversion
      __magic_name__ :							Optional[Any]		       =							255
      __magic_name__ :							Optional[int]		       =							target - 1
      __magic_name__ :							str		       =							255

      __magic_name__ :							str		       =							Image.fromarray(SCREAMING_SNAKE_CASE__						)
      return image, target





@dataclass
class 		A__    :
 lowerCamelCase__		:			Optional[str]       =field(
     default="segments/sidewalk-semantic"		,					metadata={
         "help": "Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub)."
     }		,					)
 lowerCamelCase__		:			Optional[str]       =field(
     default=_a		,					metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}			)
 lowerCamelCase__		:			Optional[float]       =field(
     default=0.15		,					metadata={"help": "Percent to split off of train for validation."}			)
 lowerCamelCase__		:			Optional[int]       =field(
     default=_a		,					metadata={
         "help": (
             "For debugging purposes or quicker training, truncate the number of training examples to this "
             "value if set."
         )
     }		,					)
 lowerCamelCase__		:			Optional[int]       =field(
     default=_a		,					metadata={
         "help": (
             "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
             "value if set."
         )
     }		,					)
 lowerCamelCase__		:			Optional[bool]       =field(
     default=_a		,					metadata={"help": "Whether or not to reduce all labels by 1 and replace background by 255."}		,					)






 def 			lowercase				(     self						)				->       str:




      """simple docstring"""






      if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
           raise ValueError(
               '''You must specify either a dataset name from the hub or a train and/or validation directory.'''						)





@dataclass
class 		A__    :
 lowerCamelCase__		:			str       =field(
     default="nvidia/mit-b0"		,					metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}		,					)
 lowerCamelCase__		:			Optional[str]       =field(
     default=_a		,					metadata={"help": "Pretrained config name or path if not the same as model_name"}			)
 lowerCamelCase__		:			Optional[str]       =field(
     default=_a		,					metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}			)
 lowerCamelCase__		:			str       =field(
     default="main"		,					metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}		,					)
 lowerCamelCase__		:			str       =field(default=_a		,					metadata={"help": "Name or path of preprocessor config."}			)
 lowerCamelCase__		:			bool       =field(
     default=_a		,					metadata={
         "help": (
             "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
             "with private models)."
         )
     }		,					)







def 			lowerCAmelCase  (     )  ->List[str]:






     """simple docstring"""






     __magic_name__ :							Optional[int]		       =							HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)	)
     if len(sys.argv	) == 2 and sys.argv[1].endswith('''.json'''	):
          # If we pass only one argument to the script and it's the path to a json file,
          # let's parse it to get our arguments.
          __magic_name__ :							Dict		       =							parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]	)	)
     else:
          __magic_name__ :							Tuple		       =							parser.parse_args_into_dataclasses()

     # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
     # information sent is the one passed as arguments along with your Python/PyTorch versions.
     send_example_telemetry('''run_semantic_segmentation''',     UpperCAmelCase,     UpperCAmelCase	)

     # Setup logging
     logging.basicConfig(
         format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''',     datefmt='''%m/%d/%Y %H:%M:%S''',     handlers=[logging.StreamHandler(sys.stdout	)],     )

     if training_args.should_log:
          # The default of training_args.log_level is passive, so we set log level at info here to have that default.
          transformers.utils.logging.set_verbosity_info()

     __magic_name__ :							Tuple		       =							training_args.get_process_log_level()
     logger.setLevel(UpperCAmelCase	)
     transformers.utils.logging.set_verbosity(UpperCAmelCase	)
     transformers.utils.logging.enable_default_handler()
     transformers.utils.logging.enable_explicit_format()

     # Log on each process the small summary:
     logger.warning(
         F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
         + F'''distributed training: {bool(training_args.local_rank != -1	)}, 16-bits training: {training_args.fpaa}'''	)
     logger.info(F'''Training/evaluation parameters {training_args}'''	)

     # Detecting last checkpoint.
     __magic_name__ :							Dict		       =							None
     if os.path.isdir(training_args.output_dir	) and training_args.do_train and not training_args.overwrite_output_dir:
          __magic_name__ :							int		       =							get_last_checkpoint(training_args.output_dir	)
          if last_checkpoint is None and len(os.listdir(training_args.output_dir	)	) > 0:
               raise ValueError(
                   F'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
                   '''Use --overwrite_output_dir to overcome.'''	)
          elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
               logger.info(
                   F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
                   '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'''	)

          # Load dataset
          # In distributed training, the load_dataset function guarantees that only one local process can concurrently
          # download the dataset.
          # TODO support datasets from local folders
     __magic_name__ :							List[Any]		       =							load_dataset(data_args.dataset_name,     cache_dir=model_args.cache_dir	)

     # Rename column names to standardized names (only "image" and "label" need to be present)
     if "pixel_values" in dataset["train"].column_names:
          __magic_name__ :							List[Any]		       =							dataset.rename_columns({'''pixel_values''': '''image'''}	)
     if "annotation" in dataset["train"].column_names:
          __magic_name__ :							Dict		       =							dataset.rename_columns({'''annotation''': '''label'''}	)

     # If we don't have a validation split, split off a percentage of train as validation.
     __magic_name__ :							List[Any]		       =							None if "validation" in dataset.keys() else data_args.train_val_split
     if isinstance(data_args.train_val_split,     UpperCAmelCase	) and data_args.train_val_split > 0.0:
          __magic_name__ :							List[Any]		       =							dataset["train"].train_test_split(data_args.train_val_split	)
          __magic_name__ :							Optional[Any]		       =							split["train"]
          __magic_name__ :							Optional[Any]		       =							split["test"]

     # Prepare label mappings.
     # We'll include these in the model's config to get human readable labels in the Inference API.
     if data_args.dataset_name == "scene_parse_150":
          __magic_name__ :							Tuple		       =							"huggingface/label-files"
          __magic_name__ :							Union[str, Any]		       =							"ade20k-id2label.json"
     else:
          __magic_name__ :							Optional[int]		       =							data_args.dataset_name
          __magic_name__ :							Optional[int]		       =							"id2label.json"
     __magic_name__ :							List[Any]		       =							json.load(open(hf_hub_download(UpperCAmelCase,     UpperCAmelCase,     repo_type='''dataset'''	),     '''r'''	)	)
     __magic_name__ :							Tuple		       =							{int(UpperCAmelCase	): v for k, v in idalabel.items()}
     __magic_name__ :							List[Any]		       =							{v: str(UpperCAmelCase	) for k, v in idalabel.items()}

     # Load the mean IoU metric from the datasets package
     __magic_name__ :							Union[str, Any]		       =							evaluate.load('''mean_iou'''	)

     # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
     # predictions and label_ids field) and has to return a dictionary string to float.
     @torch.no_grad()
     def compute_metrics(UpperCAmelCase	):
          __magic_name__ :							List[str]		       =							eval_pred
          __magic_name__ :							Optional[int]		       =							torch.from_numpy(UpperCAmelCase	)
          # scale the logits to the size of the label
          __magic_name__ :							Optional[Any]		       =							nn.functional.interpolate(
              UpperCAmelCase,     size=labels.shape[-2:],     mode='''bilinear''',     align_corners=UpperCAmelCase,     ).argmax(dim=1	)

          __magic_name__ :							Optional[int]		       =							logits_tensor.detach().cpu().numpy()
          __magic_name__ :							Optional[Any]		       =							metric.compute(
              predictions=UpperCAmelCase,     references=UpperCAmelCase,     num_labels=len(UpperCAmelCase	),     ignore_index=0,     reduce_labels=image_processor.do_reduce_labels,     )
          # add per category metrics as individual key-value pairs
          __magic_name__ :							Tuple		       =							metrics.pop('''per_category_accuracy'''	).tolist()
          __magic_name__ :							Union[str, Any]		       =							metrics.pop('''per_category_iou'''	).tolist()

          metrics.update({F'''accuracy_{idalabel[i]}''': v for i, v in enumerate(UpperCAmelCase	)}	)
          metrics.update({F'''iou_{idalabel[i]}''': v for i, v in enumerate(UpperCAmelCase	)}	)

          return metrics

     __magic_name__ :							List[Any]		       =							AutoConfig.from_pretrained(
         model_args.config_name or model_args.model_name_or_path,     labelaid=UpperCAmelCase,     idalabel=UpperCAmelCase,     cache_dir=model_args.cache_dir,     revision=model_args.model_revision,     use_auth_token=True if model_args.use_auth_token else None,     )
     __magic_name__ :							Any		       =							AutoModelForSemanticSegmentation.from_pretrained(
         model_args.model_name_or_path,     from_tf=bool('''.ckpt''' in model_args.model_name_or_path	),     config=UpperCAmelCase,     cache_dir=model_args.cache_dir,     revision=model_args.model_revision,     use_auth_token=True if model_args.use_auth_token else None,     )
     __magic_name__ :							str		       =							AutoImageProcessor.from_pretrained(
         model_args.image_processor_name or model_args.model_name_or_path,     cache_dir=model_args.cache_dir,     revision=model_args.model_revision,     use_auth_token=True if model_args.use_auth_token else None,     )

     # Define torchvision transforms to be applied to each image + target.
     # Not that straightforward in torchvision: https://github.com/pytorch/vision/issues/9
     # Currently based on official torchvision references: https://github.com/pytorch/vision/blob/main/references/segmentation/transforms.py
     if "shortest_edge" in image_processor.size:
          # We instead set the target size as (shortest_edge, shortest_edge) to here to ensure all images are batchable.
          __magic_name__ :							str		       =							(image_processor.size["shortest_edge"], image_processor.size["shortest_edge"])
     else:
          __magic_name__ :							Optional[int]		       =							(image_processor.size["height"], image_processor.size["width"])
     __magic_name__ :							Union[str, Any]		       =							Compose(
         [
             ReduceLabels() if data_args.reduce_labels else Identity(),
             RandomCrop(size=UpperCAmelCase	),
             RandomHorizontalFlip(flip_prob=0.5	),
             PILToTensor(),
             ConvertImageDtype(torch.float	),
             Normalize(mean=image_processor.image_mean,     std=image_processor.image_std	),
         ]	)
     # Define torchvision transform to be applied to each image.
     # jitter = ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1)
     __magic_name__ :							str		       =							Compose(
         [
             ReduceLabels() if data_args.reduce_labels else Identity(),
             Resize(size=UpperCAmelCase	),
             PILToTensor(),
             ConvertImageDtype(torch.float	),
             Normalize(mean=image_processor.image_mean,     std=image_processor.image_std	),
         ]	)

     def preprocess_train(UpperCAmelCase	):
          __magic_name__ :							Optional[int]		       =							[]
          __magic_name__ :							List[str]		       =							[]
          for image, target in zip(example_batch['''image'''],     example_batch['''label''']	):
               __magic_name__ :							Optional[Any]		       =							train_transforms(image.convert('''RGB'''	),     UpperCAmelCase	)
               pixel_values.append(UpperCAmelCase	)
               labels.append(UpperCAmelCase	)

          __magic_name__ :							Any		       =							{}
          __magic_name__ :							str		       =							torch.stack(UpperCAmelCase	)
          __magic_name__ :							Optional[int]		       =							torch.stack(UpperCAmelCase	)

          return encoding

     def preprocess_val(UpperCAmelCase	):
          __magic_name__ :							int		       =							[]
          __magic_name__ :							Optional[Any]		       =							[]
          for image, target in zip(example_batch['''image'''],     example_batch['''label''']	):
               __magic_name__ :							Any		       =							val_transforms(image.convert('''RGB'''	),     UpperCAmelCase	)
               pixel_values.append(UpperCAmelCase	)
               labels.append(UpperCAmelCase	)

          __magic_name__ :							Tuple		       =							{}
          __magic_name__ :							Dict		       =							torch.stack(UpperCAmelCase	)
          __magic_name__ :							Optional[int]		       =							torch.stack(UpperCAmelCase	)

          return encoding

     if training_args.do_train:
          if "train" not in dataset:
               raise ValueError('''--do_train requires a train dataset'''	)
          if data_args.max_train_samples is not None:
               __magic_name__ :							Dict		       =							(
                   dataset["train"].shuffle(seed=training_args.seed	).select(range(data_args.max_train_samples	)	)
               )
          # Set the training transforms
          dataset["train"].set_transform(UpperCAmelCase	)

     if training_args.do_eval:
          if "validation" not in dataset:
               raise ValueError('''--do_eval requires a validation dataset'''	)
          if data_args.max_eval_samples is not None:
               __magic_name__ :							str		       =							(
                   dataset["validation"].shuffle(seed=training_args.seed	).select(range(data_args.max_eval_samples	)	)
               )
          # Set the validation transforms
          dataset["validation"].set_transform(UpperCAmelCase	)

     # Initalize our trainer
     __magic_name__ :							int		       =							Trainer(
         model=UpperCAmelCase,     args=UpperCAmelCase,     train_dataset=dataset['''train'''] if training_args.do_train else None,     eval_dataset=dataset['''validation'''] if training_args.do_eval else None,     compute_metrics=UpperCAmelCase,     tokenizer=UpperCAmelCase,     data_collator=UpperCAmelCase,     )

     # Training
     if training_args.do_train:
          __magic_name__ :							Optional[int]		       =							None
          if training_args.resume_from_checkpoint is not None:
               __magic_name__ :							int		       =							training_args.resume_from_checkpoint
          elif last_checkpoint is not None:
               __magic_name__ :							List[str]		       =							last_checkpoint
          __magic_name__ :							Dict		       =							trainer.train(resume_from_checkpoint=UpperCAmelCase	)
          trainer.save_model()
          trainer.log_metrics('''train''',     train_result.metrics	)
          trainer.save_metrics('''train''',     train_result.metrics	)
          trainer.save_state()

     # Evaluation
     if training_args.do_eval:
          __magic_name__ :							str		       =							trainer.evaluate()
          trainer.log_metrics('''eval''',     UpperCAmelCase	)
          trainer.save_metrics('''eval''',     UpperCAmelCase	)

     # Write model card and (optionally) push to hub
     __magic_name__ :							List[str]		       =							{
         "finetuned_from": model_args.model_name_or_path,
         "dataset": data_args.dataset_name,
         "tags": ["image-segmentation", "vision"],
     }
     if training_args.push_to_hub:
          trainer.push_to_hub(**UpperCAmelCase	)
     else:
          trainer.create_model_card(**UpperCAmelCase	)


if __name__ == "__main__":
    main()









import gc
import unittest

import numpy as np
import torch

from diffusers import DDPMScheduler, MidiProcessor, SpectrogramDiffusionPipeline
from diffusers.pipelines.spectrogram_diffusion import SpectrogramContEncoder, SpectrogramNotesEncoder, TaFilmDecoder
from diffusers.utils import require_torch_gpu, skip_mps, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_note_seq, require_onnxruntime

from ..pipeline_params import TOKENS_TO_AUDIO_GENERATION_BATCH_PARAMS, TOKENS_TO_AUDIO_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()


lowercase_		=							'''./tests/fixtures/elise_format0.mid'''





@unittest.skip("The note-seq package currently throws an error on import"			)
class 		A__    (       __SCREAMING_SNAKE_CASE		,					unittest.TestCase			):
	lowerCamelCase__		:			Optional[int]       =SpectrogramDiffusionPipeline
	lowerCamelCase__		:			List[str]       =PipelineTesterMixin.required_optional_params - {
	    "callback",
	    "latents",
	    "callback_steps",
	    "output_type",
	    "num_images_per_prompt",
	}
	lowerCamelCase__		:			Union[str, Any]       =False
	lowerCamelCase__		:			List[Any]       =False
	lowerCamelCase__		:			List[str]       =TOKENS_TO_AUDIO_GENERATION_PARAMS
	lowerCamelCase__		:			str       =TOKENS_TO_AUDIO_GENERATION_BATCH_PARAMS






	def 			lowercase				(     self						)				->       Any:




						"""simple docstring"""






						torch.manual_seed(0						)
						__magic_name__ :							Optional[Any]		       =							SpectrogramNotesEncoder(
						    max_length=2048    ,					vocab_size=1536    ,					d_model=768    ,					dropout_rate=0.1    ,					num_layers=1    ,					num_heads=1    ,					d_kv=4    ,					d_ff=2048    ,					feed_forward_proj='''gated-gelu'''    ,					)

						__magic_name__ :							Any		       =							SpectrogramContEncoder(
						    input_dims=128    ,					targets_context_length=256    ,					d_model=768    ,					dropout_rate=0.1    ,					num_layers=1    ,					num_heads=1    ,					d_kv=4    ,					d_ff=2048    ,					feed_forward_proj='''gated-gelu'''    ,					)

						__magic_name__ :							List[Any]		       =							TaFilmDecoder(
						    input_dims=128    ,					targets_length=256    ,					max_decoder_noise_time=2_0_0_0_0.0    ,					d_model=768    ,					num_layers=1    ,					num_heads=1    ,					d_kv=4    ,					d_ff=2048    ,					dropout_rate=0.1    ,					)

						__magic_name__ :							Any		       =							DDPMScheduler()

						__magic_name__ :							Dict		       =							{
						    '''notes_encoder''': notes_encoder.eval(),
						    '''continuous_encoder''': continuous_encoder.eval(),
						    '''decoder''': decoder.eval(),
						    '''scheduler''': scheduler,
						    '''melgan''': None,
						}
						return components






	def 			lowercase				(     self    ,					lowerCamelCase    ,					lowerCamelCase=0						)				->       Dict:




						"""simple docstring"""






						if str(lowerCamelCase						).startswith('''mps'''						):
											__magic_name__ :							List[str]		       =							torch.manual_seed(lowerCamelCase						)
						else:
											__magic_name__ :							Any		       =							torch.Generator(device=lowerCamelCase						).manual_seed(lowerCamelCase						)
						__magic_name__ :							Any		       =							{
						    '''input_tokens''': [
						        [1134, 90, 1135, 1133, 1080, 112, 1132, 1080, 1133, 1079, 133, 1132, 1079, 1133, 1] + [0] * 2033
						    ],
						    '''generator''': generator,
						    '''num_inference_steps''': 4,
						    '''output_type''': '''mel''',
						}
						return inputs






	def 			lowercase				(     self						)				->       Optional[int]:




						"""simple docstring"""






						__magic_name__ :							Optional[Any]		       =							'''cpu'''  # ensure determinism for the device-dependent torch.Generator
						__magic_name__ :							Union[str, Any]		       =							self.get_dummy_components()
						__magic_name__ :							str		       =							SpectrogramDiffusionPipeline(**lowerCamelCase						)
						__magic_name__ :							List[Any]		       =							pipe.to(lowerCamelCase						)
						pipe.set_progress_bar_config(disable=lowerCamelCase						)

						__magic_name__ :							Tuple		       =							self.get_dummy_inputs(lowerCamelCase						)
						__magic_name__ :							List[str]		       =							pipe(**lowerCamelCase						)
						__magic_name__ :							Any		       =							output.audios

						__magic_name__ :							Union[str, Any]		       =							mel[0, -3:, -3:]

						assert mel_slice.shape == (3, 3)
						__magic_name__ :							Dict		       =							np.array(
						    [-1_1.5_1_2_9_2_5, -4.7_8_8_2_1_5, -0.4_6_1_7_2_9_0_5, -2.0_5_1_7_1_5, -1_0.5_3_9_1_4_7, -1_0.9_7_0_9_6_3, -9.0_9_1_6_3_4, 4.0, 4.0]						)
						assert np.abs(mel_slice.flatten() - expected_slice						).max() < 1e-2






	@skip_mps
	def 			lowercase				(     self						)				->       List[Any]:




						"""simple docstring"""






						return super().test_save_load_local()






	@skip_mps
	def 			lowercase				(     self						)				->       str:




						"""simple docstring"""






						return super().test_dict_tuple_outputs_equivalent()






	@skip_mps
	def 			lowercase				(     self						)				->       List[Any]:




						"""simple docstring"""






						return super().test_save_load_optional_components()






	@skip_mps
	def 			lowercase				(     self						)				->       Union[str, Any]:




						"""simple docstring"""






						return super().test_attention_slicing_forward_pass()






	def 			lowercase				(     self						)				->       Tuple:




						"""simple docstring"""






						pass






	def 			lowercase				(     self						)				->       int:




						"""simple docstring"""






						pass






	@skip_mps
	def 			lowercase				(     self						)				->       Optional[Any]:




						"""simple docstring"""






						return super().test_progress_bar()





@slow
@require_torch_gpu
@require_onnxruntime
@require_note_seq
class 		A__    (       unittest.TestCase			):






	def 			lowercase				(     self						)				->       List[Any]:




						"""simple docstring"""






						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()






	def 			lowercase				(     self						)				->       Optional[Any]:




						"""simple docstring"""






						__magic_name__ :							List[Any]		       =							torch_device

						__magic_name__ :							Any		       =							SpectrogramDiffusionPipeline.from_pretrained('''google/music-spectrogram-diffusion'''						)
						__magic_name__ :							Optional[int]		       =							pipe.melgan
						__magic_name__ :							List[str]		       =							None

						__magic_name__ :							Tuple		       =							pipe.to(lowerCamelCase						)
						pipe.set_progress_bar_config(disable=lowerCamelCase						)

						def callback(lowerCamelCase    ,					lowerCamelCase						):
											# decode mel to audio
											__magic_name__ :							Tuple		       =							melgan(input_features=mel_output.astype(np.floataa						)						)[0]
											assert len(audio[0]						) == 81920 * (step + 1)
											# simulate that audio is played
											return audio

						__magic_name__ :							int		       =							MidiProcessor()
						__magic_name__ :							List[str]		       =							processor(lowerCamelCase						)

						__magic_name__ :							Dict		       =							input_tokens[:3]
						__magic_name__ :							Any		       =							torch.manual_seed(0						)
						pipe(lowerCamelCase    ,					num_inference_steps=5    ,					generator=lowerCamelCase    ,					callback=lowerCamelCase    ,					output_type='''mel'''						)






	def 			lowercase				(     self						)				->       int:




						"""simple docstring"""






						__magic_name__ :							Optional[int]		       =							torch_device

						__magic_name__ :							int		       =							SpectrogramDiffusionPipeline.from_pretrained('''google/music-spectrogram-diffusion'''						)
						__magic_name__ :							str		       =							pipe.to(lowerCamelCase						)
						pipe.set_progress_bar_config(disable=lowerCamelCase						)
						__magic_name__ :							Any		       =							MidiProcessor()

						__magic_name__ :							Optional[Any]		       =							processor(lowerCamelCase						)
						# just run two denoising loops
						__magic_name__ :							Any		       =							input_tokens[:2]

						__magic_name__ :							int		       =							torch.manual_seed(0						)
						__magic_name__ :							Any		       =							pipe(lowerCamelCase    ,					num_inference_steps=2    ,					generator=lowerCamelCase						)

						__magic_name__ :							Union[str, Any]		       =							output.audios[0]

						assert abs(np.abs(lowerCamelCase						).sum() - 3_6_1_2.8_4_1						) < 1e-1






	def 			lowercase				(     self						)				->       List[str]:




						"""simple docstring"""






						__magic_name__ :							Optional[int]		       =							torch_device

						__magic_name__ :							str		       =							SpectrogramDiffusionPipeline.from_pretrained('''google/music-spectrogram-diffusion'''						)
						__magic_name__ :							List[Any]		       =							pipe.to(lowerCamelCase						)
						pipe.set_progress_bar_config(disable=lowerCamelCase						)

						__magic_name__ :							Optional[int]		       =							MidiProcessor()

						__magic_name__ :							str		       =							processor(lowerCamelCase						)

						# just run 4 denoising loops
						__magic_name__ :							List[str]		       =							input_tokens[:4]

						__magic_name__ :							Union[str, Any]		       =							torch.manual_seed(0						)
						__magic_name__ :							Dict		       =							pipe(lowerCamelCase    ,					num_inference_steps=100    ,					generator=lowerCamelCase						)

						__magic_name__ :							Optional[int]		       =							output.audios[0]
						assert abs(np.abs(lowerCamelCase						).sum() - 9_3_8_9.1_1_1_1						) < 5e-2



