"vscode:/vscode.git/clone" did not exist on "b091a7a5c9e47eebee9cfab97adcbc17ba61c726"
test_pipeline_photon.py 9.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import unittest

import numpy as np
import pytest
import torch
from transformers import AutoTokenizer
from transformers.models.t5gemma.configuration_t5gemma import T5GemmaConfig, T5GemmaModuleConfig
from transformers.models.t5gemma.modeling_t5gemma import T5GemmaEncoder

from diffusers.models import AutoencoderDC, AutoencoderKL
from diffusers.models.transformers.transformer_photon import PhotonTransformer2DModel
from diffusers.pipelines.photon.pipeline_photon import PhotonPipeline
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
from diffusers.utils import is_transformers_version

from ..pipeline_params import TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


@pytest.mark.xfail(
    condition=is_transformers_version(">", "4.57.1"),
    reason="See https://github.com/huggingface/diffusers/pull/12456#issuecomment-3424228544",
    strict=False,
)
class PhotonPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
    pipeline_class = PhotonPipeline
    params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
    batch_params = frozenset(["prompt", "negative_prompt", "num_images_per_prompt"])
    test_xformers_attention = False
    test_layerwise_casting = True
    test_group_offloading = True

    @classmethod
    def setUpClass(cls):
        # Ensure PhotonPipeline has an _execution_device property expected by __call__
        if not isinstance(getattr(PhotonPipeline, "_execution_device", None), property):
            try:
                setattr(PhotonPipeline, "_execution_device", property(lambda self: torch.device("cpu")))
            except Exception:
                pass

    def get_dummy_components(self):
        torch.manual_seed(0)
        transformer = PhotonTransformer2DModel(
            patch_size=1,
            in_channels=4,
            context_in_dim=8,
            hidden_size=8,
            mlp_ratio=2.0,
            num_heads=2,
            depth=1,
            axes_dim=[2, 2],
        )

        torch.manual_seed(0)
        vae = AutoencoderKL(
            sample_size=32,
            in_channels=3,
            out_channels=3,
            block_out_channels=(4,),
            layers_per_block=1,
            latent_channels=4,
            norm_num_groups=1,
            use_quant_conv=False,
            use_post_quant_conv=False,
            shift_factor=0.0,
            scaling_factor=1.0,
        ).eval()

        torch.manual_seed(0)
        scheduler = FlowMatchEulerDiscreteScheduler()

        torch.manual_seed(0)
        tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/dummy-gemma")
        tokenizer.model_max_length = 64

        torch.manual_seed(0)

        encoder_params = {
            "vocab_size": tokenizer.vocab_size,
            "hidden_size": 8,
            "intermediate_size": 16,
            "num_hidden_layers": 1,
            "num_attention_heads": 2,
            "num_key_value_heads": 1,
            "head_dim": 4,
            "max_position_embeddings": 64,
            "layer_types": ["full_attention"],
            "attention_bias": False,
            "attention_dropout": 0.0,
            "dropout_rate": 0.0,
            "hidden_activation": "gelu_pytorch_tanh",
            "rms_norm_eps": 1e-06,
            "attn_logit_softcapping": 50.0,
            "final_logit_softcapping": 30.0,
            "query_pre_attn_scalar": 4,
            "rope_theta": 10000.0,
            "sliding_window": 4096,
        }
        encoder_config = T5GemmaModuleConfig(**encoder_params)
        text_encoder_config = T5GemmaConfig(encoder=encoder_config, is_encoder_decoder=False, **encoder_params)
        text_encoder = T5GemmaEncoder(text_encoder_config)

        return {
            "transformer": transformer,
            "vae": vae,
            "scheduler": scheduler,
            "text_encoder": text_encoder,
            "tokenizer": tokenizer,
        }

    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)
        return {
            "prompt": "",
            "negative_prompt": "",
            "generator": generator,
            "num_inference_steps": 2,
            "guidance_scale": 1.0,
            "height": 32,
            "width": 32,
            "output_type": "pt",
            "use_resolution_binning": False,
        }

    def test_inference(self):
        device = "cpu"
        components = self.get_dummy_components()
        pipe = PhotonPipeline(**components)
        pipe.to(device)
        pipe.set_progress_bar_config(disable=None)
        try:
            pipe.register_to_config(_execution_device="cpu")
        except Exception:
            pass

        inputs = self.get_dummy_inputs(device)
        image = pipe(**inputs)[0]
        generated_image = image[0]

        self.assertEqual(generated_image.shape, (3, 32, 32))
        expected_image = torch.zeros(3, 32, 32)
        max_diff = np.abs(generated_image - expected_image).max()
        self.assertLessEqual(max_diff, 1e10)

    def test_callback_inputs(self):
        components = self.get_dummy_components()
        pipe = PhotonPipeline(**components)
        pipe = pipe.to("cpu")
        pipe.set_progress_bar_config(disable=None)
        try:
            pipe.register_to_config(_execution_device="cpu")
        except Exception:
            pass
        self.assertTrue(
            hasattr(pipe, "_callback_tensor_inputs"),
            f" {PhotonPipeline} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
        )

        def callback_inputs_subset(pipe, i, t, callback_kwargs):
            for tensor_name in callback_kwargs.keys():
                assert tensor_name in pipe._callback_tensor_inputs
            return callback_kwargs

        def callback_inputs_all(pipe, i, t, callback_kwargs):
            for tensor_name in pipe._callback_tensor_inputs:
                assert tensor_name in callback_kwargs
            for tensor_name in callback_kwargs.keys():
                assert tensor_name in pipe._callback_tensor_inputs
            return callback_kwargs

        inputs = self.get_dummy_inputs("cpu")

        inputs["callback_on_step_end"] = callback_inputs_subset
        inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
        _ = pipe(**inputs)[0]

        inputs["callback_on_step_end"] = callback_inputs_all
        inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
        _ = pipe(**inputs)[0]

    def test_attention_slicing_forward_pass(self, expected_max_diff=1e-3):
        if not self.test_attention_slicing:
            return

        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        for component in pipe.components.values():
            if hasattr(component, "set_default_attn_processor"):
                component.set_default_attn_processor()
        pipe.to("cpu")
        pipe.set_progress_bar_config(disable=None)

        def to_np_local(tensor):
            if isinstance(tensor, torch.Tensor):
                return tensor.detach().cpu().numpy()
            return tensor

        generator_device = "cpu"
        inputs = self.get_dummy_inputs(generator_device)
        output_without_slicing = pipe(**inputs)[0]

        pipe.enable_attention_slicing(slice_size=1)
        inputs = self.get_dummy_inputs(generator_device)
        output_with_slicing1 = pipe(**inputs)[0]

        pipe.enable_attention_slicing(slice_size=2)
        inputs = self.get_dummy_inputs(generator_device)
        output_with_slicing2 = pipe(**inputs)[0]

        max_diff1 = np.abs(to_np_local(output_with_slicing1) - to_np_local(output_without_slicing)).max()
        max_diff2 = np.abs(to_np_local(output_with_slicing2) - to_np_local(output_without_slicing)).max()
        self.assertLess(max(max_diff1, max_diff2), expected_max_diff)

    def test_inference_with_autoencoder_dc(self):
        """Test PhotonPipeline with AutoencoderDC (DCAE) instead of AutoencoderKL."""
        device = "cpu"

        components = self.get_dummy_components()

        torch.manual_seed(0)
        vae_dc = AutoencoderDC(
            in_channels=3,
            latent_channels=4,
            attention_head_dim=2,
            encoder_block_types=(
                "ResBlock",
                "EfficientViTBlock",
            ),
            decoder_block_types=(
                "ResBlock",
                "EfficientViTBlock",
            ),
            encoder_block_out_channels=(8, 8),
            decoder_block_out_channels=(8, 8),
            encoder_qkv_multiscales=((), (5,)),
            decoder_qkv_multiscales=((), (5,)),
            encoder_layers_per_block=(1, 1),
            decoder_layers_per_block=(1, 1),
            upsample_block_type="interpolate",
            downsample_block_type="stride_conv",
            decoder_norm_types="rms_norm",
            decoder_act_fns="silu",
        ).eval()

        components["vae"] = vae_dc

        pipe = PhotonPipeline(**components)
        pipe.to(device)
        pipe.set_progress_bar_config(disable=None)

        expected_scale_factor = vae_dc.spatial_compression_ratio
        self.assertEqual(pipe.vae_scale_factor, expected_scale_factor)

        inputs = self.get_dummy_inputs(device)
        image = pipe(**inputs)[0]
        generated_image = image[0]

        self.assertEqual(generated_image.shape, (3, 32, 32))
        expected_image = torch.zeros(3, 32, 32)
        max_diff = np.abs(generated_image - expected_image).max()
        self.assertLessEqual(max_diff, 1e10)