





"""simple docstring"""
from typing import Tuple, Union

from ...modeling_outputs import BackboneOutput
from ...modeling_utils import PreTrainedModel
from ...utils import is_timm_available, is_torch_available, requires_backends
from ...utils.backbone_utils import BackboneMixin
from .configuration_timm_backbone import TimmBackboneConfig


if is_timm_available():
       import timm


if is_torch_available():
       from torch import Tensor







class       a							(   a__   , a__  ):
 snake_case__             =       '''pixel_values'''
 snake_case__             =       False
 snake_case__             =       TimmBackboneConfig



 def __init__(     self				,       _snake_case				,       **_snake_case     ):







  """simple docstring"""






  requires_backends(self				,       'timm'     )
  super().__init__(_snake_case     )
  lowerCAmelCase    				= config

  if config.backbone is None:
   raise ValueError('backbone is not set in the config. Please set it to a timm model name.'     )

  if config.backbone not in timm.list_models():
   raise ValueError(F'backbone {config.backbone} is not supported by timm.'     )

  if hasattr(_snake_case				,       'out_features'     ) and config.out_features is not None:
   raise ValueError('out_features is not supported by TimmBackbone. Please use out_indices instead.'     )

  lowerCAmelCase    				= getattr(_snake_case				,       'use_pretrained_backbone'				,       _snake_case     )
  if pretrained is None:
   raise ValueError('use_pretrained_backbone is not set in the config. Please set it to True or False.'     )

  # We just take the final layer by default. This matches the default for the transformers models.
  lowerCAmelCase    				= config.out_indices if getattr(_snake_case				,       'out_indices'				,       _snake_case     ) is not None else (-1,)

  lowerCAmelCase    				= timm.create_model(
      config.backbone				,       pretrained=_snake_case				,       features_only=config.features_only				,       in_chans=config.num_channels				,       out_indices=_snake_case				,       **_snake_case				,       )
  # These are used to control the output of the model when called. If output_hidden_states is True, then
  # return_layers is modified to include all layers.
  lowerCAmelCase    				= self._backbone.return_layers
  lowerCAmelCase    				= {layer['module']: str(_snake_case     ) for i, layer in enumerate(self._backbone.feature_info.info     )}
  super()._init_backbone(_snake_case     )



 @classmethod
 def    UpperCamelCase__  (     cls				,       _snake_case				,       *_snake_case				,       **_snake_case     ):







  """simple docstring"""






  requires_backends(cls				,       ['vision', 'timm']     )
  from ...models.timm_backbone import TimmBackboneConfig

  lowerCAmelCase    				= kwargs.pop('config'				,       TimmBackboneConfig()     )

  lowerCAmelCase    				= kwargs.pop('use_timm_backbone'				,       _snake_case     )
  if not use_timm:
   raise ValueError('use_timm_backbone must be True for timm backbones'     )

  lowerCAmelCase    				= kwargs.pop('num_channels'				,       config.num_channels     )
  lowerCAmelCase    				= kwargs.pop('features_only'				,       config.features_only     )
  lowerCAmelCase    				= kwargs.pop('use_pretrained_backbone'				,       config.use_pretrained_backbone     )
  lowerCAmelCase    				= kwargs.pop('out_indices'				,       config.out_indices     )
  lowerCAmelCase    				= TimmBackboneConfig(
      backbone=_snake_case				,       num_channels=_snake_case				,       features_only=_snake_case				,       use_pretrained_backbone=_snake_case				,       out_indices=_snake_case				,       )
  return super()._from_config(_snake_case				,       **_snake_case     )



 def    UpperCamelCase__  (     self				,       _snake_case     ):







  """simple docstring"""






  pass



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case=None				,       _snake_case=None				,       _snake_case=None				,       **_snake_case     ):







  """simple docstring"""






  lowerCAmelCase    				= return_dict if return_dict is not None else self.config.use_return_dict
  lowerCAmelCase    				= (
      output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  )
  lowerCAmelCase    				= output_attentions if output_attentions is not None else self.config.output_attentions

  if output_attentions:
   raise ValueError('Cannot output attentions for timm backbones at the moment'     )

  if output_hidden_states:
   # We modify the return layers to include all the stages of the backbone
   lowerCAmelCase    				= self._all_layers
   lowerCAmelCase    				= self._backbone(_snake_case				,       **_snake_case     )
   lowerCAmelCase    				= self._return_layers
   lowerCAmelCase    				= tuple(hidden_states[i] for i in self.out_indices     )
  else:
   lowerCAmelCase    				= self._backbone(_snake_case				,       **_snake_case     )
   lowerCAmelCase    				= None

  lowerCAmelCase    				= tuple(_snake_case     )
  lowerCAmelCase    				= tuple(_snake_case     ) if hidden_states is not None else None

  if not return_dict:
   lowerCAmelCase    				= (feature_maps,)
   if output_hidden_states:
    lowerCAmelCase    				= output + (hidden_states,)
   return output

  return BackboneOutput(feature_maps=_snake_case				,       hidden_states=_snake_case				,       attentions=_snake_case     )












