test_torch_compile_utils.py 4.2 KB
Newer Older
1
# coding=utf-8
Aryan's avatar
Aryan committed
2
# Copyright 2025 The HuggingFace Team Inc.
3
4
5
6
7
8
9
10
11
12
13
14
15
#
# 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 clone 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
16
import inspect
17
18
19
20

import torch

from diffusers import DiffusionPipeline
21
from diffusers.utils.testing_utils import backend_empty_cache, require_torch_accelerator, slow, torch_device
22
23


24
@require_torch_accelerator
25
@slow
26
class QuantCompileTests:
27
28
29
30
31
    @property
    def quantization_config(self):
        raise NotImplementedError(
            "This property should be implemented in the subclass to return the appropriate quantization config."
        )
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

    def setUp(self):
        super().setUp()
        gc.collect()
        backend_empty_cache(torch_device)
        torch.compiler.reset()

    def tearDown(self):
        super().tearDown()
        gc.collect()
        backend_empty_cache(torch_device)
        torch.compiler.reset()

    def _init_pipeline(self, quantization_config, torch_dtype):
        pipe = DiffusionPipeline.from_pretrained(
            "stabilityai/stable-diffusion-3-medium-diffusers",
            quantization_config=quantization_config,
            torch_dtype=torch_dtype,
        )
        return pipe

53
    def _test_torch_compile(self, torch_dtype=torch.bfloat16):
54
        pipe = self._init_pipeline(self.quantization_config, torch_dtype).to(torch_device)
55
        # `fullgraph=True` ensures no graph breaks
56
57
        pipe.transformer.compile(fullgraph=True)

58
        # small resolutions to ensure speedy execution.
59
60
        with torch._dynamo.config.patch(error_on_recompile=True):
            pipe("a dog", num_inference_steps=2, max_sequence_length=16, height=256, width=256)
61

62
63
    def _test_torch_compile_with_cpu_offload(self, torch_dtype=torch.bfloat16):
        pipe = self._init_pipeline(self.quantization_config, torch_dtype)
64
        pipe.enable_model_cpu_offload()
65
66
67
68
69
70
        # regional compilation is better for offloading.
        # see: https://pytorch.org/blog/torch-compile-and-diffusers-a-hands-on-guide-to-peak-performance/
        if getattr(pipe.transformer, "_repeated_blocks"):
            pipe.transformer.compile_repeated_blocks(fullgraph=True)
        else:
            pipe.transformer.compile()
71

72
73
        # small resolutions to ensure speedy execution.
        pipe("a dog", num_inference_steps=2, max_sequence_length=16, height=256, width=256)
74

75
76
    def _test_torch_compile_with_group_offload_leaf(self, torch_dtype=torch.bfloat16, *, use_stream: bool = False):
        torch._dynamo.config.cache_size_limit = 1000
77

78
        pipe = self._init_pipeline(self.quantization_config, torch_dtype)
79
        group_offload_kwargs = {
80
            "onload_device": torch.device(torch_device),
81
82
            "offload_device": torch.device("cpu"),
            "offload_type": "leaf_level",
83
            "use_stream": use_stream,
84
85
86
87
88
89
        }
        pipe.transformer.enable_group_offload(**group_offload_kwargs)
        pipe.transformer.compile()
        for name, component in pipe.components.items():
            if name != "transformer" and isinstance(component, torch.nn.Module):
                if torch.device(component.device).type == "cpu":
90
                    component.to(torch_device)
91

92
93
94
95
96
97
98
99
100
101
102
103
104
105
        # small resolutions to ensure speedy execution.
        pipe("a dog", num_inference_steps=2, max_sequence_length=16, height=256, width=256)

    def test_torch_compile(self):
        self._test_torch_compile()

    def test_torch_compile_with_cpu_offload(self):
        self._test_torch_compile_with_cpu_offload()

    def test_torch_compile_with_group_offload_leaf(self, use_stream=False):
        for cls in inspect.getmro(self.__class__):
            if "test_torch_compile_with_group_offload_leaf" in cls.__dict__ and cls is not QuantCompileTests:
                return
        self._test_torch_compile_with_group_offload_leaf(use_stream=use_stream)