test_dance_diffusion.py 5.71 KB
Newer Older
1
# coding=utf-8
2
# Copyright 2024 HuggingFace Inc.
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import gc
import unittest

import numpy as np
import torch

from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNet1DModel
23
24
25
26
27
28
29
30
from diffusers.utils.testing_utils import (
    backend_empty_cache,
    enable_full_determinism,
    nightly,
    require_torch_accelerator,
    skip_mps,
    torch_device,
)
31

32
33
from ..pipeline_params import UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS, UNCONDITIONAL_AUDIO_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
34

35

36
enable_full_determinism()
37
38


39
40
class DanceDiffusionPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
    pipeline_class = DanceDiffusionPipeline
41
42
43
44
45
46
47
48
49
    params = UNCONDITIONAL_AUDIO_GENERATION_PARAMS
    required_optional_params = PipelineTesterMixin.required_optional_params - {
        "callback",
        "latents",
        "callback_steps",
        "output_type",
        "num_images_per_prompt",
    }
    batch_params = UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS
50
    test_attention_slicing = False
51

52
    def get_dummy_components(self):
53
        torch.manual_seed(0)
54
        unet = UNet1DModel(
55
56
57
58
59
60
            block_out_channels=(32, 32, 64),
            extra_in_channels=16,
            sample_size=512,
            sample_rate=16_000,
            in_channels=2,
            out_channels=2,
61
62
63
64
            flip_sin_to_cos=True,
            use_timestep_embedding=False,
            time_embedding_type="fourier",
            mid_block_type="UNetMidBlock1D",
65
66
            down_block_types=("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D"),
            up_block_types=("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip"),
67
        )
68
69
70
71
72
73
74
75
76
77
78
79
80
81
        scheduler = IPNDMScheduler()

        components = {
            "unet": unet,
            "scheduler": scheduler,
        }
        return components

    def get_dummy_inputs(self, device, seed=0):
        if str(device).startswith("mps"):
            generator = torch.manual_seed(seed)
        else:
            generator = torch.Generator(device=device).manual_seed(seed)
        inputs = {
82
            "batch_size": 1,
83
84
85
86
            "generator": generator,
            "num_inference_steps": 4,
        }
        return inputs
87
88
89

    def test_dance_diffusion(self):
        device = "cpu"  # ensure determinism for the device-dependent torch.Generator
90
91
        components = self.get_dummy_components()
        pipe = DanceDiffusionPipeline(**components)
92
93
94
        pipe = pipe.to(device)
        pipe.set_progress_bar_config(disable=None)

95
96
        inputs = self.get_dummy_inputs(device)
        output = pipe(**inputs)
97
98
99
100
        audio = output.audios

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

101
        assert audio.shape == (1, 2, components["unet"].sample_size)
102
103
104
        expected_slice = 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

105
106
107
108
109
110
    @skip_mps
    def test_save_load_local(self):
        return super().test_save_load_local()

    @skip_mps
    def test_dict_tuple_outputs_equivalent(self):
111
        return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3)
112
113
114
115
116
117
118
119
120

    @skip_mps
    def test_save_load_optional_components(self):
        return super().test_save_load_optional_components()

    @skip_mps
    def test_attention_slicing_forward_pass(self):
        return super().test_attention_slicing_forward_pass()

121
122
123
    def test_inference_batch_single_identical(self):
        super().test_inference_batch_single_identical(expected_max_diff=3e-3)

124

Dhruv Nair's avatar
Dhruv Nair committed
125
@nightly
126
@require_torch_accelerator
127
class PipelineIntegrationTests(unittest.TestCase):
128
129
130
131
    def setUp(self):
        # clean up the VRAM before each test
        super().setUp()
        gc.collect()
132
        backend_empty_cache(torch_device)
133

134
135
136
137
    def tearDown(self):
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
138
        backend_empty_cache(torch_device)
139
140
141
142

    def test_dance_diffusion(self):
        device = torch_device

143
        pipe = DanceDiffusionPipeline.from_pretrained("harmonai/maestro-150k")
144
145
146
        pipe = pipe.to(device)
        pipe.set_progress_bar_config(disable=None)

147
        generator = torch.manual_seed(0)
148
        output = pipe(generator=generator, num_inference_steps=100, audio_length_in_s=4.096)
149
150
151
152
        audio = output.audios

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

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

156
        assert np.abs(audio_slice.flatten() - expected_slice).max() < 1e-2
157
158
159
160

    def test_dance_diffusion_fp16(self):
        device = torch_device

161
        pipe = DanceDiffusionPipeline.from_pretrained("harmonai/maestro-150k", torch_dtype=torch.float16)
162
163
164
        pipe = pipe.to(device)
        pipe.set_progress_bar_config(disable=None)

165
        generator = torch.manual_seed(0)
166
        output = pipe(generator=generator, num_inference_steps=100, audio_length_in_s=4.096)
167
168
169
170
        audio = output.audios

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

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

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