


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__   (       snake_case__			,   unittest.TestCase      ):







    """simple docstring"""

    __magic_name__         =						DanceDiffusionPipeline
    __magic_name__         =						UNCONDITIONAL_AUDIO_GENERATION_PARAMS
    __magic_name__         =						PipelineTesterMixin.required_optional_params - {
        'callback',
        'latents',
        'callback_steps',
        'output_type',
        'num_images_per_prompt',
    }
    __magic_name__         =						UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS
    __magic_name__         =						False
    __magic_name__         =						False
    def 						a_     (			self       ):
         torch.manual_seed(0       )
         snake_case											=							UNetaDModel(
             block_out_channels=(3_2, 3_2, 6_4)     ,   extra_in_channels=1_6     ,   sample_size=5_1_2     ,   sample_rate=1_6_0_0_0     ,   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''')     ,   )
         snake_case											=							IPNDMScheduler()

         snake_case											=							{
             '''unet''': unet,
             '''scheduler''': scheduler,
         }
         return components
    def 						a_     (			self     ,   __snake_case     ,   __snake_case=0       ):
         if str(__snake_case       ).startswith('''mps'''       ):
              snake_case											=							torch.manual_seed(__snake_case       )
         else:
              snake_case											=							torch.Generator(device=__snake_case       ).manual_seed(__snake_case       )
         snake_case											=							{
             '''batch_size''': 1,
             '''generator''': generator,
             '''num_inference_steps''': 4,
         }
         return inputs
    def 						a_     (			self       ):
         snake_case											=							'''cpu'''  # ensure determinism for the device-dependent torch.Generator
         snake_case											=							self.get_dummy_components()
         snake_case											=							DanceDiffusionPipeline(**__snake_case       )
         snake_case											=							pipe.to(__snake_case       )
         pipe.set_progress_bar_config(disable=__snake_case       )

         snake_case											=							self.get_dummy_inputs(__snake_case       )
         snake_case											=							pipe(**__snake_case       )
         snake_case											=							output.audios

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

         assert audio.shape == (1, 2, components["unet"].sample_size)
         snake_case											=							np.array([-0.7265, 1.0000, -0.8388, 0.1175, 0.9498, -1.0000]       )
         assert np.abs(audio_slice.flatten() - expected_slice       ).max() < 1E-2
    @skip_mps
    def 						a_     (			self       ):
         return super().test_save_load_local()
    @skip_mps
    def 						a_     (			self       ):
         return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3       )
    @skip_mps
    def 						a_     (			self       ):
         return super().test_save_load_optional_components()
    @skip_mps
    def 						a_     (			self       ):
         return super().test_attention_slicing_forward_pass()




    def 						a_     (			self       ):
         super().test_inference_batch_single_identical(expected_max_diff=3E-3       )






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







    """simple docstring"""

    def 						a_     (			self       ):
         # clean up the VRAM after each test
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()
    def 						a_     (			self       ):
         snake_case											=							torch_device

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

         snake_case											=							torch.manual_seed(0       )
         snake_case											=							pipe(generator=__snake_case     ,   num_inference_steps=1_0_0     ,   audio_length_in_s=4.096       )
         snake_case											=							output.audios

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

         assert audio.shape == (1, 2, pipe.unet.sample_size)
         snake_case											=							np.array([-0.0192, -0.0231, -0.0318, -0.0059, 0.0002, -0.0020]       )

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




    def 						a_     (			self       ):
         snake_case											=							torch_device

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

         snake_case											=							torch.manual_seed(0       )
         snake_case											=							pipe(generator=__snake_case     ,   num_inference_steps=1_0_0     ,   audio_length_in_s=4.096       )
         snake_case											=							output.audios

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

         assert audio.shape == (1, 2, pipe.unet.sample_size)
         snake_case											=							np.array([-0.0367, -0.0488, -0.0771, -0.0525, -0.0444, -0.0341]       )

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








import argparse
import logging
import sys
from unittest.mock import patch

import run_glue_deebert

from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow


logging.basicConfig(level=logging.DEBUG)

_SCREAMING_SNAKE_CASE     :					int      =       logging.getLogger()
def      UpperCAmelCase__		():



     """simple docstring"""






     snake_case											=							argparse.ArgumentParser()
     parser.add_argument('''-f'''							)
     snake_case											=							parser.parse_args()
     return args.f

class     A__   (       snake_case__      ):







    """simple docstring"""

    def 						a_     (			self       ):
         snake_case											=							logging.StreamHandler(sys.stdout       )
         logger.addHandler(__snake_case       )
    def 						a_     (			self     ,   __snake_case       ):
         snake_case											=							get_gpu_count()

         if n_gpu > 1:
              pass
              # XXX: doesn't quite work with n_gpu > 1 https://github.com/huggingface/transformers/issues/10560
              # script = f"{self.examples_dir_str}/research_projects/deebert/run_glue_deebert.py"
              # distributed_args = f"-m torch.distributed.launch --nproc_per_node={n_gpu} {script}".split()
              # cmd = [sys.executable] + distributed_args + args
              # execute_subprocess_async(cmd, env=self.get_env())
              # XXX: test the results - need to save them first into .json file
         else:
              args.insert(0     ,   '''run_glue_deebert.py'''       )
              with patch.object(__snake_case     ,   '''argv'''     ,   __snake_case       ):
                   snake_case											=							run_glue_deebert.main()
                   for value in result.values():
                        self.assertGreaterEqual(__snake_case     ,   0.666       )




    @slow
    @require_torch_non_multi_gpu
    def 						a_     (			self       ):
         snake_case											=							'''
            --model_type roberta
            --model_name_or_path roberta-base
            --task_name MRPC
            --do_train
            --do_eval
            --do_lower_case
            --data_dir ./tests/fixtures/tests_samples/MRPC/
            --max_seq_length 128
            --per_gpu_eval_batch_size=1
            --per_gpu_train_batch_size=8
            --learning_rate 2e-4
            --num_train_epochs 3
            --overwrite_output_dir
            --seed 42
            --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage
            --plot_data_dir ./examples/deebert/results/
            --save_steps 0
            --overwrite_cache
            --eval_after_first_stage
            '''.split()
         self.run_and_check(__snake_case       )

         snake_case											=							'''
            --model_type roberta
            --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage
            --task_name MRPC
            --do_eval
            --do_lower_case
            --data_dir ./tests/fixtures/tests_samples/MRPC/
            --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage
            --plot_data_dir ./examples/deebert/results/
            --max_seq_length 128
            --eval_each_highway
            --eval_highway
            --overwrite_cache
            --per_gpu_eval_batch_size=1
            '''.split()
         self.run_and_check(__snake_case       )

         snake_case											=							'''
            --model_type roberta
            --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage
            --task_name MRPC
            --do_eval
            --do_lower_case
            --data_dir ./tests/fixtures/tests_samples/MRPC/
            --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage
            --plot_data_dir ./examples/deebert/results/
            --max_seq_length 128
            --early_exit_entropy 0.1
            --eval_highway
            --overwrite_cache
            --per_gpu_eval_batch_size=1
            '''.split()
         self.run_and_check(__snake_case       )




