Repository navigation
Fix Qwen Image 2.1 compile recompiles #15074
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
solo938
wants to merge
1
commit into
huggingface:main
Choose a base branch
from
solo938:qwenimage21-fix
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+85
−14
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -98,6 +98,36 @@ def get_dummy_inputs(self, batch_size: int = 1, device=torch_device) -> dict[str | |
| "img_mask": img_mask, | ||
| } | ||
|
|
||
| def get_generation_inputs(self, index: int, device=torch_device) -> dict[str, torch.Tensor]: | ||
| """ | ||
| Inputs for the `index`-th generation of a multi-size session: prompt length, condition-image size and target | ||
| size all vary, so the prefix length (text + condition-image tokens) differs from one generation to the next. | ||
| """ | ||
| text_len = 4 + (index % 4) | ||
| condition_tokens = 4 * (1 + index // 4) | ||
| condition_hw = {4: (2, 2), 8: (2, 4), 12: (3, 4), 16: (4, 4)}[condition_tokens] | ||
| target_hw = [(2, 2), (2, 4), (4, 2), (4, 4)][index % 4] | ||
| target_tokens = target_hw[0] * target_hw[1] | ||
|
|
||
| # The vision-language sequence is the text followed by one slot per 2x2 group of condition-image latents; the | ||
| # target image's slots are appended after it, so `img_mask` is longer than `encoder_hidden_states`. | ||
| vlm_len = text_len + condition_tokens // 4 | ||
|
|
||
| hidden_states = randn_tensor((1, condition_tokens + target_tokens, 4), generator=self.generator, device=device) | ||
| encoder_hidden_states = randn_tensor((1, vlm_len, 8), generator=self.generator, device=device) | ||
| encoder_hidden_states_mask = torch.ones((1, vlm_len), device=device, dtype=torch.long) | ||
| img_mask = torch.zeros((1, vlm_len + target_tokens // 4), device=device, dtype=torch.bool) | ||
| img_mask[:, text_len:] = True | ||
|
|
||
| return { | ||
| "hidden_states": hidden_states, | ||
| "encoder_hidden_states": encoder_hidden_states, | ||
| "encoder_hidden_states_mask": encoder_hidden_states_mask, | ||
| "timestep": torch.tensor([1.0], device=device), | ||
| "img_shapes": [[(1, *condition_hw), (1, *target_hw)]], | ||
| "img_mask": img_mask, | ||
| } | ||
|
|
||
|
|
||
| class TestQwenImage21Transformer(QwenImage21TransformerTesterConfig, ModelTesterMixin): | ||
| @pytest.mark.skip( | ||
|
|
@@ -218,6 +248,47 @@ def test_attention_backend_applies_to_decode_only(self, processor_name): | |
|
|
||
| torch.testing.assert_close(outputs[0], outputs[1]) | ||
|
|
||
| @pytest.mark.parametrize("processor_name", ["QwenImage21FlexAttnProcessor", "QwenImage21AttnProcessor"]) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We have a dedicated compilation tester class which should be used here. |
||
| def test_compiled_blocks_do_not_recompile_per_generation(self, processor_name): | ||
| """ | ||
| Regression test for https://github.com/huggingface/diffusers/issues/15027. | ||
|
|
||
| `prefix_len` (text + condition-image tokens) changes with every prompt length and condition-image size. | ||
| Values Dynamo guards by constant — the old `cache_write_slice.stop` — recompiled the repeated blocks for | ||
| every distinct prefix length, so a session of different-sized generations exhausted the recompile limit | ||
| (8) and `fullgraph=True` hard-failed. Plain `int` arguments become dynamic after their second distinct | ||
| value, so the compiled graph count must plateau instead of growing per generation. | ||
| """ | ||
| import diffusers.models.transformers.transformer_qwenimage21 as transformer_module | ||
| from diffusers.models.transformers.transformer_qwenimage21 import QwenImage21KVCache | ||
|
|
||
| init_dict = self.get_init_dict() | ||
| model = self.model_class(**init_dict).to(torch_device).eval() | ||
| model.set_attn_processor(getattr(transformer_module, processor_name)()) | ||
|
|
||
| # `backend="eager"`: the guard behavior under test is backend- and device-independent, and it keeps the | ||
| # flex path's uncompiled CPU fallback (a dense fp32 score matrix) out of the picture. | ||
| model.compile_repeated_blocks(fullgraph=True, backend="eager") | ||
|
|
||
| torch._dynamo.reset() | ||
| from torch._dynamo.utils import counters as dynamo_counters | ||
|
|
||
| dynamo_counters.clear() | ||
|
|
||
| graph_counts = [] | ||
| for index in range(12): | ||
| inputs = self.get_generation_inputs(index) | ||
| kv_cache = QwenImage21KVCache(init_dict["num_layers"]) | ||
| with torch.no_grad(): | ||
| model(**inputs, kv_cache=kv_cache, kv_cache_mode="extract", return_dict=False) | ||
| model(**inputs, kv_cache=kv_cache, kv_cache_mode="cached", return_dict=False) | ||
| graph_counts.append(dynamo_counters["stats"]["unique_graphs"]) | ||
|
|
||
| # Before the fix this loop raises `torch._dynamo.exc.FailOnRecompileLimitHit` (recompile limit 8) part-way | ||
| # through: every new prefix length added a graph. The first two generations legitimately specialize | ||
| # (static shapes, then dynamic shapes); afterwards the count must plateau. | ||
| assert graph_counts[-1] - graph_counts[1] <= 4 | ||
|
|
||
|
|
||
| class TestQwenImage21BlockCausalMask: | ||
| """ | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is a breaking change.