Spaces:
Sleeping
Sleeping
Update pipeline_qwenimage_edit.py
Browse files- pipeline_qwenimage_edit.py +85 -8
pipeline_qwenimage_edit.py
CHANGED
|
@@ -170,6 +170,29 @@ def resize_to_multiple_of(image, multiple_of=32):
|
|
| 170 |
return image
|
| 171 |
|
| 172 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
class QwenImageEditPipeline(DiffusionPipeline, QwenImageLoraLoaderMixin):
|
| 175 |
r"""
|
|
@@ -223,6 +246,43 @@ class QwenImageEditPipeline(DiffusionPipeline, QwenImageLoraLoaderMixin):
|
|
| 223 |
self.prompt_template_encode = "<|im_start|>system\nDescribe the key features of the input image (color, shape, size, texture, objects, background), then explain how the user's text instruction should alter or modify the image. Generate a new image that meets the user's requirements while maintaining consistency with the original input where appropriate.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>{}<|im_end|>\n<|im_start|>assistant\n"
|
| 224 |
self.prompt_template_encode_start_idx = 64
|
| 225 |
self.default_sample_size = 128
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
|
| 227 |
# Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage.QwenImagePipeline._extract_masked_hidden
|
| 228 |
def _extract_masked_hidden(self, hidden_states: torch.Tensor, mask: torch.Tensor):
|
|
@@ -240,10 +300,21 @@ class QwenImageEditPipeline(DiffusionPipeline, QwenImageLoraLoaderMixin):
|
|
| 240 |
device: Optional[torch.device] = None,
|
| 241 |
dtype: Optional[torch.dtype] = None,
|
| 242 |
):
|
| 243 |
-
#
|
| 244 |
-
|
|
|
|
|
|
|
|
|
|
| 245 |
if device is None:
|
| 246 |
-
device =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
dtype = dtype or self.text_encoder.dtype
|
| 248 |
|
| 249 |
prompts = [prompts] if isinstance(prompts, str) else prompts
|
|
@@ -285,16 +356,19 @@ class QwenImageEditPipeline(DiffusionPipeline, QwenImageLoraLoaderMixin):
|
|
| 285 |
return_tensors="pt"
|
| 286 |
)
|
| 287 |
|
| 288 |
-
#
|
| 289 |
-
# 不依赖 .to(device) 的自动传播
|
| 290 |
input_ids = model_inputs.input_ids.to(device)
|
| 291 |
attention_mask = model_inputs.attention_mask.to(device)
|
| 292 |
pixel_values = model_inputs.pixel_values.to(device=device, dtype=dtype)
|
| 293 |
image_grid_thw = model_inputs.image_grid_thw.to(device)
|
| 294 |
|
| 295 |
-
#
|
|
|
|
|
|
|
|
|
|
| 296 |
drop_idx = self.prompt_template_encode_start_idx
|
| 297 |
|
|
|
|
| 298 |
outputs = self.text_encoder(
|
| 299 |
input_ids=input_ids,
|
| 300 |
attention_mask=attention_mask,
|
|
@@ -343,7 +417,7 @@ class QwenImageEditPipeline(DiffusionPipeline, QwenImageLoraLoaderMixin):
|
|
| 343 |
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 344 |
provided, text embeddings will be generated from `prompt` input argument.
|
| 345 |
"""
|
| 346 |
-
#
|
| 347 |
if device is None:
|
| 348 |
device = next(self.text_encoder.parameters()).device
|
| 349 |
|
|
@@ -671,6 +745,9 @@ class QwenImageEditPipeline(DiffusionPipeline, QwenImageLoraLoaderMixin):
|
|
| 671 |
[`~pipelines.qwenimage.QwenImagePipelineOutput`] if `return_dict` is True, otherwise a `tuple`. When
|
| 672 |
returning a tuple, the first element is a list with the generated images.
|
| 673 |
"""
|
|
|
|
|
|
|
|
|
|
| 674 |
if not isinstance(images, (list, tuple)):
|
| 675 |
images = [images]
|
| 676 |
|
|
@@ -714,7 +791,7 @@ class QwenImageEditPipeline(DiffusionPipeline, QwenImageLoraLoaderMixin):
|
|
| 714 |
else:
|
| 715 |
batch_size = prompt_embeds.shape[0]
|
| 716 |
|
| 717 |
-
#
|
| 718 |
device = next(self.text_encoder.parameters()).device
|
| 719 |
|
| 720 |
# 3. Preprocess image
|
|
|
|
| 170 |
return image
|
| 171 |
|
| 172 |
|
| 173 |
+
def ensure_device_recursive(model, target_device):
|
| 174 |
+
"""
|
| 175 |
+
递归确保模型的所有组件(包括 buffer)都在目标设备上。
|
| 176 |
+
这是为了解决 ZeroGPU 环境下 register_buffer 的张量可能不会被正确移动的问题。
|
| 177 |
+
"""
|
| 178 |
+
if target_device is None:
|
| 179 |
+
return
|
| 180 |
+
|
| 181 |
+
target_device = torch.device(target_device)
|
| 182 |
+
|
| 183 |
+
for name, module in model.named_modules():
|
| 184 |
+
# 移动所有 buffer
|
| 185 |
+
for buf_name, buf in list(module._buffers.items()):
|
| 186 |
+
if buf is not None and buf.device != target_device:
|
| 187 |
+
module._buffers[buf_name] = buf.to(target_device)
|
| 188 |
+
|
| 189 |
+
# 特别处理 RoPE 相关的属性(有些可能不是通过 register_buffer 注册的)
|
| 190 |
+
for attr_name in ['inv_freq', 'cos_cached', 'sin_cached', '_cos_cached', '_sin_cached']:
|
| 191 |
+
if hasattr(module, attr_name):
|
| 192 |
+
attr = getattr(module, attr_name)
|
| 193 |
+
if isinstance(attr, torch.Tensor) and attr.device != target_device:
|
| 194 |
+
setattr(module, attr_name, attr.to(target_device))
|
| 195 |
+
|
| 196 |
|
| 197 |
class QwenImageEditPipeline(DiffusionPipeline, QwenImageLoraLoaderMixin):
|
| 198 |
r"""
|
|
|
|
| 246 |
self.prompt_template_encode = "<|im_start|>system\nDescribe the key features of the input image (color, shape, size, texture, objects, background), then explain how the user's text instruction should alter or modify the image. Generate a new image that meets the user's requirements while maintaining consistency with the original input where appropriate.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>{}<|im_end|>\n<|im_start|>assistant\n"
|
| 247 |
self.prompt_template_encode_start_idx = 64
|
| 248 |
self.default_sample_size = 128
|
| 249 |
+
|
| 250 |
+
# ZeroGPU 兼容性标记
|
| 251 |
+
self._device_ensured = False
|
| 252 |
+
|
| 253 |
+
def _ensure_device_consistency(self):
|
| 254 |
+
"""
|
| 255 |
+
确保所有模型组件在同一设备上。
|
| 256 |
+
在 ZeroGPU 环境下,这个方法应该在 @spaces.GPU 装饰的函数内部调用。
|
| 257 |
+
"""
|
| 258 |
+
if self._device_ensured:
|
| 259 |
+
return
|
| 260 |
+
|
| 261 |
+
# 获取目标设备
|
| 262 |
+
try:
|
| 263 |
+
target_device = next(self.text_encoder.parameters()).device
|
| 264 |
+
except StopIteration:
|
| 265 |
+
return
|
| 266 |
+
|
| 267 |
+
if target_device.type != 'cuda':
|
| 268 |
+
return
|
| 269 |
+
|
| 270 |
+
print(f" [PIPELINE] Ensuring device consistency on {target_device}...")
|
| 271 |
+
|
| 272 |
+
# 确保所有模型的 buffer 都在正确的设备上
|
| 273 |
+
ensure_device_recursive(self.text_encoder, target_device)
|
| 274 |
+
ensure_device_recursive(self.transformer, target_device)
|
| 275 |
+
ensure_device_recursive(self.vae, target_device)
|
| 276 |
+
|
| 277 |
+
self._device_ensured = True
|
| 278 |
+
print(f" [PIPELINE] Device consistency ensured.")
|
| 279 |
+
|
| 280 |
+
def to(self, *args, **kwargs):
|
| 281 |
+
"""
|
| 282 |
+
重写 to 方法,重置设备一致性标记
|
| 283 |
+
"""
|
| 284 |
+
self._device_ensured = False
|
| 285 |
+
return super().to(*args, **kwargs)
|
| 286 |
|
| 287 |
# Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage.QwenImagePipeline._extract_masked_hidden
|
| 288 |
def _extract_masked_hidden(self, hidden_states: torch.Tensor, mask: torch.Tensor):
|
|
|
|
| 300 |
device: Optional[torch.device] = None,
|
| 301 |
dtype: Optional[torch.dtype] = None,
|
| 302 |
):
|
| 303 |
+
# 确保设备一致性(ZeroGPU 修复)
|
| 304 |
+
self._ensure_device_consistency()
|
| 305 |
+
|
| 306 |
+
# 获取 text_encoder 的实际设备
|
| 307 |
+
encoder_device = next(self.text_encoder.parameters()).device
|
| 308 |
if device is None:
|
| 309 |
+
device = encoder_device
|
| 310 |
+
else:
|
| 311 |
+
# 确保 device 是 torch.device 对象
|
| 312 |
+
device = torch.device(device)
|
| 313 |
+
# 如果指定的设备与 encoder 设备不同,使用 encoder 的设备
|
| 314 |
+
if device != encoder_device:
|
| 315 |
+
print(f" [WARNING] Requested device {device} differs from encoder device {encoder_device}, using encoder device")
|
| 316 |
+
device = encoder_device
|
| 317 |
+
|
| 318 |
dtype = dtype or self.text_encoder.dtype
|
| 319 |
|
| 320 |
prompts = [prompts] if isinstance(prompts, str) else prompts
|
|
|
|
| 356 |
return_tensors="pt"
|
| 357 |
)
|
| 358 |
|
| 359 |
+
# 关键修复:确保所有输入张量都在正确的设备上
|
|
|
|
| 360 |
input_ids = model_inputs.input_ids.to(device)
|
| 361 |
attention_mask = model_inputs.attention_mask.to(device)
|
| 362 |
pixel_values = model_inputs.pixel_values.to(device=device, dtype=dtype)
|
| 363 |
image_grid_thw = model_inputs.image_grid_thw.to(device)
|
| 364 |
|
| 365 |
+
# 调试输出
|
| 366 |
+
print(f" [DEBUG] Input devices - input_ids: {input_ids.device}, pixel_values: {pixel_values.device}")
|
| 367 |
+
print(f" [DEBUG] Encoder device: {encoder_device}")
|
| 368 |
+
|
| 369 |
drop_idx = self.prompt_template_encode_start_idx
|
| 370 |
|
| 371 |
+
# 调用 text_encoder
|
| 372 |
outputs = self.text_encoder(
|
| 373 |
input_ids=input_ids,
|
| 374 |
attention_mask=attention_mask,
|
|
|
|
| 417 |
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 418 |
provided, text embeddings will be generated from `prompt` input argument.
|
| 419 |
"""
|
| 420 |
+
# 获取 text_encoder 的实际设备
|
| 421 |
if device is None:
|
| 422 |
device = next(self.text_encoder.parameters()).device
|
| 423 |
|
|
|
|
| 745 |
[`~pipelines.qwenimage.QwenImagePipelineOutput`] if `return_dict` is True, otherwise a `tuple`. When
|
| 746 |
returning a tuple, the first element is a list with the generated images.
|
| 747 |
"""
|
| 748 |
+
# ZeroGPU 修复:确保设备一致性
|
| 749 |
+
self._ensure_device_consistency()
|
| 750 |
+
|
| 751 |
if not isinstance(images, (list, tuple)):
|
| 752 |
images = [images]
|
| 753 |
|
|
|
|
| 791 |
else:
|
| 792 |
batch_size = prompt_embeds.shape[0]
|
| 793 |
|
| 794 |
+
# 获取 text_encoder 的实际设备
|
| 795 |
device = next(self.text_encoder.parameters()).device
|
| 796 |
|
| 797 |
# 3. Preprocess image
|