Text-to-Image
Pruna AI
English
qwen
qwen-image
image-generation
image-editing
decoder-free
vae-free
dwd
Instructions to use PrunaAI/P-Q-Image-2.1-DWD with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Pruna AI
How to use PrunaAI/P-Q-Image-2.1-DWD with Pruna AI:
from pruna import PrunaModel model = PrunaModel.from_pretrained("PrunaAI/P-Q-Image-2.1-DWD") - Notebooks
- Google Colab
- Kaggle
Download src/pq_image_dwd/model.py from PrunaAI/P-Q-Image-2.1-DWD: direct link, hf CLI and curl.
- Browser
- Download file 11.5 kB
-
https://huggingface.co/PrunaAI/P-Q-Image-2.1-DWD/resolve/main/src/pq_image_dwd/model.py
- Command line
-
hf download hf://PrunaAI/P-Q-Image-2.1-DWD/src/pq_image_dwd/model.py
-
curl -L -o model.py https://huggingface.co/PrunaAI/P-Q-Image-2.1-DWD/resolve/main/src/pq_image_dwd/model.py
11.5 kB
| """The DWD tail on top of a stock diffusers QwenImage21Transformer2DModel (Qwen-Image-2.1: 32 single-stream blocks, | |
| D = 4096, one shared modulation for every block, causal_condition). | |
| The stock transformer is never modified. At the last sampler step: | |
| prefix the stock model's own input embeddings (img_in, txt_in, rotary), its time embedding + shared modulation and | |
| its first 32 - K blocks, run in bf16 with autocast off, on the whole joint sequence | |
| [text (+ condition-image tokens); target image] without a KV cache. This is exactly the stock forward up to | |
| block 32 - K. | |
| tail the trained copy of the last K blocks with its own time embedding, shared modulation and norm_out, run on | |
| the same joint sequence (the prefix rows are needed as attention keys) under bf16 autocast; norm_out is | |
| applied to the target-image rows only. | |
| head Linear(4096 -> 768): one 16x16 normalized-Oklab pixel tile per target token. | |
| Layout of the joint sequence (as the stock forward builds it): the text embeddings, with every vision-language image | |
| slot expanded to the 2x2 latent tokens it stands for, then one slot per 2x2 group of target tokens. Text and | |
| condition-image tokens are causal and modulated from t = 0; the target image is last, bidirectional, and modulated | |
| from the sampled t. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| from dataclasses import dataclass | |
| import torch | |
| import torch.nn as nn | |
| HEAD_OUT = 3 * 16 * 16 | |
| IMG_TOKENS_PER_SLOT = 4 # one vision-language image slot stands for 2x2 latent tokens | |
| class Cond: | |
| """Condition for one image: embeds [1, L, 4096] (bf16), mask [1, L] bool or None (None: no padding), img_mask | |
| [1, L] bool (the vision-language image slots; all False for text-to-image). Editing: cond_lat [1, Nc, 64] packed, | |
| normalized latents of the condition images (in order) and cond_shapes their (1, h, w) latent grids.""" | |
| embeds: torch.Tensor | |
| mask: torch.Tensor | None | |
| img_mask: torch.Tensor | |
| cond_lat: torch.Tensor | None = None | |
| cond_shapes: tuple = () | |
| def to(self, device) -> "Cond": | |
| return Cond(self.embeds.to(device), None if self.mask is None else self.mask.to(device), | |
| self.img_mask.to(device), None if self.cond_lat is None else self.cond_lat.to(device), | |
| self.cond_shapes) | |
| class Ctx: | |
| """Per-forward metadata shared by the prefix and the tail (the stock forward's prefill path, no KV cache).""" | |
| rotary: torch.Tensor # [N, head_dim / 2] complex | |
| target_mask: torch.Tensor # [N] bool, True at the target image's tokens | |
| segments: list # block-causal prefix segments for QwenImage21AttnProcessor | |
| key_valid: torch.Tensor | None # [1, N] bool or None | |
| n_txt: int # number of tokens before the target image (text + condition images) | |
| def target_img_mask(cond: Cond, h: int, w: int) -> torch.Tensor: | |
| """The transformer's img_mask: the condition's vision-language slots + one slot per 2x2 target tokens.""" | |
| return torch.cat([cond.img_mask, cond.img_mask.new_ones(cond.img_mask.shape[0], h * w // IMG_TOKENS_PER_SLOT)], 1) | |
| def img_shapes(cond: Cond, h: int, w: int) -> list: | |
| """Per-image (frame, h, w) latent grids: condition images first, the target last.""" | |
| return [*cond.cond_shapes, (1, h, w)] | |
| def check_grid(h: int, w: int): | |
| if h <= 0 or w <= 0 or h % 2 or w % 2: | |
| raise ValueError(f"the latent grid must be even in both directions (width and height multiples of 32), " | |
| f"got {w} x {h} tokens") | |
| def build_ctx(transformer, cond: Cond, h: int, w: int, device) -> tuple[Ctx, torch.Tensor, torch.Tensor]: | |
| """Mirrors QwenImage21Transformer2DModel.forward (prefill, no KV cache) up to the block loop, minus the embeddings. | |
| Returns (ctx, repeats, image_pad_mask).""" | |
| from diffusers.models.transformers.transformer_qwenimage21 import _qwenimage21_prefix_segments | |
| check_grid(h, w) | |
| shapes = img_shapes(cond, h, w) | |
| if (cond.cond_lat is None) != (not cond.cond_shapes): | |
| raise ValueError("cond_lat and cond_shapes must be given together") | |
| if cond.cond_lat is not None and cond.cond_lat.shape[1] != sum(math.prod(s) for s in cond.cond_shapes): | |
| raise ValueError("cond_lat does not match cond_shapes") | |
| img_mask = target_img_mask(cond, h, w) | |
| repeats = torch.where(img_mask, IMG_TOKENS_PER_SLOT, 1)[0] | |
| image_pad_mask = torch.repeat_interleave(img_mask[0], repeats) | |
| rotary = transformer.pos_embed(shapes, image_pad_mask, device=device) | |
| image_ids, target_mask = transformer.build_token_metadata(image_pad_mask, shapes) | |
| key_valid = None | |
| if cond.mask is not None: | |
| key_valid = torch.ones(cond.embeds.shape[0], image_pad_mask.shape[0], dtype=torch.bool, device=device) | |
| text_positions = (~image_pad_mask).nonzero(as_tuple=True)[0] | |
| vlm_text_positions = ~img_mask[0][: cond.mask.shape[1]] | |
| key_valid[:, text_positions] = cond.mask.bool()[:, vlm_text_positions] | |
| prefix_len = int((~target_mask).sum()) | |
| segments = _qwenimage21_prefix_segments(image_ids, prefix_len) | |
| return Ctx(rotary, target_mask, segments, key_valid, prefix_len), repeats, image_pad_mask | |
| def with_zero_row(timestep: torch.Tensor) -> torch.Tensor: | |
| """causal_condition: the extra t = 0 row that text and condition-image tokens are modulated from.""" | |
| return torch.cat([timestep, timestep.new_zeros(1)], dim=0) | |
| def run_block(blk, hs: torch.Tensor, mod: torch.Tensor, ctx: Ctx) -> torch.Tensor: | |
| return blk(hidden_states=hs, modulation=mod, rotary_emb=ctx.rotary, attention_mask=None, | |
| target_token_mask=ctx.target_mask, layer_cache=None, kv_cache_mode=None, cache_write_slice=None, | |
| segments=ctx.segments, key_valid=ctx.key_valid) | |
| def prefix_forward(transformer, n_blocks: int, x: torch.Tensor, cond: Cond, timestep: torch.Tensor, h: int, w: int): | |
| """The stock transformer's forward up to (not including) block `n_blocks`, without a KV cache. | |
| x [1, h*w, 64] packed target latents (bf16), timestep [1] (model_timestep). With condition images the stock | |
| hidden_states are cat([cond.cond_lat, x]) (condition images first). Pure bf16 with autocast off, as the stock | |
| pipeline runs. Returns (hs [1, N, D], ctx).""" | |
| with torch.autocast(x.device.type, enabled=False): | |
| t = transformer | |
| B = x.shape[0] | |
| ctx, repeats, image_pad_mask = build_ctx(t, cond, h, w, x.device) | |
| hidden = t.img_in(x if cond.cond_lat is None else torch.cat([cond.cond_lat.to(x.dtype), x], dim=1)) | |
| enc = t.txt_in(cond.embeds) | |
| joint = torch.cat([enc, enc.new_zeros(B, (h * w) // IMG_TOKENS_PER_SLOT, enc.shape[2])], dim=1) | |
| joint = joint.repeat_interleave(repeats, dim=1) | |
| joint[:, image_pad_mask] = hidden | |
| temb = t.time_text_embed(with_zero_row(timestep.to(hidden.dtype)), hidden) | |
| mod = t.modulation(temb) | |
| for blk in t.transformer_blocks[:n_blocks]: | |
| joint = run_block(blk, joint, mod, ctx) | |
| return joint, ctx | |
| # parameters kept in fp32 in the released file and at run time: under bf16 autocast every Linear runs in bf16 (so | |
| # bf16 storage changes none of them), but these RMSNorm weights are used directly and an fp32 weight keeps the | |
| # normalization in fp32 | |
| FP32_SUFFIXES = ("attn.norm_q.weight", "attn.norm_k.weight") | |
| def keeps_fp32(name: str) -> bool: | |
| return name.endswith(FP32_SUFFIXES) | |
| class DWDTail(nn.Module): | |
| """Trained copy of the last K blocks + its own time embedding, shared modulation and norm_out, and the DWD head. | |
| State dict keys: blocks.{i}.*, time_text_embed.*, modulation.1.weight, norm_out.linear.weight, head.weight, | |
| head.bias (the same module names as the diffusers transformer).""" | |
| def __init__(self, k: int, dim: int = 4096, num_attention_heads: int = 32, attention_head_dim: int = 128, | |
| mlp_ratio: int = 3, eps: float = 1e-6): | |
| super().__init__() | |
| from diffusers.models.transformers.transformer_qwenimage21 import (QwenImage21AdaLayerNormContinuous, | |
| QwenImage21TimestepProjEmbeddings, | |
| QwenImage21TransformerBlock) | |
| if dim != num_attention_heads * attention_head_dim: | |
| raise ValueError("dim must be num_attention_heads * attention_head_dim") | |
| self.k = k | |
| self.blocks = nn.ModuleList([QwenImage21TransformerBlock(dim, num_attention_heads, attention_head_dim, | |
| mlp_ratio=mlp_ratio, eps=eps) for _ in range(k)]) | |
| self.time_text_embed = QwenImage21TimestepProjEmbeddings(embedding_dim=dim) | |
| self.modulation = nn.Sequential(nn.SiLU(), nn.Linear(dim, 4 * dim, bias=False)) | |
| self.norm_out = QwenImage21AdaLayerNormContinuous(dim, dim, eps=eps) | |
| self.head = nn.Linear(dim, HEAD_OUT, bias=True) | |
| def for_transformer(cls, transformer, k: int, device="meta") -> "DWDTail": | |
| """An empty tail shaped like `transformer`'s last k blocks (on the meta device by default: load weights with | |
| load_state_dict(..., assign=True)).""" | |
| c = transformer.config | |
| with torch.device(device): | |
| return cls(k, c.num_attention_heads * c.attention_head_dim, c.num_attention_heads, c.attention_head_dim, | |
| c.mlp_ratio, c.eps) | |
| def load_weights(self, sd: dict[str, torch.Tensor], time_freqs: torch.Tensor) -> "DWDTail": | |
| """Load a tail state dict (any dtype): every tensor in bf16 except the RMSNorm weights (fp32, see | |
| FP32_SUFFIXES). time_freqs: the sinusoidal timestep table (a non-persistent fp32 buffer, not in the file), | |
| taken from the stock transformer.""" | |
| names = set(self.state_dict()) | |
| missing, extra = names - set(sd), set(sd) - names | |
| if missing or extra: | |
| raise KeyError(f"tail weights do not match the model: missing {sorted(missing)[:5]}, " | |
| f"extra {sorted(extra)[:5]}") | |
| self.load_state_dict({n: v.to(torch.float32 if keeps_fp32(n) else torch.bfloat16) for n, v in sd.items()}, | |
| strict=True, assign=True) | |
| self.time_text_embed.time_proj.freqs = time_freqs.detach().to(torch.float32).clone() | |
| left = [n for n, t in list(self.named_parameters()) + list(self.named_buffers()) if t.is_meta] | |
| if left: | |
| raise RuntimeError(f"tail tensors left unloaded: {left[:5]}") | |
| return self.requires_grad_(False).eval() | |
| def tokens(self, hs: torch.Tensor, timestep: torch.Tensor, ctx: Ctx) -> torch.Tensor: | |
| """hs [1, N, D] (prefix output), timestep [1] (model_timestep) -> norm_out target rows [1, h*w, D].""" | |
| temb = self.time_text_embed(with_zero_row(timestep.to(torch.bfloat16)), hs) | |
| mod = self.modulation(temb) | |
| for b in self.blocks: | |
| hs = run_block(b, hs, mod, ctx) | |
| return self.norm_out(hs[:, ctx.n_txt:], temb, ctx.target_mask[ctx.n_txt:]) | |
| def forward(self, hs: torch.Tensor, timestep: torch.Tensor, ctx: Ctx) -> torch.Tensor: | |
| """-> head output [1, h*w, 768] (normalized Oklab tiles, (c, p1, p2) order). Runs under bf16 autocast.""" | |
| with torch.autocast(hs.device.type, dtype=torch.bfloat16): | |
| return self.head(self.tokens(hs, timestep, ctx)) | |