"""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       a							(   a__   , unittest.TestCase  ):
 snake_case__             =       DanceDiffusionPipeline
 snake_case__             =       UNCONDITIONAL_AUDIO_GENERATION_PARAMS
 snake_case__             =       PipelineTesterMixin.required_optional_params - {
     '''callback''',
     '''latents''',
     '''callback_steps''',
     '''output_type''',
     '''num_images_per_prompt''',
 }
 snake_case__             =       UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS
 snake_case__             =       False
 snake_case__             =       False



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  torch.manual_seed(0     )
  lowerCAmelCase    				= UNetaDModel(
      block_out_channels=(32, 32, 64)				,       extra_in_channels=16				,       sample_size=5_12				,       sample_rate=1_60_00				,       in_channels=2				,       out_channels=2				,       flip_sin_to_cos=_snake_case				,       use_timestep_embedding=_snake_case				,       time_embedding_type='fourier'				,       mid_block_type='UNetMidBlock1D'				,       down_block_types=('DownBlock1DNoSkip', 'DownBlock1D', 'AttnDownBlock1D')				,       up_block_types=('AttnUpBlock1D', 'UpBlock1D', 'UpBlock1DNoSkip')				,       )
  lowerCAmelCase    				= IPNDMScheduler()

  lowerCAmelCase    				= {
      'unet': unet,
      'scheduler': scheduler,
  }
  return components



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case=0     ):







  """simple docstring"""






  if str(_snake_case     ).startswith('mps'     ):
   lowerCAmelCase    				= torch.manual_seed(_snake_case     )
  else:
   lowerCAmelCase    				= torch.Generator(device=_snake_case     ).manual_seed(_snake_case     )
  lowerCAmelCase    				= {
      'batch_size': 1,
      'generator': generator,
      'num_inference_steps': 4,
  }
  return inputs



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= 'cpu'  # ensure determinism for the device-dependent torch.Generator
  lowerCAmelCase    				= self.get_dummy_components()
  lowerCAmelCase    				= DanceDiffusionPipeline(**_snake_case     )
  lowerCAmelCase    				= pipe.to(_snake_case     )
  pipe.set_progress_bar_config(disable=_snake_case     )

  lowerCAmelCase    				= self.get_dummy_inputs(_snake_case     )
  lowerCAmelCase    				= pipe(**_snake_case     )
  lowerCAmelCase    				= output.audios

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

  assert audio.shape == (1, 2, components["unet"].sample_size)
  lowerCAmelCase    				= np.array([-0.7_265, 1.0_000, -0.8_388, 0.1_175, 0.9_498, -1.0_000]     )
  assert np.abs(audio_slice.flatten() - expected_slice     ).max() < 1E-2



 @skip_mps
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  return super().test_save_load_local()



 @skip_mps
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3     )



 @skip_mps
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  return super().test_save_load_optional_components()



 @skip_mps
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  return super().test_attention_slicing_forward_pass()



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  super().test_inference_batch_single_identical(expected_max_diff=3E-3     )







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



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






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



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= torch_device

  lowerCAmelCase    				= DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k'     )
  lowerCAmelCase    				= pipe.to(_snake_case     )
  pipe.set_progress_bar_config(disable=_snake_case     )

  lowerCAmelCase    				= torch.manual_seed(0     )
  lowerCAmelCase    				= pipe(generator=_snake_case				,       num_inference_steps=1_00				,       audio_length_in_s=4.096     )
  lowerCAmelCase    				= output.audios

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

  assert audio.shape == (1, 2, pipe.unet.sample_size)
  lowerCAmelCase    				= np.array([-0.0_192, -0.0_231, -0.0_318, -0.0_059, 0.0_002, -0.0_020]     )

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



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= torch_device

  lowerCAmelCase    				= DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k'				,       torch_dtype=torch.floataa     )
  lowerCAmelCase    				= pipe.to(_snake_case     )
  pipe.set_progress_bar_config(disable=_snake_case     )

  lowerCAmelCase    				= torch.manual_seed(0     )
  lowerCAmelCase    				= pipe(generator=_snake_case				,       num_inference_steps=1_00				,       audio_length_in_s=4.096     )
  lowerCAmelCase    				= output.audios

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

  assert audio.shape == (1, 2, pipe.unet.sample_size)
  lowerCAmelCase    				= np.array([-0.0_367, -0.0_488, -0.0_771, -0.0_525, -0.0_444, -0.0_341]     )

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





