





import unittest

import torch

from diffusers import UNetaDModel
from diffusers.utils import floats_tensor, slow, torch_device

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin
class SCREAMING_SNAKE_CASE_    (       snake_case_							,					snake_case_							,					unittest.TestCase       ):
						__magic_name__:      int			   =							UNetaDModel
						__magic_name__:      List[Any]			   =							"sample"






						@property
						def UpperCAmelCase_					(   self   :   List[str]						)				->     int:







							"""simple docstring"""


							snake_case_		:      Union[str, Any]           =						4
							snake_case_		:      str           =						14
							snake_case_		:      Any           =						16

							snake_case_		:      Optional[Any]           =						floats_tensor((batch_size, num_features, seq_len)						).to(_A						)
							snake_case_		:      Dict           =						torch.tensor([10] * batch_size						).to(_A						)

							return {"sample": noise, "timestep": time_step}






						@property
						def UpperCAmelCase_					(   self   :   str						)				->     List[str]:







							"""simple docstring"""


							return (4, 14, 16)






						@property
						def UpperCAmelCase_					(   self   :   Union[str, Any]						)				->     Dict:







							"""simple docstring"""


							return (4, 14, 16)






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







							"""simple docstring"""


							pass






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







							"""simple docstring"""


							pass






						@unittest.skipIf(torch_device == 'mps'		, 'mish op not supported in MPS'						)
						def UpperCAmelCase_					(   self   :   Optional[Any]						)				->     Union[str, Any]:







							"""simple docstring"""


							super().test_determinism()






						@unittest.skipIf(torch_device == 'mps'		, 'mish op not supported in MPS'						)
						def UpperCAmelCase_					(   self   :   Optional[Any]						)				->     Any:







							"""simple docstring"""


							super().test_outputs_equivalence()






						@unittest.skipIf(torch_device == 'mps'		, 'mish op not supported in MPS'						)
						def UpperCAmelCase_					(   self   :   int						)				->     Any:







							"""simple docstring"""


							super().test_from_save_pretrained()






						@unittest.skipIf(torch_device == 'mps'		, 'mish op not supported in MPS'						)
						def UpperCAmelCase_					(   self   :   Optional[int]						)				->     Optional[int]:







							"""simple docstring"""


							super().test_from_save_pretrained_variant()






						@unittest.skipIf(torch_device == 'mps'		, 'mish op not supported in MPS'						)
						def UpperCAmelCase_					(   self   :   Any						)				->     Dict:







							"""simple docstring"""


							super().test_model_from_pretrained()






						@unittest.skipIf(torch_device == 'mps'		, 'mish op not supported in MPS'						)
						def UpperCAmelCase_					(   self   :   List[Any]						)				->     List[Any]:







							"""simple docstring"""


							super().test_output()






						def UpperCAmelCase_					(   self   :   List[str]						)				->     Optional[int]:







							"""simple docstring"""


							snake_case_		:      List[Any]           =						{
							    'block_out_channels': (32, 64, 128, 256),
							    'in_channels': 14,
							    'out_channels': 14,
							    'time_embedding_type': 'positional',
							    'use_timestep_embedding': True,
							    'flip_sin_to_cos': False,
							    'freq_shift': 1.0,
							    'out_block_type': 'OutConv1DBlock',
							    'mid_block_type': 'MidResTemporalBlock1D',
							    'down_block_types': ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D'),
							    'up_block_types': ('UpResnetBlock1D', 'UpResnetBlock1D', 'UpResnetBlock1D'),
							    'act_fn': 'mish',
							}
							snake_case_		:      Tuple           =						self.dummy_input
							return init_dict, inputs_dict






						@unittest.skipIf(torch_device == 'mps'		, 'mish op not supported in MPS'						)
						def UpperCAmelCase_					(   self   :   str						)				->     Union[str, Any]:







							"""simple docstring"""


							snake_case_    ,snake_case_		:      Optional[int]           =						UNetaDModel.from_pretrained(
							    'bglick13/hopper-medium-v2-value-function-hor32'		, output_loading_info=_A		, subfolder='unet'						)
							self.assertIsNotNone(_A						)
							self.assertEqual(len(loading_info['missing_keys']						)		, 0						)

							model.to(_A						)
							snake_case_		:      Optional[int]           =						model(**self.dummy_input						)

							assert image is not None, "Make sure output is not None"






						@unittest.skipIf(torch_device == 'mps'		, 'mish op not supported in MPS'						)
						def UpperCAmelCase_					(   self   :   Tuple						)				->     List[Any]:







							"""simple docstring"""


							snake_case_		:      Tuple           =						UNetaDModel.from_pretrained('bglick13/hopper-medium-v2-value-function-hor32'		, subfolder='unet'						)
							torch.manual_seed(0						)
							if torch.cuda.is_available():
								torch.cuda.manual_seed_all(0						)

							snake_case_		:      str           =						model.config.in_channels
							snake_case_		:      str           =						16
							snake_case_		:      List[Any]           =						torch.randn((1, seq_len, num_features)						).permute(
							    0		, 2		, 1						)  # match original, we can update values and remove
							snake_case_		:      Tuple           =						torch.full((num_features,)		, 0						)

							with torch.no_grad():
								snake_case_		:      Tuple           =						model(_A		, _A						).sample.permute(0		, 2		, 1						)

							snake_case_		:      List[Any]           =						output[0, -3:, -3:].flatten()
							# fmt: off
							snake_case_		:      str           =						torch.tensor([-2.1_3_7_1_7_2, 1.1_4_2_6_0_1_6, 0.3_6_8_8_6_8_7, -0.7_6_6_9_2_2, 0.7_3_0_3_1_4_6, 0.1_1_0_3_8_8_6_4, -0.4_7_6_0_6_3_3, 0.1_3_2_7_0_1_7_2, 0.0_2_5_9_1_3_4_8]						)
							# fmt: on
							self.assertTrue(torch.allclose(_A		, _A		, rtol=1E-3						)						)






						def UpperCAmelCase_					(   self   :   List[Any]						)				->     Optional[int]:







							"""simple docstring"""


							pass






						@slow
						def UpperCAmelCase_					(   self   :   int						)				->     Optional[Any]:







							"""simple docstring"""


							snake_case_		:      List[Any]           =						'harmonai/maestro-150k'
							snake_case_		:      Dict           =						UNetaDModel.from_pretrained(_A		, subfolder='unet'						)
							model.to(_A						)

							snake_case_		:      int           =						65536
							snake_case_		:      Optional[Any]           =						torch.sin(torch.arange(_A						)[None, None, :].repeat(1		, 2		, 1						)						).to(_A						)
							snake_case_		:      Optional[Any]           =						torch.tensor([1]						).to(_A						)

							with torch.no_grad():
								snake_case_		:      Any           =						model(_A		, _A						).sample

							snake_case_		:      int           =						output.abs().sum()
							snake_case_		:      Optional[Any]           =						output.abs().max()

							assert (output_sum - 2_2_4.0_8_9_6).abs() < 0.5
							assert (output_max - 0.0_6_0_7).abs() < 4E-4
