File size: 9,313 Bytes
43c5292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9ad1cd
43c5292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
007ae7a
43c5292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
from dataclasses import dataclass
from typing import Optional, Union

import torch
from PIL import Image
from tqdm import tqdm
import torchvision.transforms as T
from einops import rearrange

from .hunyuanimage_pipeline import HunyuanImagePipeline, HunyuanImagePipelineConfig

from hyimage.models.model_zoo import (
    HUNYUANIMAGE_REFINER_DIT,
    HUNYUANIMAGE_REFINER_VAE_16x,
    HUNYUANIMAGE_REFINER_TEXT_ENCODER,
)


@dataclass
class HunYuanImageRefinerPipelineConfig(HunyuanImagePipelineConfig):
    """
    Configuration class for HunyuanImage refiner pipeline.
    
    Inherits from HunyuanImagePipelineConfig and overrides specific parameters
    for the refiner functionality.
    """
    
    default_sampling_steps: int = 4
    shift: int = 1
    version: str = "v1.0"
    cfg_mode: str = ""

    @classmethod
    def create_default(
        cls,
        version: str = "v1.0",
        use_distilled: bool = False,
        **kwargs,
    ):
        dit_config = HUNYUANIMAGE_REFINER_DIT()
        vae_config = HUNYUANIMAGE_REFINER_VAE_16x()
        text_encoder_config = HUNYUANIMAGE_REFINER_TEXT_ENCODER()

        return cls(
            dit_config=dit_config,
            vae_config=vae_config,
            text_encoder_config=text_encoder_config,
            reprompt_config=None,
            version=version,
            **kwargs,
        )


