creegon's picture
Release 0.1.0 (same files as staging-0.1.0 @ 90a07ac4)
7b0b7bc verified
Raw History Blame Contribute Delete
7.2 kB
"""Reuse the actual Diffusers Qwen-Image-2.1 layers, with packed Ascend attention.
Only the execution layout changes: [samples, tokens, D] -> [packed_tokens, 1, D].
All tokens share every block's Q/K/V/O and SwiGLU. No language expert, cross
attention, token embedding, or vocabulary head exists in this generator.
"""
from dataclasses import asdict, dataclass
from collections import OrderedDict
import torch
from torch import nn
from torch.nn import functional as F
from . import qwenimage21_transformer as official
from .sequence import PackedDocument, PackedSequence, PackedSegment
@dataclass
class DiTConfig:
num_layers: int = 34
num_attention_heads: int = 9
attention_head_dim: int = 128
context_in_dim: int = 1024
mlp_ratio: int = 3
in_channels: int = 64
out_channels: int = 64
patch_size: int = 1
axes_dims_rope: tuple = (16, 56, 56)
causal_condition: bool = True
def validate(self):
if self.patch_size != 1 or not self.causal_condition:
raise ValueError('This T2I recipe requires patch=1 and Qwen2.1 block-causal conditioning')
if sum(self.axes_dims_rope) != self.attention_head_dim or any(x % 2 for x in self.axes_dims_rope):
raise ValueError('RoPE axes must be even and sum to head dimension')
def reference_attention(query, key, value, schedule):
"""Apply causal text attention and full image attention per packed sample."""
parts = []
start = 0
for document in schedule.documents:
text_end = start + document.segments[0].length
end = start + document.length
q_text = query[:, start:text_end].transpose(1, 2)
k_text = key[:, start:text_end].transpose(1, 2)
v_text = value[:, start:text_end].transpose(1, 2)
parts.append(F.scaled_dot_product_attention(q_text, k_text, v_text, is_causal=True).transpose(1, 2))
q_image = query[:, text_end:end].transpose(1, 2)
k_full = key[:, start:end].transpose(1, 2)
v_full = value[:, start:end].transpose(1, 2)
parts.append(F.scaled_dot_product_attention(q_image, k_full, v_full).transpose(1, 2))
start = end
return torch.cat(parts, dim=1)
class PackedProcessor:
"""No global patch: each generator owns its processor/backend."""
def __init__(self, backend='reference'):
self.backend = backend
self.fused = None
def __call__(self, attn, hidden_states, rotary_emb=None, attention_mask=None, **kwargs):
if kwargs.get('kv_cache_mode') is not None:
raise ValueError('Packed training does not accept inference KV caches')
schedule = attention_mask
n = hidden_states.shape[0]
x = hidden_states.reshape(1, n, -1)
q, k, v, _ = official._qwenimage21_prepare_qkv(attn, x, None, None, None, None)
# Equivalent real arithmetic avoids unsupported complex NPU operations.
cos,sin=rotary_emb
def rotate(value):
pair=value.float().reshape(*value.shape[:-1],-1,2)
a,b=pair.unbind(-1)
return torch.stack((a*cos-b*sin,b*cos+a*sin),-1).flatten(-2).to(value.dtype)
q,k=rotate(q),rotate(k)
if self.backend == 'ascend':
if self.fused is None:
from .npu_attention import AscendBlockAttentionBackend
self.fused = AscendBlockAttentionBackend()
out = self.fused(q[0], k[0], v[0], schedule)[None]
else:
out = reference_attention(q, k, v, schedule)
return attn.to_out[1](attn.to_out[0](out.flatten(2))).reshape(n, 1, -1)
class PackedSingleStreamDiT(nn.Module):
def __init__(self, config=None, backend='reference'):
super().__init__()
self.recipe = config or DiTConfig()
self.recipe.validate()
if backend not in ('reference', 'ascend'):
raise ValueError(backend)
self.dit = official.QwenImage21Transformer2DModel(**asdict(self.recipe))
processor = PackedProcessor(backend)
for block in self.dit.transformer_blocks:
block.attn.set_processor(processor)
self._rope_cache = OrderedDict()
@property
def config(self):
return self.dit.config
@property
def dtype(self):
return next(self.parameters()).dtype
def rope(self, length, h, w, device):
key=(length,h,w,str(device))
if key not in self._rope_cache:
# Use the official coordinate/frequency implementation unchanged on CPU.
mask=torch.arange(length+h*w)>=length
freq=self.dit.pos_embed([(1,h,w)],mask,torch.device('cpu'))
self._rope_cache[key]=(freq.real.to(device)[None,:,None],freq.imag.to(device)[None,:,None])
if len(self._rope_cache)>128:self._rope_cache.popitem(last=False)
return self._rope_cache[key]
def forward(self, images, contexts, timesteps, return_joint=False):
"""images: list [64,H,W]; contexts: unpadded list [L,1024]; t: [B]."""
if not images or len(images) != len(contexts) or timesteps.shape != (len(images),):
raise ValueError('Expected matching nonempty image/context/time batch')
hidden, rope, rows, image_indices, documents = [], [], [], [], []
offset = 0
for i, (image, context) in enumerate(zip(images, contexts)):
if image.ndim != 3 or image.shape[0] != self.recipe.in_channels:
raise ValueError('Expected a CHW latent')
if context.ndim != 2 or context.shape[1] != self.recipe.context_in_dim or not len(context):
raise ValueError('Expected nonempty unpadded text features')
h, w = image.shape[-2:]
length, count = len(context), h*w
hidden.append(torch.cat((self.dit.txt_in(context), self.dit.img_in(image.flatten(1).T)), 0))
rope.append(self.rope(length,h,w,image.device))
# A shared t=0 embedding is used for every text token, exactly as official causal_condition.
rows.extend([len(images)]*length + [i]*count)
image_indices.extend(range(offset+length, offset+length+count))
documents.append(PackedDocument(str(i), (
PackedSegment(length, 'causal', 'text', 'generation'),
PackedSegment(count, 'full', 'image', 'generation'))))
offset += length+count
x = torch.cat(hidden)[:, None, :]
rotary = tuple(torch.cat([r[i] for r in rope],dim=1) for i in range(2))
schedule = PackedSequence(tuple(documents))
t = torch.cat((timesteps.to(x.dtype), timesteps.new_zeros(1).to(x.dtype)))
temb = self.dit.time_text_embed(t, x)
row = torch.tensor(rows, device=x.device)
modulation = self.dit.modulation(temb)[row]
for block in self.dit.transformer_blocks:
x = block(x, modulation, rotary_emb=rotary, attention_mask=schedule)
if return_joint:
return x[:, 0]
index = torch.tensor(image_indices, device=x.device)
# Only image tokens have an output head/loss. Tokenwise t selection is unchanged.
out = self.dit.proj_out(self.dit.norm_out(x[index], temb[row[index]]))[:, 0]
return out