class SCREAMING_SNAKE_CASE_    (       snake_case_							,					snake_case_							,					unittest.TestCase       ):
						__magic_name__:      str			   =							UNetaDModel
						__magic_name__:      str			   =							"sample"






						@property
						def UpperCAmelCase_					(   self   :   Any						)				->     Dict:







							"""simple docstring"""


							snake_case_		:      Dict           =						4
							snake_case_		:      str           =						14
							snake_case_		:      int           =						16

							snake_case_		:      int           =						floats_tensor((batch_size, num_features, seq_len)						).to(_A						)
							snake_case_		:      Tuple           =						torch.tensor([10] * batch_size						).to(_A						)

							return {"sample": noise, "timestep": time_step}






						@property
						def UpperCAmelCase_					(   self   :   List[Any]						)				->     Optional[int]:







							"""simple docstring"""


							return (4, 14, 16)






						@property
						def UpperCAmelCase_					(   self   :   Tuple						)				->     Tuple:







							"""simple docstring"""


							return (4, 14, 1)






						@unittest.skipIf(torch_device == 'mps'		, 'mish op not supported in MPS'						)
						def UpperCAmelCase_					(   self   :   Optional[Any]						)				->     List[Any]:







							"""simple docstring"""


							super().test_determinism()






						@unittest.skipIf(torch_device == 'mps'		, 'mish op not supported in MPS'						)
						def UpperCAmelCase_					(   self   :   Optional[int]						)				->     int:







							"""simple docstring"""


							super().test_outputs_equivalence()






						@unittest.skipIf(torch_device == 'mps'		, 'mish op not supported in MPS'						)
						def UpperCAmelCase_					(   self   :   List[Any]						)				->     Any:







							"""simple docstring"""


							super().test_from_save_pretrained()






						@unittest.skipIf(torch_device == 'mps'		, 'mish op not supported in MPS'						)
						def UpperCAmelCase_					(   self   :   Optional[int]						)				->     List[Any]:







							"""simple docstring"""


							super().test_from_save_pretrained_variant()






						@unittest.skipIf(torch_device == 'mps'		, 'mish op not supported in MPS'						)
						def UpperCAmelCase_					(   self   :   Any						)				->     str:







							"""simple docstring"""


							super().test_model_from_pretrained()






						@unittest.skipIf(torch_device == 'mps'		, 'mish op not supported in MPS'						)
						def UpperCAmelCase_					(   self   :   List[str]						)				->     List[Any]:







							"""simple docstring"""


							snake_case_    ,snake_case_		:      List[str]           =						self.prepare_init_args_and_inputs_for_common()
							snake_case_		:      List[str]           =						self.model_class(**_A						)
							model.to(_A						)
							model.eval()

							with torch.no_grad():
								snake_case_		:      Optional[Any]           =						model(**_A						)

								if isinstance(_A		, _A						):
									snake_case_		:      Any           =						output.sample

							self.assertIsNotNone(_A						)
							snake_case_		:      Any           =						torch.Size((inputs_dict['sample'].shape[0], 1)						)
							self.assertEqual(output.shape		, _A		, 'Input and output shapes do not match'						)






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







							"""simple docstring"""


							pass






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







							"""simple docstring"""


							pass






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







							"""simple docstring"""


							snake_case_		:      int           =						{
							    'in_channels': 14,
							    'out_channels': 14,
							    'down_block_types': ['DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D'],
							    'up_block_types': [],
							    'out_block_type': 'ValueFunction',
							    'mid_block_type': 'ValueFunctionMidBlock1D',
							    'block_out_channels': [32, 64, 128, 256],
							    'layers_per_block': 1,
							    'downsample_each_block': True,
							    'use_timestep_embedding': True,
							    'freq_shift': 1.0,
							    'flip_sin_to_cos': False,
							    'time_embedding_type': 'positional',
							    'act_fn': 'mish',
							}
							snake_case_		:      Optional[int]           =						self.dummy_input
							return init_dict, inputs_dict






						@unittest.skipIf(torch_device == 'mps'		, 'mish op not supported in MPS'						)
						def UpperCAmelCase_					(   self   :   List[str]						)				->     Any:







							"""simple docstring"""


							snake_case_    ,snake_case_		:      List[Any]           =						UNetaDModel.from_pretrained(
							    'bglick13/hopper-medium-v2-value-function-hor32'		, output_loading_info=_A		, subfolder='value_function'						)
							self.assertIsNotNone(_A						)
							self.assertEqual(len(vf_loading_info['missing_keys']						)		, 0						)

							value_function.to(_A						)
							snake_case_		:      str           =						value_function(**self.dummy_input						)

							assert image is not None, "Make sure output is not None"






						@unittest.skipIf(torch_device == 'mps'		, 'mish op not supported in MPS'						)
						def UpperCAmelCase_					(   self   :   str						)				->     Optional[int]:







							"""simple docstring"""


							snake_case_    ,snake_case_		:      Optional[Any]           =						UNetaDModel.from_pretrained(
							    'bglick13/hopper-medium-v2-value-function-hor32'		, output_loading_info=_A		, subfolder='value_function'						)
							torch.manual_seed(0						)
							if torch.cuda.is_available():
								torch.cuda.manual_seed_all(0						)

							snake_case_		:      Tuple           =						value_function.config.in_channels
							snake_case_		:      str           =						14
							snake_case_		:      int           =						torch.randn((1, seq_len, num_features)						).permute(
							    0		, 2		, 1						)  # match original, we can update values and remove
							snake_case_		:      str           =						torch.full((num_features,)		, 0						)

							with torch.no_grad():
								snake_case_		:      Tuple           =						value_function(_A		, _A						).sample

							# fmt: off
							snake_case_		:      str           =						torch.tensor([1_6_5.2_5] * seq_len						)
							# fmt: on
							self.assertTrue(torch.allclose(_A		, _A		, rtol=1E-3						)						)






						def UpperCAmelCase_					(   self   :   str						)				->     Optional[int]:







							"""simple docstring"""


							pass


