






"""simple docstring"""



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 			a	(  a_,							a_,							unittest.TestCase      ):
    UpperCAmelCase_					:	Tuple      	=UNetaDModel
    UpperCAmelCase_					:	Optional[int]      	="sample"







    @property
    def      UpperCamelCase_ (     self			):
      lowercase				       =			4
      lowercase				       =			1_4
      lowercase				       =			1_6

      lowercase				       =			floats_tensor((batch_size, num_features, seq_len)			).to(_lowerCamelCase			)
      lowercase				       =			torch.tensor([1_0] * batch_size			).to(_lowerCamelCase			)

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







    @property
    def      UpperCamelCase_ (     self			):
      return (4, 1_4, 1_6)







    @property
    def      UpperCamelCase_ (     self			):
      return (4, 1_4, 1_6)







    def      UpperCamelCase_ (     self			):
      pass







    def      UpperCamelCase_ (     self			):
      pass







    @unittest.skipIf(torch_device == 'mps'				,						'mish op not supported in MPS'			)
    def      UpperCamelCase_ (     self			):
      super().test_determinism()







    @unittest.skipIf(torch_device == 'mps'				,						'mish op not supported in MPS'			)
    def      UpperCamelCase_ (     self			):
      super().test_outputs_equivalence()







    @unittest.skipIf(torch_device == 'mps'				,						'mish op not supported in MPS'			)
    def      UpperCamelCase_ (     self			):
      super().test_from_save_pretrained()







    @unittest.skipIf(torch_device == 'mps'				,						'mish op not supported in MPS'			)
    def      UpperCamelCase_ (     self			):
      super().test_from_save_pretrained_variant()







    @unittest.skipIf(torch_device == 'mps'				,						'mish op not supported in MPS'			)
    def      UpperCamelCase_ (     self			):
      super().test_model_from_pretrained()







    @unittest.skipIf(torch_device == 'mps'				,						'mish op not supported in MPS'			)
    def      UpperCamelCase_ (     self			):
      super().test_output()







    def      UpperCamelCase_ (     self			):
      lowercase				       =			{
          'block_out_channels': (3_2, 6_4, 1_2_8, 2_5_6),
          'in_channels': 1_4,
          'out_channels': 1_4,
          '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',
      }
      lowercase				       =			self.dummy_input
      return init_dict, inputs_dict







    @unittest.skipIf(torch_device == 'mps'				,						'mish op not supported in MPS'			)
    def      UpperCamelCase_ (     self			):
      lowercase       ,	lowercase				       =			UNetaDModel.from_pretrained(
          'bglick13/hopper-medium-v2-value-function-hor32'				,						output_loading_info=_lowerCamelCase				,						subfolder='unet'			)
      self.assertIsNotNone(_lowerCamelCase			)
      self.assertEqual(len(loading_info['missing_keys']			)				,						0			)

      model.to(_lowerCamelCase			)
      lowercase				       =			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			):
      lowercase				       =			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			)

      lowercase				       =			model.config.in_channels
      lowercase				       =			1_6
      lowercase				       =			torch.randn((1, seq_len, num_features)			).permute(
          0				,						2				,						1			)  # match original, we can update values and remove
      lowercase				       =			torch.full((num_features,)				,						0			)

      with torch.no_grad():
        lowercase				       =			model(_lowerCamelCase				,						_lowerCamelCase			).sample.permute(0				,						2				,						1			)

      lowercase				       =			output[0, -3:, -3:].flatten()
      # fmt: off
      lowercase				       =			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(_lowerCamelCase				,						_lowerCamelCase				,						rtol=1e-3			)			)







    def      UpperCamelCase_ (     self			):
      # Not implemented yet for this UNet
      pass







    @slow
    def      UpperCamelCase_ (     self			):
      lowercase				       =			'harmonai/maestro-150k'
      lowercase				       =			UNetaDModel.from_pretrained(_lowerCamelCase				,						subfolder='unet'			)
      model.to(_lowerCamelCase			)

      lowercase				       =			6_5_5_3_6
      lowercase				       =			torch.sin(torch.arange(_lowerCamelCase			)[None, None, :].repeat(1				,						2				,						1			)			).to(_lowerCamelCase			)
      lowercase				       =			torch.tensor([1]			).to(_lowerCamelCase			)

      with torch.no_grad():
        lowercase				       =			model(_lowerCamelCase				,						_lowerCamelCase			).sample

      lowercase				       =			output.abs().sum()
      lowercase				       =			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 			a	(  a_,							a_,							unittest.TestCase      ):
    UpperCAmelCase_					:	Dict      	=UNetaDModel
    UpperCAmelCase_					:	str      	="sample"







    @property
    def      UpperCamelCase_ (     self			):
      lowercase				       =			4
      lowercase				       =			1_4
      lowercase				       =			1_6

      lowercase				       =			floats_tensor((batch_size, num_features, seq_len)			).to(_lowerCamelCase			)
      lowercase				       =			torch.tensor([1_0] * batch_size			).to(_lowerCamelCase			)

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







    @property
    def      UpperCamelCase_ (     self			):
      return (4, 1_4, 1_6)







    @property
    def      UpperCamelCase_ (     self			):
      return (4, 1_4, 1)







    @unittest.skipIf(torch_device == 'mps'				,						'mish op not supported in MPS'			)
    def      UpperCamelCase_ (     self			):
      super().test_determinism()







    @unittest.skipIf(torch_device == 'mps'				,						'mish op not supported in MPS'			)
    def      UpperCamelCase_ (     self			):
      super().test_outputs_equivalence()







    @unittest.skipIf(torch_device == 'mps'				,						'mish op not supported in MPS'			)
    def      UpperCamelCase_ (     self			):
      super().test_from_save_pretrained()







    @unittest.skipIf(torch_device == 'mps'				,						'mish op not supported in MPS'			)
    def      UpperCamelCase_ (     self			):
      super().test_from_save_pretrained_variant()







    @unittest.skipIf(torch_device == 'mps'				,						'mish op not supported in MPS'			)
    def      UpperCamelCase_ (     self			):
      super().test_model_from_pretrained()







    @unittest.skipIf(torch_device == 'mps'				,						'mish op not supported in MPS'			)
    def      UpperCamelCase_ (     self			):
      # UNetRL is a value-function is different output shape
      lowercase       ,	lowercase				       =			self.prepare_init_args_and_inputs_for_common()
      lowercase				       =			self.model_class(**_lowerCamelCase			)
      model.to(_lowerCamelCase			)
      model.eval()

      with torch.no_grad():
        lowercase				       =			model(**_lowerCamelCase			)

        if isinstance(_lowerCamelCase				,						_lowerCamelCase			):
          lowercase				       =			output.sample

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







    def      UpperCamelCase_ (     self			):
      pass







    def      UpperCamelCase_ (     self			):
      pass







    def      UpperCamelCase_ (     self			):
      lowercase				       =			{
          'in_channels': 1_4,
          'out_channels': 1_4,
          'down_block_types': ['DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D'],
          'up_block_types': [],
          'out_block_type': 'ValueFunction',
          'mid_block_type': 'ValueFunctionMidBlock1D',
          'block_out_channels': [3_2, 6_4, 1_2_8, 2_5_6],
          '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',
      }
      lowercase				       =			self.dummy_input
      return init_dict, inputs_dict







    @unittest.skipIf(torch_device == 'mps'				,						'mish op not supported in MPS'			)
    def      UpperCamelCase_ (     self			):
      lowercase       ,	lowercase				       =			UNetaDModel.from_pretrained(
          'bglick13/hopper-medium-v2-value-function-hor32'				,						output_loading_info=_lowerCamelCase				,						subfolder='value_function'			)
      self.assertIsNotNone(_lowerCamelCase			)
      self.assertEqual(len(vf_loading_info['missing_keys']			)				,						0			)

      value_function.to(_lowerCamelCase			)
      lowercase				       =			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			):
      lowercase       ,	lowercase				       =			UNetaDModel.from_pretrained(
          'bglick13/hopper-medium-v2-value-function-hor32'				,						output_loading_info=_lowerCamelCase				,						subfolder='value_function'			)
      torch.manual_seed(0			)
      if torch.cuda.is_available():
        torch.cuda.manual_seed_all(0			)

      lowercase				       =			value_function.config.in_channels
      lowercase				       =			1_4
      lowercase				       =			torch.randn((1, seq_len, num_features)			).permute(
          0				,						2				,						1			)  # match original, we can update values and remove
      lowercase				       =			torch.full((num_features,)				,						0			)

      with torch.no_grad():
        lowercase				       =			value_function(_lowerCamelCase				,						_lowerCamelCase			).sample

      # fmt: off
      lowercase				       =			torch.tensor([1_6_5.2_5] * seq_len			)
      # fmt: on
      self.assertTrue(torch.allclose(_lowerCamelCase				,						_lowerCamelCase				,						rtol=1e-3			)			)







    def      UpperCamelCase_ (     self			):
      # Not implemented yet for this UNet
      pass










