diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..f9044aaf1f69a8fb64692a500219cfba03452099 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +pae-dinov2-large-d32/demo.png filter=lfs diff=lfs merge=lfs -text +pae-mae-large-d32/demo.png filter=lfs diff=lfs merge=lfs -text +pae-siglip2-so400m-d32/demo.png filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2d763a8f4c7228fe92c67af5788236bcf2b22789 --- /dev/null +++ b/README.md @@ -0,0 +1,60 @@ +--- +license: mit +language: +- en +tags: +- diffusers +- autoencoder +- vision-foundation-model +- dinov2 +- dinov3 +- mae +- siglip2 +- feature-extraction +- pae +library_name: diffusers +pipeline_tag: feature-extraction +--- + +# PAE Diffusers Checkpoints + +Converted PAE (Prior-Aligned Autoencoder) tokenizer checkpoints in standard Hub custom-pipeline layout. + +PAE is a **VAE-free** latent framework. Each variant splits into dedicated components: + +| Variant | VFM backbone (decoder config) | Latent dim | Input size | +|---------|------------------|------------|------------| +| `pae-dinov2-large-d32` | DINOv2-L (with registers) | 32 | 224 | +| `pae-dinov3-large-d32` | DINOv3-ViT-L/16 | 32 | 256 | +| `pae-mae-large-d32` | MAE-L | 32 | 256 | +| `pae-siglip2-so400m-d32` | SigLIP2-SO400M | 32 | 256 | + +Each variant directory is a self-contained Diffusers repo. Each component subfolder ships **one Python file**: + +```text +model_index.json +pipeline.py +scheduler/scheduling_flow_match_pae.py +transformers/transformer_lightning_dit.py +decoder/decoder_pae.py +decoder/diffusion_pytorch_model.safetensors +``` + +## Usage + +```python +from pathlib import Path +import torch +from diffusers import DiffusionPipeline + +model_dir = Path("/home/czy/local/models/BiliSakura/PAE-diffusers/pae-dinov2-large-d32").resolve() +pipe = DiffusionPipeline.from_pretrained( + str(model_dir), + local_files_only=True, + custom_pipeline=str(model_dir / "pipeline.py"), + trust_remote_code=True, + torch_dtype=torch.bfloat16, +).to("cuda") + +print(pipe.get_label_ids("golden retriever")) +``` diff --git a/pae-dinov2-large-d32/__pycache__/pipeline.cpython-311.pyc b/pae-dinov2-large-d32/__pycache__/pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0b172b78fc20a525254d77c9cb61e77fbc69908 Binary files /dev/null and b/pae-dinov2-large-d32/__pycache__/pipeline.cpython-311.pyc differ diff --git a/pae-dinov2-large-d32/decoder/__pycache__/decoder_pae.cpython-311.pyc b/pae-dinov2-large-d32/decoder/__pycache__/decoder_pae.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..843244441855ace73aa7ec93b558cf31f3507b43 Binary files /dev/null and b/pae-dinov2-large-d32/decoder/__pycache__/decoder_pae.cpython-311.pyc differ diff --git a/pae-dinov2-large-d32/decoder/config.json b/pae-dinov2-large-d32/decoder/config.json new file mode 100644 index 0000000000000000000000000000000000000000..66ddada8a27f94d2812600660233637f6fbd1f31 --- /dev/null +++ b/pae-dinov2-large-d32/decoder/config.json @@ -0,0 +1,79 @@ +{ + "_class_name": "PAEDecoder", + "decoder_patch_size": 16, + "encoder_config_path": "facebook/dinov2-with-registers-large", + "encoder_hidden_size": 1024, + "encoder_input_size": 224, + "encoder_num_heads": 16, + "encoder_patch_size": 14, + "latent_dim": 32, + "latent_mean": [ + -0.9140625, + 0.3515625, + 3.328125, + 0.006500244140625, + 0.298828125, + -1.3671875, + -0.0537109375, + -0.040771484375, + 1.2109375, + 0.0233154296875, + -0.07275390625, + -0.26953125, + -0.08251953125, + -0.037109375, + -1.078125, + 2.125, + 0.0439453125, + -0.02880859375, + -0.103515625, + 0.1171875, + 0.890625, + -0.52734375, + 0.09521484375, + -0.0206298828125, + -0.10302734375, + 0.51171875, + -0.12109375, + 0.054931640625, + 0.376953125, + 0.0252685546875, + -0.0177001953125, + 2.109375 + ], + "latent_multiplier": 1.0, + "latent_std": [ + 0.412109375, + 0.373046875, + 0.322265625, + 0.359375, + 0.462890625, + 0.390625, + 0.365234375, + 0.40625, + 0.40625, + 0.4140625, + 0.36328125, + 0.375, + 0.458984375, + 0.36328125, + 0.373046875, + 0.40234375, + 0.361328125, + 0.34375, + 0.421875, + 0.35546875, + 0.357421875, + 0.40234375, + 0.38671875, + 0.365234375, + 0.419921875, + 0.3828125, + 0.373046875, + 0.373046875, + 0.416015625, + 0.349609375, + 0.37890625, + 0.3515625 + ] +} diff --git a/pae-dinov2-large-d32/decoder/decoder_pae.py b/pae-dinov2-large-d32/decoder/decoder_pae.py new file mode 100644 index 0000000000000000000000000000000000000000..4592fb0fd62b7324c7d6398d7e50f4229d58a3b3 --- /dev/null +++ b/pae-dinov2-large-d32/decoder/decoder_pae.py @@ -0,0 +1,1105 @@ +from __future__ import annotations + +from transformers.configuration_utils import PretrainedConfig +from transformers.utils import ( + ModelOutput, +) +from transformers.activations import ACT2FN +class ViTMAEConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a [`ViTMAEModel`]. It is used to instantiate an ViT + MAE model according to the specified arguments, defining the model architecture. Instantiating a configuration with + the defaults will yield a similar configuration to that of the ViT + [facebook/vit-mae-base](https://huggingface.co/facebook/vit-mae-base) architecture. + + Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the + documentation from [`PretrainedConfig`] for more information. + + + Args: + hidden_size (`int`, *optional*, defaults to 768): + Dimensionality of the encoder layers and the pooler layer. + num_hidden_layers (`int`, *optional*, defaults to 12): + Number of hidden layers in the Transformer encoder. + num_attention_heads (`int`, *optional*, defaults to 12): + Number of attention heads for each attention layer in the Transformer encoder. + intermediate_size (`int`, *optional*, defaults to 3072): + Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. + hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`): + The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, + `"relu"`, `"selu"` and `"gelu_new"` are supported. + hidden_dropout_prob (`float`, *optional*, defaults to 0.0): + The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler. + attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0): + The dropout ratio for the attention probabilities. + initializer_range (`float`, *optional*, defaults to 0.02): + The standard deviation of the truncated_normal_initializer for initializing all weight matrices. + layer_norm_eps (`float`, *optional*, defaults to 1e-12): + The epsilon used by the layer normalization layers. + image_size (`int`, *optional*, defaults to 224): + The size (resolution) of each image. + patch_size (`int`, *optional*, defaults to 16): + The size (resolution) of each patch. + num_channels (`int`, *optional*, defaults to 3): + The number of input channels. + qkv_bias (`bool`, *optional*, defaults to `True`): + Whether to add a bias to the queries, keys and values. + decoder_num_attention_heads (`int`, *optional*, defaults to 16): + Number of attention heads for each attention layer in the decoder. + decoder_hidden_size (`int`, *optional*, defaults to 512): + Dimensionality of the decoder. + decoder_num_hidden_layers (`int`, *optional*, defaults to 8): + Number of hidden layers in the decoder. + decoder_intermediate_size (`int`, *optional*, defaults to 2048): + Dimensionality of the "intermediate" (i.e., feed-forward) layer in the decoder. + mask_ratio (`float`, *optional*, defaults to 0.75): + The ratio of the number of masked tokens in the input sequence. + norm_pix_loss (`bool`, *optional*, defaults to `False`): + Whether or not to train with normalized pixels (see Table 3 in the paper). Using normalized pixels improved + representation quality in the experiments of the authors. + + Example: + + ```python + >>> from transformers import ViTMAEConfig, ViTMAEModel + + >>> # Initializing a ViT MAE vit-mae-base style configuration + >>> configuration = ViTMAEConfig() + + >>> # Initializing a model (with random weights) from the vit-mae-base style configuration + >>> model = ViTMAEModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "vit_mae" + + def __init__( + self, + hidden_size=768, + num_hidden_layers=12, + num_attention_heads=12, + intermediate_size=3072, + hidden_act="gelu", + hidden_dropout_prob=0.0, + attention_probs_dropout_prob=0.0, + initializer_range=0.02, + layer_norm_eps=1e-12, + image_size=224, + patch_size=16, + num_channels=3, + qkv_bias=True, + decoder_num_attention_heads=16, + decoder_hidden_size=512, + decoder_num_hidden_layers=8, + decoder_intermediate_size=2048, + mask_ratio=0.75, + norm_pix_loss=False, + **kwargs, + ): + super().__init__(**kwargs) + + self.hidden_size = hidden_size + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.intermediate_size = intermediate_size + self.hidden_act = hidden_act + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.initializer_range = initializer_range + self.layer_norm_eps = layer_norm_eps + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.qkv_bias = qkv_bias + self.decoder_num_attention_heads = decoder_num_attention_heads + self.decoder_hidden_size = decoder_hidden_size + self.decoder_num_hidden_layers = decoder_num_hidden_layers + self.decoder_intermediate_size = decoder_intermediate_size + self.mask_ratio = mask_ratio + self.norm_pix_loss = norm_pix_loss + +# coding=utf-8 +# Copyright 2022 Facebook AI and The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""PyTorch ViT MAE (masked autoencoder) model.""" + +import collections.abc +import math +from copy import deepcopy +from dataclasses import dataclass +from typing import Optional, Set, Tuple, Union + +import numpy as np +import torch +from torch import nn +# correct the above import to the following +from transformers.modeling_outputs import BaseModelOutput + +try: + from flash_attn import flash_attn_func + HAS_FLASH_ATTN = True # if set to False, FlashAttention is unavailable +except: + print('FlashAttention is not installed.') + HAS_FLASH_ATTN = False + + +@dataclass +class ViTMAEModelOutput(ModelOutput): + """ + Class for ViTMAEModel's outputs, with potential hidden states and attentions. + + Args: + last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): + Sequence of hidden-states at the output of the last layer of the model. + mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): + Tensor indicating which patches are masked (1) and which are not (0). + ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Tensor containing the original index of the (shuffled) masked patches. + hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): + Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of + shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer + plus the initial embedding outputs. + attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): + Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, + sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in + the self-attention heads. + """ + + last_hidden_state: torch.FloatTensor = None + mask: torch.LongTensor = None + ids_restore: torch.LongTensor = None + hidden_states: Optional[Tuple[torch.FloatTensor]] = None + attentions: Optional[Tuple[torch.FloatTensor]] = None + + +@dataclass +class ViTMAEDecoderOutput(ModelOutput): + """ + Class for ViTMAEDecoder's outputs, with potential hidden states and attentions. + + Args: + logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`): + Pixel reconstruction logits. + hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): + Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of + shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer + plus the initial embedding outputs. + attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): + Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, + sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in + the self-attention heads. + """ + + logits: torch.FloatTensor = None + hidden_states: Optional[Tuple[torch.FloatTensor]] = None + attentions: Optional[Tuple[torch.FloatTensor]] = None + + +@dataclass +class ViTMAEForPreTrainingOutput(ModelOutput): + """ + Class for ViTMAEForPreTraining's outputs, with potential hidden states and attentions. + + Args: + loss (`torch.FloatTensor` of shape `(1,)`): + Pixel reconstruction loss. + logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`): + Pixel reconstruction logits. + mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): + Tensor indicating which patches are masked (1) and which are not (0). + ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Tensor containing the original index of the (shuffled) masked patches. + hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): + Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of + shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer + plus the initial embedding outputs. + attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): + Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, + sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in + the self-attention heads. + """ + + loss: Optional[torch.FloatTensor] = None + logits: torch.FloatTensor = None + mask: torch.LongTensor = None + ids_restore: torch.LongTensor = None + hidden_states: Optional[Tuple[torch.FloatTensor]] = None + attentions: Optional[Tuple[torch.FloatTensor]] = None + + +def get_2d_sincos_pos_embed(embed_dim, grid_size, add_cls_token=False): + """ + Create 2D sin/cos positional embeddings. + + Args: + embed_dim (`int`): + Embedding dimension. + grid_size (`int`): + The grid height and width. + add_cls_token (`bool`, *optional*, defaults to `False`): + Whether or not to add a classification (CLS) token. + + Returns: + (`torch.FloatTensor` of shape (grid_size*grid_size, embed_dim) or (1+grid_size*grid_size, embed_dim): the + position embeddings (with or without classification token) + """ + grid_h = np.arange(grid_size, dtype=np.float32) + grid_w = np.arange(grid_size, dtype=np.float32) + grid = np.meshgrid(grid_w, grid_h) # here w goes first + grid = np.stack(grid, axis=0) + + grid = grid.reshape([2, 1, grid_size, grid_size]) + pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) + if add_cls_token: + pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0) + return pos_embed + + +def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): + if embed_dim % 2 != 0: + raise ValueError("embed_dim must be even") + + # use half of dimensions to encode grid_h + emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) + emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2) + + emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D) + return emb + + +def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): + """ + embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D) + """ + if embed_dim % 2 != 0: + raise ValueError("embed_dim must be even") + + omega = np.arange(embed_dim // 2, dtype=float) + omega /= embed_dim / 2.0 + omega = 1.0 / 10000**omega # (D/2,) + + pos = pos.reshape(-1) # (M,) + out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product + + emb_sin = np.sin(out) # (M, D/2) + emb_cos = np.cos(out) # (M, D/2) + + emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) + return emb + + +class ViTMAEEmbeddings(nn.Module): + """ + Construct the CLS token, position and patch embeddings. + + """ + + def __init__(self, config): + super().__init__() + + self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) + self.patch_embeddings = ViTMAEPatchEmbeddings(config) + self.num_patches = self.patch_embeddings.num_patches + # fixed sin-cos embedding + self.position_embeddings = nn.Parameter( + torch.zeros(1, self.num_patches + 1, config.hidden_size), requires_grad=False + ) + self.config = config + self.initialize_weights() + + def initialize_weights(self): + # initialize (and freeze) position embeddings by sin-cos embedding + pos_embed = get_2d_sincos_pos_embed( + self.position_embeddings.shape[-1], int(self.patch_embeddings.num_patches**0.5), add_cls_token=True + ) + self.position_embeddings.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0)) + + # initialize patch_embeddings like nn.Linear (instead of nn.Conv2d) + w = self.patch_embeddings.projection.weight.data + torch.nn.init.xavier_uniform_(w.view([w.shape[0], -1])) + + # timm's trunc_normal_(std=.02) is effectively normal_(std=0.02) as cutoff is too big (2.) + torch.nn.init.normal_(self.cls_token, std=self.config.initializer_range) + + def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor: + """ + This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher + resolution images. + + Source: + https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174 + """ + num_patches = embeddings.shape[1] - 1 + num_positions = self.position_embeddings.shape[1] - 1 + + if num_patches == num_positions and height == width: + return self.position_embeddings + + class_pos_embed = self.position_embeddings[:, 0, :] + patch_pos_embed = self.position_embeddings[:, 1:, :] + dim = embeddings.shape[-1] + h0 = height // self.config.patch_size + w0 = width // self.config.patch_size + # we add a small number to avoid floating point error in the interpolation + # see discussion at https://github.com/facebookresearch/dino/issues/8 + h0, w0 = h0 + 0.1, w0 + 0.1 + patch_pos_embed = patch_pos_embed.reshape(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim) + patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2) + patch_pos_embed = nn.functional.interpolate( + patch_pos_embed, + scale_factor=(h0 / math.sqrt(num_positions), w0 / math.sqrt(num_positions)), + mode="bicubic", + align_corners=False, + ) + if int(h0) != patch_pos_embed.shape[-2] or int(w0) != patch_pos_embed.shape[-1]: + raise ValueError("Width or height does not match with the interpolated position embeddings") + patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) + return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1) + + def random_masking(self, sequence, noise=None): + """ + Perform per-sample random masking by per-sample shuffling. Per-sample shuffling is done by argsort random + noise. + + Args: + sequence (`torch.LongTensor` of shape `(batch_size, sequence_length, dim)`) + noise (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*) which is + mainly used for testing purposes to control randomness and maintain the reproducibility + """ + batch_size, seq_length, dim = sequence.shape + len_keep = int(seq_length * (1 - self.config.mask_ratio)) + + if noise is None: + noise = torch.rand(batch_size, seq_length, device=sequence.device) # noise in [0, 1] + + # sort noise for each sample + ids_shuffle = torch.argsort(noise, dim=1).to(sequence.device) # ascend: small is keep, large is remove + ids_restore = torch.argsort(ids_shuffle, dim=1).to(sequence.device) + + # keep the first subset + ids_keep = ids_shuffle[:, :len_keep] + sequence_unmasked = torch.gather(sequence, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, dim)) + + # generate the binary mask: 0 is keep, 1 is remove + mask = torch.ones([batch_size, seq_length], device=sequence.device) + mask[:, :len_keep] = 0 + # unshuffle to get the binary mask + mask = torch.gather(mask, dim=1, index=ids_restore) + + return sequence_unmasked, mask, ids_restore + + def forward(self, pixel_values, noise=None, interpolate_pos_encoding: bool = False): + batch_size, num_channels, height, width = pixel_values.shape + embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding) + if interpolate_pos_encoding: + position_embeddings = self.interpolate_pos_encoding(embeddings, height, width) + else: + position_embeddings = self.position_embeddings + + # add position embeddings w/o cls token + embeddings = embeddings + position_embeddings[:, 1:, :] + + # masking: length -> length * config.mask_ratio + embeddings, mask, ids_restore = self.random_masking(embeddings, noise) + + # append cls token + cls_token = self.cls_token + position_embeddings[:, :1, :] + cls_tokens = cls_token.expand(embeddings.shape[0], -1, -1) + embeddings = torch.cat((cls_tokens, embeddings), dim=1) + + return embeddings, mask, ids_restore + + +class ViTMAEPatchEmbeddings(nn.Module): + """ + This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial + `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a + Transformer. + """ + + def __init__(self, config): + super().__init__() + image_size, patch_size = config.image_size, config.patch_size + num_channels, hidden_size = config.num_channels, config.hidden_size + image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size) + patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size) + num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.num_patches = num_patches + + self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size) + + def forward(self, pixel_values, interpolate_pos_encoding: bool = False): + batch_size, num_channels, height, width = pixel_values.shape + if num_channels != self.num_channels: + raise ValueError( + "Make sure that the channel dimension of the pixel values match with the one set in the configuration." + ) + + if not interpolate_pos_encoding and (height != self.image_size[0] or width != self.image_size[1]): + raise ValueError( + f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})." + ) + x = self.projection(pixel_values).flatten(2).transpose(1, 2) + return x + + +# Copied from transformers.models.vit.modeling_vit.ViTSelfAttention ViT->ViTMAE +class ViTMAESelfAttention(nn.Module): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): + raise ValueError( + f"The hidden size {config.hidden_size,} is not a multiple of the number of attention " + f"heads {config.num_attention_heads}." + ) + + self.has_flash_attn = HAS_FLASH_ATTN + self.num_attention_heads = config.num_attention_heads + self.attention_head_size = int(config.hidden_size / config.num_attention_heads) + self.all_head_size = self.num_attention_heads * self.attention_head_size + + self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) + self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) + self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) + + self.dropout = nn.Dropout(config.attention_probs_dropout_prob) + self.attention_probs_dropout_prob = config.attention_probs_dropout_prob + + def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor: + new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) + x = x.view(new_x_shape) + return x.permute(0, 2, 1, 3) + + def reshape_for_flash(self, x: torch.Tensor) -> torch.Tensor: + """Reshape to (B, N, num_heads, head_dim) for flash_attn_func.""" + new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) + return x.view(new_x_shape) + + def forward( + self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False + ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]: + # Use FlashAttention when available and no special outputs are needed + if self.has_flash_attn and not output_attentions and head_mask is None: + query_layer = self.reshape_for_flash(self.query(hidden_states)) + key_layer = self.reshape_for_flash(self.key(hidden_states)) + value_layer = self.reshape_for_flash(self.value(hidden_states)) + + context_layer = flash_attn_func( + query_layer, key_layer, value_layer, + dropout_p=self.attention_probs_dropout_prob if self.training else 0.0, + causal=False, deterministic=True + ) + + context_layer = context_layer.reshape(hidden_states.size(0), -1, self.all_head_size) + return (context_layer,) + + # Fallback: manual attention computation + mixed_query_layer = self.query(hidden_states) + + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + query_layer = self.transpose_for_scores(mixed_query_layer) + + attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) + attention_scores = attention_scores / math.sqrt(self.attention_head_size) + + attention_probs = nn.functional.softmax(attention_scores, dim=-1) + attention_probs = self.dropout(attention_probs) + + if head_mask is not None: + attention_probs = attention_probs * head_mask + + context_layer = torch.matmul(attention_probs, value_layer) + + context_layer = context_layer.permute(0, 2, 1, 3).contiguous() + new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) + context_layer = context_layer.view(new_context_layer_shape) + + outputs = (context_layer, attention_probs) if output_attentions else (context_layer,) + + return outputs + + +# Copied from transformers.models.vit.modeling_vit.ViTSdpaSelfAttention ViT->ViTMAE +class ViTMAESdpaSelfAttention(ViTMAESelfAttention): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__(config) + self.attention_probs_dropout_prob = config.attention_probs_dropout_prob + + def forward( + self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False + ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]: + # Use FlashAttention when available and no special outputs are needed + if self.has_flash_attn and not output_attentions and head_mask is None: + query_layer = self.reshape_for_flash(self.query(hidden_states)) + key_layer = self.reshape_for_flash(self.key(hidden_states)) + value_layer = self.reshape_for_flash(self.value(hidden_states)) + + context_layer = flash_attn_func( + query_layer, key_layer, value_layer, + dropout_p=self.attention_probs_dropout_prob if self.training else 0.0, + causal=False, deterministic=True + ) + + context_layer = context_layer.reshape(hidden_states.size(0), -1, self.all_head_size) + return context_layer, None + + # Fallback: PyTorch SDPA + mixed_query_layer = self.query(hidden_states) + + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + query_layer = self.transpose_for_scores(mixed_query_layer) + + context_layer = torch.nn.functional.scaled_dot_product_attention( + query_layer, + key_layer, + value_layer, + head_mask, + self.attention_probs_dropout_prob if self.training else 0.0, + is_causal=False, + scale=None, + ) + + context_layer = context_layer.permute(0, 2, 1, 3).contiguous() + new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) + context_layer = context_layer.view(new_context_layer_shape) + + return context_layer, None + + +# Copied from transformers.models.vit.modeling_vit.ViTSelfOutput with ViT->ViTMAE +class ViTMAESelfOutput(nn.Module): + """ + The residual connection is defined in ViTMAELayer instead of here (as is the case with other models), due to the + layernorm applied before each block. + """ + + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + + return hidden_states + + +# Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->ViTMAE +class ViTMAEAttention(nn.Module): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.attention = ViTMAESelfAttention(config) + self.output = ViTMAESelfOutput(config) + + def forward( + self, + hidden_states: torch.Tensor, + head_mask: Optional[torch.Tensor] = None, + output_attentions: bool = False, + ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]: + self_outputs = self.attention(hidden_states, head_mask, output_attentions) + + attention_output = self.output(self_outputs[0], hidden_states) + + outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them + return outputs + +# Copied from transformers.models.vit.modeling_vit.ViTIntermediate ViT->ViTMAE +class ViTMAEIntermediate(nn.Module): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.intermediate_size) + if isinstance(config.hidden_act, str): + self.intermediate_act_fn = ACT2FN[config.hidden_act] + else: + self.intermediate_act_fn = config.hidden_act + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.intermediate_act_fn(hidden_states) + + return hidden_states + + +# Copied from transformers.models.vit.modeling_vit.ViTOutput ViT->ViTMAE +class ViTMAEOutput(nn.Module): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.dense = nn.Linear(config.intermediate_size, config.hidden_size) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + + hidden_states = hidden_states + input_tensor + + return hidden_states + + + +# Copied from transformers.models.vit.modeling_vit.ViTLayer with ViT->ViTMAE,VIT->VITMAE +class ViTMAELayer(nn.Module): + """This corresponds to the Block class in the timm implementation.""" + + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.chunk_size_feed_forward = config.chunk_size_feed_forward + self.seq_len_dim = 1 + self.attention = ViTMAEAttention(config) # no SPDA by default + self.intermediate = ViTMAEIntermediate(config) + self.output = ViTMAEOutput(config) + self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + + def forward( + self, + hidden_states: torch.Tensor, + head_mask: Optional[torch.Tensor] = None, + output_attentions: bool = False, + ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]: + self_attention_outputs = self.attention( + self.layernorm_before(hidden_states), # in ViTMAE, layernorm is applied before self-attention + head_mask, + output_attentions=output_attentions, + ) + attention_output = self_attention_outputs[0] + outputs = self_attention_outputs[1:] # add self attentions if we output attention weights + + # first residual connection + hidden_states = attention_output + hidden_states + + # in ViTMAE, layernorm is also applied after self-attention + layer_output = self.layernorm_after(hidden_states) + layer_output = self.intermediate(layer_output) + + # second residual connection is done here + layer_output = self.output(layer_output, hidden_states) + + outputs = (layer_output,) + outputs + + return outputs + + +class GeneralDecoder(nn.Module): + def __init__(self, config, num_patches): + super().__init__() + self.decoder_embed = nn.Linear(config.hidden_size, config.decoder_hidden_size, bias=True) + self.decoder_pos_embed = nn.Parameter( + torch.zeros(1, num_patches + 1, config.decoder_hidden_size), requires_grad=False + ) # fixed sin-cos embedding + + decoder_config = deepcopy(config) + decoder_config.hidden_size = config.decoder_hidden_size + decoder_config.num_hidden_layers = config.decoder_num_hidden_layers + decoder_config.num_attention_heads = config.decoder_num_attention_heads + decoder_config.intermediate_size = config.decoder_intermediate_size + self.decoder_layers = nn.ModuleList( + [ViTMAELayer(decoder_config) for _ in range(config.decoder_num_hidden_layers)] + ) + + self.decoder_norm = nn.LayerNorm(config.decoder_hidden_size, eps=config.layer_norm_eps) + self.decoder_pred = nn.Linear( + config.decoder_hidden_size, config.patch_size**2 * config.num_channels, bias=True + ) # encoder to decoder + self.gradient_checkpointing = False + self.config = config + self.num_patches = num_patches + self.initialize_weights(num_patches) + self.decoder_config = decoder_config + self.set_trainable_cls_token() + def set_trainable_cls_token(self, tensor: Optional[torch.Tensor] = None): + # register a trainable CLS token + tensor = torch.zeros(1, 1, self.decoder_config.hidden_size) if tensor is None else tensor + self.trainable_cls_token = nn.Parameter(tensor) + def interpolate_pos_encoding(self, embeddings: torch.Tensor) -> torch.Tensor: + """ + This method is a modified version of the interpolation function for ViT-mae model at the deocder, that + allows to interpolate the pre-trained decoder position encodings, to be able to use the model on higher + resolution images. + + Source: + https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174 + """ + + # -1 removes the class dimension since we later append it without interpolation + embeddings_positions = embeddings.shape[1] - 1 + num_positions = self.decoder_pos_embed.shape[1] - 1 + + # Separation of class token and patch tokens + class_pos_embed = self.decoder_pos_embed[:, 0, :] + patch_pos_embed = self.decoder_pos_embed[:, 1:, :] + + # To retain the final 3d tensor with the required dimensions + dim = self.decoder_pos_embed.shape[-1] + + # Increasing a dimension to enable bicubic interpolation + patch_pos_embed = patch_pos_embed.reshape(1, 1, -1, dim) + + # permute to bring the dimension to be interpolated, to the last + patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2) + + # Interpolating the decoder position embeddings shape wrt embeddings shape i.e (x). + # 1 keeps the other dimension constant + patch_pos_embed = nn.functional.interpolate( + patch_pos_embed, + scale_factor=(1, embeddings_positions / num_positions), + mode="bicubic", + align_corners=False, + ) + + # Converting back to the original shape + patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) + # Adding the class token back + return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1) + def interpolate_latent(self, x: torch.Tensor) -> torch.Tensor: + b, l, c = x.shape + if l == self.num_patches: + return x + # interpolate the latent + #print(f"interpolating latent from {l} to {self.num_patches}, x.shape = {x.shape}") + h, w = int(l**0.5), int(l**0.5) + x = x.reshape(b, h, w, c) + x = x.permute(0, 3, 1, 2) + target_size = (int(self.num_patches**0.5), int(self.num_patches**0.5)) + x = nn.functional.interpolate(x, size=target_size, mode="bilinear", align_corners=False) + x = x.permute(0, 2, 3, 1).contiguous().view(b, self.num_patches, c) + return x + + def initialize_weights(self, num_patches): + # initialize (and freeze) position embeddings by sin-cos embedding + decoder_pos_embed = get_2d_sincos_pos_embed( + self.decoder_pos_embed.shape[-1], int(num_patches**0.5), add_cls_token=True + ) + self.decoder_pos_embed.data.copy_(torch.from_numpy(decoder_pos_embed).float().unsqueeze(0)) + + # timm's trunc_normal_(std=.02) is effectively normal_(std=0.02) as cutoff is too big (2.) + # torch.nn.init.normal_(self.mask_token, std=self.config.initializer_range) + def unpatchify(self, patchified_pixel_values, original_image_size: Optional[Tuple[int, int]] = None): + """ + Args: + patchified_pixel_values (`torch.FloatTensor` of shape `(batch_size, num_patches, patch_size**2 * num_channels)`: + Patchified pixel values. + original_image_size (`Tuple[int, int]`, *optional*): + Original image size. + + Returns: + `torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`: + Pixel values. + """ + patch_size, num_channels = self.config.patch_size, self.config.num_channels + original_image_size = ( + original_image_size + if original_image_size is not None + else (self.config.image_size, self.config.image_size) + ) + original_height, original_width = original_image_size + num_patches_h = original_height // patch_size + num_patches_w = original_width // patch_size + # sanity check + if num_patches_h * num_patches_w != patchified_pixel_values.shape[1]: + raise ValueError( + f"The number of patches in the patchified pixel values {patchified_pixel_values.shape[1]}, does not match the number of patches on original image {num_patches_h}*{num_patches_w}" + ) + + # unpatchify + batch_size = patchified_pixel_values.shape[0] + patchified_pixel_values = patchified_pixel_values.reshape( + batch_size, + num_patches_h, + num_patches_w, + patch_size, + patch_size, + num_channels, + ) + patchified_pixel_values = torch.einsum("nhwpqc->nchpwq", patchified_pixel_values) + pixel_values = patchified_pixel_values.reshape( + batch_size, + num_channels, + num_patches_h * patch_size, + num_patches_w * patch_size, + ) + return pixel_values + + def forward( + self, + hidden_states, + output_attentions=False, + output_hidden_states=False, + return_dict=True, + interpolate_pos_encoding: bool = False, + drop_cls_token: bool = False, + ): + # embed tokens + x = self.decoder_embed(hidden_states) + #print(f"x.shape = {x.shape}") + if drop_cls_token: + x_ = x[:, 1:, :] # no cls token + x_ = self.interpolate_latent(x_) + else: + x_ = self.interpolate_latent(x) # interpolate the whole latent + cls_token = self.trainable_cls_token.expand(x_.shape[0], -1, -1) + x = torch.cat([cls_token, x_], dim=1) + + # add pos embed + if interpolate_pos_encoding: + assert drop_cls_token, "interpolate_pos_encoding only works with drop_cls_token=True" + decoder_pos_embed = self.interpolate_pos_encoding(x) + else: + decoder_pos_embed = self.decoder_pos_embed + hidden_states = x + decoder_pos_embed + #print(f"hidden_states.shape = {hidden_states.shape}") + # apply Transformer layers (blocks) + all_hidden_states = () if output_hidden_states else None + all_self_attentions = () if output_attentions else None + for i, layer_module in enumerate(self.decoder_layers): + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + if self.gradient_checkpointing and self.training: + layer_outputs = self._gradient_checkpointing_func( + layer_module.__call__, + hidden_states, + None, + output_attentions, + ) + else: + layer_outputs = layer_module(hidden_states, head_mask=None, output_attentions=output_attentions) + + hidden_states = layer_outputs[0] + + if output_attentions: + all_self_attentions = all_self_attentions + (layer_outputs[1],) + + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + hidden_states = self.decoder_norm(hidden_states) + + # predictor projection + logits = self.decoder_pred(hidden_states) + + # remove cls token + logits = logits[:, 1:, :] + + if not return_dict: + return tuple(v for v in [logits, all_hidden_states, all_self_attentions] if v is not None) + return ViTMAEDecoderOutput( + logits=logits, + hidden_states=all_hidden_states, + attentions=all_self_attentions, + ) + +import json +from math import sqrt +from pathlib import Path +from typing import Any, Dict, Optional + +import torch +import torch.nn as nn +from timm.models.vision_transformer import Attention +from transformers import AutoConfig, AutoImageProcessor + +try: + from diffusers.configuration_utils import ConfigMixin, register_to_config + from diffusers.models.modeling_utils import ModelMixin +except Exception: # pragma: no cover + class ConfigMixin: + config_name = "config.json" + + class ModelMixin(nn.Module): + pass + + def register_to_config(init): + return init + + +_PIXEL_DECODER_DEFAULTS: Dict[str, Any] = { + "decoder_hidden_size": 1024, + "decoder_intermediate_size": 4096, + "decoder_num_attention_heads": 16, + "decoder_num_hidden_layers": 24, + "layer_norm_eps": 1e-12, + "num_channels": 3, + "hidden_act": "gelu", + "qkv_bias": True, + "hidden_dropout_prob": 0.0, + "attention_probs_dropout_prob": 0.0, + "initializer_range": 0.02, +} + + +def _resolve_local_asset_path(path: str, model_root: Optional[Path] = None) -> str: + candidate = Path(path) + if candidate.is_file(): + return str(candidate) + search_roots = [] + if model_root is not None: + search_roots.extend([model_root, model_root.parent]) + for root in search_roots: + for probe in (root / candidate, root / candidate.name, root / "decoder_config" / "config.json"): + if probe.is_file(): + return str(probe) + return path + + +def _build_pixel_decoder_config( + *, + encoder_hidden_size: int, + decoder_patch_size: int, + base_patches: int, + decoder_config_path: Optional[str] = None, + overrides: Optional[Dict[str, Any]] = None, +) -> ViTMAEConfig: + pixel_decoder = dict(_PIXEL_DECODER_DEFAULTS) + if decoder_config_path is not None: + resolved = _resolve_local_asset_path(decoder_config_path) + if Path(resolved).is_file(): + with open(resolved, encoding="utf-8") as handle: + pixel_decoder.update(json.load(handle)) + if overrides: + pixel_decoder.update({key: value for key, value in overrides.items() if value is not None}) + + return ViTMAEConfig( + hidden_size=encoder_hidden_size, + patch_size=decoder_patch_size, + image_size=int(decoder_patch_size * sqrt(base_patches)), + **pixel_decoder, + ) + + +def _load_image_normalization(encoder_config_path: str) -> tuple[list[float], list[float]]: + try: + proc = AutoImageProcessor.from_pretrained(encoder_config_path, use_fast=True, local_files_only=True) + return proc.image_mean, proc.image_std + except Exception: + pass + try: + proc = AutoImageProcessor.from_pretrained(encoder_config_path, use_fast=True, local_files_only=False) + return proc.image_mean, proc.image_std + except Exception: + if "siglip" in encoder_config_path.lower(): + return [0.5, 0.5, 0.5], [0.5, 0.5, 0.5] + return [0.485, 0.456, 0.406], [0.229, 0.224, 0.225] + + +class PAEDecoder(ModelMixin, ConfigMixin): + """PAE decoder: latent decompressor + ViT-MAE pixel decoder.""" + + @register_to_config + def __init__( + self, + encoder_hidden_size: int = 1024, + encoder_num_heads: int = 16, + encoder_input_size: int = 224, + encoder_patch_size: int = 14, + encoder_config_path: str = "facebook/dinov2-with-registers-large", + latent_dim: int = 32, + decoder_patch_size: int = 16, + decoder_config_path: Optional[str] = None, + decoder_hidden_size: int = 1024, + decoder_intermediate_size: int = 4096, + decoder_num_attention_heads: int = 16, + decoder_num_hidden_layers: int = 24, + layer_norm_eps: float = 1e-12, + num_channels: int = 3, + hidden_act: str = "gelu", + qkv_bias: bool = True, + hidden_dropout_prob: float = 0.0, + attention_probs_dropout_prob: float = 0.0, + initializer_range: float = 0.02, + image_mean: Optional[list[float]] = None, + image_std: Optional[list[float]] = None, + latent_mean: Optional[list[float]] = None, + latent_std: Optional[list[float]] = None, + latent_multiplier: float = 1.0, + **kwargs, + ) -> None: + super().__init__() + if image_mean is not None and image_std is not None: + norm_mean, norm_std = image_mean, image_std + else: + norm_mean, norm_std = _load_image_normalization(encoder_config_path) + self.register_buffer("encoder_mean", torch.tensor(norm_mean).view(1, 3, 1, 1), persistent=True) + self.register_buffer("encoder_std", torch.tensor(norm_std).view(1, 3, 1, 1), persistent=True) + + self.encoder_input_size = encoder_input_size + self.encoder_patch_size = encoder_patch_size + self.base_patches = (self.encoder_input_size // self.encoder_patch_size) ** 2 + self.latent_dim = latent_dim + + self.latent_decompressor = nn.ModuleList( + [ + nn.Conv2d(latent_dim, encoder_hidden_size, kernel_size=3, padding=1), + Attention(dim=encoder_hidden_size, num_heads=encoder_num_heads), + ] + ) + + pixel_decoder_config = _build_pixel_decoder_config( + encoder_hidden_size=encoder_hidden_size, + decoder_patch_size=decoder_patch_size, + base_patches=self.base_patches, + decoder_config_path=decoder_config_path, + overrides={ + "decoder_hidden_size": decoder_hidden_size, + "decoder_intermediate_size": decoder_intermediate_size, + "decoder_num_attention_heads": decoder_num_attention_heads, + "decoder_num_hidden_layers": decoder_num_hidden_layers, + "layer_norm_eps": layer_norm_eps, + "num_channels": num_channels, + "hidden_act": hidden_act, + "qkv_bias": qkv_bias, + "hidden_dropout_prob": hidden_dropout_prob, + "attention_probs_dropout_prob": attention_probs_dropout_prob, + "initializer_range": initializer_range, + }, + ) + self.decoder = GeneralDecoder(pixel_decoder_config, num_patches=self.base_patches) + + @classmethod + def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): + model_root = Path(pretrained_model_name_or_path) + config_file = model_root / cls.config_name + if config_file.is_file(): + with open(config_file, encoding="utf-8") as handle: + config = json.load(handle) + decoder_config_path = config.get("decoder_config_path") + if decoder_config_path is not None: + resolved = _resolve_local_asset_path(decoder_config_path, model_root=model_root) + if resolved != decoder_config_path: + kwargs.setdefault("decoder_config_path", resolved) + return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) + + def decode(self, latents: torch.Tensor) -> torch.Tensor: + hidden_states = self.latent_decompressor[0](latents) + batch_size, channels, height, width = hidden_states.shape + num_tokens = height * width + hidden_states = hidden_states.view(batch_size, channels, num_tokens).transpose(1, 2) + hidden_states = self.latent_decompressor[1](hidden_states) + + output = self.decoder(hidden_states, drop_cls_token=False).logits + x_rec = self.decoder.unpatchify(output) + x_rec = x_rec * self.encoder_std.to(x_rec.device) + self.encoder_mean.to(x_rec.device) + return x_rec + + def forward(self, latents: torch.Tensor) -> torch.Tensor: + return self.decode(latents) diff --git a/pae-dinov2-large-d32/decoder/diffusion_pytorch_model.safetensors b/pae-dinov2-large-d32/decoder/diffusion_pytorch_model.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..510398026623e0b745ae191516d85fc04fab6b7c --- /dev/null +++ b/pae-dinov2-large-d32/decoder/diffusion_pytorch_model.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:313211153c3fbe6ea36c131eb41815c68acf50ab0a638a32ee6fae0a924d3d33 +size 1235663744 diff --git a/pae-dinov2-large-d32/demo.png b/pae-dinov2-large-d32/demo.png new file mode 100644 index 0000000000000000000000000000000000000000..90e4f4c4b1cbfeeb2db549a0ba2f03c676e4489f --- /dev/null +++ b/pae-dinov2-large-d32/demo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65ae67467ea0d054ba69360313edc4d935408cb8b49d5b26d1362343d817b79e +size 126582 diff --git a/pae-dinov2-large-d32/model_index.json b/pae-dinov2-large-d32/model_index.json new file mode 100644 index 0000000000000000000000000000000000000000..c71449e6f44c0678499c73c3696faea852cca1e2 --- /dev/null +++ b/pae-dinov2-large-d32/model_index.json @@ -0,0 +1,1021 @@ +{ + "_class_name": [ + "pipeline", + "PAEPipeline" + ], + "_diffusers_version": "0.31.0", + "decoder": [ + "decoder_pae", + "PAEDecoder" + ], + "id2label": { + "0": "tench, Tinca tinca", + "1": "goldfish, Carassius auratus", + "2": "great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias", + "3": "tiger shark, Galeocerdo cuvieri", + "4": "hammerhead, hammerhead shark", + "5": "electric ray, crampfish, numbfish, torpedo", + "6": "stingray", + "7": "cock", + "8": "hen", + "9": "ostrich, Struthio camelus", + "10": "brambling, Fringilla montifringilla", + "11": "goldfinch, Carduelis carduelis", + "12": "house finch, linnet, Carpodacus mexicanus", + "13": "junco, snowbird", + "14": "indigo bunting, indigo finch, indigo bird, Passerina cyanea", + "15": "robin, American robin, Turdus migratorius", + "16": "bulbul", + "17": "jay", + "18": "magpie", + "19": "chickadee", + "20": "water ouzel, dipper", + "21": "kite", + "22": "bald eagle, American eagle, Haliaeetus leucocephalus", + "23": "vulture", + "24": "great grey owl, great gray owl, Strix nebulosa", + "25": "European fire salamander, Salamandra salamandra", + "26": "common newt, Triturus vulgaris", + "27": "eft", + "28": "spotted salamander, Ambystoma maculatum", + "29": "axolotl, mud puppy, Ambystoma mexicanum", + "30": "bullfrog, Rana catesbeiana", + "31": "tree frog, tree-frog", + "32": "tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui", + "33": "loggerhead, loggerhead turtle, Caretta caretta", + "34": "leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea", + "35": "mud turtle", + "36": "terrapin", + "37": "box turtle, box tortoise", + "38": "banded gecko", + "39": "common iguana, iguana, Iguana iguana", + "40": "American chameleon, anole, Anolis carolinensis", + "41": "whiptail, whiptail lizard", + "42": "agama", + "43": "frilled lizard, Chlamydosaurus kingi", + "44": "alligator lizard", + "45": "Gila monster, Heloderma suspectum", + "46": "green lizard, Lacerta viridis", + "47": "African chameleon, Chamaeleo chamaeleon", + "48": "Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis", + "49": "African crocodile, Nile crocodile, Crocodylus niloticus", + "50": "American alligator, Alligator mississipiensis", + "51": "triceratops", + "52": "thunder snake, worm snake, Carphophis amoenus", + "53": "ringneck snake, ring-necked snake, ring snake", + "54": "hognose snake, puff adder, sand viper", + "55": "green snake, grass snake", + "56": "king snake, kingsnake", + "57": "garter snake, grass snake", + "58": "water snake", + "59": "vine snake", + "60": "night snake, Hypsiglena torquata", + "61": "boa constrictor, Constrictor constrictor", + "62": "rock python, rock snake, Python sebae", + "63": "Indian cobra, Naja naja", + "64": "green mamba", + "65": "sea snake", + "66": "horned viper, cerastes, sand viper, horned asp, Cerastes cornutus", + "67": "diamondback, diamondback rattlesnake, Crotalus adamanteus", + "68": "sidewinder, horned rattlesnake, Crotalus cerastes", + "69": "trilobite", + "70": "harvestman, daddy longlegs, Phalangium opilio", + "71": "scorpion", + "72": "black and gold garden spider, Argiope aurantia", + "73": "barn spider, Araneus cavaticus", + "74": "garden spider, Aranea diademata", + "75": "black widow, Latrodectus mactans", + "76": "tarantula", + "77": "wolf spider, hunting spider", + "78": "tick", + "79": "centipede", + "80": "black grouse", + "81": "ptarmigan", + "82": "ruffed grouse, partridge, Bonasa umbellus", + "83": "prairie chicken, prairie grouse, prairie fowl", + "84": "peacock", + "85": "quail", + "86": "partridge", + "87": "African grey, African gray, Psittacus erithacus", + "88": "macaw", + "89": "sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita", + "90": "lorikeet", + "91": "coucal", + "92": "bee eater", + "93": "hornbill", + "94": "hummingbird", + "95": "jacamar", + "96": "toucan", + "97": "drake", + "98": "red-breasted merganser, Mergus serrator", + "99": "goose", + "100": "black swan, Cygnus atratus", + "101": "tusker", + "102": "echidna, spiny anteater, anteater", + "103": "platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus", + "104": "wallaby, brush kangaroo", + "105": "koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus", + "106": "wombat", + "107": "jellyfish", + "108": "sea anemone, anemone", + "109": "brain coral", + "110": "flatworm, platyhelminth", + "111": "nematode, nematode worm, roundworm", + "112": "conch", + "113": "snail", + "114": "slug", + "115": "sea slug, nudibranch", + "116": "chiton, coat-of-mail shell, sea cradle, polyplacophore", + "117": "chambered nautilus, pearly nautilus, nautilus", + "118": "Dungeness crab, Cancer magister", + "119": "rock crab, Cancer irroratus", + "120": "fiddler crab", + "121": "king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica", + "122": "American lobster, Northern lobster, Maine lobster, Homarus americanus", + "123": "spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish", + "124": "crayfish, crawfish, crawdad, crawdaddy", + "125": "hermit crab", + "126": "isopod", + "127": "white stork, Ciconia ciconia", + "128": "black stork, Ciconia nigra", + "129": "spoonbill", + "130": "flamingo", + "131": "little blue heron, Egretta caerulea", + "132": "American egret, great white heron, Egretta albus", + "133": "bittern", + "134": "crane", + "135": "limpkin, Aramus pictus", + "136": "European gallinule, Porphyrio porphyrio", + "137": "American coot, marsh hen, mud hen, water hen, Fulica americana", + "138": "bustard", + "139": "ruddy turnstone, Arenaria interpres", + "140": "red-backed sandpiper, dunlin, Erolia alpina", + "141": "redshank, Tringa totanus", + "142": "dowitcher", + "143": "oystercatcher, oyster catcher", + "144": "pelican", + "145": "king penguin, Aptenodytes patagonica", + "146": "albatross, mollymawk", + "147": "grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus", + "148": "killer whale, killer, orca, grampus, sea wolf, Orcinus orca", + "149": "dugong, Dugong dugon", + "150": "sea lion", + "151": "Chihuahua", + "152": "Japanese spaniel", + "153": "Maltese dog, Maltese terrier, Maltese", + "154": "Pekinese, Pekingese, Peke", + "155": "Shih-Tzu", + "156": "Blenheim spaniel", + "157": "papillon", + "158": "toy terrier", + "159": "Rhodesian ridgeback", + "160": "Afghan hound, Afghan", + "161": "basset, basset hound", + "162": "beagle", + "163": "bloodhound, sleuthhound", + "164": "bluetick", + "165": "black-and-tan coonhound", + "166": "Walker hound, Walker foxhound", + "167": "English foxhound", + "168": "redbone", + "169": "borzoi, Russian wolfhound", + "170": "Irish wolfhound", + "171": "Italian greyhound", + "172": "whippet", + "173": "Ibizan hound, Ibizan Podenco", + "174": "Norwegian elkhound, elkhound", + "175": "otterhound, otter hound", + "176": "Saluki, gazelle hound", + "177": "Scottish deerhound, deerhound", + "178": "Weimaraner", + "179": "Staffordshire bullterrier, Staffordshire bull terrier", + "180": "American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier", + "181": "Bedlington terrier", + "182": "Border terrier", + "183": "Kerry blue terrier", + "184": "Irish terrier", + "185": "Norfolk terrier", + "186": "Norwich terrier", + "187": "Yorkshire terrier", + "188": "wire-haired fox terrier", + "189": "Lakeland terrier", + "190": "Sealyham terrier, Sealyham", + "191": "Airedale, Airedale terrier", + "192": "cairn, cairn terrier", + "193": "Australian terrier", + "194": "Dandie Dinmont, Dandie Dinmont terrier", + "195": "Boston bull, Boston terrier", + "196": "miniature schnauzer", + "197": "giant schnauzer", + "198": "standard schnauzer", + "199": "Scotch terrier, Scottish terrier, Scottie", + "200": "Tibetan terrier, chrysanthemum dog", + "201": "silky terrier, Sydney silky", + "202": "soft-coated wheaten terrier", + "203": "West Highland white terrier", + "204": "Lhasa, Lhasa apso", + "205": "flat-coated retriever", + "206": "curly-coated retriever", + "207": "golden retriever", + "208": "Labrador retriever", + "209": "Chesapeake Bay retriever", + "210": "German short-haired pointer", + "211": "vizsla, Hungarian pointer", + "212": "English setter", + "213": "Irish setter, red setter", + "214": "Gordon setter", + "215": "Brittany spaniel", + "216": "clumber, clumber spaniel", + "217": "English springer, English springer spaniel", + "218": "Welsh springer spaniel", + "219": "cocker spaniel, English cocker spaniel, cocker", + "220": "Sussex spaniel", + "221": "Irish water spaniel", + "222": "kuvasz", + "223": "schipperke", + "224": "groenendael", + "225": "malinois", + "226": "briard", + "227": "kelpie", + "228": "komondor", + "229": "Old English sheepdog, bobtail", + "230": "Shetland sheepdog, Shetland sheep dog, Shetland", + "231": "collie", + "232": "Border collie", + "233": "Bouvier des Flandres, Bouviers des Flandres", + "234": "Rottweiler", + "235": "German shepherd, German shepherd dog, German police dog, alsatian", + "236": "Doberman, Doberman pinscher", + "237": "miniature pinscher", + "238": "Greater Swiss Mountain dog", + "239": "Bernese mountain dog", + "240": "Appenzeller", + "241": "EntleBucher", + "242": "boxer", + "243": "bull mastiff", + "244": "Tibetan mastiff", + "245": "French bulldog", + "246": "Great Dane", + "247": "Saint Bernard, St Bernard", + "248": "Eskimo dog, husky", + "249": "malamute, malemute, Alaskan malamute", + "250": "Siberian husky", + "251": "dalmatian, coach dog, carriage dog", + "252": "affenpinscher, monkey pinscher, monkey dog", + "253": "basenji", + "254": "pug, pug-dog", + "255": "Leonberg", + "256": "Newfoundland, Newfoundland dog", + "257": "Great Pyrenees", + "258": "Samoyed, Samoyede", + "259": "Pomeranian", + "260": "chow, chow chow", + "261": "keeshond", + "262": "Brabancon griffon", + "263": "Pembroke, Pembroke Welsh corgi", + "264": "Cardigan, Cardigan Welsh corgi", + "265": "toy poodle", + "266": "miniature poodle", + "267": "standard poodle", + "268": "Mexican hairless", + "269": "timber wolf, grey wolf, gray wolf, Canis lupus", + "270": "white wolf, Arctic wolf, Canis lupus tundrarum", + "271": "red wolf, maned wolf, Canis rufus, Canis niger", + "272": "coyote, prairie wolf, brush wolf, Canis latrans", + "273": "dingo, warrigal, warragal, Canis dingo", + "274": "dhole, Cuon alpinus", + "275": "African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus", + "276": "hyena, hyaena", + "277": "red fox, Vulpes vulpes", + "278": "kit fox, Vulpes macrotis", + "279": "Arctic fox, white fox, Alopex lagopus", + "280": "grey fox, gray fox, Urocyon cinereoargenteus", + "281": "tabby, tabby cat", + "282": "tiger cat", + "283": "Persian cat", + "284": "Siamese cat, Siamese", + "285": "Egyptian cat", + "286": "cougar, puma, catamount, mountain lion, painter, panther, Felis concolor", + "287": "lynx, catamount", + "288": "leopard, Panthera pardus", + "289": "snow leopard, ounce, Panthera uncia", + "290": "jaguar, panther, Panthera onca, Felis onca", + "291": "lion, king of beasts, Panthera leo", + "292": "tiger, Panthera tigris", + "293": "cheetah, chetah, Acinonyx jubatus", + "294": "brown bear, bruin, Ursus arctos", + "295": "American black bear, black bear, Ursus americanus, Euarctos americanus", + "296": "ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus", + "297": "sloth bear, Melursus ursinus, Ursus ursinus", + "298": "mongoose", + "299": "meerkat, mierkat", + "300": "tiger beetle", + "301": "ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle", + "302": "ground beetle, carabid beetle", + "303": "long-horned beetle, longicorn, longicorn beetle", + "304": "leaf beetle, chrysomelid", + "305": "dung beetle", + "306": "rhinoceros beetle", + "307": "weevil", + "308": "fly", + "309": "bee", + "310": "ant, emmet, pismire", + "311": "grasshopper, hopper", + "312": "cricket", + "313": "walking stick, walkingstick, stick insect", + "314": "cockroach, roach", + "315": "mantis, mantid", + "316": "cicada, cicala", + "317": "leafhopper", + "318": "lacewing, lacewing fly", + "319": "dragonfly, darning needle, devils darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk", + "320": "damselfly", + "321": "admiral", + "322": "ringlet, ringlet butterfly", + "323": "monarch, monarch butterfly, milkweed butterfly, Danaus plexippus", + "324": "cabbage butterfly", + "325": "sulphur butterfly, sulfur butterfly", + "326": "lycaenid, lycaenid butterfly", + "327": "starfish, sea star", + "328": "sea urchin", + "329": "sea cucumber, holothurian", + "330": "wood rabbit, cottontail, cottontail rabbit", + "331": "hare", + "332": "Angora, Angora rabbit", + "333": "hamster", + "334": "porcupine, hedgehog", + "335": "fox squirrel, eastern fox squirrel, Sciurus niger", + "336": "marmot", + "337": "beaver", + "338": "guinea pig, Cavia cobaya", + "339": "sorrel", + "340": "zebra", + "341": "hog, pig, grunter, squealer, Sus scrofa", + "342": "wild boar, boar, Sus scrofa", + "343": "warthog", + "344": "hippopotamus, hippo, river horse, Hippopotamus amphibius", + "345": "ox", + "346": "water buffalo, water ox, Asiatic buffalo, Bubalus bubalis", + "347": "bison", + "348": "ram, tup", + "349": "bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis", + "350": "ibex, Capra ibex", + "351": "hartebeest", + "352": "impala, Aepyceros melampus", + "353": "gazelle", + "354": "Arabian camel, dromedary, Camelus dromedarius", + "355": "llama", + "356": "weasel", + "357": "mink", + "358": "polecat, fitch, foulmart, foumart, Mustela putorius", + "359": "black-footed ferret, ferret, Mustela nigripes", + "360": "otter", + "361": "skunk, polecat, wood pussy", + "362": "badger", + "363": "armadillo", + "364": "three-toed sloth, ai, Bradypus tridactylus", + "365": "orangutan, orang, orangutang, Pongo pygmaeus", + "366": "gorilla, Gorilla gorilla", + "367": "chimpanzee, chimp, Pan troglodytes", + "368": "gibbon, Hylobates lar", + "369": "siamang, Hylobates syndactylus, Symphalangus syndactylus", + "370": "guenon, guenon monkey", + "371": "patas, hussar monkey, Erythrocebus patas", + "372": "baboon", + "373": "macaque", + "374": "langur", + "375": "colobus, colobus monkey", + "376": "proboscis monkey, Nasalis larvatus", + "377": "marmoset", + "378": "capuchin, ringtail, Cebus capucinus", + "379": "howler monkey, howler", + "380": "titi, titi monkey", + "381": "spider monkey, Ateles geoffroyi", + "382": "squirrel monkey, Saimiri sciureus", + "383": "Madagascar cat, ring-tailed lemur, Lemur catta", + "384": "indri, indris, Indri indri, Indri brevicaudatus", + "385": "Indian elephant, Elephas maximus", + "386": "African elephant, Loxodonta africana", + "387": "lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens", + "388": "giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca", + "389": "barracouta, snoek", + "390": "eel", + "391": "coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch", + "392": "rock beauty, Holocanthus tricolor", + "393": "anemone fish", + "394": "sturgeon", + "395": "gar, garfish, garpike, billfish, Lepisosteus osseus", + "396": "lionfish", + "397": "puffer, pufferfish, blowfish, globefish", + "398": "abacus", + "399": "abaya", + "400": "academic gown, academic robe, judge robe", + "401": "accordion, piano accordion, squeeze box", + "402": "acoustic guitar", + "403": "aircraft carrier, carrier, flattop, attack aircraft carrier", + "404": "airliner", + "405": "airship, dirigible", + "406": "altar", + "407": "ambulance", + "408": "amphibian, amphibious vehicle", + "409": "analog clock", + "410": "apiary, bee house", + "411": "apron", + "412": "ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin", + "413": "assault rifle, assault gun", + "414": "backpack, back pack, knapsack, packsack, rucksack, haversack", + "415": "bakery, bakeshop, bakehouse", + "416": "balance beam, beam", + "417": "balloon", + "418": "ballpoint, ballpoint pen, ballpen, Biro", + "419": "Band Aid", + "420": "banjo", + "421": "bannister, banister, balustrade, balusters, handrail", + "422": "barbell", + "423": "barber chair", + "424": "barbershop", + "425": "barn", + "426": "barometer", + "427": "barrel, cask", + "428": "barrow, garden cart, lawn cart, wheelbarrow", + "429": "baseball", + "430": "basketball", + "431": "bassinet", + "432": "bassoon", + "433": "bathing cap, swimming cap", + "434": "bath towel", + "435": "bathtub, bathing tub, bath, tub", + "436": "beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon", + "437": "beacon, lighthouse, beacon light, pharos", + "438": "beaker", + "439": "bearskin, busby, shako", + "440": "beer bottle", + "441": "beer glass", + "442": "bell cote, bell cot", + "443": "bib", + "444": "bicycle-built-for-two, tandem bicycle, tandem", + "445": "bikini, two-piece", + "446": "binder, ring-binder", + "447": "binoculars, field glasses, opera glasses", + "448": "birdhouse", + "449": "boathouse", + "450": "bobsled, bobsleigh, bob", + "451": "bolo tie, bolo, bola tie, bola", + "452": "bonnet, poke bonnet", + "453": "bookcase", + "454": "bookshop, bookstore, bookstall", + "455": "bottlecap", + "456": "bow", + "457": "bow tie, bow-tie, bowtie", + "458": "brass, memorial tablet, plaque", + "459": "brassiere, bra, bandeau", + "460": "breakwater, groin, groyne, mole, bulwark, seawall, jetty", + "461": "breastplate, aegis, egis", + "462": "broom", + "463": "bucket, pail", + "464": "buckle", + "465": "bulletproof vest", + "466": "bullet train, bullet", + "467": "butcher shop, meat market", + "468": "cab, hack, taxi, taxicab", + "469": "caldron, cauldron", + "470": "candle, taper, wax light", + "471": "cannon", + "472": "canoe", + "473": "can opener, tin opener", + "474": "cardigan", + "475": "car mirror", + "476": "carousel, carrousel, merry-go-round, roundabout, whirligig", + "477": "carpenters kit, tool kit", + "478": "carton", + "479": "car wheel", + "480": "cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM", + "481": "cassette", + "482": "cassette player", + "483": "castle", + "484": "catamaran", + "485": "CD player", + "486": "cello, violoncello", + "487": "cellular telephone, cellular phone, cellphone, cell, mobile phone", + "488": "chain", + "489": "chainlink fence", + "490": "chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour", + "491": "chain saw, chainsaw", + "492": "chest", + "493": "chiffonier, commode", + "494": "chime, bell, gong", + "495": "china cabinet, china closet", + "496": "Christmas stocking", + "497": "church, church building", + "498": "cinema, movie theater, movie theatre, movie house, picture palace", + "499": "cleaver, meat cleaver, chopper", + "500": "cliff dwelling", + "501": "cloak", + "502": "clog, geta, patten, sabot", + "503": "cocktail shaker", + "504": "coffee mug", + "505": "coffeepot", + "506": "coil, spiral, volute, whorl, helix", + "507": "combination lock", + "508": "computer keyboard, keypad", + "509": "confectionery, confectionary, candy store", + "510": "container ship, containership, container vessel", + "511": "convertible", + "512": "corkscrew, bottle screw", + "513": "cornet, horn, trumpet, trump", + "514": "cowboy boot", + "515": "cowboy hat, ten-gallon hat", + "516": "cradle", + "517": "crane", + "518": "crash helmet", + "519": "crate", + "520": "crib, cot", + "521": "Crock Pot", + "522": "croquet ball", + "523": "crutch", + "524": "cuirass", + "525": "dam, dike, dyke", + "526": "desk", + "527": "desktop computer", + "528": "dial telephone, dial phone", + "529": "diaper, nappy, napkin", + "530": "digital clock", + "531": "digital watch", + "532": "dining table, board", + "533": "dishrag, dishcloth", + "534": "dishwasher, dish washer, dishwashing machine", + "535": "disk brake, disc brake", + "536": "dock, dockage, docking facility", + "537": "dogsled, dog sled, dog sleigh", + "538": "dome", + "539": "doormat, welcome mat", + "540": "drilling platform, offshore rig", + "541": "drum, membranophone, tympan", + "542": "drumstick", + "543": "dumbbell", + "544": "Dutch oven", + "545": "electric fan, blower", + "546": "electric guitar", + "547": "electric locomotive", + "548": "entertainment center", + "549": "envelope", + "550": "espresso maker", + "551": "face powder", + "552": "feather boa, boa", + "553": "file, file cabinet, filing cabinet", + "554": "fireboat", + "555": "fire engine, fire truck", + "556": "fire screen, fireguard", + "557": "flagpole, flagstaff", + "558": "flute, transverse flute", + "559": "folding chair", + "560": "football helmet", + "561": "forklift", + "562": "fountain", + "563": "fountain pen", + "564": "four-poster", + "565": "freight car", + "566": "French horn, horn", + "567": "frying pan, frypan, skillet", + "568": "fur coat", + "569": "garbage truck, dustcart", + "570": "gasmask, respirator, gas helmet", + "571": "gas pump, gasoline pump, petrol pump, island dispenser", + "572": "goblet", + "573": "go-kart", + "574": "golf ball", + "575": "golfcart, golf cart", + "576": "gondola", + "577": "gong, tam-tam", + "578": "gown", + "579": "grand piano, grand", + "580": "greenhouse, nursery, glasshouse", + "581": "grille, radiator grille", + "582": "grocery store, grocery, food market, market", + "583": "guillotine", + "584": "hair slide", + "585": "hair spray", + "586": "half track", + "587": "hammer", + "588": "hamper", + "589": "hand blower, blow dryer, blow drier, hair dryer, hair drier", + "590": "hand-held computer, hand-held microcomputer", + "591": "handkerchief, hankie, hanky, hankey", + "592": "hard disc, hard disk, fixed disk", + "593": "harmonica, mouth organ, harp, mouth harp", + "594": "harp", + "595": "harvester, reaper", + "596": "hatchet", + "597": "holster", + "598": "home theater, home theatre", + "599": "honeycomb", + "600": "hook, claw", + "601": "hoopskirt, crinoline", + "602": "horizontal bar, high bar", + "603": "horse cart, horse-cart", + "604": "hourglass", + "605": "iPod", + "606": "iron, smoothing iron", + "607": "jack-o-lantern", + "608": "jean, blue jean, denim", + "609": "jeep, landrover", + "610": "jersey, T-shirt, tee shirt", + "611": "jigsaw puzzle", + "612": "jinrikisha, ricksha, rickshaw", + "613": "joystick", + "614": "kimono", + "615": "knee pad", + "616": "knot", + "617": "lab coat, laboratory coat", + "618": "ladle", + "619": "lampshade, lamp shade", + "620": "laptop, laptop computer", + "621": "lawn mower, mower", + "622": "lens cap, lens cover", + "623": "letter opener, paper knife, paperknife", + "624": "library", + "625": "lifeboat", + "626": "lighter, light, igniter, ignitor", + "627": "limousine, limo", + "628": "liner, ocean liner", + "629": "lipstick, lip rouge", + "630": "Loafer", + "631": "lotion", + "632": "loudspeaker, speaker, speaker unit, loudspeaker system, speaker system", + "633": "loupe, jewelers loupe", + "634": "lumbermill, sawmill", + "635": "magnetic compass", + "636": "mailbag, postbag", + "637": "mailbox, letter box", + "638": "maillot", + "639": "maillot, tank suit", + "640": "manhole cover", + "641": "maraca", + "642": "marimba, xylophone", + "643": "mask", + "644": "matchstick", + "645": "maypole", + "646": "maze, labyrinth", + "647": "measuring cup", + "648": "medicine chest, medicine cabinet", + "649": "megalith, megalithic structure", + "650": "microphone, mike", + "651": "microwave, microwave oven", + "652": "military uniform", + "653": "milk can", + "654": "minibus", + "655": "miniskirt, mini", + "656": "minivan", + "657": "missile", + "658": "mitten", + "659": "mixing bowl", + "660": "mobile home, manufactured home", + "661": "Model T", + "662": "modem", + "663": "monastery", + "664": "monitor", + "665": "moped", + "666": "mortar", + "667": "mortarboard", + "668": "mosque", + "669": "mosquito net", + "670": "motor scooter, scooter", + "671": "mountain bike, all-terrain bike, off-roader", + "672": "mountain tent", + "673": "mouse, computer mouse", + "674": "mousetrap", + "675": "moving van", + "676": "muzzle", + "677": "nail", + "678": "neck brace", + "679": "necklace", + "680": "nipple", + "681": "notebook, notebook computer", + "682": "obelisk", + "683": "oboe, hautboy, hautbois", + "684": "ocarina, sweet potato", + "685": "odometer, hodometer, mileometer, milometer", + "686": "oil filter", + "687": "organ, pipe organ", + "688": "oscilloscope, scope, cathode-ray oscilloscope, CRO", + "689": "overskirt", + "690": "oxcart", + "691": "oxygen mask", + "692": "packet", + "693": "paddle, boat paddle", + "694": "paddlewheel, paddle wheel", + "695": "padlock", + "696": "paintbrush", + "697": "pajama, pyjama, pjs, jammies", + "698": "palace", + "699": "panpipe, pandean pipe, syrinx", + "700": "paper towel", + "701": "parachute, chute", + "702": "parallel bars, bars", + "703": "park bench", + "704": "parking meter", + "705": "passenger car, coach, carriage", + "706": "patio, terrace", + "707": "pay-phone, pay-station", + "708": "pedestal, plinth, footstall", + "709": "pencil box, pencil case", + "710": "pencil sharpener", + "711": "perfume, essence", + "712": "Petri dish", + "713": "photocopier", + "714": "pick, plectrum, plectron", + "715": "pickelhaube", + "716": "picket fence, paling", + "717": "pickup, pickup truck", + "718": "pier", + "719": "piggy bank, penny bank", + "720": "pill bottle", + "721": "pillow", + "722": "ping-pong ball", + "723": "pinwheel", + "724": "pirate, pirate ship", + "725": "pitcher, ewer", + "726": "plane, carpenters plane, woodworking plane", + "727": "planetarium", + "728": "plastic bag", + "729": "plate rack", + "730": "plow, plough", + "731": "plunger, plumbers helper", + "732": "Polaroid camera, Polaroid Land camera", + "733": "pole", + "734": "police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria", + "735": "poncho", + "736": "pool table, billiard table, snooker table", + "737": "pop bottle, soda bottle", + "738": "pot, flowerpot", + "739": "potters wheel", + "740": "power drill", + "741": "prayer rug, prayer mat", + "742": "printer", + "743": "prison, prison house", + "744": "projectile, missile", + "745": "projector", + "746": "puck, hockey puck", + "747": "punching bag, punch bag, punching ball, punchball", + "748": "purse", + "749": "quill, quill pen", + "750": "quilt, comforter, comfort, puff", + "751": "racer, race car, racing car", + "752": "racket, racquet", + "753": "radiator", + "754": "radio, wireless", + "755": "radio telescope, radio reflector", + "756": "rain barrel", + "757": "recreational vehicle, RV, R.V.", + "758": "reel", + "759": "reflex camera", + "760": "refrigerator, icebox", + "761": "remote control, remote", + "762": "restaurant, eating house, eating place, eatery", + "763": "revolver, six-gun, six-shooter", + "764": "rifle", + "765": "rocking chair, rocker", + "766": "rotisserie", + "767": "rubber eraser, rubber, pencil eraser", + "768": "rugby ball", + "769": "rule, ruler", + "770": "running shoe", + "771": "safe", + "772": "safety pin", + "773": "saltshaker, salt shaker", + "774": "sandal", + "775": "sarong", + "776": "sax, saxophone", + "777": "scabbard", + "778": "scale, weighing machine", + "779": "school bus", + "780": "schooner", + "781": "scoreboard", + "782": "screen, CRT screen", + "783": "screw", + "784": "screwdriver", + "785": "seat belt, seatbelt", + "786": "sewing machine", + "787": "shield, buckler", + "788": "shoe shop, shoe-shop, shoe store", + "789": "shoji", + "790": "shopping basket", + "791": "shopping cart", + "792": "shovel", + "793": "shower cap", + "794": "shower curtain", + "795": "ski", + "796": "ski mask", + "797": "sleeping bag", + "798": "slide rule, slipstick", + "799": "sliding door", + "800": "slot, one-armed bandit", + "801": "snorkel", + "802": "snowmobile", + "803": "snowplow, snowplough", + "804": "soap dispenser", + "805": "soccer ball", + "806": "sock", + "807": "solar dish, solar collector, solar furnace", + "808": "sombrero", + "809": "soup bowl", + "810": "space bar", + "811": "space heater", + "812": "space shuttle", + "813": "spatula", + "814": "speedboat", + "815": "spider web, spiders web", + "816": "spindle", + "817": "sports car, sport car", + "818": "spotlight, spot", + "819": "stage", + "820": "steam locomotive", + "821": "steel arch bridge", + "822": "steel drum", + "823": "stethoscope", + "824": "stole", + "825": "stone wall", + "826": "stopwatch, stop watch", + "827": "stove", + "828": "strainer", + "829": "streetcar, tram, tramcar, trolley, trolley car", + "830": "stretcher", + "831": "studio couch, day bed", + "832": "stupa, tope", + "833": "submarine, pigboat, sub, U-boat", + "834": "suit, suit of clothes", + "835": "sundial", + "836": "sunglass", + "837": "sunglasses, dark glasses, shades", + "838": "sunscreen, sunblock, sun blocker", + "839": "suspension bridge", + "840": "swab, swob, mop", + "841": "sweatshirt", + "842": "swimming trunks, bathing trunks", + "843": "swing", + "844": "switch, electric switch, electrical switch", + "845": "syringe", + "846": "table lamp", + "847": "tank, army tank, armored combat vehicle, armoured combat vehicle", + "848": "tape player", + "849": "teapot", + "850": "teddy, teddy bear", + "851": "television, television system", + "852": "tennis ball", + "853": "thatch, thatched roof", + "854": "theater curtain, theatre curtain", + "855": "thimble", + "856": "thresher, thrasher, threshing machine", + "857": "throne", + "858": "tile roof", + "859": "toaster", + "860": "tobacco shop, tobacconist shop, tobacconist", + "861": "toilet seat", + "862": "torch", + "863": "totem pole", + "864": "tow truck, tow car, wrecker", + "865": "toyshop", + "866": "tractor", + "867": "trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi", + "868": "tray", + "869": "trench coat", + "870": "tricycle, trike, velocipede", + "871": "trimaran", + "872": "tripod", + "873": "triumphal arch", + "874": "trolleybus, trolley coach, trackless trolley", + "875": "trombone", + "876": "tub, vat", + "877": "turnstile", + "878": "typewriter keyboard", + "879": "umbrella", + "880": "unicycle, monocycle", + "881": "upright, upright piano", + "882": "vacuum, vacuum cleaner", + "883": "vase", + "884": "vault", + "885": "velvet", + "886": "vending machine", + "887": "vestment", + "888": "viaduct", + "889": "violin, fiddle", + "890": "volleyball", + "891": "waffle iron", + "892": "wall clock", + "893": "wallet, billfold, notecase, pocketbook", + "894": "wardrobe, closet, press", + "895": "warplane, military plane", + "896": "washbasin, handbasin, washbowl, lavabo, wash-hand basin", + "897": "washer, automatic washer, washing machine", + "898": "water bottle", + "899": "water jug", + "900": "water tower", + "901": "whiskey jug", + "902": "whistle", + "903": "wig", + "904": "window screen", + "905": "window shade", + "906": "Windsor tie", + "907": "wine bottle", + "908": "wing", + "909": "wok", + "910": "wooden spoon", + "911": "wool, woolen, woollen", + "912": "worm fence, snake fence, snake-rail fence, Virginia fence", + "913": "wreck", + "914": "yawl", + "915": "yurt", + "916": "web site, website, internet site, site", + "917": "comic book", + "918": "crossword puzzle, crossword", + "919": "street sign", + "920": "traffic light, traffic signal, stoplight", + "921": "book jacket, dust cover, dust jacket, dust wrapper", + "922": "menu", + "923": "plate", + "924": "guacamole", + "925": "consomme", + "926": "hot pot, hotpot", + "927": "trifle", + "928": "ice cream, icecream", + "929": "ice lolly, lolly, lollipop, popsicle", + "930": "French loaf", + "931": "bagel, beigel", + "932": "pretzel", + "933": "cheeseburger", + "934": "hotdog, hot dog, red hot", + "935": "mashed potato", + "936": "head cabbage", + "937": "broccoli", + "938": "cauliflower", + "939": "zucchini, courgette", + "940": "spaghetti squash", + "941": "acorn squash", + "942": "butternut squash", + "943": "cucumber, cuke", + "944": "artichoke, globe artichoke", + "945": "bell pepper", + "946": "cardoon", + "947": "mushroom", + "948": "Granny Smith", + "949": "strawberry", + "950": "orange", + "951": "lemon", + "952": "fig", + "953": "pineapple, ananas", + "954": "banana", + "955": "jackfruit, jak, jack", + "956": "custard apple", + "957": "pomegranate", + "958": "hay", + "959": "carbonara", + "960": "chocolate sauce, chocolate syrup", + "961": "dough", + "962": "meat loaf, meatloaf", + "963": "pizza, pizza pie", + "964": "potpie", + "965": "burrito", + "966": "red wine", + "967": "espresso", + "968": "cup", + "969": "eggnog", + "970": "alp", + "971": "bubble", + "972": "cliff, drop, drop-off", + "973": "coral reef", + "974": "geyser", + "975": "lakeside, lakeshore", + "976": "promontory, headland, head, foreland", + "977": "sandbar, sand bar", + "978": "seashore, coast, seacoast, sea-coast", + "979": "valley, vale", + "980": "volcano", + "981": "ballplayer, baseball player", + "982": "groom, bridegroom", + "983": "scuba diver", + "984": "rapeseed", + "985": "daisy", + "986": "yellow ladys slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum", + "987": "corn", + "988": "acorn", + "989": "hip, rose hip, rosehip", + "990": "buckeye, horse chestnut, conker", + "991": "coral fungus", + "992": "agaric", + "993": "gyromitra", + "994": "stinkhorn, carrion fungus", + "995": "earthstar", + "996": "hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa", + "997": "bolete", + "998": "ear, spike, capitulum", + "999": "toilet tissue, toilet paper, bathroom tissue" + }, + "scheduler": [ + "scheduling_flow_match_pae", + "PAEFlowMatchScheduler" + ], + "transformers": [ + "transformer_lightning_dit", + "LightningDiT2DModel" + ] +} diff --git a/pae-dinov2-large-d32/pipeline.py b/pae-dinov2-large-d32/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..baed829d24d510b38fe9905fd001b835a176475f --- /dev/null +++ b/pae-dinov2-large-d32/pipeline.py @@ -0,0 +1,530 @@ +"""Hub custom pipeline: PAEPipeline. +Load with native Hugging Face diffusers and trust_remote_code=True. +""" + +from __future__ import annotations + +# Copyright 2026 The HuggingFace Team and PAE authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import inspect +import json +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple, Union + +import torch + +from diffusers.image_processor import VaeImageProcessor +from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput +from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers +from diffusers.utils.torch_utils import randn_tensor + +EXAMPLE_DOC_STRING = """ + Examples: + ```py + >>> from pathlib import Path + >>> from diffusers import DiffusionPipeline + >>> import torch + + >>> model_dir = Path("./pae-dinov2-large-d32").resolve() + >>> pipe = DiffusionPipeline.from_pretrained( + ... str(model_dir), + ... local_files_only=True, + ... custom_pipeline=str(model_dir / "pipeline.py"), + ... trust_remote_code=True, + ... torch_dtype=torch.bfloat16, + ... ) + >>> pipe.to("cuda") + + >>> print(pipe.id2label[207]) + >>> print(pipe.get_label_ids("golden retriever")) + + >>> generator = torch.Generator(device="cuda").manual_seed(42) + >>> image = pipe( + ... class_labels="golden retriever", + ... generator=generator, + ... ).images[0] + ``` +""" + + +class PAEPipeline(DiffusionPipeline): + r""" + Pipeline for class-conditional image generation with PAE tokenizers and LightningDiT. + + This model inherits from [`DiffusionPipeline`]. Components are stored in separate subfolders + (`transformers/`, `scheduler/`, `decoder/`) and loaded via `DiffusionPipeline.from_pretrained`. + + Parameters: + transformers ([`LightningDiT2DModel`]): + Class-conditional LightningDiT transformer that predicts flow-matching velocity in PAE latent space. + scheduler ([`PAEFlowMatchScheduler`]): + Flow-matching ODE/SDE scheduler. Other [`KarrasDiffusionSchedulers`] can be swapped at inference time + when their `step` API is compatible. + decoder ([`PAEDecoder`]): + Prior-Aligned Autoencoder decoder stack (decompressor + pixel decoder). + + ImageNet `id2label` mappings are read lazily from `model_index.json` when label helpers are used. + """ + + model_cpu_offload_seq = "transformers->decoder" + _optional_components = ["decoder"] + + @staticmethod + def prepare_extra_step_kwargs( + scheduler: KarrasDiffusionSchedulers, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + eta: Optional[float] = None, + ) -> Dict[str, object]: + r""" + Build kwargs forwarded to `scheduler.step` when supported. + + Args: + scheduler: + Active diffusion scheduler instance. + generator: + Optional RNG passed through to stochastic scheduler steps. + eta: + Optional DDIM-style eta when the scheduler accepts it. + """ + kwargs: Dict[str, object] = {} + step_params = set(inspect.signature(scheduler.step).parameters.keys()) + if "generator" in step_params: + kwargs["generator"] = generator + if eta is not None and "eta" in step_params: + kwargs["eta"] = eta + return kwargs + + def __init__( + self, + transformers, + scheduler: KarrasDiffusionSchedulers, + decoder=None, + transformer=None, + ) -> None: + if transformer is not None and transformers is None: + transformers = transformer + super().__init__() + self.register_modules(transformers=transformers, scheduler=scheduler, decoder=decoder) + # PAE decoders already return pixels in [0, 1]; disable VAE-style [-1, 1] denormalization. + self.image_processor = VaeImageProcessor(do_normalize=False) + self._id2label: Dict[int, str] = {} + self.labels: Dict[str, int] = {} + self._labels_loaded_from_model_index = False + + @property + def transformer(self): + """Backward-compatible alias for `transformers`.""" + return self.transformers + + @staticmethod + def _normalize_id2label(id2label: Optional[Dict[Union[int, str], str]]) -> Dict[int, str]: + if not id2label: + return {} + return {int(key): value for key, value in id2label.items()} + + @staticmethod + def _read_model_index(variant_path: Optional[str]) -> Dict[str, Any]: + if not variant_path: + return {} + variant_dir = Path(variant_path).resolve() + model_index_path = variant_dir / "model_index.json" + if not model_index_path.is_file(): + return {} + raw = json.loads(model_index_path.read_text(encoding="utf-8")) + return raw if isinstance(raw, dict) else {} + + @staticmethod + def _read_id2label_from_model_index(variant_path: Optional[str]) -> Dict[int, str]: + id2label = PAEPipeline._read_model_index(variant_path).get("id2label") + if not isinstance(id2label, dict): + return {} + return {int(key): value for key, value in id2label.items()} + + def _get_downsample_ratio(self) -> int: + override = getattr(self.config, "downsample_ratio", None) + if override is not None: + return int(override) + + encoder_input_size = None + if self.decoder is not None: + encoder_input_size = getattr(self.decoder.config, "encoder_input_size", None) + + if encoder_input_size is not None: + return int(encoder_input_size) // int(self.transformers.config.input_size) + return 16 + + def _resolve_latent_stats( + self, + latent_mean: Optional[torch.Tensor], + latent_std: Optional[torch.Tensor], + latent_multiplier: Optional[float], + device: torch.device, + dtype: torch.dtype, + ) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], float]: + if latent_mean is not None and latent_std is not None: + return latent_mean, latent_std, float(latent_multiplier if latent_multiplier is not None else 1.0) + + decoder_cfg = getattr(self.decoder, "config", None) if self.decoder is not None else None + if decoder_cfg is not None: + mean = getattr(decoder_cfg, "latent_mean", None) + std = getattr(decoder_cfg, "latent_std", None) + if mean is not None and std is not None: + multiplier = getattr(decoder_cfg, "latent_multiplier", 1.0) + mean_tensor = torch.tensor(mean, device=device, dtype=dtype).view(1, -1, 1, 1) + std_tensor = torch.tensor(std, device=device, dtype=dtype).view(1, -1, 1, 1) + return mean_tensor, std_tensor, float(multiplier) + + return latent_mean, latent_std, float(latent_multiplier if latent_multiplier is not None else 1.0) + + @staticmethod + def _build_label2id(id2label: Dict[int, str]) -> Dict[str, int]: + label2id: Dict[str, int] = {} + for class_id, value in id2label.items(): + for synonym in value.split(","): + synonym = synonym.strip() + if synonym: + label2id[synonym] = int(class_id) + return dict(sorted(label2id.items())) + + def _ensure_labels_loaded(self) -> None: + if self._labels_loaded_from_model_index: + return + loaded = self._read_id2label_from_model_index(getattr(self.config, "_name_or_path", None)) + if loaded: + self._id2label = loaded + self.labels = self._build_label2id(self._id2label) + self._labels_loaded_from_model_index = True + + @property + def id2label(self) -> Dict[int, str]: + r"""ImageNet class id to English label string (comma-separated synonyms).""" + self._ensure_labels_loaded() + return self._id2label + + def get_label_ids(self, label: Union[str, List[str]]) -> List[int]: + r""" + Map ImageNet label strings to class ids. + + Args: + label: + One or more English label strings. Each string must match a synonym in `id2label`. + + Returns: + Matching ImageNet class ids. + """ + self._ensure_labels_loaded() + label2id = self.labels + if not label2id: + raise ValueError("No English labels loaded. Ensure `id2label` exists in model_index.json.") + + if isinstance(label, str): + label = [label] + + missing = [item for item in label if item not in label2id] + if missing: + preview = ", ".join(list(label2id.keys())[:8]) + raise ValueError(f"Unknown English label(s): {missing}. Example valid labels: {preview}, ...") + return [label2id[item] for item in label] + + def _default_image_size(self) -> int: + return int(self.transformers.config.input_size) * self._get_downsample_ratio() + + def _normalize_class_labels( + self, + class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor], + ) -> torch.LongTensor: + if torch.is_tensor(class_labels): + return class_labels.to(device=self._execution_device, dtype=torch.long).reshape(-1) + + if isinstance(class_labels, int): + class_label_ids = [class_labels] + elif isinstance(class_labels, str): + class_label_ids = self.get_label_ids(class_labels) + elif class_labels and isinstance(class_labels[0], str): + class_label_ids = self.get_label_ids(class_labels) + else: + class_label_ids = list(class_labels) + + return torch.tensor(class_label_ids, device=self._execution_device, dtype=torch.long).reshape(-1) + + def check_inputs( + self, + height: int, + width: int, + num_inference_steps: int, + output_type: str, + mode: str, + ) -> None: + if num_inference_steps < 1: + raise ValueError("num_inference_steps must be >= 1.") + if output_type not in {"pil", "np", "pt", "latent"}: + raise ValueError("output_type must be one of: 'pil', 'np', 'pt', 'latent'.") + if mode not in {"ode", "sde"}: + raise ValueError("mode must be either 'ode' or 'sde'.") + + downsample = self._get_downsample_ratio() + if height % downsample != 0 or width % downsample != 0: + raise ValueError( + f"height and width must be divisible by the PAE downsample factor {downsample}." + ) + + latent_height = height // downsample + latent_width = width // downsample + expected_size = int(self.transformers.config.input_size) + if latent_height != expected_size or latent_width != expected_size: + raise ValueError( + f"Requested latent size {(latent_height, latent_width)} does not match the pretrained " + f"transformer input_size={expected_size}. Use height=width={self._default_image_size()}." + ) + + def prepare_latents( + self, + batch_size: int, + height: int, + width: int, + dtype: torch.dtype, + device: torch.device, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + ) -> torch.Tensor: + downsample = self._get_downsample_ratio() + latent_height = height // downsample + latent_width = width // downsample + return randn_tensor( + (batch_size, self.transformers.config.in_channels, latent_height, latent_width), + generator=generator, + device=device, + dtype=dtype, + ) + + @staticmethod + def _denormalize_latents( + latents: torch.Tensor, + latent_mean: Optional[torch.Tensor], + latent_std: Optional[torch.Tensor], + latent_multiplier: Optional[float], + ) -> torch.Tensor: + if latent_mean is None or latent_std is None: + return latents + multiplier = 1.0 if latent_multiplier is None else float(latent_multiplier) + mean = latent_mean.to(device=latents.device, dtype=latents.dtype) + std = latent_std.to(device=latents.device, dtype=latents.dtype) + return (latents * std) / multiplier + mean + + @staticmethod + def _apply_cfg( + model_output: torch.Tensor, + guidance_scale: float, + guidance_active: bool, + cfg_channels: int, + ) -> torch.Tensor: + if guidance_scale <= 1.0 or not guidance_active: + return model_output + eps, rest = model_output[:, :cfg_channels], model_output[:, cfg_channels:] + cond_eps, uncond_eps = torch.chunk(eps, 2, dim=0) + half_eps = uncond_eps + guidance_scale * (cond_eps - uncond_eps) + if rest.shape[1] == 0: + return half_eps + return torch.cat([half_eps, rest], dim=1) + + def decode_latents( + self, + latents: torch.Tensor, + output_type: str = "pil", + latent_mean: Optional[torch.Tensor] = None, + latent_std: Optional[torch.Tensor] = None, + latent_multiplier: Optional[float] = None, + ): + if output_type == "latent": + return latents + if self.decoder is None: + raise ValueError("PAEPipeline requires a PAE decoder component for decoding.") + + latent_mean, latent_std, latent_multiplier = self._resolve_latent_stats( + latent_mean, + latent_std, + latent_multiplier, + device=latents.device, + dtype=latents.dtype, + ) + latents = self._denormalize_latents(latents, latent_mean, latent_std, latent_multiplier) + image = self.decoder.decode(latents) + image = torch.clamp(image, 0.0, 1.0) + if output_type == "pt": + return image + return self.image_processor.postprocess(image, output_type=output_type, do_denormalize=[False] * image.shape[0]) + + @torch.inference_mode() + def __call__( + self, + class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor], + height: Optional[int] = None, + width: Optional[int] = None, + num_inference_steps: int = 250, + guidance_scale: float = 3.3, + guidance_interval: Tuple[float, float] = (0.0, 1.0), + cfg_interval_start: float = 0.3, + timestep_shift: float = 0.4, + mode: str = "ode", + heun: bool = False, + latent_mean: Optional[torch.Tensor] = None, + latent_std: Optional[torch.Tensor] = None, + latent_multiplier: Optional[float] = None, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + output_type: str = "pil", + return_dict: bool = True, + ) -> Union[ImagePipelineOutput, Tuple]: + r""" + Generate class-conditional images with PAE + LightningDiT. + + Args: + class_labels: + ImageNet class indices or human-readable English label strings. + height: + Output image height in pixels. Defaults to the pretrained native resolution. + width: + Output image width in pixels. Defaults to the pretrained native resolution. + num_inference_steps: + Number of flow-matching integration steps. + guidance_scale: + Classifier-free guidance scale. Active when `guidance_scale > 1.0`. + guidance_interval: + Timestep interval `(low, high)` where CFG is applied. + cfg_interval_start: + Disable CFG below this normalized timestep value. Default `0.3` matches DiT training configs. + timestep_shift: + Timestep warping used by LightningDiT ODE sampling. Default `0.4` matches DiT training configs. + mode: + Sampling mode passed to the PAE flow scheduler: `"ode"` or `"sde"`. + heun: + Use Heun integration for ODE sampling when True. + latent_mean: + Optional latent mean tensor for denormalization before PAE decode. Defaults to + `latent_mean` in `decoder/config.json` when omitted. + latent_std: + Optional latent std tensor for denormalization before PAE decode. Defaults to + `latent_std` in `decoder/config.json` when omitted. + latent_multiplier: + Divisor applied with `latent_std` during denormalization. Defaults to + `latent_multiplier` in `decoder/config.json` or `1.0`. + generator: + RNG for reproducibility. + output_type: + `"pil"`, `"np"`, `"pt"`, or `"latent"`. + return_dict: + Return [`ImagePipelineOutput`] if True. + """ + default_size = self._default_image_size() + height = int(height or default_size) + width = int(width or default_size) + self.check_inputs(height, width, num_inference_steps, output_type, mode) + + device = self._execution_device + model_dtype = next(self.transformers.parameters()).dtype + class_labels_tensor = self._normalize_class_labels(class_labels) + batch_size = class_labels_tensor.numel() + null_label = int(self.transformers.config.num_classes) + null_labels = torch.full((batch_size,), null_label, device=device, dtype=torch.long) + cfg_channels = int(self.transformers.config.in_channels) + + latents = self.prepare_latents( + batch_size=batch_size, + height=height, + width=width, + dtype=model_dtype, + device=device, + generator=generator, + ) + timesteps = self.scheduler.set_timesteps( + num_inference_steps, device=device, mode=mode, timestep_shift=timestep_shift + ) + extra_step_kwargs = self.prepare_extra_step_kwargs(self.scheduler, generator=generator) + + for index, timestep in enumerate(timesteps[:-1]): + next_timestep = timesteps[index + 1] + t_value = float(timestep) + guidance_active = guidance_scale > 1.0 and guidance_interval[0] <= t_value <= guidance_interval[1] + if cfg_interval_start is not None and t_value < cfg_interval_start: + guidance_active = False + + if guidance_active: + model_input = torch.cat([latents, latents], dim=0) + labels = torch.cat([class_labels_tensor, null_labels], dim=0) + else: + model_input = latents + labels = class_labels_tensor + + timestep_batch = torch.full((labels.shape[0],), t_value, device=device, dtype=model_dtype) + model_output = self.transformers( + model_input.to(dtype=model_dtype), + timestep=timestep_batch, + class_labels=labels, + return_dict=True, + ).sample + model_output = self._apply_cfg(model_output, guidance_scale, guidance_active, cfg_channels) + + if heun and mode == "ode" and index < len(timesteps) - 2: + provisional = self.scheduler.step( + model_output, + timestep[None], + latents, + next_timestep[None], + **extra_step_kwargs, + ).prev_sample + if guidance_active: + prime_input = torch.cat([provisional, provisional], dim=0) + prime_labels = torch.cat([class_labels_tensor, null_labels], dim=0) + else: + prime_input = provisional + prime_labels = class_labels_tensor + next_timestep_batch = torch.full( + (prime_labels.shape[0],), float(next_timestep), device=device, dtype=model_dtype + ) + next_output = self.transformers( + prime_input.to(dtype=model_dtype), + timestep=next_timestep_batch, + class_labels=prime_labels, + return_dict=True, + ).sample + next_output = self._apply_cfg(next_output, guidance_scale, guidance_active, cfg_channels) + latents = self.scheduler.step_heun( + model_output, next_output, timestep[None], latents, next_timestep[None] + ).prev_sample + else: + latents = self.scheduler.step( + model_output, + timestep[None], + latents, + next_timestep[None], + **extra_step_kwargs, + ).prev_sample + + image = self.decode_latents( + latents.to(dtype=model_dtype), + output_type=output_type, + latent_mean=latent_mean, + latent_std=latent_std, + latent_multiplier=latent_multiplier, + ) + + self.maybe_free_model_hooks() + if not return_dict: + return (image,) + return ImagePipelineOutput(images=image) + + +# Backward-compatible alias used by earlier PAE-diffusers releases. +PAEPipelineOutput = ImagePipelineOutput diff --git a/pae-dinov2-large-d32/scheduler/scheduler_config.json b/pae-dinov2-large-d32/scheduler/scheduler_config.json new file mode 100644 index 0000000000000000000000000000000000000000..75d51d14e68c7500bbb2ddd937dc7669b8d3e27d --- /dev/null +++ b/pae-dinov2-large-d32/scheduler/scheduler_config.json @@ -0,0 +1,7 @@ +{ + "_class_name": "PAEFlowMatchScheduler", + "_diffusers_version": "0.31.0", + "mode": "ode", + "path_type": "linear", + "num_train_timesteps": 1000 +} diff --git a/pae-dinov2-large-d32/scheduler/scheduling_flow_match_pae.py b/pae-dinov2-large-d32/scheduler/scheduling_flow_match_pae.py new file mode 100644 index 0000000000000000000000000000000000000000..e79368596bb250ea5689e1775d653291ab6e55c1 --- /dev/null +++ b/pae-dinov2-large-d32/scheduler/scheduling_flow_match_pae.py @@ -0,0 +1,200 @@ +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. + +from dataclasses import dataclass +from typing import Optional, Tuple + +import numpy as np +import torch + +try: + from diffusers.configuration_utils import ConfigMixin, register_to_config + from diffusers.schedulers.scheduling_utils import SchedulerMixin + from diffusers.utils import BaseOutput +except Exception: # pragma: no cover - importable without an installed diffusers checkout. + class BaseOutput(dict): + def __post_init__(self): + self.update(self.__dict__) + + class ConfigMixin: + config_name = "scheduler_config.json" + + class SchedulerMixin: + pass + + def register_to_config(init): + return init + + +@dataclass +class PAEFlowMatchSchedulerOutput(BaseOutput): + prev_sample: torch.FloatTensor + + +class PAEFlowMatchScheduler(SchedulerMixin, ConfigMixin): + """ + Flow-matching ODE/SDE scheduler used by PAE + LightningDiT pipelines. + + The model predicts velocity with a linear path by default. ODE timesteps run from 0 to 1 + (noise to data), matching LightningDiT transport sampling. + """ + + config_name = "scheduler_config.json" + order = 1 + + @register_to_config + def __init__( + self, + mode: str = "ode", + path_type: str = "linear", + num_train_timesteps: int = 1000, + ): + if mode not in {"ode", "sde"}: + raise ValueError("mode must be either 'ode' or 'sde'.") + if path_type not in {"linear", "cosine"}: + raise ValueError("path_type must be either 'linear' or 'cosine'.") + self.mode = mode + self.path_type = path_type + self.num_train_timesteps = num_train_timesteps + # Native NiT integrates in float64 for better numerical stability. + self.timesteps = torch.from_numpy(np.linspace(0.0, 1.0, num_train_timesteps + 1)).to(dtype=torch.float64) + + @staticmethod + def _apply_timestep_shift(timesteps: torch.Tensor, timestep_shift: float) -> torch.Tensor: + if timestep_shift <= 0: + return timesteps + return timestep_shift * timesteps / (1 + (timestep_shift - 1) * timesteps) + + def set_timesteps( + self, + num_inference_steps: int, + device: Optional[torch.device] = None, + mode: Optional[str] = None, + timestep_shift: float = 0.0, + ): + mode = mode or self.mode + dtype = self.timesteps.dtype + if mode == "sde": + timesteps = torch.linspace(1.0, 0.04, num_inference_steps, dtype=dtype) + timesteps = torch.cat([timesteps, torch.zeros(1, dtype=dtype)]) + elif mode == "ode": + timesteps = torch.linspace(0.0, 1.0, num_inference_steps + 1, dtype=dtype) + timesteps = self._apply_timestep_shift(timesteps, timestep_shift) + else: + raise ValueError("mode must be either 'ode' or 'sde'.") + self.mode = mode + self.timesteps = timesteps.to(device=device) + return self.timesteps + + @staticmethod + def _expand_t_like_sample(timestep: torch.Tensor, sample: torch.Tensor, image_sizes: torch.LongTensor): + dims = [1] * (sample.ndim - 1) + seqlens = image_sizes[:, 0] * image_sizes[:, 1] + if timestep.numel() == 1: + timestep = timestep.repeat(image_sizes.shape[0]) + return torch.cat( + [timestep[i].reshape(1, *dims).repeat(int(seqlens[i]), *dims) for i in range(image_sizes.shape[0])] + ) + + def _get_score_from_velocity( + self, + model_output: torch.Tensor, + sample: torch.Tensor, + timestep: torch.Tensor, + image_sizes: torch.LongTensor, + ): + timestep = self._expand_t_like_sample(timestep, sample, image_sizes) + if self.path_type == "linear": + alpha_t, d_alpha_t = 1 - timestep, torch.ones_like(timestep) * -1 + sigma_t, d_sigma_t = timestep, torch.ones_like(timestep) + elif self.path_type == "cosine": + alpha_t = torch.cos(timestep * np.pi / 2) + sigma_t = torch.sin(timestep * np.pi / 2) + d_alpha_t = -np.pi / 2 * torch.sin(timestep * np.pi / 2) + d_sigma_t = np.pi / 2 * torch.cos(timestep * np.pi / 2) + else: + raise ValueError(f"Unsupported path_type: {self.path_type}") + reverse_alpha_ratio = alpha_t / d_alpha_t + variance = sigma_t**2 - reverse_alpha_ratio * d_sigma_t * sigma_t + return (reverse_alpha_ratio * model_output - sample) / variance + + @staticmethod + def _compute_diffusion(timestep: torch.Tensor): + return 2 * timestep + + @staticmethod + def _promote_dtypes(*tensors: torch.Tensor) -> torch.dtype: + dtype = None + for tensor in tensors: + if tensor.is_floating_point() or tensor.is_complex(): + dtype = tensor.dtype if dtype is None else torch.promote_types(dtype, tensor.dtype) + return dtype if dtype is not None else torch.get_default_dtype() + + def step( + self, + model_output: torch.Tensor, + timestep: torch.Tensor, + sample: torch.Tensor, + next_timestep: torch.Tensor, + image_sizes: Optional[torch.LongTensor] = None, + generator: Optional[torch.Generator] = None, + return_dict: bool = True, + ) -> PAEFlowMatchSchedulerOutput: + sample_dtype = sample.dtype + compute_dtype = torch.float64 + sample = sample.to(dtype=compute_dtype) + model_output = model_output.to(dtype=compute_dtype) + timestep = timestep.to(device=sample.device, dtype=compute_dtype).flatten() + next_timestep = next_timestep.to(device=sample.device, dtype=compute_dtype).flatten() + + if self.mode == "ode": + prev_sample = sample + (next_timestep[0] - timestep[0]) * model_output + else: + if image_sizes is None: + batch = sample.shape[0] + side = int(sample.shape[-1]) + image_sizes = torch.tensor([[side, side]] * batch, device=sample.device, dtype=torch.long) + image_sizes = image_sizes.to(device=sample.device, dtype=torch.long) + diffusion = self._compute_diffusion(timestep[0]) + score = self._get_score_from_velocity(model_output, sample, timestep, image_sizes) + drift = model_output - 0.5 * diffusion * score + dt = next_timestep[0] - timestep[0] + if torch.allclose(next_timestep[0], torch.zeros_like(next_timestep[0])): + prev_sample = sample + drift * dt + else: + if generator is not None: + noise = torch.randn(sample.shape, generator=generator, device=sample.device, dtype=sample.dtype) + else: + noise = torch.randn_like(sample) + prev_sample = sample + drift * dt + torch.sqrt(diffusion) * noise * torch.sqrt(torch.abs(dt)) + + prev_sample = prev_sample.to(sample_dtype) + if not return_dict: + return (prev_sample,) + return PAEFlowMatchSchedulerOutput(prev_sample=prev_sample) + + def step_heun( + self, + model_output: torch.Tensor, + next_model_output: torch.Tensor, + timestep: torch.Tensor, + sample: torch.Tensor, + next_timestep: torch.Tensor, + return_dict: bool = True, + ) -> PAEFlowMatchSchedulerOutput: + if self.mode != "ode": + raise ValueError("Heun correction is only defined for ODE sampling.") + sample_dtype = sample.dtype + compute_dtype = torch.float64 + sample = sample.to(dtype=compute_dtype) + model_output = model_output.to(dtype=compute_dtype) + next_model_output = next_model_output.to(dtype=compute_dtype) + timestep = timestep.to(device=sample.device, dtype=compute_dtype).flatten() + next_timestep = next_timestep.to(device=sample.device, dtype=compute_dtype).flatten() + prev_sample = sample + (next_timestep[0] - timestep[0]) * (0.5 * model_output + 0.5 * next_model_output) + prev_sample = prev_sample.to(sample_dtype) + if not return_dict: + return (prev_sample,) + return PAEFlowMatchSchedulerOutput(prev_sample=prev_sample) diff --git a/pae-dinov2-large-d32/transformers/__pycache__/transformer_lightning_dit.cpython-311.pyc b/pae-dinov2-large-d32/transformers/__pycache__/transformer_lightning_dit.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffb83515c3a8e3f8edd17f78d0f4746d621d5707 Binary files /dev/null and b/pae-dinov2-large-d32/transformers/__pycache__/transformer_lightning_dit.cpython-311.pyc differ diff --git a/pae-dinov2-large-d32/transformers/config.json b/pae-dinov2-large-d32/transformers/config.json new file mode 100644 index 0000000000000000000000000000000000000000..d5ddc59564b5939f9c622a5c19dc93ed567ac544 --- /dev/null +++ b/pae-dinov2-large-d32/transformers/config.json @@ -0,0 +1,15 @@ +{ + "_class_name": "LightningDiT2DModel", + "depth": 28, + "hidden_size": 1152, + "in_channels": 32, + "input_size": 16, + "num_classes": 1000, + "num_heads": 16, + "patch_size": 1, + "use_qknorm": true, + "use_rmsnorm": true, + "use_rope": true, + "use_swiglu": true, + "wo_shift": false +} diff --git a/pae-dinov2-large-d32/transformers/diffusion_pytorch_model.safetensors b/pae-dinov2-large-d32/transformers/diffusion_pytorch_model.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..a6ae1c9166be3702522bc6a77640c929c7836e0d --- /dev/null +++ b/pae-dinov2-large-d32/transformers/diffusion_pytorch_model.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef0c13279e80947042b013465bfb7ccac0328c5c30d4eb5326b548d32e47892e +size 2701230752 diff --git a/pae-dinov2-large-d32/transformers/transformer_lightning_dit.py b/pae-dinov2-large-d32/transformers/transformer_lightning_dit.py new file mode 100644 index 0000000000000000000000000000000000000000..80d061481bca0a538950bfd25b531e8bf1c05d61 --- /dev/null +++ b/pae-dinov2-large-d32/transformers/transformer_lightning_dit.py @@ -0,0 +1,794 @@ +from __future__ import annotations + +import torch +import torch.nn.functional as F +from torch import nn + + +class RMSNorm(torch.nn.Module): + def __init__(self, dim: int, eps: float = 1e-6): + super().__init__() + self.eps = eps + self.weight = nn.Parameter(torch.ones(dim)) + + def _norm(self, x: torch.Tensor) -> torch.Tensor: + return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + output = self._norm(x.float()).type_as(x) + return output * self.weight + +from math import pi + +import torch +from torch import nn + +from einops import rearrange, repeat + + + +def broadcat(tensors, dim = -1): + num_tensors = len(tensors) + shape_lens = set(list(map(lambda t: len(t.shape), tensors))) + assert len(shape_lens) == 1, 'tensors must all have the same number of dimensions' + shape_len = list(shape_lens)[0] + dim = (dim + shape_len) if dim < 0 else dim + dims = list(zip(*map(lambda t: list(t.shape), tensors))) + expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim] + assert all([*map(lambda t: len(set(t[1])) <= 2, expandable_dims)]), 'invalid dimensions for broadcastable concatentation' + max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims)) + expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims)) + expanded_dims.insert(dim, (dim, dims[dim])) + expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims))) + tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes))) + return torch.cat(tensors, dim = dim) + + + +def rotate_half(x): + x = rearrange(x, '... (d r) -> ... d r', r = 2) + x1, x2 = x.unbind(dim = -1) + x = torch.stack((-x2, x1), dim = -1) + return rearrange(x, '... d r -> ... (d r)') + + + +class VisionRotaryEmbedding(nn.Module): + def __init__( + self, + dim, + pt_seq_len, + ft_seq_len=None, + custom_freqs = None, + freqs_for = 'lang', + theta = 10000, + max_freq = 10, + num_freqs = 1, + ): + super().__init__() + if custom_freqs: + freqs = custom_freqs + elif freqs_for == 'lang': + freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim)) + elif freqs_for == 'pixel': + freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi + elif freqs_for == 'constant': + freqs = torch.ones(num_freqs).float() + else: + raise ValueError(f'unknown modality {freqs_for}') + + if ft_seq_len is None: ft_seq_len = pt_seq_len + t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len + + freqs_h = torch.einsum('..., f -> ... f', t, freqs) + freqs_h = repeat(freqs_h, '... n -> ... (n r)', r = 2) + + freqs_w = torch.einsum('..., f -> ... f', t, freqs) + freqs_w = repeat(freqs_w, '... n -> ... (n r)', r = 2) + + freqs = broadcat((freqs_h[:, None, :], freqs_w[None, :, :]), dim = -1) + + self.register_buffer("freqs_cos", freqs.cos()) + self.register_buffer("freqs_sin", freqs.sin()) + + # print('======== shape of rope freq', self.freqs_cos.shape, '========') + + def forward(self, t, start_index = 0): + rot_dim = self.freqs_cos.shape[-1] + end_index = start_index + rot_dim + assert rot_dim <= t.shape[-1], f'feature dimension {t.shape[-1]} is not of sufficient size to rotate in all the positions {rot_dim}' + t_left, t, t_right = t[..., :start_index], t[..., start_index:end_index], t[..., end_index:] + t = (t * self.freqs_cos) + (rotate_half(t) * self.freqs_sin) + return torch.cat((t_left, t, t_right), dim = -1) + + + +class VisionRotaryEmbeddingFast(nn.Module): + def __init__( + self, + dim, + pt_seq_len=16, + ft_seq_len=None, + custom_freqs = None, + freqs_for = 'lang', + theta = 10000, + max_freq = 10, + num_freqs = 1, + ): + super().__init__() + if custom_freqs: + freqs = custom_freqs + elif freqs_for == 'lang': + freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim)) + elif freqs_for == 'pixel': + freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi + elif freqs_for == 'constant': + freqs = torch.ones(num_freqs).float() + else: + raise ValueError(f'unknown modality {freqs_for}') + + if ft_seq_len is None: ft_seq_len = pt_seq_len + t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len + + freqs = torch.einsum('..., f -> ... f', t, freqs) + freqs = repeat(freqs, '... n -> ... (n r)', r = 2) + freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim = -1) + + freqs_cos = freqs.cos().view(-1, freqs.shape[-1]) + freqs_sin = freqs.sin().view(-1, freqs.shape[-1]) + + self.register_buffer("freqs_cos", freqs_cos) + self.register_buffer("freqs_sin", freqs_sin) + + # print('======== shape of rope freq', self.freqs_cos.shape, '========') + + def forward(self, t): return t * self.freqs_cos + rotate_half(t) * self.freqs_sin + +import os +import torch +from typing import Callable, Optional +import warnings + +from torch import Tensor, nn +import torch.nn.functional as F + + +class SwiGLUFFN(nn.Module): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = None, + drop: float = 0.0, + bias: bool = True, + ) -> None: + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias) + self.w3 = nn.Linear(hidden_features, out_features, bias=bias) + def forward(self, x: Tensor) -> Tensor: + x12 = self.w12(x) + x1, x2 = x12.chunk(2, dim=-1) + hidden = F.silu(x1) * x2 + return self.w3(hidden) + + +XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None +try: + if XFORMERS_ENABLED: + from xformers.ops import SwiGLU + + XFORMERS_AVAILABLE = True + # warnings.warn("xFormers is available (SwiGLU)") + else: + # warnings.warn("xFormers is disabled (SwiGLU)") + raise ImportError +except ImportError: + SwiGLU = SwiGLUFFN + XFORMERS_AVAILABLE = False + + # warnings.warn("xFormers is not available (SwiGLU)") + + +class SwiGLUFFNFused(SwiGLU): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = None, + drop: float = 0.0, + bias: bool = True, + ) -> None: + out_features = out_features or in_features + hidden_features = hidden_features or in_features + hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8 + super().__init__( + in_features=in_features, + hidden_features=hidden_features, + out_features=out_features, + bias=bias, + ) + +from dataclasses import dataclass +from typing import Optional, Tuple, Union + +import torch + +try: + from diffusers.configuration_utils import ConfigMixin, register_to_config + from diffusers.models.modeling_utils import ModelMixin + from diffusers.utils import BaseOutput +except Exception: # pragma: no cover + class BaseOutput(dict): + def __post_init__(self): + self.update(self.__dict__) + + class ConfigMixin: + config_name = "config.json" + + class ModelMixin(torch.nn.Module): + pass + + def register_to_config(init): + return init + + +@dataclass +class LightningDiT2DModelOutput(BaseOutput): + sample: torch.FloatTensor + + +import os +import math +import numpy as np + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.utils.checkpoint import checkpoint + +from timm.models.vision_transformer import PatchEmbed, Mlp +def modulate(x, shift, scale): + if shift is None: + return x * (1 + scale.unsqueeze(1)) + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) + +class Attention(nn.Module): + """ + Attention module of LightningDiT. + """ + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = False, + qk_norm: bool = False, + attn_drop: float = 0., + proj_drop: float = 0., + norm_layer: nn.Module = nn.LayerNorm, + fused_attn: bool = True, + use_rmsnorm: bool = False, + ) -> None: + super().__init__() + assert dim % num_heads == 0, 'dim should be divisible by num_heads' + + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.scale = self.head_dim ** -0.5 + self.fused_attn = fused_attn + + if use_rmsnorm: + norm_layer = RMSNorm + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + def forward(self, x: torch.Tensor, rope=None) -> torch.Tensor: + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) + q, k, v = qkv.unbind(0) + q, k = self.q_norm(q), self.k_norm(k) + + if rope is not None: + q = rope(q) + k = rope(k) + + if self.fused_attn: + x = F.scaled_dot_product_attention( + q, k, v, + dropout_p=self.attn_drop.p if self.training else 0., + ) + else: + q = q * self.scale + attn = q @ k.transpose(-2, -1) + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + x = attn @ v + + x = x.transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class TimestepEmbedder(nn.Module): + """ + Embeds scalar timesteps into vector representations. + Same as DiT. + """ + def __init__(self, hidden_size: int, frequency_embedding_size: int = 256) -> None: + super().__init__() + self.frequency_embedding_size = frequency_embedding_size + self.mlp = nn.Sequential( + nn.Linear(frequency_embedding_size, hidden_size, bias=True), + nn.SiLU(), + nn.Linear(hidden_size, hidden_size, bias=True), + ) + + @staticmethod + def timestep_embedding(t: torch.Tensor, dim: int, max_period: int = 10000) -> torch.Tensor: + """ + Create sinusoidal timestep embeddings. + Args: + t: A 1-D Tensor of N indices, one per batch element. These may be fractional. + dim: The dimension of the output. + max_period: Controls the minimum frequency of the embeddings. + Returns: + An (N, D) Tensor of positional embeddings. + """ + # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py + half = dim // 2 + freqs = torch.exp( + -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half + ).to(device=t.device) + + args = t[:, 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) + + return embedding + def forward(self, t: torch.Tensor) -> torch.Tensor: + t_freq = self.timestep_embedding(t, self.frequency_embedding_size) + t_emb = self.mlp(t_freq) + return t_emb + + +class LabelEmbedder(nn.Module): + """ + Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance. + Same as DiT. + """ + def __init__(self, num_classes, hidden_size, dropout_prob): + super().__init__() + use_cfg_embedding = dropout_prob > 0 + self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size) + self.num_classes = num_classes + self.dropout_prob = dropout_prob + + def token_drop(self, labels, force_drop_ids=None): + """ + Drops labels to enable classifier-free guidance. + """ + if force_drop_ids is None: + drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob + else: + drop_ids = force_drop_ids == 1 + labels = torch.where(drop_ids, self.num_classes, labels) + return labels + def forward(self, labels, train, force_drop_ids=None): + use_dropout = self.dropout_prob > 0 + if (train and use_dropout) or (force_drop_ids is not None): + labels = self.token_drop(labels, force_drop_ids) + embeddings = self.embedding_table(labels) + return embeddings + +class LightningDiTBlock(nn.Module): + """ + Lightning DiT Block. We add features including: + - ROPE + - QKNorm + - RMSNorm + - SwiGLU + - No shift AdaLN. + Not all of them are used in the final model, please refer to the paper for more details. + """ + def __init__( + self, + hidden_size, + num_heads, + mlp_ratio=4.0, + use_qknorm=False, + use_swiglu=False, + use_rmsnorm=False, + wo_shift=False, + **block_kwargs + ): + super().__init__() + + # Initialize normalization layers + if not use_rmsnorm: + self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + else: + self.norm1 = RMSNorm(hidden_size) + self.norm2 = RMSNorm(hidden_size) + + # Initialize attention layer + self.attn = Attention( + hidden_size, + num_heads=num_heads, + qkv_bias=True, + qk_norm=use_qknorm, + use_rmsnorm=use_rmsnorm, + **block_kwargs + ) + + # Initialize MLP layer + mlp_hidden_dim = int(hidden_size * mlp_ratio) + approx_gelu = lambda: nn.GELU(approximate="tanh") + if use_swiglu: + # here we did not use SwiGLU from xformers because it is not compatible with torch.compile for now. + self.mlp = SwiGLUFFN(hidden_size, int(2/3 * mlp_hidden_dim)) + else: + self.mlp = Mlp( + in_features=hidden_size, + hidden_features=mlp_hidden_dim, + act_layer=approx_gelu, + drop=0 + ) + + # Initialize AdaLN modulation + if wo_shift: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(hidden_size, 4 * hidden_size, bias=True) + ) + else: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(hidden_size, 6 * hidden_size, bias=True) + ) + self.wo_shift = wo_shift + def forward(self, x, c, feat_rope=None): + if self.wo_shift: + scale_msa, gate_msa, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(4, dim=1) + shift_msa = None + shift_mlp = None + else: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=1) + + x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa), rope=feat_rope) + x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp)) + return x + +class FinalLayer(nn.Module): + """ + The final layer of LightningDiT. + """ + def __init__(self, hidden_size, patch_size, out_channels, use_rmsnorm=False): + super().__init__() + if not use_rmsnorm: + self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + else: + self.norm_final = RMSNorm(hidden_size) + self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True) + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(hidden_size, 2 * hidden_size, bias=True) + ) + def forward(self, x, c): + shift, scale = self.adaLN_modulation(c).chunk(2, dim=1) + x = modulate(self.norm_final(x), shift, scale) + x = self.linear(x) + return x + + +class LightningDiT2DModel(ModelMixin, ConfigMixin): + """ + Diffusion model with a Transformer backbone. + """ + @register_to_config + def __init__( + self, + input_size: int = 32, + patch_size=2, + in_channels=32, + hidden_size=1152, + depth=28, + num_heads=16, + mlp_ratio=4.0, + class_dropout_prob=0.1, + num_classes=1000, + learn_sigma=False, + use_qknorm=False, + use_swiglu=False, + use_rope=False, + use_rmsnorm=False, + wo_shift=False, + use_checkpoint=False, + use_abs_pos=True, + ): + super().__init__() + self.use_abs_pos = use_abs_pos + self.learn_sigma = learn_sigma + self.in_channels = in_channels + self.out_channels = in_channels if not learn_sigma else in_channels * 2 + self.patch_size = patch_size + self.num_heads = num_heads + self.use_rope = use_rope + self.use_rmsnorm = use_rmsnorm + self.depth = depth + self.hidden_size = hidden_size + self.use_checkpoint = use_checkpoint + self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size, bias=True) + self.t_embedder = TimestepEmbedder(hidden_size) + self.y_embedder = LabelEmbedder(num_classes, hidden_size, class_dropout_prob) + num_patches = self.x_embedder.num_patches + # Will use fixed sin-cos embedding: + self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False) + + if not self.use_abs_pos and not self.use_rope: + import warnings + warnings.warn("Warning: Both Absolute Position Embedding and RoPE are disabled. " + "The model will be permutation-invariant (orderless)!") + + # use rotary position encoding, borrow from EVA + if self.use_rope: + half_head_dim = hidden_size // num_heads // 2 + hw_seq_len = input_size // patch_size + self.feat_rope = VisionRotaryEmbeddingFast( + dim=half_head_dim, + pt_seq_len=hw_seq_len, + ) + else: + self.feat_rope = None + + self.blocks = nn.ModuleList([ + LightningDiTBlock(hidden_size, + num_heads, + mlp_ratio=mlp_ratio, + use_qknorm=use_qknorm, + use_swiglu=use_swiglu, + use_rmsnorm=use_rmsnorm, + wo_shift=wo_shift, + ) for _ in range(depth) + ]) + self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels, use_rmsnorm=use_rmsnorm) + self.initialize_weights() + if hasattr(self, "register_to_config"): + self.register_to_config( + input_size=input_size, + patch_size=patch_size, + in_channels=in_channels, + hidden_size=hidden_size, + depth=depth, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + class_dropout_prob=class_dropout_prob, + num_classes=num_classes, + learn_sigma=learn_sigma, + use_qknorm=use_qknorm, + use_swiglu=use_swiglu, + use_rope=use_rope, + use_rmsnorm=use_rmsnorm, + wo_shift=wo_shift, + use_checkpoint=use_checkpoint, + use_abs_pos=use_abs_pos, + ) + + def initialize_weights(self): + # Initialize transformer layers: + def _basic_init(module): + if isinstance(module, nn.Linear): + torch.nn.init.xavier_uniform_(module.weight) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + self.apply(_basic_init) + + + if self.use_abs_pos: + pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5)) + self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0)) + else: + nn.init.constant_(self.pos_embed, 0) + + # Initialize patch_embed like nn.Linear (instead of nn.Conv2d): + w = self.x_embedder.proj.weight.data + nn.init.xavier_uniform_(w.view([w.shape[0], -1])) + nn.init.constant_(self.x_embedder.proj.bias, 0) + + # Initialize label embedding table: + nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02) + + # Initialize timestep embedding MLP: + nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02) + nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02) + + # Zero-out adaLN modulation layers in LightningDiT blocks: + for block in self.blocks: + nn.init.constant_(block.adaLN_modulation[-1].weight, 0) + nn.init.constant_(block.adaLN_modulation[-1].bias, 0) + + # Zero-out output layers: + nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0) + nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0) + nn.init.constant_(self.final_layer.linear.weight, 0) + nn.init.constant_(self.final_layer.linear.bias, 0) + + def unpatchify(self, x): + """ + x: (N, T, patch_size**2 * C) + imgs: (N, H, W, C) + """ + c = self.out_channels + p = self.x_embedder.patch_size[0] + h = w = int(x.shape[1] ** 0.5) + assert h * w == x.shape[1] + + x = x.reshape(shape=(x.shape[0], h, w, p, p, c)) + x = torch.einsum('nhwpqc->nchpwq', x) + imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p)) + return imgs + + def forward( + self, + hidden_states: torch.Tensor, + timestep: Optional[torch.LongTensor] = None, + class_labels: Optional[torch.LongTensor] = None, + return_dict: bool = True, + ): + x = hidden_states + t = timestep + y = class_labels + """ + Forward pass of LightningDiT. + x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images) + t: (N,) tensor of diffusion timesteps + y: (N,) tensor of class labels + use_checkpoint: boolean to toggle checkpointing + """ + + use_checkpoint = self.use_checkpoint + + x = self.x_embedder(x) + if self.use_abs_pos: + x = x + self.pos_embed + t = self.t_embedder(t) # (N, D) + y = self.y_embedder(y, self.training) # (N, D) + c = t + y # (N, D) + + for block in self.blocks: + if use_checkpoint: + x = checkpoint(block, x, c, self.feat_rope, use_reentrant=True) + else: + x = block(x, c, self.feat_rope) + + x = self.final_layer(x, c) # (N, T, patch_size ** 2 * out_channels) + x = self.unpatchify(x) # (N, out_channels, H, W) + + if self.learn_sigma: + x, _ = x.chunk(2, dim=1) + if not return_dict: + return (x,) + return LightningDiT2DModelOutput(sample=x) + + def forward_with_cfg(self, x, t, y, cfg_scale, cfg_interval=None, cfg_interval_start=None): + """ + Forward pass of LightningDiT, but also batches the unconditional forward pass for classifier-free guidance. + """ + # https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb + combined = torch.cat([x, x], dim=0) + model_out = self.forward(combined, t, y, return_dict=False)[0] + # For exact reproducibility reasons, we apply classifier-free guidance on only + # three channels by default. The standard approach to cfg applies it to all channels. + # This can be done by uncommenting the following line and commenting-out the line following that. + eps, rest = model_out[:, :self.in_channels], model_out[:, self.in_channels:] + # eps, rest = model_out[:, :3], model_out[:, 3:] + cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0) + half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps) + + if cfg_interval is True: + timestep = t[0] + if timestep < cfg_interval_start: + half_eps = cond_eps + + eps = torch.cat([half_eps, half_eps], dim=0) + return torch.cat([eps, rest], dim=1) + +def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0): + """ + grid_size: int of the grid height and width + return: + pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token) + """ + grid_h = np.arange(grid_size, dtype=np.float32) + grid_w = np.arange(grid_size, dtype=np.float32) + grid = np.meshgrid(grid_w, grid_h) # here w goes first + grid = np.stack(grid, axis=0) + + grid = grid.reshape([2, 1, grid_size, grid_size]) + pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) + if cls_token and extra_tokens > 0: + pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0) + return pos_embed + + +def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): + assert embed_dim % 2 == 0 + + # use half of dimensions to encode grid_h + emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) + emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2) + + emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D) + return emb + + +def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): + """ + embed_dim: output dimension for each position + pos: a list of positions to be encoded: size (M,) + out: (M, D) + """ + assert embed_dim % 2 == 0 + omega = np.arange(embed_dim // 2, dtype=np.float64) + omega /= embed_dim / 2. + omega = 1. / 10000**omega # (D/2,) + + pos = pos.reshape(-1) # (M,) + out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product + + emb_sin = np.sin(out) # (M, D/2) + emb_cos = np.cos(out) # (M, D/2) + + emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) + return emb + + +################################################################################# +# LightningDiT Configs # +################################################################################# + +def _lightning_dit_XL_1(**kwargs): + return LightningDiT2DModel(depth=28, hidden_size=1152, patch_size=1, num_heads=16, **kwargs) + +def _lightning_dit_XL_2(**kwargs): + return LightningDiT2DModel(depth=28, hidden_size=1152, patch_size=2, num_heads=16, **kwargs) + +def _lightning_dit_L_2(**kwargs): + return LightningDiT2DModel(depth=24, hidden_size=1024, patch_size=2, num_heads=16, **kwargs) + +def _lightning_dit_B_1(**kwargs): + return LightningDiT2DModel(depth=12, hidden_size=768, patch_size=1, num_heads=12, **kwargs) + +def _lightning_dit_B_2(**kwargs): + return LightningDiT2DModel(depth=12, hidden_size=768, patch_size=2, num_heads=12, **kwargs) + +def _lightning_dit_1p0B_1(**kwargs): + return LightningDiT2DModel(depth=24, hidden_size=1536, patch_size=1, num_heads=24, **kwargs) + +def _lightning_dit_1p0B_2(**kwargs): + return LightningDiT2DModel(depth=24, hidden_size=1536, patch_size=2, num_heads=24, **kwargs) + +def _lightning_dit_1p6B_1(**kwargs): + return LightningDiT2DModel(depth=28, hidden_size=1792, patch_size=1, num_heads=28, **kwargs) + +def _lightning_dit_1p6B_2(**kwargs): + return LightningDiT2DModel(depth=28, hidden_size=1792, patch_size=2, num_heads=28, **kwargs) + +LIGHTNING_DIT_PRESETS = { + 'LightningDiT-B/1': _lightning_dit_B_1, 'LightningDiT-B/2': _lightning_dit_B_2, + 'LightningDiT-L/2': _lightning_dit_L_2, + 'LightningDiT-XL/1': _lightning_dit_XL_1, 'LightningDiT-XL/2': _lightning_dit_XL_2, + 'LightningDiT-1p0B/1': _lightning_dit_1p0B_1, 'LightningDiT-1p0B/2': _lightning_dit_1p0B_2, + 'LightningDiT-1p6B/1': _lightning_dit_1p6B_1, 'LightningDiT-1p6B/2': _lightning_dit_1p6B_2, +} diff --git a/pae-dinov3-large-d32/decoder/config.json b/pae-dinov3-large-d32/decoder/config.json new file mode 100644 index 0000000000000000000000000000000000000000..b9335c9094b830099b37415a529a59a335e5a895 --- /dev/null +++ b/pae-dinov3-large-d32/decoder/config.json @@ -0,0 +1,79 @@ +{ + "_class_name": "PAEDecoder", + "decoder_patch_size": 16, + "encoder_config_path": "facebook/dinov3-vitl16-pretrain-lvd1689m", + "encoder_hidden_size": 1024, + "encoder_input_size": 256, + "encoder_num_heads": 16, + "encoder_patch_size": 16, + "latent_dim": 32, + "latent_mean": [ + -1.140625, + 0.03759765625, + -0.275390625, + -0.34375, + -0.265625, + 0.015869140625, + 0.1884765625, + 0.0087890625, + 1.625, + -0.005279541015625, + 0.34765625, + -1.03125, + 0.47265625, + -1.4375, + 0.00604248046875, + 0.484375, + -0.1328125, + 0.5234375, + -0.11865234375, + -0.37109375, + 0.474609375, + -1.5390625, + 0.7734375, + -0.087890625, + 0.039794921875, + 0.734375, + -0.030517578125, + -0.158203125, + -3.078125, + 0.0869140625, + 0.138671875, + -0.74609375 + ], + "latent_multiplier": 1.0, + "latent_std": [ + 0.5390625, + 0.53515625, + 0.62109375, + 0.5546875, + 0.53125, + 0.44140625, + 0.53125, + 0.53125, + 0.55078125, + 0.58203125, + 0.74609375, + 0.48046875, + 0.49609375, + 0.5390625, + 0.59765625, + 0.5703125, + 0.55859375, + 0.66015625, + 0.55859375, + 0.50390625, + 0.55078125, + 0.490234375, + 0.7109375, + 0.55859375, + 0.53515625, + 0.486328125, + 0.5234375, + 0.515625, + 0.466796875, + 0.5390625, + 0.59375, + 0.51171875 + ] +} diff --git a/pae-dinov3-large-d32/decoder/decoder_pae.py b/pae-dinov3-large-d32/decoder/decoder_pae.py new file mode 100644 index 0000000000000000000000000000000000000000..4592fb0fd62b7324c7d6398d7e50f4229d58a3b3 --- /dev/null +++ b/pae-dinov3-large-d32/decoder/decoder_pae.py @@ -0,0 +1,1105 @@ +from __future__ import annotations + +from transformers.configuration_utils import PretrainedConfig +from transformers.utils import ( + ModelOutput, +) +from transformers.activations import ACT2FN +class ViTMAEConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a [`ViTMAEModel`]. It is used to instantiate an ViT + MAE model according to the specified arguments, defining the model architecture. Instantiating a configuration with + the defaults will yield a similar configuration to that of the ViT + [facebook/vit-mae-base](https://huggingface.co/facebook/vit-mae-base) architecture. + + Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the + documentation from [`PretrainedConfig`] for more information. + + + Args: + hidden_size (`int`, *optional*, defaults to 768): + Dimensionality of the encoder layers and the pooler layer. + num_hidden_layers (`int`, *optional*, defaults to 12): + Number of hidden layers in the Transformer encoder. + num_attention_heads (`int`, *optional*, defaults to 12): + Number of attention heads for each attention layer in the Transformer encoder. + intermediate_size (`int`, *optional*, defaults to 3072): + Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. + hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`): + The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, + `"relu"`, `"selu"` and `"gelu_new"` are supported. + hidden_dropout_prob (`float`, *optional*, defaults to 0.0): + The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler. + attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0): + The dropout ratio for the attention probabilities. + initializer_range (`float`, *optional*, defaults to 0.02): + The standard deviation of the truncated_normal_initializer for initializing all weight matrices. + layer_norm_eps (`float`, *optional*, defaults to 1e-12): + The epsilon used by the layer normalization layers. + image_size (`int`, *optional*, defaults to 224): + The size (resolution) of each image. + patch_size (`int`, *optional*, defaults to 16): + The size (resolution) of each patch. + num_channels (`int`, *optional*, defaults to 3): + The number of input channels. + qkv_bias (`bool`, *optional*, defaults to `True`): + Whether to add a bias to the queries, keys and values. + decoder_num_attention_heads (`int`, *optional*, defaults to 16): + Number of attention heads for each attention layer in the decoder. + decoder_hidden_size (`int`, *optional*, defaults to 512): + Dimensionality of the decoder. + decoder_num_hidden_layers (`int`, *optional*, defaults to 8): + Number of hidden layers in the decoder. + decoder_intermediate_size (`int`, *optional*, defaults to 2048): + Dimensionality of the "intermediate" (i.e., feed-forward) layer in the decoder. + mask_ratio (`float`, *optional*, defaults to 0.75): + The ratio of the number of masked tokens in the input sequence. + norm_pix_loss (`bool`, *optional*, defaults to `False`): + Whether or not to train with normalized pixels (see Table 3 in the paper). Using normalized pixels improved + representation quality in the experiments of the authors. + + Example: + + ```python + >>> from transformers import ViTMAEConfig, ViTMAEModel + + >>> # Initializing a ViT MAE vit-mae-base style configuration + >>> configuration = ViTMAEConfig() + + >>> # Initializing a model (with random weights) from the vit-mae-base style configuration + >>> model = ViTMAEModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "vit_mae" + + def __init__( + self, + hidden_size=768, + num_hidden_layers=12, + num_attention_heads=12, + intermediate_size=3072, + hidden_act="gelu", + hidden_dropout_prob=0.0, + attention_probs_dropout_prob=0.0, + initializer_range=0.02, + layer_norm_eps=1e-12, + image_size=224, + patch_size=16, + num_channels=3, + qkv_bias=True, + decoder_num_attention_heads=16, + decoder_hidden_size=512, + decoder_num_hidden_layers=8, + decoder_intermediate_size=2048, + mask_ratio=0.75, + norm_pix_loss=False, + **kwargs, + ): + super().__init__(**kwargs) + + self.hidden_size = hidden_size + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.intermediate_size = intermediate_size + self.hidden_act = hidden_act + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.initializer_range = initializer_range + self.layer_norm_eps = layer_norm_eps + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.qkv_bias = qkv_bias + self.decoder_num_attention_heads = decoder_num_attention_heads + self.decoder_hidden_size = decoder_hidden_size + self.decoder_num_hidden_layers = decoder_num_hidden_layers + self.decoder_intermediate_size = decoder_intermediate_size + self.mask_ratio = mask_ratio + self.norm_pix_loss = norm_pix_loss + +# coding=utf-8 +# Copyright 2022 Facebook AI and The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""PyTorch ViT MAE (masked autoencoder) model.""" + +import collections.abc +import math +from copy import deepcopy +from dataclasses import dataclass +from typing import Optional, Set, Tuple, Union + +import numpy as np +import torch +from torch import nn +# correct the above import to the following +from transformers.modeling_outputs import BaseModelOutput + +try: + from flash_attn import flash_attn_func + HAS_FLASH_ATTN = True # if set to False, FlashAttention is unavailable +except: + print('FlashAttention is not installed.') + HAS_FLASH_ATTN = False + + +@dataclass +class ViTMAEModelOutput(ModelOutput): + """ + Class for ViTMAEModel's outputs, with potential hidden states and attentions. + + Args: + last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): + Sequence of hidden-states at the output of the last layer of the model. + mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): + Tensor indicating which patches are masked (1) and which are not (0). + ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Tensor containing the original index of the (shuffled) masked patches. + hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): + Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of + shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer + plus the initial embedding outputs. + attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): + Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, + sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in + the self-attention heads. + """ + + last_hidden_state: torch.FloatTensor = None + mask: torch.LongTensor = None + ids_restore: torch.LongTensor = None + hidden_states: Optional[Tuple[torch.FloatTensor]] = None + attentions: Optional[Tuple[torch.FloatTensor]] = None + + +@dataclass +class ViTMAEDecoderOutput(ModelOutput): + """ + Class for ViTMAEDecoder's outputs, with potential hidden states and attentions. + + Args: + logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`): + Pixel reconstruction logits. + hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): + Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of + shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer + plus the initial embedding outputs. + attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): + Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, + sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in + the self-attention heads. + """ + + logits: torch.FloatTensor = None + hidden_states: Optional[Tuple[torch.FloatTensor]] = None + attentions: Optional[Tuple[torch.FloatTensor]] = None + + +@dataclass +class ViTMAEForPreTrainingOutput(ModelOutput): + """ + Class for ViTMAEForPreTraining's outputs, with potential hidden states and attentions. + + Args: + loss (`torch.FloatTensor` of shape `(1,)`): + Pixel reconstruction loss. + logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`): + Pixel reconstruction logits. + mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): + Tensor indicating which patches are masked (1) and which are not (0). + ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Tensor containing the original index of the (shuffled) masked patches. + hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): + Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of + shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer + plus the initial embedding outputs. + attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): + Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, + sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in + the self-attention heads. + """ + + loss: Optional[torch.FloatTensor] = None + logits: torch.FloatTensor = None + mask: torch.LongTensor = None + ids_restore: torch.LongTensor = None + hidden_states: Optional[Tuple[torch.FloatTensor]] = None + attentions: Optional[Tuple[torch.FloatTensor]] = None + + +def get_2d_sincos_pos_embed(embed_dim, grid_size, add_cls_token=False): + """ + Create 2D sin/cos positional embeddings. + + Args: + embed_dim (`int`): + Embedding dimension. + grid_size (`int`): + The grid height and width. + add_cls_token (`bool`, *optional*, defaults to `False`): + Whether or not to add a classification (CLS) token. + + Returns: + (`torch.FloatTensor` of shape (grid_size*grid_size, embed_dim) or (1+grid_size*grid_size, embed_dim): the + position embeddings (with or without classification token) + """ + grid_h = np.arange(grid_size, dtype=np.float32) + grid_w = np.arange(grid_size, dtype=np.float32) + grid = np.meshgrid(grid_w, grid_h) # here w goes first + grid = np.stack(grid, axis=0) + + grid = grid.reshape([2, 1, grid_size, grid_size]) + pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) + if add_cls_token: + pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0) + return pos_embed + + +def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): + if embed_dim % 2 != 0: + raise ValueError("embed_dim must be even") + + # use half of dimensions to encode grid_h + emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) + emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2) + + emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D) + return emb + + +def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): + """ + embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D) + """ + if embed_dim % 2 != 0: + raise ValueError("embed_dim must be even") + + omega = np.arange(embed_dim // 2, dtype=float) + omega /= embed_dim / 2.0 + omega = 1.0 / 10000**omega # (D/2,) + + pos = pos.reshape(-1) # (M,) + out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product + + emb_sin = np.sin(out) # (M, D/2) + emb_cos = np.cos(out) # (M, D/2) + + emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) + return emb + + +class ViTMAEEmbeddings(nn.Module): + """ + Construct the CLS token, position and patch embeddings. + + """ + + def __init__(self, config): + super().__init__() + + self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) + self.patch_embeddings = ViTMAEPatchEmbeddings(config) + self.num_patches = self.patch_embeddings.num_patches + # fixed sin-cos embedding + self.position_embeddings = nn.Parameter( + torch.zeros(1, self.num_patches + 1, config.hidden_size), requires_grad=False + ) + self.config = config + self.initialize_weights() + + def initialize_weights(self): + # initialize (and freeze) position embeddings by sin-cos embedding + pos_embed = get_2d_sincos_pos_embed( + self.position_embeddings.shape[-1], int(self.patch_embeddings.num_patches**0.5), add_cls_token=True + ) + self.position_embeddings.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0)) + + # initialize patch_embeddings like nn.Linear (instead of nn.Conv2d) + w = self.patch_embeddings.projection.weight.data + torch.nn.init.xavier_uniform_(w.view([w.shape[0], -1])) + + # timm's trunc_normal_(std=.02) is effectively normal_(std=0.02) as cutoff is too big (2.) + torch.nn.init.normal_(self.cls_token, std=self.config.initializer_range) + + def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor: + """ + This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher + resolution images. + + Source: + https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174 + """ + num_patches = embeddings.shape[1] - 1 + num_positions = self.position_embeddings.shape[1] - 1 + + if num_patches == num_positions and height == width: + return self.position_embeddings + + class_pos_embed = self.position_embeddings[:, 0, :] + patch_pos_embed = self.position_embeddings[:, 1:, :] + dim = embeddings.shape[-1] + h0 = height // self.config.patch_size + w0 = width // self.config.patch_size + # we add a small number to avoid floating point error in the interpolation + # see discussion at https://github.com/facebookresearch/dino/issues/8 + h0, w0 = h0 + 0.1, w0 + 0.1 + patch_pos_embed = patch_pos_embed.reshape(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim) + patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2) + patch_pos_embed = nn.functional.interpolate( + patch_pos_embed, + scale_factor=(h0 / math.sqrt(num_positions), w0 / math.sqrt(num_positions)), + mode="bicubic", + align_corners=False, + ) + if int(h0) != patch_pos_embed.shape[-2] or int(w0) != patch_pos_embed.shape[-1]: + raise ValueError("Width or height does not match with the interpolated position embeddings") + patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) + return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1) + + def random_masking(self, sequence, noise=None): + """ + Perform per-sample random masking by per-sample shuffling. Per-sample shuffling is done by argsort random + noise. + + Args: + sequence (`torch.LongTensor` of shape `(batch_size, sequence_length, dim)`) + noise (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*) which is + mainly used for testing purposes to control randomness and maintain the reproducibility + """ + batch_size, seq_length, dim = sequence.shape + len_keep = int(seq_length * (1 - self.config.mask_ratio)) + + if noise is None: + noise = torch.rand(batch_size, seq_length, device=sequence.device) # noise in [0, 1] + + # sort noise for each sample + ids_shuffle = torch.argsort(noise, dim=1).to(sequence.device) # ascend: small is keep, large is remove + ids_restore = torch.argsort(ids_shuffle, dim=1).to(sequence.device) + + # keep the first subset + ids_keep = ids_shuffle[:, :len_keep] + sequence_unmasked = torch.gather(sequence, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, dim)) + + # generate the binary mask: 0 is keep, 1 is remove + mask = torch.ones([batch_size, seq_length], device=sequence.device) + mask[:, :len_keep] = 0 + # unshuffle to get the binary mask + mask = torch.gather(mask, dim=1, index=ids_restore) + + return sequence_unmasked, mask, ids_restore + + def forward(self, pixel_values, noise=None, interpolate_pos_encoding: bool = False): + batch_size, num_channels, height, width = pixel_values.shape + embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding) + if interpolate_pos_encoding: + position_embeddings = self.interpolate_pos_encoding(embeddings, height, width) + else: + position_embeddings = self.position_embeddings + + # add position embeddings w/o cls token + embeddings = embeddings + position_embeddings[:, 1:, :] + + # masking: length -> length * config.mask_ratio + embeddings, mask, ids_restore = self.random_masking(embeddings, noise) + + # append cls token + cls_token = self.cls_token + position_embeddings[:, :1, :] + cls_tokens = cls_token.expand(embeddings.shape[0], -1, -1) + embeddings = torch.cat((cls_tokens, embeddings), dim=1) + + return embeddings, mask, ids_restore + + +class ViTMAEPatchEmbeddings(nn.Module): + """ + This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial + `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a + Transformer. + """ + + def __init__(self, config): + super().__init__() + image_size, patch_size = config.image_size, config.patch_size + num_channels, hidden_size = config.num_channels, config.hidden_size + image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size) + patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size) + num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.num_patches = num_patches + + self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size) + + def forward(self, pixel_values, interpolate_pos_encoding: bool = False): + batch_size, num_channels, height, width = pixel_values.shape + if num_channels != self.num_channels: + raise ValueError( + "Make sure that the channel dimension of the pixel values match with the one set in the configuration." + ) + + if not interpolate_pos_encoding and (height != self.image_size[0] or width != self.image_size[1]): + raise ValueError( + f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})." + ) + x = self.projection(pixel_values).flatten(2).transpose(1, 2) + return x + + +# Copied from transformers.models.vit.modeling_vit.ViTSelfAttention ViT->ViTMAE +class ViTMAESelfAttention(nn.Module): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): + raise ValueError( + f"The hidden size {config.hidden_size,} is not a multiple of the number of attention " + f"heads {config.num_attention_heads}." + ) + + self.has_flash_attn = HAS_FLASH_ATTN + self.num_attention_heads = config.num_attention_heads + self.attention_head_size = int(config.hidden_size / config.num_attention_heads) + self.all_head_size = self.num_attention_heads * self.attention_head_size + + self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) + self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) + self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) + + self.dropout = nn.Dropout(config.attention_probs_dropout_prob) + self.attention_probs_dropout_prob = config.attention_probs_dropout_prob + + def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor: + new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) + x = x.view(new_x_shape) + return x.permute(0, 2, 1, 3) + + def reshape_for_flash(self, x: torch.Tensor) -> torch.Tensor: + """Reshape to (B, N, num_heads, head_dim) for flash_attn_func.""" + new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) + return x.view(new_x_shape) + + def forward( + self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False + ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]: + # Use FlashAttention when available and no special outputs are needed + if self.has_flash_attn and not output_attentions and head_mask is None: + query_layer = self.reshape_for_flash(self.query(hidden_states)) + key_layer = self.reshape_for_flash(self.key(hidden_states)) + value_layer = self.reshape_for_flash(self.value(hidden_states)) + + context_layer = flash_attn_func( + query_layer, key_layer, value_layer, + dropout_p=self.attention_probs_dropout_prob if self.training else 0.0, + causal=False, deterministic=True + ) + + context_layer = context_layer.reshape(hidden_states.size(0), -1, self.all_head_size) + return (context_layer,) + + # Fallback: manual attention computation + mixed_query_layer = self.query(hidden_states) + + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + query_layer = self.transpose_for_scores(mixed_query_layer) + + attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) + attention_scores = attention_scores / math.sqrt(self.attention_head_size) + + attention_probs = nn.functional.softmax(attention_scores, dim=-1) + attention_probs = self.dropout(attention_probs) + + if head_mask is not None: + attention_probs = attention_probs * head_mask + + context_layer = torch.matmul(attention_probs, value_layer) + + context_layer = context_layer.permute(0, 2, 1, 3).contiguous() + new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) + context_layer = context_layer.view(new_context_layer_shape) + + outputs = (context_layer, attention_probs) if output_attentions else (context_layer,) + + return outputs + + +# Copied from transformers.models.vit.modeling_vit.ViTSdpaSelfAttention ViT->ViTMAE +class ViTMAESdpaSelfAttention(ViTMAESelfAttention): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__(config) + self.attention_probs_dropout_prob = config.attention_probs_dropout_prob + + def forward( + self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False + ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]: + # Use FlashAttention when available and no special outputs are needed + if self.has_flash_attn and not output_attentions and head_mask is None: + query_layer = self.reshape_for_flash(self.query(hidden_states)) + key_layer = self.reshape_for_flash(self.key(hidden_states)) + value_layer = self.reshape_for_flash(self.value(hidden_states)) + + context_layer = flash_attn_func( + query_layer, key_layer, value_layer, + dropout_p=self.attention_probs_dropout_prob if self.training else 0.0, + causal=False, deterministic=True + ) + + context_layer = context_layer.reshape(hidden_states.size(0), -1, self.all_head_size) + return context_layer, None + + # Fallback: PyTorch SDPA + mixed_query_layer = self.query(hidden_states) + + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + query_layer = self.transpose_for_scores(mixed_query_layer) + + context_layer = torch.nn.functional.scaled_dot_product_attention( + query_layer, + key_layer, + value_layer, + head_mask, + self.attention_probs_dropout_prob if self.training else 0.0, + is_causal=False, + scale=None, + ) + + context_layer = context_layer.permute(0, 2, 1, 3).contiguous() + new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) + context_layer = context_layer.view(new_context_layer_shape) + + return context_layer, None + + +# Copied from transformers.models.vit.modeling_vit.ViTSelfOutput with ViT->ViTMAE +class ViTMAESelfOutput(nn.Module): + """ + The residual connection is defined in ViTMAELayer instead of here (as is the case with other models), due to the + layernorm applied before each block. + """ + + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + + return hidden_states + + +# Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->ViTMAE +class ViTMAEAttention(nn.Module): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.attention = ViTMAESelfAttention(config) + self.output = ViTMAESelfOutput(config) + + def forward( + self, + hidden_states: torch.Tensor, + head_mask: Optional[torch.Tensor] = None, + output_attentions: bool = False, + ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]: + self_outputs = self.attention(hidden_states, head_mask, output_attentions) + + attention_output = self.output(self_outputs[0], hidden_states) + + outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them + return outputs + +# Copied from transformers.models.vit.modeling_vit.ViTIntermediate ViT->ViTMAE +class ViTMAEIntermediate(nn.Module): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.intermediate_size) + if isinstance(config.hidden_act, str): + self.intermediate_act_fn = ACT2FN[config.hidden_act] + else: + self.intermediate_act_fn = config.hidden_act + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.intermediate_act_fn(hidden_states) + + return hidden_states + + +# Copied from transformers.models.vit.modeling_vit.ViTOutput ViT->ViTMAE +class ViTMAEOutput(nn.Module): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.dense = nn.Linear(config.intermediate_size, config.hidden_size) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + + hidden_states = hidden_states + input_tensor + + return hidden_states + + + +# Copied from transformers.models.vit.modeling_vit.ViTLayer with ViT->ViTMAE,VIT->VITMAE +class ViTMAELayer(nn.Module): + """This corresponds to the Block class in the timm implementation.""" + + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.chunk_size_feed_forward = config.chunk_size_feed_forward + self.seq_len_dim = 1 + self.attention = ViTMAEAttention(config) # no SPDA by default + self.intermediate = ViTMAEIntermediate(config) + self.output = ViTMAEOutput(config) + self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + + def forward( + self, + hidden_states: torch.Tensor, + head_mask: Optional[torch.Tensor] = None, + output_attentions: bool = False, + ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]: + self_attention_outputs = self.attention( + self.layernorm_before(hidden_states), # in ViTMAE, layernorm is applied before self-attention + head_mask, + output_attentions=output_attentions, + ) + attention_output = self_attention_outputs[0] + outputs = self_attention_outputs[1:] # add self attentions if we output attention weights + + # first residual connection + hidden_states = attention_output + hidden_states + + # in ViTMAE, layernorm is also applied after self-attention + layer_output = self.layernorm_after(hidden_states) + layer_output = self.intermediate(layer_output) + + # second residual connection is done here + layer_output = self.output(layer_output, hidden_states) + + outputs = (layer_output,) + outputs + + return outputs + + +class GeneralDecoder(nn.Module): + def __init__(self, config, num_patches): + super().__init__() + self.decoder_embed = nn.Linear(config.hidden_size, config.decoder_hidden_size, bias=True) + self.decoder_pos_embed = nn.Parameter( + torch.zeros(1, num_patches + 1, config.decoder_hidden_size), requires_grad=False + ) # fixed sin-cos embedding + + decoder_config = deepcopy(config) + decoder_config.hidden_size = config.decoder_hidden_size + decoder_config.num_hidden_layers = config.decoder_num_hidden_layers + decoder_config.num_attention_heads = config.decoder_num_attention_heads + decoder_config.intermediate_size = config.decoder_intermediate_size + self.decoder_layers = nn.ModuleList( + [ViTMAELayer(decoder_config) for _ in range(config.decoder_num_hidden_layers)] + ) + + self.decoder_norm = nn.LayerNorm(config.decoder_hidden_size, eps=config.layer_norm_eps) + self.decoder_pred = nn.Linear( + config.decoder_hidden_size, config.patch_size**2 * config.num_channels, bias=True + ) # encoder to decoder + self.gradient_checkpointing = False + self.config = config + self.num_patches = num_patches + self.initialize_weights(num_patches) + self.decoder_config = decoder_config + self.set_trainable_cls_token() + def set_trainable_cls_token(self, tensor: Optional[torch.Tensor] = None): + # register a trainable CLS token + tensor = torch.zeros(1, 1, self.decoder_config.hidden_size) if tensor is None else tensor + self.trainable_cls_token = nn.Parameter(tensor) + def interpolate_pos_encoding(self, embeddings: torch.Tensor) -> torch.Tensor: + """ + This method is a modified version of the interpolation function for ViT-mae model at the deocder, that + allows to interpolate the pre-trained decoder position encodings, to be able to use the model on higher + resolution images. + + Source: + https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174 + """ + + # -1 removes the class dimension since we later append it without interpolation + embeddings_positions = embeddings.shape[1] - 1 + num_positions = self.decoder_pos_embed.shape[1] - 1 + + # Separation of class token and patch tokens + class_pos_embed = self.decoder_pos_embed[:, 0, :] + patch_pos_embed = self.decoder_pos_embed[:, 1:, :] + + # To retain the final 3d tensor with the required dimensions + dim = self.decoder_pos_embed.shape[-1] + + # Increasing a dimension to enable bicubic interpolation + patch_pos_embed = patch_pos_embed.reshape(1, 1, -1, dim) + + # permute to bring the dimension to be interpolated, to the last + patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2) + + # Interpolating the decoder position embeddings shape wrt embeddings shape i.e (x). + # 1 keeps the other dimension constant + patch_pos_embed = nn.functional.interpolate( + patch_pos_embed, + scale_factor=(1, embeddings_positions / num_positions), + mode="bicubic", + align_corners=False, + ) + + # Converting back to the original shape + patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) + # Adding the class token back + return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1) + def interpolate_latent(self, x: torch.Tensor) -> torch.Tensor: + b, l, c = x.shape + if l == self.num_patches: + return x + # interpolate the latent + #print(f"interpolating latent from {l} to {self.num_patches}, x.shape = {x.shape}") + h, w = int(l**0.5), int(l**0.5) + x = x.reshape(b, h, w, c) + x = x.permute(0, 3, 1, 2) + target_size = (int(self.num_patches**0.5), int(self.num_patches**0.5)) + x = nn.functional.interpolate(x, size=target_size, mode="bilinear", align_corners=False) + x = x.permute(0, 2, 3, 1).contiguous().view(b, self.num_patches, c) + return x + + def initialize_weights(self, num_patches): + # initialize (and freeze) position embeddings by sin-cos embedding + decoder_pos_embed = get_2d_sincos_pos_embed( + self.decoder_pos_embed.shape[-1], int(num_patches**0.5), add_cls_token=True + ) + self.decoder_pos_embed.data.copy_(torch.from_numpy(decoder_pos_embed).float().unsqueeze(0)) + + # timm's trunc_normal_(std=.02) is effectively normal_(std=0.02) as cutoff is too big (2.) + # torch.nn.init.normal_(self.mask_token, std=self.config.initializer_range) + def unpatchify(self, patchified_pixel_values, original_image_size: Optional[Tuple[int, int]] = None): + """ + Args: + patchified_pixel_values (`torch.FloatTensor` of shape `(batch_size, num_patches, patch_size**2 * num_channels)`: + Patchified pixel values. + original_image_size (`Tuple[int, int]`, *optional*): + Original image size. + + Returns: + `torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`: + Pixel values. + """ + patch_size, num_channels = self.config.patch_size, self.config.num_channels + original_image_size = ( + original_image_size + if original_image_size is not None + else (self.config.image_size, self.config.image_size) + ) + original_height, original_width = original_image_size + num_patches_h = original_height // patch_size + num_patches_w = original_width // patch_size + # sanity check + if num_patches_h * num_patches_w != patchified_pixel_values.shape[1]: + raise ValueError( + f"The number of patches in the patchified pixel values {patchified_pixel_values.shape[1]}, does not match the number of patches on original image {num_patches_h}*{num_patches_w}" + ) + + # unpatchify + batch_size = patchified_pixel_values.shape[0] + patchified_pixel_values = patchified_pixel_values.reshape( + batch_size, + num_patches_h, + num_patches_w, + patch_size, + patch_size, + num_channels, + ) + patchified_pixel_values = torch.einsum("nhwpqc->nchpwq", patchified_pixel_values) + pixel_values = patchified_pixel_values.reshape( + batch_size, + num_channels, + num_patches_h * patch_size, + num_patches_w * patch_size, + ) + return pixel_values + + def forward( + self, + hidden_states, + output_attentions=False, + output_hidden_states=False, + return_dict=True, + interpolate_pos_encoding: bool = False, + drop_cls_token: bool = False, + ): + # embed tokens + x = self.decoder_embed(hidden_states) + #print(f"x.shape = {x.shape}") + if drop_cls_token: + x_ = x[:, 1:, :] # no cls token + x_ = self.interpolate_latent(x_) + else: + x_ = self.interpolate_latent(x) # interpolate the whole latent + cls_token = self.trainable_cls_token.expand(x_.shape[0], -1, -1) + x = torch.cat([cls_token, x_], dim=1) + + # add pos embed + if interpolate_pos_encoding: + assert drop_cls_token, "interpolate_pos_encoding only works with drop_cls_token=True" + decoder_pos_embed = self.interpolate_pos_encoding(x) + else: + decoder_pos_embed = self.decoder_pos_embed + hidden_states = x + decoder_pos_embed + #print(f"hidden_states.shape = {hidden_states.shape}") + # apply Transformer layers (blocks) + all_hidden_states = () if output_hidden_states else None + all_self_attentions = () if output_attentions else None + for i, layer_module in enumerate(self.decoder_layers): + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + if self.gradient_checkpointing and self.training: + layer_outputs = self._gradient_checkpointing_func( + layer_module.__call__, + hidden_states, + None, + output_attentions, + ) + else: + layer_outputs = layer_module(hidden_states, head_mask=None, output_attentions=output_attentions) + + hidden_states = layer_outputs[0] + + if output_attentions: + all_self_attentions = all_self_attentions + (layer_outputs[1],) + + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + hidden_states = self.decoder_norm(hidden_states) + + # predictor projection + logits = self.decoder_pred(hidden_states) + + # remove cls token + logits = logits[:, 1:, :] + + if not return_dict: + return tuple(v for v in [logits, all_hidden_states, all_self_attentions] if v is not None) + return ViTMAEDecoderOutput( + logits=logits, + hidden_states=all_hidden_states, + attentions=all_self_attentions, + ) + +import json +from math import sqrt +from pathlib import Path +from typing import Any, Dict, Optional + +import torch +import torch.nn as nn +from timm.models.vision_transformer import Attention +from transformers import AutoConfig, AutoImageProcessor + +try: + from diffusers.configuration_utils import ConfigMixin, register_to_config + from diffusers.models.modeling_utils import ModelMixin +except Exception: # pragma: no cover + class ConfigMixin: + config_name = "config.json" + + class ModelMixin(nn.Module): + pass + + def register_to_config(init): + return init + + +_PIXEL_DECODER_DEFAULTS: Dict[str, Any] = { + "decoder_hidden_size": 1024, + "decoder_intermediate_size": 4096, + "decoder_num_attention_heads": 16, + "decoder_num_hidden_layers": 24, + "layer_norm_eps": 1e-12, + "num_channels": 3, + "hidden_act": "gelu", + "qkv_bias": True, + "hidden_dropout_prob": 0.0, + "attention_probs_dropout_prob": 0.0, + "initializer_range": 0.02, +} + + +def _resolve_local_asset_path(path: str, model_root: Optional[Path] = None) -> str: + candidate = Path(path) + if candidate.is_file(): + return str(candidate) + search_roots = [] + if model_root is not None: + search_roots.extend([model_root, model_root.parent]) + for root in search_roots: + for probe in (root / candidate, root / candidate.name, root / "decoder_config" / "config.json"): + if probe.is_file(): + return str(probe) + return path + + +def _build_pixel_decoder_config( + *, + encoder_hidden_size: int, + decoder_patch_size: int, + base_patches: int, + decoder_config_path: Optional[str] = None, + overrides: Optional[Dict[str, Any]] = None, +) -> ViTMAEConfig: + pixel_decoder = dict(_PIXEL_DECODER_DEFAULTS) + if decoder_config_path is not None: + resolved = _resolve_local_asset_path(decoder_config_path) + if Path(resolved).is_file(): + with open(resolved, encoding="utf-8") as handle: + pixel_decoder.update(json.load(handle)) + if overrides: + pixel_decoder.update({key: value for key, value in overrides.items() if value is not None}) + + return ViTMAEConfig( + hidden_size=encoder_hidden_size, + patch_size=decoder_patch_size, + image_size=int(decoder_patch_size * sqrt(base_patches)), + **pixel_decoder, + ) + + +def _load_image_normalization(encoder_config_path: str) -> tuple[list[float], list[float]]: + try: + proc = AutoImageProcessor.from_pretrained(encoder_config_path, use_fast=True, local_files_only=True) + return proc.image_mean, proc.image_std + except Exception: + pass + try: + proc = AutoImageProcessor.from_pretrained(encoder_config_path, use_fast=True, local_files_only=False) + return proc.image_mean, proc.image_std + except Exception: + if "siglip" in encoder_config_path.lower(): + return [0.5, 0.5, 0.5], [0.5, 0.5, 0.5] + return [0.485, 0.456, 0.406], [0.229, 0.224, 0.225] + + +class PAEDecoder(ModelMixin, ConfigMixin): + """PAE decoder: latent decompressor + ViT-MAE pixel decoder.""" + + @register_to_config + def __init__( + self, + encoder_hidden_size: int = 1024, + encoder_num_heads: int = 16, + encoder_input_size: int = 224, + encoder_patch_size: int = 14, + encoder_config_path: str = "facebook/dinov2-with-registers-large", + latent_dim: int = 32, + decoder_patch_size: int = 16, + decoder_config_path: Optional[str] = None, + decoder_hidden_size: int = 1024, + decoder_intermediate_size: int = 4096, + decoder_num_attention_heads: int = 16, + decoder_num_hidden_layers: int = 24, + layer_norm_eps: float = 1e-12, + num_channels: int = 3, + hidden_act: str = "gelu", + qkv_bias: bool = True, + hidden_dropout_prob: float = 0.0, + attention_probs_dropout_prob: float = 0.0, + initializer_range: float = 0.02, + image_mean: Optional[list[float]] = None, + image_std: Optional[list[float]] = None, + latent_mean: Optional[list[float]] = None, + latent_std: Optional[list[float]] = None, + latent_multiplier: float = 1.0, + **kwargs, + ) -> None: + super().__init__() + if image_mean is not None and image_std is not None: + norm_mean, norm_std = image_mean, image_std + else: + norm_mean, norm_std = _load_image_normalization(encoder_config_path) + self.register_buffer("encoder_mean", torch.tensor(norm_mean).view(1, 3, 1, 1), persistent=True) + self.register_buffer("encoder_std", torch.tensor(norm_std).view(1, 3, 1, 1), persistent=True) + + self.encoder_input_size = encoder_input_size + self.encoder_patch_size = encoder_patch_size + self.base_patches = (self.encoder_input_size // self.encoder_patch_size) ** 2 + self.latent_dim = latent_dim + + self.latent_decompressor = nn.ModuleList( + [ + nn.Conv2d(latent_dim, encoder_hidden_size, kernel_size=3, padding=1), + Attention(dim=encoder_hidden_size, num_heads=encoder_num_heads), + ] + ) + + pixel_decoder_config = _build_pixel_decoder_config( + encoder_hidden_size=encoder_hidden_size, + decoder_patch_size=decoder_patch_size, + base_patches=self.base_patches, + decoder_config_path=decoder_config_path, + overrides={ + "decoder_hidden_size": decoder_hidden_size, + "decoder_intermediate_size": decoder_intermediate_size, + "decoder_num_attention_heads": decoder_num_attention_heads, + "decoder_num_hidden_layers": decoder_num_hidden_layers, + "layer_norm_eps": layer_norm_eps, + "num_channels": num_channels, + "hidden_act": hidden_act, + "qkv_bias": qkv_bias, + "hidden_dropout_prob": hidden_dropout_prob, + "attention_probs_dropout_prob": attention_probs_dropout_prob, + "initializer_range": initializer_range, + }, + ) + self.decoder = GeneralDecoder(pixel_decoder_config, num_patches=self.base_patches) + + @classmethod + def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): + model_root = Path(pretrained_model_name_or_path) + config_file = model_root / cls.config_name + if config_file.is_file(): + with open(config_file, encoding="utf-8") as handle: + config = json.load(handle) + decoder_config_path = config.get("decoder_config_path") + if decoder_config_path is not None: + resolved = _resolve_local_asset_path(decoder_config_path, model_root=model_root) + if resolved != decoder_config_path: + kwargs.setdefault("decoder_config_path", resolved) + return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) + + def decode(self, latents: torch.Tensor) -> torch.Tensor: + hidden_states = self.latent_decompressor[0](latents) + batch_size, channels, height, width = hidden_states.shape + num_tokens = height * width + hidden_states = hidden_states.view(batch_size, channels, num_tokens).transpose(1, 2) + hidden_states = self.latent_decompressor[1](hidden_states) + + output = self.decoder(hidden_states, drop_cls_token=False).logits + x_rec = self.decoder.unpatchify(output) + x_rec = x_rec * self.encoder_std.to(x_rec.device) + self.encoder_mean.to(x_rec.device) + return x_rec + + def forward(self, latents: torch.Tensor) -> torch.Tensor: + return self.decode(latents) diff --git a/pae-dinov3-large-d32/decoder/diffusion_pytorch_model.safetensors b/pae-dinov3-large-d32/decoder/diffusion_pytorch_model.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..9324a5f9aee6969b69516a138b318ec1bca025cb --- /dev/null +++ b/pae-dinov3-large-d32/decoder/diffusion_pytorch_model.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:57842b0b1aaa90793d74c7fa959e9c242a553798320271cde5bf0cd6a372d608 +size 1235663744 diff --git a/pae-dinov3-large-d32/demo.png b/pae-dinov3-large-d32/demo.png new file mode 100644 index 0000000000000000000000000000000000000000..235393ceac09779bfeee5115f463d79dfb05725a Binary files /dev/null and b/pae-dinov3-large-d32/demo.png differ diff --git a/pae-dinov3-large-d32/model_index.json b/pae-dinov3-large-d32/model_index.json new file mode 100644 index 0000000000000000000000000000000000000000..c71449e6f44c0678499c73c3696faea852cca1e2 --- /dev/null +++ b/pae-dinov3-large-d32/model_index.json @@ -0,0 +1,1021 @@ +{ + "_class_name": [ + "pipeline", + "PAEPipeline" + ], + "_diffusers_version": "0.31.0", + "decoder": [ + "decoder_pae", + "PAEDecoder" + ], + "id2label": { + "0": "tench, Tinca tinca", + "1": "goldfish, Carassius auratus", + "2": "great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias", + "3": "tiger shark, Galeocerdo cuvieri", + "4": "hammerhead, hammerhead shark", + "5": "electric ray, crampfish, numbfish, torpedo", + "6": "stingray", + "7": "cock", + "8": "hen", + "9": "ostrich, Struthio camelus", + "10": "brambling, Fringilla montifringilla", + "11": "goldfinch, Carduelis carduelis", + "12": "house finch, linnet, Carpodacus mexicanus", + "13": "junco, snowbird", + "14": "indigo bunting, indigo finch, indigo bird, Passerina cyanea", + "15": "robin, American robin, Turdus migratorius", + "16": "bulbul", + "17": "jay", + "18": "magpie", + "19": "chickadee", + "20": "water ouzel, dipper", + "21": "kite", + "22": "bald eagle, American eagle, Haliaeetus leucocephalus", + "23": "vulture", + "24": "great grey owl, great gray owl, Strix nebulosa", + "25": "European fire salamander, Salamandra salamandra", + "26": "common newt, Triturus vulgaris", + "27": "eft", + "28": "spotted salamander, Ambystoma maculatum", + "29": "axolotl, mud puppy, Ambystoma mexicanum", + "30": "bullfrog, Rana catesbeiana", + "31": "tree frog, tree-frog", + "32": "tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui", + "33": "loggerhead, loggerhead turtle, Caretta caretta", + "34": "leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea", + "35": "mud turtle", + "36": "terrapin", + "37": "box turtle, box tortoise", + "38": "banded gecko", + "39": "common iguana, iguana, Iguana iguana", + "40": "American chameleon, anole, Anolis carolinensis", + "41": "whiptail, whiptail lizard", + "42": "agama", + "43": "frilled lizard, Chlamydosaurus kingi", + "44": "alligator lizard", + "45": "Gila monster, Heloderma suspectum", + "46": "green lizard, Lacerta viridis", + "47": "African chameleon, Chamaeleo chamaeleon", + "48": "Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis", + "49": "African crocodile, Nile crocodile, Crocodylus niloticus", + "50": "American alligator, Alligator mississipiensis", + "51": "triceratops", + "52": "thunder snake, worm snake, Carphophis amoenus", + "53": "ringneck snake, ring-necked snake, ring snake", + "54": "hognose snake, puff adder, sand viper", + "55": "green snake, grass snake", + "56": "king snake, kingsnake", + "57": "garter snake, grass snake", + "58": "water snake", + "59": "vine snake", + "60": "night snake, Hypsiglena torquata", + "61": "boa constrictor, Constrictor constrictor", + "62": "rock python, rock snake, Python sebae", + "63": "Indian cobra, Naja naja", + "64": "green mamba", + "65": "sea snake", + "66": "horned viper, cerastes, sand viper, horned asp, Cerastes cornutus", + "67": "diamondback, diamondback rattlesnake, Crotalus adamanteus", + "68": "sidewinder, horned rattlesnake, Crotalus cerastes", + "69": "trilobite", + "70": "harvestman, daddy longlegs, Phalangium opilio", + "71": "scorpion", + "72": "black and gold garden spider, Argiope aurantia", + "73": "barn spider, Araneus cavaticus", + "74": "garden spider, Aranea diademata", + "75": "black widow, Latrodectus mactans", + "76": "tarantula", + "77": "wolf spider, hunting spider", + "78": "tick", + "79": "centipede", + "80": "black grouse", + "81": "ptarmigan", + "82": "ruffed grouse, partridge, Bonasa umbellus", + "83": "prairie chicken, prairie grouse, prairie fowl", + "84": "peacock", + "85": "quail", + "86": "partridge", + "87": "African grey, African gray, Psittacus erithacus", + "88": "macaw", + "89": "sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita", + "90": "lorikeet", + "91": "coucal", + "92": "bee eater", + "93": "hornbill", + "94": "hummingbird", + "95": "jacamar", + "96": "toucan", + "97": "drake", + "98": "red-breasted merganser, Mergus serrator", + "99": "goose", + "100": "black swan, Cygnus atratus", + "101": "tusker", + "102": "echidna, spiny anteater, anteater", + "103": "platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus", + "104": "wallaby, brush kangaroo", + "105": "koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus", + "106": "wombat", + "107": "jellyfish", + "108": "sea anemone, anemone", + "109": "brain coral", + "110": "flatworm, platyhelminth", + "111": "nematode, nematode worm, roundworm", + "112": "conch", + "113": "snail", + "114": "slug", + "115": "sea slug, nudibranch", + "116": "chiton, coat-of-mail shell, sea cradle, polyplacophore", + "117": "chambered nautilus, pearly nautilus, nautilus", + "118": "Dungeness crab, Cancer magister", + "119": "rock crab, Cancer irroratus", + "120": "fiddler crab", + "121": "king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica", + "122": "American lobster, Northern lobster, Maine lobster, Homarus americanus", + "123": "spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish", + "124": "crayfish, crawfish, crawdad, crawdaddy", + "125": "hermit crab", + "126": "isopod", + "127": "white stork, Ciconia ciconia", + "128": "black stork, Ciconia nigra", + "129": "spoonbill", + "130": "flamingo", + "131": "little blue heron, Egretta caerulea", + "132": "American egret, great white heron, Egretta albus", + "133": "bittern", + "134": "crane", + "135": "limpkin, Aramus pictus", + "136": "European gallinule, Porphyrio porphyrio", + "137": "American coot, marsh hen, mud hen, water hen, Fulica americana", + "138": "bustard", + "139": "ruddy turnstone, Arenaria interpres", + "140": "red-backed sandpiper, dunlin, Erolia alpina", + "141": "redshank, Tringa totanus", + "142": "dowitcher", + "143": "oystercatcher, oyster catcher", + "144": "pelican", + "145": "king penguin, Aptenodytes patagonica", + "146": "albatross, mollymawk", + "147": "grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus", + "148": "killer whale, killer, orca, grampus, sea wolf, Orcinus orca", + "149": "dugong, Dugong dugon", + "150": "sea lion", + "151": "Chihuahua", + "152": "Japanese spaniel", + "153": "Maltese dog, Maltese terrier, Maltese", + "154": "Pekinese, Pekingese, Peke", + "155": "Shih-Tzu", + "156": "Blenheim spaniel", + "157": "papillon", + "158": "toy terrier", + "159": "Rhodesian ridgeback", + "160": "Afghan hound, Afghan", + "161": "basset, basset hound", + "162": "beagle", + "163": "bloodhound, sleuthhound", + "164": "bluetick", + "165": "black-and-tan coonhound", + "166": "Walker hound, Walker foxhound", + "167": "English foxhound", + "168": "redbone", + "169": "borzoi, Russian wolfhound", + "170": "Irish wolfhound", + "171": "Italian greyhound", + "172": "whippet", + "173": "Ibizan hound, Ibizan Podenco", + "174": "Norwegian elkhound, elkhound", + "175": "otterhound, otter hound", + "176": "Saluki, gazelle hound", + "177": "Scottish deerhound, deerhound", + "178": "Weimaraner", + "179": "Staffordshire bullterrier, Staffordshire bull terrier", + "180": "American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier", + "181": "Bedlington terrier", + "182": "Border terrier", + "183": "Kerry blue terrier", + "184": "Irish terrier", + "185": "Norfolk terrier", + "186": "Norwich terrier", + "187": "Yorkshire terrier", + "188": "wire-haired fox terrier", + "189": "Lakeland terrier", + "190": "Sealyham terrier, Sealyham", + "191": "Airedale, Airedale terrier", + "192": "cairn, cairn terrier", + "193": "Australian terrier", + "194": "Dandie Dinmont, Dandie Dinmont terrier", + "195": "Boston bull, Boston terrier", + "196": "miniature schnauzer", + "197": "giant schnauzer", + "198": "standard schnauzer", + "199": "Scotch terrier, Scottish terrier, Scottie", + "200": "Tibetan terrier, chrysanthemum dog", + "201": "silky terrier, Sydney silky", + "202": "soft-coated wheaten terrier", + "203": "West Highland white terrier", + "204": "Lhasa, Lhasa apso", + "205": "flat-coated retriever", + "206": "curly-coated retriever", + "207": "golden retriever", + "208": "Labrador retriever", + "209": "Chesapeake Bay retriever", + "210": "German short-haired pointer", + "211": "vizsla, Hungarian pointer", + "212": "English setter", + "213": "Irish setter, red setter", + "214": "Gordon setter", + "215": "Brittany spaniel", + "216": "clumber, clumber spaniel", + "217": "English springer, English springer spaniel", + "218": "Welsh springer spaniel", + "219": "cocker spaniel, English cocker spaniel, cocker", + "220": "Sussex spaniel", + "221": "Irish water spaniel", + "222": "kuvasz", + "223": "schipperke", + "224": "groenendael", + "225": "malinois", + "226": "briard", + "227": "kelpie", + "228": "komondor", + "229": "Old English sheepdog, bobtail", + "230": "Shetland sheepdog, Shetland sheep dog, Shetland", + "231": "collie", + "232": "Border collie", + "233": "Bouvier des Flandres, Bouviers des Flandres", + "234": "Rottweiler", + "235": "German shepherd, German shepherd dog, German police dog, alsatian", + "236": "Doberman, Doberman pinscher", + "237": "miniature pinscher", + "238": "Greater Swiss Mountain dog", + "239": "Bernese mountain dog", + "240": "Appenzeller", + "241": "EntleBucher", + "242": "boxer", + "243": "bull mastiff", + "244": "Tibetan mastiff", + "245": "French bulldog", + "246": "Great Dane", + "247": "Saint Bernard, St Bernard", + "248": "Eskimo dog, husky", + "249": "malamute, malemute, Alaskan malamute", + "250": "Siberian husky", + "251": "dalmatian, coach dog, carriage dog", + "252": "affenpinscher, monkey pinscher, monkey dog", + "253": "basenji", + "254": "pug, pug-dog", + "255": "Leonberg", + "256": "Newfoundland, Newfoundland dog", + "257": "Great Pyrenees", + "258": "Samoyed, Samoyede", + "259": "Pomeranian", + "260": "chow, chow chow", + "261": "keeshond", + "262": "Brabancon griffon", + "263": "Pembroke, Pembroke Welsh corgi", + "264": "Cardigan, Cardigan Welsh corgi", + "265": "toy poodle", + "266": "miniature poodle", + "267": "standard poodle", + "268": "Mexican hairless", + "269": "timber wolf, grey wolf, gray wolf, Canis lupus", + "270": "white wolf, Arctic wolf, Canis lupus tundrarum", + "271": "red wolf, maned wolf, Canis rufus, Canis niger", + "272": "coyote, prairie wolf, brush wolf, Canis latrans", + "273": "dingo, warrigal, warragal, Canis dingo", + "274": "dhole, Cuon alpinus", + "275": "African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus", + "276": "hyena, hyaena", + "277": "red fox, Vulpes vulpes", + "278": "kit fox, Vulpes macrotis", + "279": "Arctic fox, white fox, Alopex lagopus", + "280": "grey fox, gray fox, Urocyon cinereoargenteus", + "281": "tabby, tabby cat", + "282": "tiger cat", + "283": "Persian cat", + "284": "Siamese cat, Siamese", + "285": "Egyptian cat", + "286": "cougar, puma, catamount, mountain lion, painter, panther, Felis concolor", + "287": "lynx, catamount", + "288": "leopard, Panthera pardus", + "289": "snow leopard, ounce, Panthera uncia", + "290": "jaguar, panther, Panthera onca, Felis onca", + "291": "lion, king of beasts, Panthera leo", + "292": "tiger, Panthera tigris", + "293": "cheetah, chetah, Acinonyx jubatus", + "294": "brown bear, bruin, Ursus arctos", + "295": "American black bear, black bear, Ursus americanus, Euarctos americanus", + "296": "ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus", + "297": "sloth bear, Melursus ursinus, Ursus ursinus", + "298": "mongoose", + "299": "meerkat, mierkat", + "300": "tiger beetle", + "301": "ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle", + "302": "ground beetle, carabid beetle", + "303": "long-horned beetle, longicorn, longicorn beetle", + "304": "leaf beetle, chrysomelid", + "305": "dung beetle", + "306": "rhinoceros beetle", + "307": "weevil", + "308": "fly", + "309": "bee", + "310": "ant, emmet, pismire", + "311": "grasshopper, hopper", + "312": "cricket", + "313": "walking stick, walkingstick, stick insect", + "314": "cockroach, roach", + "315": "mantis, mantid", + "316": "cicada, cicala", + "317": "leafhopper", + "318": "lacewing, lacewing fly", + "319": "dragonfly, darning needle, devils darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk", + "320": "damselfly", + "321": "admiral", + "322": "ringlet, ringlet butterfly", + "323": "monarch, monarch butterfly, milkweed butterfly, Danaus plexippus", + "324": "cabbage butterfly", + "325": "sulphur butterfly, sulfur butterfly", + "326": "lycaenid, lycaenid butterfly", + "327": "starfish, sea star", + "328": "sea urchin", + "329": "sea cucumber, holothurian", + "330": "wood rabbit, cottontail, cottontail rabbit", + "331": "hare", + "332": "Angora, Angora rabbit", + "333": "hamster", + "334": "porcupine, hedgehog", + "335": "fox squirrel, eastern fox squirrel, Sciurus niger", + "336": "marmot", + "337": "beaver", + "338": "guinea pig, Cavia cobaya", + "339": "sorrel", + "340": "zebra", + "341": "hog, pig, grunter, squealer, Sus scrofa", + "342": "wild boar, boar, Sus scrofa", + "343": "warthog", + "344": "hippopotamus, hippo, river horse, Hippopotamus amphibius", + "345": "ox", + "346": "water buffalo, water ox, Asiatic buffalo, Bubalus bubalis", + "347": "bison", + "348": "ram, tup", + "349": "bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis", + "350": "ibex, Capra ibex", + "351": "hartebeest", + "352": "impala, Aepyceros melampus", + "353": "gazelle", + "354": "Arabian camel, dromedary, Camelus dromedarius", + "355": "llama", + "356": "weasel", + "357": "mink", + "358": "polecat, fitch, foulmart, foumart, Mustela putorius", + "359": "black-footed ferret, ferret, Mustela nigripes", + "360": "otter", + "361": "skunk, polecat, wood pussy", + "362": "badger", + "363": "armadillo", + "364": "three-toed sloth, ai, Bradypus tridactylus", + "365": "orangutan, orang, orangutang, Pongo pygmaeus", + "366": "gorilla, Gorilla gorilla", + "367": "chimpanzee, chimp, Pan troglodytes", + "368": "gibbon, Hylobates lar", + "369": "siamang, Hylobates syndactylus, Symphalangus syndactylus", + "370": "guenon, guenon monkey", + "371": "patas, hussar monkey, Erythrocebus patas", + "372": "baboon", + "373": "macaque", + "374": "langur", + "375": "colobus, colobus monkey", + "376": "proboscis monkey, Nasalis larvatus", + "377": "marmoset", + "378": "capuchin, ringtail, Cebus capucinus", + "379": "howler monkey, howler", + "380": "titi, titi monkey", + "381": "spider monkey, Ateles geoffroyi", + "382": "squirrel monkey, Saimiri sciureus", + "383": "Madagascar cat, ring-tailed lemur, Lemur catta", + "384": "indri, indris, Indri indri, Indri brevicaudatus", + "385": "Indian elephant, Elephas maximus", + "386": "African elephant, Loxodonta africana", + "387": "lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens", + "388": "giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca", + "389": "barracouta, snoek", + "390": "eel", + "391": "coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch", + "392": "rock beauty, Holocanthus tricolor", + "393": "anemone fish", + "394": "sturgeon", + "395": "gar, garfish, garpike, billfish, Lepisosteus osseus", + "396": "lionfish", + "397": "puffer, pufferfish, blowfish, globefish", + "398": "abacus", + "399": "abaya", + "400": "academic gown, academic robe, judge robe", + "401": "accordion, piano accordion, squeeze box", + "402": "acoustic guitar", + "403": "aircraft carrier, carrier, flattop, attack aircraft carrier", + "404": "airliner", + "405": "airship, dirigible", + "406": "altar", + "407": "ambulance", + "408": "amphibian, amphibious vehicle", + "409": "analog clock", + "410": "apiary, bee house", + "411": "apron", + "412": "ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin", + "413": "assault rifle, assault gun", + "414": "backpack, back pack, knapsack, packsack, rucksack, haversack", + "415": "bakery, bakeshop, bakehouse", + "416": "balance beam, beam", + "417": "balloon", + "418": "ballpoint, ballpoint pen, ballpen, Biro", + "419": "Band Aid", + "420": "banjo", + "421": "bannister, banister, balustrade, balusters, handrail", + "422": "barbell", + "423": "barber chair", + "424": "barbershop", + "425": "barn", + "426": "barometer", + "427": "barrel, cask", + "428": "barrow, garden cart, lawn cart, wheelbarrow", + "429": "baseball", + "430": "basketball", + "431": "bassinet", + "432": "bassoon", + "433": "bathing cap, swimming cap", + "434": "bath towel", + "435": "bathtub, bathing tub, bath, tub", + "436": "beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon", + "437": "beacon, lighthouse, beacon light, pharos", + "438": "beaker", + "439": "bearskin, busby, shako", + "440": "beer bottle", + "441": "beer glass", + "442": "bell cote, bell cot", + "443": "bib", + "444": "bicycle-built-for-two, tandem bicycle, tandem", + "445": "bikini, two-piece", + "446": "binder, ring-binder", + "447": "binoculars, field glasses, opera glasses", + "448": "birdhouse", + "449": "boathouse", + "450": "bobsled, bobsleigh, bob", + "451": "bolo tie, bolo, bola tie, bola", + "452": "bonnet, poke bonnet", + "453": "bookcase", + "454": "bookshop, bookstore, bookstall", + "455": "bottlecap", + "456": "bow", + "457": "bow tie, bow-tie, bowtie", + "458": "brass, memorial tablet, plaque", + "459": "brassiere, bra, bandeau", + "460": "breakwater, groin, groyne, mole, bulwark, seawall, jetty", + "461": "breastplate, aegis, egis", + "462": "broom", + "463": "bucket, pail", + "464": "buckle", + "465": "bulletproof vest", + "466": "bullet train, bullet", + "467": "butcher shop, meat market", + "468": "cab, hack, taxi, taxicab", + "469": "caldron, cauldron", + "470": "candle, taper, wax light", + "471": "cannon", + "472": "canoe", + "473": "can opener, tin opener", + "474": "cardigan", + "475": "car mirror", + "476": "carousel, carrousel, merry-go-round, roundabout, whirligig", + "477": "carpenters kit, tool kit", + "478": "carton", + "479": "car wheel", + "480": "cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM", + "481": "cassette", + "482": "cassette player", + "483": "castle", + "484": "catamaran", + "485": "CD player", + "486": "cello, violoncello", + "487": "cellular telephone, cellular phone, cellphone, cell, mobile phone", + "488": "chain", + "489": "chainlink fence", + "490": "chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour", + "491": "chain saw, chainsaw", + "492": "chest", + "493": "chiffonier, commode", + "494": "chime, bell, gong", + "495": "china cabinet, china closet", + "496": "Christmas stocking", + "497": "church, church building", + "498": "cinema, movie theater, movie theatre, movie house, picture palace", + "499": "cleaver, meat cleaver, chopper", + "500": "cliff dwelling", + "501": "cloak", + "502": "clog, geta, patten, sabot", + "503": "cocktail shaker", + "504": "coffee mug", + "505": "coffeepot", + "506": "coil, spiral, volute, whorl, helix", + "507": "combination lock", + "508": "computer keyboard, keypad", + "509": "confectionery, confectionary, candy store", + "510": "container ship, containership, container vessel", + "511": "convertible", + "512": "corkscrew, bottle screw", + "513": "cornet, horn, trumpet, trump", + "514": "cowboy boot", + "515": "cowboy hat, ten-gallon hat", + "516": "cradle", + "517": "crane", + "518": "crash helmet", + "519": "crate", + "520": "crib, cot", + "521": "Crock Pot", + "522": "croquet ball", + "523": "crutch", + "524": "cuirass", + "525": "dam, dike, dyke", + "526": "desk", + "527": "desktop computer", + "528": "dial telephone, dial phone", + "529": "diaper, nappy, napkin", + "530": "digital clock", + "531": "digital watch", + "532": "dining table, board", + "533": "dishrag, dishcloth", + "534": "dishwasher, dish washer, dishwashing machine", + "535": "disk brake, disc brake", + "536": "dock, dockage, docking facility", + "537": "dogsled, dog sled, dog sleigh", + "538": "dome", + "539": "doormat, welcome mat", + "540": "drilling platform, offshore rig", + "541": "drum, membranophone, tympan", + "542": "drumstick", + "543": "dumbbell", + "544": "Dutch oven", + "545": "electric fan, blower", + "546": "electric guitar", + "547": "electric locomotive", + "548": "entertainment center", + "549": "envelope", + "550": "espresso maker", + "551": "face powder", + "552": "feather boa, boa", + "553": "file, file cabinet, filing cabinet", + "554": "fireboat", + "555": "fire engine, fire truck", + "556": "fire screen, fireguard", + "557": "flagpole, flagstaff", + "558": "flute, transverse flute", + "559": "folding chair", + "560": "football helmet", + "561": "forklift", + "562": "fountain", + "563": "fountain pen", + "564": "four-poster", + "565": "freight car", + "566": "French horn, horn", + "567": "frying pan, frypan, skillet", + "568": "fur coat", + "569": "garbage truck, dustcart", + "570": "gasmask, respirator, gas helmet", + "571": "gas pump, gasoline pump, petrol pump, island dispenser", + "572": "goblet", + "573": "go-kart", + "574": "golf ball", + "575": "golfcart, golf cart", + "576": "gondola", + "577": "gong, tam-tam", + "578": "gown", + "579": "grand piano, grand", + "580": "greenhouse, nursery, glasshouse", + "581": "grille, radiator grille", + "582": "grocery store, grocery, food market, market", + "583": "guillotine", + "584": "hair slide", + "585": "hair spray", + "586": "half track", + "587": "hammer", + "588": "hamper", + "589": "hand blower, blow dryer, blow drier, hair dryer, hair drier", + "590": "hand-held computer, hand-held microcomputer", + "591": "handkerchief, hankie, hanky, hankey", + "592": "hard disc, hard disk, fixed disk", + "593": "harmonica, mouth organ, harp, mouth harp", + "594": "harp", + "595": "harvester, reaper", + "596": "hatchet", + "597": "holster", + "598": "home theater, home theatre", + "599": "honeycomb", + "600": "hook, claw", + "601": "hoopskirt, crinoline", + "602": "horizontal bar, high bar", + "603": "horse cart, horse-cart", + "604": "hourglass", + "605": "iPod", + "606": "iron, smoothing iron", + "607": "jack-o-lantern", + "608": "jean, blue jean, denim", + "609": "jeep, landrover", + "610": "jersey, T-shirt, tee shirt", + "611": "jigsaw puzzle", + "612": "jinrikisha, ricksha, rickshaw", + "613": "joystick", + "614": "kimono", + "615": "knee pad", + "616": "knot", + "617": "lab coat, laboratory coat", + "618": "ladle", + "619": "lampshade, lamp shade", + "620": "laptop, laptop computer", + "621": "lawn mower, mower", + "622": "lens cap, lens cover", + "623": "letter opener, paper knife, paperknife", + "624": "library", + "625": "lifeboat", + "626": "lighter, light, igniter, ignitor", + "627": "limousine, limo", + "628": "liner, ocean liner", + "629": "lipstick, lip rouge", + "630": "Loafer", + "631": "lotion", + "632": "loudspeaker, speaker, speaker unit, loudspeaker system, speaker system", + "633": "loupe, jewelers loupe", + "634": "lumbermill, sawmill", + "635": "magnetic compass", + "636": "mailbag, postbag", + "637": "mailbox, letter box", + "638": "maillot", + "639": "maillot, tank suit", + "640": "manhole cover", + "641": "maraca", + "642": "marimba, xylophone", + "643": "mask", + "644": "matchstick", + "645": "maypole", + "646": "maze, labyrinth", + "647": "measuring cup", + "648": "medicine chest, medicine cabinet", + "649": "megalith, megalithic structure", + "650": "microphone, mike", + "651": "microwave, microwave oven", + "652": "military uniform", + "653": "milk can", + "654": "minibus", + "655": "miniskirt, mini", + "656": "minivan", + "657": "missile", + "658": "mitten", + "659": "mixing bowl", + "660": "mobile home, manufactured home", + "661": "Model T", + "662": "modem", + "663": "monastery", + "664": "monitor", + "665": "moped", + "666": "mortar", + "667": "mortarboard", + "668": "mosque", + "669": "mosquito net", + "670": "motor scooter, scooter", + "671": "mountain bike, all-terrain bike, off-roader", + "672": "mountain tent", + "673": "mouse, computer mouse", + "674": "mousetrap", + "675": "moving van", + "676": "muzzle", + "677": "nail", + "678": "neck brace", + "679": "necklace", + "680": "nipple", + "681": "notebook, notebook computer", + "682": "obelisk", + "683": "oboe, hautboy, hautbois", + "684": "ocarina, sweet potato", + "685": "odometer, hodometer, mileometer, milometer", + "686": "oil filter", + "687": "organ, pipe organ", + "688": "oscilloscope, scope, cathode-ray oscilloscope, CRO", + "689": "overskirt", + "690": "oxcart", + "691": "oxygen mask", + "692": "packet", + "693": "paddle, boat paddle", + "694": "paddlewheel, paddle wheel", + "695": "padlock", + "696": "paintbrush", + "697": "pajama, pyjama, pjs, jammies", + "698": "palace", + "699": "panpipe, pandean pipe, syrinx", + "700": "paper towel", + "701": "parachute, chute", + "702": "parallel bars, bars", + "703": "park bench", + "704": "parking meter", + "705": "passenger car, coach, carriage", + "706": "patio, terrace", + "707": "pay-phone, pay-station", + "708": "pedestal, plinth, footstall", + "709": "pencil box, pencil case", + "710": "pencil sharpener", + "711": "perfume, essence", + "712": "Petri dish", + "713": "photocopier", + "714": "pick, plectrum, plectron", + "715": "pickelhaube", + "716": "picket fence, paling", + "717": "pickup, pickup truck", + "718": "pier", + "719": "piggy bank, penny bank", + "720": "pill bottle", + "721": "pillow", + "722": "ping-pong ball", + "723": "pinwheel", + "724": "pirate, pirate ship", + "725": "pitcher, ewer", + "726": "plane, carpenters plane, woodworking plane", + "727": "planetarium", + "728": "plastic bag", + "729": "plate rack", + "730": "plow, plough", + "731": "plunger, plumbers helper", + "732": "Polaroid camera, Polaroid Land camera", + "733": "pole", + "734": "police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria", + "735": "poncho", + "736": "pool table, billiard table, snooker table", + "737": "pop bottle, soda bottle", + "738": "pot, flowerpot", + "739": "potters wheel", + "740": "power drill", + "741": "prayer rug, prayer mat", + "742": "printer", + "743": "prison, prison house", + "744": "projectile, missile", + "745": "projector", + "746": "puck, hockey puck", + "747": "punching bag, punch bag, punching ball, punchball", + "748": "purse", + "749": "quill, quill pen", + "750": "quilt, comforter, comfort, puff", + "751": "racer, race car, racing car", + "752": "racket, racquet", + "753": "radiator", + "754": "radio, wireless", + "755": "radio telescope, radio reflector", + "756": "rain barrel", + "757": "recreational vehicle, RV, R.V.", + "758": "reel", + "759": "reflex camera", + "760": "refrigerator, icebox", + "761": "remote control, remote", + "762": "restaurant, eating house, eating place, eatery", + "763": "revolver, six-gun, six-shooter", + "764": "rifle", + "765": "rocking chair, rocker", + "766": "rotisserie", + "767": "rubber eraser, rubber, pencil eraser", + "768": "rugby ball", + "769": "rule, ruler", + "770": "running shoe", + "771": "safe", + "772": "safety pin", + "773": "saltshaker, salt shaker", + "774": "sandal", + "775": "sarong", + "776": "sax, saxophone", + "777": "scabbard", + "778": "scale, weighing machine", + "779": "school bus", + "780": "schooner", + "781": "scoreboard", + "782": "screen, CRT screen", + "783": "screw", + "784": "screwdriver", + "785": "seat belt, seatbelt", + "786": "sewing machine", + "787": "shield, buckler", + "788": "shoe shop, shoe-shop, shoe store", + "789": "shoji", + "790": "shopping basket", + "791": "shopping cart", + "792": "shovel", + "793": "shower cap", + "794": "shower curtain", + "795": "ski", + "796": "ski mask", + "797": "sleeping bag", + "798": "slide rule, slipstick", + "799": "sliding door", + "800": "slot, one-armed bandit", + "801": "snorkel", + "802": "snowmobile", + "803": "snowplow, snowplough", + "804": "soap dispenser", + "805": "soccer ball", + "806": "sock", + "807": "solar dish, solar collector, solar furnace", + "808": "sombrero", + "809": "soup bowl", + "810": "space bar", + "811": "space heater", + "812": "space shuttle", + "813": "spatula", + "814": "speedboat", + "815": "spider web, spiders web", + "816": "spindle", + "817": "sports car, sport car", + "818": "spotlight, spot", + "819": "stage", + "820": "steam locomotive", + "821": "steel arch bridge", + "822": "steel drum", + "823": "stethoscope", + "824": "stole", + "825": "stone wall", + "826": "stopwatch, stop watch", + "827": "stove", + "828": "strainer", + "829": "streetcar, tram, tramcar, trolley, trolley car", + "830": "stretcher", + "831": "studio couch, day bed", + "832": "stupa, tope", + "833": "submarine, pigboat, sub, U-boat", + "834": "suit, suit of clothes", + "835": "sundial", + "836": "sunglass", + "837": "sunglasses, dark glasses, shades", + "838": "sunscreen, sunblock, sun blocker", + "839": "suspension bridge", + "840": "swab, swob, mop", + "841": "sweatshirt", + "842": "swimming trunks, bathing trunks", + "843": "swing", + "844": "switch, electric switch, electrical switch", + "845": "syringe", + "846": "table lamp", + "847": "tank, army tank, armored combat vehicle, armoured combat vehicle", + "848": "tape player", + "849": "teapot", + "850": "teddy, teddy bear", + "851": "television, television system", + "852": "tennis ball", + "853": "thatch, thatched roof", + "854": "theater curtain, theatre curtain", + "855": "thimble", + "856": "thresher, thrasher, threshing machine", + "857": "throne", + "858": "tile roof", + "859": "toaster", + "860": "tobacco shop, tobacconist shop, tobacconist", + "861": "toilet seat", + "862": "torch", + "863": "totem pole", + "864": "tow truck, tow car, wrecker", + "865": "toyshop", + "866": "tractor", + "867": "trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi", + "868": "tray", + "869": "trench coat", + "870": "tricycle, trike, velocipede", + "871": "trimaran", + "872": "tripod", + "873": "triumphal arch", + "874": "trolleybus, trolley coach, trackless trolley", + "875": "trombone", + "876": "tub, vat", + "877": "turnstile", + "878": "typewriter keyboard", + "879": "umbrella", + "880": "unicycle, monocycle", + "881": "upright, upright piano", + "882": "vacuum, vacuum cleaner", + "883": "vase", + "884": "vault", + "885": "velvet", + "886": "vending machine", + "887": "vestment", + "888": "viaduct", + "889": "violin, fiddle", + "890": "volleyball", + "891": "waffle iron", + "892": "wall clock", + "893": "wallet, billfold, notecase, pocketbook", + "894": "wardrobe, closet, press", + "895": "warplane, military plane", + "896": "washbasin, handbasin, washbowl, lavabo, wash-hand basin", + "897": "washer, automatic washer, washing machine", + "898": "water bottle", + "899": "water jug", + "900": "water tower", + "901": "whiskey jug", + "902": "whistle", + "903": "wig", + "904": "window screen", + "905": "window shade", + "906": "Windsor tie", + "907": "wine bottle", + "908": "wing", + "909": "wok", + "910": "wooden spoon", + "911": "wool, woolen, woollen", + "912": "worm fence, snake fence, snake-rail fence, Virginia fence", + "913": "wreck", + "914": "yawl", + "915": "yurt", + "916": "web site, website, internet site, site", + "917": "comic book", + "918": "crossword puzzle, crossword", + "919": "street sign", + "920": "traffic light, traffic signal, stoplight", + "921": "book jacket, dust cover, dust jacket, dust wrapper", + "922": "menu", + "923": "plate", + "924": "guacamole", + "925": "consomme", + "926": "hot pot, hotpot", + "927": "trifle", + "928": "ice cream, icecream", + "929": "ice lolly, lolly, lollipop, popsicle", + "930": "French loaf", + "931": "bagel, beigel", + "932": "pretzel", + "933": "cheeseburger", + "934": "hotdog, hot dog, red hot", + "935": "mashed potato", + "936": "head cabbage", + "937": "broccoli", + "938": "cauliflower", + "939": "zucchini, courgette", + "940": "spaghetti squash", + "941": "acorn squash", + "942": "butternut squash", + "943": "cucumber, cuke", + "944": "artichoke, globe artichoke", + "945": "bell pepper", + "946": "cardoon", + "947": "mushroom", + "948": "Granny Smith", + "949": "strawberry", + "950": "orange", + "951": "lemon", + "952": "fig", + "953": "pineapple, ananas", + "954": "banana", + "955": "jackfruit, jak, jack", + "956": "custard apple", + "957": "pomegranate", + "958": "hay", + "959": "carbonara", + "960": "chocolate sauce, chocolate syrup", + "961": "dough", + "962": "meat loaf, meatloaf", + "963": "pizza, pizza pie", + "964": "potpie", + "965": "burrito", + "966": "red wine", + "967": "espresso", + "968": "cup", + "969": "eggnog", + "970": "alp", + "971": "bubble", + "972": "cliff, drop, drop-off", + "973": "coral reef", + "974": "geyser", + "975": "lakeside, lakeshore", + "976": "promontory, headland, head, foreland", + "977": "sandbar, sand bar", + "978": "seashore, coast, seacoast, sea-coast", + "979": "valley, vale", + "980": "volcano", + "981": "ballplayer, baseball player", + "982": "groom, bridegroom", + "983": "scuba diver", + "984": "rapeseed", + "985": "daisy", + "986": "yellow ladys slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum", + "987": "corn", + "988": "acorn", + "989": "hip, rose hip, rosehip", + "990": "buckeye, horse chestnut, conker", + "991": "coral fungus", + "992": "agaric", + "993": "gyromitra", + "994": "stinkhorn, carrion fungus", + "995": "earthstar", + "996": "hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa", + "997": "bolete", + "998": "ear, spike, capitulum", + "999": "toilet tissue, toilet paper, bathroom tissue" + }, + "scheduler": [ + "scheduling_flow_match_pae", + "PAEFlowMatchScheduler" + ], + "transformers": [ + "transformer_lightning_dit", + "LightningDiT2DModel" + ] +} diff --git a/pae-dinov3-large-d32/pipeline.py b/pae-dinov3-large-d32/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..baed829d24d510b38fe9905fd001b835a176475f --- /dev/null +++ b/pae-dinov3-large-d32/pipeline.py @@ -0,0 +1,530 @@ +"""Hub custom pipeline: PAEPipeline. +Load with native Hugging Face diffusers and trust_remote_code=True. +""" + +from __future__ import annotations + +# Copyright 2026 The HuggingFace Team and PAE authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import inspect +import json +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple, Union + +import torch + +from diffusers.image_processor import VaeImageProcessor +from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput +from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers +from diffusers.utils.torch_utils import randn_tensor + +EXAMPLE_DOC_STRING = """ + Examples: + ```py + >>> from pathlib import Path + >>> from diffusers import DiffusionPipeline + >>> import torch + + >>> model_dir = Path("./pae-dinov2-large-d32").resolve() + >>> pipe = DiffusionPipeline.from_pretrained( + ... str(model_dir), + ... local_files_only=True, + ... custom_pipeline=str(model_dir / "pipeline.py"), + ... trust_remote_code=True, + ... torch_dtype=torch.bfloat16, + ... ) + >>> pipe.to("cuda") + + >>> print(pipe.id2label[207]) + >>> print(pipe.get_label_ids("golden retriever")) + + >>> generator = torch.Generator(device="cuda").manual_seed(42) + >>> image = pipe( + ... class_labels="golden retriever", + ... generator=generator, + ... ).images[0] + ``` +""" + + +class PAEPipeline(DiffusionPipeline): + r""" + Pipeline for class-conditional image generation with PAE tokenizers and LightningDiT. + + This model inherits from [`DiffusionPipeline`]. Components are stored in separate subfolders + (`transformers/`, `scheduler/`, `decoder/`) and loaded via `DiffusionPipeline.from_pretrained`. + + Parameters: + transformers ([`LightningDiT2DModel`]): + Class-conditional LightningDiT transformer that predicts flow-matching velocity in PAE latent space. + scheduler ([`PAEFlowMatchScheduler`]): + Flow-matching ODE/SDE scheduler. Other [`KarrasDiffusionSchedulers`] can be swapped at inference time + when their `step` API is compatible. + decoder ([`PAEDecoder`]): + Prior-Aligned Autoencoder decoder stack (decompressor + pixel decoder). + + ImageNet `id2label` mappings are read lazily from `model_index.json` when label helpers are used. + """ + + model_cpu_offload_seq = "transformers->decoder" + _optional_components = ["decoder"] + + @staticmethod + def prepare_extra_step_kwargs( + scheduler: KarrasDiffusionSchedulers, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + eta: Optional[float] = None, + ) -> Dict[str, object]: + r""" + Build kwargs forwarded to `scheduler.step` when supported. + + Args: + scheduler: + Active diffusion scheduler instance. + generator: + Optional RNG passed through to stochastic scheduler steps. + eta: + Optional DDIM-style eta when the scheduler accepts it. + """ + kwargs: Dict[str, object] = {} + step_params = set(inspect.signature(scheduler.step).parameters.keys()) + if "generator" in step_params: + kwargs["generator"] = generator + if eta is not None and "eta" in step_params: + kwargs["eta"] = eta + return kwargs + + def __init__( + self, + transformers, + scheduler: KarrasDiffusionSchedulers, + decoder=None, + transformer=None, + ) -> None: + if transformer is not None and transformers is None: + transformers = transformer + super().__init__() + self.register_modules(transformers=transformers, scheduler=scheduler, decoder=decoder) + # PAE decoders already return pixels in [0, 1]; disable VAE-style [-1, 1] denormalization. + self.image_processor = VaeImageProcessor(do_normalize=False) + self._id2label: Dict[int, str] = {} + self.labels: Dict[str, int] = {} + self._labels_loaded_from_model_index = False + + @property + def transformer(self): + """Backward-compatible alias for `transformers`.""" + return self.transformers + + @staticmethod + def _normalize_id2label(id2label: Optional[Dict[Union[int, str], str]]) -> Dict[int, str]: + if not id2label: + return {} + return {int(key): value for key, value in id2label.items()} + + @staticmethod + def _read_model_index(variant_path: Optional[str]) -> Dict[str, Any]: + if not variant_path: + return {} + variant_dir = Path(variant_path).resolve() + model_index_path = variant_dir / "model_index.json" + if not model_index_path.is_file(): + return {} + raw = json.loads(model_index_path.read_text(encoding="utf-8")) + return raw if isinstance(raw, dict) else {} + + @staticmethod + def _read_id2label_from_model_index(variant_path: Optional[str]) -> Dict[int, str]: + id2label = PAEPipeline._read_model_index(variant_path).get("id2label") + if not isinstance(id2label, dict): + return {} + return {int(key): value for key, value in id2label.items()} + + def _get_downsample_ratio(self) -> int: + override = getattr(self.config, "downsample_ratio", None) + if override is not None: + return int(override) + + encoder_input_size = None + if self.decoder is not None: + encoder_input_size = getattr(self.decoder.config, "encoder_input_size", None) + + if encoder_input_size is not None: + return int(encoder_input_size) // int(self.transformers.config.input_size) + return 16 + + def _resolve_latent_stats( + self, + latent_mean: Optional[torch.Tensor], + latent_std: Optional[torch.Tensor], + latent_multiplier: Optional[float], + device: torch.device, + dtype: torch.dtype, + ) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], float]: + if latent_mean is not None and latent_std is not None: + return latent_mean, latent_std, float(latent_multiplier if latent_multiplier is not None else 1.0) + + decoder_cfg = getattr(self.decoder, "config", None) if self.decoder is not None else None + if decoder_cfg is not None: + mean = getattr(decoder_cfg, "latent_mean", None) + std = getattr(decoder_cfg, "latent_std", None) + if mean is not None and std is not None: + multiplier = getattr(decoder_cfg, "latent_multiplier", 1.0) + mean_tensor = torch.tensor(mean, device=device, dtype=dtype).view(1, -1, 1, 1) + std_tensor = torch.tensor(std, device=device, dtype=dtype).view(1, -1, 1, 1) + return mean_tensor, std_tensor, float(multiplier) + + return latent_mean, latent_std, float(latent_multiplier if latent_multiplier is not None else 1.0) + + @staticmethod + def _build_label2id(id2label: Dict[int, str]) -> Dict[str, int]: + label2id: Dict[str, int] = {} + for class_id, value in id2label.items(): + for synonym in value.split(","): + synonym = synonym.strip() + if synonym: + label2id[synonym] = int(class_id) + return dict(sorted(label2id.items())) + + def _ensure_labels_loaded(self) -> None: + if self._labels_loaded_from_model_index: + return + loaded = self._read_id2label_from_model_index(getattr(self.config, "_name_or_path", None)) + if loaded: + self._id2label = loaded + self.labels = self._build_label2id(self._id2label) + self._labels_loaded_from_model_index = True + + @property + def id2label(self) -> Dict[int, str]: + r"""ImageNet class id to English label string (comma-separated synonyms).""" + self._ensure_labels_loaded() + return self._id2label + + def get_label_ids(self, label: Union[str, List[str]]) -> List[int]: + r""" + Map ImageNet label strings to class ids. + + Args: + label: + One or more English label strings. Each string must match a synonym in `id2label`. + + Returns: + Matching ImageNet class ids. + """ + self._ensure_labels_loaded() + label2id = self.labels + if not label2id: + raise ValueError("No English labels loaded. Ensure `id2label` exists in model_index.json.") + + if isinstance(label, str): + label = [label] + + missing = [item for item in label if item not in label2id] + if missing: + preview = ", ".join(list(label2id.keys())[:8]) + raise ValueError(f"Unknown English label(s): {missing}. Example valid labels: {preview}, ...") + return [label2id[item] for item in label] + + def _default_image_size(self) -> int: + return int(self.transformers.config.input_size) * self._get_downsample_ratio() + + def _normalize_class_labels( + self, + class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor], + ) -> torch.LongTensor: + if torch.is_tensor(class_labels): + return class_labels.to(device=self._execution_device, dtype=torch.long).reshape(-1) + + if isinstance(class_labels, int): + class_label_ids = [class_labels] + elif isinstance(class_labels, str): + class_label_ids = self.get_label_ids(class_labels) + elif class_labels and isinstance(class_labels[0], str): + class_label_ids = self.get_label_ids(class_labels) + else: + class_label_ids = list(class_labels) + + return torch.tensor(class_label_ids, device=self._execution_device, dtype=torch.long).reshape(-1) + + def check_inputs( + self, + height: int, + width: int, + num_inference_steps: int, + output_type: str, + mode: str, + ) -> None: + if num_inference_steps < 1: + raise ValueError("num_inference_steps must be >= 1.") + if output_type not in {"pil", "np", "pt", "latent"}: + raise ValueError("output_type must be one of: 'pil', 'np', 'pt', 'latent'.") + if mode not in {"ode", "sde"}: + raise ValueError("mode must be either 'ode' or 'sde'.") + + downsample = self._get_downsample_ratio() + if height % downsample != 0 or width % downsample != 0: + raise ValueError( + f"height and width must be divisible by the PAE downsample factor {downsample}." + ) + + latent_height = height // downsample + latent_width = width // downsample + expected_size = int(self.transformers.config.input_size) + if latent_height != expected_size or latent_width != expected_size: + raise ValueError( + f"Requested latent size {(latent_height, latent_width)} does not match the pretrained " + f"transformer input_size={expected_size}. Use height=width={self._default_image_size()}." + ) + + def prepare_latents( + self, + batch_size: int, + height: int, + width: int, + dtype: torch.dtype, + device: torch.device, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + ) -> torch.Tensor: + downsample = self._get_downsample_ratio() + latent_height = height // downsample + latent_width = width // downsample + return randn_tensor( + (batch_size, self.transformers.config.in_channels, latent_height, latent_width), + generator=generator, + device=device, + dtype=dtype, + ) + + @staticmethod + def _denormalize_latents( + latents: torch.Tensor, + latent_mean: Optional[torch.Tensor], + latent_std: Optional[torch.Tensor], + latent_multiplier: Optional[float], + ) -> torch.Tensor: + if latent_mean is None or latent_std is None: + return latents + multiplier = 1.0 if latent_multiplier is None else float(latent_multiplier) + mean = latent_mean.to(device=latents.device, dtype=latents.dtype) + std = latent_std.to(device=latents.device, dtype=latents.dtype) + return (latents * std) / multiplier + mean + + @staticmethod + def _apply_cfg( + model_output: torch.Tensor, + guidance_scale: float, + guidance_active: bool, + cfg_channels: int, + ) -> torch.Tensor: + if guidance_scale <= 1.0 or not guidance_active: + return model_output + eps, rest = model_output[:, :cfg_channels], model_output[:, cfg_channels:] + cond_eps, uncond_eps = torch.chunk(eps, 2, dim=0) + half_eps = uncond_eps + guidance_scale * (cond_eps - uncond_eps) + if rest.shape[1] == 0: + return half_eps + return torch.cat([half_eps, rest], dim=1) + + def decode_latents( + self, + latents: torch.Tensor, + output_type: str = "pil", + latent_mean: Optional[torch.Tensor] = None, + latent_std: Optional[torch.Tensor] = None, + latent_multiplier: Optional[float] = None, + ): + if output_type == "latent": + return latents + if self.decoder is None: + raise ValueError("PAEPipeline requires a PAE decoder component for decoding.") + + latent_mean, latent_std, latent_multiplier = self._resolve_latent_stats( + latent_mean, + latent_std, + latent_multiplier, + device=latents.device, + dtype=latents.dtype, + ) + latents = self._denormalize_latents(latents, latent_mean, latent_std, latent_multiplier) + image = self.decoder.decode(latents) + image = torch.clamp(image, 0.0, 1.0) + if output_type == "pt": + return image + return self.image_processor.postprocess(image, output_type=output_type, do_denormalize=[False] * image.shape[0]) + + @torch.inference_mode() + def __call__( + self, + class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor], + height: Optional[int] = None, + width: Optional[int] = None, + num_inference_steps: int = 250, + guidance_scale: float = 3.3, + guidance_interval: Tuple[float, float] = (0.0, 1.0), + cfg_interval_start: float = 0.3, + timestep_shift: float = 0.4, + mode: str = "ode", + heun: bool = False, + latent_mean: Optional[torch.Tensor] = None, + latent_std: Optional[torch.Tensor] = None, + latent_multiplier: Optional[float] = None, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + output_type: str = "pil", + return_dict: bool = True, + ) -> Union[ImagePipelineOutput, Tuple]: + r""" + Generate class-conditional images with PAE + LightningDiT. + + Args: + class_labels: + ImageNet class indices or human-readable English label strings. + height: + Output image height in pixels. Defaults to the pretrained native resolution. + width: + Output image width in pixels. Defaults to the pretrained native resolution. + num_inference_steps: + Number of flow-matching integration steps. + guidance_scale: + Classifier-free guidance scale. Active when `guidance_scale > 1.0`. + guidance_interval: + Timestep interval `(low, high)` where CFG is applied. + cfg_interval_start: + Disable CFG below this normalized timestep value. Default `0.3` matches DiT training configs. + timestep_shift: + Timestep warping used by LightningDiT ODE sampling. Default `0.4` matches DiT training configs. + mode: + Sampling mode passed to the PAE flow scheduler: `"ode"` or `"sde"`. + heun: + Use Heun integration for ODE sampling when True. + latent_mean: + Optional latent mean tensor for denormalization before PAE decode. Defaults to + `latent_mean` in `decoder/config.json` when omitted. + latent_std: + Optional latent std tensor for denormalization before PAE decode. Defaults to + `latent_std` in `decoder/config.json` when omitted. + latent_multiplier: + Divisor applied with `latent_std` during denormalization. Defaults to + `latent_multiplier` in `decoder/config.json` or `1.0`. + generator: + RNG for reproducibility. + output_type: + `"pil"`, `"np"`, `"pt"`, or `"latent"`. + return_dict: + Return [`ImagePipelineOutput`] if True. + """ + default_size = self._default_image_size() + height = int(height or default_size) + width = int(width or default_size) + self.check_inputs(height, width, num_inference_steps, output_type, mode) + + device = self._execution_device + model_dtype = next(self.transformers.parameters()).dtype + class_labels_tensor = self._normalize_class_labels(class_labels) + batch_size = class_labels_tensor.numel() + null_label = int(self.transformers.config.num_classes) + null_labels = torch.full((batch_size,), null_label, device=device, dtype=torch.long) + cfg_channels = int(self.transformers.config.in_channels) + + latents = self.prepare_latents( + batch_size=batch_size, + height=height, + width=width, + dtype=model_dtype, + device=device, + generator=generator, + ) + timesteps = self.scheduler.set_timesteps( + num_inference_steps, device=device, mode=mode, timestep_shift=timestep_shift + ) + extra_step_kwargs = self.prepare_extra_step_kwargs(self.scheduler, generator=generator) + + for index, timestep in enumerate(timesteps[:-1]): + next_timestep = timesteps[index + 1] + t_value = float(timestep) + guidance_active = guidance_scale > 1.0 and guidance_interval[0] <= t_value <= guidance_interval[1] + if cfg_interval_start is not None and t_value < cfg_interval_start: + guidance_active = False + + if guidance_active: + model_input = torch.cat([latents, latents], dim=0) + labels = torch.cat([class_labels_tensor, null_labels], dim=0) + else: + model_input = latents + labels = class_labels_tensor + + timestep_batch = torch.full((labels.shape[0],), t_value, device=device, dtype=model_dtype) + model_output = self.transformers( + model_input.to(dtype=model_dtype), + timestep=timestep_batch, + class_labels=labels, + return_dict=True, + ).sample + model_output = self._apply_cfg(model_output, guidance_scale, guidance_active, cfg_channels) + + if heun and mode == "ode" and index < len(timesteps) - 2: + provisional = self.scheduler.step( + model_output, + timestep[None], + latents, + next_timestep[None], + **extra_step_kwargs, + ).prev_sample + if guidance_active: + prime_input = torch.cat([provisional, provisional], dim=0) + prime_labels = torch.cat([class_labels_tensor, null_labels], dim=0) + else: + prime_input = provisional + prime_labels = class_labels_tensor + next_timestep_batch = torch.full( + (prime_labels.shape[0],), float(next_timestep), device=device, dtype=model_dtype + ) + next_output = self.transformers( + prime_input.to(dtype=model_dtype), + timestep=next_timestep_batch, + class_labels=prime_labels, + return_dict=True, + ).sample + next_output = self._apply_cfg(next_output, guidance_scale, guidance_active, cfg_channels) + latents = self.scheduler.step_heun( + model_output, next_output, timestep[None], latents, next_timestep[None] + ).prev_sample + else: + latents = self.scheduler.step( + model_output, + timestep[None], + latents, + next_timestep[None], + **extra_step_kwargs, + ).prev_sample + + image = self.decode_latents( + latents.to(dtype=model_dtype), + output_type=output_type, + latent_mean=latent_mean, + latent_std=latent_std, + latent_multiplier=latent_multiplier, + ) + + self.maybe_free_model_hooks() + if not return_dict: + return (image,) + return ImagePipelineOutput(images=image) + + +# Backward-compatible alias used by earlier PAE-diffusers releases. +PAEPipelineOutput = ImagePipelineOutput diff --git a/pae-dinov3-large-d32/scheduler/scheduler_config.json b/pae-dinov3-large-d32/scheduler/scheduler_config.json new file mode 100644 index 0000000000000000000000000000000000000000..75d51d14e68c7500bbb2ddd937dc7669b8d3e27d --- /dev/null +++ b/pae-dinov3-large-d32/scheduler/scheduler_config.json @@ -0,0 +1,7 @@ +{ + "_class_name": "PAEFlowMatchScheduler", + "_diffusers_version": "0.31.0", + "mode": "ode", + "path_type": "linear", + "num_train_timesteps": 1000 +} diff --git a/pae-dinov3-large-d32/scheduler/scheduling_flow_match_pae.py b/pae-dinov3-large-d32/scheduler/scheduling_flow_match_pae.py new file mode 100644 index 0000000000000000000000000000000000000000..e79368596bb250ea5689e1775d653291ab6e55c1 --- /dev/null +++ b/pae-dinov3-large-d32/scheduler/scheduling_flow_match_pae.py @@ -0,0 +1,200 @@ +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. + +from dataclasses import dataclass +from typing import Optional, Tuple + +import numpy as np +import torch + +try: + from diffusers.configuration_utils import ConfigMixin, register_to_config + from diffusers.schedulers.scheduling_utils import SchedulerMixin + from diffusers.utils import BaseOutput +except Exception: # pragma: no cover - importable without an installed diffusers checkout. + class BaseOutput(dict): + def __post_init__(self): + self.update(self.__dict__) + + class ConfigMixin: + config_name = "scheduler_config.json" + + class SchedulerMixin: + pass + + def register_to_config(init): + return init + + +@dataclass +class PAEFlowMatchSchedulerOutput(BaseOutput): + prev_sample: torch.FloatTensor + + +class PAEFlowMatchScheduler(SchedulerMixin, ConfigMixin): + """ + Flow-matching ODE/SDE scheduler used by PAE + LightningDiT pipelines. + + The model predicts velocity with a linear path by default. ODE timesteps run from 0 to 1 + (noise to data), matching LightningDiT transport sampling. + """ + + config_name = "scheduler_config.json" + order = 1 + + @register_to_config + def __init__( + self, + mode: str = "ode", + path_type: str = "linear", + num_train_timesteps: int = 1000, + ): + if mode not in {"ode", "sde"}: + raise ValueError("mode must be either 'ode' or 'sde'.") + if path_type not in {"linear", "cosine"}: + raise ValueError("path_type must be either 'linear' or 'cosine'.") + self.mode = mode + self.path_type = path_type + self.num_train_timesteps = num_train_timesteps + # Native NiT integrates in float64 for better numerical stability. + self.timesteps = torch.from_numpy(np.linspace(0.0, 1.0, num_train_timesteps + 1)).to(dtype=torch.float64) + + @staticmethod + def _apply_timestep_shift(timesteps: torch.Tensor, timestep_shift: float) -> torch.Tensor: + if timestep_shift <= 0: + return timesteps + return timestep_shift * timesteps / (1 + (timestep_shift - 1) * timesteps) + + def set_timesteps( + self, + num_inference_steps: int, + device: Optional[torch.device] = None, + mode: Optional[str] = None, + timestep_shift: float = 0.0, + ): + mode = mode or self.mode + dtype = self.timesteps.dtype + if mode == "sde": + timesteps = torch.linspace(1.0, 0.04, num_inference_steps, dtype=dtype) + timesteps = torch.cat([timesteps, torch.zeros(1, dtype=dtype)]) + elif mode == "ode": + timesteps = torch.linspace(0.0, 1.0, num_inference_steps + 1, dtype=dtype) + timesteps = self._apply_timestep_shift(timesteps, timestep_shift) + else: + raise ValueError("mode must be either 'ode' or 'sde'.") + self.mode = mode + self.timesteps = timesteps.to(device=device) + return self.timesteps + + @staticmethod + def _expand_t_like_sample(timestep: torch.Tensor, sample: torch.Tensor, image_sizes: torch.LongTensor): + dims = [1] * (sample.ndim - 1) + seqlens = image_sizes[:, 0] * image_sizes[:, 1] + if timestep.numel() == 1: + timestep = timestep.repeat(image_sizes.shape[0]) + return torch.cat( + [timestep[i].reshape(1, *dims).repeat(int(seqlens[i]), *dims) for i in range(image_sizes.shape[0])] + ) + + def _get_score_from_velocity( + self, + model_output: torch.Tensor, + sample: torch.Tensor, + timestep: torch.Tensor, + image_sizes: torch.LongTensor, + ): + timestep = self._expand_t_like_sample(timestep, sample, image_sizes) + if self.path_type == "linear": + alpha_t, d_alpha_t = 1 - timestep, torch.ones_like(timestep) * -1 + sigma_t, d_sigma_t = timestep, torch.ones_like(timestep) + elif self.path_type == "cosine": + alpha_t = torch.cos(timestep * np.pi / 2) + sigma_t = torch.sin(timestep * np.pi / 2) + d_alpha_t = -np.pi / 2 * torch.sin(timestep * np.pi / 2) + d_sigma_t = np.pi / 2 * torch.cos(timestep * np.pi / 2) + else: + raise ValueError(f"Unsupported path_type: {self.path_type}") + reverse_alpha_ratio = alpha_t / d_alpha_t + variance = sigma_t**2 - reverse_alpha_ratio * d_sigma_t * sigma_t + return (reverse_alpha_ratio * model_output - sample) / variance + + @staticmethod + def _compute_diffusion(timestep: torch.Tensor): + return 2 * timestep + + @staticmethod + def _promote_dtypes(*tensors: torch.Tensor) -> torch.dtype: + dtype = None + for tensor in tensors: + if tensor.is_floating_point() or tensor.is_complex(): + dtype = tensor.dtype if dtype is None else torch.promote_types(dtype, tensor.dtype) + return dtype if dtype is not None else torch.get_default_dtype() + + def step( + self, + model_output: torch.Tensor, + timestep: torch.Tensor, + sample: torch.Tensor, + next_timestep: torch.Tensor, + image_sizes: Optional[torch.LongTensor] = None, + generator: Optional[torch.Generator] = None, + return_dict: bool = True, + ) -> PAEFlowMatchSchedulerOutput: + sample_dtype = sample.dtype + compute_dtype = torch.float64 + sample = sample.to(dtype=compute_dtype) + model_output = model_output.to(dtype=compute_dtype) + timestep = timestep.to(device=sample.device, dtype=compute_dtype).flatten() + next_timestep = next_timestep.to(device=sample.device, dtype=compute_dtype).flatten() + + if self.mode == "ode": + prev_sample = sample + (next_timestep[0] - timestep[0]) * model_output + else: + if image_sizes is None: + batch = sample.shape[0] + side = int(sample.shape[-1]) + image_sizes = torch.tensor([[side, side]] * batch, device=sample.device, dtype=torch.long) + image_sizes = image_sizes.to(device=sample.device, dtype=torch.long) + diffusion = self._compute_diffusion(timestep[0]) + score = self._get_score_from_velocity(model_output, sample, timestep, image_sizes) + drift = model_output - 0.5 * diffusion * score + dt = next_timestep[0] - timestep[0] + if torch.allclose(next_timestep[0], torch.zeros_like(next_timestep[0])): + prev_sample = sample + drift * dt + else: + if generator is not None: + noise = torch.randn(sample.shape, generator=generator, device=sample.device, dtype=sample.dtype) + else: + noise = torch.randn_like(sample) + prev_sample = sample + drift * dt + torch.sqrt(diffusion) * noise * torch.sqrt(torch.abs(dt)) + + prev_sample = prev_sample.to(sample_dtype) + if not return_dict: + return (prev_sample,) + return PAEFlowMatchSchedulerOutput(prev_sample=prev_sample) + + def step_heun( + self, + model_output: torch.Tensor, + next_model_output: torch.Tensor, + timestep: torch.Tensor, + sample: torch.Tensor, + next_timestep: torch.Tensor, + return_dict: bool = True, + ) -> PAEFlowMatchSchedulerOutput: + if self.mode != "ode": + raise ValueError("Heun correction is only defined for ODE sampling.") + sample_dtype = sample.dtype + compute_dtype = torch.float64 + sample = sample.to(dtype=compute_dtype) + model_output = model_output.to(dtype=compute_dtype) + next_model_output = next_model_output.to(dtype=compute_dtype) + timestep = timestep.to(device=sample.device, dtype=compute_dtype).flatten() + next_timestep = next_timestep.to(device=sample.device, dtype=compute_dtype).flatten() + prev_sample = sample + (next_timestep[0] - timestep[0]) * (0.5 * model_output + 0.5 * next_model_output) + prev_sample = prev_sample.to(sample_dtype) + if not return_dict: + return (prev_sample,) + return PAEFlowMatchSchedulerOutput(prev_sample=prev_sample) diff --git a/pae-dinov3-large-d32/transformers/config.json b/pae-dinov3-large-d32/transformers/config.json new file mode 100644 index 0000000000000000000000000000000000000000..d5ddc59564b5939f9c622a5c19dc93ed567ac544 --- /dev/null +++ b/pae-dinov3-large-d32/transformers/config.json @@ -0,0 +1,15 @@ +{ + "_class_name": "LightningDiT2DModel", + "depth": 28, + "hidden_size": 1152, + "in_channels": 32, + "input_size": 16, + "num_classes": 1000, + "num_heads": 16, + "patch_size": 1, + "use_qknorm": true, + "use_rmsnorm": true, + "use_rope": true, + "use_swiglu": true, + "wo_shift": false +} diff --git a/pae-dinov3-large-d32/transformers/diffusion_pytorch_model.safetensors b/pae-dinov3-large-d32/transformers/diffusion_pytorch_model.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..09d3299e249fce2ecfcac649bdcec04818947b0e --- /dev/null +++ b/pae-dinov3-large-d32/transformers/diffusion_pytorch_model.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:81b9436b33326a31de395fd17b4bad4f93b75fd8498beeac7574ca91760fc681 +size 2701230752 diff --git a/pae-dinov3-large-d32/transformers/transformer_lightning_dit.py b/pae-dinov3-large-d32/transformers/transformer_lightning_dit.py new file mode 100644 index 0000000000000000000000000000000000000000..80d061481bca0a538950bfd25b531e8bf1c05d61 --- /dev/null +++ b/pae-dinov3-large-d32/transformers/transformer_lightning_dit.py @@ -0,0 +1,794 @@ +from __future__ import annotations + +import torch +import torch.nn.functional as F +from torch import nn + + +class RMSNorm(torch.nn.Module): + def __init__(self, dim: int, eps: float = 1e-6): + super().__init__() + self.eps = eps + self.weight = nn.Parameter(torch.ones(dim)) + + def _norm(self, x: torch.Tensor) -> torch.Tensor: + return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + output = self._norm(x.float()).type_as(x) + return output * self.weight + +from math import pi + +import torch +from torch import nn + +from einops import rearrange, repeat + + + +def broadcat(tensors, dim = -1): + num_tensors = len(tensors) + shape_lens = set(list(map(lambda t: len(t.shape), tensors))) + assert len(shape_lens) == 1, 'tensors must all have the same number of dimensions' + shape_len = list(shape_lens)[0] + dim = (dim + shape_len) if dim < 0 else dim + dims = list(zip(*map(lambda t: list(t.shape), tensors))) + expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim] + assert all([*map(lambda t: len(set(t[1])) <= 2, expandable_dims)]), 'invalid dimensions for broadcastable concatentation' + max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims)) + expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims)) + expanded_dims.insert(dim, (dim, dims[dim])) + expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims))) + tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes))) + return torch.cat(tensors, dim = dim) + + + +def rotate_half(x): + x = rearrange(x, '... (d r) -> ... d r', r = 2) + x1, x2 = x.unbind(dim = -1) + x = torch.stack((-x2, x1), dim = -1) + return rearrange(x, '... d r -> ... (d r)') + + + +class VisionRotaryEmbedding(nn.Module): + def __init__( + self, + dim, + pt_seq_len, + ft_seq_len=None, + custom_freqs = None, + freqs_for = 'lang', + theta = 10000, + max_freq = 10, + num_freqs = 1, + ): + super().__init__() + if custom_freqs: + freqs = custom_freqs + elif freqs_for == 'lang': + freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim)) + elif freqs_for == 'pixel': + freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi + elif freqs_for == 'constant': + freqs = torch.ones(num_freqs).float() + else: + raise ValueError(f'unknown modality {freqs_for}') + + if ft_seq_len is None: ft_seq_len = pt_seq_len + t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len + + freqs_h = torch.einsum('..., f -> ... f', t, freqs) + freqs_h = repeat(freqs_h, '... n -> ... (n r)', r = 2) + + freqs_w = torch.einsum('..., f -> ... f', t, freqs) + freqs_w = repeat(freqs_w, '... n -> ... (n r)', r = 2) + + freqs = broadcat((freqs_h[:, None, :], freqs_w[None, :, :]), dim = -1) + + self.register_buffer("freqs_cos", freqs.cos()) + self.register_buffer("freqs_sin", freqs.sin()) + + # print('======== shape of rope freq', self.freqs_cos.shape, '========') + + def forward(self, t, start_index = 0): + rot_dim = self.freqs_cos.shape[-1] + end_index = start_index + rot_dim + assert rot_dim <= t.shape[-1], f'feature dimension {t.shape[-1]} is not of sufficient size to rotate in all the positions {rot_dim}' + t_left, t, t_right = t[..., :start_index], t[..., start_index:end_index], t[..., end_index:] + t = (t * self.freqs_cos) + (rotate_half(t) * self.freqs_sin) + return torch.cat((t_left, t, t_right), dim = -1) + + + +class VisionRotaryEmbeddingFast(nn.Module): + def __init__( + self, + dim, + pt_seq_len=16, + ft_seq_len=None, + custom_freqs = None, + freqs_for = 'lang', + theta = 10000, + max_freq = 10, + num_freqs = 1, + ): + super().__init__() + if custom_freqs: + freqs = custom_freqs + elif freqs_for == 'lang': + freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim)) + elif freqs_for == 'pixel': + freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi + elif freqs_for == 'constant': + freqs = torch.ones(num_freqs).float() + else: + raise ValueError(f'unknown modality {freqs_for}') + + if ft_seq_len is None: ft_seq_len = pt_seq_len + t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len + + freqs = torch.einsum('..., f -> ... f', t, freqs) + freqs = repeat(freqs, '... n -> ... (n r)', r = 2) + freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim = -1) + + freqs_cos = freqs.cos().view(-1, freqs.shape[-1]) + freqs_sin = freqs.sin().view(-1, freqs.shape[-1]) + + self.register_buffer("freqs_cos", freqs_cos) + self.register_buffer("freqs_sin", freqs_sin) + + # print('======== shape of rope freq', self.freqs_cos.shape, '========') + + def forward(self, t): return t * self.freqs_cos + rotate_half(t) * self.freqs_sin + +import os +import torch +from typing import Callable, Optional +import warnings + +from torch import Tensor, nn +import torch.nn.functional as F + + +class SwiGLUFFN(nn.Module): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = None, + drop: float = 0.0, + bias: bool = True, + ) -> None: + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias) + self.w3 = nn.Linear(hidden_features, out_features, bias=bias) + def forward(self, x: Tensor) -> Tensor: + x12 = self.w12(x) + x1, x2 = x12.chunk(2, dim=-1) + hidden = F.silu(x1) * x2 + return self.w3(hidden) + + +XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None +try: + if XFORMERS_ENABLED: + from xformers.ops import SwiGLU + + XFORMERS_AVAILABLE = True + # warnings.warn("xFormers is available (SwiGLU)") + else: + # warnings.warn("xFormers is disabled (SwiGLU)") + raise ImportError +except ImportError: + SwiGLU = SwiGLUFFN + XFORMERS_AVAILABLE = False + + # warnings.warn("xFormers is not available (SwiGLU)") + + +class SwiGLUFFNFused(SwiGLU): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = None, + drop: float = 0.0, + bias: bool = True, + ) -> None: + out_features = out_features or in_features + hidden_features = hidden_features or in_features + hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8 + super().__init__( + in_features=in_features, + hidden_features=hidden_features, + out_features=out_features, + bias=bias, + ) + +from dataclasses import dataclass +from typing import Optional, Tuple, Union + +import torch + +try: + from diffusers.configuration_utils import ConfigMixin, register_to_config + from diffusers.models.modeling_utils import ModelMixin + from diffusers.utils import BaseOutput +except Exception: # pragma: no cover + class BaseOutput(dict): + def __post_init__(self): + self.update(self.__dict__) + + class ConfigMixin: + config_name = "config.json" + + class ModelMixin(torch.nn.Module): + pass + + def register_to_config(init): + return init + + +@dataclass +class LightningDiT2DModelOutput(BaseOutput): + sample: torch.FloatTensor + + +import os +import math +import numpy as np + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.utils.checkpoint import checkpoint + +from timm.models.vision_transformer import PatchEmbed, Mlp +def modulate(x, shift, scale): + if shift is None: + return x * (1 + scale.unsqueeze(1)) + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) + +class Attention(nn.Module): + """ + Attention module of LightningDiT. + """ + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = False, + qk_norm: bool = False, + attn_drop: float = 0., + proj_drop: float = 0., + norm_layer: nn.Module = nn.LayerNorm, + fused_attn: bool = True, + use_rmsnorm: bool = False, + ) -> None: + super().__init__() + assert dim % num_heads == 0, 'dim should be divisible by num_heads' + + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.scale = self.head_dim ** -0.5 + self.fused_attn = fused_attn + + if use_rmsnorm: + norm_layer = RMSNorm + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + def forward(self, x: torch.Tensor, rope=None) -> torch.Tensor: + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) + q, k, v = qkv.unbind(0) + q, k = self.q_norm(q), self.k_norm(k) + + if rope is not None: + q = rope(q) + k = rope(k) + + if self.fused_attn: + x = F.scaled_dot_product_attention( + q, k, v, + dropout_p=self.attn_drop.p if self.training else 0., + ) + else: + q = q * self.scale + attn = q @ k.transpose(-2, -1) + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + x = attn @ v + + x = x.transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class TimestepEmbedder(nn.Module): + """ + Embeds scalar timesteps into vector representations. + Same as DiT. + """ + def __init__(self, hidden_size: int, frequency_embedding_size: int = 256) -> None: + super().__init__() + self.frequency_embedding_size = frequency_embedding_size + self.mlp = nn.Sequential( + nn.Linear(frequency_embedding_size, hidden_size, bias=True), + nn.SiLU(), + nn.Linear(hidden_size, hidden_size, bias=True), + ) + + @staticmethod + def timestep_embedding(t: torch.Tensor, dim: int, max_period: int = 10000) -> torch.Tensor: + """ + Create sinusoidal timestep embeddings. + Args: + t: A 1-D Tensor of N indices, one per batch element. These may be fractional. + dim: The dimension of the output. + max_period: Controls the minimum frequency of the embeddings. + Returns: + An (N, D) Tensor of positional embeddings. + """ + # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py + half = dim // 2 + freqs = torch.exp( + -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half + ).to(device=t.device) + + args = t[:, 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) + + return embedding + def forward(self, t: torch.Tensor) -> torch.Tensor: + t_freq = self.timestep_embedding(t, self.frequency_embedding_size) + t_emb = self.mlp(t_freq) + return t_emb + + +class LabelEmbedder(nn.Module): + """ + Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance. + Same as DiT. + """ + def __init__(self, num_classes, hidden_size, dropout_prob): + super().__init__() + use_cfg_embedding = dropout_prob > 0 + self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size) + self.num_classes = num_classes + self.dropout_prob = dropout_prob + + def token_drop(self, labels, force_drop_ids=None): + """ + Drops labels to enable classifier-free guidance. + """ + if force_drop_ids is None: + drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob + else: + drop_ids = force_drop_ids == 1 + labels = torch.where(drop_ids, self.num_classes, labels) + return labels + def forward(self, labels, train, force_drop_ids=None): + use_dropout = self.dropout_prob > 0 + if (train and use_dropout) or (force_drop_ids is not None): + labels = self.token_drop(labels, force_drop_ids) + embeddings = self.embedding_table(labels) + return embeddings + +class LightningDiTBlock(nn.Module): + """ + Lightning DiT Block. We add features including: + - ROPE + - QKNorm + - RMSNorm + - SwiGLU + - No shift AdaLN. + Not all of them are used in the final model, please refer to the paper for more details. + """ + def __init__( + self, + hidden_size, + num_heads, + mlp_ratio=4.0, + use_qknorm=False, + use_swiglu=False, + use_rmsnorm=False, + wo_shift=False, + **block_kwargs + ): + super().__init__() + + # Initialize normalization layers + if not use_rmsnorm: + self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + else: + self.norm1 = RMSNorm(hidden_size) + self.norm2 = RMSNorm(hidden_size) + + # Initialize attention layer + self.attn = Attention( + hidden_size, + num_heads=num_heads, + qkv_bias=True, + qk_norm=use_qknorm, + use_rmsnorm=use_rmsnorm, + **block_kwargs + ) + + # Initialize MLP layer + mlp_hidden_dim = int(hidden_size * mlp_ratio) + approx_gelu = lambda: nn.GELU(approximate="tanh") + if use_swiglu: + # here we did not use SwiGLU from xformers because it is not compatible with torch.compile for now. + self.mlp = SwiGLUFFN(hidden_size, int(2/3 * mlp_hidden_dim)) + else: + self.mlp = Mlp( + in_features=hidden_size, + hidden_features=mlp_hidden_dim, + act_layer=approx_gelu, + drop=0 + ) + + # Initialize AdaLN modulation + if wo_shift: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(hidden_size, 4 * hidden_size, bias=True) + ) + else: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(hidden_size, 6 * hidden_size, bias=True) + ) + self.wo_shift = wo_shift + def forward(self, x, c, feat_rope=None): + if self.wo_shift: + scale_msa, gate_msa, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(4, dim=1) + shift_msa = None + shift_mlp = None + else: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=1) + + x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa), rope=feat_rope) + x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp)) + return x + +class FinalLayer(nn.Module): + """ + The final layer of LightningDiT. + """ + def __init__(self, hidden_size, patch_size, out_channels, use_rmsnorm=False): + super().__init__() + if not use_rmsnorm: + self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + else: + self.norm_final = RMSNorm(hidden_size) + self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True) + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(hidden_size, 2 * hidden_size, bias=True) + ) + def forward(self, x, c): + shift, scale = self.adaLN_modulation(c).chunk(2, dim=1) + x = modulate(self.norm_final(x), shift, scale) + x = self.linear(x) + return x + + +class LightningDiT2DModel(ModelMixin, ConfigMixin): + """ + Diffusion model with a Transformer backbone. + """ + @register_to_config + def __init__( + self, + input_size: int = 32, + patch_size=2, + in_channels=32, + hidden_size=1152, + depth=28, + num_heads=16, + mlp_ratio=4.0, + class_dropout_prob=0.1, + num_classes=1000, + learn_sigma=False, + use_qknorm=False, + use_swiglu=False, + use_rope=False, + use_rmsnorm=False, + wo_shift=False, + use_checkpoint=False, + use_abs_pos=True, + ): + super().__init__() + self.use_abs_pos = use_abs_pos + self.learn_sigma = learn_sigma + self.in_channels = in_channels + self.out_channels = in_channels if not learn_sigma else in_channels * 2 + self.patch_size = patch_size + self.num_heads = num_heads + self.use_rope = use_rope + self.use_rmsnorm = use_rmsnorm + self.depth = depth + self.hidden_size = hidden_size + self.use_checkpoint = use_checkpoint + self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size, bias=True) + self.t_embedder = TimestepEmbedder(hidden_size) + self.y_embedder = LabelEmbedder(num_classes, hidden_size, class_dropout_prob) + num_patches = self.x_embedder.num_patches + # Will use fixed sin-cos embedding: + self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False) + + if not self.use_abs_pos and not self.use_rope: + import warnings + warnings.warn("Warning: Both Absolute Position Embedding and RoPE are disabled. " + "The model will be permutation-invariant (orderless)!") + + # use rotary position encoding, borrow from EVA + if self.use_rope: + half_head_dim = hidden_size // num_heads // 2 + hw_seq_len = input_size // patch_size + self.feat_rope = VisionRotaryEmbeddingFast( + dim=half_head_dim, + pt_seq_len=hw_seq_len, + ) + else: + self.feat_rope = None + + self.blocks = nn.ModuleList([ + LightningDiTBlock(hidden_size, + num_heads, + mlp_ratio=mlp_ratio, + use_qknorm=use_qknorm, + use_swiglu=use_swiglu, + use_rmsnorm=use_rmsnorm, + wo_shift=wo_shift, + ) for _ in range(depth) + ]) + self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels, use_rmsnorm=use_rmsnorm) + self.initialize_weights() + if hasattr(self, "register_to_config"): + self.register_to_config( + input_size=input_size, + patch_size=patch_size, + in_channels=in_channels, + hidden_size=hidden_size, + depth=depth, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + class_dropout_prob=class_dropout_prob, + num_classes=num_classes, + learn_sigma=learn_sigma, + use_qknorm=use_qknorm, + use_swiglu=use_swiglu, + use_rope=use_rope, + use_rmsnorm=use_rmsnorm, + wo_shift=wo_shift, + use_checkpoint=use_checkpoint, + use_abs_pos=use_abs_pos, + ) + + def initialize_weights(self): + # Initialize transformer layers: + def _basic_init(module): + if isinstance(module, nn.Linear): + torch.nn.init.xavier_uniform_(module.weight) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + self.apply(_basic_init) + + + if self.use_abs_pos: + pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5)) + self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0)) + else: + nn.init.constant_(self.pos_embed, 0) + + # Initialize patch_embed like nn.Linear (instead of nn.Conv2d): + w = self.x_embedder.proj.weight.data + nn.init.xavier_uniform_(w.view([w.shape[0], -1])) + nn.init.constant_(self.x_embedder.proj.bias, 0) + + # Initialize label embedding table: + nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02) + + # Initialize timestep embedding MLP: + nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02) + nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02) + + # Zero-out adaLN modulation layers in LightningDiT blocks: + for block in self.blocks: + nn.init.constant_(block.adaLN_modulation[-1].weight, 0) + nn.init.constant_(block.adaLN_modulation[-1].bias, 0) + + # Zero-out output layers: + nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0) + nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0) + nn.init.constant_(self.final_layer.linear.weight, 0) + nn.init.constant_(self.final_layer.linear.bias, 0) + + def unpatchify(self, x): + """ + x: (N, T, patch_size**2 * C) + imgs: (N, H, W, C) + """ + c = self.out_channels + p = self.x_embedder.patch_size[0] + h = w = int(x.shape[1] ** 0.5) + assert h * w == x.shape[1] + + x = x.reshape(shape=(x.shape[0], h, w, p, p, c)) + x = torch.einsum('nhwpqc->nchpwq', x) + imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p)) + return imgs + + def forward( + self, + hidden_states: torch.Tensor, + timestep: Optional[torch.LongTensor] = None, + class_labels: Optional[torch.LongTensor] = None, + return_dict: bool = True, + ): + x = hidden_states + t = timestep + y = class_labels + """ + Forward pass of LightningDiT. + x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images) + t: (N,) tensor of diffusion timesteps + y: (N,) tensor of class labels + use_checkpoint: boolean to toggle checkpointing + """ + + use_checkpoint = self.use_checkpoint + + x = self.x_embedder(x) + if self.use_abs_pos: + x = x + self.pos_embed + t = self.t_embedder(t) # (N, D) + y = self.y_embedder(y, self.training) # (N, D) + c = t + y # (N, D) + + for block in self.blocks: + if use_checkpoint: + x = checkpoint(block, x, c, self.feat_rope, use_reentrant=True) + else: + x = block(x, c, self.feat_rope) + + x = self.final_layer(x, c) # (N, T, patch_size ** 2 * out_channels) + x = self.unpatchify(x) # (N, out_channels, H, W) + + if self.learn_sigma: + x, _ = x.chunk(2, dim=1) + if not return_dict: + return (x,) + return LightningDiT2DModelOutput(sample=x) + + def forward_with_cfg(self, x, t, y, cfg_scale, cfg_interval=None, cfg_interval_start=None): + """ + Forward pass of LightningDiT, but also batches the unconditional forward pass for classifier-free guidance. + """ + # https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb + combined = torch.cat([x, x], dim=0) + model_out = self.forward(combined, t, y, return_dict=False)[0] + # For exact reproducibility reasons, we apply classifier-free guidance on only + # three channels by default. The standard approach to cfg applies it to all channels. + # This can be done by uncommenting the following line and commenting-out the line following that. + eps, rest = model_out[:, :self.in_channels], model_out[:, self.in_channels:] + # eps, rest = model_out[:, :3], model_out[:, 3:] + cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0) + half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps) + + if cfg_interval is True: + timestep = t[0] + if timestep < cfg_interval_start: + half_eps = cond_eps + + eps = torch.cat([half_eps, half_eps], dim=0) + return torch.cat([eps, rest], dim=1) + +def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0): + """ + grid_size: int of the grid height and width + return: + pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token) + """ + grid_h = np.arange(grid_size, dtype=np.float32) + grid_w = np.arange(grid_size, dtype=np.float32) + grid = np.meshgrid(grid_w, grid_h) # here w goes first + grid = np.stack(grid, axis=0) + + grid = grid.reshape([2, 1, grid_size, grid_size]) + pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) + if cls_token and extra_tokens > 0: + pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0) + return pos_embed + + +def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): + assert embed_dim % 2 == 0 + + # use half of dimensions to encode grid_h + emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) + emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2) + + emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D) + return emb + + +def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): + """ + embed_dim: output dimension for each position + pos: a list of positions to be encoded: size (M,) + out: (M, D) + """ + assert embed_dim % 2 == 0 + omega = np.arange(embed_dim // 2, dtype=np.float64) + omega /= embed_dim / 2. + omega = 1. / 10000**omega # (D/2,) + + pos = pos.reshape(-1) # (M,) + out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product + + emb_sin = np.sin(out) # (M, D/2) + emb_cos = np.cos(out) # (M, D/2) + + emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) + return emb + + +################################################################################# +# LightningDiT Configs # +################################################################################# + +def _lightning_dit_XL_1(**kwargs): + return LightningDiT2DModel(depth=28, hidden_size=1152, patch_size=1, num_heads=16, **kwargs) + +def _lightning_dit_XL_2(**kwargs): + return LightningDiT2DModel(depth=28, hidden_size=1152, patch_size=2, num_heads=16, **kwargs) + +def _lightning_dit_L_2(**kwargs): + return LightningDiT2DModel(depth=24, hidden_size=1024, patch_size=2, num_heads=16, **kwargs) + +def _lightning_dit_B_1(**kwargs): + return LightningDiT2DModel(depth=12, hidden_size=768, patch_size=1, num_heads=12, **kwargs) + +def _lightning_dit_B_2(**kwargs): + return LightningDiT2DModel(depth=12, hidden_size=768, patch_size=2, num_heads=12, **kwargs) + +def _lightning_dit_1p0B_1(**kwargs): + return LightningDiT2DModel(depth=24, hidden_size=1536, patch_size=1, num_heads=24, **kwargs) + +def _lightning_dit_1p0B_2(**kwargs): + return LightningDiT2DModel(depth=24, hidden_size=1536, patch_size=2, num_heads=24, **kwargs) + +def _lightning_dit_1p6B_1(**kwargs): + return LightningDiT2DModel(depth=28, hidden_size=1792, patch_size=1, num_heads=28, **kwargs) + +def _lightning_dit_1p6B_2(**kwargs): + return LightningDiT2DModel(depth=28, hidden_size=1792, patch_size=2, num_heads=28, **kwargs) + +LIGHTNING_DIT_PRESETS = { + 'LightningDiT-B/1': _lightning_dit_B_1, 'LightningDiT-B/2': _lightning_dit_B_2, + 'LightningDiT-L/2': _lightning_dit_L_2, + 'LightningDiT-XL/1': _lightning_dit_XL_1, 'LightningDiT-XL/2': _lightning_dit_XL_2, + 'LightningDiT-1p0B/1': _lightning_dit_1p0B_1, 'LightningDiT-1p0B/2': _lightning_dit_1p0B_2, + 'LightningDiT-1p6B/1': _lightning_dit_1p6B_1, 'LightningDiT-1p6B/2': _lightning_dit_1p6B_2, +} diff --git a/pae-mae-large-d32/decoder/config.json b/pae-mae-large-d32/decoder/config.json new file mode 100644 index 0000000000000000000000000000000000000000..f927a5248edf516e46fa38503d3541c5b7ecb7e1 --- /dev/null +++ b/pae-mae-large-d32/decoder/config.json @@ -0,0 +1,79 @@ +{ + "_class_name": "PAEDecoder", + "decoder_patch_size": 16, + "encoder_config_path": "facebook/vit-mae-large", + "encoder_hidden_size": 1024, + "encoder_input_size": 256, + "encoder_num_heads": 16, + "encoder_patch_size": 16, + "latent_dim": 32, + "latent_mean": [ + 0.6328125, + 1.1171875, + -1.140625, + 0.95703125, + 0.80859375, + -0.8046875, + 0.43359375, + -0.263671875, + 1.28125, + 0.341796875, + -0.291015625, + -0.80859375, + 0.71484375, + -0.89453125, + -1.046875, + 0.96875, + -1.484375, + 0.71875, + 0.1767578125, + 0.9140625, + 0.9453125, + -1.0, + 1.0859375, + -1.3515625, + -1.1015625, + -0.625, + 0.53125, + 0.640625, + -1.3984375, + 0.4921875, + 1.1015625, + 0.515625 + ], + "latent_multiplier": 1.0, + "latent_std": [ + 0.5546875, + 0.328125, + 0.32421875, + 0.3203125, + 0.458984375, + 0.3515625, + 0.55078125, + 0.470703125, + 0.38671875, + 0.51171875, + 0.490234375, + 0.515625, + 0.380859375, + 0.486328125, + 0.3515625, + 0.5390625, + 0.3046875, + 0.6015625, + 0.404296875, + 0.482421875, + 0.3828125, + 0.373046875, + 0.408203125, + 0.447265625, + 0.4765625, + 0.390625, + 0.45703125, + 0.45703125, + 0.4375, + 0.416015625, + 0.45703125, + 0.484375 + ] +} diff --git a/pae-mae-large-d32/decoder/decoder_pae.py b/pae-mae-large-d32/decoder/decoder_pae.py new file mode 100644 index 0000000000000000000000000000000000000000..4592fb0fd62b7324c7d6398d7e50f4229d58a3b3 --- /dev/null +++ b/pae-mae-large-d32/decoder/decoder_pae.py @@ -0,0 +1,1105 @@ +from __future__ import annotations + +from transformers.configuration_utils import PretrainedConfig +from transformers.utils import ( + ModelOutput, +) +from transformers.activations import ACT2FN +class ViTMAEConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a [`ViTMAEModel`]. It is used to instantiate an ViT + MAE model according to the specified arguments, defining the model architecture. Instantiating a configuration with + the defaults will yield a similar configuration to that of the ViT + [facebook/vit-mae-base](https://huggingface.co/facebook/vit-mae-base) architecture. + + Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the + documentation from [`PretrainedConfig`] for more information. + + + Args: + hidden_size (`int`, *optional*, defaults to 768): + Dimensionality of the encoder layers and the pooler layer. + num_hidden_layers (`int`, *optional*, defaults to 12): + Number of hidden layers in the Transformer encoder. + num_attention_heads (`int`, *optional*, defaults to 12): + Number of attention heads for each attention layer in the Transformer encoder. + intermediate_size (`int`, *optional*, defaults to 3072): + Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. + hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`): + The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, + `"relu"`, `"selu"` and `"gelu_new"` are supported. + hidden_dropout_prob (`float`, *optional*, defaults to 0.0): + The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler. + attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0): + The dropout ratio for the attention probabilities. + initializer_range (`float`, *optional*, defaults to 0.02): + The standard deviation of the truncated_normal_initializer for initializing all weight matrices. + layer_norm_eps (`float`, *optional*, defaults to 1e-12): + The epsilon used by the layer normalization layers. + image_size (`int`, *optional*, defaults to 224): + The size (resolution) of each image. + patch_size (`int`, *optional*, defaults to 16): + The size (resolution) of each patch. + num_channels (`int`, *optional*, defaults to 3): + The number of input channels. + qkv_bias (`bool`, *optional*, defaults to `True`): + Whether to add a bias to the queries, keys and values. + decoder_num_attention_heads (`int`, *optional*, defaults to 16): + Number of attention heads for each attention layer in the decoder. + decoder_hidden_size (`int`, *optional*, defaults to 512): + Dimensionality of the decoder. + decoder_num_hidden_layers (`int`, *optional*, defaults to 8): + Number of hidden layers in the decoder. + decoder_intermediate_size (`int`, *optional*, defaults to 2048): + Dimensionality of the "intermediate" (i.e., feed-forward) layer in the decoder. + mask_ratio (`float`, *optional*, defaults to 0.75): + The ratio of the number of masked tokens in the input sequence. + norm_pix_loss (`bool`, *optional*, defaults to `False`): + Whether or not to train with normalized pixels (see Table 3 in the paper). Using normalized pixels improved + representation quality in the experiments of the authors. + + Example: + + ```python + >>> from transformers import ViTMAEConfig, ViTMAEModel + + >>> # Initializing a ViT MAE vit-mae-base style configuration + >>> configuration = ViTMAEConfig() + + >>> # Initializing a model (with random weights) from the vit-mae-base style configuration + >>> model = ViTMAEModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "vit_mae" + + def __init__( + self, + hidden_size=768, + num_hidden_layers=12, + num_attention_heads=12, + intermediate_size=3072, + hidden_act="gelu", + hidden_dropout_prob=0.0, + attention_probs_dropout_prob=0.0, + initializer_range=0.02, + layer_norm_eps=1e-12, + image_size=224, + patch_size=16, + num_channels=3, + qkv_bias=True, + decoder_num_attention_heads=16, + decoder_hidden_size=512, + decoder_num_hidden_layers=8, + decoder_intermediate_size=2048, + mask_ratio=0.75, + norm_pix_loss=False, + **kwargs, + ): + super().__init__(**kwargs) + + self.hidden_size = hidden_size + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.intermediate_size = intermediate_size + self.hidden_act = hidden_act + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.initializer_range = initializer_range + self.layer_norm_eps = layer_norm_eps + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.qkv_bias = qkv_bias + self.decoder_num_attention_heads = decoder_num_attention_heads + self.decoder_hidden_size = decoder_hidden_size + self.decoder_num_hidden_layers = decoder_num_hidden_layers + self.decoder_intermediate_size = decoder_intermediate_size + self.mask_ratio = mask_ratio + self.norm_pix_loss = norm_pix_loss + +# coding=utf-8 +# Copyright 2022 Facebook AI and The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""PyTorch ViT MAE (masked autoencoder) model.""" + +import collections.abc +import math +from copy import deepcopy +from dataclasses import dataclass +from typing import Optional, Set, Tuple, Union + +import numpy as np +import torch +from torch import nn +# correct the above import to the following +from transformers.modeling_outputs import BaseModelOutput + +try: + from flash_attn import flash_attn_func + HAS_FLASH_ATTN = True # if set to False, FlashAttention is unavailable +except: + print('FlashAttention is not installed.') + HAS_FLASH_ATTN = False + + +@dataclass +class ViTMAEModelOutput(ModelOutput): + """ + Class for ViTMAEModel's outputs, with potential hidden states and attentions. + + Args: + last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): + Sequence of hidden-states at the output of the last layer of the model. + mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): + Tensor indicating which patches are masked (1) and which are not (0). + ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Tensor containing the original index of the (shuffled) masked patches. + hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): + Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of + shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer + plus the initial embedding outputs. + attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): + Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, + sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in + the self-attention heads. + """ + + last_hidden_state: torch.FloatTensor = None + mask: torch.LongTensor = None + ids_restore: torch.LongTensor = None + hidden_states: Optional[Tuple[torch.FloatTensor]] = None + attentions: Optional[Tuple[torch.FloatTensor]] = None + + +@dataclass +class ViTMAEDecoderOutput(ModelOutput): + """ + Class for ViTMAEDecoder's outputs, with potential hidden states and attentions. + + Args: + logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`): + Pixel reconstruction logits. + hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): + Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of + shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer + plus the initial embedding outputs. + attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): + Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, + sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in + the self-attention heads. + """ + + logits: torch.FloatTensor = None + hidden_states: Optional[Tuple[torch.FloatTensor]] = None + attentions: Optional[Tuple[torch.FloatTensor]] = None + + +@dataclass +class ViTMAEForPreTrainingOutput(ModelOutput): + """ + Class for ViTMAEForPreTraining's outputs, with potential hidden states and attentions. + + Args: + loss (`torch.FloatTensor` of shape `(1,)`): + Pixel reconstruction loss. + logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`): + Pixel reconstruction logits. + mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): + Tensor indicating which patches are masked (1) and which are not (0). + ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Tensor containing the original index of the (shuffled) masked patches. + hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): + Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of + shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer + plus the initial embedding outputs. + attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): + Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, + sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in + the self-attention heads. + """ + + loss: Optional[torch.FloatTensor] = None + logits: torch.FloatTensor = None + mask: torch.LongTensor = None + ids_restore: torch.LongTensor = None + hidden_states: Optional[Tuple[torch.FloatTensor]] = None + attentions: Optional[Tuple[torch.FloatTensor]] = None + + +def get_2d_sincos_pos_embed(embed_dim, grid_size, add_cls_token=False): + """ + Create 2D sin/cos positional embeddings. + + Args: + embed_dim (`int`): + Embedding dimension. + grid_size (`int`): + The grid height and width. + add_cls_token (`bool`, *optional*, defaults to `False`): + Whether or not to add a classification (CLS) token. + + Returns: + (`torch.FloatTensor` of shape (grid_size*grid_size, embed_dim) or (1+grid_size*grid_size, embed_dim): the + position embeddings (with or without classification token) + """ + grid_h = np.arange(grid_size, dtype=np.float32) + grid_w = np.arange(grid_size, dtype=np.float32) + grid = np.meshgrid(grid_w, grid_h) # here w goes first + grid = np.stack(grid, axis=0) + + grid = grid.reshape([2, 1, grid_size, grid_size]) + pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) + if add_cls_token: + pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0) + return pos_embed + + +def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): + if embed_dim % 2 != 0: + raise ValueError("embed_dim must be even") + + # use half of dimensions to encode grid_h + emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) + emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2) + + emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D) + return emb + + +def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): + """ + embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D) + """ + if embed_dim % 2 != 0: + raise ValueError("embed_dim must be even") + + omega = np.arange(embed_dim // 2, dtype=float) + omega /= embed_dim / 2.0 + omega = 1.0 / 10000**omega # (D/2,) + + pos = pos.reshape(-1) # (M,) + out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product + + emb_sin = np.sin(out) # (M, D/2) + emb_cos = np.cos(out) # (M, D/2) + + emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) + return emb + + +class ViTMAEEmbeddings(nn.Module): + """ + Construct the CLS token, position and patch embeddings. + + """ + + def __init__(self, config): + super().__init__() + + self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) + self.patch_embeddings = ViTMAEPatchEmbeddings(config) + self.num_patches = self.patch_embeddings.num_patches + # fixed sin-cos embedding + self.position_embeddings = nn.Parameter( + torch.zeros(1, self.num_patches + 1, config.hidden_size), requires_grad=False + ) + self.config = config + self.initialize_weights() + + def initialize_weights(self): + # initialize (and freeze) position embeddings by sin-cos embedding + pos_embed = get_2d_sincos_pos_embed( + self.position_embeddings.shape[-1], int(self.patch_embeddings.num_patches**0.5), add_cls_token=True + ) + self.position_embeddings.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0)) + + # initialize patch_embeddings like nn.Linear (instead of nn.Conv2d) + w = self.patch_embeddings.projection.weight.data + torch.nn.init.xavier_uniform_(w.view([w.shape[0], -1])) + + # timm's trunc_normal_(std=.02) is effectively normal_(std=0.02) as cutoff is too big (2.) + torch.nn.init.normal_(self.cls_token, std=self.config.initializer_range) + + def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor: + """ + This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher + resolution images. + + Source: + https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174 + """ + num_patches = embeddings.shape[1] - 1 + num_positions = self.position_embeddings.shape[1] - 1 + + if num_patches == num_positions and height == width: + return self.position_embeddings + + class_pos_embed = self.position_embeddings[:, 0, :] + patch_pos_embed = self.position_embeddings[:, 1:, :] + dim = embeddings.shape[-1] + h0 = height // self.config.patch_size + w0 = width // self.config.patch_size + # we add a small number to avoid floating point error in the interpolation + # see discussion at https://github.com/facebookresearch/dino/issues/8 + h0, w0 = h0 + 0.1, w0 + 0.1 + patch_pos_embed = patch_pos_embed.reshape(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim) + patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2) + patch_pos_embed = nn.functional.interpolate( + patch_pos_embed, + scale_factor=(h0 / math.sqrt(num_positions), w0 / math.sqrt(num_positions)), + mode="bicubic", + align_corners=False, + ) + if int(h0) != patch_pos_embed.shape[-2] or int(w0) != patch_pos_embed.shape[-1]: + raise ValueError("Width or height does not match with the interpolated position embeddings") + patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) + return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1) + + def random_masking(self, sequence, noise=None): + """ + Perform per-sample random masking by per-sample shuffling. Per-sample shuffling is done by argsort random + noise. + + Args: + sequence (`torch.LongTensor` of shape `(batch_size, sequence_length, dim)`) + noise (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*) which is + mainly used for testing purposes to control randomness and maintain the reproducibility + """ + batch_size, seq_length, dim = sequence.shape + len_keep = int(seq_length * (1 - self.config.mask_ratio)) + + if noise is None: + noise = torch.rand(batch_size, seq_length, device=sequence.device) # noise in [0, 1] + + # sort noise for each sample + ids_shuffle = torch.argsort(noise, dim=1).to(sequence.device) # ascend: small is keep, large is remove + ids_restore = torch.argsort(ids_shuffle, dim=1).to(sequence.device) + + # keep the first subset + ids_keep = ids_shuffle[:, :len_keep] + sequence_unmasked = torch.gather(sequence, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, dim)) + + # generate the binary mask: 0 is keep, 1 is remove + mask = torch.ones([batch_size, seq_length], device=sequence.device) + mask[:, :len_keep] = 0 + # unshuffle to get the binary mask + mask = torch.gather(mask, dim=1, index=ids_restore) + + return sequence_unmasked, mask, ids_restore + + def forward(self, pixel_values, noise=None, interpolate_pos_encoding: bool = False): + batch_size, num_channels, height, width = pixel_values.shape + embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding) + if interpolate_pos_encoding: + position_embeddings = self.interpolate_pos_encoding(embeddings, height, width) + else: + position_embeddings = self.position_embeddings + + # add position embeddings w/o cls token + embeddings = embeddings + position_embeddings[:, 1:, :] + + # masking: length -> length * config.mask_ratio + embeddings, mask, ids_restore = self.random_masking(embeddings, noise) + + # append cls token + cls_token = self.cls_token + position_embeddings[:, :1, :] + cls_tokens = cls_token.expand(embeddings.shape[0], -1, -1) + embeddings = torch.cat((cls_tokens, embeddings), dim=1) + + return embeddings, mask, ids_restore + + +class ViTMAEPatchEmbeddings(nn.Module): + """ + This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial + `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a + Transformer. + """ + + def __init__(self, config): + super().__init__() + image_size, patch_size = config.image_size, config.patch_size + num_channels, hidden_size = config.num_channels, config.hidden_size + image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size) + patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size) + num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.num_patches = num_patches + + self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size) + + def forward(self, pixel_values, interpolate_pos_encoding: bool = False): + batch_size, num_channels, height, width = pixel_values.shape + if num_channels != self.num_channels: + raise ValueError( + "Make sure that the channel dimension of the pixel values match with the one set in the configuration." + ) + + if not interpolate_pos_encoding and (height != self.image_size[0] or width != self.image_size[1]): + raise ValueError( + f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})." + ) + x = self.projection(pixel_values).flatten(2).transpose(1, 2) + return x + + +# Copied from transformers.models.vit.modeling_vit.ViTSelfAttention ViT->ViTMAE +class ViTMAESelfAttention(nn.Module): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): + raise ValueError( + f"The hidden size {config.hidden_size,} is not a multiple of the number of attention " + f"heads {config.num_attention_heads}." + ) + + self.has_flash_attn = HAS_FLASH_ATTN + self.num_attention_heads = config.num_attention_heads + self.attention_head_size = int(config.hidden_size / config.num_attention_heads) + self.all_head_size = self.num_attention_heads * self.attention_head_size + + self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) + self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) + self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) + + self.dropout = nn.Dropout(config.attention_probs_dropout_prob) + self.attention_probs_dropout_prob = config.attention_probs_dropout_prob + + def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor: + new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) + x = x.view(new_x_shape) + return x.permute(0, 2, 1, 3) + + def reshape_for_flash(self, x: torch.Tensor) -> torch.Tensor: + """Reshape to (B, N, num_heads, head_dim) for flash_attn_func.""" + new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) + return x.view(new_x_shape) + + def forward( + self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False + ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]: + # Use FlashAttention when available and no special outputs are needed + if self.has_flash_attn and not output_attentions and head_mask is None: + query_layer = self.reshape_for_flash(self.query(hidden_states)) + key_layer = self.reshape_for_flash(self.key(hidden_states)) + value_layer = self.reshape_for_flash(self.value(hidden_states)) + + context_layer = flash_attn_func( + query_layer, key_layer, value_layer, + dropout_p=self.attention_probs_dropout_prob if self.training else 0.0, + causal=False, deterministic=True + ) + + context_layer = context_layer.reshape(hidden_states.size(0), -1, self.all_head_size) + return (context_layer,) + + # Fallback: manual attention computation + mixed_query_layer = self.query(hidden_states) + + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + query_layer = self.transpose_for_scores(mixed_query_layer) + + attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) + attention_scores = attention_scores / math.sqrt(self.attention_head_size) + + attention_probs = nn.functional.softmax(attention_scores, dim=-1) + attention_probs = self.dropout(attention_probs) + + if head_mask is not None: + attention_probs = attention_probs * head_mask + + context_layer = torch.matmul(attention_probs, value_layer) + + context_layer = context_layer.permute(0, 2, 1, 3).contiguous() + new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) + context_layer = context_layer.view(new_context_layer_shape) + + outputs = (context_layer, attention_probs) if output_attentions else (context_layer,) + + return outputs + + +# Copied from transformers.models.vit.modeling_vit.ViTSdpaSelfAttention ViT->ViTMAE +class ViTMAESdpaSelfAttention(ViTMAESelfAttention): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__(config) + self.attention_probs_dropout_prob = config.attention_probs_dropout_prob + + def forward( + self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False + ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]: + # Use FlashAttention when available and no special outputs are needed + if self.has_flash_attn and not output_attentions and head_mask is None: + query_layer = self.reshape_for_flash(self.query(hidden_states)) + key_layer = self.reshape_for_flash(self.key(hidden_states)) + value_layer = self.reshape_for_flash(self.value(hidden_states)) + + context_layer = flash_attn_func( + query_layer, key_layer, value_layer, + dropout_p=self.attention_probs_dropout_prob if self.training else 0.0, + causal=False, deterministic=True + ) + + context_layer = context_layer.reshape(hidden_states.size(0), -1, self.all_head_size) + return context_layer, None + + # Fallback: PyTorch SDPA + mixed_query_layer = self.query(hidden_states) + + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + query_layer = self.transpose_for_scores(mixed_query_layer) + + context_layer = torch.nn.functional.scaled_dot_product_attention( + query_layer, + key_layer, + value_layer, + head_mask, + self.attention_probs_dropout_prob if self.training else 0.0, + is_causal=False, + scale=None, + ) + + context_layer = context_layer.permute(0, 2, 1, 3).contiguous() + new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) + context_layer = context_layer.view(new_context_layer_shape) + + return context_layer, None + + +# Copied from transformers.models.vit.modeling_vit.ViTSelfOutput with ViT->ViTMAE +class ViTMAESelfOutput(nn.Module): + """ + The residual connection is defined in ViTMAELayer instead of here (as is the case with other models), due to the + layernorm applied before each block. + """ + + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + + return hidden_states + + +# Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->ViTMAE +class ViTMAEAttention(nn.Module): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.attention = ViTMAESelfAttention(config) + self.output = ViTMAESelfOutput(config) + + def forward( + self, + hidden_states: torch.Tensor, + head_mask: Optional[torch.Tensor] = None, + output_attentions: bool = False, + ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]: + self_outputs = self.attention(hidden_states, head_mask, output_attentions) + + attention_output = self.output(self_outputs[0], hidden_states) + + outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them + return outputs + +# Copied from transformers.models.vit.modeling_vit.ViTIntermediate ViT->ViTMAE +class ViTMAEIntermediate(nn.Module): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.intermediate_size) + if isinstance(config.hidden_act, str): + self.intermediate_act_fn = ACT2FN[config.hidden_act] + else: + self.intermediate_act_fn = config.hidden_act + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.intermediate_act_fn(hidden_states) + + return hidden_states + + +# Copied from transformers.models.vit.modeling_vit.ViTOutput ViT->ViTMAE +class ViTMAEOutput(nn.Module): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.dense = nn.Linear(config.intermediate_size, config.hidden_size) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + + hidden_states = hidden_states + input_tensor + + return hidden_states + + + +# Copied from transformers.models.vit.modeling_vit.ViTLayer with ViT->ViTMAE,VIT->VITMAE +class ViTMAELayer(nn.Module): + """This corresponds to the Block class in the timm implementation.""" + + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.chunk_size_feed_forward = config.chunk_size_feed_forward + self.seq_len_dim = 1 + self.attention = ViTMAEAttention(config) # no SPDA by default + self.intermediate = ViTMAEIntermediate(config) + self.output = ViTMAEOutput(config) + self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + + def forward( + self, + hidden_states: torch.Tensor, + head_mask: Optional[torch.Tensor] = None, + output_attentions: bool = False, + ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]: + self_attention_outputs = self.attention( + self.layernorm_before(hidden_states), # in ViTMAE, layernorm is applied before self-attention + head_mask, + output_attentions=output_attentions, + ) + attention_output = self_attention_outputs[0] + outputs = self_attention_outputs[1:] # add self attentions if we output attention weights + + # first residual connection + hidden_states = attention_output + hidden_states + + # in ViTMAE, layernorm is also applied after self-attention + layer_output = self.layernorm_after(hidden_states) + layer_output = self.intermediate(layer_output) + + # second residual connection is done here + layer_output = self.output(layer_output, hidden_states) + + outputs = (layer_output,) + outputs + + return outputs + + +class GeneralDecoder(nn.Module): + def __init__(self, config, num_patches): + super().__init__() + self.decoder_embed = nn.Linear(config.hidden_size, config.decoder_hidden_size, bias=True) + self.decoder_pos_embed = nn.Parameter( + torch.zeros(1, num_patches + 1, config.decoder_hidden_size), requires_grad=False + ) # fixed sin-cos embedding + + decoder_config = deepcopy(config) + decoder_config.hidden_size = config.decoder_hidden_size + decoder_config.num_hidden_layers = config.decoder_num_hidden_layers + decoder_config.num_attention_heads = config.decoder_num_attention_heads + decoder_config.intermediate_size = config.decoder_intermediate_size + self.decoder_layers = nn.ModuleList( + [ViTMAELayer(decoder_config) for _ in range(config.decoder_num_hidden_layers)] + ) + + self.decoder_norm = nn.LayerNorm(config.decoder_hidden_size, eps=config.layer_norm_eps) + self.decoder_pred = nn.Linear( + config.decoder_hidden_size, config.patch_size**2 * config.num_channels, bias=True + ) # encoder to decoder + self.gradient_checkpointing = False + self.config = config + self.num_patches = num_patches + self.initialize_weights(num_patches) + self.decoder_config = decoder_config + self.set_trainable_cls_token() + def set_trainable_cls_token(self, tensor: Optional[torch.Tensor] = None): + # register a trainable CLS token + tensor = torch.zeros(1, 1, self.decoder_config.hidden_size) if tensor is None else tensor + self.trainable_cls_token = nn.Parameter(tensor) + def interpolate_pos_encoding(self, embeddings: torch.Tensor) -> torch.Tensor: + """ + This method is a modified version of the interpolation function for ViT-mae model at the deocder, that + allows to interpolate the pre-trained decoder position encodings, to be able to use the model on higher + resolution images. + + Source: + https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174 + """ + + # -1 removes the class dimension since we later append it without interpolation + embeddings_positions = embeddings.shape[1] - 1 + num_positions = self.decoder_pos_embed.shape[1] - 1 + + # Separation of class token and patch tokens + class_pos_embed = self.decoder_pos_embed[:, 0, :] + patch_pos_embed = self.decoder_pos_embed[:, 1:, :] + + # To retain the final 3d tensor with the required dimensions + dim = self.decoder_pos_embed.shape[-1] + + # Increasing a dimension to enable bicubic interpolation + patch_pos_embed = patch_pos_embed.reshape(1, 1, -1, dim) + + # permute to bring the dimension to be interpolated, to the last + patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2) + + # Interpolating the decoder position embeddings shape wrt embeddings shape i.e (x). + # 1 keeps the other dimension constant + patch_pos_embed = nn.functional.interpolate( + patch_pos_embed, + scale_factor=(1, embeddings_positions / num_positions), + mode="bicubic", + align_corners=False, + ) + + # Converting back to the original shape + patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) + # Adding the class token back + return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1) + def interpolate_latent(self, x: torch.Tensor) -> torch.Tensor: + b, l, c = x.shape + if l == self.num_patches: + return x + # interpolate the latent + #print(f"interpolating latent from {l} to {self.num_patches}, x.shape = {x.shape}") + h, w = int(l**0.5), int(l**0.5) + x = x.reshape(b, h, w, c) + x = x.permute(0, 3, 1, 2) + target_size = (int(self.num_patches**0.5), int(self.num_patches**0.5)) + x = nn.functional.interpolate(x, size=target_size, mode="bilinear", align_corners=False) + x = x.permute(0, 2, 3, 1).contiguous().view(b, self.num_patches, c) + return x + + def initialize_weights(self, num_patches): + # initialize (and freeze) position embeddings by sin-cos embedding + decoder_pos_embed = get_2d_sincos_pos_embed( + self.decoder_pos_embed.shape[-1], int(num_patches**0.5), add_cls_token=True + ) + self.decoder_pos_embed.data.copy_(torch.from_numpy(decoder_pos_embed).float().unsqueeze(0)) + + # timm's trunc_normal_(std=.02) is effectively normal_(std=0.02) as cutoff is too big (2.) + # torch.nn.init.normal_(self.mask_token, std=self.config.initializer_range) + def unpatchify(self, patchified_pixel_values, original_image_size: Optional[Tuple[int, int]] = None): + """ + Args: + patchified_pixel_values (`torch.FloatTensor` of shape `(batch_size, num_patches, patch_size**2 * num_channels)`: + Patchified pixel values. + original_image_size (`Tuple[int, int]`, *optional*): + Original image size. + + Returns: + `torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`: + Pixel values. + """ + patch_size, num_channels = self.config.patch_size, self.config.num_channels + original_image_size = ( + original_image_size + if original_image_size is not None + else (self.config.image_size, self.config.image_size) + ) + original_height, original_width = original_image_size + num_patches_h = original_height // patch_size + num_patches_w = original_width // patch_size + # sanity check + if num_patches_h * num_patches_w != patchified_pixel_values.shape[1]: + raise ValueError( + f"The number of patches in the patchified pixel values {patchified_pixel_values.shape[1]}, does not match the number of patches on original image {num_patches_h}*{num_patches_w}" + ) + + # unpatchify + batch_size = patchified_pixel_values.shape[0] + patchified_pixel_values = patchified_pixel_values.reshape( + batch_size, + num_patches_h, + num_patches_w, + patch_size, + patch_size, + num_channels, + ) + patchified_pixel_values = torch.einsum("nhwpqc->nchpwq", patchified_pixel_values) + pixel_values = patchified_pixel_values.reshape( + batch_size, + num_channels, + num_patches_h * patch_size, + num_patches_w * patch_size, + ) + return pixel_values + + def forward( + self, + hidden_states, + output_attentions=False, + output_hidden_states=False, + return_dict=True, + interpolate_pos_encoding: bool = False, + drop_cls_token: bool = False, + ): + # embed tokens + x = self.decoder_embed(hidden_states) + #print(f"x.shape = {x.shape}") + if drop_cls_token: + x_ = x[:, 1:, :] # no cls token + x_ = self.interpolate_latent(x_) + else: + x_ = self.interpolate_latent(x) # interpolate the whole latent + cls_token = self.trainable_cls_token.expand(x_.shape[0], -1, -1) + x = torch.cat([cls_token, x_], dim=1) + + # add pos embed + if interpolate_pos_encoding: + assert drop_cls_token, "interpolate_pos_encoding only works with drop_cls_token=True" + decoder_pos_embed = self.interpolate_pos_encoding(x) + else: + decoder_pos_embed = self.decoder_pos_embed + hidden_states = x + decoder_pos_embed + #print(f"hidden_states.shape = {hidden_states.shape}") + # apply Transformer layers (blocks) + all_hidden_states = () if output_hidden_states else None + all_self_attentions = () if output_attentions else None + for i, layer_module in enumerate(self.decoder_layers): + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + if self.gradient_checkpointing and self.training: + layer_outputs = self._gradient_checkpointing_func( + layer_module.__call__, + hidden_states, + None, + output_attentions, + ) + else: + layer_outputs = layer_module(hidden_states, head_mask=None, output_attentions=output_attentions) + + hidden_states = layer_outputs[0] + + if output_attentions: + all_self_attentions = all_self_attentions + (layer_outputs[1],) + + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + hidden_states = self.decoder_norm(hidden_states) + + # predictor projection + logits = self.decoder_pred(hidden_states) + + # remove cls token + logits = logits[:, 1:, :] + + if not return_dict: + return tuple(v for v in [logits, all_hidden_states, all_self_attentions] if v is not None) + return ViTMAEDecoderOutput( + logits=logits, + hidden_states=all_hidden_states, + attentions=all_self_attentions, + ) + +import json +from math import sqrt +from pathlib import Path +from typing import Any, Dict, Optional + +import torch +import torch.nn as nn +from timm.models.vision_transformer import Attention +from transformers import AutoConfig, AutoImageProcessor + +try: + from diffusers.configuration_utils import ConfigMixin, register_to_config + from diffusers.models.modeling_utils import ModelMixin +except Exception: # pragma: no cover + class ConfigMixin: + config_name = "config.json" + + class ModelMixin(nn.Module): + pass + + def register_to_config(init): + return init + + +_PIXEL_DECODER_DEFAULTS: Dict[str, Any] = { + "decoder_hidden_size": 1024, + "decoder_intermediate_size": 4096, + "decoder_num_attention_heads": 16, + "decoder_num_hidden_layers": 24, + "layer_norm_eps": 1e-12, + "num_channels": 3, + "hidden_act": "gelu", + "qkv_bias": True, + "hidden_dropout_prob": 0.0, + "attention_probs_dropout_prob": 0.0, + "initializer_range": 0.02, +} + + +def _resolve_local_asset_path(path: str, model_root: Optional[Path] = None) -> str: + candidate = Path(path) + if candidate.is_file(): + return str(candidate) + search_roots = [] + if model_root is not None: + search_roots.extend([model_root, model_root.parent]) + for root in search_roots: + for probe in (root / candidate, root / candidate.name, root / "decoder_config" / "config.json"): + if probe.is_file(): + return str(probe) + return path + + +def _build_pixel_decoder_config( + *, + encoder_hidden_size: int, + decoder_patch_size: int, + base_patches: int, + decoder_config_path: Optional[str] = None, + overrides: Optional[Dict[str, Any]] = None, +) -> ViTMAEConfig: + pixel_decoder = dict(_PIXEL_DECODER_DEFAULTS) + if decoder_config_path is not None: + resolved = _resolve_local_asset_path(decoder_config_path) + if Path(resolved).is_file(): + with open(resolved, encoding="utf-8") as handle: + pixel_decoder.update(json.load(handle)) + if overrides: + pixel_decoder.update({key: value for key, value in overrides.items() if value is not None}) + + return ViTMAEConfig( + hidden_size=encoder_hidden_size, + patch_size=decoder_patch_size, + image_size=int(decoder_patch_size * sqrt(base_patches)), + **pixel_decoder, + ) + + +def _load_image_normalization(encoder_config_path: str) -> tuple[list[float], list[float]]: + try: + proc = AutoImageProcessor.from_pretrained(encoder_config_path, use_fast=True, local_files_only=True) + return proc.image_mean, proc.image_std + except Exception: + pass + try: + proc = AutoImageProcessor.from_pretrained(encoder_config_path, use_fast=True, local_files_only=False) + return proc.image_mean, proc.image_std + except Exception: + if "siglip" in encoder_config_path.lower(): + return [0.5, 0.5, 0.5], [0.5, 0.5, 0.5] + return [0.485, 0.456, 0.406], [0.229, 0.224, 0.225] + + +class PAEDecoder(ModelMixin, ConfigMixin): + """PAE decoder: latent decompressor + ViT-MAE pixel decoder.""" + + @register_to_config + def __init__( + self, + encoder_hidden_size: int = 1024, + encoder_num_heads: int = 16, + encoder_input_size: int = 224, + encoder_patch_size: int = 14, + encoder_config_path: str = "facebook/dinov2-with-registers-large", + latent_dim: int = 32, + decoder_patch_size: int = 16, + decoder_config_path: Optional[str] = None, + decoder_hidden_size: int = 1024, + decoder_intermediate_size: int = 4096, + decoder_num_attention_heads: int = 16, + decoder_num_hidden_layers: int = 24, + layer_norm_eps: float = 1e-12, + num_channels: int = 3, + hidden_act: str = "gelu", + qkv_bias: bool = True, + hidden_dropout_prob: float = 0.0, + attention_probs_dropout_prob: float = 0.0, + initializer_range: float = 0.02, + image_mean: Optional[list[float]] = None, + image_std: Optional[list[float]] = None, + latent_mean: Optional[list[float]] = None, + latent_std: Optional[list[float]] = None, + latent_multiplier: float = 1.0, + **kwargs, + ) -> None: + super().__init__() + if image_mean is not None and image_std is not None: + norm_mean, norm_std = image_mean, image_std + else: + norm_mean, norm_std = _load_image_normalization(encoder_config_path) + self.register_buffer("encoder_mean", torch.tensor(norm_mean).view(1, 3, 1, 1), persistent=True) + self.register_buffer("encoder_std", torch.tensor(norm_std).view(1, 3, 1, 1), persistent=True) + + self.encoder_input_size = encoder_input_size + self.encoder_patch_size = encoder_patch_size + self.base_patches = (self.encoder_input_size // self.encoder_patch_size) ** 2 + self.latent_dim = latent_dim + + self.latent_decompressor = nn.ModuleList( + [ + nn.Conv2d(latent_dim, encoder_hidden_size, kernel_size=3, padding=1), + Attention(dim=encoder_hidden_size, num_heads=encoder_num_heads), + ] + ) + + pixel_decoder_config = _build_pixel_decoder_config( + encoder_hidden_size=encoder_hidden_size, + decoder_patch_size=decoder_patch_size, + base_patches=self.base_patches, + decoder_config_path=decoder_config_path, + overrides={ + "decoder_hidden_size": decoder_hidden_size, + "decoder_intermediate_size": decoder_intermediate_size, + "decoder_num_attention_heads": decoder_num_attention_heads, + "decoder_num_hidden_layers": decoder_num_hidden_layers, + "layer_norm_eps": layer_norm_eps, + "num_channels": num_channels, + "hidden_act": hidden_act, + "qkv_bias": qkv_bias, + "hidden_dropout_prob": hidden_dropout_prob, + "attention_probs_dropout_prob": attention_probs_dropout_prob, + "initializer_range": initializer_range, + }, + ) + self.decoder = GeneralDecoder(pixel_decoder_config, num_patches=self.base_patches) + + @classmethod + def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): + model_root = Path(pretrained_model_name_or_path) + config_file = model_root / cls.config_name + if config_file.is_file(): + with open(config_file, encoding="utf-8") as handle: + config = json.load(handle) + decoder_config_path = config.get("decoder_config_path") + if decoder_config_path is not None: + resolved = _resolve_local_asset_path(decoder_config_path, model_root=model_root) + if resolved != decoder_config_path: + kwargs.setdefault("decoder_config_path", resolved) + return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) + + def decode(self, latents: torch.Tensor) -> torch.Tensor: + hidden_states = self.latent_decompressor[0](latents) + batch_size, channels, height, width = hidden_states.shape + num_tokens = height * width + hidden_states = hidden_states.view(batch_size, channels, num_tokens).transpose(1, 2) + hidden_states = self.latent_decompressor[1](hidden_states) + + output = self.decoder(hidden_states, drop_cls_token=False).logits + x_rec = self.decoder.unpatchify(output) + x_rec = x_rec * self.encoder_std.to(x_rec.device) + self.encoder_mean.to(x_rec.device) + return x_rec + + def forward(self, latents: torch.Tensor) -> torch.Tensor: + return self.decode(latents) diff --git a/pae-mae-large-d32/decoder/diffusion_pytorch_model.safetensors b/pae-mae-large-d32/decoder/diffusion_pytorch_model.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..fbde3920c3c0c808d8fb6d8f7610c9e8bb9ec38a --- /dev/null +++ b/pae-mae-large-d32/decoder/diffusion_pytorch_model.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f80444f2ef4c3f684622bf7fde19c7c0b50a60c7c986de85149398c416b8148 +size 1235663744 diff --git a/pae-mae-large-d32/demo.png b/pae-mae-large-d32/demo.png new file mode 100644 index 0000000000000000000000000000000000000000..85be755e873febd4879b01fe8b3d65eb6a0d26d9 --- /dev/null +++ b/pae-mae-large-d32/demo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:09cb9479853d76ba5b314818f761a35ed7cfffa5977a6575af7d15ea3d6e9635 +size 114977 diff --git a/pae-mae-large-d32/model_index.json b/pae-mae-large-d32/model_index.json new file mode 100644 index 0000000000000000000000000000000000000000..c71449e6f44c0678499c73c3696faea852cca1e2 --- /dev/null +++ b/pae-mae-large-d32/model_index.json @@ -0,0 +1,1021 @@ +{ + "_class_name": [ + "pipeline", + "PAEPipeline" + ], + "_diffusers_version": "0.31.0", + "decoder": [ + "decoder_pae", + "PAEDecoder" + ], + "id2label": { + "0": "tench, Tinca tinca", + "1": "goldfish, Carassius auratus", + "2": "great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias", + "3": "tiger shark, Galeocerdo cuvieri", + "4": "hammerhead, hammerhead shark", + "5": "electric ray, crampfish, numbfish, torpedo", + "6": "stingray", + "7": "cock", + "8": "hen", + "9": "ostrich, Struthio camelus", + "10": "brambling, Fringilla montifringilla", + "11": "goldfinch, Carduelis carduelis", + "12": "house finch, linnet, Carpodacus mexicanus", + "13": "junco, snowbird", + "14": "indigo bunting, indigo finch, indigo bird, Passerina cyanea", + "15": "robin, American robin, Turdus migratorius", + "16": "bulbul", + "17": "jay", + "18": "magpie", + "19": "chickadee", + "20": "water ouzel, dipper", + "21": "kite", + "22": "bald eagle, American eagle, Haliaeetus leucocephalus", + "23": "vulture", + "24": "great grey owl, great gray owl, Strix nebulosa", + "25": "European fire salamander, Salamandra salamandra", + "26": "common newt, Triturus vulgaris", + "27": "eft", + "28": "spotted salamander, Ambystoma maculatum", + "29": "axolotl, mud puppy, Ambystoma mexicanum", + "30": "bullfrog, Rana catesbeiana", + "31": "tree frog, tree-frog", + "32": "tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui", + "33": "loggerhead, loggerhead turtle, Caretta caretta", + "34": "leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea", + "35": "mud turtle", + "36": "terrapin", + "37": "box turtle, box tortoise", + "38": "banded gecko", + "39": "common iguana, iguana, Iguana iguana", + "40": "American chameleon, anole, Anolis carolinensis", + "41": "whiptail, whiptail lizard", + "42": "agama", + "43": "frilled lizard, Chlamydosaurus kingi", + "44": "alligator lizard", + "45": "Gila monster, Heloderma suspectum", + "46": "green lizard, Lacerta viridis", + "47": "African chameleon, Chamaeleo chamaeleon", + "48": "Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis", + "49": "African crocodile, Nile crocodile, Crocodylus niloticus", + "50": "American alligator, Alligator mississipiensis", + "51": "triceratops", + "52": "thunder snake, worm snake, Carphophis amoenus", + "53": "ringneck snake, ring-necked snake, ring snake", + "54": "hognose snake, puff adder, sand viper", + "55": "green snake, grass snake", + "56": "king snake, kingsnake", + "57": "garter snake, grass snake", + "58": "water snake", + "59": "vine snake", + "60": "night snake, Hypsiglena torquata", + "61": "boa constrictor, Constrictor constrictor", + "62": "rock python, rock snake, Python sebae", + "63": "Indian cobra, Naja naja", + "64": "green mamba", + "65": "sea snake", + "66": "horned viper, cerastes, sand viper, horned asp, Cerastes cornutus", + "67": "diamondback, diamondback rattlesnake, Crotalus adamanteus", + "68": "sidewinder, horned rattlesnake, Crotalus cerastes", + "69": "trilobite", + "70": "harvestman, daddy longlegs, Phalangium opilio", + "71": "scorpion", + "72": "black and gold garden spider, Argiope aurantia", + "73": "barn spider, Araneus cavaticus", + "74": "garden spider, Aranea diademata", + "75": "black widow, Latrodectus mactans", + "76": "tarantula", + "77": "wolf spider, hunting spider", + "78": "tick", + "79": "centipede", + "80": "black grouse", + "81": "ptarmigan", + "82": "ruffed grouse, partridge, Bonasa umbellus", + "83": "prairie chicken, prairie grouse, prairie fowl", + "84": "peacock", + "85": "quail", + "86": "partridge", + "87": "African grey, African gray, Psittacus erithacus", + "88": "macaw", + "89": "sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita", + "90": "lorikeet", + "91": "coucal", + "92": "bee eater", + "93": "hornbill", + "94": "hummingbird", + "95": "jacamar", + "96": "toucan", + "97": "drake", + "98": "red-breasted merganser, Mergus serrator", + "99": "goose", + "100": "black swan, Cygnus atratus", + "101": "tusker", + "102": "echidna, spiny anteater, anteater", + "103": "platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus", + "104": "wallaby, brush kangaroo", + "105": "koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus", + "106": "wombat", + "107": "jellyfish", + "108": "sea anemone, anemone", + "109": "brain coral", + "110": "flatworm, platyhelminth", + "111": "nematode, nematode worm, roundworm", + "112": "conch", + "113": "snail", + "114": "slug", + "115": "sea slug, nudibranch", + "116": "chiton, coat-of-mail shell, sea cradle, polyplacophore", + "117": "chambered nautilus, pearly nautilus, nautilus", + "118": "Dungeness crab, Cancer magister", + "119": "rock crab, Cancer irroratus", + "120": "fiddler crab", + "121": "king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica", + "122": "American lobster, Northern lobster, Maine lobster, Homarus americanus", + "123": "spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish", + "124": "crayfish, crawfish, crawdad, crawdaddy", + "125": "hermit crab", + "126": "isopod", + "127": "white stork, Ciconia ciconia", + "128": "black stork, Ciconia nigra", + "129": "spoonbill", + "130": "flamingo", + "131": "little blue heron, Egretta caerulea", + "132": "American egret, great white heron, Egretta albus", + "133": "bittern", + "134": "crane", + "135": "limpkin, Aramus pictus", + "136": "European gallinule, Porphyrio porphyrio", + "137": "American coot, marsh hen, mud hen, water hen, Fulica americana", + "138": "bustard", + "139": "ruddy turnstone, Arenaria interpres", + "140": "red-backed sandpiper, dunlin, Erolia alpina", + "141": "redshank, Tringa totanus", + "142": "dowitcher", + "143": "oystercatcher, oyster catcher", + "144": "pelican", + "145": "king penguin, Aptenodytes patagonica", + "146": "albatross, mollymawk", + "147": "grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus", + "148": "killer whale, killer, orca, grampus, sea wolf, Orcinus orca", + "149": "dugong, Dugong dugon", + "150": "sea lion", + "151": "Chihuahua", + "152": "Japanese spaniel", + "153": "Maltese dog, Maltese terrier, Maltese", + "154": "Pekinese, Pekingese, Peke", + "155": "Shih-Tzu", + "156": "Blenheim spaniel", + "157": "papillon", + "158": "toy terrier", + "159": "Rhodesian ridgeback", + "160": "Afghan hound, Afghan", + "161": "basset, basset hound", + "162": "beagle", + "163": "bloodhound, sleuthhound", + "164": "bluetick", + "165": "black-and-tan coonhound", + "166": "Walker hound, Walker foxhound", + "167": "English foxhound", + "168": "redbone", + "169": "borzoi, Russian wolfhound", + "170": "Irish wolfhound", + "171": "Italian greyhound", + "172": "whippet", + "173": "Ibizan hound, Ibizan Podenco", + "174": "Norwegian elkhound, elkhound", + "175": "otterhound, otter hound", + "176": "Saluki, gazelle hound", + "177": "Scottish deerhound, deerhound", + "178": "Weimaraner", + "179": "Staffordshire bullterrier, Staffordshire bull terrier", + "180": "American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier", + "181": "Bedlington terrier", + "182": "Border terrier", + "183": "Kerry blue terrier", + "184": "Irish terrier", + "185": "Norfolk terrier", + "186": "Norwich terrier", + "187": "Yorkshire terrier", + "188": "wire-haired fox terrier", + "189": "Lakeland terrier", + "190": "Sealyham terrier, Sealyham", + "191": "Airedale, Airedale terrier", + "192": "cairn, cairn terrier", + "193": "Australian terrier", + "194": "Dandie Dinmont, Dandie Dinmont terrier", + "195": "Boston bull, Boston terrier", + "196": "miniature schnauzer", + "197": "giant schnauzer", + "198": "standard schnauzer", + "199": "Scotch terrier, Scottish terrier, Scottie", + "200": "Tibetan terrier, chrysanthemum dog", + "201": "silky terrier, Sydney silky", + "202": "soft-coated wheaten terrier", + "203": "West Highland white terrier", + "204": "Lhasa, Lhasa apso", + "205": "flat-coated retriever", + "206": "curly-coated retriever", + "207": "golden retriever", + "208": "Labrador retriever", + "209": "Chesapeake Bay retriever", + "210": "German short-haired pointer", + "211": "vizsla, Hungarian pointer", + "212": "English setter", + "213": "Irish setter, red setter", + "214": "Gordon setter", + "215": "Brittany spaniel", + "216": "clumber, clumber spaniel", + "217": "English springer, English springer spaniel", + "218": "Welsh springer spaniel", + "219": "cocker spaniel, English cocker spaniel, cocker", + "220": "Sussex spaniel", + "221": "Irish water spaniel", + "222": "kuvasz", + "223": "schipperke", + "224": "groenendael", + "225": "malinois", + "226": "briard", + "227": "kelpie", + "228": "komondor", + "229": "Old English sheepdog, bobtail", + "230": "Shetland sheepdog, Shetland sheep dog, Shetland", + "231": "collie", + "232": "Border collie", + "233": "Bouvier des Flandres, Bouviers des Flandres", + "234": "Rottweiler", + "235": "German shepherd, German shepherd dog, German police dog, alsatian", + "236": "Doberman, Doberman pinscher", + "237": "miniature pinscher", + "238": "Greater Swiss Mountain dog", + "239": "Bernese mountain dog", + "240": "Appenzeller", + "241": "EntleBucher", + "242": "boxer", + "243": "bull mastiff", + "244": "Tibetan mastiff", + "245": "French bulldog", + "246": "Great Dane", + "247": "Saint Bernard, St Bernard", + "248": "Eskimo dog, husky", + "249": "malamute, malemute, Alaskan malamute", + "250": "Siberian husky", + "251": "dalmatian, coach dog, carriage dog", + "252": "affenpinscher, monkey pinscher, monkey dog", + "253": "basenji", + "254": "pug, pug-dog", + "255": "Leonberg", + "256": "Newfoundland, Newfoundland dog", + "257": "Great Pyrenees", + "258": "Samoyed, Samoyede", + "259": "Pomeranian", + "260": "chow, chow chow", + "261": "keeshond", + "262": "Brabancon griffon", + "263": "Pembroke, Pembroke Welsh corgi", + "264": "Cardigan, Cardigan Welsh corgi", + "265": "toy poodle", + "266": "miniature poodle", + "267": "standard poodle", + "268": "Mexican hairless", + "269": "timber wolf, grey wolf, gray wolf, Canis lupus", + "270": "white wolf, Arctic wolf, Canis lupus tundrarum", + "271": "red wolf, maned wolf, Canis rufus, Canis niger", + "272": "coyote, prairie wolf, brush wolf, Canis latrans", + "273": "dingo, warrigal, warragal, Canis dingo", + "274": "dhole, Cuon alpinus", + "275": "African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus", + "276": "hyena, hyaena", + "277": "red fox, Vulpes vulpes", + "278": "kit fox, Vulpes macrotis", + "279": "Arctic fox, white fox, Alopex lagopus", + "280": "grey fox, gray fox, Urocyon cinereoargenteus", + "281": "tabby, tabby cat", + "282": "tiger cat", + "283": "Persian cat", + "284": "Siamese cat, Siamese", + "285": "Egyptian cat", + "286": "cougar, puma, catamount, mountain lion, painter, panther, Felis concolor", + "287": "lynx, catamount", + "288": "leopard, Panthera pardus", + "289": "snow leopard, ounce, Panthera uncia", + "290": "jaguar, panther, Panthera onca, Felis onca", + "291": "lion, king of beasts, Panthera leo", + "292": "tiger, Panthera tigris", + "293": "cheetah, chetah, Acinonyx jubatus", + "294": "brown bear, bruin, Ursus arctos", + "295": "American black bear, black bear, Ursus americanus, Euarctos americanus", + "296": "ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus", + "297": "sloth bear, Melursus ursinus, Ursus ursinus", + "298": "mongoose", + "299": "meerkat, mierkat", + "300": "tiger beetle", + "301": "ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle", + "302": "ground beetle, carabid beetle", + "303": "long-horned beetle, longicorn, longicorn beetle", + "304": "leaf beetle, chrysomelid", + "305": "dung beetle", + "306": "rhinoceros beetle", + "307": "weevil", + "308": "fly", + "309": "bee", + "310": "ant, emmet, pismire", + "311": "grasshopper, hopper", + "312": "cricket", + "313": "walking stick, walkingstick, stick insect", + "314": "cockroach, roach", + "315": "mantis, mantid", + "316": "cicada, cicala", + "317": "leafhopper", + "318": "lacewing, lacewing fly", + "319": "dragonfly, darning needle, devils darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk", + "320": "damselfly", + "321": "admiral", + "322": "ringlet, ringlet butterfly", + "323": "monarch, monarch butterfly, milkweed butterfly, Danaus plexippus", + "324": "cabbage butterfly", + "325": "sulphur butterfly, sulfur butterfly", + "326": "lycaenid, lycaenid butterfly", + "327": "starfish, sea star", + "328": "sea urchin", + "329": "sea cucumber, holothurian", + "330": "wood rabbit, cottontail, cottontail rabbit", + "331": "hare", + "332": "Angora, Angora rabbit", + "333": "hamster", + "334": "porcupine, hedgehog", + "335": "fox squirrel, eastern fox squirrel, Sciurus niger", + "336": "marmot", + "337": "beaver", + "338": "guinea pig, Cavia cobaya", + "339": "sorrel", + "340": "zebra", + "341": "hog, pig, grunter, squealer, Sus scrofa", + "342": "wild boar, boar, Sus scrofa", + "343": "warthog", + "344": "hippopotamus, hippo, river horse, Hippopotamus amphibius", + "345": "ox", + "346": "water buffalo, water ox, Asiatic buffalo, Bubalus bubalis", + "347": "bison", + "348": "ram, tup", + "349": "bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis", + "350": "ibex, Capra ibex", + "351": "hartebeest", + "352": "impala, Aepyceros melampus", + "353": "gazelle", + "354": "Arabian camel, dromedary, Camelus dromedarius", + "355": "llama", + "356": "weasel", + "357": "mink", + "358": "polecat, fitch, foulmart, foumart, Mustela putorius", + "359": "black-footed ferret, ferret, Mustela nigripes", + "360": "otter", + "361": "skunk, polecat, wood pussy", + "362": "badger", + "363": "armadillo", + "364": "three-toed sloth, ai, Bradypus tridactylus", + "365": "orangutan, orang, orangutang, Pongo pygmaeus", + "366": "gorilla, Gorilla gorilla", + "367": "chimpanzee, chimp, Pan troglodytes", + "368": "gibbon, Hylobates lar", + "369": "siamang, Hylobates syndactylus, Symphalangus syndactylus", + "370": "guenon, guenon monkey", + "371": "patas, hussar monkey, Erythrocebus patas", + "372": "baboon", + "373": "macaque", + "374": "langur", + "375": "colobus, colobus monkey", + "376": "proboscis monkey, Nasalis larvatus", + "377": "marmoset", + "378": "capuchin, ringtail, Cebus capucinus", + "379": "howler monkey, howler", + "380": "titi, titi monkey", + "381": "spider monkey, Ateles geoffroyi", + "382": "squirrel monkey, Saimiri sciureus", + "383": "Madagascar cat, ring-tailed lemur, Lemur catta", + "384": "indri, indris, Indri indri, Indri brevicaudatus", + "385": "Indian elephant, Elephas maximus", + "386": "African elephant, Loxodonta africana", + "387": "lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens", + "388": "giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca", + "389": "barracouta, snoek", + "390": "eel", + "391": "coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch", + "392": "rock beauty, Holocanthus tricolor", + "393": "anemone fish", + "394": "sturgeon", + "395": "gar, garfish, garpike, billfish, Lepisosteus osseus", + "396": "lionfish", + "397": "puffer, pufferfish, blowfish, globefish", + "398": "abacus", + "399": "abaya", + "400": "academic gown, academic robe, judge robe", + "401": "accordion, piano accordion, squeeze box", + "402": "acoustic guitar", + "403": "aircraft carrier, carrier, flattop, attack aircraft carrier", + "404": "airliner", + "405": "airship, dirigible", + "406": "altar", + "407": "ambulance", + "408": "amphibian, amphibious vehicle", + "409": "analog clock", + "410": "apiary, bee house", + "411": "apron", + "412": "ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin", + "413": "assault rifle, assault gun", + "414": "backpack, back pack, knapsack, packsack, rucksack, haversack", + "415": "bakery, bakeshop, bakehouse", + "416": "balance beam, beam", + "417": "balloon", + "418": "ballpoint, ballpoint pen, ballpen, Biro", + "419": "Band Aid", + "420": "banjo", + "421": "bannister, banister, balustrade, balusters, handrail", + "422": "barbell", + "423": "barber chair", + "424": "barbershop", + "425": "barn", + "426": "barometer", + "427": "barrel, cask", + "428": "barrow, garden cart, lawn cart, wheelbarrow", + "429": "baseball", + "430": "basketball", + "431": "bassinet", + "432": "bassoon", + "433": "bathing cap, swimming cap", + "434": "bath towel", + "435": "bathtub, bathing tub, bath, tub", + "436": "beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon", + "437": "beacon, lighthouse, beacon light, pharos", + "438": "beaker", + "439": "bearskin, busby, shako", + "440": "beer bottle", + "441": "beer glass", + "442": "bell cote, bell cot", + "443": "bib", + "444": "bicycle-built-for-two, tandem bicycle, tandem", + "445": "bikini, two-piece", + "446": "binder, ring-binder", + "447": "binoculars, field glasses, opera glasses", + "448": "birdhouse", + "449": "boathouse", + "450": "bobsled, bobsleigh, bob", + "451": "bolo tie, bolo, bola tie, bola", + "452": "bonnet, poke bonnet", + "453": "bookcase", + "454": "bookshop, bookstore, bookstall", + "455": "bottlecap", + "456": "bow", + "457": "bow tie, bow-tie, bowtie", + "458": "brass, memorial tablet, plaque", + "459": "brassiere, bra, bandeau", + "460": "breakwater, groin, groyne, mole, bulwark, seawall, jetty", + "461": "breastplate, aegis, egis", + "462": "broom", + "463": "bucket, pail", + "464": "buckle", + "465": "bulletproof vest", + "466": "bullet train, bullet", + "467": "butcher shop, meat market", + "468": "cab, hack, taxi, taxicab", + "469": "caldron, cauldron", + "470": "candle, taper, wax light", + "471": "cannon", + "472": "canoe", + "473": "can opener, tin opener", + "474": "cardigan", + "475": "car mirror", + "476": "carousel, carrousel, merry-go-round, roundabout, whirligig", + "477": "carpenters kit, tool kit", + "478": "carton", + "479": "car wheel", + "480": "cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM", + "481": "cassette", + "482": "cassette player", + "483": "castle", + "484": "catamaran", + "485": "CD player", + "486": "cello, violoncello", + "487": "cellular telephone, cellular phone, cellphone, cell, mobile phone", + "488": "chain", + "489": "chainlink fence", + "490": "chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour", + "491": "chain saw, chainsaw", + "492": "chest", + "493": "chiffonier, commode", + "494": "chime, bell, gong", + "495": "china cabinet, china closet", + "496": "Christmas stocking", + "497": "church, church building", + "498": "cinema, movie theater, movie theatre, movie house, picture palace", + "499": "cleaver, meat cleaver, chopper", + "500": "cliff dwelling", + "501": "cloak", + "502": "clog, geta, patten, sabot", + "503": "cocktail shaker", + "504": "coffee mug", + "505": "coffeepot", + "506": "coil, spiral, volute, whorl, helix", + "507": "combination lock", + "508": "computer keyboard, keypad", + "509": "confectionery, confectionary, candy store", + "510": "container ship, containership, container vessel", + "511": "convertible", + "512": "corkscrew, bottle screw", + "513": "cornet, horn, trumpet, trump", + "514": "cowboy boot", + "515": "cowboy hat, ten-gallon hat", + "516": "cradle", + "517": "crane", + "518": "crash helmet", + "519": "crate", + "520": "crib, cot", + "521": "Crock Pot", + "522": "croquet ball", + "523": "crutch", + "524": "cuirass", + "525": "dam, dike, dyke", + "526": "desk", + "527": "desktop computer", + "528": "dial telephone, dial phone", + "529": "diaper, nappy, napkin", + "530": "digital clock", + "531": "digital watch", + "532": "dining table, board", + "533": "dishrag, dishcloth", + "534": "dishwasher, dish washer, dishwashing machine", + "535": "disk brake, disc brake", + "536": "dock, dockage, docking facility", + "537": "dogsled, dog sled, dog sleigh", + "538": "dome", + "539": "doormat, welcome mat", + "540": "drilling platform, offshore rig", + "541": "drum, membranophone, tympan", + "542": "drumstick", + "543": "dumbbell", + "544": "Dutch oven", + "545": "electric fan, blower", + "546": "electric guitar", + "547": "electric locomotive", + "548": "entertainment center", + "549": "envelope", + "550": "espresso maker", + "551": "face powder", + "552": "feather boa, boa", + "553": "file, file cabinet, filing cabinet", + "554": "fireboat", + "555": "fire engine, fire truck", + "556": "fire screen, fireguard", + "557": "flagpole, flagstaff", + "558": "flute, transverse flute", + "559": "folding chair", + "560": "football helmet", + "561": "forklift", + "562": "fountain", + "563": "fountain pen", + "564": "four-poster", + "565": "freight car", + "566": "French horn, horn", + "567": "frying pan, frypan, skillet", + "568": "fur coat", + "569": "garbage truck, dustcart", + "570": "gasmask, respirator, gas helmet", + "571": "gas pump, gasoline pump, petrol pump, island dispenser", + "572": "goblet", + "573": "go-kart", + "574": "golf ball", + "575": "golfcart, golf cart", + "576": "gondola", + "577": "gong, tam-tam", + "578": "gown", + "579": "grand piano, grand", + "580": "greenhouse, nursery, glasshouse", + "581": "grille, radiator grille", + "582": "grocery store, grocery, food market, market", + "583": "guillotine", + "584": "hair slide", + "585": "hair spray", + "586": "half track", + "587": "hammer", + "588": "hamper", + "589": "hand blower, blow dryer, blow drier, hair dryer, hair drier", + "590": "hand-held computer, hand-held microcomputer", + "591": "handkerchief, hankie, hanky, hankey", + "592": "hard disc, hard disk, fixed disk", + "593": "harmonica, mouth organ, harp, mouth harp", + "594": "harp", + "595": "harvester, reaper", + "596": "hatchet", + "597": "holster", + "598": "home theater, home theatre", + "599": "honeycomb", + "600": "hook, claw", + "601": "hoopskirt, crinoline", + "602": "horizontal bar, high bar", + "603": "horse cart, horse-cart", + "604": "hourglass", + "605": "iPod", + "606": "iron, smoothing iron", + "607": "jack-o-lantern", + "608": "jean, blue jean, denim", + "609": "jeep, landrover", + "610": "jersey, T-shirt, tee shirt", + "611": "jigsaw puzzle", + "612": "jinrikisha, ricksha, rickshaw", + "613": "joystick", + "614": "kimono", + "615": "knee pad", + "616": "knot", + "617": "lab coat, laboratory coat", + "618": "ladle", + "619": "lampshade, lamp shade", + "620": "laptop, laptop computer", + "621": "lawn mower, mower", + "622": "lens cap, lens cover", + "623": "letter opener, paper knife, paperknife", + "624": "library", + "625": "lifeboat", + "626": "lighter, light, igniter, ignitor", + "627": "limousine, limo", + "628": "liner, ocean liner", + "629": "lipstick, lip rouge", + "630": "Loafer", + "631": "lotion", + "632": "loudspeaker, speaker, speaker unit, loudspeaker system, speaker system", + "633": "loupe, jewelers loupe", + "634": "lumbermill, sawmill", + "635": "magnetic compass", + "636": "mailbag, postbag", + "637": "mailbox, letter box", + "638": "maillot", + "639": "maillot, tank suit", + "640": "manhole cover", + "641": "maraca", + "642": "marimba, xylophone", + "643": "mask", + "644": "matchstick", + "645": "maypole", + "646": "maze, labyrinth", + "647": "measuring cup", + "648": "medicine chest, medicine cabinet", + "649": "megalith, megalithic structure", + "650": "microphone, mike", + "651": "microwave, microwave oven", + "652": "military uniform", + "653": "milk can", + "654": "minibus", + "655": "miniskirt, mini", + "656": "minivan", + "657": "missile", + "658": "mitten", + "659": "mixing bowl", + "660": "mobile home, manufactured home", + "661": "Model T", + "662": "modem", + "663": "monastery", + "664": "monitor", + "665": "moped", + "666": "mortar", + "667": "mortarboard", + "668": "mosque", + "669": "mosquito net", + "670": "motor scooter, scooter", + "671": "mountain bike, all-terrain bike, off-roader", + "672": "mountain tent", + "673": "mouse, computer mouse", + "674": "mousetrap", + "675": "moving van", + "676": "muzzle", + "677": "nail", + "678": "neck brace", + "679": "necklace", + "680": "nipple", + "681": "notebook, notebook computer", + "682": "obelisk", + "683": "oboe, hautboy, hautbois", + "684": "ocarina, sweet potato", + "685": "odometer, hodometer, mileometer, milometer", + "686": "oil filter", + "687": "organ, pipe organ", + "688": "oscilloscope, scope, cathode-ray oscilloscope, CRO", + "689": "overskirt", + "690": "oxcart", + "691": "oxygen mask", + "692": "packet", + "693": "paddle, boat paddle", + "694": "paddlewheel, paddle wheel", + "695": "padlock", + "696": "paintbrush", + "697": "pajama, pyjama, pjs, jammies", + "698": "palace", + "699": "panpipe, pandean pipe, syrinx", + "700": "paper towel", + "701": "parachute, chute", + "702": "parallel bars, bars", + "703": "park bench", + "704": "parking meter", + "705": "passenger car, coach, carriage", + "706": "patio, terrace", + "707": "pay-phone, pay-station", + "708": "pedestal, plinth, footstall", + "709": "pencil box, pencil case", + "710": "pencil sharpener", + "711": "perfume, essence", + "712": "Petri dish", + "713": "photocopier", + "714": "pick, plectrum, plectron", + "715": "pickelhaube", + "716": "picket fence, paling", + "717": "pickup, pickup truck", + "718": "pier", + "719": "piggy bank, penny bank", + "720": "pill bottle", + "721": "pillow", + "722": "ping-pong ball", + "723": "pinwheel", + "724": "pirate, pirate ship", + "725": "pitcher, ewer", + "726": "plane, carpenters plane, woodworking plane", + "727": "planetarium", + "728": "plastic bag", + "729": "plate rack", + "730": "plow, plough", + "731": "plunger, plumbers helper", + "732": "Polaroid camera, Polaroid Land camera", + "733": "pole", + "734": "police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria", + "735": "poncho", + "736": "pool table, billiard table, snooker table", + "737": "pop bottle, soda bottle", + "738": "pot, flowerpot", + "739": "potters wheel", + "740": "power drill", + "741": "prayer rug, prayer mat", + "742": "printer", + "743": "prison, prison house", + "744": "projectile, missile", + "745": "projector", + "746": "puck, hockey puck", + "747": "punching bag, punch bag, punching ball, punchball", + "748": "purse", + "749": "quill, quill pen", + "750": "quilt, comforter, comfort, puff", + "751": "racer, race car, racing car", + "752": "racket, racquet", + "753": "radiator", + "754": "radio, wireless", + "755": "radio telescope, radio reflector", + "756": "rain barrel", + "757": "recreational vehicle, RV, R.V.", + "758": "reel", + "759": "reflex camera", + "760": "refrigerator, icebox", + "761": "remote control, remote", + "762": "restaurant, eating house, eating place, eatery", + "763": "revolver, six-gun, six-shooter", + "764": "rifle", + "765": "rocking chair, rocker", + "766": "rotisserie", + "767": "rubber eraser, rubber, pencil eraser", + "768": "rugby ball", + "769": "rule, ruler", + "770": "running shoe", + "771": "safe", + "772": "safety pin", + "773": "saltshaker, salt shaker", + "774": "sandal", + "775": "sarong", + "776": "sax, saxophone", + "777": "scabbard", + "778": "scale, weighing machine", + "779": "school bus", + "780": "schooner", + "781": "scoreboard", + "782": "screen, CRT screen", + "783": "screw", + "784": "screwdriver", + "785": "seat belt, seatbelt", + "786": "sewing machine", + "787": "shield, buckler", + "788": "shoe shop, shoe-shop, shoe store", + "789": "shoji", + "790": "shopping basket", + "791": "shopping cart", + "792": "shovel", + "793": "shower cap", + "794": "shower curtain", + "795": "ski", + "796": "ski mask", + "797": "sleeping bag", + "798": "slide rule, slipstick", + "799": "sliding door", + "800": "slot, one-armed bandit", + "801": "snorkel", + "802": "snowmobile", + "803": "snowplow, snowplough", + "804": "soap dispenser", + "805": "soccer ball", + "806": "sock", + "807": "solar dish, solar collector, solar furnace", + "808": "sombrero", + "809": "soup bowl", + "810": "space bar", + "811": "space heater", + "812": "space shuttle", + "813": "spatula", + "814": "speedboat", + "815": "spider web, spiders web", + "816": "spindle", + "817": "sports car, sport car", + "818": "spotlight, spot", + "819": "stage", + "820": "steam locomotive", + "821": "steel arch bridge", + "822": "steel drum", + "823": "stethoscope", + "824": "stole", + "825": "stone wall", + "826": "stopwatch, stop watch", + "827": "stove", + "828": "strainer", + "829": "streetcar, tram, tramcar, trolley, trolley car", + "830": "stretcher", + "831": "studio couch, day bed", + "832": "stupa, tope", + "833": "submarine, pigboat, sub, U-boat", + "834": "suit, suit of clothes", + "835": "sundial", + "836": "sunglass", + "837": "sunglasses, dark glasses, shades", + "838": "sunscreen, sunblock, sun blocker", + "839": "suspension bridge", + "840": "swab, swob, mop", + "841": "sweatshirt", + "842": "swimming trunks, bathing trunks", + "843": "swing", + "844": "switch, electric switch, electrical switch", + "845": "syringe", + "846": "table lamp", + "847": "tank, army tank, armored combat vehicle, armoured combat vehicle", + "848": "tape player", + "849": "teapot", + "850": "teddy, teddy bear", + "851": "television, television system", + "852": "tennis ball", + "853": "thatch, thatched roof", + "854": "theater curtain, theatre curtain", + "855": "thimble", + "856": "thresher, thrasher, threshing machine", + "857": "throne", + "858": "tile roof", + "859": "toaster", + "860": "tobacco shop, tobacconist shop, tobacconist", + "861": "toilet seat", + "862": "torch", + "863": "totem pole", + "864": "tow truck, tow car, wrecker", + "865": "toyshop", + "866": "tractor", + "867": "trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi", + "868": "tray", + "869": "trench coat", + "870": "tricycle, trike, velocipede", + "871": "trimaran", + "872": "tripod", + "873": "triumphal arch", + "874": "trolleybus, trolley coach, trackless trolley", + "875": "trombone", + "876": "tub, vat", + "877": "turnstile", + "878": "typewriter keyboard", + "879": "umbrella", + "880": "unicycle, monocycle", + "881": "upright, upright piano", + "882": "vacuum, vacuum cleaner", + "883": "vase", + "884": "vault", + "885": "velvet", + "886": "vending machine", + "887": "vestment", + "888": "viaduct", + "889": "violin, fiddle", + "890": "volleyball", + "891": "waffle iron", + "892": "wall clock", + "893": "wallet, billfold, notecase, pocketbook", + "894": "wardrobe, closet, press", + "895": "warplane, military plane", + "896": "washbasin, handbasin, washbowl, lavabo, wash-hand basin", + "897": "washer, automatic washer, washing machine", + "898": "water bottle", + "899": "water jug", + "900": "water tower", + "901": "whiskey jug", + "902": "whistle", + "903": "wig", + "904": "window screen", + "905": "window shade", + "906": "Windsor tie", + "907": "wine bottle", + "908": "wing", + "909": "wok", + "910": "wooden spoon", + "911": "wool, woolen, woollen", + "912": "worm fence, snake fence, snake-rail fence, Virginia fence", + "913": "wreck", + "914": "yawl", + "915": "yurt", + "916": "web site, website, internet site, site", + "917": "comic book", + "918": "crossword puzzle, crossword", + "919": "street sign", + "920": "traffic light, traffic signal, stoplight", + "921": "book jacket, dust cover, dust jacket, dust wrapper", + "922": "menu", + "923": "plate", + "924": "guacamole", + "925": "consomme", + "926": "hot pot, hotpot", + "927": "trifle", + "928": "ice cream, icecream", + "929": "ice lolly, lolly, lollipop, popsicle", + "930": "French loaf", + "931": "bagel, beigel", + "932": "pretzel", + "933": "cheeseburger", + "934": "hotdog, hot dog, red hot", + "935": "mashed potato", + "936": "head cabbage", + "937": "broccoli", + "938": "cauliflower", + "939": "zucchini, courgette", + "940": "spaghetti squash", + "941": "acorn squash", + "942": "butternut squash", + "943": "cucumber, cuke", + "944": "artichoke, globe artichoke", + "945": "bell pepper", + "946": "cardoon", + "947": "mushroom", + "948": "Granny Smith", + "949": "strawberry", + "950": "orange", + "951": "lemon", + "952": "fig", + "953": "pineapple, ananas", + "954": "banana", + "955": "jackfruit, jak, jack", + "956": "custard apple", + "957": "pomegranate", + "958": "hay", + "959": "carbonara", + "960": "chocolate sauce, chocolate syrup", + "961": "dough", + "962": "meat loaf, meatloaf", + "963": "pizza, pizza pie", + "964": "potpie", + "965": "burrito", + "966": "red wine", + "967": "espresso", + "968": "cup", + "969": "eggnog", + "970": "alp", + "971": "bubble", + "972": "cliff, drop, drop-off", + "973": "coral reef", + "974": "geyser", + "975": "lakeside, lakeshore", + "976": "promontory, headland, head, foreland", + "977": "sandbar, sand bar", + "978": "seashore, coast, seacoast, sea-coast", + "979": "valley, vale", + "980": "volcano", + "981": "ballplayer, baseball player", + "982": "groom, bridegroom", + "983": "scuba diver", + "984": "rapeseed", + "985": "daisy", + "986": "yellow ladys slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum", + "987": "corn", + "988": "acorn", + "989": "hip, rose hip, rosehip", + "990": "buckeye, horse chestnut, conker", + "991": "coral fungus", + "992": "agaric", + "993": "gyromitra", + "994": "stinkhorn, carrion fungus", + "995": "earthstar", + "996": "hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa", + "997": "bolete", + "998": "ear, spike, capitulum", + "999": "toilet tissue, toilet paper, bathroom tissue" + }, + "scheduler": [ + "scheduling_flow_match_pae", + "PAEFlowMatchScheduler" + ], + "transformers": [ + "transformer_lightning_dit", + "LightningDiT2DModel" + ] +} diff --git a/pae-mae-large-d32/pipeline.py b/pae-mae-large-d32/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..baed829d24d510b38fe9905fd001b835a176475f --- /dev/null +++ b/pae-mae-large-d32/pipeline.py @@ -0,0 +1,530 @@ +"""Hub custom pipeline: PAEPipeline. +Load with native Hugging Face diffusers and trust_remote_code=True. +""" + +from __future__ import annotations + +# Copyright 2026 The HuggingFace Team and PAE authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import inspect +import json +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple, Union + +import torch + +from diffusers.image_processor import VaeImageProcessor +from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput +from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers +from diffusers.utils.torch_utils import randn_tensor + +EXAMPLE_DOC_STRING = """ + Examples: + ```py + >>> from pathlib import Path + >>> from diffusers import DiffusionPipeline + >>> import torch + + >>> model_dir = Path("./pae-dinov2-large-d32").resolve() + >>> pipe = DiffusionPipeline.from_pretrained( + ... str(model_dir), + ... local_files_only=True, + ... custom_pipeline=str(model_dir / "pipeline.py"), + ... trust_remote_code=True, + ... torch_dtype=torch.bfloat16, + ... ) + >>> pipe.to("cuda") + + >>> print(pipe.id2label[207]) + >>> print(pipe.get_label_ids("golden retriever")) + + >>> generator = torch.Generator(device="cuda").manual_seed(42) + >>> image = pipe( + ... class_labels="golden retriever", + ... generator=generator, + ... ).images[0] + ``` +""" + + +class PAEPipeline(DiffusionPipeline): + r""" + Pipeline for class-conditional image generation with PAE tokenizers and LightningDiT. + + This model inherits from [`DiffusionPipeline`]. Components are stored in separate subfolders + (`transformers/`, `scheduler/`, `decoder/`) and loaded via `DiffusionPipeline.from_pretrained`. + + Parameters: + transformers ([`LightningDiT2DModel`]): + Class-conditional LightningDiT transformer that predicts flow-matching velocity in PAE latent space. + scheduler ([`PAEFlowMatchScheduler`]): + Flow-matching ODE/SDE scheduler. Other [`KarrasDiffusionSchedulers`] can be swapped at inference time + when their `step` API is compatible. + decoder ([`PAEDecoder`]): + Prior-Aligned Autoencoder decoder stack (decompressor + pixel decoder). + + ImageNet `id2label` mappings are read lazily from `model_index.json` when label helpers are used. + """ + + model_cpu_offload_seq = "transformers->decoder" + _optional_components = ["decoder"] + + @staticmethod + def prepare_extra_step_kwargs( + scheduler: KarrasDiffusionSchedulers, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + eta: Optional[float] = None, + ) -> Dict[str, object]: + r""" + Build kwargs forwarded to `scheduler.step` when supported. + + Args: + scheduler: + Active diffusion scheduler instance. + generator: + Optional RNG passed through to stochastic scheduler steps. + eta: + Optional DDIM-style eta when the scheduler accepts it. + """ + kwargs: Dict[str, object] = {} + step_params = set(inspect.signature(scheduler.step).parameters.keys()) + if "generator" in step_params: + kwargs["generator"] = generator + if eta is not None and "eta" in step_params: + kwargs["eta"] = eta + return kwargs + + def __init__( + self, + transformers, + scheduler: KarrasDiffusionSchedulers, + decoder=None, + transformer=None, + ) -> None: + if transformer is not None and transformers is None: + transformers = transformer + super().__init__() + self.register_modules(transformers=transformers, scheduler=scheduler, decoder=decoder) + # PAE decoders already return pixels in [0, 1]; disable VAE-style [-1, 1] denormalization. + self.image_processor = VaeImageProcessor(do_normalize=False) + self._id2label: Dict[int, str] = {} + self.labels: Dict[str, int] = {} + self._labels_loaded_from_model_index = False + + @property + def transformer(self): + """Backward-compatible alias for `transformers`.""" + return self.transformers + + @staticmethod + def _normalize_id2label(id2label: Optional[Dict[Union[int, str], str]]) -> Dict[int, str]: + if not id2label: + return {} + return {int(key): value for key, value in id2label.items()} + + @staticmethod + def _read_model_index(variant_path: Optional[str]) -> Dict[str, Any]: + if not variant_path: + return {} + variant_dir = Path(variant_path).resolve() + model_index_path = variant_dir / "model_index.json" + if not model_index_path.is_file(): + return {} + raw = json.loads(model_index_path.read_text(encoding="utf-8")) + return raw if isinstance(raw, dict) else {} + + @staticmethod + def _read_id2label_from_model_index(variant_path: Optional[str]) -> Dict[int, str]: + id2label = PAEPipeline._read_model_index(variant_path).get("id2label") + if not isinstance(id2label, dict): + return {} + return {int(key): value for key, value in id2label.items()} + + def _get_downsample_ratio(self) -> int: + override = getattr(self.config, "downsample_ratio", None) + if override is not None: + return int(override) + + encoder_input_size = None + if self.decoder is not None: + encoder_input_size = getattr(self.decoder.config, "encoder_input_size", None) + + if encoder_input_size is not None: + return int(encoder_input_size) // int(self.transformers.config.input_size) + return 16 + + def _resolve_latent_stats( + self, + latent_mean: Optional[torch.Tensor], + latent_std: Optional[torch.Tensor], + latent_multiplier: Optional[float], + device: torch.device, + dtype: torch.dtype, + ) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], float]: + if latent_mean is not None and latent_std is not None: + return latent_mean, latent_std, float(latent_multiplier if latent_multiplier is not None else 1.0) + + decoder_cfg = getattr(self.decoder, "config", None) if self.decoder is not None else None + if decoder_cfg is not None: + mean = getattr(decoder_cfg, "latent_mean", None) + std = getattr(decoder_cfg, "latent_std", None) + if mean is not None and std is not None: + multiplier = getattr(decoder_cfg, "latent_multiplier", 1.0) + mean_tensor = torch.tensor(mean, device=device, dtype=dtype).view(1, -1, 1, 1) + std_tensor = torch.tensor(std, device=device, dtype=dtype).view(1, -1, 1, 1) + return mean_tensor, std_tensor, float(multiplier) + + return latent_mean, latent_std, float(latent_multiplier if latent_multiplier is not None else 1.0) + + @staticmethod + def _build_label2id(id2label: Dict[int, str]) -> Dict[str, int]: + label2id: Dict[str, int] = {} + for class_id, value in id2label.items(): + for synonym in value.split(","): + synonym = synonym.strip() + if synonym: + label2id[synonym] = int(class_id) + return dict(sorted(label2id.items())) + + def _ensure_labels_loaded(self) -> None: + if self._labels_loaded_from_model_index: + return + loaded = self._read_id2label_from_model_index(getattr(self.config, "_name_or_path", None)) + if loaded: + self._id2label = loaded + self.labels = self._build_label2id(self._id2label) + self._labels_loaded_from_model_index = True + + @property + def id2label(self) -> Dict[int, str]: + r"""ImageNet class id to English label string (comma-separated synonyms).""" + self._ensure_labels_loaded() + return self._id2label + + def get_label_ids(self, label: Union[str, List[str]]) -> List[int]: + r""" + Map ImageNet label strings to class ids. + + Args: + label: + One or more English label strings. Each string must match a synonym in `id2label`. + + Returns: + Matching ImageNet class ids. + """ + self._ensure_labels_loaded() + label2id = self.labels + if not label2id: + raise ValueError("No English labels loaded. Ensure `id2label` exists in model_index.json.") + + if isinstance(label, str): + label = [label] + + missing = [item for item in label if item not in label2id] + if missing: + preview = ", ".join(list(label2id.keys())[:8]) + raise ValueError(f"Unknown English label(s): {missing}. Example valid labels: {preview}, ...") + return [label2id[item] for item in label] + + def _default_image_size(self) -> int: + return int(self.transformers.config.input_size) * self._get_downsample_ratio() + + def _normalize_class_labels( + self, + class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor], + ) -> torch.LongTensor: + if torch.is_tensor(class_labels): + return class_labels.to(device=self._execution_device, dtype=torch.long).reshape(-1) + + if isinstance(class_labels, int): + class_label_ids = [class_labels] + elif isinstance(class_labels, str): + class_label_ids = self.get_label_ids(class_labels) + elif class_labels and isinstance(class_labels[0], str): + class_label_ids = self.get_label_ids(class_labels) + else: + class_label_ids = list(class_labels) + + return torch.tensor(class_label_ids, device=self._execution_device, dtype=torch.long).reshape(-1) + + def check_inputs( + self, + height: int, + width: int, + num_inference_steps: int, + output_type: str, + mode: str, + ) -> None: + if num_inference_steps < 1: + raise ValueError("num_inference_steps must be >= 1.") + if output_type not in {"pil", "np", "pt", "latent"}: + raise ValueError("output_type must be one of: 'pil', 'np', 'pt', 'latent'.") + if mode not in {"ode", "sde"}: + raise ValueError("mode must be either 'ode' or 'sde'.") + + downsample = self._get_downsample_ratio() + if height % downsample != 0 or width % downsample != 0: + raise ValueError( + f"height and width must be divisible by the PAE downsample factor {downsample}." + ) + + latent_height = height // downsample + latent_width = width // downsample + expected_size = int(self.transformers.config.input_size) + if latent_height != expected_size or latent_width != expected_size: + raise ValueError( + f"Requested latent size {(latent_height, latent_width)} does not match the pretrained " + f"transformer input_size={expected_size}. Use height=width={self._default_image_size()}." + ) + + def prepare_latents( + self, + batch_size: int, + height: int, + width: int, + dtype: torch.dtype, + device: torch.device, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + ) -> torch.Tensor: + downsample = self._get_downsample_ratio() + latent_height = height // downsample + latent_width = width // downsample + return randn_tensor( + (batch_size, self.transformers.config.in_channels, latent_height, latent_width), + generator=generator, + device=device, + dtype=dtype, + ) + + @staticmethod + def _denormalize_latents( + latents: torch.Tensor, + latent_mean: Optional[torch.Tensor], + latent_std: Optional[torch.Tensor], + latent_multiplier: Optional[float], + ) -> torch.Tensor: + if latent_mean is None or latent_std is None: + return latents + multiplier = 1.0 if latent_multiplier is None else float(latent_multiplier) + mean = latent_mean.to(device=latents.device, dtype=latents.dtype) + std = latent_std.to(device=latents.device, dtype=latents.dtype) + return (latents * std) / multiplier + mean + + @staticmethod + def _apply_cfg( + model_output: torch.Tensor, + guidance_scale: float, + guidance_active: bool, + cfg_channels: int, + ) -> torch.Tensor: + if guidance_scale <= 1.0 or not guidance_active: + return model_output + eps, rest = model_output[:, :cfg_channels], model_output[:, cfg_channels:] + cond_eps, uncond_eps = torch.chunk(eps, 2, dim=0) + half_eps = uncond_eps + guidance_scale * (cond_eps - uncond_eps) + if rest.shape[1] == 0: + return half_eps + return torch.cat([half_eps, rest], dim=1) + + def decode_latents( + self, + latents: torch.Tensor, + output_type: str = "pil", + latent_mean: Optional[torch.Tensor] = None, + latent_std: Optional[torch.Tensor] = None, + latent_multiplier: Optional[float] = None, + ): + if output_type == "latent": + return latents + if self.decoder is None: + raise ValueError("PAEPipeline requires a PAE decoder component for decoding.") + + latent_mean, latent_std, latent_multiplier = self._resolve_latent_stats( + latent_mean, + latent_std, + latent_multiplier, + device=latents.device, + dtype=latents.dtype, + ) + latents = self._denormalize_latents(latents, latent_mean, latent_std, latent_multiplier) + image = self.decoder.decode(latents) + image = torch.clamp(image, 0.0, 1.0) + if output_type == "pt": + return image + return self.image_processor.postprocess(image, output_type=output_type, do_denormalize=[False] * image.shape[0]) + + @torch.inference_mode() + def __call__( + self, + class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor], + height: Optional[int] = None, + width: Optional[int] = None, + num_inference_steps: int = 250, + guidance_scale: float = 3.3, + guidance_interval: Tuple[float, float] = (0.0, 1.0), + cfg_interval_start: float = 0.3, + timestep_shift: float = 0.4, + mode: str = "ode", + heun: bool = False, + latent_mean: Optional[torch.Tensor] = None, + latent_std: Optional[torch.Tensor] = None, + latent_multiplier: Optional[float] = None, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + output_type: str = "pil", + return_dict: bool = True, + ) -> Union[ImagePipelineOutput, Tuple]: + r""" + Generate class-conditional images with PAE + LightningDiT. + + Args: + class_labels: + ImageNet class indices or human-readable English label strings. + height: + Output image height in pixels. Defaults to the pretrained native resolution. + width: + Output image width in pixels. Defaults to the pretrained native resolution. + num_inference_steps: + Number of flow-matching integration steps. + guidance_scale: + Classifier-free guidance scale. Active when `guidance_scale > 1.0`. + guidance_interval: + Timestep interval `(low, high)` where CFG is applied. + cfg_interval_start: + Disable CFG below this normalized timestep value. Default `0.3` matches DiT training configs. + timestep_shift: + Timestep warping used by LightningDiT ODE sampling. Default `0.4` matches DiT training configs. + mode: + Sampling mode passed to the PAE flow scheduler: `"ode"` or `"sde"`. + heun: + Use Heun integration for ODE sampling when True. + latent_mean: + Optional latent mean tensor for denormalization before PAE decode. Defaults to + `latent_mean` in `decoder/config.json` when omitted. + latent_std: + Optional latent std tensor for denormalization before PAE decode. Defaults to + `latent_std` in `decoder/config.json` when omitted. + latent_multiplier: + Divisor applied with `latent_std` during denormalization. Defaults to + `latent_multiplier` in `decoder/config.json` or `1.0`. + generator: + RNG for reproducibility. + output_type: + `"pil"`, `"np"`, `"pt"`, or `"latent"`. + return_dict: + Return [`ImagePipelineOutput`] if True. + """ + default_size = self._default_image_size() + height = int(height or default_size) + width = int(width or default_size) + self.check_inputs(height, width, num_inference_steps, output_type, mode) + + device = self._execution_device + model_dtype = next(self.transformers.parameters()).dtype + class_labels_tensor = self._normalize_class_labels(class_labels) + batch_size = class_labels_tensor.numel() + null_label = int(self.transformers.config.num_classes) + null_labels = torch.full((batch_size,), null_label, device=device, dtype=torch.long) + cfg_channels = int(self.transformers.config.in_channels) + + latents = self.prepare_latents( + batch_size=batch_size, + height=height, + width=width, + dtype=model_dtype, + device=device, + generator=generator, + ) + timesteps = self.scheduler.set_timesteps( + num_inference_steps, device=device, mode=mode, timestep_shift=timestep_shift + ) + extra_step_kwargs = self.prepare_extra_step_kwargs(self.scheduler, generator=generator) + + for index, timestep in enumerate(timesteps[:-1]): + next_timestep = timesteps[index + 1] + t_value = float(timestep) + guidance_active = guidance_scale > 1.0 and guidance_interval[0] <= t_value <= guidance_interval[1] + if cfg_interval_start is not None and t_value < cfg_interval_start: + guidance_active = False + + if guidance_active: + model_input = torch.cat([latents, latents], dim=0) + labels = torch.cat([class_labels_tensor, null_labels], dim=0) + else: + model_input = latents + labels = class_labels_tensor + + timestep_batch = torch.full((labels.shape[0],), t_value, device=device, dtype=model_dtype) + model_output = self.transformers( + model_input.to(dtype=model_dtype), + timestep=timestep_batch, + class_labels=labels, + return_dict=True, + ).sample + model_output = self._apply_cfg(model_output, guidance_scale, guidance_active, cfg_channels) + + if heun and mode == "ode" and index < len(timesteps) - 2: + provisional = self.scheduler.step( + model_output, + timestep[None], + latents, + next_timestep[None], + **extra_step_kwargs, + ).prev_sample + if guidance_active: + prime_input = torch.cat([provisional, provisional], dim=0) + prime_labels = torch.cat([class_labels_tensor, null_labels], dim=0) + else: + prime_input = provisional + prime_labels = class_labels_tensor + next_timestep_batch = torch.full( + (prime_labels.shape[0],), float(next_timestep), device=device, dtype=model_dtype + ) + next_output = self.transformers( + prime_input.to(dtype=model_dtype), + timestep=next_timestep_batch, + class_labels=prime_labels, + return_dict=True, + ).sample + next_output = self._apply_cfg(next_output, guidance_scale, guidance_active, cfg_channels) + latents = self.scheduler.step_heun( + model_output, next_output, timestep[None], latents, next_timestep[None] + ).prev_sample + else: + latents = self.scheduler.step( + model_output, + timestep[None], + latents, + next_timestep[None], + **extra_step_kwargs, + ).prev_sample + + image = self.decode_latents( + latents.to(dtype=model_dtype), + output_type=output_type, + latent_mean=latent_mean, + latent_std=latent_std, + latent_multiplier=latent_multiplier, + ) + + self.maybe_free_model_hooks() + if not return_dict: + return (image,) + return ImagePipelineOutput(images=image) + + +# Backward-compatible alias used by earlier PAE-diffusers releases. +PAEPipelineOutput = ImagePipelineOutput diff --git a/pae-mae-large-d32/scheduler/scheduler_config.json b/pae-mae-large-d32/scheduler/scheduler_config.json new file mode 100644 index 0000000000000000000000000000000000000000..75d51d14e68c7500bbb2ddd937dc7669b8d3e27d --- /dev/null +++ b/pae-mae-large-d32/scheduler/scheduler_config.json @@ -0,0 +1,7 @@ +{ + "_class_name": "PAEFlowMatchScheduler", + "_diffusers_version": "0.31.0", + "mode": "ode", + "path_type": "linear", + "num_train_timesteps": 1000 +} diff --git a/pae-mae-large-d32/scheduler/scheduling_flow_match_pae.py b/pae-mae-large-d32/scheduler/scheduling_flow_match_pae.py new file mode 100644 index 0000000000000000000000000000000000000000..e79368596bb250ea5689e1775d653291ab6e55c1 --- /dev/null +++ b/pae-mae-large-d32/scheduler/scheduling_flow_match_pae.py @@ -0,0 +1,200 @@ +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. + +from dataclasses import dataclass +from typing import Optional, Tuple + +import numpy as np +import torch + +try: + from diffusers.configuration_utils import ConfigMixin, register_to_config + from diffusers.schedulers.scheduling_utils import SchedulerMixin + from diffusers.utils import BaseOutput +except Exception: # pragma: no cover - importable without an installed diffusers checkout. + class BaseOutput(dict): + def __post_init__(self): + self.update(self.__dict__) + + class ConfigMixin: + config_name = "scheduler_config.json" + + class SchedulerMixin: + pass + + def register_to_config(init): + return init + + +@dataclass +class PAEFlowMatchSchedulerOutput(BaseOutput): + prev_sample: torch.FloatTensor + + +class PAEFlowMatchScheduler(SchedulerMixin, ConfigMixin): + """ + Flow-matching ODE/SDE scheduler used by PAE + LightningDiT pipelines. + + The model predicts velocity with a linear path by default. ODE timesteps run from 0 to 1 + (noise to data), matching LightningDiT transport sampling. + """ + + config_name = "scheduler_config.json" + order = 1 + + @register_to_config + def __init__( + self, + mode: str = "ode", + path_type: str = "linear", + num_train_timesteps: int = 1000, + ): + if mode not in {"ode", "sde"}: + raise ValueError("mode must be either 'ode' or 'sde'.") + if path_type not in {"linear", "cosine"}: + raise ValueError("path_type must be either 'linear' or 'cosine'.") + self.mode = mode + self.path_type = path_type + self.num_train_timesteps = num_train_timesteps + # Native NiT integrates in float64 for better numerical stability. + self.timesteps = torch.from_numpy(np.linspace(0.0, 1.0, num_train_timesteps + 1)).to(dtype=torch.float64) + + @staticmethod + def _apply_timestep_shift(timesteps: torch.Tensor, timestep_shift: float) -> torch.Tensor: + if timestep_shift <= 0: + return timesteps + return timestep_shift * timesteps / (1 + (timestep_shift - 1) * timesteps) + + def set_timesteps( + self, + num_inference_steps: int, + device: Optional[torch.device] = None, + mode: Optional[str] = None, + timestep_shift: float = 0.0, + ): + mode = mode or self.mode + dtype = self.timesteps.dtype + if mode == "sde": + timesteps = torch.linspace(1.0, 0.04, num_inference_steps, dtype=dtype) + timesteps = torch.cat([timesteps, torch.zeros(1, dtype=dtype)]) + elif mode == "ode": + timesteps = torch.linspace(0.0, 1.0, num_inference_steps + 1, dtype=dtype) + timesteps = self._apply_timestep_shift(timesteps, timestep_shift) + else: + raise ValueError("mode must be either 'ode' or 'sde'.") + self.mode = mode + self.timesteps = timesteps.to(device=device) + return self.timesteps + + @staticmethod + def _expand_t_like_sample(timestep: torch.Tensor, sample: torch.Tensor, image_sizes: torch.LongTensor): + dims = [1] * (sample.ndim - 1) + seqlens = image_sizes[:, 0] * image_sizes[:, 1] + if timestep.numel() == 1: + timestep = timestep.repeat(image_sizes.shape[0]) + return torch.cat( + [timestep[i].reshape(1, *dims).repeat(int(seqlens[i]), *dims) for i in range(image_sizes.shape[0])] + ) + + def _get_score_from_velocity( + self, + model_output: torch.Tensor, + sample: torch.Tensor, + timestep: torch.Tensor, + image_sizes: torch.LongTensor, + ): + timestep = self._expand_t_like_sample(timestep, sample, image_sizes) + if self.path_type == "linear": + alpha_t, d_alpha_t = 1 - timestep, torch.ones_like(timestep) * -1 + sigma_t, d_sigma_t = timestep, torch.ones_like(timestep) + elif self.path_type == "cosine": + alpha_t = torch.cos(timestep * np.pi / 2) + sigma_t = torch.sin(timestep * np.pi / 2) + d_alpha_t = -np.pi / 2 * torch.sin(timestep * np.pi / 2) + d_sigma_t = np.pi / 2 * torch.cos(timestep * np.pi / 2) + else: + raise ValueError(f"Unsupported path_type: {self.path_type}") + reverse_alpha_ratio = alpha_t / d_alpha_t + variance = sigma_t**2 - reverse_alpha_ratio * d_sigma_t * sigma_t + return (reverse_alpha_ratio * model_output - sample) / variance + + @staticmethod + def _compute_diffusion(timestep: torch.Tensor): + return 2 * timestep + + @staticmethod + def _promote_dtypes(*tensors: torch.Tensor) -> torch.dtype: + dtype = None + for tensor in tensors: + if tensor.is_floating_point() or tensor.is_complex(): + dtype = tensor.dtype if dtype is None else torch.promote_types(dtype, tensor.dtype) + return dtype if dtype is not None else torch.get_default_dtype() + + def step( + self, + model_output: torch.Tensor, + timestep: torch.Tensor, + sample: torch.Tensor, + next_timestep: torch.Tensor, + image_sizes: Optional[torch.LongTensor] = None, + generator: Optional[torch.Generator] = None, + return_dict: bool = True, + ) -> PAEFlowMatchSchedulerOutput: + sample_dtype = sample.dtype + compute_dtype = torch.float64 + sample = sample.to(dtype=compute_dtype) + model_output = model_output.to(dtype=compute_dtype) + timestep = timestep.to(device=sample.device, dtype=compute_dtype).flatten() + next_timestep = next_timestep.to(device=sample.device, dtype=compute_dtype).flatten() + + if self.mode == "ode": + prev_sample = sample + (next_timestep[0] - timestep[0]) * model_output + else: + if image_sizes is None: + batch = sample.shape[0] + side = int(sample.shape[-1]) + image_sizes = torch.tensor([[side, side]] * batch, device=sample.device, dtype=torch.long) + image_sizes = image_sizes.to(device=sample.device, dtype=torch.long) + diffusion = self._compute_diffusion(timestep[0]) + score = self._get_score_from_velocity(model_output, sample, timestep, image_sizes) + drift = model_output - 0.5 * diffusion * score + dt = next_timestep[0] - timestep[0] + if torch.allclose(next_timestep[0], torch.zeros_like(next_timestep[0])): + prev_sample = sample + drift * dt + else: + if generator is not None: + noise = torch.randn(sample.shape, generator=generator, device=sample.device, dtype=sample.dtype) + else: + noise = torch.randn_like(sample) + prev_sample = sample + drift * dt + torch.sqrt(diffusion) * noise * torch.sqrt(torch.abs(dt)) + + prev_sample = prev_sample.to(sample_dtype) + if not return_dict: + return (prev_sample,) + return PAEFlowMatchSchedulerOutput(prev_sample=prev_sample) + + def step_heun( + self, + model_output: torch.Tensor, + next_model_output: torch.Tensor, + timestep: torch.Tensor, + sample: torch.Tensor, + next_timestep: torch.Tensor, + return_dict: bool = True, + ) -> PAEFlowMatchSchedulerOutput: + if self.mode != "ode": + raise ValueError("Heun correction is only defined for ODE sampling.") + sample_dtype = sample.dtype + compute_dtype = torch.float64 + sample = sample.to(dtype=compute_dtype) + model_output = model_output.to(dtype=compute_dtype) + next_model_output = next_model_output.to(dtype=compute_dtype) + timestep = timestep.to(device=sample.device, dtype=compute_dtype).flatten() + next_timestep = next_timestep.to(device=sample.device, dtype=compute_dtype).flatten() + prev_sample = sample + (next_timestep[0] - timestep[0]) * (0.5 * model_output + 0.5 * next_model_output) + prev_sample = prev_sample.to(sample_dtype) + if not return_dict: + return (prev_sample,) + return PAEFlowMatchSchedulerOutput(prev_sample=prev_sample) diff --git a/pae-mae-large-d32/transformers/config.json b/pae-mae-large-d32/transformers/config.json new file mode 100644 index 0000000000000000000000000000000000000000..d5ddc59564b5939f9c622a5c19dc93ed567ac544 --- /dev/null +++ b/pae-mae-large-d32/transformers/config.json @@ -0,0 +1,15 @@ +{ + "_class_name": "LightningDiT2DModel", + "depth": 28, + "hidden_size": 1152, + "in_channels": 32, + "input_size": 16, + "num_classes": 1000, + "num_heads": 16, + "patch_size": 1, + "use_qknorm": true, + "use_rmsnorm": true, + "use_rope": true, + "use_swiglu": true, + "wo_shift": false +} diff --git a/pae-mae-large-d32/transformers/diffusion_pytorch_model.safetensors b/pae-mae-large-d32/transformers/diffusion_pytorch_model.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..10956ca8f6aa911e7e1e3bf00cc39d40945524f5 --- /dev/null +++ b/pae-mae-large-d32/transformers/diffusion_pytorch_model.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:acc704ff0e386b2c71b4a576b3d5e9bff103c8047b61dad3f9dfaeb70d27c750 +size 2701230752 diff --git a/pae-mae-large-d32/transformers/transformer_lightning_dit.py b/pae-mae-large-d32/transformers/transformer_lightning_dit.py new file mode 100644 index 0000000000000000000000000000000000000000..80d061481bca0a538950bfd25b531e8bf1c05d61 --- /dev/null +++ b/pae-mae-large-d32/transformers/transformer_lightning_dit.py @@ -0,0 +1,794 @@ +from __future__ import annotations + +import torch +import torch.nn.functional as F +from torch import nn + + +class RMSNorm(torch.nn.Module): + def __init__(self, dim: int, eps: float = 1e-6): + super().__init__() + self.eps = eps + self.weight = nn.Parameter(torch.ones(dim)) + + def _norm(self, x: torch.Tensor) -> torch.Tensor: + return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + output = self._norm(x.float()).type_as(x) + return output * self.weight + +from math import pi + +import torch +from torch import nn + +from einops import rearrange, repeat + + + +def broadcat(tensors, dim = -1): + num_tensors = len(tensors) + shape_lens = set(list(map(lambda t: len(t.shape), tensors))) + assert len(shape_lens) == 1, 'tensors must all have the same number of dimensions' + shape_len = list(shape_lens)[0] + dim = (dim + shape_len) if dim < 0 else dim + dims = list(zip(*map(lambda t: list(t.shape), tensors))) + expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim] + assert all([*map(lambda t: len(set(t[1])) <= 2, expandable_dims)]), 'invalid dimensions for broadcastable concatentation' + max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims)) + expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims)) + expanded_dims.insert(dim, (dim, dims[dim])) + expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims))) + tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes))) + return torch.cat(tensors, dim = dim) + + + +def rotate_half(x): + x = rearrange(x, '... (d r) -> ... d r', r = 2) + x1, x2 = x.unbind(dim = -1) + x = torch.stack((-x2, x1), dim = -1) + return rearrange(x, '... d r -> ... (d r)') + + + +class VisionRotaryEmbedding(nn.Module): + def __init__( + self, + dim, + pt_seq_len, + ft_seq_len=None, + custom_freqs = None, + freqs_for = 'lang', + theta = 10000, + max_freq = 10, + num_freqs = 1, + ): + super().__init__() + if custom_freqs: + freqs = custom_freqs + elif freqs_for == 'lang': + freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim)) + elif freqs_for == 'pixel': + freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi + elif freqs_for == 'constant': + freqs = torch.ones(num_freqs).float() + else: + raise ValueError(f'unknown modality {freqs_for}') + + if ft_seq_len is None: ft_seq_len = pt_seq_len + t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len + + freqs_h = torch.einsum('..., f -> ... f', t, freqs) + freqs_h = repeat(freqs_h, '... n -> ... (n r)', r = 2) + + freqs_w = torch.einsum('..., f -> ... f', t, freqs) + freqs_w = repeat(freqs_w, '... n -> ... (n r)', r = 2) + + freqs = broadcat((freqs_h[:, None, :], freqs_w[None, :, :]), dim = -1) + + self.register_buffer("freqs_cos", freqs.cos()) + self.register_buffer("freqs_sin", freqs.sin()) + + # print('======== shape of rope freq', self.freqs_cos.shape, '========') + + def forward(self, t, start_index = 0): + rot_dim = self.freqs_cos.shape[-1] + end_index = start_index + rot_dim + assert rot_dim <= t.shape[-1], f'feature dimension {t.shape[-1]} is not of sufficient size to rotate in all the positions {rot_dim}' + t_left, t, t_right = t[..., :start_index], t[..., start_index:end_index], t[..., end_index:] + t = (t * self.freqs_cos) + (rotate_half(t) * self.freqs_sin) + return torch.cat((t_left, t, t_right), dim = -1) + + + +class VisionRotaryEmbeddingFast(nn.Module): + def __init__( + self, + dim, + pt_seq_len=16, + ft_seq_len=None, + custom_freqs = None, + freqs_for = 'lang', + theta = 10000, + max_freq = 10, + num_freqs = 1, + ): + super().__init__() + if custom_freqs: + freqs = custom_freqs + elif freqs_for == 'lang': + freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim)) + elif freqs_for == 'pixel': + freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi + elif freqs_for == 'constant': + freqs = torch.ones(num_freqs).float() + else: + raise ValueError(f'unknown modality {freqs_for}') + + if ft_seq_len is None: ft_seq_len = pt_seq_len + t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len + + freqs = torch.einsum('..., f -> ... f', t, freqs) + freqs = repeat(freqs, '... n -> ... (n r)', r = 2) + freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim = -1) + + freqs_cos = freqs.cos().view(-1, freqs.shape[-1]) + freqs_sin = freqs.sin().view(-1, freqs.shape[-1]) + + self.register_buffer("freqs_cos", freqs_cos) + self.register_buffer("freqs_sin", freqs_sin) + + # print('======== shape of rope freq', self.freqs_cos.shape, '========') + + def forward(self, t): return t * self.freqs_cos + rotate_half(t) * self.freqs_sin + +import os +import torch +from typing import Callable, Optional +import warnings + +from torch import Tensor, nn +import torch.nn.functional as F + + +class SwiGLUFFN(nn.Module): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = None, + drop: float = 0.0, + bias: bool = True, + ) -> None: + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias) + self.w3 = nn.Linear(hidden_features, out_features, bias=bias) + def forward(self, x: Tensor) -> Tensor: + x12 = self.w12(x) + x1, x2 = x12.chunk(2, dim=-1) + hidden = F.silu(x1) * x2 + return self.w3(hidden) + + +XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None +try: + if XFORMERS_ENABLED: + from xformers.ops import SwiGLU + + XFORMERS_AVAILABLE = True + # warnings.warn("xFormers is available (SwiGLU)") + else: + # warnings.warn("xFormers is disabled (SwiGLU)") + raise ImportError +except ImportError: + SwiGLU = SwiGLUFFN + XFORMERS_AVAILABLE = False + + # warnings.warn("xFormers is not available (SwiGLU)") + + +class SwiGLUFFNFused(SwiGLU): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = None, + drop: float = 0.0, + bias: bool = True, + ) -> None: + out_features = out_features or in_features + hidden_features = hidden_features or in_features + hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8 + super().__init__( + in_features=in_features, + hidden_features=hidden_features, + out_features=out_features, + bias=bias, + ) + +from dataclasses import dataclass +from typing import Optional, Tuple, Union + +import torch + +try: + from diffusers.configuration_utils import ConfigMixin, register_to_config + from diffusers.models.modeling_utils import ModelMixin + from diffusers.utils import BaseOutput +except Exception: # pragma: no cover + class BaseOutput(dict): + def __post_init__(self): + self.update(self.__dict__) + + class ConfigMixin: + config_name = "config.json" + + class ModelMixin(torch.nn.Module): + pass + + def register_to_config(init): + return init + + +@dataclass +class LightningDiT2DModelOutput(BaseOutput): + sample: torch.FloatTensor + + +import os +import math +import numpy as np + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.utils.checkpoint import checkpoint + +from timm.models.vision_transformer import PatchEmbed, Mlp +def modulate(x, shift, scale): + if shift is None: + return x * (1 + scale.unsqueeze(1)) + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) + +class Attention(nn.Module): + """ + Attention module of LightningDiT. + """ + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = False, + qk_norm: bool = False, + attn_drop: float = 0., + proj_drop: float = 0., + norm_layer: nn.Module = nn.LayerNorm, + fused_attn: bool = True, + use_rmsnorm: bool = False, + ) -> None: + super().__init__() + assert dim % num_heads == 0, 'dim should be divisible by num_heads' + + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.scale = self.head_dim ** -0.5 + self.fused_attn = fused_attn + + if use_rmsnorm: + norm_layer = RMSNorm + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + def forward(self, x: torch.Tensor, rope=None) -> torch.Tensor: + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) + q, k, v = qkv.unbind(0) + q, k = self.q_norm(q), self.k_norm(k) + + if rope is not None: + q = rope(q) + k = rope(k) + + if self.fused_attn: + x = F.scaled_dot_product_attention( + q, k, v, + dropout_p=self.attn_drop.p if self.training else 0., + ) + else: + q = q * self.scale + attn = q @ k.transpose(-2, -1) + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + x = attn @ v + + x = x.transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class TimestepEmbedder(nn.Module): + """ + Embeds scalar timesteps into vector representations. + Same as DiT. + """ + def __init__(self, hidden_size: int, frequency_embedding_size: int = 256) -> None: + super().__init__() + self.frequency_embedding_size = frequency_embedding_size + self.mlp = nn.Sequential( + nn.Linear(frequency_embedding_size, hidden_size, bias=True), + nn.SiLU(), + nn.Linear(hidden_size, hidden_size, bias=True), + ) + + @staticmethod + def timestep_embedding(t: torch.Tensor, dim: int, max_period: int = 10000) -> torch.Tensor: + """ + Create sinusoidal timestep embeddings. + Args: + t: A 1-D Tensor of N indices, one per batch element. These may be fractional. + dim: The dimension of the output. + max_period: Controls the minimum frequency of the embeddings. + Returns: + An (N, D) Tensor of positional embeddings. + """ + # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py + half = dim // 2 + freqs = torch.exp( + -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half + ).to(device=t.device) + + args = t[:, 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) + + return embedding + def forward(self, t: torch.Tensor) -> torch.Tensor: + t_freq = self.timestep_embedding(t, self.frequency_embedding_size) + t_emb = self.mlp(t_freq) + return t_emb + + +class LabelEmbedder(nn.Module): + """ + Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance. + Same as DiT. + """ + def __init__(self, num_classes, hidden_size, dropout_prob): + super().__init__() + use_cfg_embedding = dropout_prob > 0 + self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size) + self.num_classes = num_classes + self.dropout_prob = dropout_prob + + def token_drop(self, labels, force_drop_ids=None): + """ + Drops labels to enable classifier-free guidance. + """ + if force_drop_ids is None: + drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob + else: + drop_ids = force_drop_ids == 1 + labels = torch.where(drop_ids, self.num_classes, labels) + return labels + def forward(self, labels, train, force_drop_ids=None): + use_dropout = self.dropout_prob > 0 + if (train and use_dropout) or (force_drop_ids is not None): + labels = self.token_drop(labels, force_drop_ids) + embeddings = self.embedding_table(labels) + return embeddings + +class LightningDiTBlock(nn.Module): + """ + Lightning DiT Block. We add features including: + - ROPE + - QKNorm + - RMSNorm + - SwiGLU + - No shift AdaLN. + Not all of them are used in the final model, please refer to the paper for more details. + """ + def __init__( + self, + hidden_size, + num_heads, + mlp_ratio=4.0, + use_qknorm=False, + use_swiglu=False, + use_rmsnorm=False, + wo_shift=False, + **block_kwargs + ): + super().__init__() + + # Initialize normalization layers + if not use_rmsnorm: + self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + else: + self.norm1 = RMSNorm(hidden_size) + self.norm2 = RMSNorm(hidden_size) + + # Initialize attention layer + self.attn = Attention( + hidden_size, + num_heads=num_heads, + qkv_bias=True, + qk_norm=use_qknorm, + use_rmsnorm=use_rmsnorm, + **block_kwargs + ) + + # Initialize MLP layer + mlp_hidden_dim = int(hidden_size * mlp_ratio) + approx_gelu = lambda: nn.GELU(approximate="tanh") + if use_swiglu: + # here we did not use SwiGLU from xformers because it is not compatible with torch.compile for now. + self.mlp = SwiGLUFFN(hidden_size, int(2/3 * mlp_hidden_dim)) + else: + self.mlp = Mlp( + in_features=hidden_size, + hidden_features=mlp_hidden_dim, + act_layer=approx_gelu, + drop=0 + ) + + # Initialize AdaLN modulation + if wo_shift: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(hidden_size, 4 * hidden_size, bias=True) + ) + else: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(hidden_size, 6 * hidden_size, bias=True) + ) + self.wo_shift = wo_shift + def forward(self, x, c, feat_rope=None): + if self.wo_shift: + scale_msa, gate_msa, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(4, dim=1) + shift_msa = None + shift_mlp = None + else: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=1) + + x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa), rope=feat_rope) + x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp)) + return x + +class FinalLayer(nn.Module): + """ + The final layer of LightningDiT. + """ + def __init__(self, hidden_size, patch_size, out_channels, use_rmsnorm=False): + super().__init__() + if not use_rmsnorm: + self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + else: + self.norm_final = RMSNorm(hidden_size) + self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True) + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(hidden_size, 2 * hidden_size, bias=True) + ) + def forward(self, x, c): + shift, scale = self.adaLN_modulation(c).chunk(2, dim=1) + x = modulate(self.norm_final(x), shift, scale) + x = self.linear(x) + return x + + +class LightningDiT2DModel(ModelMixin, ConfigMixin): + """ + Diffusion model with a Transformer backbone. + """ + @register_to_config + def __init__( + self, + input_size: int = 32, + patch_size=2, + in_channels=32, + hidden_size=1152, + depth=28, + num_heads=16, + mlp_ratio=4.0, + class_dropout_prob=0.1, + num_classes=1000, + learn_sigma=False, + use_qknorm=False, + use_swiglu=False, + use_rope=False, + use_rmsnorm=False, + wo_shift=False, + use_checkpoint=False, + use_abs_pos=True, + ): + super().__init__() + self.use_abs_pos = use_abs_pos + self.learn_sigma = learn_sigma + self.in_channels = in_channels + self.out_channels = in_channels if not learn_sigma else in_channels * 2 + self.patch_size = patch_size + self.num_heads = num_heads + self.use_rope = use_rope + self.use_rmsnorm = use_rmsnorm + self.depth = depth + self.hidden_size = hidden_size + self.use_checkpoint = use_checkpoint + self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size, bias=True) + self.t_embedder = TimestepEmbedder(hidden_size) + self.y_embedder = LabelEmbedder(num_classes, hidden_size, class_dropout_prob) + num_patches = self.x_embedder.num_patches + # Will use fixed sin-cos embedding: + self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False) + + if not self.use_abs_pos and not self.use_rope: + import warnings + warnings.warn("Warning: Both Absolute Position Embedding and RoPE are disabled. " + "The model will be permutation-invariant (orderless)!") + + # use rotary position encoding, borrow from EVA + if self.use_rope: + half_head_dim = hidden_size // num_heads // 2 + hw_seq_len = input_size // patch_size + self.feat_rope = VisionRotaryEmbeddingFast( + dim=half_head_dim, + pt_seq_len=hw_seq_len, + ) + else: + self.feat_rope = None + + self.blocks = nn.ModuleList([ + LightningDiTBlock(hidden_size, + num_heads, + mlp_ratio=mlp_ratio, + use_qknorm=use_qknorm, + use_swiglu=use_swiglu, + use_rmsnorm=use_rmsnorm, + wo_shift=wo_shift, + ) for _ in range(depth) + ]) + self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels, use_rmsnorm=use_rmsnorm) + self.initialize_weights() + if hasattr(self, "register_to_config"): + self.register_to_config( + input_size=input_size, + patch_size=patch_size, + in_channels=in_channels, + hidden_size=hidden_size, + depth=depth, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + class_dropout_prob=class_dropout_prob, + num_classes=num_classes, + learn_sigma=learn_sigma, + use_qknorm=use_qknorm, + use_swiglu=use_swiglu, + use_rope=use_rope, + use_rmsnorm=use_rmsnorm, + wo_shift=wo_shift, + use_checkpoint=use_checkpoint, + use_abs_pos=use_abs_pos, + ) + + def initialize_weights(self): + # Initialize transformer layers: + def _basic_init(module): + if isinstance(module, nn.Linear): + torch.nn.init.xavier_uniform_(module.weight) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + self.apply(_basic_init) + + + if self.use_abs_pos: + pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5)) + self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0)) + else: + nn.init.constant_(self.pos_embed, 0) + + # Initialize patch_embed like nn.Linear (instead of nn.Conv2d): + w = self.x_embedder.proj.weight.data + nn.init.xavier_uniform_(w.view([w.shape[0], -1])) + nn.init.constant_(self.x_embedder.proj.bias, 0) + + # Initialize label embedding table: + nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02) + + # Initialize timestep embedding MLP: + nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02) + nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02) + + # Zero-out adaLN modulation layers in LightningDiT blocks: + for block in self.blocks: + nn.init.constant_(block.adaLN_modulation[-1].weight, 0) + nn.init.constant_(block.adaLN_modulation[-1].bias, 0) + + # Zero-out output layers: + nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0) + nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0) + nn.init.constant_(self.final_layer.linear.weight, 0) + nn.init.constant_(self.final_layer.linear.bias, 0) + + def unpatchify(self, x): + """ + x: (N, T, patch_size**2 * C) + imgs: (N, H, W, C) + """ + c = self.out_channels + p = self.x_embedder.patch_size[0] + h = w = int(x.shape[1] ** 0.5) + assert h * w == x.shape[1] + + x = x.reshape(shape=(x.shape[0], h, w, p, p, c)) + x = torch.einsum('nhwpqc->nchpwq', x) + imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p)) + return imgs + + def forward( + self, + hidden_states: torch.Tensor, + timestep: Optional[torch.LongTensor] = None, + class_labels: Optional[torch.LongTensor] = None, + return_dict: bool = True, + ): + x = hidden_states + t = timestep + y = class_labels + """ + Forward pass of LightningDiT. + x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images) + t: (N,) tensor of diffusion timesteps + y: (N,) tensor of class labels + use_checkpoint: boolean to toggle checkpointing + """ + + use_checkpoint = self.use_checkpoint + + x = self.x_embedder(x) + if self.use_abs_pos: + x = x + self.pos_embed + t = self.t_embedder(t) # (N, D) + y = self.y_embedder(y, self.training) # (N, D) + c = t + y # (N, D) + + for block in self.blocks: + if use_checkpoint: + x = checkpoint(block, x, c, self.feat_rope, use_reentrant=True) + else: + x = block(x, c, self.feat_rope) + + x = self.final_layer(x, c) # (N, T, patch_size ** 2 * out_channels) + x = self.unpatchify(x) # (N, out_channels, H, W) + + if self.learn_sigma: + x, _ = x.chunk(2, dim=1) + if not return_dict: + return (x,) + return LightningDiT2DModelOutput(sample=x) + + def forward_with_cfg(self, x, t, y, cfg_scale, cfg_interval=None, cfg_interval_start=None): + """ + Forward pass of LightningDiT, but also batches the unconditional forward pass for classifier-free guidance. + """ + # https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb + combined = torch.cat([x, x], dim=0) + model_out = self.forward(combined, t, y, return_dict=False)[0] + # For exact reproducibility reasons, we apply classifier-free guidance on only + # three channels by default. The standard approach to cfg applies it to all channels. + # This can be done by uncommenting the following line and commenting-out the line following that. + eps, rest = model_out[:, :self.in_channels], model_out[:, self.in_channels:] + # eps, rest = model_out[:, :3], model_out[:, 3:] + cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0) + half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps) + + if cfg_interval is True: + timestep = t[0] + if timestep < cfg_interval_start: + half_eps = cond_eps + + eps = torch.cat([half_eps, half_eps], dim=0) + return torch.cat([eps, rest], dim=1) + +def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0): + """ + grid_size: int of the grid height and width + return: + pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token) + """ + grid_h = np.arange(grid_size, dtype=np.float32) + grid_w = np.arange(grid_size, dtype=np.float32) + grid = np.meshgrid(grid_w, grid_h) # here w goes first + grid = np.stack(grid, axis=0) + + grid = grid.reshape([2, 1, grid_size, grid_size]) + pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) + if cls_token and extra_tokens > 0: + pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0) + return pos_embed + + +def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): + assert embed_dim % 2 == 0 + + # use half of dimensions to encode grid_h + emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) + emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2) + + emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D) + return emb + + +def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): + """ + embed_dim: output dimension for each position + pos: a list of positions to be encoded: size (M,) + out: (M, D) + """ + assert embed_dim % 2 == 0 + omega = np.arange(embed_dim // 2, dtype=np.float64) + omega /= embed_dim / 2. + omega = 1. / 10000**omega # (D/2,) + + pos = pos.reshape(-1) # (M,) + out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product + + emb_sin = np.sin(out) # (M, D/2) + emb_cos = np.cos(out) # (M, D/2) + + emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) + return emb + + +################################################################################# +# LightningDiT Configs # +################################################################################# + +def _lightning_dit_XL_1(**kwargs): + return LightningDiT2DModel(depth=28, hidden_size=1152, patch_size=1, num_heads=16, **kwargs) + +def _lightning_dit_XL_2(**kwargs): + return LightningDiT2DModel(depth=28, hidden_size=1152, patch_size=2, num_heads=16, **kwargs) + +def _lightning_dit_L_2(**kwargs): + return LightningDiT2DModel(depth=24, hidden_size=1024, patch_size=2, num_heads=16, **kwargs) + +def _lightning_dit_B_1(**kwargs): + return LightningDiT2DModel(depth=12, hidden_size=768, patch_size=1, num_heads=12, **kwargs) + +def _lightning_dit_B_2(**kwargs): + return LightningDiT2DModel(depth=12, hidden_size=768, patch_size=2, num_heads=12, **kwargs) + +def _lightning_dit_1p0B_1(**kwargs): + return LightningDiT2DModel(depth=24, hidden_size=1536, patch_size=1, num_heads=24, **kwargs) + +def _lightning_dit_1p0B_2(**kwargs): + return LightningDiT2DModel(depth=24, hidden_size=1536, patch_size=2, num_heads=24, **kwargs) + +def _lightning_dit_1p6B_1(**kwargs): + return LightningDiT2DModel(depth=28, hidden_size=1792, patch_size=1, num_heads=28, **kwargs) + +def _lightning_dit_1p6B_2(**kwargs): + return LightningDiT2DModel(depth=28, hidden_size=1792, patch_size=2, num_heads=28, **kwargs) + +LIGHTNING_DIT_PRESETS = { + 'LightningDiT-B/1': _lightning_dit_B_1, 'LightningDiT-B/2': _lightning_dit_B_2, + 'LightningDiT-L/2': _lightning_dit_L_2, + 'LightningDiT-XL/1': _lightning_dit_XL_1, 'LightningDiT-XL/2': _lightning_dit_XL_2, + 'LightningDiT-1p0B/1': _lightning_dit_1p0B_1, 'LightningDiT-1p0B/2': _lightning_dit_1p0B_2, + 'LightningDiT-1p6B/1': _lightning_dit_1p6B_1, 'LightningDiT-1p6B/2': _lightning_dit_1p6B_2, +} diff --git a/pae-siglip2-so400m-d32/__pycache__/pipeline.cpython-311.pyc b/pae-siglip2-so400m-d32/__pycache__/pipeline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4670e86bbeb6f511a1c12550a556211b079a4e85 Binary files /dev/null and b/pae-siglip2-so400m-d32/__pycache__/pipeline.cpython-311.pyc differ diff --git a/pae-siglip2-so400m-d32/decoder/__pycache__/decoder_pae.cpython-311.pyc b/pae-siglip2-so400m-d32/decoder/__pycache__/decoder_pae.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cff741320f719c901005f4ff591a339fbe83beb8 Binary files /dev/null and b/pae-siglip2-so400m-d32/decoder/__pycache__/decoder_pae.cpython-311.pyc differ diff --git a/pae-siglip2-so400m-d32/decoder/config.json b/pae-siglip2-so400m-d32/decoder/config.json new file mode 100644 index 0000000000000000000000000000000000000000..71dd3c724191b8a9f4ebe8b0f5fd0c2ddf45a336 --- /dev/null +++ b/pae-siglip2-so400m-d32/decoder/config.json @@ -0,0 +1,89 @@ +{ + "_class_name": "PAEDecoder", + "decoder_patch_size": 16, + "encoder_config_path": "google/siglip2-so400m-patch16-256", + "encoder_hidden_size": 1152, + "encoder_input_size": 256, + "encoder_num_heads": 16, + "encoder_patch_size": 16, + "image_mean": [ + 0.5, + 0.5, + 0.5 + ], + "image_std": [ + 0.5, + 0.5, + 0.5 + ], + "latent_dim": 32, + "latent_mean": [ + -0.035400390625, + -0.038818359375, + -0.0220947265625, + 0.06884765625, + -0.52734375, + 0.03076171875, + -0.29296875, + 0.314453125, + -0.294921875, + -0.04296875, + -0.86328125, + -0.057373046875, + -1.6484375, + 0.2890625, + -1.8671875, + 0.05517578125, + -1.6484375, + 1.3203125, + 1.2890625, + 0.333984375, + 0.1396484375, + -0.458984375, + -0.61328125, + 0.326171875, + 0.11181640625, + -0.1923828125, + -0.248046875, + -1.40625, + 1.546875, + 0.037353515625, + 0.19140625, + 2.796875 + ], + "latent_multiplier": 1.0, + "latent_std": [ + 0.357421875, + 0.375, + 0.388671875, + 0.353515625, + 0.349609375, + 0.380859375, + 0.38671875, + 0.44921875, + 0.439453125, + 0.38671875, + 0.431640625, + 0.39453125, + 0.39453125, + 0.40234375, + 0.34765625, + 0.404296875, + 0.458984375, + 0.376953125, + 0.3984375, + 0.435546875, + 0.408203125, + 0.357421875, + 0.41796875, + 0.44140625, + 0.40625, + 0.380859375, + 0.37890625, + 0.515625, + 0.380859375, + 0.388671875, + 0.375, + 0.439453125 + ] +} diff --git a/pae-siglip2-so400m-d32/decoder/decoder_pae.py b/pae-siglip2-so400m-d32/decoder/decoder_pae.py new file mode 100644 index 0000000000000000000000000000000000000000..4592fb0fd62b7324c7d6398d7e50f4229d58a3b3 --- /dev/null +++ b/pae-siglip2-so400m-d32/decoder/decoder_pae.py @@ -0,0 +1,1105 @@ +from __future__ import annotations + +from transformers.configuration_utils import PretrainedConfig +from transformers.utils import ( + ModelOutput, +) +from transformers.activations import ACT2FN +class ViTMAEConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a [`ViTMAEModel`]. It is used to instantiate an ViT + MAE model according to the specified arguments, defining the model architecture. Instantiating a configuration with + the defaults will yield a similar configuration to that of the ViT + [facebook/vit-mae-base](https://huggingface.co/facebook/vit-mae-base) architecture. + + Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the + documentation from [`PretrainedConfig`] for more information. + + + Args: + hidden_size (`int`, *optional*, defaults to 768): + Dimensionality of the encoder layers and the pooler layer. + num_hidden_layers (`int`, *optional*, defaults to 12): + Number of hidden layers in the Transformer encoder. + num_attention_heads (`int`, *optional*, defaults to 12): + Number of attention heads for each attention layer in the Transformer encoder. + intermediate_size (`int`, *optional*, defaults to 3072): + Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. + hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`): + The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, + `"relu"`, `"selu"` and `"gelu_new"` are supported. + hidden_dropout_prob (`float`, *optional*, defaults to 0.0): + The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler. + attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0): + The dropout ratio for the attention probabilities. + initializer_range (`float`, *optional*, defaults to 0.02): + The standard deviation of the truncated_normal_initializer for initializing all weight matrices. + layer_norm_eps (`float`, *optional*, defaults to 1e-12): + The epsilon used by the layer normalization layers. + image_size (`int`, *optional*, defaults to 224): + The size (resolution) of each image. + patch_size (`int`, *optional*, defaults to 16): + The size (resolution) of each patch. + num_channels (`int`, *optional*, defaults to 3): + The number of input channels. + qkv_bias (`bool`, *optional*, defaults to `True`): + Whether to add a bias to the queries, keys and values. + decoder_num_attention_heads (`int`, *optional*, defaults to 16): + Number of attention heads for each attention layer in the decoder. + decoder_hidden_size (`int`, *optional*, defaults to 512): + Dimensionality of the decoder. + decoder_num_hidden_layers (`int`, *optional*, defaults to 8): + Number of hidden layers in the decoder. + decoder_intermediate_size (`int`, *optional*, defaults to 2048): + Dimensionality of the "intermediate" (i.e., feed-forward) layer in the decoder. + mask_ratio (`float`, *optional*, defaults to 0.75): + The ratio of the number of masked tokens in the input sequence. + norm_pix_loss (`bool`, *optional*, defaults to `False`): + Whether or not to train with normalized pixels (see Table 3 in the paper). Using normalized pixels improved + representation quality in the experiments of the authors. + + Example: + + ```python + >>> from transformers import ViTMAEConfig, ViTMAEModel + + >>> # Initializing a ViT MAE vit-mae-base style configuration + >>> configuration = ViTMAEConfig() + + >>> # Initializing a model (with random weights) from the vit-mae-base style configuration + >>> model = ViTMAEModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "vit_mae" + + def __init__( + self, + hidden_size=768, + num_hidden_layers=12, + num_attention_heads=12, + intermediate_size=3072, + hidden_act="gelu", + hidden_dropout_prob=0.0, + attention_probs_dropout_prob=0.0, + initializer_range=0.02, + layer_norm_eps=1e-12, + image_size=224, + patch_size=16, + num_channels=3, + qkv_bias=True, + decoder_num_attention_heads=16, + decoder_hidden_size=512, + decoder_num_hidden_layers=8, + decoder_intermediate_size=2048, + mask_ratio=0.75, + norm_pix_loss=False, + **kwargs, + ): + super().__init__(**kwargs) + + self.hidden_size = hidden_size + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.intermediate_size = intermediate_size + self.hidden_act = hidden_act + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.initializer_range = initializer_range + self.layer_norm_eps = layer_norm_eps + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.qkv_bias = qkv_bias + self.decoder_num_attention_heads = decoder_num_attention_heads + self.decoder_hidden_size = decoder_hidden_size + self.decoder_num_hidden_layers = decoder_num_hidden_layers + self.decoder_intermediate_size = decoder_intermediate_size + self.mask_ratio = mask_ratio + self.norm_pix_loss = norm_pix_loss + +# coding=utf-8 +# Copyright 2022 Facebook AI and The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""PyTorch ViT MAE (masked autoencoder) model.""" + +import collections.abc +import math +from copy import deepcopy +from dataclasses import dataclass +from typing import Optional, Set, Tuple, Union + +import numpy as np +import torch +from torch import nn +# correct the above import to the following +from transformers.modeling_outputs import BaseModelOutput + +try: + from flash_attn import flash_attn_func + HAS_FLASH_ATTN = True # if set to False, FlashAttention is unavailable +except: + print('FlashAttention is not installed.') + HAS_FLASH_ATTN = False + + +@dataclass +class ViTMAEModelOutput(ModelOutput): + """ + Class for ViTMAEModel's outputs, with potential hidden states and attentions. + + Args: + last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): + Sequence of hidden-states at the output of the last layer of the model. + mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): + Tensor indicating which patches are masked (1) and which are not (0). + ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Tensor containing the original index of the (shuffled) masked patches. + hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): + Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of + shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer + plus the initial embedding outputs. + attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): + Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, + sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in + the self-attention heads. + """ + + last_hidden_state: torch.FloatTensor = None + mask: torch.LongTensor = None + ids_restore: torch.LongTensor = None + hidden_states: Optional[Tuple[torch.FloatTensor]] = None + attentions: Optional[Tuple[torch.FloatTensor]] = None + + +@dataclass +class ViTMAEDecoderOutput(ModelOutput): + """ + Class for ViTMAEDecoder's outputs, with potential hidden states and attentions. + + Args: + logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`): + Pixel reconstruction logits. + hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): + Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of + shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer + plus the initial embedding outputs. + attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): + Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, + sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in + the self-attention heads. + """ + + logits: torch.FloatTensor = None + hidden_states: Optional[Tuple[torch.FloatTensor]] = None + attentions: Optional[Tuple[torch.FloatTensor]] = None + + +@dataclass +class ViTMAEForPreTrainingOutput(ModelOutput): + """ + Class for ViTMAEForPreTraining's outputs, with potential hidden states and attentions. + + Args: + loss (`torch.FloatTensor` of shape `(1,)`): + Pixel reconstruction loss. + logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`): + Pixel reconstruction logits. + mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): + Tensor indicating which patches are masked (1) and which are not (0). + ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Tensor containing the original index of the (shuffled) masked patches. + hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): + Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of + shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer + plus the initial embedding outputs. + attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): + Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, + sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in + the self-attention heads. + """ + + loss: Optional[torch.FloatTensor] = None + logits: torch.FloatTensor = None + mask: torch.LongTensor = None + ids_restore: torch.LongTensor = None + hidden_states: Optional[Tuple[torch.FloatTensor]] = None + attentions: Optional[Tuple[torch.FloatTensor]] = None + + +def get_2d_sincos_pos_embed(embed_dim, grid_size, add_cls_token=False): + """ + Create 2D sin/cos positional embeddings. + + Args: + embed_dim (`int`): + Embedding dimension. + grid_size (`int`): + The grid height and width. + add_cls_token (`bool`, *optional*, defaults to `False`): + Whether or not to add a classification (CLS) token. + + Returns: + (`torch.FloatTensor` of shape (grid_size*grid_size, embed_dim) or (1+grid_size*grid_size, embed_dim): the + position embeddings (with or without classification token) + """ + grid_h = np.arange(grid_size, dtype=np.float32) + grid_w = np.arange(grid_size, dtype=np.float32) + grid = np.meshgrid(grid_w, grid_h) # here w goes first + grid = np.stack(grid, axis=0) + + grid = grid.reshape([2, 1, grid_size, grid_size]) + pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) + if add_cls_token: + pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0) + return pos_embed + + +def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): + if embed_dim % 2 != 0: + raise ValueError("embed_dim must be even") + + # use half of dimensions to encode grid_h + emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) + emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2) + + emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D) + return emb + + +def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): + """ + embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D) + """ + if embed_dim % 2 != 0: + raise ValueError("embed_dim must be even") + + omega = np.arange(embed_dim // 2, dtype=float) + omega /= embed_dim / 2.0 + omega = 1.0 / 10000**omega # (D/2,) + + pos = pos.reshape(-1) # (M,) + out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product + + emb_sin = np.sin(out) # (M, D/2) + emb_cos = np.cos(out) # (M, D/2) + + emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) + return emb + + +class ViTMAEEmbeddings(nn.Module): + """ + Construct the CLS token, position and patch embeddings. + + """ + + def __init__(self, config): + super().__init__() + + self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) + self.patch_embeddings = ViTMAEPatchEmbeddings(config) + self.num_patches = self.patch_embeddings.num_patches + # fixed sin-cos embedding + self.position_embeddings = nn.Parameter( + torch.zeros(1, self.num_patches + 1, config.hidden_size), requires_grad=False + ) + self.config = config + self.initialize_weights() + + def initialize_weights(self): + # initialize (and freeze) position embeddings by sin-cos embedding + pos_embed = get_2d_sincos_pos_embed( + self.position_embeddings.shape[-1], int(self.patch_embeddings.num_patches**0.5), add_cls_token=True + ) + self.position_embeddings.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0)) + + # initialize patch_embeddings like nn.Linear (instead of nn.Conv2d) + w = self.patch_embeddings.projection.weight.data + torch.nn.init.xavier_uniform_(w.view([w.shape[0], -1])) + + # timm's trunc_normal_(std=.02) is effectively normal_(std=0.02) as cutoff is too big (2.) + torch.nn.init.normal_(self.cls_token, std=self.config.initializer_range) + + def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor: + """ + This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher + resolution images. + + Source: + https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174 + """ + num_patches = embeddings.shape[1] - 1 + num_positions = self.position_embeddings.shape[1] - 1 + + if num_patches == num_positions and height == width: + return self.position_embeddings + + class_pos_embed = self.position_embeddings[:, 0, :] + patch_pos_embed = self.position_embeddings[:, 1:, :] + dim = embeddings.shape[-1] + h0 = height // self.config.patch_size + w0 = width // self.config.patch_size + # we add a small number to avoid floating point error in the interpolation + # see discussion at https://github.com/facebookresearch/dino/issues/8 + h0, w0 = h0 + 0.1, w0 + 0.1 + patch_pos_embed = patch_pos_embed.reshape(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim) + patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2) + patch_pos_embed = nn.functional.interpolate( + patch_pos_embed, + scale_factor=(h0 / math.sqrt(num_positions), w0 / math.sqrt(num_positions)), + mode="bicubic", + align_corners=False, + ) + if int(h0) != patch_pos_embed.shape[-2] or int(w0) != patch_pos_embed.shape[-1]: + raise ValueError("Width or height does not match with the interpolated position embeddings") + patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) + return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1) + + def random_masking(self, sequence, noise=None): + """ + Perform per-sample random masking by per-sample shuffling. Per-sample shuffling is done by argsort random + noise. + + Args: + sequence (`torch.LongTensor` of shape `(batch_size, sequence_length, dim)`) + noise (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*) which is + mainly used for testing purposes to control randomness and maintain the reproducibility + """ + batch_size, seq_length, dim = sequence.shape + len_keep = int(seq_length * (1 - self.config.mask_ratio)) + + if noise is None: + noise = torch.rand(batch_size, seq_length, device=sequence.device) # noise in [0, 1] + + # sort noise for each sample + ids_shuffle = torch.argsort(noise, dim=1).to(sequence.device) # ascend: small is keep, large is remove + ids_restore = torch.argsort(ids_shuffle, dim=1).to(sequence.device) + + # keep the first subset + ids_keep = ids_shuffle[:, :len_keep] + sequence_unmasked = torch.gather(sequence, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, dim)) + + # generate the binary mask: 0 is keep, 1 is remove + mask = torch.ones([batch_size, seq_length], device=sequence.device) + mask[:, :len_keep] = 0 + # unshuffle to get the binary mask + mask = torch.gather(mask, dim=1, index=ids_restore) + + return sequence_unmasked, mask, ids_restore + + def forward(self, pixel_values, noise=None, interpolate_pos_encoding: bool = False): + batch_size, num_channels, height, width = pixel_values.shape + embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding) + if interpolate_pos_encoding: + position_embeddings = self.interpolate_pos_encoding(embeddings, height, width) + else: + position_embeddings = self.position_embeddings + + # add position embeddings w/o cls token + embeddings = embeddings + position_embeddings[:, 1:, :] + + # masking: length -> length * config.mask_ratio + embeddings, mask, ids_restore = self.random_masking(embeddings, noise) + + # append cls token + cls_token = self.cls_token + position_embeddings[:, :1, :] + cls_tokens = cls_token.expand(embeddings.shape[0], -1, -1) + embeddings = torch.cat((cls_tokens, embeddings), dim=1) + + return embeddings, mask, ids_restore + + +class ViTMAEPatchEmbeddings(nn.Module): + """ + This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial + `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a + Transformer. + """ + + def __init__(self, config): + super().__init__() + image_size, patch_size = config.image_size, config.patch_size + num_channels, hidden_size = config.num_channels, config.hidden_size + image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size) + patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size) + num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.num_patches = num_patches + + self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size) + + def forward(self, pixel_values, interpolate_pos_encoding: bool = False): + batch_size, num_channels, height, width = pixel_values.shape + if num_channels != self.num_channels: + raise ValueError( + "Make sure that the channel dimension of the pixel values match with the one set in the configuration." + ) + + if not interpolate_pos_encoding and (height != self.image_size[0] or width != self.image_size[1]): + raise ValueError( + f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})." + ) + x = self.projection(pixel_values).flatten(2).transpose(1, 2) + return x + + +# Copied from transformers.models.vit.modeling_vit.ViTSelfAttention ViT->ViTMAE +class ViTMAESelfAttention(nn.Module): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): + raise ValueError( + f"The hidden size {config.hidden_size,} is not a multiple of the number of attention " + f"heads {config.num_attention_heads}." + ) + + self.has_flash_attn = HAS_FLASH_ATTN + self.num_attention_heads = config.num_attention_heads + self.attention_head_size = int(config.hidden_size / config.num_attention_heads) + self.all_head_size = self.num_attention_heads * self.attention_head_size + + self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) + self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) + self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) + + self.dropout = nn.Dropout(config.attention_probs_dropout_prob) + self.attention_probs_dropout_prob = config.attention_probs_dropout_prob + + def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor: + new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) + x = x.view(new_x_shape) + return x.permute(0, 2, 1, 3) + + def reshape_for_flash(self, x: torch.Tensor) -> torch.Tensor: + """Reshape to (B, N, num_heads, head_dim) for flash_attn_func.""" + new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) + return x.view(new_x_shape) + + def forward( + self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False + ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]: + # Use FlashAttention when available and no special outputs are needed + if self.has_flash_attn and not output_attentions and head_mask is None: + query_layer = self.reshape_for_flash(self.query(hidden_states)) + key_layer = self.reshape_for_flash(self.key(hidden_states)) + value_layer = self.reshape_for_flash(self.value(hidden_states)) + + context_layer = flash_attn_func( + query_layer, key_layer, value_layer, + dropout_p=self.attention_probs_dropout_prob if self.training else 0.0, + causal=False, deterministic=True + ) + + context_layer = context_layer.reshape(hidden_states.size(0), -1, self.all_head_size) + return (context_layer,) + + # Fallback: manual attention computation + mixed_query_layer = self.query(hidden_states) + + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + query_layer = self.transpose_for_scores(mixed_query_layer) + + attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) + attention_scores = attention_scores / math.sqrt(self.attention_head_size) + + attention_probs = nn.functional.softmax(attention_scores, dim=-1) + attention_probs = self.dropout(attention_probs) + + if head_mask is not None: + attention_probs = attention_probs * head_mask + + context_layer = torch.matmul(attention_probs, value_layer) + + context_layer = context_layer.permute(0, 2, 1, 3).contiguous() + new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) + context_layer = context_layer.view(new_context_layer_shape) + + outputs = (context_layer, attention_probs) if output_attentions else (context_layer,) + + return outputs + + +# Copied from transformers.models.vit.modeling_vit.ViTSdpaSelfAttention ViT->ViTMAE +class ViTMAESdpaSelfAttention(ViTMAESelfAttention): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__(config) + self.attention_probs_dropout_prob = config.attention_probs_dropout_prob + + def forward( + self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False + ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]: + # Use FlashAttention when available and no special outputs are needed + if self.has_flash_attn and not output_attentions and head_mask is None: + query_layer = self.reshape_for_flash(self.query(hidden_states)) + key_layer = self.reshape_for_flash(self.key(hidden_states)) + value_layer = self.reshape_for_flash(self.value(hidden_states)) + + context_layer = flash_attn_func( + query_layer, key_layer, value_layer, + dropout_p=self.attention_probs_dropout_prob if self.training else 0.0, + causal=False, deterministic=True + ) + + context_layer = context_layer.reshape(hidden_states.size(0), -1, self.all_head_size) + return context_layer, None + + # Fallback: PyTorch SDPA + mixed_query_layer = self.query(hidden_states) + + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + query_layer = self.transpose_for_scores(mixed_query_layer) + + context_layer = torch.nn.functional.scaled_dot_product_attention( + query_layer, + key_layer, + value_layer, + head_mask, + self.attention_probs_dropout_prob if self.training else 0.0, + is_causal=False, + scale=None, + ) + + context_layer = context_layer.permute(0, 2, 1, 3).contiguous() + new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) + context_layer = context_layer.view(new_context_layer_shape) + + return context_layer, None + + +# Copied from transformers.models.vit.modeling_vit.ViTSelfOutput with ViT->ViTMAE +class ViTMAESelfOutput(nn.Module): + """ + The residual connection is defined in ViTMAELayer instead of here (as is the case with other models), due to the + layernorm applied before each block. + """ + + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + + return hidden_states + + +# Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->ViTMAE +class ViTMAEAttention(nn.Module): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.attention = ViTMAESelfAttention(config) + self.output = ViTMAESelfOutput(config) + + def forward( + self, + hidden_states: torch.Tensor, + head_mask: Optional[torch.Tensor] = None, + output_attentions: bool = False, + ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]: + self_outputs = self.attention(hidden_states, head_mask, output_attentions) + + attention_output = self.output(self_outputs[0], hidden_states) + + outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them + return outputs + +# Copied from transformers.models.vit.modeling_vit.ViTIntermediate ViT->ViTMAE +class ViTMAEIntermediate(nn.Module): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.intermediate_size) + if isinstance(config.hidden_act, str): + self.intermediate_act_fn = ACT2FN[config.hidden_act] + else: + self.intermediate_act_fn = config.hidden_act + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.intermediate_act_fn(hidden_states) + + return hidden_states + + +# Copied from transformers.models.vit.modeling_vit.ViTOutput ViT->ViTMAE +class ViTMAEOutput(nn.Module): + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.dense = nn.Linear(config.intermediate_size, config.hidden_size) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + + hidden_states = hidden_states + input_tensor + + return hidden_states + + + +# Copied from transformers.models.vit.modeling_vit.ViTLayer with ViT->ViTMAE,VIT->VITMAE +class ViTMAELayer(nn.Module): + """This corresponds to the Block class in the timm implementation.""" + + def __init__(self, config: ViTMAEConfig) -> None: + super().__init__() + self.chunk_size_feed_forward = config.chunk_size_feed_forward + self.seq_len_dim = 1 + self.attention = ViTMAEAttention(config) # no SPDA by default + self.intermediate = ViTMAEIntermediate(config) + self.output = ViTMAEOutput(config) + self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + + def forward( + self, + hidden_states: torch.Tensor, + head_mask: Optional[torch.Tensor] = None, + output_attentions: bool = False, + ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]: + self_attention_outputs = self.attention( + self.layernorm_before(hidden_states), # in ViTMAE, layernorm is applied before self-attention + head_mask, + output_attentions=output_attentions, + ) + attention_output = self_attention_outputs[0] + outputs = self_attention_outputs[1:] # add self attentions if we output attention weights + + # first residual connection + hidden_states = attention_output + hidden_states + + # in ViTMAE, layernorm is also applied after self-attention + layer_output = self.layernorm_after(hidden_states) + layer_output = self.intermediate(layer_output) + + # second residual connection is done here + layer_output = self.output(layer_output, hidden_states) + + outputs = (layer_output,) + outputs + + return outputs + + +class GeneralDecoder(nn.Module): + def __init__(self, config, num_patches): + super().__init__() + self.decoder_embed = nn.Linear(config.hidden_size, config.decoder_hidden_size, bias=True) + self.decoder_pos_embed = nn.Parameter( + torch.zeros(1, num_patches + 1, config.decoder_hidden_size), requires_grad=False + ) # fixed sin-cos embedding + + decoder_config = deepcopy(config) + decoder_config.hidden_size = config.decoder_hidden_size + decoder_config.num_hidden_layers = config.decoder_num_hidden_layers + decoder_config.num_attention_heads = config.decoder_num_attention_heads + decoder_config.intermediate_size = config.decoder_intermediate_size + self.decoder_layers = nn.ModuleList( + [ViTMAELayer(decoder_config) for _ in range(config.decoder_num_hidden_layers)] + ) + + self.decoder_norm = nn.LayerNorm(config.decoder_hidden_size, eps=config.layer_norm_eps) + self.decoder_pred = nn.Linear( + config.decoder_hidden_size, config.patch_size**2 * config.num_channels, bias=True + ) # encoder to decoder + self.gradient_checkpointing = False + self.config = config + self.num_patches = num_patches + self.initialize_weights(num_patches) + self.decoder_config = decoder_config + self.set_trainable_cls_token() + def set_trainable_cls_token(self, tensor: Optional[torch.Tensor] = None): + # register a trainable CLS token + tensor = torch.zeros(1, 1, self.decoder_config.hidden_size) if tensor is None else tensor + self.trainable_cls_token = nn.Parameter(tensor) + def interpolate_pos_encoding(self, embeddings: torch.Tensor) -> torch.Tensor: + """ + This method is a modified version of the interpolation function for ViT-mae model at the deocder, that + allows to interpolate the pre-trained decoder position encodings, to be able to use the model on higher + resolution images. + + Source: + https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174 + """ + + # -1 removes the class dimension since we later append it without interpolation + embeddings_positions = embeddings.shape[1] - 1 + num_positions = self.decoder_pos_embed.shape[1] - 1 + + # Separation of class token and patch tokens + class_pos_embed = self.decoder_pos_embed[:, 0, :] + patch_pos_embed = self.decoder_pos_embed[:, 1:, :] + + # To retain the final 3d tensor with the required dimensions + dim = self.decoder_pos_embed.shape[-1] + + # Increasing a dimension to enable bicubic interpolation + patch_pos_embed = patch_pos_embed.reshape(1, 1, -1, dim) + + # permute to bring the dimension to be interpolated, to the last + patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2) + + # Interpolating the decoder position embeddings shape wrt embeddings shape i.e (x). + # 1 keeps the other dimension constant + patch_pos_embed = nn.functional.interpolate( + patch_pos_embed, + scale_factor=(1, embeddings_positions / num_positions), + mode="bicubic", + align_corners=False, + ) + + # Converting back to the original shape + patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) + # Adding the class token back + return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1) + def interpolate_latent(self, x: torch.Tensor) -> torch.Tensor: + b, l, c = x.shape + if l == self.num_patches: + return x + # interpolate the latent + #print(f"interpolating latent from {l} to {self.num_patches}, x.shape = {x.shape}") + h, w = int(l**0.5), int(l**0.5) + x = x.reshape(b, h, w, c) + x = x.permute(0, 3, 1, 2) + target_size = (int(self.num_patches**0.5), int(self.num_patches**0.5)) + x = nn.functional.interpolate(x, size=target_size, mode="bilinear", align_corners=False) + x = x.permute(0, 2, 3, 1).contiguous().view(b, self.num_patches, c) + return x + + def initialize_weights(self, num_patches): + # initialize (and freeze) position embeddings by sin-cos embedding + decoder_pos_embed = get_2d_sincos_pos_embed( + self.decoder_pos_embed.shape[-1], int(num_patches**0.5), add_cls_token=True + ) + self.decoder_pos_embed.data.copy_(torch.from_numpy(decoder_pos_embed).float().unsqueeze(0)) + + # timm's trunc_normal_(std=.02) is effectively normal_(std=0.02) as cutoff is too big (2.) + # torch.nn.init.normal_(self.mask_token, std=self.config.initializer_range) + def unpatchify(self, patchified_pixel_values, original_image_size: Optional[Tuple[int, int]] = None): + """ + Args: + patchified_pixel_values (`torch.FloatTensor` of shape `(batch_size, num_patches, patch_size**2 * num_channels)`: + Patchified pixel values. + original_image_size (`Tuple[int, int]`, *optional*): + Original image size. + + Returns: + `torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`: + Pixel values. + """ + patch_size, num_channels = self.config.patch_size, self.config.num_channels + original_image_size = ( + original_image_size + if original_image_size is not None + else (self.config.image_size, self.config.image_size) + ) + original_height, original_width = original_image_size + num_patches_h = original_height // patch_size + num_patches_w = original_width // patch_size + # sanity check + if num_patches_h * num_patches_w != patchified_pixel_values.shape[1]: + raise ValueError( + f"The number of patches in the patchified pixel values {patchified_pixel_values.shape[1]}, does not match the number of patches on original image {num_patches_h}*{num_patches_w}" + ) + + # unpatchify + batch_size = patchified_pixel_values.shape[0] + patchified_pixel_values = patchified_pixel_values.reshape( + batch_size, + num_patches_h, + num_patches_w, + patch_size, + patch_size, + num_channels, + ) + patchified_pixel_values = torch.einsum("nhwpqc->nchpwq", patchified_pixel_values) + pixel_values = patchified_pixel_values.reshape( + batch_size, + num_channels, + num_patches_h * patch_size, + num_patches_w * patch_size, + ) + return pixel_values + + def forward( + self, + hidden_states, + output_attentions=False, + output_hidden_states=False, + return_dict=True, + interpolate_pos_encoding: bool = False, + drop_cls_token: bool = False, + ): + # embed tokens + x = self.decoder_embed(hidden_states) + #print(f"x.shape = {x.shape}") + if drop_cls_token: + x_ = x[:, 1:, :] # no cls token + x_ = self.interpolate_latent(x_) + else: + x_ = self.interpolate_latent(x) # interpolate the whole latent + cls_token = self.trainable_cls_token.expand(x_.shape[0], -1, -1) + x = torch.cat([cls_token, x_], dim=1) + + # add pos embed + if interpolate_pos_encoding: + assert drop_cls_token, "interpolate_pos_encoding only works with drop_cls_token=True" + decoder_pos_embed = self.interpolate_pos_encoding(x) + else: + decoder_pos_embed = self.decoder_pos_embed + hidden_states = x + decoder_pos_embed + #print(f"hidden_states.shape = {hidden_states.shape}") + # apply Transformer layers (blocks) + all_hidden_states = () if output_hidden_states else None + all_self_attentions = () if output_attentions else None + for i, layer_module in enumerate(self.decoder_layers): + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + if self.gradient_checkpointing and self.training: + layer_outputs = self._gradient_checkpointing_func( + layer_module.__call__, + hidden_states, + None, + output_attentions, + ) + else: + layer_outputs = layer_module(hidden_states, head_mask=None, output_attentions=output_attentions) + + hidden_states = layer_outputs[0] + + if output_attentions: + all_self_attentions = all_self_attentions + (layer_outputs[1],) + + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + hidden_states = self.decoder_norm(hidden_states) + + # predictor projection + logits = self.decoder_pred(hidden_states) + + # remove cls token + logits = logits[:, 1:, :] + + if not return_dict: + return tuple(v for v in [logits, all_hidden_states, all_self_attentions] if v is not None) + return ViTMAEDecoderOutput( + logits=logits, + hidden_states=all_hidden_states, + attentions=all_self_attentions, + ) + +import json +from math import sqrt +from pathlib import Path +from typing import Any, Dict, Optional + +import torch +import torch.nn as nn +from timm.models.vision_transformer import Attention +from transformers import AutoConfig, AutoImageProcessor + +try: + from diffusers.configuration_utils import ConfigMixin, register_to_config + from diffusers.models.modeling_utils import ModelMixin +except Exception: # pragma: no cover + class ConfigMixin: + config_name = "config.json" + + class ModelMixin(nn.Module): + pass + + def register_to_config(init): + return init + + +_PIXEL_DECODER_DEFAULTS: Dict[str, Any] = { + "decoder_hidden_size": 1024, + "decoder_intermediate_size": 4096, + "decoder_num_attention_heads": 16, + "decoder_num_hidden_layers": 24, + "layer_norm_eps": 1e-12, + "num_channels": 3, + "hidden_act": "gelu", + "qkv_bias": True, + "hidden_dropout_prob": 0.0, + "attention_probs_dropout_prob": 0.0, + "initializer_range": 0.02, +} + + +def _resolve_local_asset_path(path: str, model_root: Optional[Path] = None) -> str: + candidate = Path(path) + if candidate.is_file(): + return str(candidate) + search_roots = [] + if model_root is not None: + search_roots.extend([model_root, model_root.parent]) + for root in search_roots: + for probe in (root / candidate, root / candidate.name, root / "decoder_config" / "config.json"): + if probe.is_file(): + return str(probe) + return path + + +def _build_pixel_decoder_config( + *, + encoder_hidden_size: int, + decoder_patch_size: int, + base_patches: int, + decoder_config_path: Optional[str] = None, + overrides: Optional[Dict[str, Any]] = None, +) -> ViTMAEConfig: + pixel_decoder = dict(_PIXEL_DECODER_DEFAULTS) + if decoder_config_path is not None: + resolved = _resolve_local_asset_path(decoder_config_path) + if Path(resolved).is_file(): + with open(resolved, encoding="utf-8") as handle: + pixel_decoder.update(json.load(handle)) + if overrides: + pixel_decoder.update({key: value for key, value in overrides.items() if value is not None}) + + return ViTMAEConfig( + hidden_size=encoder_hidden_size, + patch_size=decoder_patch_size, + image_size=int(decoder_patch_size * sqrt(base_patches)), + **pixel_decoder, + ) + + +def _load_image_normalization(encoder_config_path: str) -> tuple[list[float], list[float]]: + try: + proc = AutoImageProcessor.from_pretrained(encoder_config_path, use_fast=True, local_files_only=True) + return proc.image_mean, proc.image_std + except Exception: + pass + try: + proc = AutoImageProcessor.from_pretrained(encoder_config_path, use_fast=True, local_files_only=False) + return proc.image_mean, proc.image_std + except Exception: + if "siglip" in encoder_config_path.lower(): + return [0.5, 0.5, 0.5], [0.5, 0.5, 0.5] + return [0.485, 0.456, 0.406], [0.229, 0.224, 0.225] + + +class PAEDecoder(ModelMixin, ConfigMixin): + """PAE decoder: latent decompressor + ViT-MAE pixel decoder.""" + + @register_to_config + def __init__( + self, + encoder_hidden_size: int = 1024, + encoder_num_heads: int = 16, + encoder_input_size: int = 224, + encoder_patch_size: int = 14, + encoder_config_path: str = "facebook/dinov2-with-registers-large", + latent_dim: int = 32, + decoder_patch_size: int = 16, + decoder_config_path: Optional[str] = None, + decoder_hidden_size: int = 1024, + decoder_intermediate_size: int = 4096, + decoder_num_attention_heads: int = 16, + decoder_num_hidden_layers: int = 24, + layer_norm_eps: float = 1e-12, + num_channels: int = 3, + hidden_act: str = "gelu", + qkv_bias: bool = True, + hidden_dropout_prob: float = 0.0, + attention_probs_dropout_prob: float = 0.0, + initializer_range: float = 0.02, + image_mean: Optional[list[float]] = None, + image_std: Optional[list[float]] = None, + latent_mean: Optional[list[float]] = None, + latent_std: Optional[list[float]] = None, + latent_multiplier: float = 1.0, + **kwargs, + ) -> None: + super().__init__() + if image_mean is not None and image_std is not None: + norm_mean, norm_std = image_mean, image_std + else: + norm_mean, norm_std = _load_image_normalization(encoder_config_path) + self.register_buffer("encoder_mean", torch.tensor(norm_mean).view(1, 3, 1, 1), persistent=True) + self.register_buffer("encoder_std", torch.tensor(norm_std).view(1, 3, 1, 1), persistent=True) + + self.encoder_input_size = encoder_input_size + self.encoder_patch_size = encoder_patch_size + self.base_patches = (self.encoder_input_size // self.encoder_patch_size) ** 2 + self.latent_dim = latent_dim + + self.latent_decompressor = nn.ModuleList( + [ + nn.Conv2d(latent_dim, encoder_hidden_size, kernel_size=3, padding=1), + Attention(dim=encoder_hidden_size, num_heads=encoder_num_heads), + ] + ) + + pixel_decoder_config = _build_pixel_decoder_config( + encoder_hidden_size=encoder_hidden_size, + decoder_patch_size=decoder_patch_size, + base_patches=self.base_patches, + decoder_config_path=decoder_config_path, + overrides={ + "decoder_hidden_size": decoder_hidden_size, + "decoder_intermediate_size": decoder_intermediate_size, + "decoder_num_attention_heads": decoder_num_attention_heads, + "decoder_num_hidden_layers": decoder_num_hidden_layers, + "layer_norm_eps": layer_norm_eps, + "num_channels": num_channels, + "hidden_act": hidden_act, + "qkv_bias": qkv_bias, + "hidden_dropout_prob": hidden_dropout_prob, + "attention_probs_dropout_prob": attention_probs_dropout_prob, + "initializer_range": initializer_range, + }, + ) + self.decoder = GeneralDecoder(pixel_decoder_config, num_patches=self.base_patches) + + @classmethod + def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): + model_root = Path(pretrained_model_name_or_path) + config_file = model_root / cls.config_name + if config_file.is_file(): + with open(config_file, encoding="utf-8") as handle: + config = json.load(handle) + decoder_config_path = config.get("decoder_config_path") + if decoder_config_path is not None: + resolved = _resolve_local_asset_path(decoder_config_path, model_root=model_root) + if resolved != decoder_config_path: + kwargs.setdefault("decoder_config_path", resolved) + return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) + + def decode(self, latents: torch.Tensor) -> torch.Tensor: + hidden_states = self.latent_decompressor[0](latents) + batch_size, channels, height, width = hidden_states.shape + num_tokens = height * width + hidden_states = hidden_states.view(batch_size, channels, num_tokens).transpose(1, 2) + hidden_states = self.latent_decompressor[1](hidden_states) + + output = self.decoder(hidden_states, drop_cls_token=False).logits + x_rec = self.decoder.unpatchify(output) + x_rec = x_rec * self.encoder_std.to(x_rec.device) + self.encoder_mean.to(x_rec.device) + return x_rec + + def forward(self, latents: torch.Tensor) -> torch.Tensor: + return self.decode(latents) diff --git a/pae-siglip2-so400m-d32/decoder/diffusion_pytorch_model.safetensors b/pae-siglip2-so400m-d32/decoder/diffusion_pytorch_model.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..df0e2576e4fca1c1daa096e0b825d92977a2d33f --- /dev/null +++ b/pae-siglip2-so400m-d32/decoder/diffusion_pytorch_model.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e1ff5e7b81fa169348b91fc9833bf4c66059e73393794934514eceb4c94f18d8 +size 1240792960 diff --git a/pae-siglip2-so400m-d32/demo.png b/pae-siglip2-so400m-d32/demo.png new file mode 100644 index 0000000000000000000000000000000000000000..4e88afe7267d5a4ee3d624c52af450fdf800dd3e --- /dev/null +++ b/pae-siglip2-so400m-d32/demo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bad659462f7aed15c5260c1460d94a75195273c353a3cf36ca475520462c2746 +size 106293 diff --git a/pae-siglip2-so400m-d32/model_index.json b/pae-siglip2-so400m-d32/model_index.json new file mode 100644 index 0000000000000000000000000000000000000000..c71449e6f44c0678499c73c3696faea852cca1e2 --- /dev/null +++ b/pae-siglip2-so400m-d32/model_index.json @@ -0,0 +1,1021 @@ +{ + "_class_name": [ + "pipeline", + "PAEPipeline" + ], + "_diffusers_version": "0.31.0", + "decoder": [ + "decoder_pae", + "PAEDecoder" + ], + "id2label": { + "0": "tench, Tinca tinca", + "1": "goldfish, Carassius auratus", + "2": "great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias", + "3": "tiger shark, Galeocerdo cuvieri", + "4": "hammerhead, hammerhead shark", + "5": "electric ray, crampfish, numbfish, torpedo", + "6": "stingray", + "7": "cock", + "8": "hen", + "9": "ostrich, Struthio camelus", + "10": "brambling, Fringilla montifringilla", + "11": "goldfinch, Carduelis carduelis", + "12": "house finch, linnet, Carpodacus mexicanus", + "13": "junco, snowbird", + "14": "indigo bunting, indigo finch, indigo bird, Passerina cyanea", + "15": "robin, American robin, Turdus migratorius", + "16": "bulbul", + "17": "jay", + "18": "magpie", + "19": "chickadee", + "20": "water ouzel, dipper", + "21": "kite", + "22": "bald eagle, American eagle, Haliaeetus leucocephalus", + "23": "vulture", + "24": "great grey owl, great gray owl, Strix nebulosa", + "25": "European fire salamander, Salamandra salamandra", + "26": "common newt, Triturus vulgaris", + "27": "eft", + "28": "spotted salamander, Ambystoma maculatum", + "29": "axolotl, mud puppy, Ambystoma mexicanum", + "30": "bullfrog, Rana catesbeiana", + "31": "tree frog, tree-frog", + "32": "tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui", + "33": "loggerhead, loggerhead turtle, Caretta caretta", + "34": "leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea", + "35": "mud turtle", + "36": "terrapin", + "37": "box turtle, box tortoise", + "38": "banded gecko", + "39": "common iguana, iguana, Iguana iguana", + "40": "American chameleon, anole, Anolis carolinensis", + "41": "whiptail, whiptail lizard", + "42": "agama", + "43": "frilled lizard, Chlamydosaurus kingi", + "44": "alligator lizard", + "45": "Gila monster, Heloderma suspectum", + "46": "green lizard, Lacerta viridis", + "47": "African chameleon, Chamaeleo chamaeleon", + "48": "Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis", + "49": "African crocodile, Nile crocodile, Crocodylus niloticus", + "50": "American alligator, Alligator mississipiensis", + "51": "triceratops", + "52": "thunder snake, worm snake, Carphophis amoenus", + "53": "ringneck snake, ring-necked snake, ring snake", + "54": "hognose snake, puff adder, sand viper", + "55": "green snake, grass snake", + "56": "king snake, kingsnake", + "57": "garter snake, grass snake", + "58": "water snake", + "59": "vine snake", + "60": "night snake, Hypsiglena torquata", + "61": "boa constrictor, Constrictor constrictor", + "62": "rock python, rock snake, Python sebae", + "63": "Indian cobra, Naja naja", + "64": "green mamba", + "65": "sea snake", + "66": "horned viper, cerastes, sand viper, horned asp, Cerastes cornutus", + "67": "diamondback, diamondback rattlesnake, Crotalus adamanteus", + "68": "sidewinder, horned rattlesnake, Crotalus cerastes", + "69": "trilobite", + "70": "harvestman, daddy longlegs, Phalangium opilio", + "71": "scorpion", + "72": "black and gold garden spider, Argiope aurantia", + "73": "barn spider, Araneus cavaticus", + "74": "garden spider, Aranea diademata", + "75": "black widow, Latrodectus mactans", + "76": "tarantula", + "77": "wolf spider, hunting spider", + "78": "tick", + "79": "centipede", + "80": "black grouse", + "81": "ptarmigan", + "82": "ruffed grouse, partridge, Bonasa umbellus", + "83": "prairie chicken, prairie grouse, prairie fowl", + "84": "peacock", + "85": "quail", + "86": "partridge", + "87": "African grey, African gray, Psittacus erithacus", + "88": "macaw", + "89": "sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita", + "90": "lorikeet", + "91": "coucal", + "92": "bee eater", + "93": "hornbill", + "94": "hummingbird", + "95": "jacamar", + "96": "toucan", + "97": "drake", + "98": "red-breasted merganser, Mergus serrator", + "99": "goose", + "100": "black swan, Cygnus atratus", + "101": "tusker", + "102": "echidna, spiny anteater, anteater", + "103": "platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus", + "104": "wallaby, brush kangaroo", + "105": "koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus", + "106": "wombat", + "107": "jellyfish", + "108": "sea anemone, anemone", + "109": "brain coral", + "110": "flatworm, platyhelminth", + "111": "nematode, nematode worm, roundworm", + "112": "conch", + "113": "snail", + "114": "slug", + "115": "sea slug, nudibranch", + "116": "chiton, coat-of-mail shell, sea cradle, polyplacophore", + "117": "chambered nautilus, pearly nautilus, nautilus", + "118": "Dungeness crab, Cancer magister", + "119": "rock crab, Cancer irroratus", + "120": "fiddler crab", + "121": "king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica", + "122": "American lobster, Northern lobster, Maine lobster, Homarus americanus", + "123": "spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish", + "124": "crayfish, crawfish, crawdad, crawdaddy", + "125": "hermit crab", + "126": "isopod", + "127": "white stork, Ciconia ciconia", + "128": "black stork, Ciconia nigra", + "129": "spoonbill", + "130": "flamingo", + "131": "little blue heron, Egretta caerulea", + "132": "American egret, great white heron, Egretta albus", + "133": "bittern", + "134": "crane", + "135": "limpkin, Aramus pictus", + "136": "European gallinule, Porphyrio porphyrio", + "137": "American coot, marsh hen, mud hen, water hen, Fulica americana", + "138": "bustard", + "139": "ruddy turnstone, Arenaria interpres", + "140": "red-backed sandpiper, dunlin, Erolia alpina", + "141": "redshank, Tringa totanus", + "142": "dowitcher", + "143": "oystercatcher, oyster catcher", + "144": "pelican", + "145": "king penguin, Aptenodytes patagonica", + "146": "albatross, mollymawk", + "147": "grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus", + "148": "killer whale, killer, orca, grampus, sea wolf, Orcinus orca", + "149": "dugong, Dugong dugon", + "150": "sea lion", + "151": "Chihuahua", + "152": "Japanese spaniel", + "153": "Maltese dog, Maltese terrier, Maltese", + "154": "Pekinese, Pekingese, Peke", + "155": "Shih-Tzu", + "156": "Blenheim spaniel", + "157": "papillon", + "158": "toy terrier", + "159": "Rhodesian ridgeback", + "160": "Afghan hound, Afghan", + "161": "basset, basset hound", + "162": "beagle", + "163": "bloodhound, sleuthhound", + "164": "bluetick", + "165": "black-and-tan coonhound", + "166": "Walker hound, Walker foxhound", + "167": "English foxhound", + "168": "redbone", + "169": "borzoi, Russian wolfhound", + "170": "Irish wolfhound", + "171": "Italian greyhound", + "172": "whippet", + "173": "Ibizan hound, Ibizan Podenco", + "174": "Norwegian elkhound, elkhound", + "175": "otterhound, otter hound", + "176": "Saluki, gazelle hound", + "177": "Scottish deerhound, deerhound", + "178": "Weimaraner", + "179": "Staffordshire bullterrier, Staffordshire bull terrier", + "180": "American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier", + "181": "Bedlington terrier", + "182": "Border terrier", + "183": "Kerry blue terrier", + "184": "Irish terrier", + "185": "Norfolk terrier", + "186": "Norwich terrier", + "187": "Yorkshire terrier", + "188": "wire-haired fox terrier", + "189": "Lakeland terrier", + "190": "Sealyham terrier, Sealyham", + "191": "Airedale, Airedale terrier", + "192": "cairn, cairn terrier", + "193": "Australian terrier", + "194": "Dandie Dinmont, Dandie Dinmont terrier", + "195": "Boston bull, Boston terrier", + "196": "miniature schnauzer", + "197": "giant schnauzer", + "198": "standard schnauzer", + "199": "Scotch terrier, Scottish terrier, Scottie", + "200": "Tibetan terrier, chrysanthemum dog", + "201": "silky terrier, Sydney silky", + "202": "soft-coated wheaten terrier", + "203": "West Highland white terrier", + "204": "Lhasa, Lhasa apso", + "205": "flat-coated retriever", + "206": "curly-coated retriever", + "207": "golden retriever", + "208": "Labrador retriever", + "209": "Chesapeake Bay retriever", + "210": "German short-haired pointer", + "211": "vizsla, Hungarian pointer", + "212": "English setter", + "213": "Irish setter, red setter", + "214": "Gordon setter", + "215": "Brittany spaniel", + "216": "clumber, clumber spaniel", + "217": "English springer, English springer spaniel", + "218": "Welsh springer spaniel", + "219": "cocker spaniel, English cocker spaniel, cocker", + "220": "Sussex spaniel", + "221": "Irish water spaniel", + "222": "kuvasz", + "223": "schipperke", + "224": "groenendael", + "225": "malinois", + "226": "briard", + "227": "kelpie", + "228": "komondor", + "229": "Old English sheepdog, bobtail", + "230": "Shetland sheepdog, Shetland sheep dog, Shetland", + "231": "collie", + "232": "Border collie", + "233": "Bouvier des Flandres, Bouviers des Flandres", + "234": "Rottweiler", + "235": "German shepherd, German shepherd dog, German police dog, alsatian", + "236": "Doberman, Doberman pinscher", + "237": "miniature pinscher", + "238": "Greater Swiss Mountain dog", + "239": "Bernese mountain dog", + "240": "Appenzeller", + "241": "EntleBucher", + "242": "boxer", + "243": "bull mastiff", + "244": "Tibetan mastiff", + "245": "French bulldog", + "246": "Great Dane", + "247": "Saint Bernard, St Bernard", + "248": "Eskimo dog, husky", + "249": "malamute, malemute, Alaskan malamute", + "250": "Siberian husky", + "251": "dalmatian, coach dog, carriage dog", + "252": "affenpinscher, monkey pinscher, monkey dog", + "253": "basenji", + "254": "pug, pug-dog", + "255": "Leonberg", + "256": "Newfoundland, Newfoundland dog", + "257": "Great Pyrenees", + "258": "Samoyed, Samoyede", + "259": "Pomeranian", + "260": "chow, chow chow", + "261": "keeshond", + "262": "Brabancon griffon", + "263": "Pembroke, Pembroke Welsh corgi", + "264": "Cardigan, Cardigan Welsh corgi", + "265": "toy poodle", + "266": "miniature poodle", + "267": "standard poodle", + "268": "Mexican hairless", + "269": "timber wolf, grey wolf, gray wolf, Canis lupus", + "270": "white wolf, Arctic wolf, Canis lupus tundrarum", + "271": "red wolf, maned wolf, Canis rufus, Canis niger", + "272": "coyote, prairie wolf, brush wolf, Canis latrans", + "273": "dingo, warrigal, warragal, Canis dingo", + "274": "dhole, Cuon alpinus", + "275": "African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus", + "276": "hyena, hyaena", + "277": "red fox, Vulpes vulpes", + "278": "kit fox, Vulpes macrotis", + "279": "Arctic fox, white fox, Alopex lagopus", + "280": "grey fox, gray fox, Urocyon cinereoargenteus", + "281": "tabby, tabby cat", + "282": "tiger cat", + "283": "Persian cat", + "284": "Siamese cat, Siamese", + "285": "Egyptian cat", + "286": "cougar, puma, catamount, mountain lion, painter, panther, Felis concolor", + "287": "lynx, catamount", + "288": "leopard, Panthera pardus", + "289": "snow leopard, ounce, Panthera uncia", + "290": "jaguar, panther, Panthera onca, Felis onca", + "291": "lion, king of beasts, Panthera leo", + "292": "tiger, Panthera tigris", + "293": "cheetah, chetah, Acinonyx jubatus", + "294": "brown bear, bruin, Ursus arctos", + "295": "American black bear, black bear, Ursus americanus, Euarctos americanus", + "296": "ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus", + "297": "sloth bear, Melursus ursinus, Ursus ursinus", + "298": "mongoose", + "299": "meerkat, mierkat", + "300": "tiger beetle", + "301": "ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle", + "302": "ground beetle, carabid beetle", + "303": "long-horned beetle, longicorn, longicorn beetle", + "304": "leaf beetle, chrysomelid", + "305": "dung beetle", + "306": "rhinoceros beetle", + "307": "weevil", + "308": "fly", + "309": "bee", + "310": "ant, emmet, pismire", + "311": "grasshopper, hopper", + "312": "cricket", + "313": "walking stick, walkingstick, stick insect", + "314": "cockroach, roach", + "315": "mantis, mantid", + "316": "cicada, cicala", + "317": "leafhopper", + "318": "lacewing, lacewing fly", + "319": "dragonfly, darning needle, devils darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk", + "320": "damselfly", + "321": "admiral", + "322": "ringlet, ringlet butterfly", + "323": "monarch, monarch butterfly, milkweed butterfly, Danaus plexippus", + "324": "cabbage butterfly", + "325": "sulphur butterfly, sulfur butterfly", + "326": "lycaenid, lycaenid butterfly", + "327": "starfish, sea star", + "328": "sea urchin", + "329": "sea cucumber, holothurian", + "330": "wood rabbit, cottontail, cottontail rabbit", + "331": "hare", + "332": "Angora, Angora rabbit", + "333": "hamster", + "334": "porcupine, hedgehog", + "335": "fox squirrel, eastern fox squirrel, Sciurus niger", + "336": "marmot", + "337": "beaver", + "338": "guinea pig, Cavia cobaya", + "339": "sorrel", + "340": "zebra", + "341": "hog, pig, grunter, squealer, Sus scrofa", + "342": "wild boar, boar, Sus scrofa", + "343": "warthog", + "344": "hippopotamus, hippo, river horse, Hippopotamus amphibius", + "345": "ox", + "346": "water buffalo, water ox, Asiatic buffalo, Bubalus bubalis", + "347": "bison", + "348": "ram, tup", + "349": "bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis", + "350": "ibex, Capra ibex", + "351": "hartebeest", + "352": "impala, Aepyceros melampus", + "353": "gazelle", + "354": "Arabian camel, dromedary, Camelus dromedarius", + "355": "llama", + "356": "weasel", + "357": "mink", + "358": "polecat, fitch, foulmart, foumart, Mustela putorius", + "359": "black-footed ferret, ferret, Mustela nigripes", + "360": "otter", + "361": "skunk, polecat, wood pussy", + "362": "badger", + "363": "armadillo", + "364": "three-toed sloth, ai, Bradypus tridactylus", + "365": "orangutan, orang, orangutang, Pongo pygmaeus", + "366": "gorilla, Gorilla gorilla", + "367": "chimpanzee, chimp, Pan troglodytes", + "368": "gibbon, Hylobates lar", + "369": "siamang, Hylobates syndactylus, Symphalangus syndactylus", + "370": "guenon, guenon monkey", + "371": "patas, hussar monkey, Erythrocebus patas", + "372": "baboon", + "373": "macaque", + "374": "langur", + "375": "colobus, colobus monkey", + "376": "proboscis monkey, Nasalis larvatus", + "377": "marmoset", + "378": "capuchin, ringtail, Cebus capucinus", + "379": "howler monkey, howler", + "380": "titi, titi monkey", + "381": "spider monkey, Ateles geoffroyi", + "382": "squirrel monkey, Saimiri sciureus", + "383": "Madagascar cat, ring-tailed lemur, Lemur catta", + "384": "indri, indris, Indri indri, Indri brevicaudatus", + "385": "Indian elephant, Elephas maximus", + "386": "African elephant, Loxodonta africana", + "387": "lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens", + "388": "giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca", + "389": "barracouta, snoek", + "390": "eel", + "391": "coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch", + "392": "rock beauty, Holocanthus tricolor", + "393": "anemone fish", + "394": "sturgeon", + "395": "gar, garfish, garpike, billfish, Lepisosteus osseus", + "396": "lionfish", + "397": "puffer, pufferfish, blowfish, globefish", + "398": "abacus", + "399": "abaya", + "400": "academic gown, academic robe, judge robe", + "401": "accordion, piano accordion, squeeze box", + "402": "acoustic guitar", + "403": "aircraft carrier, carrier, flattop, attack aircraft carrier", + "404": "airliner", + "405": "airship, dirigible", + "406": "altar", + "407": "ambulance", + "408": "amphibian, amphibious vehicle", + "409": "analog clock", + "410": "apiary, bee house", + "411": "apron", + "412": "ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin", + "413": "assault rifle, assault gun", + "414": "backpack, back pack, knapsack, packsack, rucksack, haversack", + "415": "bakery, bakeshop, bakehouse", + "416": "balance beam, beam", + "417": "balloon", + "418": "ballpoint, ballpoint pen, ballpen, Biro", + "419": "Band Aid", + "420": "banjo", + "421": "bannister, banister, balustrade, balusters, handrail", + "422": "barbell", + "423": "barber chair", + "424": "barbershop", + "425": "barn", + "426": "barometer", + "427": "barrel, cask", + "428": "barrow, garden cart, lawn cart, wheelbarrow", + "429": "baseball", + "430": "basketball", + "431": "bassinet", + "432": "bassoon", + "433": "bathing cap, swimming cap", + "434": "bath towel", + "435": "bathtub, bathing tub, bath, tub", + "436": "beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon", + "437": "beacon, lighthouse, beacon light, pharos", + "438": "beaker", + "439": "bearskin, busby, shako", + "440": "beer bottle", + "441": "beer glass", + "442": "bell cote, bell cot", + "443": "bib", + "444": "bicycle-built-for-two, tandem bicycle, tandem", + "445": "bikini, two-piece", + "446": "binder, ring-binder", + "447": "binoculars, field glasses, opera glasses", + "448": "birdhouse", + "449": "boathouse", + "450": "bobsled, bobsleigh, bob", + "451": "bolo tie, bolo, bola tie, bola", + "452": "bonnet, poke bonnet", + "453": "bookcase", + "454": "bookshop, bookstore, bookstall", + "455": "bottlecap", + "456": "bow", + "457": "bow tie, bow-tie, bowtie", + "458": "brass, memorial tablet, plaque", + "459": "brassiere, bra, bandeau", + "460": "breakwater, groin, groyne, mole, bulwark, seawall, jetty", + "461": "breastplate, aegis, egis", + "462": "broom", + "463": "bucket, pail", + "464": "buckle", + "465": "bulletproof vest", + "466": "bullet train, bullet", + "467": "butcher shop, meat market", + "468": "cab, hack, taxi, taxicab", + "469": "caldron, cauldron", + "470": "candle, taper, wax light", + "471": "cannon", + "472": "canoe", + "473": "can opener, tin opener", + "474": "cardigan", + "475": "car mirror", + "476": "carousel, carrousel, merry-go-round, roundabout, whirligig", + "477": "carpenters kit, tool kit", + "478": "carton", + "479": "car wheel", + "480": "cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM", + "481": "cassette", + "482": "cassette player", + "483": "castle", + "484": "catamaran", + "485": "CD player", + "486": "cello, violoncello", + "487": "cellular telephone, cellular phone, cellphone, cell, mobile phone", + "488": "chain", + "489": "chainlink fence", + "490": "chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour", + "491": "chain saw, chainsaw", + "492": "chest", + "493": "chiffonier, commode", + "494": "chime, bell, gong", + "495": "china cabinet, china closet", + "496": "Christmas stocking", + "497": "church, church building", + "498": "cinema, movie theater, movie theatre, movie house, picture palace", + "499": "cleaver, meat cleaver, chopper", + "500": "cliff dwelling", + "501": "cloak", + "502": "clog, geta, patten, sabot", + "503": "cocktail shaker", + "504": "coffee mug", + "505": "coffeepot", + "506": "coil, spiral, volute, whorl, helix", + "507": "combination lock", + "508": "computer keyboard, keypad", + "509": "confectionery, confectionary, candy store", + "510": "container ship, containership, container vessel", + "511": "convertible", + "512": "corkscrew, bottle screw", + "513": "cornet, horn, trumpet, trump", + "514": "cowboy boot", + "515": "cowboy hat, ten-gallon hat", + "516": "cradle", + "517": "crane", + "518": "crash helmet", + "519": "crate", + "520": "crib, cot", + "521": "Crock Pot", + "522": "croquet ball", + "523": "crutch", + "524": "cuirass", + "525": "dam, dike, dyke", + "526": "desk", + "527": "desktop computer", + "528": "dial telephone, dial phone", + "529": "diaper, nappy, napkin", + "530": "digital clock", + "531": "digital watch", + "532": "dining table, board", + "533": "dishrag, dishcloth", + "534": "dishwasher, dish washer, dishwashing machine", + "535": "disk brake, disc brake", + "536": "dock, dockage, docking facility", + "537": "dogsled, dog sled, dog sleigh", + "538": "dome", + "539": "doormat, welcome mat", + "540": "drilling platform, offshore rig", + "541": "drum, membranophone, tympan", + "542": "drumstick", + "543": "dumbbell", + "544": "Dutch oven", + "545": "electric fan, blower", + "546": "electric guitar", + "547": "electric locomotive", + "548": "entertainment center", + "549": "envelope", + "550": "espresso maker", + "551": "face powder", + "552": "feather boa, boa", + "553": "file, file cabinet, filing cabinet", + "554": "fireboat", + "555": "fire engine, fire truck", + "556": "fire screen, fireguard", + "557": "flagpole, flagstaff", + "558": "flute, transverse flute", + "559": "folding chair", + "560": "football helmet", + "561": "forklift", + "562": "fountain", + "563": "fountain pen", + "564": "four-poster", + "565": "freight car", + "566": "French horn, horn", + "567": "frying pan, frypan, skillet", + "568": "fur coat", + "569": "garbage truck, dustcart", + "570": "gasmask, respirator, gas helmet", + "571": "gas pump, gasoline pump, petrol pump, island dispenser", + "572": "goblet", + "573": "go-kart", + "574": "golf ball", + "575": "golfcart, golf cart", + "576": "gondola", + "577": "gong, tam-tam", + "578": "gown", + "579": "grand piano, grand", + "580": "greenhouse, nursery, glasshouse", + "581": "grille, radiator grille", + "582": "grocery store, grocery, food market, market", + "583": "guillotine", + "584": "hair slide", + "585": "hair spray", + "586": "half track", + "587": "hammer", + "588": "hamper", + "589": "hand blower, blow dryer, blow drier, hair dryer, hair drier", + "590": "hand-held computer, hand-held microcomputer", + "591": "handkerchief, hankie, hanky, hankey", + "592": "hard disc, hard disk, fixed disk", + "593": "harmonica, mouth organ, harp, mouth harp", + "594": "harp", + "595": "harvester, reaper", + "596": "hatchet", + "597": "holster", + "598": "home theater, home theatre", + "599": "honeycomb", + "600": "hook, claw", + "601": "hoopskirt, crinoline", + "602": "horizontal bar, high bar", + "603": "horse cart, horse-cart", + "604": "hourglass", + "605": "iPod", + "606": "iron, smoothing iron", + "607": "jack-o-lantern", + "608": "jean, blue jean, denim", + "609": "jeep, landrover", + "610": "jersey, T-shirt, tee shirt", + "611": "jigsaw puzzle", + "612": "jinrikisha, ricksha, rickshaw", + "613": "joystick", + "614": "kimono", + "615": "knee pad", + "616": "knot", + "617": "lab coat, laboratory coat", + "618": "ladle", + "619": "lampshade, lamp shade", + "620": "laptop, laptop computer", + "621": "lawn mower, mower", + "622": "lens cap, lens cover", + "623": "letter opener, paper knife, paperknife", + "624": "library", + "625": "lifeboat", + "626": "lighter, light, igniter, ignitor", + "627": "limousine, limo", + "628": "liner, ocean liner", + "629": "lipstick, lip rouge", + "630": "Loafer", + "631": "lotion", + "632": "loudspeaker, speaker, speaker unit, loudspeaker system, speaker system", + "633": "loupe, jewelers loupe", + "634": "lumbermill, sawmill", + "635": "magnetic compass", + "636": "mailbag, postbag", + "637": "mailbox, letter box", + "638": "maillot", + "639": "maillot, tank suit", + "640": "manhole cover", + "641": "maraca", + "642": "marimba, xylophone", + "643": "mask", + "644": "matchstick", + "645": "maypole", + "646": "maze, labyrinth", + "647": "measuring cup", + "648": "medicine chest, medicine cabinet", + "649": "megalith, megalithic structure", + "650": "microphone, mike", + "651": "microwave, microwave oven", + "652": "military uniform", + "653": "milk can", + "654": "minibus", + "655": "miniskirt, mini", + "656": "minivan", + "657": "missile", + "658": "mitten", + "659": "mixing bowl", + "660": "mobile home, manufactured home", + "661": "Model T", + "662": "modem", + "663": "monastery", + "664": "monitor", + "665": "moped", + "666": "mortar", + "667": "mortarboard", + "668": "mosque", + "669": "mosquito net", + "670": "motor scooter, scooter", + "671": "mountain bike, all-terrain bike, off-roader", + "672": "mountain tent", + "673": "mouse, computer mouse", + "674": "mousetrap", + "675": "moving van", + "676": "muzzle", + "677": "nail", + "678": "neck brace", + "679": "necklace", + "680": "nipple", + "681": "notebook, notebook computer", + "682": "obelisk", + "683": "oboe, hautboy, hautbois", + "684": "ocarina, sweet potato", + "685": "odometer, hodometer, mileometer, milometer", + "686": "oil filter", + "687": "organ, pipe organ", + "688": "oscilloscope, scope, cathode-ray oscilloscope, CRO", + "689": "overskirt", + "690": "oxcart", + "691": "oxygen mask", + "692": "packet", + "693": "paddle, boat paddle", + "694": "paddlewheel, paddle wheel", + "695": "padlock", + "696": "paintbrush", + "697": "pajama, pyjama, pjs, jammies", + "698": "palace", + "699": "panpipe, pandean pipe, syrinx", + "700": "paper towel", + "701": "parachute, chute", + "702": "parallel bars, bars", + "703": "park bench", + "704": "parking meter", + "705": "passenger car, coach, carriage", + "706": "patio, terrace", + "707": "pay-phone, pay-station", + "708": "pedestal, plinth, footstall", + "709": "pencil box, pencil case", + "710": "pencil sharpener", + "711": "perfume, essence", + "712": "Petri dish", + "713": "photocopier", + "714": "pick, plectrum, plectron", + "715": "pickelhaube", + "716": "picket fence, paling", + "717": "pickup, pickup truck", + "718": "pier", + "719": "piggy bank, penny bank", + "720": "pill bottle", + "721": "pillow", + "722": "ping-pong ball", + "723": "pinwheel", + "724": "pirate, pirate ship", + "725": "pitcher, ewer", + "726": "plane, carpenters plane, woodworking plane", + "727": "planetarium", + "728": "plastic bag", + "729": "plate rack", + "730": "plow, plough", + "731": "plunger, plumbers helper", + "732": "Polaroid camera, Polaroid Land camera", + "733": "pole", + "734": "police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria", + "735": "poncho", + "736": "pool table, billiard table, snooker table", + "737": "pop bottle, soda bottle", + "738": "pot, flowerpot", + "739": "potters wheel", + "740": "power drill", + "741": "prayer rug, prayer mat", + "742": "printer", + "743": "prison, prison house", + "744": "projectile, missile", + "745": "projector", + "746": "puck, hockey puck", + "747": "punching bag, punch bag, punching ball, punchball", + "748": "purse", + "749": "quill, quill pen", + "750": "quilt, comforter, comfort, puff", + "751": "racer, race car, racing car", + "752": "racket, racquet", + "753": "radiator", + "754": "radio, wireless", + "755": "radio telescope, radio reflector", + "756": "rain barrel", + "757": "recreational vehicle, RV, R.V.", + "758": "reel", + "759": "reflex camera", + "760": "refrigerator, icebox", + "761": "remote control, remote", + "762": "restaurant, eating house, eating place, eatery", + "763": "revolver, six-gun, six-shooter", + "764": "rifle", + "765": "rocking chair, rocker", + "766": "rotisserie", + "767": "rubber eraser, rubber, pencil eraser", + "768": "rugby ball", + "769": "rule, ruler", + "770": "running shoe", + "771": "safe", + "772": "safety pin", + "773": "saltshaker, salt shaker", + "774": "sandal", + "775": "sarong", + "776": "sax, saxophone", + "777": "scabbard", + "778": "scale, weighing machine", + "779": "school bus", + "780": "schooner", + "781": "scoreboard", + "782": "screen, CRT screen", + "783": "screw", + "784": "screwdriver", + "785": "seat belt, seatbelt", + "786": "sewing machine", + "787": "shield, buckler", + "788": "shoe shop, shoe-shop, shoe store", + "789": "shoji", + "790": "shopping basket", + "791": "shopping cart", + "792": "shovel", + "793": "shower cap", + "794": "shower curtain", + "795": "ski", + "796": "ski mask", + "797": "sleeping bag", + "798": "slide rule, slipstick", + "799": "sliding door", + "800": "slot, one-armed bandit", + "801": "snorkel", + "802": "snowmobile", + "803": "snowplow, snowplough", + "804": "soap dispenser", + "805": "soccer ball", + "806": "sock", + "807": "solar dish, solar collector, solar furnace", + "808": "sombrero", + "809": "soup bowl", + "810": "space bar", + "811": "space heater", + "812": "space shuttle", + "813": "spatula", + "814": "speedboat", + "815": "spider web, spiders web", + "816": "spindle", + "817": "sports car, sport car", + "818": "spotlight, spot", + "819": "stage", + "820": "steam locomotive", + "821": "steel arch bridge", + "822": "steel drum", + "823": "stethoscope", + "824": "stole", + "825": "stone wall", + "826": "stopwatch, stop watch", + "827": "stove", + "828": "strainer", + "829": "streetcar, tram, tramcar, trolley, trolley car", + "830": "stretcher", + "831": "studio couch, day bed", + "832": "stupa, tope", + "833": "submarine, pigboat, sub, U-boat", + "834": "suit, suit of clothes", + "835": "sundial", + "836": "sunglass", + "837": "sunglasses, dark glasses, shades", + "838": "sunscreen, sunblock, sun blocker", + "839": "suspension bridge", + "840": "swab, swob, mop", + "841": "sweatshirt", + "842": "swimming trunks, bathing trunks", + "843": "swing", + "844": "switch, electric switch, electrical switch", + "845": "syringe", + "846": "table lamp", + "847": "tank, army tank, armored combat vehicle, armoured combat vehicle", + "848": "tape player", + "849": "teapot", + "850": "teddy, teddy bear", + "851": "television, television system", + "852": "tennis ball", + "853": "thatch, thatched roof", + "854": "theater curtain, theatre curtain", + "855": "thimble", + "856": "thresher, thrasher, threshing machine", + "857": "throne", + "858": "tile roof", + "859": "toaster", + "860": "tobacco shop, tobacconist shop, tobacconist", + "861": "toilet seat", + "862": "torch", + "863": "totem pole", + "864": "tow truck, tow car, wrecker", + "865": "toyshop", + "866": "tractor", + "867": "trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi", + "868": "tray", + "869": "trench coat", + "870": "tricycle, trike, velocipede", + "871": "trimaran", + "872": "tripod", + "873": "triumphal arch", + "874": "trolleybus, trolley coach, trackless trolley", + "875": "trombone", + "876": "tub, vat", + "877": "turnstile", + "878": "typewriter keyboard", + "879": "umbrella", + "880": "unicycle, monocycle", + "881": "upright, upright piano", + "882": "vacuum, vacuum cleaner", + "883": "vase", + "884": "vault", + "885": "velvet", + "886": "vending machine", + "887": "vestment", + "888": "viaduct", + "889": "violin, fiddle", + "890": "volleyball", + "891": "waffle iron", + "892": "wall clock", + "893": "wallet, billfold, notecase, pocketbook", + "894": "wardrobe, closet, press", + "895": "warplane, military plane", + "896": "washbasin, handbasin, washbowl, lavabo, wash-hand basin", + "897": "washer, automatic washer, washing machine", + "898": "water bottle", + "899": "water jug", + "900": "water tower", + "901": "whiskey jug", + "902": "whistle", + "903": "wig", + "904": "window screen", + "905": "window shade", + "906": "Windsor tie", + "907": "wine bottle", + "908": "wing", + "909": "wok", + "910": "wooden spoon", + "911": "wool, woolen, woollen", + "912": "worm fence, snake fence, snake-rail fence, Virginia fence", + "913": "wreck", + "914": "yawl", + "915": "yurt", + "916": "web site, website, internet site, site", + "917": "comic book", + "918": "crossword puzzle, crossword", + "919": "street sign", + "920": "traffic light, traffic signal, stoplight", + "921": "book jacket, dust cover, dust jacket, dust wrapper", + "922": "menu", + "923": "plate", + "924": "guacamole", + "925": "consomme", + "926": "hot pot, hotpot", + "927": "trifle", + "928": "ice cream, icecream", + "929": "ice lolly, lolly, lollipop, popsicle", + "930": "French loaf", + "931": "bagel, beigel", + "932": "pretzel", + "933": "cheeseburger", + "934": "hotdog, hot dog, red hot", + "935": "mashed potato", + "936": "head cabbage", + "937": "broccoli", + "938": "cauliflower", + "939": "zucchini, courgette", + "940": "spaghetti squash", + "941": "acorn squash", + "942": "butternut squash", + "943": "cucumber, cuke", + "944": "artichoke, globe artichoke", + "945": "bell pepper", + "946": "cardoon", + "947": "mushroom", + "948": "Granny Smith", + "949": "strawberry", + "950": "orange", + "951": "lemon", + "952": "fig", + "953": "pineapple, ananas", + "954": "banana", + "955": "jackfruit, jak, jack", + "956": "custard apple", + "957": "pomegranate", + "958": "hay", + "959": "carbonara", + "960": "chocolate sauce, chocolate syrup", + "961": "dough", + "962": "meat loaf, meatloaf", + "963": "pizza, pizza pie", + "964": "potpie", + "965": "burrito", + "966": "red wine", + "967": "espresso", + "968": "cup", + "969": "eggnog", + "970": "alp", + "971": "bubble", + "972": "cliff, drop, drop-off", + "973": "coral reef", + "974": "geyser", + "975": "lakeside, lakeshore", + "976": "promontory, headland, head, foreland", + "977": "sandbar, sand bar", + "978": "seashore, coast, seacoast, sea-coast", + "979": "valley, vale", + "980": "volcano", + "981": "ballplayer, baseball player", + "982": "groom, bridegroom", + "983": "scuba diver", + "984": "rapeseed", + "985": "daisy", + "986": "yellow ladys slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum", + "987": "corn", + "988": "acorn", + "989": "hip, rose hip, rosehip", + "990": "buckeye, horse chestnut, conker", + "991": "coral fungus", + "992": "agaric", + "993": "gyromitra", + "994": "stinkhorn, carrion fungus", + "995": "earthstar", + "996": "hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa", + "997": "bolete", + "998": "ear, spike, capitulum", + "999": "toilet tissue, toilet paper, bathroom tissue" + }, + "scheduler": [ + "scheduling_flow_match_pae", + "PAEFlowMatchScheduler" + ], + "transformers": [ + "transformer_lightning_dit", + "LightningDiT2DModel" + ] +} diff --git a/pae-siglip2-so400m-d32/pipeline.py b/pae-siglip2-so400m-d32/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..baed829d24d510b38fe9905fd001b835a176475f --- /dev/null +++ b/pae-siglip2-so400m-d32/pipeline.py @@ -0,0 +1,530 @@ +"""Hub custom pipeline: PAEPipeline. +Load with native Hugging Face diffusers and trust_remote_code=True. +""" + +from __future__ import annotations + +# Copyright 2026 The HuggingFace Team and PAE authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import inspect +import json +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple, Union + +import torch + +from diffusers.image_processor import VaeImageProcessor +from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput +from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers +from diffusers.utils.torch_utils import randn_tensor + +EXAMPLE_DOC_STRING = """ + Examples: + ```py + >>> from pathlib import Path + >>> from diffusers import DiffusionPipeline + >>> import torch + + >>> model_dir = Path("./pae-dinov2-large-d32").resolve() + >>> pipe = DiffusionPipeline.from_pretrained( + ... str(model_dir), + ... local_files_only=True, + ... custom_pipeline=str(model_dir / "pipeline.py"), + ... trust_remote_code=True, + ... torch_dtype=torch.bfloat16, + ... ) + >>> pipe.to("cuda") + + >>> print(pipe.id2label[207]) + >>> print(pipe.get_label_ids("golden retriever")) + + >>> generator = torch.Generator(device="cuda").manual_seed(42) + >>> image = pipe( + ... class_labels="golden retriever", + ... generator=generator, + ... ).images[0] + ``` +""" + + +class PAEPipeline(DiffusionPipeline): + r""" + Pipeline for class-conditional image generation with PAE tokenizers and LightningDiT. + + This model inherits from [`DiffusionPipeline`]. Components are stored in separate subfolders + (`transformers/`, `scheduler/`, `decoder/`) and loaded via `DiffusionPipeline.from_pretrained`. + + Parameters: + transformers ([`LightningDiT2DModel`]): + Class-conditional LightningDiT transformer that predicts flow-matching velocity in PAE latent space. + scheduler ([`PAEFlowMatchScheduler`]): + Flow-matching ODE/SDE scheduler. Other [`KarrasDiffusionSchedulers`] can be swapped at inference time + when their `step` API is compatible. + decoder ([`PAEDecoder`]): + Prior-Aligned Autoencoder decoder stack (decompressor + pixel decoder). + + ImageNet `id2label` mappings are read lazily from `model_index.json` when label helpers are used. + """ + + model_cpu_offload_seq = "transformers->decoder" + _optional_components = ["decoder"] + + @staticmethod + def prepare_extra_step_kwargs( + scheduler: KarrasDiffusionSchedulers, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + eta: Optional[float] = None, + ) -> Dict[str, object]: + r""" + Build kwargs forwarded to `scheduler.step` when supported. + + Args: + scheduler: + Active diffusion scheduler instance. + generator: + Optional RNG passed through to stochastic scheduler steps. + eta: + Optional DDIM-style eta when the scheduler accepts it. + """ + kwargs: Dict[str, object] = {} + step_params = set(inspect.signature(scheduler.step).parameters.keys()) + if "generator" in step_params: + kwargs["generator"] = generator + if eta is not None and "eta" in step_params: + kwargs["eta"] = eta + return kwargs + + def __init__( + self, + transformers, + scheduler: KarrasDiffusionSchedulers, + decoder=None, + transformer=None, + ) -> None: + if transformer is not None and transformers is None: + transformers = transformer + super().__init__() + self.register_modules(transformers=transformers, scheduler=scheduler, decoder=decoder) + # PAE decoders already return pixels in [0, 1]; disable VAE-style [-1, 1] denormalization. + self.image_processor = VaeImageProcessor(do_normalize=False) + self._id2label: Dict[int, str] = {} + self.labels: Dict[str, int] = {} + self._labels_loaded_from_model_index = False + + @property + def transformer(self): + """Backward-compatible alias for `transformers`.""" + return self.transformers + + @staticmethod + def _normalize_id2label(id2label: Optional[Dict[Union[int, str], str]]) -> Dict[int, str]: + if not id2label: + return {} + return {int(key): value for key, value in id2label.items()} + + @staticmethod + def _read_model_index(variant_path: Optional[str]) -> Dict[str, Any]: + if not variant_path: + return {} + variant_dir = Path(variant_path).resolve() + model_index_path = variant_dir / "model_index.json" + if not model_index_path.is_file(): + return {} + raw = json.loads(model_index_path.read_text(encoding="utf-8")) + return raw if isinstance(raw, dict) else {} + + @staticmethod + def _read_id2label_from_model_index(variant_path: Optional[str]) -> Dict[int, str]: + id2label = PAEPipeline._read_model_index(variant_path).get("id2label") + if not isinstance(id2label, dict): + return {} + return {int(key): value for key, value in id2label.items()} + + def _get_downsample_ratio(self) -> int: + override = getattr(self.config, "downsample_ratio", None) + if override is not None: + return int(override) + + encoder_input_size = None + if self.decoder is not None: + encoder_input_size = getattr(self.decoder.config, "encoder_input_size", None) + + if encoder_input_size is not None: + return int(encoder_input_size) // int(self.transformers.config.input_size) + return 16 + + def _resolve_latent_stats( + self, + latent_mean: Optional[torch.Tensor], + latent_std: Optional[torch.Tensor], + latent_multiplier: Optional[float], + device: torch.device, + dtype: torch.dtype, + ) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], float]: + if latent_mean is not None and latent_std is not None: + return latent_mean, latent_std, float(latent_multiplier if latent_multiplier is not None else 1.0) + + decoder_cfg = getattr(self.decoder, "config", None) if self.decoder is not None else None + if decoder_cfg is not None: + mean = getattr(decoder_cfg, "latent_mean", None) + std = getattr(decoder_cfg, "latent_std", None) + if mean is not None and std is not None: + multiplier = getattr(decoder_cfg, "latent_multiplier", 1.0) + mean_tensor = torch.tensor(mean, device=device, dtype=dtype).view(1, -1, 1, 1) + std_tensor = torch.tensor(std, device=device, dtype=dtype).view(1, -1, 1, 1) + return mean_tensor, std_tensor, float(multiplier) + + return latent_mean, latent_std, float(latent_multiplier if latent_multiplier is not None else 1.0) + + @staticmethod + def _build_label2id(id2label: Dict[int, str]) -> Dict[str, int]: + label2id: Dict[str, int] = {} + for class_id, value in id2label.items(): + for synonym in value.split(","): + synonym = synonym.strip() + if synonym: + label2id[synonym] = int(class_id) + return dict(sorted(label2id.items())) + + def _ensure_labels_loaded(self) -> None: + if self._labels_loaded_from_model_index: + return + loaded = self._read_id2label_from_model_index(getattr(self.config, "_name_or_path", None)) + if loaded: + self._id2label = loaded + self.labels = self._build_label2id(self._id2label) + self._labels_loaded_from_model_index = True + + @property + def id2label(self) -> Dict[int, str]: + r"""ImageNet class id to English label string (comma-separated synonyms).""" + self._ensure_labels_loaded() + return self._id2label + + def get_label_ids(self, label: Union[str, List[str]]) -> List[int]: + r""" + Map ImageNet label strings to class ids. + + Args: + label: + One or more English label strings. Each string must match a synonym in `id2label`. + + Returns: + Matching ImageNet class ids. + """ + self._ensure_labels_loaded() + label2id = self.labels + if not label2id: + raise ValueError("No English labels loaded. Ensure `id2label` exists in model_index.json.") + + if isinstance(label, str): + label = [label] + + missing = [item for item in label if item not in label2id] + if missing: + preview = ", ".join(list(label2id.keys())[:8]) + raise ValueError(f"Unknown English label(s): {missing}. Example valid labels: {preview}, ...") + return [label2id[item] for item in label] + + def _default_image_size(self) -> int: + return int(self.transformers.config.input_size) * self._get_downsample_ratio() + + def _normalize_class_labels( + self, + class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor], + ) -> torch.LongTensor: + if torch.is_tensor(class_labels): + return class_labels.to(device=self._execution_device, dtype=torch.long).reshape(-1) + + if isinstance(class_labels, int): + class_label_ids = [class_labels] + elif isinstance(class_labels, str): + class_label_ids = self.get_label_ids(class_labels) + elif class_labels and isinstance(class_labels[0], str): + class_label_ids = self.get_label_ids(class_labels) + else: + class_label_ids = list(class_labels) + + return torch.tensor(class_label_ids, device=self._execution_device, dtype=torch.long).reshape(-1) + + def check_inputs( + self, + height: int, + width: int, + num_inference_steps: int, + output_type: str, + mode: str, + ) -> None: + if num_inference_steps < 1: + raise ValueError("num_inference_steps must be >= 1.") + if output_type not in {"pil", "np", "pt", "latent"}: + raise ValueError("output_type must be one of: 'pil', 'np', 'pt', 'latent'.") + if mode not in {"ode", "sde"}: + raise ValueError("mode must be either 'ode' or 'sde'.") + + downsample = self._get_downsample_ratio() + if height % downsample != 0 or width % downsample != 0: + raise ValueError( + f"height and width must be divisible by the PAE downsample factor {downsample}." + ) + + latent_height = height // downsample + latent_width = width // downsample + expected_size = int(self.transformers.config.input_size) + if latent_height != expected_size or latent_width != expected_size: + raise ValueError( + f"Requested latent size {(latent_height, latent_width)} does not match the pretrained " + f"transformer input_size={expected_size}. Use height=width={self._default_image_size()}." + ) + + def prepare_latents( + self, + batch_size: int, + height: int, + width: int, + dtype: torch.dtype, + device: torch.device, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + ) -> torch.Tensor: + downsample = self._get_downsample_ratio() + latent_height = height // downsample + latent_width = width // downsample + return randn_tensor( + (batch_size, self.transformers.config.in_channels, latent_height, latent_width), + generator=generator, + device=device, + dtype=dtype, + ) + + @staticmethod + def _denormalize_latents( + latents: torch.Tensor, + latent_mean: Optional[torch.Tensor], + latent_std: Optional[torch.Tensor], + latent_multiplier: Optional[float], + ) -> torch.Tensor: + if latent_mean is None or latent_std is None: + return latents + multiplier = 1.0 if latent_multiplier is None else float(latent_multiplier) + mean = latent_mean.to(device=latents.device, dtype=latents.dtype) + std = latent_std.to(device=latents.device, dtype=latents.dtype) + return (latents * std) / multiplier + mean + + @staticmethod + def _apply_cfg( + model_output: torch.Tensor, + guidance_scale: float, + guidance_active: bool, + cfg_channels: int, + ) -> torch.Tensor: + if guidance_scale <= 1.0 or not guidance_active: + return model_output + eps, rest = model_output[:, :cfg_channels], model_output[:, cfg_channels:] + cond_eps, uncond_eps = torch.chunk(eps, 2, dim=0) + half_eps = uncond_eps + guidance_scale * (cond_eps - uncond_eps) + if rest.shape[1] == 0: + return half_eps + return torch.cat([half_eps, rest], dim=1) + + def decode_latents( + self, + latents: torch.Tensor, + output_type: str = "pil", + latent_mean: Optional[torch.Tensor] = None, + latent_std: Optional[torch.Tensor] = None, + latent_multiplier: Optional[float] = None, + ): + if output_type == "latent": + return latents + if self.decoder is None: + raise ValueError("PAEPipeline requires a PAE decoder component for decoding.") + + latent_mean, latent_std, latent_multiplier = self._resolve_latent_stats( + latent_mean, + latent_std, + latent_multiplier, + device=latents.device, + dtype=latents.dtype, + ) + latents = self._denormalize_latents(latents, latent_mean, latent_std, latent_multiplier) + image = self.decoder.decode(latents) + image = torch.clamp(image, 0.0, 1.0) + if output_type == "pt": + return image + return self.image_processor.postprocess(image, output_type=output_type, do_denormalize=[False] * image.shape[0]) + + @torch.inference_mode() + def __call__( + self, + class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor], + height: Optional[int] = None, + width: Optional[int] = None, + num_inference_steps: int = 250, + guidance_scale: float = 3.3, + guidance_interval: Tuple[float, float] = (0.0, 1.0), + cfg_interval_start: float = 0.3, + timestep_shift: float = 0.4, + mode: str = "ode", + heun: bool = False, + latent_mean: Optional[torch.Tensor] = None, + latent_std: Optional[torch.Tensor] = None, + latent_multiplier: Optional[float] = None, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + output_type: str = "pil", + return_dict: bool = True, + ) -> Union[ImagePipelineOutput, Tuple]: + r""" + Generate class-conditional images with PAE + LightningDiT. + + Args: + class_labels: + ImageNet class indices or human-readable English label strings. + height: + Output image height in pixels. Defaults to the pretrained native resolution. + width: + Output image width in pixels. Defaults to the pretrained native resolution. + num_inference_steps: + Number of flow-matching integration steps. + guidance_scale: + Classifier-free guidance scale. Active when `guidance_scale > 1.0`. + guidance_interval: + Timestep interval `(low, high)` where CFG is applied. + cfg_interval_start: + Disable CFG below this normalized timestep value. Default `0.3` matches DiT training configs. + timestep_shift: + Timestep warping used by LightningDiT ODE sampling. Default `0.4` matches DiT training configs. + mode: + Sampling mode passed to the PAE flow scheduler: `"ode"` or `"sde"`. + heun: + Use Heun integration for ODE sampling when True. + latent_mean: + Optional latent mean tensor for denormalization before PAE decode. Defaults to + `latent_mean` in `decoder/config.json` when omitted. + latent_std: + Optional latent std tensor for denormalization before PAE decode. Defaults to + `latent_std` in `decoder/config.json` when omitted. + latent_multiplier: + Divisor applied with `latent_std` during denormalization. Defaults to + `latent_multiplier` in `decoder/config.json` or `1.0`. + generator: + RNG for reproducibility. + output_type: + `"pil"`, `"np"`, `"pt"`, or `"latent"`. + return_dict: + Return [`ImagePipelineOutput`] if True. + """ + default_size = self._default_image_size() + height = int(height or default_size) + width = int(width or default_size) + self.check_inputs(height, width, num_inference_steps, output_type, mode) + + device = self._execution_device + model_dtype = next(self.transformers.parameters()).dtype + class_labels_tensor = self._normalize_class_labels(class_labels) + batch_size = class_labels_tensor.numel() + null_label = int(self.transformers.config.num_classes) + null_labels = torch.full((batch_size,), null_label, device=device, dtype=torch.long) + cfg_channels = int(self.transformers.config.in_channels) + + latents = self.prepare_latents( + batch_size=batch_size, + height=height, + width=width, + dtype=model_dtype, + device=device, + generator=generator, + ) + timesteps = self.scheduler.set_timesteps( + num_inference_steps, device=device, mode=mode, timestep_shift=timestep_shift + ) + extra_step_kwargs = self.prepare_extra_step_kwargs(self.scheduler, generator=generator) + + for index, timestep in enumerate(timesteps[:-1]): + next_timestep = timesteps[index + 1] + t_value = float(timestep) + guidance_active = guidance_scale > 1.0 and guidance_interval[0] <= t_value <= guidance_interval[1] + if cfg_interval_start is not None and t_value < cfg_interval_start: + guidance_active = False + + if guidance_active: + model_input = torch.cat([latents, latents], dim=0) + labels = torch.cat([class_labels_tensor, null_labels], dim=0) + else: + model_input = latents + labels = class_labels_tensor + + timestep_batch = torch.full((labels.shape[0],), t_value, device=device, dtype=model_dtype) + model_output = self.transformers( + model_input.to(dtype=model_dtype), + timestep=timestep_batch, + class_labels=labels, + return_dict=True, + ).sample + model_output = self._apply_cfg(model_output, guidance_scale, guidance_active, cfg_channels) + + if heun and mode == "ode" and index < len(timesteps) - 2: + provisional = self.scheduler.step( + model_output, + timestep[None], + latents, + next_timestep[None], + **extra_step_kwargs, + ).prev_sample + if guidance_active: + prime_input = torch.cat([provisional, provisional], dim=0) + prime_labels = torch.cat([class_labels_tensor, null_labels], dim=0) + else: + prime_input = provisional + prime_labels = class_labels_tensor + next_timestep_batch = torch.full( + (prime_labels.shape[0],), float(next_timestep), device=device, dtype=model_dtype + ) + next_output = self.transformers( + prime_input.to(dtype=model_dtype), + timestep=next_timestep_batch, + class_labels=prime_labels, + return_dict=True, + ).sample + next_output = self._apply_cfg(next_output, guidance_scale, guidance_active, cfg_channels) + latents = self.scheduler.step_heun( + model_output, next_output, timestep[None], latents, next_timestep[None] + ).prev_sample + else: + latents = self.scheduler.step( + model_output, + timestep[None], + latents, + next_timestep[None], + **extra_step_kwargs, + ).prev_sample + + image = self.decode_latents( + latents.to(dtype=model_dtype), + output_type=output_type, + latent_mean=latent_mean, + latent_std=latent_std, + latent_multiplier=latent_multiplier, + ) + + self.maybe_free_model_hooks() + if not return_dict: + return (image,) + return ImagePipelineOutput(images=image) + + +# Backward-compatible alias used by earlier PAE-diffusers releases. +PAEPipelineOutput = ImagePipelineOutput diff --git a/pae-siglip2-so400m-d32/scheduler/__pycache__/scheduling_flow_match_pae.cpython-311.pyc b/pae-siglip2-so400m-d32/scheduler/__pycache__/scheduling_flow_match_pae.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64d05c55e59af2ffd0783efda59e1154276847ab Binary files /dev/null and b/pae-siglip2-so400m-d32/scheduler/__pycache__/scheduling_flow_match_pae.cpython-311.pyc differ diff --git a/pae-siglip2-so400m-d32/scheduler/scheduler_config.json b/pae-siglip2-so400m-d32/scheduler/scheduler_config.json new file mode 100644 index 0000000000000000000000000000000000000000..75d51d14e68c7500bbb2ddd937dc7669b8d3e27d --- /dev/null +++ b/pae-siglip2-so400m-d32/scheduler/scheduler_config.json @@ -0,0 +1,7 @@ +{ + "_class_name": "PAEFlowMatchScheduler", + "_diffusers_version": "0.31.0", + "mode": "ode", + "path_type": "linear", + "num_train_timesteps": 1000 +} diff --git a/pae-siglip2-so400m-d32/scheduler/scheduling_flow_match_pae.py b/pae-siglip2-so400m-d32/scheduler/scheduling_flow_match_pae.py new file mode 100644 index 0000000000000000000000000000000000000000..e79368596bb250ea5689e1775d653291ab6e55c1 --- /dev/null +++ b/pae-siglip2-so400m-d32/scheduler/scheduling_flow_match_pae.py @@ -0,0 +1,200 @@ +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. + +from dataclasses import dataclass +from typing import Optional, Tuple + +import numpy as np +import torch + +try: + from diffusers.configuration_utils import ConfigMixin, register_to_config + from diffusers.schedulers.scheduling_utils import SchedulerMixin + from diffusers.utils import BaseOutput +except Exception: # pragma: no cover - importable without an installed diffusers checkout. + class BaseOutput(dict): + def __post_init__(self): + self.update(self.__dict__) + + class ConfigMixin: + config_name = "scheduler_config.json" + + class SchedulerMixin: + pass + + def register_to_config(init): + return init + + +@dataclass +class PAEFlowMatchSchedulerOutput(BaseOutput): + prev_sample: torch.FloatTensor + + +class PAEFlowMatchScheduler(SchedulerMixin, ConfigMixin): + """ + Flow-matching ODE/SDE scheduler used by PAE + LightningDiT pipelines. + + The model predicts velocity with a linear path by default. ODE timesteps run from 0 to 1 + (noise to data), matching LightningDiT transport sampling. + """ + + config_name = "scheduler_config.json" + order = 1 + + @register_to_config + def __init__( + self, + mode: str = "ode", + path_type: str = "linear", + num_train_timesteps: int = 1000, + ): + if mode not in {"ode", "sde"}: + raise ValueError("mode must be either 'ode' or 'sde'.") + if path_type not in {"linear", "cosine"}: + raise ValueError("path_type must be either 'linear' or 'cosine'.") + self.mode = mode + self.path_type = path_type + self.num_train_timesteps = num_train_timesteps + # Native NiT integrates in float64 for better numerical stability. + self.timesteps = torch.from_numpy(np.linspace(0.0, 1.0, num_train_timesteps + 1)).to(dtype=torch.float64) + + @staticmethod + def _apply_timestep_shift(timesteps: torch.Tensor, timestep_shift: float) -> torch.Tensor: + if timestep_shift <= 0: + return timesteps + return timestep_shift * timesteps / (1 + (timestep_shift - 1) * timesteps) + + def set_timesteps( + self, + num_inference_steps: int, + device: Optional[torch.device] = None, + mode: Optional[str] = None, + timestep_shift: float = 0.0, + ): + mode = mode or self.mode + dtype = self.timesteps.dtype + if mode == "sde": + timesteps = torch.linspace(1.0, 0.04, num_inference_steps, dtype=dtype) + timesteps = torch.cat([timesteps, torch.zeros(1, dtype=dtype)]) + elif mode == "ode": + timesteps = torch.linspace(0.0, 1.0, num_inference_steps + 1, dtype=dtype) + timesteps = self._apply_timestep_shift(timesteps, timestep_shift) + else: + raise ValueError("mode must be either 'ode' or 'sde'.") + self.mode = mode + self.timesteps = timesteps.to(device=device) + return self.timesteps + + @staticmethod + def _expand_t_like_sample(timestep: torch.Tensor, sample: torch.Tensor, image_sizes: torch.LongTensor): + dims = [1] * (sample.ndim - 1) + seqlens = image_sizes[:, 0] * image_sizes[:, 1] + if timestep.numel() == 1: + timestep = timestep.repeat(image_sizes.shape[0]) + return torch.cat( + [timestep[i].reshape(1, *dims).repeat(int(seqlens[i]), *dims) for i in range(image_sizes.shape[0])] + ) + + def _get_score_from_velocity( + self, + model_output: torch.Tensor, + sample: torch.Tensor, + timestep: torch.Tensor, + image_sizes: torch.LongTensor, + ): + timestep = self._expand_t_like_sample(timestep, sample, image_sizes) + if self.path_type == "linear": + alpha_t, d_alpha_t = 1 - timestep, torch.ones_like(timestep) * -1 + sigma_t, d_sigma_t = timestep, torch.ones_like(timestep) + elif self.path_type == "cosine": + alpha_t = torch.cos(timestep * np.pi / 2) + sigma_t = torch.sin(timestep * np.pi / 2) + d_alpha_t = -np.pi / 2 * torch.sin(timestep * np.pi / 2) + d_sigma_t = np.pi / 2 * torch.cos(timestep * np.pi / 2) + else: + raise ValueError(f"Unsupported path_type: {self.path_type}") + reverse_alpha_ratio = alpha_t / d_alpha_t + variance = sigma_t**2 - reverse_alpha_ratio * d_sigma_t * sigma_t + return (reverse_alpha_ratio * model_output - sample) / variance + + @staticmethod + def _compute_diffusion(timestep: torch.Tensor): + return 2 * timestep + + @staticmethod + def _promote_dtypes(*tensors: torch.Tensor) -> torch.dtype: + dtype = None + for tensor in tensors: + if tensor.is_floating_point() or tensor.is_complex(): + dtype = tensor.dtype if dtype is None else torch.promote_types(dtype, tensor.dtype) + return dtype if dtype is not None else torch.get_default_dtype() + + def step( + self, + model_output: torch.Tensor, + timestep: torch.Tensor, + sample: torch.Tensor, + next_timestep: torch.Tensor, + image_sizes: Optional[torch.LongTensor] = None, + generator: Optional[torch.Generator] = None, + return_dict: bool = True, + ) -> PAEFlowMatchSchedulerOutput: + sample_dtype = sample.dtype + compute_dtype = torch.float64 + sample = sample.to(dtype=compute_dtype) + model_output = model_output.to(dtype=compute_dtype) + timestep = timestep.to(device=sample.device, dtype=compute_dtype).flatten() + next_timestep = next_timestep.to(device=sample.device, dtype=compute_dtype).flatten() + + if self.mode == "ode": + prev_sample = sample + (next_timestep[0] - timestep[0]) * model_output + else: + if image_sizes is None: + batch = sample.shape[0] + side = int(sample.shape[-1]) + image_sizes = torch.tensor([[side, side]] * batch, device=sample.device, dtype=torch.long) + image_sizes = image_sizes.to(device=sample.device, dtype=torch.long) + diffusion = self._compute_diffusion(timestep[0]) + score = self._get_score_from_velocity(model_output, sample, timestep, image_sizes) + drift = model_output - 0.5 * diffusion * score + dt = next_timestep[0] - timestep[0] + if torch.allclose(next_timestep[0], torch.zeros_like(next_timestep[0])): + prev_sample = sample + drift * dt + else: + if generator is not None: + noise = torch.randn(sample.shape, generator=generator, device=sample.device, dtype=sample.dtype) + else: + noise = torch.randn_like(sample) + prev_sample = sample + drift * dt + torch.sqrt(diffusion) * noise * torch.sqrt(torch.abs(dt)) + + prev_sample = prev_sample.to(sample_dtype) + if not return_dict: + return (prev_sample,) + return PAEFlowMatchSchedulerOutput(prev_sample=prev_sample) + + def step_heun( + self, + model_output: torch.Tensor, + next_model_output: torch.Tensor, + timestep: torch.Tensor, + sample: torch.Tensor, + next_timestep: torch.Tensor, + return_dict: bool = True, + ) -> PAEFlowMatchSchedulerOutput: + if self.mode != "ode": + raise ValueError("Heun correction is only defined for ODE sampling.") + sample_dtype = sample.dtype + compute_dtype = torch.float64 + sample = sample.to(dtype=compute_dtype) + model_output = model_output.to(dtype=compute_dtype) + next_model_output = next_model_output.to(dtype=compute_dtype) + timestep = timestep.to(device=sample.device, dtype=compute_dtype).flatten() + next_timestep = next_timestep.to(device=sample.device, dtype=compute_dtype).flatten() + prev_sample = sample + (next_timestep[0] - timestep[0]) * (0.5 * model_output + 0.5 * next_model_output) + prev_sample = prev_sample.to(sample_dtype) + if not return_dict: + return (prev_sample,) + return PAEFlowMatchSchedulerOutput(prev_sample=prev_sample) diff --git a/pae-siglip2-so400m-d32/transformers/__pycache__/transformer_lightning_dit.cpython-311.pyc b/pae-siglip2-so400m-d32/transformers/__pycache__/transformer_lightning_dit.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..338b4f3c0f2a575ed0b80c169d5f0927000b5778 Binary files /dev/null and b/pae-siglip2-so400m-d32/transformers/__pycache__/transformer_lightning_dit.cpython-311.pyc differ diff --git a/pae-siglip2-so400m-d32/transformers/config.json b/pae-siglip2-so400m-d32/transformers/config.json new file mode 100644 index 0000000000000000000000000000000000000000..0ada32ab81a0b5c6f1f858f1507967f000966914 --- /dev/null +++ b/pae-siglip2-so400m-d32/transformers/config.json @@ -0,0 +1,20 @@ +{ + "_class_name": "LightningDiT2DModel", + "class_dropout_prob": 0.1, + "depth": 28, + "hidden_size": 1152, + "in_channels": 32, + "input_size": 16, + "learn_sigma": false, + "mlp_ratio": 4.0, + "num_classes": 1000, + "num_heads": 16, + "patch_size": 1, + "use_abs_pos": true, + "use_checkpoint": false, + "use_qknorm": true, + "use_rmsnorm": true, + "use_rope": true, + "use_swiglu": true, + "wo_shift": false +} diff --git a/pae-siglip2-so400m-d32/transformers/diffusion_pytorch_model.safetensors b/pae-siglip2-so400m-d32/transformers/diffusion_pytorch_model.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..9f36529d68094421cd0bbf77765a1b9b582ec3d6 --- /dev/null +++ b/pae-siglip2-so400m-d32/transformers/diffusion_pytorch_model.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d981339a09cc0e4d8a11affff112c2bc06209213216e9185e1b8fde84c0904cc +size 2701230752 diff --git a/pae-siglip2-so400m-d32/transformers/transformer_lightning_dit.py b/pae-siglip2-so400m-d32/transformers/transformer_lightning_dit.py new file mode 100644 index 0000000000000000000000000000000000000000..80d061481bca0a538950bfd25b531e8bf1c05d61 --- /dev/null +++ b/pae-siglip2-so400m-d32/transformers/transformer_lightning_dit.py @@ -0,0 +1,794 @@ +from __future__ import annotations + +import torch +import torch.nn.functional as F +from torch import nn + + +class RMSNorm(torch.nn.Module): + def __init__(self, dim: int, eps: float = 1e-6): + super().__init__() + self.eps = eps + self.weight = nn.Parameter(torch.ones(dim)) + + def _norm(self, x: torch.Tensor) -> torch.Tensor: + return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + output = self._norm(x.float()).type_as(x) + return output * self.weight + +from math import pi + +import torch +from torch import nn + +from einops import rearrange, repeat + + + +def broadcat(tensors, dim = -1): + num_tensors = len(tensors) + shape_lens = set(list(map(lambda t: len(t.shape), tensors))) + assert len(shape_lens) == 1, 'tensors must all have the same number of dimensions' + shape_len = list(shape_lens)[0] + dim = (dim + shape_len) if dim < 0 else dim + dims = list(zip(*map(lambda t: list(t.shape), tensors))) + expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim] + assert all([*map(lambda t: len(set(t[1])) <= 2, expandable_dims)]), 'invalid dimensions for broadcastable concatentation' + max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims)) + expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims)) + expanded_dims.insert(dim, (dim, dims[dim])) + expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims))) + tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes))) + return torch.cat(tensors, dim = dim) + + + +def rotate_half(x): + x = rearrange(x, '... (d r) -> ... d r', r = 2) + x1, x2 = x.unbind(dim = -1) + x = torch.stack((-x2, x1), dim = -1) + return rearrange(x, '... d r -> ... (d r)') + + + +class VisionRotaryEmbedding(nn.Module): + def __init__( + self, + dim, + pt_seq_len, + ft_seq_len=None, + custom_freqs = None, + freqs_for = 'lang', + theta = 10000, + max_freq = 10, + num_freqs = 1, + ): + super().__init__() + if custom_freqs: + freqs = custom_freqs + elif freqs_for == 'lang': + freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim)) + elif freqs_for == 'pixel': + freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi + elif freqs_for == 'constant': + freqs = torch.ones(num_freqs).float() + else: + raise ValueError(f'unknown modality {freqs_for}') + + if ft_seq_len is None: ft_seq_len = pt_seq_len + t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len + + freqs_h = torch.einsum('..., f -> ... f', t, freqs) + freqs_h = repeat(freqs_h, '... n -> ... (n r)', r = 2) + + freqs_w = torch.einsum('..., f -> ... f', t, freqs) + freqs_w = repeat(freqs_w, '... n -> ... (n r)', r = 2) + + freqs = broadcat((freqs_h[:, None, :], freqs_w[None, :, :]), dim = -1) + + self.register_buffer("freqs_cos", freqs.cos()) + self.register_buffer("freqs_sin", freqs.sin()) + + # print('======== shape of rope freq', self.freqs_cos.shape, '========') + + def forward(self, t, start_index = 0): + rot_dim = self.freqs_cos.shape[-1] + end_index = start_index + rot_dim + assert rot_dim <= t.shape[-1], f'feature dimension {t.shape[-1]} is not of sufficient size to rotate in all the positions {rot_dim}' + t_left, t, t_right = t[..., :start_index], t[..., start_index:end_index], t[..., end_index:] + t = (t * self.freqs_cos) + (rotate_half(t) * self.freqs_sin) + return torch.cat((t_left, t, t_right), dim = -1) + + + +class VisionRotaryEmbeddingFast(nn.Module): + def __init__( + self, + dim, + pt_seq_len=16, + ft_seq_len=None, + custom_freqs = None, + freqs_for = 'lang', + theta = 10000, + max_freq = 10, + num_freqs = 1, + ): + super().__init__() + if custom_freqs: + freqs = custom_freqs + elif freqs_for == 'lang': + freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim)) + elif freqs_for == 'pixel': + freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi + elif freqs_for == 'constant': + freqs = torch.ones(num_freqs).float() + else: + raise ValueError(f'unknown modality {freqs_for}') + + if ft_seq_len is None: ft_seq_len = pt_seq_len + t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len + + freqs = torch.einsum('..., f -> ... f', t, freqs) + freqs = repeat(freqs, '... n -> ... (n r)', r = 2) + freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim = -1) + + freqs_cos = freqs.cos().view(-1, freqs.shape[-1]) + freqs_sin = freqs.sin().view(-1, freqs.shape[-1]) + + self.register_buffer("freqs_cos", freqs_cos) + self.register_buffer("freqs_sin", freqs_sin) + + # print('======== shape of rope freq', self.freqs_cos.shape, '========') + + def forward(self, t): return t * self.freqs_cos + rotate_half(t) * self.freqs_sin + +import os +import torch +from typing import Callable, Optional +import warnings + +from torch import Tensor, nn +import torch.nn.functional as F + + +class SwiGLUFFN(nn.Module): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = None, + drop: float = 0.0, + bias: bool = True, + ) -> None: + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias) + self.w3 = nn.Linear(hidden_features, out_features, bias=bias) + def forward(self, x: Tensor) -> Tensor: + x12 = self.w12(x) + x1, x2 = x12.chunk(2, dim=-1) + hidden = F.silu(x1) * x2 + return self.w3(hidden) + + +XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None +try: + if XFORMERS_ENABLED: + from xformers.ops import SwiGLU + + XFORMERS_AVAILABLE = True + # warnings.warn("xFormers is available (SwiGLU)") + else: + # warnings.warn("xFormers is disabled (SwiGLU)") + raise ImportError +except ImportError: + SwiGLU = SwiGLUFFN + XFORMERS_AVAILABLE = False + + # warnings.warn("xFormers is not available (SwiGLU)") + + +class SwiGLUFFNFused(SwiGLU): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = None, + drop: float = 0.0, + bias: bool = True, + ) -> None: + out_features = out_features or in_features + hidden_features = hidden_features or in_features + hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8 + super().__init__( + in_features=in_features, + hidden_features=hidden_features, + out_features=out_features, + bias=bias, + ) + +from dataclasses import dataclass +from typing import Optional, Tuple, Union + +import torch + +try: + from diffusers.configuration_utils import ConfigMixin, register_to_config + from diffusers.models.modeling_utils import ModelMixin + from diffusers.utils import BaseOutput +except Exception: # pragma: no cover + class BaseOutput(dict): + def __post_init__(self): + self.update(self.__dict__) + + class ConfigMixin: + config_name = "config.json" + + class ModelMixin(torch.nn.Module): + pass + + def register_to_config(init): + return init + + +@dataclass +class LightningDiT2DModelOutput(BaseOutput): + sample: torch.FloatTensor + + +import os +import math +import numpy as np + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.utils.checkpoint import checkpoint + +from timm.models.vision_transformer import PatchEmbed, Mlp +def modulate(x, shift, scale): + if shift is None: + return x * (1 + scale.unsqueeze(1)) + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) + +class Attention(nn.Module): + """ + Attention module of LightningDiT. + """ + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = False, + qk_norm: bool = False, + attn_drop: float = 0., + proj_drop: float = 0., + norm_layer: nn.Module = nn.LayerNorm, + fused_attn: bool = True, + use_rmsnorm: bool = False, + ) -> None: + super().__init__() + assert dim % num_heads == 0, 'dim should be divisible by num_heads' + + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.scale = self.head_dim ** -0.5 + self.fused_attn = fused_attn + + if use_rmsnorm: + norm_layer = RMSNorm + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + def forward(self, x: torch.Tensor, rope=None) -> torch.Tensor: + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) + q, k, v = qkv.unbind(0) + q, k = self.q_norm(q), self.k_norm(k) + + if rope is not None: + q = rope(q) + k = rope(k) + + if self.fused_attn: + x = F.scaled_dot_product_attention( + q, k, v, + dropout_p=self.attn_drop.p if self.training else 0., + ) + else: + q = q * self.scale + attn = q @ k.transpose(-2, -1) + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + x = attn @ v + + x = x.transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class TimestepEmbedder(nn.Module): + """ + Embeds scalar timesteps into vector representations. + Same as DiT. + """ + def __init__(self, hidden_size: int, frequency_embedding_size: int = 256) -> None: + super().__init__() + self.frequency_embedding_size = frequency_embedding_size + self.mlp = nn.Sequential( + nn.Linear(frequency_embedding_size, hidden_size, bias=True), + nn.SiLU(), + nn.Linear(hidden_size, hidden_size, bias=True), + ) + + @staticmethod + def timestep_embedding(t: torch.Tensor, dim: int, max_period: int = 10000) -> torch.Tensor: + """ + Create sinusoidal timestep embeddings. + Args: + t: A 1-D Tensor of N indices, one per batch element. These may be fractional. + dim: The dimension of the output. + max_period: Controls the minimum frequency of the embeddings. + Returns: + An (N, D) Tensor of positional embeddings. + """ + # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py + half = dim // 2 + freqs = torch.exp( + -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half + ).to(device=t.device) + + args = t[:, 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) + + return embedding + def forward(self, t: torch.Tensor) -> torch.Tensor: + t_freq = self.timestep_embedding(t, self.frequency_embedding_size) + t_emb = self.mlp(t_freq) + return t_emb + + +class LabelEmbedder(nn.Module): + """ + Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance. + Same as DiT. + """ + def __init__(self, num_classes, hidden_size, dropout_prob): + super().__init__() + use_cfg_embedding = dropout_prob > 0 + self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size) + self.num_classes = num_classes + self.dropout_prob = dropout_prob + + def token_drop(self, labels, force_drop_ids=None): + """ + Drops labels to enable classifier-free guidance. + """ + if force_drop_ids is None: + drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob + else: + drop_ids = force_drop_ids == 1 + labels = torch.where(drop_ids, self.num_classes, labels) + return labels + def forward(self, labels, train, force_drop_ids=None): + use_dropout = self.dropout_prob > 0 + if (train and use_dropout) or (force_drop_ids is not None): + labels = self.token_drop(labels, force_drop_ids) + embeddings = self.embedding_table(labels) + return embeddings + +class LightningDiTBlock(nn.Module): + """ + Lightning DiT Block. We add features including: + - ROPE + - QKNorm + - RMSNorm + - SwiGLU + - No shift AdaLN. + Not all of them are used in the final model, please refer to the paper for more details. + """ + def __init__( + self, + hidden_size, + num_heads, + mlp_ratio=4.0, + use_qknorm=False, + use_swiglu=False, + use_rmsnorm=False, + wo_shift=False, + **block_kwargs + ): + super().__init__() + + # Initialize normalization layers + if not use_rmsnorm: + self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + else: + self.norm1 = RMSNorm(hidden_size) + self.norm2 = RMSNorm(hidden_size) + + # Initialize attention layer + self.attn = Attention( + hidden_size, + num_heads=num_heads, + qkv_bias=True, + qk_norm=use_qknorm, + use_rmsnorm=use_rmsnorm, + **block_kwargs + ) + + # Initialize MLP layer + mlp_hidden_dim = int(hidden_size * mlp_ratio) + approx_gelu = lambda: nn.GELU(approximate="tanh") + if use_swiglu: + # here we did not use SwiGLU from xformers because it is not compatible with torch.compile for now. + self.mlp = SwiGLUFFN(hidden_size, int(2/3 * mlp_hidden_dim)) + else: + self.mlp = Mlp( + in_features=hidden_size, + hidden_features=mlp_hidden_dim, + act_layer=approx_gelu, + drop=0 + ) + + # Initialize AdaLN modulation + if wo_shift: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(hidden_size, 4 * hidden_size, bias=True) + ) + else: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(hidden_size, 6 * hidden_size, bias=True) + ) + self.wo_shift = wo_shift + def forward(self, x, c, feat_rope=None): + if self.wo_shift: + scale_msa, gate_msa, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(4, dim=1) + shift_msa = None + shift_mlp = None + else: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=1) + + x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa), rope=feat_rope) + x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp)) + return x + +class FinalLayer(nn.Module): + """ + The final layer of LightningDiT. + """ + def __init__(self, hidden_size, patch_size, out_channels, use_rmsnorm=False): + super().__init__() + if not use_rmsnorm: + self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + else: + self.norm_final = RMSNorm(hidden_size) + self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True) + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(hidden_size, 2 * hidden_size, bias=True) + ) + def forward(self, x, c): + shift, scale = self.adaLN_modulation(c).chunk(2, dim=1) + x = modulate(self.norm_final(x), shift, scale) + x = self.linear(x) + return x + + +class LightningDiT2DModel(ModelMixin, ConfigMixin): + """ + Diffusion model with a Transformer backbone. + """ + @register_to_config + def __init__( + self, + input_size: int = 32, + patch_size=2, + in_channels=32, + hidden_size=1152, + depth=28, + num_heads=16, + mlp_ratio=4.0, + class_dropout_prob=0.1, + num_classes=1000, + learn_sigma=False, + use_qknorm=False, + use_swiglu=False, + use_rope=False, + use_rmsnorm=False, + wo_shift=False, + use_checkpoint=False, + use_abs_pos=True, + ): + super().__init__() + self.use_abs_pos = use_abs_pos + self.learn_sigma = learn_sigma + self.in_channels = in_channels + self.out_channels = in_channels if not learn_sigma else in_channels * 2 + self.patch_size = patch_size + self.num_heads = num_heads + self.use_rope = use_rope + self.use_rmsnorm = use_rmsnorm + self.depth = depth + self.hidden_size = hidden_size + self.use_checkpoint = use_checkpoint + self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size, bias=True) + self.t_embedder = TimestepEmbedder(hidden_size) + self.y_embedder = LabelEmbedder(num_classes, hidden_size, class_dropout_prob) + num_patches = self.x_embedder.num_patches + # Will use fixed sin-cos embedding: + self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False) + + if not self.use_abs_pos and not self.use_rope: + import warnings + warnings.warn("Warning: Both Absolute Position Embedding and RoPE are disabled. " + "The model will be permutation-invariant (orderless)!") + + # use rotary position encoding, borrow from EVA + if self.use_rope: + half_head_dim = hidden_size // num_heads // 2 + hw_seq_len = input_size // patch_size + self.feat_rope = VisionRotaryEmbeddingFast( + dim=half_head_dim, + pt_seq_len=hw_seq_len, + ) + else: + self.feat_rope = None + + self.blocks = nn.ModuleList([ + LightningDiTBlock(hidden_size, + num_heads, + mlp_ratio=mlp_ratio, + use_qknorm=use_qknorm, + use_swiglu=use_swiglu, + use_rmsnorm=use_rmsnorm, + wo_shift=wo_shift, + ) for _ in range(depth) + ]) + self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels, use_rmsnorm=use_rmsnorm) + self.initialize_weights() + if hasattr(self, "register_to_config"): + self.register_to_config( + input_size=input_size, + patch_size=patch_size, + in_channels=in_channels, + hidden_size=hidden_size, + depth=depth, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + class_dropout_prob=class_dropout_prob, + num_classes=num_classes, + learn_sigma=learn_sigma, + use_qknorm=use_qknorm, + use_swiglu=use_swiglu, + use_rope=use_rope, + use_rmsnorm=use_rmsnorm, + wo_shift=wo_shift, + use_checkpoint=use_checkpoint, + use_abs_pos=use_abs_pos, + ) + + def initialize_weights(self): + # Initialize transformer layers: + def _basic_init(module): + if isinstance(module, nn.Linear): + torch.nn.init.xavier_uniform_(module.weight) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + self.apply(_basic_init) + + + if self.use_abs_pos: + pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5)) + self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0)) + else: + nn.init.constant_(self.pos_embed, 0) + + # Initialize patch_embed like nn.Linear (instead of nn.Conv2d): + w = self.x_embedder.proj.weight.data + nn.init.xavier_uniform_(w.view([w.shape[0], -1])) + nn.init.constant_(self.x_embedder.proj.bias, 0) + + # Initialize label embedding table: + nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02) + + # Initialize timestep embedding MLP: + nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02) + nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02) + + # Zero-out adaLN modulation layers in LightningDiT blocks: + for block in self.blocks: + nn.init.constant_(block.adaLN_modulation[-1].weight, 0) + nn.init.constant_(block.adaLN_modulation[-1].bias, 0) + + # Zero-out output layers: + nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0) + nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0) + nn.init.constant_(self.final_layer.linear.weight, 0) + nn.init.constant_(self.final_layer.linear.bias, 0) + + def unpatchify(self, x): + """ + x: (N, T, patch_size**2 * C) + imgs: (N, H, W, C) + """ + c = self.out_channels + p = self.x_embedder.patch_size[0] + h = w = int(x.shape[1] ** 0.5) + assert h * w == x.shape[1] + + x = x.reshape(shape=(x.shape[0], h, w, p, p, c)) + x = torch.einsum('nhwpqc->nchpwq', x) + imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p)) + return imgs + + def forward( + self, + hidden_states: torch.Tensor, + timestep: Optional[torch.LongTensor] = None, + class_labels: Optional[torch.LongTensor] = None, + return_dict: bool = True, + ): + x = hidden_states + t = timestep + y = class_labels + """ + Forward pass of LightningDiT. + x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images) + t: (N,) tensor of diffusion timesteps + y: (N,) tensor of class labels + use_checkpoint: boolean to toggle checkpointing + """ + + use_checkpoint = self.use_checkpoint + + x = self.x_embedder(x) + if self.use_abs_pos: + x = x + self.pos_embed + t = self.t_embedder(t) # (N, D) + y = self.y_embedder(y, self.training) # (N, D) + c = t + y # (N, D) + + for block in self.blocks: + if use_checkpoint: + x = checkpoint(block, x, c, self.feat_rope, use_reentrant=True) + else: + x = block(x, c, self.feat_rope) + + x = self.final_layer(x, c) # (N, T, patch_size ** 2 * out_channels) + x = self.unpatchify(x) # (N, out_channels, H, W) + + if self.learn_sigma: + x, _ = x.chunk(2, dim=1) + if not return_dict: + return (x,) + return LightningDiT2DModelOutput(sample=x) + + def forward_with_cfg(self, x, t, y, cfg_scale, cfg_interval=None, cfg_interval_start=None): + """ + Forward pass of LightningDiT, but also batches the unconditional forward pass for classifier-free guidance. + """ + # https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb + combined = torch.cat([x, x], dim=0) + model_out = self.forward(combined, t, y, return_dict=False)[0] + # For exact reproducibility reasons, we apply classifier-free guidance on only + # three channels by default. The standard approach to cfg applies it to all channels. + # This can be done by uncommenting the following line and commenting-out the line following that. + eps, rest = model_out[:, :self.in_channels], model_out[:, self.in_channels:] + # eps, rest = model_out[:, :3], model_out[:, 3:] + cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0) + half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps) + + if cfg_interval is True: + timestep = t[0] + if timestep < cfg_interval_start: + half_eps = cond_eps + + eps = torch.cat([half_eps, half_eps], dim=0) + return torch.cat([eps, rest], dim=1) + +def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0): + """ + grid_size: int of the grid height and width + return: + pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token) + """ + grid_h = np.arange(grid_size, dtype=np.float32) + grid_w = np.arange(grid_size, dtype=np.float32) + grid = np.meshgrid(grid_w, grid_h) # here w goes first + grid = np.stack(grid, axis=0) + + grid = grid.reshape([2, 1, grid_size, grid_size]) + pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) + if cls_token and extra_tokens > 0: + pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0) + return pos_embed + + +def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): + assert embed_dim % 2 == 0 + + # use half of dimensions to encode grid_h + emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) + emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2) + + emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D) + return emb + + +def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): + """ + embed_dim: output dimension for each position + pos: a list of positions to be encoded: size (M,) + out: (M, D) + """ + assert embed_dim % 2 == 0 + omega = np.arange(embed_dim // 2, dtype=np.float64) + omega /= embed_dim / 2. + omega = 1. / 10000**omega # (D/2,) + + pos = pos.reshape(-1) # (M,) + out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product + + emb_sin = np.sin(out) # (M, D/2) + emb_cos = np.cos(out) # (M, D/2) + + emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) + return emb + + +################################################################################# +# LightningDiT Configs # +################################################################################# + +def _lightning_dit_XL_1(**kwargs): + return LightningDiT2DModel(depth=28, hidden_size=1152, patch_size=1, num_heads=16, **kwargs) + +def _lightning_dit_XL_2(**kwargs): + return LightningDiT2DModel(depth=28, hidden_size=1152, patch_size=2, num_heads=16, **kwargs) + +def _lightning_dit_L_2(**kwargs): + return LightningDiT2DModel(depth=24, hidden_size=1024, patch_size=2, num_heads=16, **kwargs) + +def _lightning_dit_B_1(**kwargs): + return LightningDiT2DModel(depth=12, hidden_size=768, patch_size=1, num_heads=12, **kwargs) + +def _lightning_dit_B_2(**kwargs): + return LightningDiT2DModel(depth=12, hidden_size=768, patch_size=2, num_heads=12, **kwargs) + +def _lightning_dit_1p0B_1(**kwargs): + return LightningDiT2DModel(depth=24, hidden_size=1536, patch_size=1, num_heads=24, **kwargs) + +def _lightning_dit_1p0B_2(**kwargs): + return LightningDiT2DModel(depth=24, hidden_size=1536, patch_size=2, num_heads=24, **kwargs) + +def _lightning_dit_1p6B_1(**kwargs): + return LightningDiT2DModel(depth=28, hidden_size=1792, patch_size=1, num_heads=28, **kwargs) + +def _lightning_dit_1p6B_2(**kwargs): + return LightningDiT2DModel(depth=28, hidden_size=1792, patch_size=2, num_heads=28, **kwargs) + +LIGHTNING_DIT_PRESETS = { + 'LightningDiT-B/1': _lightning_dit_B_1, 'LightningDiT-B/2': _lightning_dit_B_2, + 'LightningDiT-L/2': _lightning_dit_L_2, + 'LightningDiT-XL/1': _lightning_dit_XL_1, 'LightningDiT-XL/2': _lightning_dit_XL_2, + 'LightningDiT-1p0B/1': _lightning_dit_1p0B_1, 'LightningDiT-1p0B/2': _lightning_dit_1p0B_2, + 'LightningDiT-1p6B/1': _lightning_dit_1p6B_1, 'LightningDiT-1p6B/2': _lightning_dit_1p6B_2, +}