# Copyright 2026 The HuggingFace Team, The Jeveration Authors and Bytedance Ltd. and/or its affiliates. # All rights reserved. # # Licensed under the Apache License, Version 2.0. See the LICENSE and NOTICE files in this repository. # # Adapted from TA-TiTok's text-aware decoder (https://github.com/bytedance/1d-tokenizer, Apache-2.0, # modeling/modules/blocks.py) and Jeveration's source decoder (https://github.com/Carol-lyh/Jeveration, Apache-2.0, # jeveration/tokenizer.py), with the same computations. Each layer's packed attention projections are split into # `attn.to_q`, `to_k`, `to_v` and `to_out.0`, and short module names are spelled out (see `DECODER_RENAMES` in # convert_jeveration_to_diffusers.py). from collections import OrderedDict import torch import torch.nn as nn from diffusers import ModelMixin from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.models.attention import AttentionMixin, AttentionModuleMixin from diffusers.models.attention_dispatch import dispatch_attention_fn class JeverationDecoderAttnProcessor: """Unmasked self-attention over all positions.""" _attention_backend = None _parallel_config = None def __call__(self, attn, hidden_states): query = attn.to_q(hidden_states).unflatten(-1, (attn.heads, -1)) key = attn.to_k(hidden_states).unflatten(-1, (attn.heads, -1)) value = attn.to_v(hidden_states).unflatten(-1, (attn.heads, -1)) hidden_states = dispatch_attention_fn( query, key, value, backend=self._attention_backend, parallel_config=self._parallel_config ) return attn.to_out[0](hidden_states.flatten(2, 3).to(query.dtype)) class JeverationDecoderAttention(nn.Module, AttentionModuleMixin): _default_processor_cls = JeverationDecoderAttnProcessor _available_processors = [JeverationDecoderAttnProcessor] def __init__(self, dim, heads): super().__init__() self.heads = heads self.to_q = nn.Linear(dim, dim) self.to_k = nn.Linear(dim, dim) self.to_v = nn.Linear(dim, dim) self.to_out = nn.ModuleList([nn.Linear(dim, dim), nn.Dropout(0.0)]) self.set_processor(JeverationDecoderAttnProcessor()) def forward(self, hidden_states): return self.processor(self, hidden_states) class ResidualAttentionBlock(nn.Module): def __init__(self, width, heads, mlp_ratio=4.0): super().__init__() self.norm1 = nn.LayerNorm(width) self.attn = JeverationDecoderAttention(width, heads) self.norm2 = nn.LayerNorm(width) mlp_width = int(width * mlp_ratio) self.mlp = nn.Sequential( OrderedDict( [("fc1", nn.Linear(width, mlp_width)), ("gelu", nn.GELU()), ("fc2", nn.Linear(mlp_width, width))] ) ) def forward(self, hidden_states): hidden_states = hidden_states + self.attn(self.norm1(hidden_states)) return hidden_states + self.mlp(self.norm2(hidden_states)) class SourceGate(nn.Module): """Blends the source picture's features into the image patches after a decoder layer.""" def __init__(self, width): super().__init__() self.patch_gate = nn.Linear(width, 1) self.source_gate = nn.Linear(width, 1) self.proj = nn.Linear(width, width) def forward(self, previous, patches, source): patch_weight = torch.sigmoid(self.patch_gate(previous)) source_weight = torch.sigmoid(self.source_gate(source)) return patches * (1 - patch_weight) + source_weight * self.proj(source) class JeverationImageDecoder(ModelMixin, ConfigMixin, AttentionMixin): """TA-TiTok's text-aware decoder at 512 px: 128 codes and the CLIP text tower's per-token output -> RGB. With `source_branch`, a gated branch also reads the source image (image-to-image): every `gate_every` layers, the patch tokens are partly replaced by features of the source image and its task embedding. The tokenizer's codebook is stored here, so the decoder turns code indices into pixels on its own. """ # The code embeddings are looked up in float32, as in the reference. _keep_in_fp32_modules = ["codebook"] @register_to_config def __init__( self, image_size: int = 512, patch_size: int = 16, width: int = 1024, num_layers: int = 24, num_heads: int = 16, num_latent_tokens: int = 128, token_size: int = 64, codebook_size: int = 8192, text_context_length: int = 77, text_embed_dim: int = 768, source_branch: bool = False, num_tasks: int = 4, gate_every: int = 4, ): super().__init__() self.grid_size = image_size // patch_size scale = width**-0.5 self.register_buffer("codebook", torch.zeros(codebook_size, token_size)) self.decoder_embed = nn.Linear(token_size, width) self.class_embedding = nn.Parameter(scale * torch.randn(1, width)) self.positional_embedding = nn.Parameter(scale * torch.randn(self.grid_size**2 + 1, width)) self.mask_token = nn.Parameter(scale * torch.randn(1, 1, width)) self.latent_token_positional_embedding = nn.Parameter(scale * torch.randn(num_latent_tokens, width)) self.norm_in = nn.LayerNorm(width) self.transformer = nn.ModuleList([ResidualAttentionBlock(width, num_heads) for _ in range(num_layers)]) self.norm_out = nn.LayerNorm(width) self.ffn = nn.Sequential(nn.Conv2d(width, patch_size * patch_size * 3, 1)) self.conv_out = nn.Conv2d(3, 3, 3, padding=1) self.text_guidance_proj = nn.Linear(text_embed_dim, width) self.text_guidance_positional_embedding = nn.Parameter(scale * torch.randn(text_context_length, width)) if source_branch: self.cond_in = nn.Sequential( nn.Conv2d(3, 64, 3, 2, 1), nn.GELU(), nn.Conv2d(64, 128, 3, 2, 1), nn.GELU(), nn.Conv2d(128, 256, 3, 2, 1), nn.GELU(), nn.Conv2d(256, width, 2, 2), ) self.cond_task = nn.Embedding(num_tasks + 1, width) self.cond_gates = nn.ModuleList( [SourceGate(width) for _ in range(len(range(gate_every - 1, num_layers, gate_every)))] ) def to_pixels(self, patches): """[B, patch * patch * 3, grid, grid] -> [B, 3, grid * patch, grid * patch], the patch layout of the trained decoder.""" batch_size, _, grid_height, grid_width = patches.shape patch = self.config.patch_size patches = patches.view(batch_size, patch, patch, 3, grid_height, grid_width).permute(0, 3, 4, 1, 5, 2) return patches.reshape(batch_size, 3, grid_height * patch, grid_width * patch) def forward(self, codes, text_guidance, source=None, task=None): """ Args: codes (`torch.Tensor`): The sampled codebook indices `[B, N]` (int64). text_guidance (`torch.Tensor`): The CLIP text features `[B, 77, 768]`. source (`torch.Tensor`, *optional*): The source images `[B, 3, 512, 512]` in [0, 1], for the source branch only. task (`torch.Tensor`, *optional*): The task ids `[B]` (> 0), given together with `source`. Returns: `torch.Tensor`: the images `[B, 3, 512, 512]`, not clamped. """ if (source is None) != (task is None): raise ValueError("Give both `source` and `task`, or neither.") if source is not None and not self.config.source_branch: raise ValueError("This decoder has no source branch; use the source image decoder for image-to-image.") dtype = self.dtype hidden_states = self.decoder_embed(self.codebook[codes].to(dtype)) batch_size, seq_len = hidden_states.shape[:2] num_patches = self.grid_size**2 mask_tokens = self.mask_token.repeat(batch_size, num_patches, 1).to(hidden_states.dtype) if source is not None: source_features = self.cond_in(source.to(dtype).contiguous()).flatten(2).transpose(1, 2) source_features = source_features + self.cond_task(task).unsqueeze(1) class_token = self.class_embedding.unsqueeze(0).expand(batch_size, -1, -1).to(mask_tokens.dtype) mask_tokens = torch.cat([class_token, mask_tokens], dim=1) + self.positional_embedding.to(mask_tokens.dtype) hidden_states = hidden_states + self.latent_token_positional_embedding[:seq_len] hidden_states = torch.cat([mask_tokens, hidden_states], dim=1) text = self.text_guidance_proj(text_guidance.to(dtype)) + self.text_guidance_positional_embedding hidden_states = self.norm_in(torch.cat([hidden_states, text], dim=1)) # Position 0 is the class token, then come the image patches. patch_positions = slice(1, 1 + num_patches) gate_index = 0 for layer_index, layer in enumerate(self.transformer): previous = hidden_states hidden_states = layer(hidden_states) if source is not None and (layer_index + 1) % self.config.gate_every == 0: patches = self.cond_gates[gate_index]( previous[:, patch_positions], hidden_states[:, patch_positions], source_features ) gate_index += 1 hidden_states = torch.cat( [hidden_states[:, :1], patches.to(hidden_states.dtype), hidden_states[:, 1 + num_patches :]], 1 ) hidden_states = self.norm_out(hidden_states[:, patch_positions]) hidden_states = hidden_states.permute(0, 2, 1).reshape(batch_size, -1, self.grid_size, self.grid_size) return self.conv_out(self.to_pixels(self.ffn(hidden_states)))