"""simple docstring"""



import json
import os
import shutil
import tempfile
import unittest

from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor
from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES
from transformers.utils import FEATURE_EXTRACTOR_NAME

from .test_feature_extraction_wavaveca import floats_list

class 			a	(  unittest.TestCase      ):







    def      UpperCamelCase_ (     self			):
      lowercase				       =			'<pad> <s> </s> <unk> | E T A O N I H S R D L U M W C F G Y P B V K \' X J Q Z'.split(' '			)
      lowercase				       =			dict(zip(_lowerCamelCase				,						range(len(_lowerCamelCase			)			)			)			)

      lowercase				       =			{
          'pad_token': '<pad>',
          'unk_token': '<unk>',
          'bos_token': '<s>',
          'eos_token': '</s>',
      }
      lowercase				       =			{
          'feature_size': 1,
          'padding_value': 0.0,
          'sampling_rate': 1_6_0_0_0,
          'return_attention_mask': False,
          'do_normalize': True,
      }

      lowercase				       =			tempfile.mkdtemp()
      lowercase				       =			os.path.join(self.tmpdirname				,						VOCAB_FILES_NAMES['vocab_file']			)
      lowercase				       =			os.path.join(self.tmpdirname				,						_lowerCamelCase			)
      with open(self.vocab_file				,						'w'				,						encoding='utf-8'			) as fp:
        fp.write(json.dumps(_lowerCamelCase			) + '\n'			)

      with open(self.feature_extraction_file				,						'w'				,						encoding='utf-8'			) as fp:
        fp.write(json.dumps(_lowerCamelCase			) + '\n'			)







    def      UpperCamelCase_ (     self				,						**_lowerCamelCase			):
      lowercase				       =			self.add_kwargs_tokens_map.copy()
      kwargs.update(_lowerCamelCase			)
      return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname				,						**_lowerCamelCase			)







    def      UpperCamelCase_ (     self				,						**_lowerCamelCase			):
      return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname				,						**_lowerCamelCase			)







    def      UpperCamelCase_ (     self			):
      shutil.rmtree(self.tmpdirname			)







    def      UpperCamelCase_ (     self			):
      lowercase				       =			self.get_tokenizer()
      lowercase				       =			self.get_feature_extractor()

      lowercase				       =			WavaVecaProcessor(tokenizer=_lowerCamelCase				,						feature_extractor=_lowerCamelCase			)

      processor.save_pretrained(self.tmpdirname			)
      lowercase				       =			WavaVecaProcessor.from_pretrained(self.tmpdirname			)

      self.assertEqual(processor.tokenizer.get_vocab()				,						tokenizer.get_vocab()			)
      self.assertIsInstance(processor.tokenizer				,						_lowerCamelCase			)

      self.assertEqual(processor.feature_extractor.to_json_string()				,						feature_extractor.to_json_string()			)
      self.assertIsInstance(processor.feature_extractor				,						_lowerCamelCase			)







    def      UpperCamelCase_ (     self			):
      lowercase				       =			WavaVecaProcessor(tokenizer=self.get_tokenizer()				,						feature_extractor=self.get_feature_extractor()			)
      processor.save_pretrained(self.tmpdirname			)

      lowercase				       =			self.get_tokenizer(bos_token='(BOS)'				,						eos_token='(EOS)'			)
      lowercase				       =			self.get_feature_extractor(do_normalize=_lowerCamelCase				,						padding_value=1.0			)

      lowercase				       =			WavaVecaProcessor.from_pretrained(
          self.tmpdirname				,						bos_token='(BOS)'				,						eos_token='(EOS)'				,						do_normalize=_lowerCamelCase				,						padding_value=1.0			)

      self.assertEqual(processor.tokenizer.get_vocab()				,						tokenizer_add_kwargs.get_vocab()			)
      self.assertIsInstance(processor.tokenizer				,						_lowerCamelCase			)

      self.assertEqual(processor.feature_extractor.to_json_string()				,						feature_extractor_add_kwargs.to_json_string()			)
      self.assertIsInstance(processor.feature_extractor				,						_lowerCamelCase			)







    def      UpperCamelCase_ (     self			):
      lowercase				       =			self.get_feature_extractor()
      lowercase				       =			self.get_tokenizer()

      lowercase				       =			WavaVecaProcessor(tokenizer=_lowerCamelCase				,						feature_extractor=_lowerCamelCase			)

      lowercase				       =			floats_list((3, 1_0_0_0)			)

      lowercase				       =			feature_extractor(_lowerCamelCase				,						return_tensors='np'			)
      lowercase				       =			processor(_lowerCamelCase				,						return_tensors='np'			)

      for key in input_feat_extract.keys():
        self.assertAlmostEqual(input_feat_extract[key].sum()				,						input_processor[key].sum()				,						delta=1e-2			)







    def      UpperCamelCase_ (     self			):
      lowercase				       =			self.get_feature_extractor()
      lowercase				       =			self.get_tokenizer()

      lowercase				       =			WavaVecaProcessor(tokenizer=_lowerCamelCase				,						feature_extractor=_lowerCamelCase			)

      lowercase				       =			'This is a test string'

      lowercase				       =			processor(text=_lowerCamelCase			)

      lowercase				       =			tokenizer(_lowerCamelCase			)

      for key in encoded_tok.keys():
        self.assertListEqual(encoded_tok[key]				,						encoded_processor[key]			)







    def      UpperCamelCase_ (     self			):
      lowercase				       =			self.get_feature_extractor()
      lowercase				       =			self.get_tokenizer()

      lowercase				       =			WavaVecaProcessor(tokenizer=_lowerCamelCase				,						feature_extractor=_lowerCamelCase			)

      lowercase				       =			[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

      lowercase				       =			processor.batch_decode(_lowerCamelCase			)
      lowercase				       =			tokenizer.batch_decode(_lowerCamelCase			)

      self.assertListEqual(_lowerCamelCase				,						_lowerCamelCase			)







    def      UpperCamelCase_ (     self			):
      lowercase				       =			self.get_feature_extractor()
      lowercase				       =			self.get_tokenizer()

      lowercase				       =			WavaVecaProcessor(tokenizer=_lowerCamelCase				,						feature_extractor=_lowerCamelCase			)

      self.assertListEqual(
          processor.model_input_names				,						feature_extractor.model_input_names				,						msg='`processor` and `feature_extractor` model input names do not match'				,						)


