| 489 | fn_recursive_attn_processor(name, module, processor) |
| 490 | |
| 491 | def forward( |
| 492 | self, |
| 493 | hidden_states: torch.Tensor, |
| 494 | encoder_hidden_states: torch.Tensor, |
| 495 | timestep: Optional[torch.Tensor] = None, # 使用flow mathcing |
| 496 | timestep_t: Optional[torch.Tensor] = None, # 当前时间 t 使用mean flow |
| 497 | timestep_r: Optional[torch.Tensor] = None, # 参考时间 r 使用mean flow |
| 498 | guidance: Optional[torch.Tensor] = None, |
| 499 | encoder_attention_mask: Optional[torch.Tensor] = None, |
| 500 | attention_mask: Optional[torch.Tensor] = None, |
| 501 | attention_kwargs: Optional[Dict[str, Any]] = None, |
| 502 | controlnet_block_samples: Optional[Tuple[torch.Tensor]] = None, |
| 503 | return_dict: bool = True, |
| 504 | ) -> Union[Tuple[torch.Tensor, ...], Transformer2DModelOutput]: |
| 505 | |
| 506 | |
| 507 | if attention_kwargs is not None: |
| 508 | attention_kwargs = attention_kwargs.copy() |
| 509 | lora_scale = attention_kwargs.pop("scale", 1.0) |
| 510 | else: |
| 511 | lora_scale = 1.0 |
| 512 | |
| 513 | if USE_PEFT_BACKEND: |
| 514 | # weight the lora layers by setting `lora_scale` for each PEFT layer |
| 515 | scale_lora_layers(self, lora_scale) |
| 516 | else: |
| 517 | if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None: |
| 518 | logger.warning( |
| 519 | "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective." |
| 520 | ) |
| 521 | if attention_mask is not None and attention_mask.ndim == 2: |
| 522 | |
| 523 | attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0 |
| 524 | attention_mask = attention_mask.unsqueeze(1) |
| 525 | |
| 526 | |
| 527 | if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2: |
| 528 | encoder_attention_mask = (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10000.0 |
| 529 | encoder_attention_mask = encoder_attention_mask.unsqueeze(1) |
| 530 | |
| 531 | # 1. Input |
| 532 | batch_size, num_channels, height, width = hidden_states.shape |
| 533 | p = self.config.patch_size |
| 534 | post_patch_height, post_patch_width = height // p, width // p |
| 535 | |
| 536 | hidden_states = self.patch_embed(hidden_states) |
| 537 | |
| 538 | |
| 539 | if timestep is not None: |
| 540 | if guidance is not None: |
| 541 | timestep, embedded_timestep = self.time_embed( |
| 542 | timestep, guidance=guidance, hidden_dtype=hidden_states.dtype |
| 543 | ) |
| 544 | else: |
| 545 | timestep, embedded_timestep = self.time_embed( |
| 546 | timestep, batch_size=batch_size, hidden_dtype=hidden_states.dtype |
| 547 | ) |
| 548 | |