Revert " Fix QwenImage txt_seq_lens handling (#12702)" · NotSoBot/nsb.api.diffusers@6b77b72 · GitHub
Skip to content

Commit 6b77b72

Browse files
committed
Revert " Fix QwenImage txt_seq_lens handling (huggingface#12702)"
This reverts commit dad5cb5.
1 parent 8daaa6b commit 6b77b72

17 files changed

Lines changed: 172 additions & 513 deletions

‎docs/source/en/api/pipelines/qwenimage.md‎

Lines changed: 2 additions & 36 deletions

‎examples/dreambooth/train_dreambooth_lora_qwen_image.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1513,12 +1513,14 @@ def get_sigmas(timesteps, n_dim=4, dtype=torch.float32):
15131513
height=model_input.shape[3],
15141514
width=model_input.shape[4],
15151515
)
1516+
print(f"{prompt_embeds_mask.sum(dim=1).tolist()=}")
15161517
model_pred = transformer(
15171518
hidden_states=packed_noisy_model_input,
15181519
encoder_hidden_states=prompt_embeds,
15191520
encoder_hidden_states_mask=prompt_embeds_mask,
15201521
timestep=timesteps / 1000,
15211522
img_shapes=img_shapes,
1523+
txt_seq_lens=prompt_embeds_mask.sum(dim=1).tolist(),
15221524
return_dict=False,
15231525
)[0]
15241526
model_pred = QwenImagePipeline._unpack_latents(

‎src/diffusers/models/attention_dispatch.py‎

Lines changed: 2 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -2128,43 +2128,6 @@ def score_mod(score, batch_idx, head_idx, q_idx, kv_idx):
21282128
return out
21292129

21302130

2131-
def _prepare_additive_attn_mask(
2132-
attn_mask: torch.Tensor, target_dtype: torch.dtype, reshape_4d: bool = True
2133-
) -> torch.Tensor:
2134-
"""
2135-
Convert a 2D attention mask to an additive mask, optionally reshaping to 4D for SDPA.
2136-
2137-
This helper is used by both native SDPA and xformers backends to handle both boolean and additive masks.
2138-
2139-
Args:
2140-
attn_mask: 2D tensor [batch_size, seq_len_k]
2141-
- Boolean: True means attend, False means mask out
2142-
- Additive: 0.0 means attend, -inf means mask out
2143-
target_dtype: The dtype to convert the mask to (usually query.dtype)
2144-
reshape_4d: If True, reshape from [batch_size, seq_len_k] to [batch_size, 1, 1, seq_len_k] for broadcasting
2145-
2146-
Returns:
2147-
Additive mask tensor where 0.0 means attend and -inf means mask out. Shape is [batch_size, seq_len_k] if
2148-
reshape_4d=False, or [batch_size, 1, 1, seq_len_k] if reshape_4d=True.
2149-
"""
2150-
# Check if the mask is boolean or already additive
2151-
if attn_mask.dtype == torch.bool:
2152-
# Convert boolean to additive: True -> 0.0, False -> -inf
2153-
attn_mask = torch.where(attn_mask, 0.0, float("-inf"))
2154-
# Convert to target dtype
2155-
attn_mask = attn_mask.to(dtype=target_dtype)
2156-
else:
2157-
# Already additive mask - just ensure correct dtype
2158-
attn_mask = attn_mask.to(dtype=target_dtype)
2159-
2160-
# Optionally reshape to 4D for broadcasting in attention mechanisms
2161-
if reshape_4d:
2162-
batch_size, seq_len_k = attn_mask.shape
2163-
attn_mask = attn_mask.view(batch_size, 1, 1, seq_len_k)
2164-
2165-
return attn_mask
2166-
2167-
21682131
@_AttentionBackendRegistry.register(
21692132
AttentionBackendName.NATIVE,
21702133
constraints=[_check_device, _check_shape],
@@ -2184,19 +2147,6 @@ def _native_attention(
21842147
) -> torch.Tensor:
21852148
if return_lse:
21862149
raise ValueError("Native attention backend does not support setting `return_lse=True`.")
2187-
2188-
# Reshape 2D mask to 4D for SDPA
2189-
# SDPA accepts both boolean masks (torch.bool) and additive masks (float)
2190-
if (
2191-
attn_mask is not None
2192-
and attn_mask.ndim == 2
2193-
and attn_mask.shape[0] == query.shape[0]
2194-
and attn_mask.shape[1] == key.shape[1]
2195-
):
2196-
# Just reshape [batch_size, seq_len_k] -> [batch_size, 1, 1, seq_len_k]
2197-
# SDPA handles both boolean and additive masks correctly
2198-
attn_mask = attn_mask.unsqueeze(1).unsqueeze(1)
2199-
22002150
if _parallel_config is None:
22012151
query, key, value = (x.permute(0, 2, 1, 3) for x in (query, key, value))
22022152
out = torch.nn.functional.scaled_dot_product_attention(
@@ -2763,34 +2713,10 @@ def _xformers_attention(
27632713
attn_mask = xops.LowerTriangularMask()
27642714
elif attn_mask is not None:
27652715
if attn_mask.ndim == 2:
2766-
# Convert 2D mask to 4D for xformers
2767-
# Mask can be boolean (True=attend, False=mask) or additive (0.0=attend, -inf=mask)
2768-
# xformers requires 4D additive masks [batch, heads, seq_q, seq_k]
2769-
# Need memory alignment - create larger tensor and slice for alignment
2770-
original_seq_len = attn_mask.size(1)
2771-
aligned_seq_len = ((original_seq_len + 7) // 8) * 8 # Round up to multiple of 8
2772-
2773-
# Create aligned 4D tensor and slice to ensure proper memory layout
2774-
aligned_mask = torch.zeros(
2775-
(batch_size, num_heads_q, seq_len_q, aligned_seq_len),
2776-
dtype=query.dtype,
2777-
device=query.device,
2778-
)
2779-
# Convert to 4D additive mask (handles both boolean and additive inputs)
2780-
mask_additive = _prepare_additive_attn_mask(
2781-
attn_mask, target_dtype=query.dtype
2782-
) # [batch, 1, 1, seq_len_k]
2783-
# Broadcast to [batch, heads, seq_q, seq_len_k]
2784-
aligned_mask[:, :, :, :original_seq_len] = mask_additive
2785-
# Mask out the padding (already -inf from zeros -> where with default)
2786-
aligned_mask[:, :, :, original_seq_len:] = float("-inf")
2787-
2788-
# Slice to actual size with proper alignment
2789-
attn_mask = aligned_mask[:, :, :, :seq_len_kv]
2716+
attn_mask = attn_mask.view(attn_mask.size(0), 1, attn_mask.size(1), 1)
27902717
elif attn_mask.ndim != 4:
27912718
raise ValueError("Only 2D and 4D attention masks are supported for xformers attention.")
2792-
elif attn_mask.ndim == 4:
2793-
attn_mask = attn_mask.expand(batch_size, num_heads_q, seq_len_q, seq_len_kv).type_as(query)
2719+
attn_mask = attn_mask.expand(batch_size, num_heads_q, seq_len_q, seq_len_kv).type_as(query)
27942720

27952721
if enable_gqa:
27962722
if num_heads_q % num_heads_kv != 0:

‎src/diffusers/models/controlnets/controlnet_qwenimage.py‎

Lines changed: 16 additions & 55 deletions

0 commit comments

Comments
 (0)