AlekseyCalvin commited on
Commit
0fa63d6
1 Parent(s): 4ffc890

Create pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +210 -0
pipeline.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ from diffusers import FlowMatchEulerDiscreteScheduler
4
+ from diffusers import FluxPipeline
5
+ from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
6
+ from typing import Any, Callable, Dict, List, Optional, Union
7
+ from PIL import Image
8
+ from diffusers.pipelines.flux.pipeline_flux import calculate_shift, retrieve_timesteps
9
+
10
+ from diffusers.utils import is_torch_xla_available
11
+
12
+ if is_torch_xla_available():
13
+ import torch_xla.core.xla_model as xm
14
+
15
+ XLA_AVAILABLE = True
16
+ else:
17
+ XLA_AVAILABLE = False
18
+
19
+
20
+ # Constants for shift calculation
21
+ BASE_SEQ_LEN = 256
22
+ MAX_SEQ_LEN = 4096
23
+ BASE_SHIFT = 0.5
24
+ MAX_SHIFT = 1.2
25
+
26
+ # Helper functions
27
+ def calculate_timestep_shift(image_seq_len: int) -> float:
28
+ """Calculates the timestep shift (mu) based on the image sequence length."""
29
+ m = (MAX_SHIFT - BASE_SHIFT) / (MAX_SEQ_LEN - BASE_SEQ_LEN)
30
+ b = BASE_SHIFT - m * BASE_SEQ_LEN
31
+ mu = image_seq_len * m + b
32
+ return mu
33
+
34
+ def prepare_timesteps(
35
+ scheduler: FlowMatchEulerDiscreteScheduler,
36
+ num_inference_steps: Optional[int] = None,
37
+ device: Optional[Union[str, torch.device]] = None,
38
+ timesteps: Optional[List[int]] = None,
39
+ sigmas: Optional[List[float]] = None,
40
+ mu: Optional[float] = None,
41
+ ) -> (torch.Tensor, int):
42
+ """Prepares the timesteps for the diffusion process."""
43
+ if timesteps is not None and sigmas is not None:
44
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed.")
45
+
46
+ if timesteps is not None:
47
+ scheduler.set_timesteps(timesteps=timesteps, device=device)
48
+ elif sigmas is not None:
49
+ scheduler.set_timesteps(sigmas=sigmas, device=device)
50
+ else:
51
+ scheduler.set_timesteps(num_inference_steps, device=device, mu=mu)
52
+
53
+ timesteps = scheduler.timesteps
54
+ num_inference_steps = len(timesteps)
55
+ return timesteps, num_inference_steps
56
+
57
+ # FLUX pipeline function
58
+ class FluxWithCFGPipeline(FluxPipeline):
59
+
60
+ @torch.inference_mode()
61
+ def generate_images(
62
+ self,
63
+ prompt: Union[str, List[str]] = None,
64
+ prompt_2: Optional[Union[str, List[str]]] = None,
65
+ height: Optional[int] = None,
66
+ width: Optional[int] = None,
67
+ negative_prompt: Optional[Union[str, List[str]]] = None,
68
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
69
+ num_inference_steps: int = 4,
70
+ timesteps: List[int] = None,
71
+ guidance_scale: float = 3.5,
72
+ num_images_per_prompt: Optional[int] = 1,
73
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
74
+ latents: Optional[torch.FloatTensor] = None,
75
+ prompt_embeds: Optional[torch.FloatTensor] = None,
76
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
77
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
78
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
79
+ output_type: Optional[str] = "pil",
80
+ return_dict: bool = True,
81
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
82
+ max_sequence_length: int = 300,
83
+ ):
84
+ height = height or self.default_sample_size * self.vae_scale_factor
85
+ width = width or self.default_sample_size * self.vae_scale_factor
86
+
87
+ # 1. Check inputs
88
+ self.check_inputs(
89
+ prompt,
90
+ prompt_2,
91
+ negative_prompt,
92
+ height,
93
+ width,
94
+ prompt_embeds=prompt_embeds,
95
+ pooled_prompt_embeds=pooled_prompt_embeds,
96
+ max_sequence_length=max_sequence_length,
97
+ )
98
+
99
+ self._guidance_scale = guidance_scale
100
+ self._joint_attention_kwargs = joint_attention_kwargs
101
+ self._interrupt = False
102
+
103
+ # 2. Define call parameters
104
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
105
+ device = "cuda" if torch.cuda.is_available() else "cpu"
106
+
107
+ # 3. Encode prompt
108
+ lora_scale = joint_attention_kwargs.get("scale", None) if joint_attention_kwargs is not None else None
109
+ prompt_embeds, pooled_prompt_embeds, text_ids = self.encode_prompt(
110
+ prompt=prompt,
111
+ prompt_2=prompt_2,
112
+ prompt_embeds=prompt_embeds,
113
+ pooled_prompt_embeds=pooled_prompt_embeds,
114
+ device=device,
115
+ num_images_per_prompt=num_images_per_prompt,
116
+ max_sequence_length=max_sequence_length,
117
+ lora_scale=lora_scale,
118
+ )
119
+ negative_prompt_embeds, negative_pooled_prompt_embeds, negative_text_ids = self.encode_prompt(
120
+ prompt=negative_prompt,
121
+ prompt_2=negative_prompt_2,
122
+ prompt_embeds=negative_prompt_embeds,
123
+ pooled_prompt_embeds=negative_pooled_prompt_embeds,
124
+ device=device,
125
+ num_images_per_prompt=num_images_per_prompt,
126
+ max_sequence_length=max_sequence_length,
127
+ lora_scale=lora_scale,
128
+ )
129
+
130
+ # 4. Prepare latent variables
131
+ num_channels_latents = self.transformer.config.in_channels // 4
132
+ latents, latent_image_ids = self.prepare_latents(
133
+ batch_size * num_images_per_prompt,
134
+ num_channels_latents,
135
+ height,
136
+ width,
137
+ prompt_embeds.dtype,
138
+ negative_prompt_embeds.dtype,
139
+ device,
140
+ generator,
141
+ latents,
142
+ )
143
+
144
+ # 5. Prepare timesteps
145
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
146
+ image_seq_len = latents.shape[1]
147
+ mu = calculate_timestep_shift(image_seq_len)
148
+ timesteps, num_inference_steps = prepare_timesteps(
149
+ self.scheduler,
150
+ num_inference_steps,
151
+ device,
152
+ timesteps,
153
+ sigmas,
154
+ mu=mu,
155
+ )
156
+ self._num_timesteps = len(timesteps)
157
+
158
+ # Handle guidance
159
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float16).expand(latents.shape[0]) if self.transformer.config.guidance_embeds else None
160
+
161
+ # 6. Denoising loop
162
+ for i, t in enumerate(timesteps):
163
+ if self.interrupt:
164
+ continue
165
+
166
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
167
+
168
+ noise_pred = self.transformer(
169
+ hidden_states=latents,
170
+ timestep=timestep / 1000,
171
+ guidance=guidance,
172
+ pooled_projections=pooled_prompt_embeds,
173
+ encoder_hidden_states=prompt_embeds,
174
+ txt_ids=text_ids,
175
+ img_ids=latent_image_ids,
176
+ joint_attention_kwargs=self.joint_attention_kwargs,
177
+ return_dict=False,
178
+ )[0]
179
+
180
+ noise_pred_uncond = self.transformer(
181
+ hidden_states=latents,
182
+ timestep=timestep / 1000,
183
+ guidance=guidance,
184
+ pooled_projections=negative_pooled_prompt_embeds,
185
+ encoder_hidden_states=negative_prompt_embeds,
186
+ txt_ids=negative_text_ids,
187
+ img_ids=latent_image_ids,
188
+ joint_attention_kwargs=self.joint_attention_kwargs,
189
+ return_dict=False,
190
+ )[0]
191
+
192
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
193
+
194
+ latents_dtype = latents.dtype
195
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
196
+ # Yield intermediate result
197
+ torch.cuda.empty_cache()
198
+
199
+ # Final image
200
+ return self._decode_latents_to_image(latents, height, width, output_type)
201
+ self.maybe_free_model_hooks()
202
+ torch.cuda.empty_cache()
203
+
204
+ def _decode_latents_to_image(self, latents, height, width, output_type, vae=None):
205
+ """Decodes the given latents into an image."""
206
+ vae = vae or self.vae
207
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
208
+ latents = (latents / vae.config.scaling_factor) + vae.config.shift_factor
209
+ image = vae.decode(latents, return_dict=False)[0]
210
+ return self.image_processor.postprocess(image, output_type=output_type)[0]