class HunYuanImageRefinerPipeline(HunyuanImagePipeline):
    """A refiner pipeline for HunyuanImage that inherits from the main pipeline.
    
    This pipeline refines existing images using the same model architecture
    but with different default parameters and an image input.
    """
    
    def __init__(self, config: HunYuanImageRefinerPipelineConfig, **kwargs):
        """Initialize the refiner pipeline.
        
        Args:
            config: Refiner-specific configuration
            **kwargs: Additional arguments passed to parent class
        """
        assert isinstance(config, HunYuanImageRefinerPipelineConfig)
        super().__init__(config, **kwargs)
        assert self.cfg_distilled
        
    def _condition_aug(self, latents, noise=None, strength=0.25):
        """Apply conditioning augmentation for refiner.
        
        Args:
            latents: Input latents tensor
            noise: Optional noise tensor, if None will be generated
            strength: Augmentation strength factor
            
        Returns:
            Augmented latents tensor
        """
        if noise is None:
            noise = torch.randn_like(latents)
        return strength * noise + (1 - strength) * latents

    @torch.no_grad()
    def __call__(
        self,
        prompt: str,
        negative_prompt: str = "",
        width: int = 2048,
        height: int = 2048,
        use_reprompt: bool = False,
        num_inference_steps: Optional[int] = None,
        guidance_scale: Optional[float] = None,
        shift: int = 4,
        seed: Optional[int] = 42,
        image: Optional[Image.Image] = None,
        **kwargs,
    ) -> Image.Image:
        """Refine an existing image using text guidance.

        Args:
            prompt: Text prompt describing the desired refinement
            negative_prompt: Negative prompt for guidance
            width: Image width
            height: Image height
            use_reprompt: Whether to use reprompt (ignored for refiner)
            num_inference_steps: Number of denoising steps (overrides config if provided)
            guidance_scale: Strength of classifier-free guidance (overrides config if provided)
            seed: Random seed for reproducibility
            image: Image to be refined (required for refiner)
            **kwargs: Additional arguments

        Returns:
            Refined PIL Image
        """
        if image is None:
            raise ValueError("Image parameter is required for refiner pipeline")
            
        if seed is not None:
            generator = torch.Generator(device='cpu').manual_seed(seed)
            torch.manual_seed(seed)
        else:
            generator = None

        sampling_steps = (
            num_inference_steps
            if num_inference_steps is not None
            else self.default_sampling_steps
        )
        guidance_scale = (
            guidance_scale if guidance_scale is not None else self.default_guidance_scale
        )
        shift = shift if shift is not None else self.shift

        # Print log about current refinement task
        print("=" * 60)
        print("🔧 HunyuanImage Refinement Task")
        print("-" * 60)
        print(f"Prompt:           {prompt}")
        print(f"Guidance Scale:   {guidance_scale}")
        print(f"Shift:            {self.shift}")
        print(f"Seed:             {seed}")
        print(f"Image Size:       {width} x {height}")
        print(f"Sampling Steps:   {sampling_steps}")
        print("=" * 60)

        # Encode prompts
        pos_text_emb, pos_text_mask = self._encode_text(prompt)

        latents = self._prepare_latents(width, height, generator=generator, vae_downsampling_factor=16)

        _pil_to_tensor = T.Compose(
            [
                T.ToTensor(),  # convert to tensor and normalize to [0, 1]
                T.Normalize([0.5], [0.5]),  # transform to [-1, 1]
            ]
        )

        image_tensor = (
            _pil_to_tensor(image).unsqueeze(0).to("cuda", dtype=self.vae.dtype)
        )
        image_tensor = image_tensor.unsqueeze(2)

        with torch.no_grad():
            cond_latents = self.vae.encode(
                image_tensor.to(self.device, dtype=self.vae.dtype)
            ).latent_dist.sample()

        # reorg tokens
        cond_latents = torch.cat((cond_latents[:, :, :1], cond_latents), dim=2)
        cond_latents = rearrange(cond_latents, "b c f h w -> b f c h w")
        cond_latents = rearrange(cond_latents, "b (f n) c h w -> b f (n c) h w", n=2)
        cond_latents = rearrange(cond_latents, "b f c h w -> b c f h w").contiguous()

        if (
            hasattr(self.vae.config, "shift_factor")
            and self.vae.config.shift_factor
        ):
            cond_latents.sub_(self.vae.config.shift_factor).mul_(
                self.vae.config.scaling_factor
            )
        else:
            cond_latents.mul_(self.vae.config.scaling_factor)
        
        
        # Apply conditioning augmentation
        cond_latents = self._condition_aug(cond_latents)

        timesteps, sigmas = self.get_timesteps_sigmas(sampling_steps, shift)

        text_emb = pos_text_emb
        text_mask = pos_text_mask

        for i, t in enumerate(tqdm(timesteps, desc="Refining", total=len(timesteps))):
            # Concatenate noise latents with condition latents for refiner input
            latent_model_input = torch.cat([latents, cond_latents], dim=1)
            t_expand = t.repeat(latent_model_input.shape[0])

            # Predict noise with guidance
            noise_pred = self._denoise_step(
                latent_model_input,
                t_expand,
                text_emb,
                text_mask,
                None,
                None,
                guidance_scale,
                timesteps_r=None,
            )

            latents = self.step(latents, noise_pred, sigmas, i)

        refined_image = self._decode_latents(latents, reorg_tokens=True)

        # Convert to PIL Image
        refined_image = (refined_image.squeeze(0).permute(1, 2, 0) * 255).byte().numpy()
        pil_image = Image.fromarray(refined_image)

        return pil_image

    @classmethod
    def from_pretrained(
        cls,
        model_name: str = "hunyuanimage-refiner",
        use_distilled: bool = False,
        **kwargs,
    ):
        """Create refiner pipeline from pretrained model.
        
        Args:
            model_name: Model name, currently only supports "hunyuanimage-refiner"
            use_distilled: Whether to use distilled model (unused for refiner)
            **kwargs: Additional configuration options
        """
        if model_name == "hunyuanimage-refiner":
            version = "v1.0"
        else:
            raise ValueError(
                f"Unsupported refiner model name: {model_name}. Supported names: 'hunyuanimage-refiner'"
            )

        config = HunYuanImageRefinerPipelineConfig.create_default(
            version=version, **kwargs
        )

        return cls(config=config)

    @classmethod
    def from_config(cls, config: Union[HunYuanImageRefinerPipelineConfig, HunyuanImagePipelineConfig]):
        """Create refiner pipeline from configuration object.
        
        Args:
            config: Configuration object for the pipeline
            
        Returns:
            Initialized refiner pipeline instance
        """
        return cls(config=config)



# Convenience function for easy access
def RefinerPipeline(
    model_name: str = "hunyuanimage-refiner",
    **kwargs,
):
    """Factory function to create HunYuanImageRefinerPipeline.

    Args:
        model_name: Model name, currently only supports "hunyuanimage-refiner"
        **kwargs: Additional configuration options
        
    Returns:
        Initialized refiner pipeline instance
    """
    return HunYuanImageRefinerPipeline.from_pretrained(
        model_name, **kwargs
    )