'''simple docstring'''

import argparse

import torch
from saprl.hub import distilhubert

from transformers import HubertConfig, HubertModel, WavaVecaFeatureExtractor, logging


logging.set_verbosity_info()
lowerCAmelCase_			:			List[str]    	=   logging.get_logger(__name__)

lowerCAmelCase_			:			Optional[Any]    	=   {
    "post_extract_proj": "feature_projection.projection",
    "encoder.pos_conv.0": "encoder.pos_conv_embed.conv",
    "self_attn.k_proj": "encoder.layers.*.attention.k_proj",
    "self_attn.v_proj": "encoder.layers.*.attention.v_proj",
    "self_attn.q_proj": "encoder.layers.*.attention.q_proj",
    "self_attn.out_proj": "encoder.layers.*.attention.out_proj",
    "self_attn_layer_norm": "encoder.layers.*.layer_norm",
    "fc1": "encoder.layers.*.feed_forward.intermediate_dense",
    "fc2": "encoder.layers.*.feed_forward.output_dense",
    "final_layer_norm": "encoder.layers.*.final_layer_norm",
    "encoder.layer_norm": "encoder.layer_norm",
    "mask_emb": "masked_spec_embed",
}


def __a			(						__lowerCamelCase      :    Dict			,		__lowerCamelCase      :    Optional[int]			,		__lowerCamelCase      :    str			,		__lowerCamelCase      :    int			,		__lowerCamelCase      :    Union[str, Any]					)						->				Optional[Any]:
      '''simple docstring'''


      for attribute in key.split("."					):
            lowercase_     			=   getattr(__lowerCamelCase			,		__lowerCamelCase					)

      if weight_type is not None:
            lowercase_     			=   getattr(__lowerCamelCase			,		__lowerCamelCase					).shape
      else:
            lowercase_     			=   hf_pointer.shape

      assert hf_shape == value.shape, (
          f'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be'
          f' {value.shape} for {full_name}'
      )

      if weight_type == "weight":
            lowercase_     			=   value
      elif weight_type == "weight_g":
            lowercase_     			=   value
      elif weight_type == "weight_v":
            lowercase_     			=   value
      elif weight_type == "bias":
            lowercase_     			=   value
      else:
            lowercase_     			=   value

      logger.info(f'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.'					)


