Instructions to use nebulette/nano-transformers with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use nebulette/nano-transformers with Transformers:
# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("nebulette/nano-transformers", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload 4 files
Browse filesFiles changed (4)
- __init__.pyAdded
- model.pyAdded+290
- pipeline.pyAdded+234
- vae.pyAdded+380
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290import mathfrom safetensors.torch import load_modelimport torchimport torch.nn as nnimport torch.nn.functional as F
SPRINT_NUM_F = 2SPRINT_NUM_H = 2TEXT_EMBED_DIM = 640
def adaln( x: torch.Tensor, scale: torch.Tensor, shift: torch.Tensor, eps: float = 1e-6): normalized = F.layer_norm( x, normalized_shape=(x.shape[-1],), weight=None, bias=None, eps=eps, )
return normalized * (1 + scale) + shift
def rope_2d(head_dim, height, width, device): """Split-half 2D RoPE over centered token coordinates (x frequencies, then y), as (1, N, 1, head_dim // 2, 2, 2) rotations.""" axis_dim = head_dim // 2 inv_freq = 1.0 / (10000.0 ** (torch.arange(0, axis_dim, 2, dtype=torch.float32, device=device) / axis_dim)) y = torch.arange(height, dtype=torch.float32, device=device) - (height - 1) / 2 x = torch.arange(width, dtype=torch.float32, device=device) - (width - 1) / 2 y, x = torch.meshgrid(y, x, indexing="ij") angles = torch.cat([torch.outer(x.flatten(), inv_freq), torch.outer(y.flatten(), inv_freq)], dim=-1) cos, sin = torch.cos(angles), torch.sin(angles) return torch.stack([cos, -sin, sin, cos], dim=-1).view(1, height * width, 1, axis_dim, 2, 2)
def modulate(x, shift, scale): return torch.addcmul(shift, x, 1 + scale)
def rope_split_half(x, pe): """Differentiable ck.apply_rope_split_half1: pair k is (x[k], x[k + head_dim // 2]).""" x_ = x.reshape(*x.shape[:-1], 2, -1).movedim(-2, -1).unsqueeze(-2).to(pe.dtype) return (pe[..., 0] * x_[..., 0] + pe[..., 1] * x_[..., 1]).movedim(-1, -2).reshape(x.shape).type_as(x)
def norm_rope(q, k, q_norm, k_norm, pe): return rope_split_half(q_norm(q), pe), rope_split_half(k_norm(k), pe)
class Embed(nn.Module): def __init__(self, in_dim, hidden_size, norm=False, dtype=None, device=None): super().__init__() self.proj = nn.Linear(in_dim, hidden_size, bias=True, dtype=dtype, device=device) self.norm = nn.RMSNorm(hidden_size, eps=1e-6, dtype=dtype, device=device) if norm else nn.Identity()
def forward(self, x): return self.norm(self.proj(x))
class FeedForward(nn.Module): def __init__(self, dim, hidden_dim, dtype=None, device=None): super().__init__() self.w12 = nn.Linear(dim, hidden_dim * 2, bias=False, dtype=dtype, device=device) self.w3 = nn.Linear(hidden_dim, dim, bias=False, dtype=dtype, device=device)
def forward(self, x): x1, x2 = self.w12(x).chunk(2, dim=-1) return self.w3(F.silu(x1) * x2)
class Attention(nn.Module): """Self-attention over image tokens with 2D RoPE, optionally joint with (non-rotated) text keys and values."""
def __init__(self, dim, num_heads, cross_attention, dtype=None, device=None): super().__init__() self.num_heads = num_heads self.head_dim = dim // num_heads self.qkv_x = nn.Linear(dim, dim * 3, bias=False, dtype=dtype, device=device) self.kv_y = nn.Linear(dim, dim * 2, bias=False, dtype=dtype, device=device) if cross_attention else None self.q_norm = nn.RMSNorm(self.head_dim, eps=1e-6, dtype=dtype, device=device) self.k_norm = nn.RMSNorm(self.head_dim, eps=1e-6, dtype=dtype, device=device) self.proj = nn.Linear(dim, dim, bias=True, dtype=dtype, device=device)
def forward(self, x, txt, pe, txt_bias, transformer_options={}): b, n, c = x.shape q, k, v = self.qkv_x(x).view(b, n, 3, self.num_heads, self.head_dim).unbind(2) q, k = norm_rope(q, k, self.q_norm, self.k_norm, pe) mask = None if self.kv_y is not None: ky, vy = self.kv_y(txt).view(b, -1, 2, self.num_heads, self.head_dim).unbind(2) k = torch.cat([k, self.k_norm(ky)], dim=1) v = torch.cat([v, vy], dim=1) # Image keys are always visible; text keys carry log(emphasis weight), -inf for padding. mask = F.pad(txt_bias, (n, 0))[:, None, None, :] # x = optimized_attention(q.reshape(b, n, c), k.reshape(b, -1, c), v.reshape(b, -1, c), self.num_heads, mask=mask, transformer_options=transformer_options) q = q.transpose(1, 2) k = k.transpose(1, 2) v = v.transpose(1, 2) # Mask from ldm/modules/attention, attention_pytorch() function. if mask is not None: # add a batch dimension if there isn't already one if mask.ndim == 2: mask = mask.unsqueeze(0) # add a heads dimension if there isn't already one if mask.ndim == 3: mask = mask.unsqueeze(1) x = F.scaled_dot_product_attention(q, k, v, attn_mask=mask) x = x.transpose(1, 2).reshape(b, n, c)
return self.proj(x)
class DiTBlock(nn.Module): """Image block; its adaLN modulation is computed by the caller (adaLN-single)."""
def __init__(self, hidden_size, num_heads, mlp_hidden, cross_attention, dtype=None, device=None): super().__init__() self.norm1 = nn.RMSNorm(hidden_size, eps=1e-6, dtype=dtype, device=device) self.attn = Attention(hidden_size, num_heads, cross_attention, dtype=dtype, device=device) self.norm2 = nn.RMSNorm(hidden_size, eps=1e-6, dtype=dtype, device=device) self.mlp = FeedForward(hidden_size, mlp_hidden, dtype=dtype, device=device)
def forward(self, x, txt, pe, mod, txt_bias, transformer_options={}): shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = mod.chunk(6, dim=-1) x = torch.addcmul(x, gate_msa, self.attn(modulate(self.norm1(x), shift_msa, scale_msa), txt, pe, txt_bias, transformer_options=transformer_options)) return torch.addcmul(x, gate_mlp, self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp)))
class TextRefineAttention(nn.Module): def __init__(self, dim, num_heads, dtype=None, device=None): super().__init__() self.num_heads = num_heads self.head_dim = dim // num_heads self.qkv = nn.Linear(dim, dim * 3, bias=False, dtype=dtype, device=device) self.q_norm = nn.RMSNorm(self.head_dim, eps=1e-6, dtype=dtype, device=device) self.k_norm = nn.RMSNorm(self.head_dim, eps=1e-6, dtype=dtype, device=device) self.proj = nn.Linear(dim, dim, bias=True, dtype=dtype, device=device)
def forward(self, x, mask, transformer_options={}): b, n, c = x.shape q, k, v = self.qkv(x).view(b, n, 3, self.num_heads, self.head_dim).unbind(2) q, k = self.q_norm(q), self.k_norm(k) # SDPA expects (B, H, N, D) q = q.transpose(1, 2) k = k.transpose(1, 2) v = v.transpose(1, 2) # x = optimized_attention(self.q_norm(q).reshape(b, n, c), self.k_norm(k).reshape(b, n, c), v.reshape(b, n, c), self.num_heads, mask=mask, transformer_options=transformer_options) x = F.scaled_dot_product_attention(q, k, v) x = x.transpose(1, 2).reshape(b, n, c) return self.proj(x)
class TextRefineBlock(nn.Module): def __init__(self, hidden_size, num_heads, mlp_hidden, dtype=None, device=None): super().__init__() self.norm1 = nn.RMSNorm(hidden_size, eps=1e-6, dtype=dtype, device=device) self.attn = TextRefineAttention(hidden_size, num_heads, dtype=dtype, device=device) self.norm2 = nn.RMSNorm(hidden_size, eps=1e-6, dtype=dtype, device=device) self.mlp = FeedForward(hidden_size, mlp_hidden, dtype=dtype, device=device) self.adaLN_modulation = nn.Sequential(nn.Linear(hidden_size, 6 * hidden_size, bias=True, dtype=dtype, device=device))
def forward(self, x, c, mask, keep, transformer_options={}): shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=-1) x = torch.addcmul(x, gate_msa, self.attn(modulate(self.norm1(x), shift_msa, scale_msa), mask, transformer_options=transformer_options)) x = torch.addcmul(x, gate_mlp, self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))) return x * keep
class FinalLayer(nn.Module): def __init__(self, hidden_size, out_channels, dtype=None, device=None): super().__init__() self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device) self.adaLN_modulation = nn.Linear(hidden_size, 2 * hidden_size, bias=True, dtype=dtype, device=device) self.linear = nn.Linear(hidden_size, out_channels, bias=True, dtype=dtype, device=device)
def forward(self, x, c): shift, scale = self.adaLN_modulation(c).chunk(2, dim=-1) return self.linear(adaln(x, scale, shift, self.norm_final.eps))
class TimestepEmbedder(nn.Module): """ Embeds scalar timesteps into vector representations. """
def __init__(self, hidden_size, frequency_embedding_size=256, output_size=None, dtype=None, device=None, max_period=10000): super().__init__() if output_size is None: output_size = hidden_size self.mlp = nn.Sequential( nn.Linear(frequency_embedding_size, hidden_size, bias=True, dtype=dtype, device=device), nn.SiLU(), nn.Linear(hidden_size, output_size, bias=True, dtype=dtype, device=device), ) self.frequency_embedding_size = frequency_embedding_size self.max_period = max_period
def forward(self, t, dtype, **kwargs): t_freq = self.timestep_embedding(t).to(dtype) t_emb = self.mlp(t_freq) return t_emb
def timestep_embedding(self, timesteps, repeat_only=False): """ Create sinusoidal timestep embeddings. :param timesteps: a 1-D Tensor of N indices, one per batch element. These may be fractional. :return: an [N x dim] Tensor of positional embeddings. """ dim = self.frequency_embedding_size if not repeat_only: half = dim // 2 freqs = torch.exp( -math.log(self.max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=timesteps.device) / half ) args = timesteps[:, None].float() * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2: embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) else: # embedding = repeat(timesteps, 'b -> b d', d=dim) embedding = timesteps[:, None].expand(-1, dim) return embedding
class Transformer2DModel(nn.Module): def __init__(self, in_channels=64, hidden_size=1536, num_heads=16, num_blocks=18, num_text_blocks=2, mlp_hidden=4096, dtype=None, device=None): super().__init__() self.dtype = dtype self.in_channels = in_channels self.num_heads = num_heads self.head_dim = hidden_size // num_heads self.s_embedder = Embed(in_channels, hidden_size, dtype=dtype, device=device) self.t_embedder = TimestepEmbedder(hidden_size, dtype=dtype, device=device) self.y_embedder = Embed(TEXT_EMBED_DIM, hidden_size, norm=True, dtype=dtype, device=device) self.shared_encoder_adaLN = nn.Sequential(nn.Linear(hidden_size, 6 * hidden_size, bias=True, dtype=dtype, device=device)) self.encoder_adaLN_offsets = nn.ParameterList([nn.Parameter(torch.empty(6 * hidden_size, dtype=dtype, device=device)) for _ in range(num_blocks)]) self.y_pool_proj = nn.Linear(hidden_size, hidden_size, bias=False, dtype=dtype, device=device) self.sprint_out_proj = nn.Linear(hidden_size, hidden_size, bias=False, dtype=dtype, device=device) self.blocks = nn.ModuleList([DiTBlock(hidden_size, num_heads, mlp_hidden, i % 2 == 0, dtype=dtype, device=device) for i in range(num_blocks)]) self.text_refine_blocks = nn.ModuleList([TextRefineBlock(hidden_size, num_heads, mlp_hidden, dtype=dtype, device=device) for _ in range(num_text_blocks)]) self.final_layer = FinalLayer(hidden_size, in_channels, dtype=dtype, device=device)
def run_block(self, i, x, txt, pe, mod, txt_bias, transformer_options): offset = self.encoder_adaLN_offsets[i].to(dtype=mod.dtype) return self.blocks[i](x, txt, pe, mod + offset, txt_bias, transformer_options=transformer_options)
def sparse_path(self, x, txt, pe, mod, txt_bias, transformer_options): g = x for i in range(SPRINT_NUM_F, len(self.blocks) - SPRINT_NUM_H): g = self.run_block(i, g, txt, pe, mod, txt_bias, transformer_options) return x + self.sprint_out_proj(g - x)
@torch.no_grad() def forward(self, x, timestep, context, token_weights, sparse_skip=None, transformer_options={}, **kwargs): """sparse_skip: optional per-row flags; flagged rows skip the sparse middle blocks.""" b, _, h, w = x.shape keep = token_weights > 0 txt_bias = torch.log(token_weights.clamp(min=1e-4)).masked_fill(~keep, float("-inf")) # Refine attention is a hard mask; a row with no text key keeps its first one and is zeroed after. refine_keep = keep.clone() refine_keep[:, 0] |= ~keep.any(dim=1) refine_mask = torch.zeros_like(txt_bias).masked_fill(~refine_keep, float("-inf"))[:, None, None, :] keep = keep.unsqueeze(-1).to(x.dtype)
t = self.t_embedder(timestep * 1000.0, x.dtype).unsqueeze(1) txt = self.y_embedder(context) time_condition = F.silu(t) for block in self.text_refine_blocks: txt = block(txt, time_condition, refine_mask, keep, transformer_options=transformer_options)
weights = token_weights.unsqueeze(-1) pooled = (txt * weights).sum(dim=1) / weights.sum(dim=1).clamp(min=1.0) condition = F.silu(t + self.y_pool_proj(pooled).unsqueeze(1)) mod = self.shared_encoder_adaLN(condition)
pe = rope_2d(self.head_dim, h, w, x.device) s = self.s_embedder(x.flatten(2).transpose(1, 2)) for i in range(SPRINT_NUM_F): s = self.run_block(i, s, txt, pe, mod, txt_bias, transformer_options)
if sparse_skip is None or not any(sparse_skip): s = self.sparse_path(s, txt, pe, mod, txt_bias, transformer_options) elif not all(sparse_skip): rows = [i for i, skip in enumerate(sparse_skip) if not skip] s[rows] = self.sparse_path(s[rows], txt[rows], pe, mod[rows], txt_bias[rows], transformer_options)
for i in range(len(self.blocks) - SPRINT_NUM_H, len(self.blocks)): s = self.run_block(i, s, txt, pe, mod, txt_bias, transformer_options)
x0 = self.final_layer(s, condition).transpose(1, 2).reshape(b, self.in_channels, h, w) return (x - x0) / timestep.view(-1, 1, 1, 1)
@staticmethod def from_safetensors(path, device=None): model = Transformer2DModel() load_model(model, path)
return model.to(device)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234from .model import Transformer2DModelfrom .vae import VAEfrom PIL import Imageimport torchfrom transformers import AutoTokenizer, Gemma3ForCausalLM
NUM_STEPS = 50CFG_SCALE = 4.0SHIFT = 3.0
HEIGHT = 1024WIDTH = 1024
class Pipeline: def __init__( self, transformer: str, text_encoder: str, vae: str, device=None ): self.transformer = Transformer2DModel.from_safetensors(transformer) self.transformer.eval() self.tokenizer = AutoTokenizer.from_pretrained(text_encoder) self.text_encoder = Gemma3ForCausalLM.from_pretrained(text_encoder) self.text_encoder.eval() self.vae = VAE.from_safetensors(vae) self.vae.eval() self.transformer.to(device) self.text_encoder.to(device) self.vae.to(device)
@staticmethod def get_timestep_schedule( num_steps: int, shift: float = 3.0, device: str = "cuda", ): """ Creates a timestep schedule from 1 -> 0.
The common flow-matching shift is:
t_shifted = s*t / (1 + (s - 1)*t)
where s is the shift value. """ t = torch.linspace( 1.0, 0.0, num_steps + 1, device=device, dtype=torch.float32, )
if shift != 1.0: t = shift * t / (1.0 + (shift - 1.0) * t)
return t
def encode_text( self, text: str, device: str, dtype: torch.dtype ): tokens = self.tokenizer( text, return_tensors="pt", padding=False, truncation=True, )
input_ids = tokens.input_ids.to(device) attention_mask = tokens.attention_mask.to(device)
with torch.inference_mode(): outputs = self.text_encoder( input_ids=input_ids, attention_mask=attention_mask, output_hidden_states=True, return_dict=True, )
# Gemma hidden_states[-1] is the output of the final layer. # Use the penultimate layer with final normalization. hidden = outputs.hidden_states[-2]
# Depending on the exact Gemma implementation, the final norm may # be exposed as model.norm or model.language_model.norm. if hasattr(self.text_encoder, "model") and hasattr(self.text_encoder.model, "norm"): hidden = self.text_encoder.model.norm(hidden) elif hasattr(self.text_encoder, "language_model") and hasattr( self.text_encoder.language_model, "norm" ): hidden = self.text_encoder.language_model.norm(hidden)
hidden = hidden.to(device=device, dtype=dtype) token_weights = attention_mask.to(device=device, dtype=dtype)
return hidden, token_weights
def predict_velocity( model, latents: torch.Tensor, timestep: torch.Tensor, cond_context: torch.Tensor, cond_weights: torch.Tensor, uncond_context: torch.Tensor, uncond_weights: torch.Tensor, cfg_scale: float, ): """ Performs classifier-free guidance.
The unconditioned pass uses sparse_skip=True, matching the path-drop behavior used during training. """ batch_size = latents.shape[0] t = timestep.expand(batch_size)
with torch.autocast(device_type="cuda", dtype=latents.dtype): velocity_uncond = model( latents, t, uncond_context, token_weights=uncond_weights, sparse_skip=[True] * batch_size, )
velocity_cond = model( latents, t, cond_context, token_weights=cond_weights, sparse_skip=[False] * batch_size, )
# CFG interpolation. velocity = velocity_uncond + cfg_scale * ( velocity_cond - velocity_uncond )
return velocity.float()
@torch.inference_mode() def generate( self, positive: str, negative: str = '', height: int = 256, width: int = 256, num_steps: int = 50, cfg_scale: float = 4.0, shift: float = 3.0, seed: int = 0, ): torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed)
device = next(self.transformer.parameters()).device dtype = next(self.transformer.parameters()).dtype
# Encode conditional and unconditional prompts. cond_context, cond_weights = self.encode_text( positive, device, dtype, )
uncond_context, uncond_weights = self.encode_text( negative, device, dtype, )
latent_channels = 64 latent_height = height // 8 latent_width = width // 8
latents = torch.randn( 1, latent_channels, latent_height, latent_width, device=device, dtype=dtype, )
timesteps = Pipeline.get_timestep_schedule( num_steps=num_steps, shift=shift, device=device, )
for step in range(num_steps): t_cur = timesteps[step] t_next = timesteps[step + 1]
dt = t_next - t_cur
timestep = t_cur.reshape(1)
velocity = Pipeline.predict_velocity( model=self.transformer, latents=latents, timestep=timestep, cond_context=cond_context, cond_weights=cond_weights, uncond_context=uncond_context, uncond_weights=uncond_weights, cfg_scale=cfg_scale, )
# Euler integration from t=1 toward t=0. latents = latents.float() + dt * velocity latents = latents.to(dtype)
# Decode the final x prediction. # # Adjust this call if your VAE uses decode(latents) with a different # latent scaling convention. image = self.vae.decode(latents.float())
# Convert from BCHW float [0, 1] to a PIL image. if isinstance(image, (tuple, list)): image = image[0]
image = image.float().clamp(0.0, 1.0) image = image[0].permute(1, 2, 0) image = (image * 255.0).round().to(torch.uint8).cpu().numpy()
return Image.fromarray(image)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380import mathimport numpy as npfrom safetensors.torch import load_fileimport timmimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom transformers import Dinov2Modelfrom typing import Optional, Tuplefrom timm.models.vision_transformer import VisionTransformer
DINO_MODEL_NAME = "vit_base_patch14_dinov2.lvd142m"
DINO_MEAN = (0.485, 0.456, 0.406)DINO_STD = (0.229, 0.224, 0.225)
DINO_PATCH_SIZE = 14DINO_GRID = 37LATENT_DOWNSAMPLE_FACTOR = 16ENCODER_LAYERS = 6
class ResnetBlock(nn.Module): def __init__(self, in_ch: int, out_ch: int) -> None: super().__init__() self.norm1 = nn.GroupNorm(32, in_ch, eps=1e-6, affine=True) self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1) self.norm2 = nn.GroupNorm(32, out_ch, eps=1e-6, affine=True) self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1) self.nin_shortcut = ( nn.Conv2d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity() )
def forward(self, x: torch.Tensor) -> torch.Tensor: h = self.conv1(F.silu(self.norm1(x))) h = self.conv2(F.silu(self.norm2(h))) return self.nin_shortcut(x) + h
class AttnBlock(nn.Module): def __init__(self, channels: int) -> None: super().__init__() self.norm = nn.GroupNorm(32, channels, eps=1e-6, affine=True) self.q = nn.Conv2d(channels, channels, kernel_size=1) self.k = nn.Conv2d(channels, channels, kernel_size=1) self.v = nn.Conv2d(channels, channels, kernel_size=1) self.proj_out = nn.Conv2d(channels, channels, 1)
def forward(self, x: torch.Tensor) -> torch.Tensor: batch, channels, height, width = x.shape normalized = self.norm(x) # (B, C, H, W) -> (B, H*W, C) q = self.q(normalized).flatten(2).transpose(1, 2) k = self.k(normalized).flatten(2).transpose(1, 2) v = self.v(normalized).flatten(2).transpose(1, 2) h = F.scaled_dot_product_attention(q, k, v) h = h.transpose(1, 2).reshape(batch, channels, height, width) return x + self.proj_out(h)
class Upsample(nn.Module): def __init__(self, channels: int, scale_factor: float) -> None: super().__init__() self.conv = nn.Conv2d(channels, channels, 3, padding=1) self.scale_factor = scale_factor
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.conv(F.interpolate(x, scale_factor=self.scale_factor, mode="nearest"))
class Decoder(nn.Module): # ldm/modules/diffusionmodules/model.py def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks, attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels, resolution, z_channels, tanh_out=False, use_linear_attn=False, attn_op=AttnBlock, conv3d=False, time_compress=None, **ignorekwargs): super().__init__() self.ch = ch self.temb_ch = 0 self.num_resolutions = len(ch_mult) self.num_res_blocks = num_res_blocks self.resolution = resolution self.in_channels = in_channels self.tanh_out = tanh_out self.carried = False
# compute block_in and curr_res at lowest res block_in = ch*ch_mult[self.num_resolutions-1] curr_res = resolution // 2**(self.num_resolutions-1) self.z_shape = (1,z_channels,curr_res,curr_res)
# z to block_in self.conv_in = nn.Conv2d( z_channels, block_in, kernel_size=3, stride=1, padding=1)
# middle self.mid = MidBlock(block_in)
# upsampling self.up = nn.ModuleList() for i_level in reversed(range(self.num_resolutions)): block = nn.ModuleList() attn = nn.ModuleList() block_out = ch*ch_mult[i_level] for i_block in range(self.num_res_blocks+1): block.append(ResnetBlock(block_in, block_out)) block_in = block_out if curr_res in attn_resolutions: attn.append(AttnBlock(block_in)) up = nn.Module() up.block = block up.attn = attn if i_level != 0: scale_factor = 2.0 if time_compress is not None: if i_level > math.log2(time_compress): scale_factor = (1.0, 2.0, 2.0)
up.upsample = Upsample(block_in, scale_factor=scale_factor) curr_res = curr_res * 2 self.up.insert(0, up) # prepend to get consistent order
self.norm_out = nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True) self.conv_out = nn.Conv2d( block_in, out_ch, kernel_size=3, stride=1, padding=1)
def forward(self, z, **kwargs) -> list[torch.Tensor]: # timestep embedding temb = None h = self.conv_in(z) h = self.mid(h)
if self.carried: h = torch.split(h, 2, dim=2) else: h = [ h ] out = [] conv_carry_in = None for i, h1 in enumerate(h): conv_carry_out = [] if i == len(h) - 1: conv_carry_out = None for i_level in reversed(range(self.num_resolutions)): for i_block in range(self.num_res_blocks+1): h1 = self.up[i_level].block[i_block](h1) if len(self.up[i_level].attn) > 0: assert i == 0 #carried should not happen if attn exists h1 = self.up[i_level].attn[i_block](h1) if i_level != 0: h1 = self.up[i_level].upsample(h1)
h1 = self.norm_out(h1) h1 = F.silu(h1) h1 = self.conv_out(h1) if self.tanh_out: h1 = torch.tanh(h1) out.append(h1) conv_carry_in = conv_carry_out
return out
class MidBlock(nn.Module): def __init__(self, block_in): super().__init__() self.block_1 = ResnetBlock(block_in, block_in) self.attn_1 = AttnBlock(block_in) self.block_2 = ResnetBlock(block_in, block_in)
def forward(self, x): x = self.block_1(x) x = self.attn_1(x) x = self.block_2(x)
return x
class VAE(nn.Module): def __init__(self): super().__init__() self.latent_channels = 64 self._dino = [timm.create_model( DINO_MODEL_NAME, pretrained=True, num_classes=0, dynamic_img_size=True, dynamic_img_pad=True )] # The call_dino() works without changing the output_fmt. # self.dino.patch_embed.output_fmt = 'NCHW' self.dino.eval() # self._dino[0].patch_embed.strict_img_size = False self.embed_dim = self.dino.embed_dim
# The original model uses the final six DINO transformer blocks. self.feature_norms = nn.ModuleList([ nn.LayerNorm(self.embed_dim, eps=1e-6) for _ in range(ENCODER_LAYERS) ]) self.encoder_projection = nn.Conv2d( self.embed_dim * ENCODER_LAYERS, self.latent_channels // 2, kernel_size=1, ) self.semantic_projection = nn.Conv2d( self.embed_dim, self.latent_channels // 2, kernel_size=1, ) self.semantic_patch_embeddings = Dinov2PatchEmbeddings(self.embed_dim)
# Replace this with a PyTorch implementation. self.decoder = Decoder( ch=128, in_channels=3, out_ch=3, ch_mult=(1, 1, 2, 2, 4), num_res_blocks=2, attn_resolutions=(16,), resolution=256, z_channels=self.latent_channels, tanh_out=True, ) self.register_buffer( "latent_mean", torch.empty(1, self.latent_channels, 1, 1), ) self.register_buffer( "latent_std", torch.empty(1, self.latent_channels, 1, 1), ) self.register_buffer( "dino_mean", torch.tensor(DINO_MEAN).view(1, 3, 1, 1), persistent=False ) self.register_buffer( "dino_std", torch.tensor(DINO_STD).view(1, 3, 1, 1), persistent=False )
@property def dino(self) -> VisionTransformer: return self._dino[0]
def call_dino(self, pixel_values, patch_embeddings=None): # This was probably from Dinov2Embeddings.interpolate_pos_encoding() function. if patch_embeddings is None: x = self.dino.patch_embed(pixel_values) else: x = patch_embeddings(pixel_values) if x.shape[-1] == self.dino.embed_dim: x = x.flatten(1, 2) else: x = x.flatten(2).transpose(1, 2) # NCHW -> NLC pos = self.dino.pos_embed.to(x.dtype) patch_pos = pos[:, 1:].reshape(1, DINO_GRID, DINO_GRID, -1).permute(0, 3, 1, 2) grid = (pixel_values.shape[-2] // DINO_PATCH_SIZE, pixel_values.shape[-1] // DINO_PATCH_SIZE) patch_pos = F.interpolate(patch_pos, size=grid, mode="bicubic", antialias=True).flatten(2).transpose(1, 2) pos = torch.cat([pos[:, :1], patch_pos], dim=1).to(x.dtype) B, _, _ = x.shape cls = self.dino.cls_token.expand(B, 1, -1).to(x.dtype) x = torch.cat([cls, x], dim=1) + pos hidden_states = [] for layer in self.dino.blocks: x = layer(x) hidden_states.append(x)
return hidden_states
def encode(self, x: torch.Tensor) -> torch.Tensor: """ Input: x: [-1, 1], shape [B, 3, H, W]
Output: Normalized latent tensor. """ batch_size, _, height, width = x.shape grid_h = max(1, (height + LATENT_DOWNSAMPLE_FACTOR // 2) // LATENT_DOWNSAMPLE_FACTOR) grid_w = max(1, (width + LATENT_DOWNSAMPLE_FACTOR // 2) // LATENT_DOWNSAMPLE_FACTOR) target_height = grid_h * DINO_PATCH_SIZE target_width = grid_w * DINO_PATCH_SIZE x = F.interpolate( x, size=(target_height, target_width), mode="bicubic", align_corners=False, antialias=True, )
# Convert [-1, 1] to [0, 1], then apply ImageNet normalization. # x = (x + 1.0) * 0.5 x = (x - self.dino_mean) / self.dino_std
print(self.dino.patch_embed.output_fmt) hidden_states = self.call_dino(x)
# Match: # dino_hidden_states(...)[-ENCODER_LAYERS:] features = hidden_states[-ENCODER_LAYERS:] normalized_features = [] for feature, norm in zip(features, self.feature_norms): # Remove CLS token. feature = feature[:, 1:] feature = norm(feature) normalized_features.append(feature) features = torch.cat(normalized_features, dim=-1) # (B, patches, C * ENCODER_LAYERS) features = ( features.transpose(1, 2) .reshape(batch_size, -1, grid_h, grid_w) ) # (B, C * ENCODER_LAYERS, grid_h, grid_w)
# Semantic branch uses the final transformer block followed by # the model's final LayerNorm. assert not torch.equal(self.dino.patch_embed.proj.weight, self.semantic_patch_embeddings.projection.weight) semantic = self.call_dino(x, self.semantic_patch_embeddings)[-1][:, 1:] semantic = self.dino.norm(semantic) semantic = ( semantic.transpose(1, 2) .reshape(batch_size, -1, grid_h, grid_w,) )
z = torch.cat([self.encoder_projection(features), self.semantic_projection(semantic)], dim=1)
return (z - self.latent_mean) / self.latent_std
def decode(self, z: torch.Tensor) -> torch.Tensor: z = z * self.latent_std + self.latent_mean
return self.decoder(z)
@torch.no_grad() def forward(self, x: torch.Tensor) -> torch.Tensor: return self.decode(self.encode(x))
@staticmethod def from_safetensors(path, device=None): model = VAE() sd = load_file(path) for key in list(sd.keys()): if key.startswith('encoder.'): del sd[key] model.load_state_dict(sd) del sd
return model.to(device)
def to_numpy_array(self, x: torch.Tensor): # Clip the tanh output. x = (x.detach().clamp(-1, 1) + 1) / 2 * 255.0 if len(x.shape) == 4: x = x.squeeze(0) x = x.cpu().movedim(0, 2) # (CHW) -> (HWC)
return x.numpy().astype(np.uint8)
def to_tensor(self, image): pixels = torch.from_numpy(np.array(image)).float() pixels = pixels.permute(2, 0, 1) # Dino requires [0, 1] values. pixels = (pixels / 255.0) # * 2.0 - 1.0
return pixels.unsqueeze(0)
class Dinov2PatchEmbeddings(nn.Module): def __init__(self, hidden_dim: int): super().__init__() self.projection = nn.Conv2d(3, hidden_dim, kernel_size=14, stride=14)
def forward(self, x): # See transformers.models.dinov2.modeling_dinov2 for implementation. return self.projection(x)__init__.pyAdded
model.pyAdded+290
pipeline.pyAdded+234
vae.pyAdded+380