Skip to content

enable compilation in qwen image. #12061

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
wants to merge 6 commits into
base: main
Choose a base branch
from
Open

enable compilation in qwen image. #12061

wants to merge 6 commits into from

Conversation

sayakpaul
Copy link
Member

@sayakpaul sayakpaul commented Aug 4, 2025

What does this PR do?

  • Adds tests for the Qwen transformer model tests.
  • Enable compilation with triggering recompilations.

Timing (compilation) gathered from an H100:

  • PR branch: timings.mean()=tensor(42.8954)
  • tests/qwen-image: timings.mean()=tensor(75.9385)
Code
from diffusers import DiffusionPipeline
import torch
import time

pipe = DiffusionPipeline.from_pretrained("Qwen/Qwen-Image", torch_dtype=torch.bfloat16).to("cuda")
# pipe.load_lora_weights("trained-qwen-image-lora")
pipe.transformer.compile(fullgraph=True)

timings = []
for _ in range(3):
    start = time.time()
    image = pipe(
        "a 3dicon, a llama with a signboard saying 'Qwen is awesome'", 
        guidance_scale=1.0, 
        num_inference_steps=50,

    ).images[0]
    end = time.time()
    timings.append(end - start)

timings = torch.tensor(timings)
print(f"{timings.mean()=}")
image.save("llama_pretrained.png")

@sayakpaul sayakpaul requested a review from a-r-r-o-w August 4, 2025 10:18
Comment on lines -201 to -204
if self.pos_freqs.device != device:
self.pos_freqs = self.pos_freqs.to(device)
self.neg_freqs = self.neg_freqs.to(device)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recompilation trigger one.

if isinstance(video_fhw, list):
video_fhw = video_fhw[0]
frame, height, width = video_fhw
rope_key = f"{frame}_{height}_{width}"

if rope_key not in self.rope_cache:
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recompilation trigger two.

Comment on lines +1714 to +1718
if self.model_class.__name__ == "QwenImageTransformer2DModel":
pytest.skip(
"QwenImageTransformer2DModel doesn't support group offloading with disk. Needs to be investigated."
)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will investigate in a follow-up.

@HuggingFaceDocBuilderDev

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Base automatically changed from tests/qwen-image to main August 4, 2025 10:58
@a-r-r-o-w
Copy link
Member

@sayakpaul Could you rebase with main? Sorry I didn't see this before stacked over tests/qwen-image

@sayakpaul
Copy link
Member Author

Done!

@@ -236,6 +223,25 @@ def forward(self, video_fhw, txt_seq_lens, device):

return vid_freqs, txt_freqs

@functools.lru_cache(maxsize=None)
def _compute_video_freqs(self, frame, height, width):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO: we need to remove frame (can be done in future PR)

@@ -236,6 +223,25 @@ def forward(self, video_fhw, txt_seq_lens, device):

return vid_freqs, txt_freqs

@functools.lru_cache(maxsize=None)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's remove the self.rope_cache and just use the lru_cache implementation? WDYT @yiyixuxu?

WDYT about maybe putting maxsize=128 or something here so that long running services that use diffusers don't accidentally die with OOM (probably very unlikely though) @sayakpaul?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maxsize=128 sounds reasonable to me.

@@ -179,6 +180,8 @@ def __init__(self, theta: int, axes_dim: List[int], scale_rope=False):
dim=1,
)
self.rope_cache = {}
self.register_buffer("pos_freqs", pos_freqs, persistent=False)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is most likely not equivalent. When registered as buffer, if the model is loaded in bf16, the precision of these will bf16 instead of fp32. Doing RoPE in bf16 may harm image quality, so we need to be careful here. Not sure what's best to do here -- maybe for now we can put the rope layer in _keep_modules_in_fp32?

This recompilation related problem seems to have become too common with RoPE. Maybe we need to rethink the design a bit.

Copy link
Member Author

@sayakpaul sayakpaul Aug 4, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just for the record, sharing the recompilation error we get without the buffer implementation:

>               raise exc.RecompileError(message)

E               torch._dynamo.exc.RecompileError: Recompiling function forward in /fsx/sayak/diffusers/src/diffusers/models/transformers/transformer_qwenimage.py:529

E                   triggered by the following guard failure(s):

E                   - 0/0: tensor 'self._modules['pos_embed'].neg_freqs' dispatch key set mismatch. expected DispatchKeySet(CPU, BackendSelect, ADInplaceOrView, AutogradCPU), actual DispatchKeySet(CUDA, BackendSelect, ADInplaceOrView, AutogradCUDA)


../miniconda3/envs/diffusers/lib/python3.10/site-packages/torch/_dynamo/guards.py:3822: RecompileError

But I agree with your first point.

@sayakpaul sayakpaul requested a review from yiyixuxu August 4, 2025 13:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants