-
Notifications
You must be signed in to change notification settings - Fork 274
[FEAT] support for z-image-turbo #815
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
Merged
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
8e7385f
[FEAT] support for z-image
devgdovg de1bb36
fix wrong doc string
devgdovg 85667ac
patch scale key
devgdovg 431be72
add pytest case for z-image-turbo
devgdovg 938e418
fix test case
devgdovg 579826d
add test case for `skip_refiners` model
devgdovg a054f75
update example
lmxyy 5a101a4
update
lmxyy 06f3091
update docs
devgdovg 52a691e
update docs
devgdovg 727fac4
update docs
devgdovg 8bbdc1c
update
lmxyy 1d1c581
runnable
lmxyy c7d9e7a
rename the test
lmxyy da61478
skip the fp4_r256 test
lmxyy 14dd5f9
update the dependencies
lmxyy ef6efbb
update image link
lmxyy 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
7 changes: 7 additions & 0 deletions
7
docs/source/python_api/nunchaku.models.attention_processors.zimage.rst
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 |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| nunchaku.models.attention_processors.zimage | ||
| =========================================== | ||
|
|
||
| .. automodule:: nunchaku.models.attention_processors.zimage | ||
| :members: | ||
| :undoc-members: | ||
| :show-inheritance: |
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
7 changes: 7 additions & 0 deletions
7
docs/source/python_api/nunchaku.models.transformers.transformer_zimage.rst
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 |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| nunchaku.models.transformers.transformer\_zimage | ||
| ================================================ | ||
|
|
||
| .. automodule:: nunchaku.models.transformers.transformer_zimage | ||
| :members: | ||
| :undoc-members: | ||
| :show-inheritance: |
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 |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| Z-Image | ||
| ======= | ||
|
|
||
| The following is the example of running Nunchaku version of Z-Image text-to-image pipeline. | ||
|
|
||
| .. tabs:: | ||
|
|
||
| .. tab:: Z-Image-Turbo | ||
|
|
||
| .. literalinclude:: ../../../examples/v1/z-image-turbo.py | ||
| :language: python | ||
| :caption: Running Z-Image-Turbo (`examples/v1/z-image-turbo.py <https://github.com/nunchaku-tech/nunchaku/blob/main/examples/v1/z-image-turbo.py>`__) | ||
| :linenos: | ||
|
|
||
|
|
||
| For more details, see :class:`~nunchaku.models.transformers.transformer_zimage.NunchakuZImageTransformer2DModel`. |
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 |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| import torch | ||
| from diffusers.pipelines.z_image.pipeline_z_image import ZImagePipeline | ||
|
|
||
| from nunchaku import NunchakuZImageTransformer2DModel | ||
| from nunchaku.utils import get_precision | ||
|
|
||
| if __name__ == "__main__": | ||
| precision = get_precision() # auto-detect your precision is 'int4' or 'fp4' based on your GPU | ||
| rank = 128 # Use 32 for faster sampling; 256 (INT4 only) for best quality | ||
| transformer = NunchakuZImageTransformer2DModel.from_pretrained( | ||
| f"nunchaku-tech/nunchaku-z-image-turbo/svdq-{precision}_r{rank}-z-image-turbo.safetensors" | ||
| ) | ||
|
|
||
| pipe = ZImagePipeline.from_pretrained( | ||
| "Tongyi-MAI/Z-Image-Turbo", transformer=transformer, torch_dtype=torch.bfloat16, low_cpu_mem_usage=False | ||
| ).to("cuda") | ||
|
|
||
| prompt = "a young military male cooking in the kitchen for therapy" | ||
|
|
||
| image = pipe( | ||
| prompt=prompt, | ||
| height=1024, | ||
| width=1024, | ||
| num_inference_steps=8, # This actually results in 8 DiT forwards | ||
| guidance_scale=0.0, # Guidance should be 0 for the Turbo models | ||
| generator=torch.Generator().manual_seed(12345), | ||
| ).images[0] | ||
|
|
||
| image.save(f"z-image-turbo-{precision}_r{rank}.png") | ||
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
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 |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| """ | ||
| Attention processor implementations for :class:`~nunchaku.models.transformers.transformer_zimage.NunchakuZImageAttention`. | ||
| """ | ||
|
|
||
| from typing import Optional | ||
|
|
||
| import torch | ||
| from diffusers.models.attention_dispatch import dispatch_attention_fn | ||
| from diffusers.models.transformers.transformer_z_image import ZSingleStreamAttnProcessor | ||
|
|
||
|
|
||
| class NunchakuZSingleStreamAttnProcessor(ZSingleStreamAttnProcessor): | ||
| """ | ||
| Nunchaku attention processor for Z-Image-Turbo. | ||
| Adapted from diffusers.models.transformers.transformer_z_image.ZSingleStreamAttnProcessor. | ||
|
|
||
| """ | ||
|
|
||
| def __init__(self): | ||
| super().__init__() | ||
|
|
||
| # Adapted from diffusers.models.transformers.transformer_z_image.ZSingleStreamAttnProcessor#__call__ | ||
| def __call__( | ||
| self, | ||
| attn, | ||
| hidden_states: torch.Tensor, | ||
| encoder_hidden_states: Optional[torch.Tensor] = None, | ||
| attention_mask: Optional[torch.Tensor] = None, | ||
| freqs_cis: Optional[torch.Tensor] = None, | ||
| ) -> torch.Tensor: | ||
| """ | ||
| Forward pass of the attention module. Adapted from diffusers.models.transformers.transformer_z_image.ZSingleStreamAttnProcessor#__call__. | ||
| """ | ||
|
|
||
| qkv = attn.to_qkv(hidden_states) | ||
| query, key, value = qkv.chunk(3, dim=-1) | ||
|
|
||
| query = query.unflatten(-1, (attn.heads, -1)) | ||
| key = key.unflatten(-1, (attn.heads, -1)) | ||
| value = value.unflatten(-1, (attn.heads, -1)) | ||
|
|
||
| # Apply Norms | ||
| if attn.norm_q is not None: | ||
| query = attn.norm_q(query) | ||
| if attn.norm_k is not None: | ||
| key = attn.norm_k(key) | ||
|
|
||
| # Apply RoPE | ||
| def apply_rotary_emb(x_in: torch.Tensor, freqs_cis: torch.Tensor) -> torch.Tensor: | ||
| with torch.amp.autocast("cuda", enabled=False): | ||
| x = torch.view_as_complex(x_in.float().reshape(*x_in.shape[:-1], -1, 2)) | ||
| freqs_cis = freqs_cis.unsqueeze(2) | ||
| x_out = torch.view_as_real(x * freqs_cis).flatten(3) | ||
| return x_out.type_as(x_in) # todo | ||
|
|
||
| if freqs_cis is not None: | ||
| query = apply_rotary_emb(query, freqs_cis) | ||
| key = apply_rotary_emb(key, freqs_cis) | ||
|
|
||
| # Cast to correct dtype | ||
| dtype = query.dtype | ||
| query, key = query.to(dtype), key.to(dtype) | ||
|
|
||
| # From [batch, seq_len] to [batch, 1, 1, seq_len] -> broadcast to [batch, heads, seq_len, seq_len] | ||
| if attention_mask is not None and attention_mask.ndim == 2: | ||
| attention_mask = attention_mask[:, None, None, :] | ||
|
|
||
| # Compute joint attention | ||
| hidden_states = dispatch_attention_fn( | ||
| query, | ||
| key, | ||
| value, | ||
| attn_mask=attention_mask, | ||
| dropout_p=0.0, | ||
| is_causal=False, | ||
| backend=self._attention_backend, | ||
| parallel_config=self._parallel_config, | ||
| ) | ||
|
|
||
| # Reshape back | ||
| hidden_states = hidden_states.flatten(2, 3) | ||
| hidden_states = hidden_states.to(dtype) | ||
|
|
||
| output = attn.to_out[0](hidden_states) | ||
| if len(attn.to_out) > 1: # dropout | ||
| output = attn.to_out[1](output) | ||
|
|
||
| return output |
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
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
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 should probably be set to
num_inference_steps=9to match the official example: https://github.com/Tongyi-MAI/Z-Image?tab=readme-ov-file#-quick-start