def __a			(						__lowerCamelCase      :    List[str]			,		__lowerCamelCase      :    Optional[int]					)						->				List[Any]:
      '''simple docstring'''


      lowercase_     			=   []
      lowercase_     			=   fairseq_model.state_dict()

      lowercase_     			=   hf_model.feature_extractor

      for name, value in fairseq_dict.items():
            lowercase_     			=   False
            if "conv_layers" in name:
                  load_conv_layer(
                      __lowerCamelCase			,		__lowerCamelCase			,		__lowerCamelCase			,		__lowerCamelCase			,		hf_model.config.feat_extract_norm == "group"			,		)
                  lowercase_     			=   True
            else:
                  for key, mapped_key in MAPPING.items():
                        lowercase_     			=   mapped_key

                        if key in name:
                              lowercase_     			=   True
                              if "*" in mapped_key:
                                    lowercase_     			=   name.split(__lowerCamelCase					)[0].split("."					)[-2]
                                    lowercase_     			=   mapped_key.replace("*"			,		__lowerCamelCase					)
                              if "weight_g" in name:
                                    lowercase_     			=   "weight_g"
                              elif "weight_v" in name:
                                    lowercase_     			=   "weight_v"
                              elif "weight" in name:
                                    lowercase_     			=   "weight"
                              elif "bias" in name:
                                    lowercase_     			=   "bias"
                              else:
                                    lowercase_     			=   None
                              set_recursively(__lowerCamelCase			,		__lowerCamelCase			,		__lowerCamelCase			,		__lowerCamelCase			,		__lowerCamelCase					)
                        continue
            if not is_used:
                  unused_weights.append(__lowerCamelCase					)

      logger.warning(f'Unused weights: {unused_weights}'					)


def __a			(						__lowerCamelCase      :    Any			,		__lowerCamelCase      :    Optional[int]			,		__lowerCamelCase      :    List[str]			,		__lowerCamelCase      :    List[str]			,		__lowerCamelCase      :    Optional[Any]					)						->				Tuple:
      '''simple docstring'''


      lowercase_     			=   full_name.split("conv_layers."					)[-1]
      lowercase_     			=   name.split("."					)
      lowercase_     			=   int(items[0]					)
      lowercase_     			=   int(items[1]					)

      if type_id == 0:
            if "bias" in name:
                  assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
                      f'{full_name} has size {value.shape}, but'
                      f' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.'
                  )
                  lowercase_     			=   value
                  logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.'					)
            elif "weight" in name:
                  assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
                      f'{full_name} has size {value.shape}, but'
                      f' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.'
                  )
                  lowercase_     			=   value
                  logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.'					)
      elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
            if "bias" in name:
                  assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
                      f'{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was'
                      " found."
                  )
                  lowercase_     			=   value
                  logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'					)
            elif "weight" in name:
                  assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
                      f'{full_name} has size {value.shape}, but'
                      f' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.'
                  )
                  lowercase_     			=   value
                  logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'					)
      else:
            unused_weights.append(__lowerCamelCase					)


def __a			(						__lowerCamelCase      :    Optional[int]					)						->				Dict:
      '''simple docstring'''


      lowercase_     			=   HubertConfig()
      lowercase_     			=   model.config

      lowercase_     			=   fs_config.activation_dropout
      lowercase_     			=   False
      lowercase_     			=   fs_config.attention_dropout
      lowercase_     			=   False
      lowercase_     			=   eval(fs_config.extractor_conv_feature_layers					)
      lowercase_     			=   [x[0] for x in conv_layers]
      lowercase_     			=   [x[1] for x in conv_layers]
      lowercase_     			=   [x[2] for x in conv_layers]
      lowercase_     			=   "gelu"
      lowercase_     			=   "layer" if fs_config.extractor_mode == "layer_norm" else "group"
      lowercase_     			=   False
      lowercase_     			=   0.0
      lowercase_     			=   0.0
      lowercase_     			=   fs_config.activation_fn
      lowercase_     			=   fs_config.dropout
      lowercase_     			=   fs_config.encoder_embed_dim
      lowercase_     			=   0.0_2
      lowercase_     			=   fs_config.encoder_ffn_embed_dim
      lowercase_     			=   1e-5
      lowercase_     			=   0.0
      lowercase_     			=   fs_config.encoder_attention_heads
      lowercase_     			=   fs_config.conv_pos_groups
      lowercase_     			=   fs_config.conv_pos
      lowercase_     			=   len(__lowerCamelCase					)
      lowercase_     			=   fs_config.encoder_layers

      return config


@torch.no_grad()
def __a			(						__lowerCamelCase      :    Optional[Any]			,		__lowerCamelCase      :    Any=None					)						->				Any:
      '''simple docstring'''


      lowercase_     			=   distilhubert().model.model

      if config_path is not None:
            lowercase_     			=   HubertConfig.from_pretrained(__lowerCamelCase					)
      else:
            lowercase_     			=   convert_config(__lowerCamelCase					)
      lowercase_     			=   model.eval()

      lowercase_     			=   WavaVecaFeatureExtractor(
          feature_size=1			,		sampling_rate=16_000			,		padding_value=0			,		do_normalize=__lowerCamelCase			,		return_attention_mask=__lowerCamelCase			,		)
      lowercase_     			=   HubertModel(__lowerCamelCase					)

      recursively_load_weights(__lowerCamelCase			,		__lowerCamelCase					)

      feature_extractor.save_pretrained(__lowerCamelCase					)
      hf_model.save_pretrained(__lowerCamelCase					)


if __name__ == "__main__":
       lowerCAmelCase_			:			str    	=   argparse.ArgumentParser()
       parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
       parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
       lowerCAmelCase_			:			str    	=   parser.parse_args()
       convert_hubert_checkpoint(args.pytorch_dump_folder_path, args.config_path)






