Feature Extraction
Diffusers
Safetensors
English
autoencoder
vision-foundation-model
dinov2
dinov3
mae
siglip2
pae
Instructions to use BiliSakura/PAE-diffusers with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use BiliSakura/PAE-diffusers with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("BiliSakura/PAE-diffusers", dtype=torch.bfloat16, device_map="cuda") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
Upload PAE diffusers checkpoints with model card metadata
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +3 -0
- README.md +60 -0
- pae-dinov2-large-d32/__pycache__/pipeline.cpython-311.pyc +0 -0
- pae-dinov2-large-d32/decoder/__pycache__/decoder_pae.cpython-311.pyc +0 -0
- pae-dinov2-large-d32/decoder/config.json +79 -0
- pae-dinov2-large-d32/decoder/decoder_pae.py +1105 -0
- pae-dinov2-large-d32/decoder/diffusion_pytorch_model.safetensors +3 -0
- pae-dinov2-large-d32/demo.png +3 -0
- pae-dinov2-large-d32/model_index.json +1021 -0
- pae-dinov2-large-d32/pipeline.py +530 -0
- pae-dinov2-large-d32/scheduler/scheduler_config.json +7 -0
- pae-dinov2-large-d32/scheduler/scheduling_flow_match_pae.py +200 -0
- pae-dinov2-large-d32/transformers/__pycache__/transformer_lightning_dit.cpython-311.pyc +0 -0
- pae-dinov2-large-d32/transformers/config.json +15 -0
- pae-dinov2-large-d32/transformers/diffusion_pytorch_model.safetensors +3 -0
- pae-dinov2-large-d32/transformers/transformer_lightning_dit.py +794 -0
- pae-dinov3-large-d32/decoder/config.json +79 -0
- pae-dinov3-large-d32/decoder/decoder_pae.py +1105 -0
- pae-dinov3-large-d32/decoder/diffusion_pytorch_model.safetensors +3 -0
- pae-dinov3-large-d32/demo.png +0 -0
- pae-dinov3-large-d32/model_index.json +1021 -0
- pae-dinov3-large-d32/pipeline.py +530 -0
- pae-dinov3-large-d32/scheduler/scheduler_config.json +7 -0
- pae-dinov3-large-d32/scheduler/scheduling_flow_match_pae.py +200 -0
- pae-dinov3-large-d32/transformers/config.json +15 -0
- pae-dinov3-large-d32/transformers/diffusion_pytorch_model.safetensors +3 -0
- pae-dinov3-large-d32/transformers/transformer_lightning_dit.py +794 -0
- pae-mae-large-d32/decoder/config.json +79 -0
- pae-mae-large-d32/decoder/decoder_pae.py +1105 -0
- pae-mae-large-d32/decoder/diffusion_pytorch_model.safetensors +3 -0
- pae-mae-large-d32/demo.png +3 -0
- pae-mae-large-d32/model_index.json +1021 -0
- pae-mae-large-d32/pipeline.py +530 -0
- pae-mae-large-d32/scheduler/scheduler_config.json +7 -0
- pae-mae-large-d32/scheduler/scheduling_flow_match_pae.py +200 -0
- pae-mae-large-d32/transformers/config.json +15 -0
- pae-mae-large-d32/transformers/diffusion_pytorch_model.safetensors +3 -0
- pae-mae-large-d32/transformers/transformer_lightning_dit.py +794 -0
- pae-siglip2-so400m-d32/__pycache__/pipeline.cpython-311.pyc +0 -0
- pae-siglip2-so400m-d32/decoder/__pycache__/decoder_pae.cpython-311.pyc +0 -0
- pae-siglip2-so400m-d32/decoder/config.json +89 -0
- pae-siglip2-so400m-d32/decoder/decoder_pae.py +1105 -0
- pae-siglip2-so400m-d32/decoder/diffusion_pytorch_model.safetensors +3 -0
- pae-siglip2-so400m-d32/demo.png +3 -0
- pae-siglip2-so400m-d32/model_index.json +1021 -0
- pae-siglip2-so400m-d32/pipeline.py +530 -0
- pae-siglip2-so400m-d32/scheduler/__pycache__/scheduling_flow_match_pae.cpython-311.pyc +0 -0
- pae-siglip2-so400m-d32/scheduler/scheduler_config.json +7 -0
- pae-siglip2-so400m-d32/scheduler/scheduling_flow_match_pae.py +200 -0
- pae-siglip2-so400m-d32/transformers/__pycache__/transformer_lightning_dit.cpython-311.pyc +0 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
pae-dinov2-large-d32/demo.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
pae-mae-large-d32/demo.png filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
pae-siglip2-so400m-d32/demo.png filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
tags:
|
| 6 |
+
- diffusers
|
| 7 |
+
- autoencoder
|
| 8 |
+
- vision-foundation-model
|
| 9 |
+
- dinov2
|
| 10 |
+
- dinov3
|
| 11 |
+
- mae
|
| 12 |
+
- siglip2
|
| 13 |
+
- feature-extraction
|
| 14 |
+
- pae
|
| 15 |
+
library_name: diffusers
|
| 16 |
+
pipeline_tag: feature-extraction
|
| 17 |
+
---
|
| 18 |
+
|
| 19 |
+
# PAE Diffusers Checkpoints
|
| 20 |
+
|
| 21 |
+
Converted PAE (Prior-Aligned Autoencoder) tokenizer checkpoints in standard Hub custom-pipeline layout.
|
| 22 |
+
|
| 23 |
+
PAE is a **VAE-free** latent framework. Each variant splits into dedicated components:
|
| 24 |
+
|
| 25 |
+
| Variant | VFM backbone (decoder config) | Latent dim | Input size |
|
| 26 |
+
|---------|------------------|------------|------------|
|
| 27 |
+
| `pae-dinov2-large-d32` | DINOv2-L (with registers) | 32 | 224 |
|
| 28 |
+
| `pae-dinov3-large-d32` | DINOv3-ViT-L/16 | 32 | 256 |
|
| 29 |
+
| `pae-mae-large-d32` | MAE-L | 32 | 256 |
|
| 30 |
+
| `pae-siglip2-so400m-d32` | SigLIP2-SO400M | 32 | 256 |
|
| 31 |
+
|
| 32 |
+
Each variant directory is a self-contained Diffusers repo. Each component subfolder ships **one Python file**:
|
| 33 |
+
|
| 34 |
+
```text
|
| 35 |
+
model_index.json
|
| 36 |
+
pipeline.py
|
| 37 |
+
scheduler/scheduling_flow_match_pae.py
|
| 38 |
+
transformers/transformer_lightning_dit.py
|
| 39 |
+
decoder/decoder_pae.py
|
| 40 |
+
decoder/diffusion_pytorch_model.safetensors
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
## Usage
|
| 44 |
+
|
| 45 |
+
```python
|
| 46 |
+
from pathlib import Path
|
| 47 |
+
import torch
|
| 48 |
+
from diffusers import DiffusionPipeline
|
| 49 |
+
|
| 50 |
+
model_dir = Path("/home/czy/local/models/BiliSakura/PAE-diffusers/pae-dinov2-large-d32").resolve()
|
| 51 |
+
pipe = DiffusionPipeline.from_pretrained(
|
| 52 |
+
str(model_dir),
|
| 53 |
+
local_files_only=True,
|
| 54 |
+
custom_pipeline=str(model_dir / "pipeline.py"),
|
| 55 |
+
trust_remote_code=True,
|
| 56 |
+
torch_dtype=torch.bfloat16,
|
| 57 |
+
).to("cuda")
|
| 58 |
+
|
| 59 |
+
print(pipe.get_label_ids("golden retriever"))
|
| 60 |
+
```
|
pae-dinov2-large-d32/__pycache__/pipeline.cpython-311.pyc
ADDED
|
Binary file (22.4 kB). View file
|
|
|
pae-dinov2-large-d32/decoder/__pycache__/decoder_pae.cpython-311.pyc
ADDED
|
Binary file (56.6 kB). View file
|
|
|
pae-dinov2-large-d32/decoder/config.json
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "PAEDecoder",
|
| 3 |
+
"decoder_patch_size": 16,
|
| 4 |
+
"encoder_config_path": "facebook/dinov2-with-registers-large",
|
| 5 |
+
"encoder_hidden_size": 1024,
|
| 6 |
+
"encoder_input_size": 224,
|
| 7 |
+
"encoder_num_heads": 16,
|
| 8 |
+
"encoder_patch_size": 14,
|
| 9 |
+
"latent_dim": 32,
|
| 10 |
+
"latent_mean": [
|
| 11 |
+
-0.9140625,
|
| 12 |
+
0.3515625,
|
| 13 |
+
3.328125,
|
| 14 |
+
0.006500244140625,
|
| 15 |
+
0.298828125,
|
| 16 |
+
-1.3671875,
|
| 17 |
+
-0.0537109375,
|
| 18 |
+
-0.040771484375,
|
| 19 |
+
1.2109375,
|
| 20 |
+
0.0233154296875,
|
| 21 |
+
-0.07275390625,
|
| 22 |
+
-0.26953125,
|
| 23 |
+
-0.08251953125,
|
| 24 |
+
-0.037109375,
|
| 25 |
+
-1.078125,
|
| 26 |
+
2.125,
|
| 27 |
+
0.0439453125,
|
| 28 |
+
-0.02880859375,
|
| 29 |
+
-0.103515625,
|
| 30 |
+
0.1171875,
|
| 31 |
+
0.890625,
|
| 32 |
+
-0.52734375,
|
| 33 |
+
0.09521484375,
|
| 34 |
+
-0.0206298828125,
|
| 35 |
+
-0.10302734375,
|
| 36 |
+
0.51171875,
|
| 37 |
+
-0.12109375,
|
| 38 |
+
0.054931640625,
|
| 39 |
+
0.376953125,
|
| 40 |
+
0.0252685546875,
|
| 41 |
+
-0.0177001953125,
|
| 42 |
+
2.109375
|
| 43 |
+
],
|
| 44 |
+
"latent_multiplier": 1.0,
|
| 45 |
+
"latent_std": [
|
| 46 |
+
0.412109375,
|
| 47 |
+
0.373046875,
|
| 48 |
+
0.322265625,
|
| 49 |
+
0.359375,
|
| 50 |
+
0.462890625,
|
| 51 |
+
0.390625,
|
| 52 |
+
0.365234375,
|
| 53 |
+
0.40625,
|
| 54 |
+
0.40625,
|
| 55 |
+
0.4140625,
|
| 56 |
+
0.36328125,
|
| 57 |
+
0.375,
|
| 58 |
+
0.458984375,
|
| 59 |
+
0.36328125,
|
| 60 |
+
0.373046875,
|
| 61 |
+
0.40234375,
|
| 62 |
+
0.361328125,
|
| 63 |
+
0.34375,
|
| 64 |
+
0.421875,
|
| 65 |
+
0.35546875,
|
| 66 |
+
0.357421875,
|
| 67 |
+
0.40234375,
|
| 68 |
+
0.38671875,
|
| 69 |
+
0.365234375,
|
| 70 |
+
0.419921875,
|
| 71 |
+
0.3828125,
|
| 72 |
+
0.373046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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 4 |
+
from transformers.utils import (
|
| 5 |
+
ModelOutput,
|
| 6 |
+
)
|
| 7 |
+
from transformers.activations import ACT2FN
|
| 8 |
+
class ViTMAEConfig(PretrainedConfig):
|
| 9 |
+
r"""
|
| 10 |
+
This is the configuration class to store the configuration of a [`ViTMAEModel`]. It is used to instantiate an ViT
|
| 11 |
+
MAE model according to the specified arguments, defining the model architecture. Instantiating a configuration with
|
| 12 |
+
the defaults will yield a similar configuration to that of the ViT
|
| 13 |
+
[facebook/vit-mae-base](https://huggingface.co/facebook/vit-mae-base) architecture.
|
| 14 |
+
|
| 15 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 16 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 21 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 22 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 23 |
+
Number of hidden layers in the Transformer encoder.
|
| 24 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 25 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 26 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 27 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 28 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 29 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 30 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 31 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 32 |
+
The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.
|
| 33 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 34 |
+
The dropout ratio for the attention probabilities.
|
| 35 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 36 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 37 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 38 |
+
The epsilon used by the layer normalization layers.
|
| 39 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 40 |
+
The size (resolution) of each image.
|
| 41 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 42 |
+
The size (resolution) of each patch.
|
| 43 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 44 |
+
The number of input channels.
|
| 45 |
+
qkv_bias (`bool`, *optional*, defaults to `True`):
|
| 46 |
+
Whether to add a bias to the queries, keys and values.
|
| 47 |
+
decoder_num_attention_heads (`int`, *optional*, defaults to 16):
|
| 48 |
+
Number of attention heads for each attention layer in the decoder.
|
| 49 |
+
decoder_hidden_size (`int`, *optional*, defaults to 512):
|
| 50 |
+
Dimensionality of the decoder.
|
| 51 |
+
decoder_num_hidden_layers (`int`, *optional*, defaults to 8):
|
| 52 |
+
Number of hidden layers in the decoder.
|
| 53 |
+
decoder_intermediate_size (`int`, *optional*, defaults to 2048):
|
| 54 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the decoder.
|
| 55 |
+
mask_ratio (`float`, *optional*, defaults to 0.75):
|
| 56 |
+
The ratio of the number of masked tokens in the input sequence.
|
| 57 |
+
norm_pix_loss (`bool`, *optional*, defaults to `False`):
|
| 58 |
+
Whether or not to train with normalized pixels (see Table 3 in the paper). Using normalized pixels improved
|
| 59 |
+
representation quality in the experiments of the authors.
|
| 60 |
+
|
| 61 |
+
Example:
|
| 62 |
+
|
| 63 |
+
```python
|
| 64 |
+
>>> from transformers import ViTMAEConfig, ViTMAEModel
|
| 65 |
+
|
| 66 |
+
>>> # Initializing a ViT MAE vit-mae-base style configuration
|
| 67 |
+
>>> configuration = ViTMAEConfig()
|
| 68 |
+
|
| 69 |
+
>>> # Initializing a model (with random weights) from the vit-mae-base style configuration
|
| 70 |
+
>>> model = ViTMAEModel(configuration)
|
| 71 |
+
|
| 72 |
+
>>> # Accessing the model configuration
|
| 73 |
+
>>> configuration = model.config
|
| 74 |
+
```"""
|
| 75 |
+
|
| 76 |
+
model_type = "vit_mae"
|
| 77 |
+
|
| 78 |
+
def __init__(
|
| 79 |
+
self,
|
| 80 |
+
hidden_size=768,
|
| 81 |
+
num_hidden_layers=12,
|
| 82 |
+
num_attention_heads=12,
|
| 83 |
+
intermediate_size=3072,
|
| 84 |
+
hidden_act="gelu",
|
| 85 |
+
hidden_dropout_prob=0.0,
|
| 86 |
+
attention_probs_dropout_prob=0.0,
|
| 87 |
+
initializer_range=0.02,
|
| 88 |
+
layer_norm_eps=1e-12,
|
| 89 |
+
image_size=224,
|
| 90 |
+
patch_size=16,
|
| 91 |
+
num_channels=3,
|
| 92 |
+
qkv_bias=True,
|
| 93 |
+
decoder_num_attention_heads=16,
|
| 94 |
+
decoder_hidden_size=512,
|
| 95 |
+
decoder_num_hidden_layers=8,
|
| 96 |
+
decoder_intermediate_size=2048,
|
| 97 |
+
mask_ratio=0.75,
|
| 98 |
+
norm_pix_loss=False,
|
| 99 |
+
**kwargs,
|
| 100 |
+
):
|
| 101 |
+
super().__init__(**kwargs)
|
| 102 |
+
|
| 103 |
+
self.hidden_size = hidden_size
|
| 104 |
+
self.num_hidden_layers = num_hidden_layers
|
| 105 |
+
self.num_attention_heads = num_attention_heads
|
| 106 |
+
self.intermediate_size = intermediate_size
|
| 107 |
+
self.hidden_act = hidden_act
|
| 108 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 109 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 110 |
+
self.initializer_range = initializer_range
|
| 111 |
+
self.layer_norm_eps = layer_norm_eps
|
| 112 |
+
self.image_size = image_size
|
| 113 |
+
self.patch_size = patch_size
|
| 114 |
+
self.num_channels = num_channels
|
| 115 |
+
self.qkv_bias = qkv_bias
|
| 116 |
+
self.decoder_num_attention_heads = decoder_num_attention_heads
|
| 117 |
+
self.decoder_hidden_size = decoder_hidden_size
|
| 118 |
+
self.decoder_num_hidden_layers = decoder_num_hidden_layers
|
| 119 |
+
self.decoder_intermediate_size = decoder_intermediate_size
|
| 120 |
+
self.mask_ratio = mask_ratio
|
| 121 |
+
self.norm_pix_loss = norm_pix_loss
|
| 122 |
+
|
| 123 |
+
# coding=utf-8
|
| 124 |
+
# Copyright 2022 Facebook AI and The HuggingFace Inc. team. All rights reserved.
|
| 125 |
+
#
|
| 126 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 127 |
+
# you may not use this file except in compliance with the License.
|
| 128 |
+
# You may obtain a copy of the License at
|
| 129 |
+
#
|
| 130 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 131 |
+
#
|
| 132 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 133 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 134 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 135 |
+
# See the License for the specific language governing permissions and
|
| 136 |
+
# limitations under the License.
|
| 137 |
+
"""PyTorch ViT MAE (masked autoencoder) model."""
|
| 138 |
+
|
| 139 |
+
import collections.abc
|
| 140 |
+
import math
|
| 141 |
+
from copy import deepcopy
|
| 142 |
+
from dataclasses import dataclass
|
| 143 |
+
from typing import Optional, Set, Tuple, Union
|
| 144 |
+
|
| 145 |
+
import numpy as np
|
| 146 |
+
import torch
|
| 147 |
+
from torch import nn
|
| 148 |
+
# correct the above import to the following
|
| 149 |
+
from transformers.modeling_outputs import BaseModelOutput
|
| 150 |
+
|
| 151 |
+
try:
|
| 152 |
+
from flash_attn import flash_attn_func
|
| 153 |
+
HAS_FLASH_ATTN = True # if set to False, FlashAttention is unavailable
|
| 154 |
+
except:
|
| 155 |
+
print('FlashAttention is not installed.')
|
| 156 |
+
HAS_FLASH_ATTN = False
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@dataclass
|
| 160 |
+
class ViTMAEModelOutput(ModelOutput):
|
| 161 |
+
"""
|
| 162 |
+
Class for ViTMAEModel's outputs, with potential hidden states and attentions.
|
| 163 |
+
|
| 164 |
+
Args:
|
| 165 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 166 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 167 |
+
mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
|
| 168 |
+
Tensor indicating which patches are masked (1) and which are not (0).
|
| 169 |
+
ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 170 |
+
Tensor containing the original index of the (shuffled) masked patches.
|
| 171 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 172 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 173 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 174 |
+
plus the initial embedding outputs.
|
| 175 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 176 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 177 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 178 |
+
the self-attention heads.
|
| 179 |
+
"""
|
| 180 |
+
|
| 181 |
+
last_hidden_state: torch.FloatTensor = None
|
| 182 |
+
mask: torch.LongTensor = None
|
| 183 |
+
ids_restore: torch.LongTensor = None
|
| 184 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 185 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
@dataclass
|
| 189 |
+
class ViTMAEDecoderOutput(ModelOutput):
|
| 190 |
+
"""
|
| 191 |
+
Class for ViTMAEDecoder's outputs, with potential hidden states and attentions.
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`):
|
| 195 |
+
Pixel reconstruction logits.
|
| 196 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 197 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 198 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 199 |
+
plus the initial embedding outputs.
|
| 200 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 201 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 202 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 203 |
+
the self-attention heads.
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
logits: torch.FloatTensor = None
|
| 207 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 208 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
@dataclass
|
| 212 |
+
class ViTMAEForPreTrainingOutput(ModelOutput):
|
| 213 |
+
"""
|
| 214 |
+
Class for ViTMAEForPreTraining's outputs, with potential hidden states and attentions.
|
| 215 |
+
|
| 216 |
+
Args:
|
| 217 |
+
loss (`torch.FloatTensor` of shape `(1,)`):
|
| 218 |
+
Pixel reconstruction loss.
|
| 219 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`):
|
| 220 |
+
Pixel reconstruction logits.
|
| 221 |
+
mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
|
| 222 |
+
Tensor indicating which patches are masked (1) and which are not (0).
|
| 223 |
+
ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 224 |
+
Tensor containing the original index of the (shuffled) masked patches.
|
| 225 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 226 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 227 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 228 |
+
plus the initial embedding outputs.
|
| 229 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 230 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 231 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 232 |
+
the self-attention heads.
|
| 233 |
+
"""
|
| 234 |
+
|
| 235 |
+
loss: Optional[torch.FloatTensor] = None
|
| 236 |
+
logits: torch.FloatTensor = None
|
| 237 |
+
mask: torch.LongTensor = None
|
| 238 |
+
ids_restore: torch.LongTensor = None
|
| 239 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 240 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def get_2d_sincos_pos_embed(embed_dim, grid_size, add_cls_token=False):
|
| 244 |
+
"""
|
| 245 |
+
Create 2D sin/cos positional embeddings.
|
| 246 |
+
|
| 247 |
+
Args:
|
| 248 |
+
embed_dim (`int`):
|
| 249 |
+
Embedding dimension.
|
| 250 |
+
grid_size (`int`):
|
| 251 |
+
The grid height and width.
|
| 252 |
+
add_cls_token (`bool`, *optional*, defaults to `False`):
|
| 253 |
+
Whether or not to add a classification (CLS) token.
|
| 254 |
+
|
| 255 |
+
Returns:
|
| 256 |
+
(`torch.FloatTensor` of shape (grid_size*grid_size, embed_dim) or (1+grid_size*grid_size, embed_dim): the
|
| 257 |
+
position embeddings (with or without classification token)
|
| 258 |
+
"""
|
| 259 |
+
grid_h = np.arange(grid_size, dtype=np.float32)
|
| 260 |
+
grid_w = np.arange(grid_size, dtype=np.float32)
|
| 261 |
+
grid = np.meshgrid(grid_w, grid_h) # here w goes first
|
| 262 |
+
grid = np.stack(grid, axis=0)
|
| 263 |
+
|
| 264 |
+
grid = grid.reshape([2, 1, grid_size, grid_size])
|
| 265 |
+
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
| 266 |
+
if add_cls_token:
|
| 267 |
+
pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
|
| 268 |
+
return pos_embed
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
|
| 272 |
+
if embed_dim % 2 != 0:
|
| 273 |
+
raise ValueError("embed_dim must be even")
|
| 274 |
+
|
| 275 |
+
# use half of dimensions to encode grid_h
|
| 276 |
+
emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
|
| 277 |
+
emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
|
| 278 |
+
|
| 279 |
+
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
|
| 280 |
+
return emb
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
|
| 284 |
+
"""
|
| 285 |
+
embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D)
|
| 286 |
+
"""
|
| 287 |
+
if embed_dim % 2 != 0:
|
| 288 |
+
raise ValueError("embed_dim must be even")
|
| 289 |
+
|
| 290 |
+
omega = np.arange(embed_dim // 2, dtype=float)
|
| 291 |
+
omega /= embed_dim / 2.0
|
| 292 |
+
omega = 1.0 / 10000**omega # (D/2,)
|
| 293 |
+
|
| 294 |
+
pos = pos.reshape(-1) # (M,)
|
| 295 |
+
out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
|
| 296 |
+
|
| 297 |
+
emb_sin = np.sin(out) # (M, D/2)
|
| 298 |
+
emb_cos = np.cos(out) # (M, D/2)
|
| 299 |
+
|
| 300 |
+
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
|
| 301 |
+
return emb
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
class ViTMAEEmbeddings(nn.Module):
|
| 305 |
+
"""
|
| 306 |
+
Construct the CLS token, position and patch embeddings.
|
| 307 |
+
|
| 308 |
+
"""
|
| 309 |
+
|
| 310 |
+
def __init__(self, config):
|
| 311 |
+
super().__init__()
|
| 312 |
+
|
| 313 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 314 |
+
self.patch_embeddings = ViTMAEPatchEmbeddings(config)
|
| 315 |
+
self.num_patches = self.patch_embeddings.num_patches
|
| 316 |
+
# fixed sin-cos embedding
|
| 317 |
+
self.position_embeddings = nn.Parameter(
|
| 318 |
+
torch.zeros(1, self.num_patches + 1, config.hidden_size), requires_grad=False
|
| 319 |
+
)
|
| 320 |
+
self.config = config
|
| 321 |
+
self.initialize_weights()
|
| 322 |
+
|
| 323 |
+
def initialize_weights(self):
|
| 324 |
+
# initialize (and freeze) position embeddings by sin-cos embedding
|
| 325 |
+
pos_embed = get_2d_sincos_pos_embed(
|
| 326 |
+
self.position_embeddings.shape[-1], int(self.patch_embeddings.num_patches**0.5), add_cls_token=True
|
| 327 |
+
)
|
| 328 |
+
self.position_embeddings.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
|
| 329 |
+
|
| 330 |
+
# initialize patch_embeddings like nn.Linear (instead of nn.Conv2d)
|
| 331 |
+
w = self.patch_embeddings.projection.weight.data
|
| 332 |
+
torch.nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
|
| 333 |
+
|
| 334 |
+
# timm's trunc_normal_(std=.02) is effectively normal_(std=0.02) as cutoff is too big (2.)
|
| 335 |
+
torch.nn.init.normal_(self.cls_token, std=self.config.initializer_range)
|
| 336 |
+
|
| 337 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
| 338 |
+
"""
|
| 339 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher
|
| 340 |
+
resolution images.
|
| 341 |
+
|
| 342 |
+
Source:
|
| 343 |
+
https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174
|
| 344 |
+
"""
|
| 345 |
+
num_patches = embeddings.shape[1] - 1
|
| 346 |
+
num_positions = self.position_embeddings.shape[1] - 1
|
| 347 |
+
|
| 348 |
+
if num_patches == num_positions and height == width:
|
| 349 |
+
return self.position_embeddings
|
| 350 |
+
|
| 351 |
+
class_pos_embed = self.position_embeddings[:, 0, :]
|
| 352 |
+
patch_pos_embed = self.position_embeddings[:, 1:, :]
|
| 353 |
+
dim = embeddings.shape[-1]
|
| 354 |
+
h0 = height // self.config.patch_size
|
| 355 |
+
w0 = width // self.config.patch_size
|
| 356 |
+
# we add a small number to avoid floating point error in the interpolation
|
| 357 |
+
# see discussion at https://github.com/facebookresearch/dino/issues/8
|
| 358 |
+
h0, w0 = h0 + 0.1, w0 + 0.1
|
| 359 |
+
patch_pos_embed = patch_pos_embed.reshape(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim)
|
| 360 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 361 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 362 |
+
patch_pos_embed,
|
| 363 |
+
scale_factor=(h0 / math.sqrt(num_positions), w0 / math.sqrt(num_positions)),
|
| 364 |
+
mode="bicubic",
|
| 365 |
+
align_corners=False,
|
| 366 |
+
)
|
| 367 |
+
if int(h0) != patch_pos_embed.shape[-2] or int(w0) != patch_pos_embed.shape[-1]:
|
| 368 |
+
raise ValueError("Width or height does not match with the interpolated position embeddings")
|
| 369 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 370 |
+
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
|
| 371 |
+
|
| 372 |
+
def random_masking(self, sequence, noise=None):
|
| 373 |
+
"""
|
| 374 |
+
Perform per-sample random masking by per-sample shuffling. Per-sample shuffling is done by argsort random
|
| 375 |
+
noise.
|
| 376 |
+
|
| 377 |
+
Args:
|
| 378 |
+
sequence (`torch.LongTensor` of shape `(batch_size, sequence_length, dim)`)
|
| 379 |
+
noise (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*) which is
|
| 380 |
+
mainly used for testing purposes to control randomness and maintain the reproducibility
|
| 381 |
+
"""
|
| 382 |
+
batch_size, seq_length, dim = sequence.shape
|
| 383 |
+
len_keep = int(seq_length * (1 - self.config.mask_ratio))
|
| 384 |
+
|
| 385 |
+
if noise is None:
|
| 386 |
+
noise = torch.rand(batch_size, seq_length, device=sequence.device) # noise in [0, 1]
|
| 387 |
+
|
| 388 |
+
# sort noise for each sample
|
| 389 |
+
ids_shuffle = torch.argsort(noise, dim=1).to(sequence.device) # ascend: small is keep, large is remove
|
| 390 |
+
ids_restore = torch.argsort(ids_shuffle, dim=1).to(sequence.device)
|
| 391 |
+
|
| 392 |
+
# keep the first subset
|
| 393 |
+
ids_keep = ids_shuffle[:, :len_keep]
|
| 394 |
+
sequence_unmasked = torch.gather(sequence, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, dim))
|
| 395 |
+
|
| 396 |
+
# generate the binary mask: 0 is keep, 1 is remove
|
| 397 |
+
mask = torch.ones([batch_size, seq_length], device=sequence.device)
|
| 398 |
+
mask[:, :len_keep] = 0
|
| 399 |
+
# unshuffle to get the binary mask
|
| 400 |
+
mask = torch.gather(mask, dim=1, index=ids_restore)
|
| 401 |
+
|
| 402 |
+
return sequence_unmasked, mask, ids_restore
|
| 403 |
+
|
| 404 |
+
def forward(self, pixel_values, noise=None, interpolate_pos_encoding: bool = False):
|
| 405 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 406 |
+
embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
|
| 407 |
+
if interpolate_pos_encoding:
|
| 408 |
+
position_embeddings = self.interpolate_pos_encoding(embeddings, height, width)
|
| 409 |
+
else:
|
| 410 |
+
position_embeddings = self.position_embeddings
|
| 411 |
+
|
| 412 |
+
# add position embeddings w/o cls token
|
| 413 |
+
embeddings = embeddings + position_embeddings[:, 1:, :]
|
| 414 |
+
|
| 415 |
+
# masking: length -> length * config.mask_ratio
|
| 416 |
+
embeddings, mask, ids_restore = self.random_masking(embeddings, noise)
|
| 417 |
+
|
| 418 |
+
# append cls token
|
| 419 |
+
cls_token = self.cls_token + position_embeddings[:, :1, :]
|
| 420 |
+
cls_tokens = cls_token.expand(embeddings.shape[0], -1, -1)
|
| 421 |
+
embeddings = torch.cat((cls_tokens, embeddings), dim=1)
|
| 422 |
+
|
| 423 |
+
return embeddings, mask, ids_restore
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
class ViTMAEPatchEmbeddings(nn.Module):
|
| 427 |
+
"""
|
| 428 |
+
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
|
| 429 |
+
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
|
| 430 |
+
Transformer.
|
| 431 |
+
"""
|
| 432 |
+
|
| 433 |
+
def __init__(self, config):
|
| 434 |
+
super().__init__()
|
| 435 |
+
image_size, patch_size = config.image_size, config.patch_size
|
| 436 |
+
num_channels, hidden_size = config.num_channels, config.hidden_size
|
| 437 |
+
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
|
| 438 |
+
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 439 |
+
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
| 440 |
+
self.image_size = image_size
|
| 441 |
+
self.patch_size = patch_size
|
| 442 |
+
self.num_channels = num_channels
|
| 443 |
+
self.num_patches = num_patches
|
| 444 |
+
|
| 445 |
+
self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
|
| 446 |
+
|
| 447 |
+
def forward(self, pixel_values, interpolate_pos_encoding: bool = False):
|
| 448 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 449 |
+
if num_channels != self.num_channels:
|
| 450 |
+
raise ValueError(
|
| 451 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
if not interpolate_pos_encoding and (height != self.image_size[0] or width != self.image_size[1]):
|
| 455 |
+
raise ValueError(
|
| 456 |
+
f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
|
| 457 |
+
)
|
| 458 |
+
x = self.projection(pixel_values).flatten(2).transpose(1, 2)
|
| 459 |
+
return x
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
# Copied from transformers.models.vit.modeling_vit.ViTSelfAttention ViT->ViTMAE
|
| 463 |
+
class ViTMAESelfAttention(nn.Module):
|
| 464 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 465 |
+
super().__init__()
|
| 466 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 467 |
+
raise ValueError(
|
| 468 |
+
f"The hidden size {config.hidden_size,} is not a multiple of the number of attention "
|
| 469 |
+
f"heads {config.num_attention_heads}."
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
self.has_flash_attn = HAS_FLASH_ATTN
|
| 473 |
+
self.num_attention_heads = config.num_attention_heads
|
| 474 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 475 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 476 |
+
|
| 477 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 478 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 479 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 480 |
+
|
| 481 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 482 |
+
self.attention_probs_dropout_prob = config.attention_probs_dropout_prob
|
| 483 |
+
|
| 484 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
| 485 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 486 |
+
x = x.view(new_x_shape)
|
| 487 |
+
return x.permute(0, 2, 1, 3)
|
| 488 |
+
|
| 489 |
+
def reshape_for_flash(self, x: torch.Tensor) -> torch.Tensor:
|
| 490 |
+
"""Reshape to (B, N, num_heads, head_dim) for flash_attn_func."""
|
| 491 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 492 |
+
return x.view(new_x_shape)
|
| 493 |
+
|
| 494 |
+
def forward(
|
| 495 |
+
self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
|
| 496 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 497 |
+
# Use FlashAttention when available and no special outputs are needed
|
| 498 |
+
if self.has_flash_attn and not output_attentions and head_mask is None:
|
| 499 |
+
query_layer = self.reshape_for_flash(self.query(hidden_states))
|
| 500 |
+
key_layer = self.reshape_for_flash(self.key(hidden_states))
|
| 501 |
+
value_layer = self.reshape_for_flash(self.value(hidden_states))
|
| 502 |
+
|
| 503 |
+
context_layer = flash_attn_func(
|
| 504 |
+
query_layer, key_layer, value_layer,
|
| 505 |
+
dropout_p=self.attention_probs_dropout_prob if self.training else 0.0,
|
| 506 |
+
causal=False, deterministic=True
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
context_layer = context_layer.reshape(hidden_states.size(0), -1, self.all_head_size)
|
| 510 |
+
return (context_layer,)
|
| 511 |
+
|
| 512 |
+
# Fallback: manual attention computation
|
| 513 |
+
mixed_query_layer = self.query(hidden_states)
|
| 514 |
+
|
| 515 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 516 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 517 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 518 |
+
|
| 519 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 520 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 521 |
+
|
| 522 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 523 |
+
attention_probs = self.dropout(attention_probs)
|
| 524 |
+
|
| 525 |
+
if head_mask is not None:
|
| 526 |
+
attention_probs = attention_probs * head_mask
|
| 527 |
+
|
| 528 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 529 |
+
|
| 530 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 531 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 532 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 533 |
+
|
| 534 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 535 |
+
|
| 536 |
+
return outputs
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
# Copied from transformers.models.vit.modeling_vit.ViTSdpaSelfAttention ViT->ViTMAE
|
| 540 |
+
class ViTMAESdpaSelfAttention(ViTMAESelfAttention):
|
| 541 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 542 |
+
super().__init__(config)
|
| 543 |
+
self.attention_probs_dropout_prob = config.attention_probs_dropout_prob
|
| 544 |
+
|
| 545 |
+
def forward(
|
| 546 |
+
self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
|
| 547 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 548 |
+
# Use FlashAttention when available and no special outputs are needed
|
| 549 |
+
if self.has_flash_attn and not output_attentions and head_mask is None:
|
| 550 |
+
query_layer = self.reshape_for_flash(self.query(hidden_states))
|
| 551 |
+
key_layer = self.reshape_for_flash(self.key(hidden_states))
|
| 552 |
+
value_layer = self.reshape_for_flash(self.value(hidden_states))
|
| 553 |
+
|
| 554 |
+
context_layer = flash_attn_func(
|
| 555 |
+
query_layer, key_layer, value_layer,
|
| 556 |
+
dropout_p=self.attention_probs_dropout_prob if self.training else 0.0,
|
| 557 |
+
causal=False, deterministic=True
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
context_layer = context_layer.reshape(hidden_states.size(0), -1, self.all_head_size)
|
| 561 |
+
return context_layer, None
|
| 562 |
+
|
| 563 |
+
# Fallback: PyTorch SDPA
|
| 564 |
+
mixed_query_layer = self.query(hidden_states)
|
| 565 |
+
|
| 566 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 567 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 568 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 569 |
+
|
| 570 |
+
context_layer = torch.nn.functional.scaled_dot_product_attention(
|
| 571 |
+
query_layer,
|
| 572 |
+
key_layer,
|
| 573 |
+
value_layer,
|
| 574 |
+
head_mask,
|
| 575 |
+
self.attention_probs_dropout_prob if self.training else 0.0,
|
| 576 |
+
is_causal=False,
|
| 577 |
+
scale=None,
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 581 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 582 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 583 |
+
|
| 584 |
+
return context_layer, None
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
# Copied from transformers.models.vit.modeling_vit.ViTSelfOutput with ViT->ViTMAE
|
| 588 |
+
class ViTMAESelfOutput(nn.Module):
|
| 589 |
+
"""
|
| 590 |
+
The residual connection is defined in ViTMAELayer instead of here (as is the case with other models), due to the
|
| 591 |
+
layernorm applied before each block.
|
| 592 |
+
"""
|
| 593 |
+
|
| 594 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 595 |
+
super().__init__()
|
| 596 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 597 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 598 |
+
|
| 599 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 600 |
+
hidden_states = self.dense(hidden_states)
|
| 601 |
+
hidden_states = self.dropout(hidden_states)
|
| 602 |
+
|
| 603 |
+
return hidden_states
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
# Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->ViTMAE
|
| 607 |
+
class ViTMAEAttention(nn.Module):
|
| 608 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 609 |
+
super().__init__()
|
| 610 |
+
self.attention = ViTMAESelfAttention(config)
|
| 611 |
+
self.output = ViTMAESelfOutput(config)
|
| 612 |
+
|
| 613 |
+
def forward(
|
| 614 |
+
self,
|
| 615 |
+
hidden_states: torch.Tensor,
|
| 616 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 617 |
+
output_attentions: bool = False,
|
| 618 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 619 |
+
self_outputs = self.attention(hidden_states, head_mask, output_attentions)
|
| 620 |
+
|
| 621 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 622 |
+
|
| 623 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 624 |
+
return outputs
|
| 625 |
+
|
| 626 |
+
# Copied from transformers.models.vit.modeling_vit.ViTIntermediate ViT->ViTMAE
|
| 627 |
+
class ViTMAEIntermediate(nn.Module):
|
| 628 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 629 |
+
super().__init__()
|
| 630 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 631 |
+
if isinstance(config.hidden_act, str):
|
| 632 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 633 |
+
else:
|
| 634 |
+
self.intermediate_act_fn = config.hidden_act
|
| 635 |
+
|
| 636 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 637 |
+
hidden_states = self.dense(hidden_states)
|
| 638 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 639 |
+
|
| 640 |
+
return hidden_states
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
# Copied from transformers.models.vit.modeling_vit.ViTOutput ViT->ViTMAE
|
| 644 |
+
class ViTMAEOutput(nn.Module):
|
| 645 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 646 |
+
super().__init__()
|
| 647 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 648 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 649 |
+
|
| 650 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 651 |
+
hidden_states = self.dense(hidden_states)
|
| 652 |
+
hidden_states = self.dropout(hidden_states)
|
| 653 |
+
|
| 654 |
+
hidden_states = hidden_states + input_tensor
|
| 655 |
+
|
| 656 |
+
return hidden_states
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
# Copied from transformers.models.vit.modeling_vit.ViTLayer with ViT->ViTMAE,VIT->VITMAE
|
| 661 |
+
class ViTMAELayer(nn.Module):
|
| 662 |
+
"""This corresponds to the Block class in the timm implementation."""
|
| 663 |
+
|
| 664 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 665 |
+
super().__init__()
|
| 666 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 667 |
+
self.seq_len_dim = 1
|
| 668 |
+
self.attention = ViTMAEAttention(config) # no SPDA by default
|
| 669 |
+
self.intermediate = ViTMAEIntermediate(config)
|
| 670 |
+
self.output = ViTMAEOutput(config)
|
| 671 |
+
self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 672 |
+
self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 673 |
+
|
| 674 |
+
def forward(
|
| 675 |
+
self,
|
| 676 |
+
hidden_states: torch.Tensor,
|
| 677 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 678 |
+
output_attentions: bool = False,
|
| 679 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 680 |
+
self_attention_outputs = self.attention(
|
| 681 |
+
self.layernorm_before(hidden_states), # in ViTMAE, layernorm is applied before self-attention
|
| 682 |
+
head_mask,
|
| 683 |
+
output_attentions=output_attentions,
|
| 684 |
+
)
|
| 685 |
+
attention_output = self_attention_outputs[0]
|
| 686 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 687 |
+
|
| 688 |
+
# first residual connection
|
| 689 |
+
hidden_states = attention_output + hidden_states
|
| 690 |
+
|
| 691 |
+
# in ViTMAE, layernorm is also applied after self-attention
|
| 692 |
+
layer_output = self.layernorm_after(hidden_states)
|
| 693 |
+
layer_output = self.intermediate(layer_output)
|
| 694 |
+
|
| 695 |
+
# second residual connection is done here
|
| 696 |
+
layer_output = self.output(layer_output, hidden_states)
|
| 697 |
+
|
| 698 |
+
outputs = (layer_output,) + outputs
|
| 699 |
+
|
| 700 |
+
return outputs
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
class GeneralDecoder(nn.Module):
|
| 704 |
+
def __init__(self, config, num_patches):
|
| 705 |
+
super().__init__()
|
| 706 |
+
self.decoder_embed = nn.Linear(config.hidden_size, config.decoder_hidden_size, bias=True)
|
| 707 |
+
self.decoder_pos_embed = nn.Parameter(
|
| 708 |
+
torch.zeros(1, num_patches + 1, config.decoder_hidden_size), requires_grad=False
|
| 709 |
+
) # fixed sin-cos embedding
|
| 710 |
+
|
| 711 |
+
decoder_config = deepcopy(config)
|
| 712 |
+
decoder_config.hidden_size = config.decoder_hidden_size
|
| 713 |
+
decoder_config.num_hidden_layers = config.decoder_num_hidden_layers
|
| 714 |
+
decoder_config.num_attention_heads = config.decoder_num_attention_heads
|
| 715 |
+
decoder_config.intermediate_size = config.decoder_intermediate_size
|
| 716 |
+
self.decoder_layers = nn.ModuleList(
|
| 717 |
+
[ViTMAELayer(decoder_config) for _ in range(config.decoder_num_hidden_layers)]
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
self.decoder_norm = nn.LayerNorm(config.decoder_hidden_size, eps=config.layer_norm_eps)
|
| 721 |
+
self.decoder_pred = nn.Linear(
|
| 722 |
+
config.decoder_hidden_size, config.patch_size**2 * config.num_channels, bias=True
|
| 723 |
+
) # encoder to decoder
|
| 724 |
+
self.gradient_checkpointing = False
|
| 725 |
+
self.config = config
|
| 726 |
+
self.num_patches = num_patches
|
| 727 |
+
self.initialize_weights(num_patches)
|
| 728 |
+
self.decoder_config = decoder_config
|
| 729 |
+
self.set_trainable_cls_token()
|
| 730 |
+
def set_trainable_cls_token(self, tensor: Optional[torch.Tensor] = None):
|
| 731 |
+
# register a trainable CLS token
|
| 732 |
+
tensor = torch.zeros(1, 1, self.decoder_config.hidden_size) if tensor is None else tensor
|
| 733 |
+
self.trainable_cls_token = nn.Parameter(tensor)
|
| 734 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor) -> torch.Tensor:
|
| 735 |
+
"""
|
| 736 |
+
This method is a modified version of the interpolation function for ViT-mae model at the deocder, that
|
| 737 |
+
allows to interpolate the pre-trained decoder position encodings, to be able to use the model on higher
|
| 738 |
+
resolution images.
|
| 739 |
+
|
| 740 |
+
Source:
|
| 741 |
+
https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174
|
| 742 |
+
"""
|
| 743 |
+
|
| 744 |
+
# -1 removes the class dimension since we later append it without interpolation
|
| 745 |
+
embeddings_positions = embeddings.shape[1] - 1
|
| 746 |
+
num_positions = self.decoder_pos_embed.shape[1] - 1
|
| 747 |
+
|
| 748 |
+
# Separation of class token and patch tokens
|
| 749 |
+
class_pos_embed = self.decoder_pos_embed[:, 0, :]
|
| 750 |
+
patch_pos_embed = self.decoder_pos_embed[:, 1:, :]
|
| 751 |
+
|
| 752 |
+
# To retain the final 3d tensor with the required dimensions
|
| 753 |
+
dim = self.decoder_pos_embed.shape[-1]
|
| 754 |
+
|
| 755 |
+
# Increasing a dimension to enable bicubic interpolation
|
| 756 |
+
patch_pos_embed = patch_pos_embed.reshape(1, 1, -1, dim)
|
| 757 |
+
|
| 758 |
+
# permute to bring the dimension to be interpolated, to the last
|
| 759 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 760 |
+
|
| 761 |
+
# Interpolating the decoder position embeddings shape wrt embeddings shape i.e (x).
|
| 762 |
+
# 1 keeps the other dimension constant
|
| 763 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 764 |
+
patch_pos_embed,
|
| 765 |
+
scale_factor=(1, embeddings_positions / num_positions),
|
| 766 |
+
mode="bicubic",
|
| 767 |
+
align_corners=False,
|
| 768 |
+
)
|
| 769 |
+
|
| 770 |
+
# Converting back to the original shape
|
| 771 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 772 |
+
# Adding the class token back
|
| 773 |
+
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
|
| 774 |
+
def interpolate_latent(self, x: torch.Tensor) -> torch.Tensor:
|
| 775 |
+
b, l, c = x.shape
|
| 776 |
+
if l == self.num_patches:
|
| 777 |
+
return x
|
| 778 |
+
# interpolate the latent
|
| 779 |
+
#print(f"interpolating latent from {l} to {self.num_patches}, x.shape = {x.shape}")
|
| 780 |
+
h, w = int(l**0.5), int(l**0.5)
|
| 781 |
+
x = x.reshape(b, h, w, c)
|
| 782 |
+
x = x.permute(0, 3, 1, 2)
|
| 783 |
+
target_size = (int(self.num_patches**0.5), int(self.num_patches**0.5))
|
| 784 |
+
x = nn.functional.interpolate(x, size=target_size, mode="bilinear", align_corners=False)
|
| 785 |
+
x = x.permute(0, 2, 3, 1).contiguous().view(b, self.num_patches, c)
|
| 786 |
+
return x
|
| 787 |
+
|
| 788 |
+
def initialize_weights(self, num_patches):
|
| 789 |
+
# initialize (and freeze) position embeddings by sin-cos embedding
|
| 790 |
+
decoder_pos_embed = get_2d_sincos_pos_embed(
|
| 791 |
+
self.decoder_pos_embed.shape[-1], int(num_patches**0.5), add_cls_token=True
|
| 792 |
+
)
|
| 793 |
+
self.decoder_pos_embed.data.copy_(torch.from_numpy(decoder_pos_embed).float().unsqueeze(0))
|
| 794 |
+
|
| 795 |
+
# timm's trunc_normal_(std=.02) is effectively normal_(std=0.02) as cutoff is too big (2.)
|
| 796 |
+
# torch.nn.init.normal_(self.mask_token, std=self.config.initializer_range)
|
| 797 |
+
def unpatchify(self, patchified_pixel_values, original_image_size: Optional[Tuple[int, int]] = None):
|
| 798 |
+
"""
|
| 799 |
+
Args:
|
| 800 |
+
patchified_pixel_values (`torch.FloatTensor` of shape `(batch_size, num_patches, patch_size**2 * num_channels)`:
|
| 801 |
+
Patchified pixel values.
|
| 802 |
+
original_image_size (`Tuple[int, int]`, *optional*):
|
| 803 |
+
Original image size.
|
| 804 |
+
|
| 805 |
+
Returns:
|
| 806 |
+
`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`:
|
| 807 |
+
Pixel values.
|
| 808 |
+
"""
|
| 809 |
+
patch_size, num_channels = self.config.patch_size, self.config.num_channels
|
| 810 |
+
original_image_size = (
|
| 811 |
+
original_image_size
|
| 812 |
+
if original_image_size is not None
|
| 813 |
+
else (self.config.image_size, self.config.image_size)
|
| 814 |
+
)
|
| 815 |
+
original_height, original_width = original_image_size
|
| 816 |
+
num_patches_h = original_height // patch_size
|
| 817 |
+
num_patches_w = original_width // patch_size
|
| 818 |
+
# sanity check
|
| 819 |
+
if num_patches_h * num_patches_w != patchified_pixel_values.shape[1]:
|
| 820 |
+
raise ValueError(
|
| 821 |
+
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}"
|
| 822 |
+
)
|
| 823 |
+
|
| 824 |
+
# unpatchify
|
| 825 |
+
batch_size = patchified_pixel_values.shape[0]
|
| 826 |
+
patchified_pixel_values = patchified_pixel_values.reshape(
|
| 827 |
+
batch_size,
|
| 828 |
+
num_patches_h,
|
| 829 |
+
num_patches_w,
|
| 830 |
+
patch_size,
|
| 831 |
+
patch_size,
|
| 832 |
+
num_channels,
|
| 833 |
+
)
|
| 834 |
+
patchified_pixel_values = torch.einsum("nhwpqc->nchpwq", patchified_pixel_values)
|
| 835 |
+
pixel_values = patchified_pixel_values.reshape(
|
| 836 |
+
batch_size,
|
| 837 |
+
num_channels,
|
| 838 |
+
num_patches_h * patch_size,
|
| 839 |
+
num_patches_w * patch_size,
|
| 840 |
+
)
|
| 841 |
+
return pixel_values
|
| 842 |
+
|
| 843 |
+
def forward(
|
| 844 |
+
self,
|
| 845 |
+
hidden_states,
|
| 846 |
+
output_attentions=False,
|
| 847 |
+
output_hidden_states=False,
|
| 848 |
+
return_dict=True,
|
| 849 |
+
interpolate_pos_encoding: bool = False,
|
| 850 |
+
drop_cls_token: bool = False,
|
| 851 |
+
):
|
| 852 |
+
# embed tokens
|
| 853 |
+
x = self.decoder_embed(hidden_states)
|
| 854 |
+
#print(f"x.shape = {x.shape}")
|
| 855 |
+
if drop_cls_token:
|
| 856 |
+
x_ = x[:, 1:, :] # no cls token
|
| 857 |
+
x_ = self.interpolate_latent(x_)
|
| 858 |
+
else:
|
| 859 |
+
x_ = self.interpolate_latent(x) # interpolate the whole latent
|
| 860 |
+
cls_token = self.trainable_cls_token.expand(x_.shape[0], -1, -1)
|
| 861 |
+
x = torch.cat([cls_token, x_], dim=1)
|
| 862 |
+
|
| 863 |
+
# add pos embed
|
| 864 |
+
if interpolate_pos_encoding:
|
| 865 |
+
assert drop_cls_token, "interpolate_pos_encoding only works with drop_cls_token=True"
|
| 866 |
+
decoder_pos_embed = self.interpolate_pos_encoding(x)
|
| 867 |
+
else:
|
| 868 |
+
decoder_pos_embed = self.decoder_pos_embed
|
| 869 |
+
hidden_states = x + decoder_pos_embed
|
| 870 |
+
#print(f"hidden_states.shape = {hidden_states.shape}")
|
| 871 |
+
# apply Transformer layers (blocks)
|
| 872 |
+
all_hidden_states = () if output_hidden_states else None
|
| 873 |
+
all_self_attentions = () if output_attentions else None
|
| 874 |
+
for i, layer_module in enumerate(self.decoder_layers):
|
| 875 |
+
if output_hidden_states:
|
| 876 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 877 |
+
|
| 878 |
+
if self.gradient_checkpointing and self.training:
|
| 879 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 880 |
+
layer_module.__call__,
|
| 881 |
+
hidden_states,
|
| 882 |
+
None,
|
| 883 |
+
output_attentions,
|
| 884 |
+
)
|
| 885 |
+
else:
|
| 886 |
+
layer_outputs = layer_module(hidden_states, head_mask=None, output_attentions=output_attentions)
|
| 887 |
+
|
| 888 |
+
hidden_states = layer_outputs[0]
|
| 889 |
+
|
| 890 |
+
if output_attentions:
|
| 891 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 892 |
+
|
| 893 |
+
if output_hidden_states:
|
| 894 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 895 |
+
|
| 896 |
+
hidden_states = self.decoder_norm(hidden_states)
|
| 897 |
+
|
| 898 |
+
# predictor projection
|
| 899 |
+
logits = self.decoder_pred(hidden_states)
|
| 900 |
+
|
| 901 |
+
# remove cls token
|
| 902 |
+
logits = logits[:, 1:, :]
|
| 903 |
+
|
| 904 |
+
if not return_dict:
|
| 905 |
+
return tuple(v for v in [logits, all_hidden_states, all_self_attentions] if v is not None)
|
| 906 |
+
return ViTMAEDecoderOutput(
|
| 907 |
+
logits=logits,
|
| 908 |
+
hidden_states=all_hidden_states,
|
| 909 |
+
attentions=all_self_attentions,
|
| 910 |
+
)
|
| 911 |
+
|
| 912 |
+
import json
|
| 913 |
+
from math import sqrt
|
| 914 |
+
from pathlib import Path
|
| 915 |
+
from typing import Any, Dict, Optional
|
| 916 |
+
|
| 917 |
+
import torch
|
| 918 |
+
import torch.nn as nn
|
| 919 |
+
from timm.models.vision_transformer import Attention
|
| 920 |
+
from transformers import AutoConfig, AutoImageProcessor
|
| 921 |
+
|
| 922 |
+
try:
|
| 923 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 924 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 925 |
+
except Exception: # pragma: no cover
|
| 926 |
+
class ConfigMixin:
|
| 927 |
+
config_name = "config.json"
|
| 928 |
+
|
| 929 |
+
class ModelMixin(nn.Module):
|
| 930 |
+
pass
|
| 931 |
+
|
| 932 |
+
def register_to_config(init):
|
| 933 |
+
return init
|
| 934 |
+
|
| 935 |
+
|
| 936 |
+
_PIXEL_DECODER_DEFAULTS: Dict[str, Any] = {
|
| 937 |
+
"decoder_hidden_size": 1024,
|
| 938 |
+
"decoder_intermediate_size": 4096,
|
| 939 |
+
"decoder_num_attention_heads": 16,
|
| 940 |
+
"decoder_num_hidden_layers": 24,
|
| 941 |
+
"layer_norm_eps": 1e-12,
|
| 942 |
+
"num_channels": 3,
|
| 943 |
+
"hidden_act": "gelu",
|
| 944 |
+
"qkv_bias": True,
|
| 945 |
+
"hidden_dropout_prob": 0.0,
|
| 946 |
+
"attention_probs_dropout_prob": 0.0,
|
| 947 |
+
"initializer_range": 0.02,
|
| 948 |
+
}
|
| 949 |
+
|
| 950 |
+
|
| 951 |
+
def _resolve_local_asset_path(path: str, model_root: Optional[Path] = None) -> str:
|
| 952 |
+
candidate = Path(path)
|
| 953 |
+
if candidate.is_file():
|
| 954 |
+
return str(candidate)
|
| 955 |
+
search_roots = []
|
| 956 |
+
if model_root is not None:
|
| 957 |
+
search_roots.extend([model_root, model_root.parent])
|
| 958 |
+
for root in search_roots:
|
| 959 |
+
for probe in (root / candidate, root / candidate.name, root / "decoder_config" / "config.json"):
|
| 960 |
+
if probe.is_file():
|
| 961 |
+
return str(probe)
|
| 962 |
+
return path
|
| 963 |
+
|
| 964 |
+
|
| 965 |
+
def _build_pixel_decoder_config(
|
| 966 |
+
*,
|
| 967 |
+
encoder_hidden_size: int,
|
| 968 |
+
decoder_patch_size: int,
|
| 969 |
+
base_patches: int,
|
| 970 |
+
decoder_config_path: Optional[str] = None,
|
| 971 |
+
overrides: Optional[Dict[str, Any]] = None,
|
| 972 |
+
) -> ViTMAEConfig:
|
| 973 |
+
pixel_decoder = dict(_PIXEL_DECODER_DEFAULTS)
|
| 974 |
+
if decoder_config_path is not None:
|
| 975 |
+
resolved = _resolve_local_asset_path(decoder_config_path)
|
| 976 |
+
if Path(resolved).is_file():
|
| 977 |
+
with open(resolved, encoding="utf-8") as handle:
|
| 978 |
+
pixel_decoder.update(json.load(handle))
|
| 979 |
+
if overrides:
|
| 980 |
+
pixel_decoder.update({key: value for key, value in overrides.items() if value is not None})
|
| 981 |
+
|
| 982 |
+
return ViTMAEConfig(
|
| 983 |
+
hidden_size=encoder_hidden_size,
|
| 984 |
+
patch_size=decoder_patch_size,
|
| 985 |
+
image_size=int(decoder_patch_size * sqrt(base_patches)),
|
| 986 |
+
**pixel_decoder,
|
| 987 |
+
)
|
| 988 |
+
|
| 989 |
+
|
| 990 |
+
def _load_image_normalization(encoder_config_path: str) -> tuple[list[float], list[float]]:
|
| 991 |
+
try:
|
| 992 |
+
proc = AutoImageProcessor.from_pretrained(encoder_config_path, use_fast=True, local_files_only=True)
|
| 993 |
+
return proc.image_mean, proc.image_std
|
| 994 |
+
except Exception:
|
| 995 |
+
pass
|
| 996 |
+
try:
|
| 997 |
+
proc = AutoImageProcessor.from_pretrained(encoder_config_path, use_fast=True, local_files_only=False)
|
| 998 |
+
return proc.image_mean, proc.image_std
|
| 999 |
+
except Exception:
|
| 1000 |
+
if "siglip" in encoder_config_path.lower():
|
| 1001 |
+
return [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]
|
| 1002 |
+
return [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
|
| 1003 |
+
|
| 1004 |
+
|
| 1005 |
+
class PAEDecoder(ModelMixin, ConfigMixin):
|
| 1006 |
+
"""PAE decoder: latent decompressor + ViT-MAE pixel decoder."""
|
| 1007 |
+
|
| 1008 |
+
@register_to_config
|
| 1009 |
+
def __init__(
|
| 1010 |
+
self,
|
| 1011 |
+
encoder_hidden_size: int = 1024,
|
| 1012 |
+
encoder_num_heads: int = 16,
|
| 1013 |
+
encoder_input_size: int = 224,
|
| 1014 |
+
encoder_patch_size: int = 14,
|
| 1015 |
+
encoder_config_path: str = "facebook/dinov2-with-registers-large",
|
| 1016 |
+
latent_dim: int = 32,
|
| 1017 |
+
decoder_patch_size: int = 16,
|
| 1018 |
+
decoder_config_path: Optional[str] = None,
|
| 1019 |
+
decoder_hidden_size: int = 1024,
|
| 1020 |
+
decoder_intermediate_size: int = 4096,
|
| 1021 |
+
decoder_num_attention_heads: int = 16,
|
| 1022 |
+
decoder_num_hidden_layers: int = 24,
|
| 1023 |
+
layer_norm_eps: float = 1e-12,
|
| 1024 |
+
num_channels: int = 3,
|
| 1025 |
+
hidden_act: str = "gelu",
|
| 1026 |
+
qkv_bias: bool = True,
|
| 1027 |
+
hidden_dropout_prob: float = 0.0,
|
| 1028 |
+
attention_probs_dropout_prob: float = 0.0,
|
| 1029 |
+
initializer_range: float = 0.02,
|
| 1030 |
+
image_mean: Optional[list[float]] = None,
|
| 1031 |
+
image_std: Optional[list[float]] = None,
|
| 1032 |
+
latent_mean: Optional[list[float]] = None,
|
| 1033 |
+
latent_std: Optional[list[float]] = None,
|
| 1034 |
+
latent_multiplier: float = 1.0,
|
| 1035 |
+
**kwargs,
|
| 1036 |
+
) -> None:
|
| 1037 |
+
super().__init__()
|
| 1038 |
+
if image_mean is not None and image_std is not None:
|
| 1039 |
+
norm_mean, norm_std = image_mean, image_std
|
| 1040 |
+
else:
|
| 1041 |
+
norm_mean, norm_std = _load_image_normalization(encoder_config_path)
|
| 1042 |
+
self.register_buffer("encoder_mean", torch.tensor(norm_mean).view(1, 3, 1, 1), persistent=True)
|
| 1043 |
+
self.register_buffer("encoder_std", torch.tensor(norm_std).view(1, 3, 1, 1), persistent=True)
|
| 1044 |
+
|
| 1045 |
+
self.encoder_input_size = encoder_input_size
|
| 1046 |
+
self.encoder_patch_size = encoder_patch_size
|
| 1047 |
+
self.base_patches = (self.encoder_input_size // self.encoder_patch_size) ** 2
|
| 1048 |
+
self.latent_dim = latent_dim
|
| 1049 |
+
|
| 1050 |
+
self.latent_decompressor = nn.ModuleList(
|
| 1051 |
+
[
|
| 1052 |
+
nn.Conv2d(latent_dim, encoder_hidden_size, kernel_size=3, padding=1),
|
| 1053 |
+
Attention(dim=encoder_hidden_size, num_heads=encoder_num_heads),
|
| 1054 |
+
]
|
| 1055 |
+
)
|
| 1056 |
+
|
| 1057 |
+
pixel_decoder_config = _build_pixel_decoder_config(
|
| 1058 |
+
encoder_hidden_size=encoder_hidden_size,
|
| 1059 |
+
decoder_patch_size=decoder_patch_size,
|
| 1060 |
+
base_patches=self.base_patches,
|
| 1061 |
+
decoder_config_path=decoder_config_path,
|
| 1062 |
+
overrides={
|
| 1063 |
+
"decoder_hidden_size": decoder_hidden_size,
|
| 1064 |
+
"decoder_intermediate_size": decoder_intermediate_size,
|
| 1065 |
+
"decoder_num_attention_heads": decoder_num_attention_heads,
|
| 1066 |
+
"decoder_num_hidden_layers": decoder_num_hidden_layers,
|
| 1067 |
+
"layer_norm_eps": layer_norm_eps,
|
| 1068 |
+
"num_channels": num_channels,
|
| 1069 |
+
"hidden_act": hidden_act,
|
| 1070 |
+
"qkv_bias": qkv_bias,
|
| 1071 |
+
"hidden_dropout_prob": hidden_dropout_prob,
|
| 1072 |
+
"attention_probs_dropout_prob": attention_probs_dropout_prob,
|
| 1073 |
+
"initializer_range": initializer_range,
|
| 1074 |
+
},
|
| 1075 |
+
)
|
| 1076 |
+
self.decoder = GeneralDecoder(pixel_decoder_config, num_patches=self.base_patches)
|
| 1077 |
+
|
| 1078 |
+
@classmethod
|
| 1079 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 1080 |
+
model_root = Path(pretrained_model_name_or_path)
|
| 1081 |
+
config_file = model_root / cls.config_name
|
| 1082 |
+
if config_file.is_file():
|
| 1083 |
+
with open(config_file, encoding="utf-8") as handle:
|
| 1084 |
+
config = json.load(handle)
|
| 1085 |
+
decoder_config_path = config.get("decoder_config_path")
|
| 1086 |
+
if decoder_config_path is not None:
|
| 1087 |
+
resolved = _resolve_local_asset_path(decoder_config_path, model_root=model_root)
|
| 1088 |
+
if resolved != decoder_config_path:
|
| 1089 |
+
kwargs.setdefault("decoder_config_path", resolved)
|
| 1090 |
+
return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
|
| 1091 |
+
|
| 1092 |
+
def decode(self, latents: torch.Tensor) -> torch.Tensor:
|
| 1093 |
+
hidden_states = self.latent_decompressor[0](latents)
|
| 1094 |
+
batch_size, channels, height, width = hidden_states.shape
|
| 1095 |
+
num_tokens = height * width
|
| 1096 |
+
hidden_states = hidden_states.view(batch_size, channels, num_tokens).transpose(1, 2)
|
| 1097 |
+
hidden_states = self.latent_decompressor[1](hidden_states)
|
| 1098 |
+
|
| 1099 |
+
output = self.decoder(hidden_states, drop_cls_token=False).logits
|
| 1100 |
+
x_rec = self.decoder.unpatchify(output)
|
| 1101 |
+
x_rec = x_rec * self.encoder_std.to(x_rec.device) + self.encoder_mean.to(x_rec.device)
|
| 1102 |
+
return x_rec
|
| 1103 |
+
|
| 1104 |
+
def forward(self, latents: torch.Tensor) -> torch.Tensor:
|
| 1105 |
+
return self.decode(latents)
|
pae-dinov2-large-d32/decoder/diffusion_pytorch_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:313211153c3fbe6ea36c131eb41815c68acf50ab0a638a32ee6fae0a924d3d33
|
| 3 |
+
size 1235663744
|
pae-dinov2-large-d32/demo.png
ADDED
|
Git LFS Details
|
pae-dinov2-large-d32/model_index.json
ADDED
|
@@ -0,0 +1,1021 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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2": "great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias",
|
| 15 |
+
"3": "tiger shark, Galeocerdo cuvieri",
|
| 16 |
+
"4": "hammerhead, hammerhead shark",
|
| 17 |
+
"5": "electric ray, crampfish, numbfish, torpedo",
|
| 18 |
+
"6": "stingray",
|
| 19 |
+
"7": "cock",
|
| 20 |
+
"8": "hen",
|
| 21 |
+
"9": "ostrich, Struthio camelus",
|
| 22 |
+
"10": "brambling, Fringilla montifringilla",
|
| 23 |
+
"11": "goldfinch, Carduelis carduelis",
|
| 24 |
+
"12": "house finch, linnet, Carpodacus mexicanus",
|
| 25 |
+
"13": "junco, snowbird",
|
| 26 |
+
"14": "indigo bunting, indigo finch, indigo bird, Passerina cyanea",
|
| 27 |
+
"15": "robin, American robin, Turdus migratorius",
|
| 28 |
+
"16": "bulbul",
|
| 29 |
+
"17": "jay",
|
| 30 |
+
"18": "magpie",
|
| 31 |
+
"19": "chickadee",
|
| 32 |
+
"20": "water ouzel, dipper",
|
| 33 |
+
"21": "kite",
|
| 34 |
+
"22": "bald eagle, American eagle, Haliaeetus leucocephalus",
|
| 35 |
+
"23": "vulture",
|
| 36 |
+
"24": "great grey owl, great gray owl, Strix nebulosa",
|
| 37 |
+
"25": "European fire salamander, Salamandra salamandra",
|
| 38 |
+
"26": "common newt, Triturus vulgaris",
|
| 39 |
+
"27": "eft",
|
| 40 |
+
"28": "spotted salamander, Ambystoma maculatum",
|
| 41 |
+
"29": "axolotl, mud puppy, Ambystoma mexicanum",
|
| 42 |
+
"30": "bullfrog, Rana catesbeiana",
|
| 43 |
+
"31": "tree frog, tree-frog",
|
| 44 |
+
"32": "tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui",
|
| 45 |
+
"33": "loggerhead, loggerhead turtle, Caretta caretta",
|
| 46 |
+
"34": "leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea",
|
| 47 |
+
"35": "mud turtle",
|
| 48 |
+
"36": "terrapin",
|
| 49 |
+
"37": "box turtle, box tortoise",
|
| 50 |
+
"38": "banded gecko",
|
| 51 |
+
"39": "common iguana, iguana, Iguana iguana",
|
| 52 |
+
"40": "American chameleon, anole, Anolis carolinensis",
|
| 53 |
+
"41": "whiptail, whiptail lizard",
|
| 54 |
+
"42": "agama",
|
| 55 |
+
"43": "frilled lizard, Chlamydosaurus kingi",
|
| 56 |
+
"44": "alligator lizard",
|
| 57 |
+
"45": "Gila monster, Heloderma suspectum",
|
| 58 |
+
"46": "green lizard, Lacerta viridis",
|
| 59 |
+
"47": "African chameleon, Chamaeleo chamaeleon",
|
| 60 |
+
"48": "Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis",
|
| 61 |
+
"49": "African crocodile, Nile crocodile, Crocodylus niloticus",
|
| 62 |
+
"50": "American alligator, Alligator mississipiensis",
|
| 63 |
+
"51": "triceratops",
|
| 64 |
+
"52": "thunder snake, worm snake, Carphophis amoenus",
|
| 65 |
+
"53": "ringneck snake, ring-necked snake, ring snake",
|
| 66 |
+
"54": "hognose snake, puff adder, sand viper",
|
| 67 |
+
"55": "green snake, grass snake",
|
| 68 |
+
"56": "king snake, kingsnake",
|
| 69 |
+
"57": "garter snake, grass snake",
|
| 70 |
+
"58": "water snake",
|
| 71 |
+
"59": "vine snake",
|
| 72 |
+
"60": "night snake, Hypsiglena torquata",
|
| 73 |
+
"61": "boa constrictor, Constrictor constrictor",
|
| 74 |
+
"62": "rock python, rock snake, Python sebae",
|
| 75 |
+
"63": "Indian cobra, Naja naja",
|
| 76 |
+
"64": "green mamba",
|
| 77 |
+
"65": "sea snake",
|
| 78 |
+
"66": "horned viper, cerastes, sand viper, horned asp, Cerastes cornutus",
|
| 79 |
+
"67": "diamondback, diamondback rattlesnake, Crotalus adamanteus",
|
| 80 |
+
"68": "sidewinder, horned rattlesnake, Crotalus cerastes",
|
| 81 |
+
"69": "trilobite",
|
| 82 |
+
"70": "harvestman, daddy longlegs, Phalangium opilio",
|
| 83 |
+
"71": "scorpion",
|
| 84 |
+
"72": "black and gold garden spider, Argiope aurantia",
|
| 85 |
+
"73": "barn spider, Araneus cavaticus",
|
| 86 |
+
"74": "garden spider, Aranea diademata",
|
| 87 |
+
"75": "black widow, Latrodectus mactans",
|
| 88 |
+
"76": "tarantula",
|
| 89 |
+
"77": "wolf spider, hunting spider",
|
| 90 |
+
"78": "tick",
|
| 91 |
+
"79": "centipede",
|
| 92 |
+
"80": "black grouse",
|
| 93 |
+
"81": "ptarmigan",
|
| 94 |
+
"82": "ruffed grouse, partridge, Bonasa umbellus",
|
| 95 |
+
"83": "prairie chicken, prairie grouse, prairie fowl",
|
| 96 |
+
"84": "peacock",
|
| 97 |
+
"85": "quail",
|
| 98 |
+
"86": "partridge",
|
| 99 |
+
"87": "African grey, African gray, Psittacus erithacus",
|
| 100 |
+
"88": "macaw",
|
| 101 |
+
"89": "sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita",
|
| 102 |
+
"90": "lorikeet",
|
| 103 |
+
"91": "coucal",
|
| 104 |
+
"92": "bee eater",
|
| 105 |
+
"93": "hornbill",
|
| 106 |
+
"94": "hummingbird",
|
| 107 |
+
"95": "jacamar",
|
| 108 |
+
"96": "toucan",
|
| 109 |
+
"97": "drake",
|
| 110 |
+
"98": "red-breasted merganser, Mergus serrator",
|
| 111 |
+
"99": "goose",
|
| 112 |
+
"100": "black swan, Cygnus atratus",
|
| 113 |
+
"101": "tusker",
|
| 114 |
+
"102": "echidna, spiny anteater, anteater",
|
| 115 |
+
"103": "platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus",
|
| 116 |
+
"104": "wallaby, brush kangaroo",
|
| 117 |
+
"105": "koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus",
|
| 118 |
+
"106": "wombat",
|
| 119 |
+
"107": "jellyfish",
|
| 120 |
+
"108": "sea anemone, anemone",
|
| 121 |
+
"109": "brain coral",
|
| 122 |
+
"110": "flatworm, platyhelminth",
|
| 123 |
+
"111": "nematode, nematode worm, roundworm",
|
| 124 |
+
"112": "conch",
|
| 125 |
+
"113": "snail",
|
| 126 |
+
"114": "slug",
|
| 127 |
+
"115": "sea slug, nudibranch",
|
| 128 |
+
"116": "chiton, coat-of-mail shell, sea cradle, polyplacophore",
|
| 129 |
+
"117": "chambered nautilus, pearly nautilus, nautilus",
|
| 130 |
+
"118": "Dungeness crab, Cancer magister",
|
| 131 |
+
"119": "rock crab, Cancer irroratus",
|
| 132 |
+
"120": "fiddler crab",
|
| 133 |
+
"121": "king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica",
|
| 134 |
+
"122": "American lobster, Northern lobster, Maine lobster, Homarus americanus",
|
| 135 |
+
"123": "spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish",
|
| 136 |
+
"124": "crayfish, crawfish, crawdad, crawdaddy",
|
| 137 |
+
"125": "hermit crab",
|
| 138 |
+
"126": "isopod",
|
| 139 |
+
"127": "white stork, Ciconia ciconia",
|
| 140 |
+
"128": "black stork, Ciconia nigra",
|
| 141 |
+
"129": "spoonbill",
|
| 142 |
+
"130": "flamingo",
|
| 143 |
+
"131": "little blue heron, Egretta caerulea",
|
| 144 |
+
"132": "American egret, great white heron, Egretta albus",
|
| 145 |
+
"133": "bittern",
|
| 146 |
+
"134": "crane",
|
| 147 |
+
"135": "limpkin, Aramus pictus",
|
| 148 |
+
"136": "European gallinule, Porphyrio porphyrio",
|
| 149 |
+
"137": "American coot, marsh hen, mud hen, water hen, Fulica americana",
|
| 150 |
+
"138": "bustard",
|
| 151 |
+
"139": "ruddy turnstone, Arenaria interpres",
|
| 152 |
+
"140": "red-backed sandpiper, dunlin, Erolia alpina",
|
| 153 |
+
"141": "redshank, Tringa totanus",
|
| 154 |
+
"142": "dowitcher",
|
| 155 |
+
"143": "oystercatcher, oyster catcher",
|
| 156 |
+
"144": "pelican",
|
| 157 |
+
"145": "king penguin, Aptenodytes patagonica",
|
| 158 |
+
"146": "albatross, mollymawk",
|
| 159 |
+
"147": "grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus",
|
| 160 |
+
"148": "killer whale, killer, orca, grampus, sea wolf, Orcinus orca",
|
| 161 |
+
"149": "dugong, Dugong dugon",
|
| 162 |
+
"150": "sea lion",
|
| 163 |
+
"151": "Chihuahua",
|
| 164 |
+
"152": "Japanese spaniel",
|
| 165 |
+
"153": "Maltese dog, Maltese terrier, Maltese",
|
| 166 |
+
"154": "Pekinese, Pekingese, Peke",
|
| 167 |
+
"155": "Shih-Tzu",
|
| 168 |
+
"156": "Blenheim spaniel",
|
| 169 |
+
"157": "papillon",
|
| 170 |
+
"158": "toy terrier",
|
| 171 |
+
"159": "Rhodesian ridgeback",
|
| 172 |
+
"160": "Afghan hound, Afghan",
|
| 173 |
+
"161": "basset, basset hound",
|
| 174 |
+
"162": "beagle",
|
| 175 |
+
"163": "bloodhound, sleuthhound",
|
| 176 |
+
"164": "bluetick",
|
| 177 |
+
"165": "black-and-tan coonhound",
|
| 178 |
+
"166": "Walker hound, Walker foxhound",
|
| 179 |
+
"167": "English foxhound",
|
| 180 |
+
"168": "redbone",
|
| 181 |
+
"169": "borzoi, Russian wolfhound",
|
| 182 |
+
"170": "Irish wolfhound",
|
| 183 |
+
"171": "Italian greyhound",
|
| 184 |
+
"172": "whippet",
|
| 185 |
+
"173": "Ibizan hound, Ibizan Podenco",
|
| 186 |
+
"174": "Norwegian elkhound, elkhound",
|
| 187 |
+
"175": "otterhound, otter hound",
|
| 188 |
+
"176": "Saluki, gazelle hound",
|
| 189 |
+
"177": "Scottish deerhound, deerhound",
|
| 190 |
+
"178": "Weimaraner",
|
| 191 |
+
"179": "Staffordshire bullterrier, Staffordshire bull terrier",
|
| 192 |
+
"180": "American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier",
|
| 193 |
+
"181": "Bedlington terrier",
|
| 194 |
+
"182": "Border terrier",
|
| 195 |
+
"183": "Kerry blue terrier",
|
| 196 |
+
"184": "Irish terrier",
|
| 197 |
+
"185": "Norfolk terrier",
|
| 198 |
+
"186": "Norwich terrier",
|
| 199 |
+
"187": "Yorkshire terrier",
|
| 200 |
+
"188": "wire-haired fox terrier",
|
| 201 |
+
"189": "Lakeland terrier",
|
| 202 |
+
"190": "Sealyham terrier, Sealyham",
|
| 203 |
+
"191": "Airedale, Airedale terrier",
|
| 204 |
+
"192": "cairn, cairn terrier",
|
| 205 |
+
"193": "Australian terrier",
|
| 206 |
+
"194": "Dandie Dinmont, Dandie Dinmont terrier",
|
| 207 |
+
"195": "Boston bull, Boston terrier",
|
| 208 |
+
"196": "miniature schnauzer",
|
| 209 |
+
"197": "giant schnauzer",
|
| 210 |
+
"198": "standard schnauzer",
|
| 211 |
+
"199": "Scotch terrier, Scottish terrier, Scottie",
|
| 212 |
+
"200": "Tibetan terrier, chrysanthemum dog",
|
| 213 |
+
"201": "silky terrier, Sydney silky",
|
| 214 |
+
"202": "soft-coated wheaten terrier",
|
| 215 |
+
"203": "West Highland white terrier",
|
| 216 |
+
"204": "Lhasa, Lhasa apso",
|
| 217 |
+
"205": "flat-coated retriever",
|
| 218 |
+
"206": "curly-coated retriever",
|
| 219 |
+
"207": "golden retriever",
|
| 220 |
+
"208": "Labrador retriever",
|
| 221 |
+
"209": "Chesapeake Bay retriever",
|
| 222 |
+
"210": "German short-haired pointer",
|
| 223 |
+
"211": "vizsla, Hungarian pointer",
|
| 224 |
+
"212": "English setter",
|
| 225 |
+
"213": "Irish setter, red setter",
|
| 226 |
+
"214": "Gordon setter",
|
| 227 |
+
"215": "Brittany spaniel",
|
| 228 |
+
"216": "clumber, clumber spaniel",
|
| 229 |
+
"217": "English springer, English springer spaniel",
|
| 230 |
+
"218": "Welsh springer spaniel",
|
| 231 |
+
"219": "cocker spaniel, English cocker spaniel, cocker",
|
| 232 |
+
"220": "Sussex spaniel",
|
| 233 |
+
"221": "Irish water spaniel",
|
| 234 |
+
"222": "kuvasz",
|
| 235 |
+
"223": "schipperke",
|
| 236 |
+
"224": "groenendael",
|
| 237 |
+
"225": "malinois",
|
| 238 |
+
"226": "briard",
|
| 239 |
+
"227": "kelpie",
|
| 240 |
+
"228": "komondor",
|
| 241 |
+
"229": "Old English sheepdog, bobtail",
|
| 242 |
+
"230": "Shetland sheepdog, Shetland sheep dog, Shetland",
|
| 243 |
+
"231": "collie",
|
| 244 |
+
"232": "Border collie",
|
| 245 |
+
"233": "Bouvier des Flandres, Bouviers des Flandres",
|
| 246 |
+
"234": "Rottweiler",
|
| 247 |
+
"235": "German shepherd, German shepherd dog, German police dog, alsatian",
|
| 248 |
+
"236": "Doberman, Doberman pinscher",
|
| 249 |
+
"237": "miniature pinscher",
|
| 250 |
+
"238": "Greater Swiss Mountain dog",
|
| 251 |
+
"239": "Bernese mountain dog",
|
| 252 |
+
"240": "Appenzeller",
|
| 253 |
+
"241": "EntleBucher",
|
| 254 |
+
"242": "boxer",
|
| 255 |
+
"243": "bull mastiff",
|
| 256 |
+
"244": "Tibetan mastiff",
|
| 257 |
+
"245": "French bulldog",
|
| 258 |
+
"246": "Great Dane",
|
| 259 |
+
"247": "Saint Bernard, St Bernard",
|
| 260 |
+
"248": "Eskimo dog, husky",
|
| 261 |
+
"249": "malamute, malemute, Alaskan malamute",
|
| 262 |
+
"250": "Siberian husky",
|
| 263 |
+
"251": "dalmatian, coach dog, carriage dog",
|
| 264 |
+
"252": "affenpinscher, monkey pinscher, monkey dog",
|
| 265 |
+
"253": "basenji",
|
| 266 |
+
"254": "pug, pug-dog",
|
| 267 |
+
"255": "Leonberg",
|
| 268 |
+
"256": "Newfoundland, Newfoundland dog",
|
| 269 |
+
"257": "Great Pyrenees",
|
| 270 |
+
"258": "Samoyed, Samoyede",
|
| 271 |
+
"259": "Pomeranian",
|
| 272 |
+
"260": "chow, chow chow",
|
| 273 |
+
"261": "keeshond",
|
| 274 |
+
"262": "Brabancon griffon",
|
| 275 |
+
"263": "Pembroke, Pembroke Welsh corgi",
|
| 276 |
+
"264": "Cardigan, Cardigan Welsh corgi",
|
| 277 |
+
"265": "toy poodle",
|
| 278 |
+
"266": "miniature poodle",
|
| 279 |
+
"267": "standard poodle",
|
| 280 |
+
"268": "Mexican hairless",
|
| 281 |
+
"269": "timber wolf, grey wolf, gray wolf, Canis lupus",
|
| 282 |
+
"270": "white wolf, Arctic wolf, Canis lupus tundrarum",
|
| 283 |
+
"271": "red wolf, maned wolf, Canis rufus, Canis niger",
|
| 284 |
+
"272": "coyote, prairie wolf, brush wolf, Canis latrans",
|
| 285 |
+
"273": "dingo, warrigal, warragal, Canis dingo",
|
| 286 |
+
"274": "dhole, Cuon alpinus",
|
| 287 |
+
"275": "African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus",
|
| 288 |
+
"276": "hyena, hyaena",
|
| 289 |
+
"277": "red fox, Vulpes vulpes",
|
| 290 |
+
"278": "kit fox, Vulpes macrotis",
|
| 291 |
+
"279": "Arctic fox, white fox, Alopex lagopus",
|
| 292 |
+
"280": "grey fox, gray fox, Urocyon cinereoargenteus",
|
| 293 |
+
"281": "tabby, tabby cat",
|
| 294 |
+
"282": "tiger cat",
|
| 295 |
+
"283": "Persian cat",
|
| 296 |
+
"284": "Siamese cat, Siamese",
|
| 297 |
+
"285": "Egyptian cat",
|
| 298 |
+
"286": "cougar, puma, catamount, mountain lion, painter, panther, Felis concolor",
|
| 299 |
+
"287": "lynx, catamount",
|
| 300 |
+
"288": "leopard, Panthera pardus",
|
| 301 |
+
"289": "snow leopard, ounce, Panthera uncia",
|
| 302 |
+
"290": "jaguar, panther, Panthera onca, Felis onca",
|
| 303 |
+
"291": "lion, king of beasts, Panthera leo",
|
| 304 |
+
"292": "tiger, Panthera tigris",
|
| 305 |
+
"293": "cheetah, chetah, Acinonyx jubatus",
|
| 306 |
+
"294": "brown bear, bruin, Ursus arctos",
|
| 307 |
+
"295": "American black bear, black bear, Ursus americanus, Euarctos americanus",
|
| 308 |
+
"296": "ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus",
|
| 309 |
+
"297": "sloth bear, Melursus ursinus, Ursus ursinus",
|
| 310 |
+
"298": "mongoose",
|
| 311 |
+
"299": "meerkat, mierkat",
|
| 312 |
+
"300": "tiger beetle",
|
| 313 |
+
"301": "ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle",
|
| 314 |
+
"302": "ground beetle, carabid beetle",
|
| 315 |
+
"303": "long-horned beetle, longicorn, longicorn beetle",
|
| 316 |
+
"304": "leaf beetle, chrysomelid",
|
| 317 |
+
"305": "dung beetle",
|
| 318 |
+
"306": "rhinoceros beetle",
|
| 319 |
+
"307": "weevil",
|
| 320 |
+
"308": "fly",
|
| 321 |
+
"309": "bee",
|
| 322 |
+
"310": "ant, emmet, pismire",
|
| 323 |
+
"311": "grasshopper, hopper",
|
| 324 |
+
"312": "cricket",
|
| 325 |
+
"313": "walking stick, walkingstick, stick insect",
|
| 326 |
+
"314": "cockroach, roach",
|
| 327 |
+
"315": "mantis, mantid",
|
| 328 |
+
"316": "cicada, cicala",
|
| 329 |
+
"317": "leafhopper",
|
| 330 |
+
"318": "lacewing, lacewing fly",
|
| 331 |
+
"319": "dragonfly, darning needle, devils darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk",
|
| 332 |
+
"320": "damselfly",
|
| 333 |
+
"321": "admiral",
|
| 334 |
+
"322": "ringlet, ringlet butterfly",
|
| 335 |
+
"323": "monarch, monarch butterfly, milkweed butterfly, Danaus plexippus",
|
| 336 |
+
"324": "cabbage butterfly",
|
| 337 |
+
"325": "sulphur butterfly, sulfur butterfly",
|
| 338 |
+
"326": "lycaenid, lycaenid butterfly",
|
| 339 |
+
"327": "starfish, sea star",
|
| 340 |
+
"328": "sea urchin",
|
| 341 |
+
"329": "sea cucumber, holothurian",
|
| 342 |
+
"330": "wood rabbit, cottontail, cottontail rabbit",
|
| 343 |
+
"331": "hare",
|
| 344 |
+
"332": "Angora, Angora rabbit",
|
| 345 |
+
"333": "hamster",
|
| 346 |
+
"334": "porcupine, hedgehog",
|
| 347 |
+
"335": "fox squirrel, eastern fox squirrel, Sciurus niger",
|
| 348 |
+
"336": "marmot",
|
| 349 |
+
"337": "beaver",
|
| 350 |
+
"338": "guinea pig, Cavia cobaya",
|
| 351 |
+
"339": "sorrel",
|
| 352 |
+
"340": "zebra",
|
| 353 |
+
"341": "hog, pig, grunter, squealer, Sus scrofa",
|
| 354 |
+
"342": "wild boar, boar, Sus scrofa",
|
| 355 |
+
"343": "warthog",
|
| 356 |
+
"344": "hippopotamus, hippo, river horse, Hippopotamus amphibius",
|
| 357 |
+
"345": "ox",
|
| 358 |
+
"346": "water buffalo, water ox, Asiatic buffalo, Bubalus bubalis",
|
| 359 |
+
"347": "bison",
|
| 360 |
+
"348": "ram, tup",
|
| 361 |
+
"349": "bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis",
|
| 362 |
+
"350": "ibex, Capra ibex",
|
| 363 |
+
"351": "hartebeest",
|
| 364 |
+
"352": "impala, Aepyceros melampus",
|
| 365 |
+
"353": "gazelle",
|
| 366 |
+
"354": "Arabian camel, dromedary, Camelus dromedarius",
|
| 367 |
+
"355": "llama",
|
| 368 |
+
"356": "weasel",
|
| 369 |
+
"357": "mink",
|
| 370 |
+
"358": "polecat, fitch, foulmart, foumart, Mustela putorius",
|
| 371 |
+
"359": "black-footed ferret, ferret, Mustela nigripes",
|
| 372 |
+
"360": "otter",
|
| 373 |
+
"361": "skunk, polecat, wood pussy",
|
| 374 |
+
"362": "badger",
|
| 375 |
+
"363": "armadillo",
|
| 376 |
+
"364": "three-toed sloth, ai, Bradypus tridactylus",
|
| 377 |
+
"365": "orangutan, orang, orangutang, Pongo pygmaeus",
|
| 378 |
+
"366": "gorilla, Gorilla gorilla",
|
| 379 |
+
"367": "chimpanzee, chimp, Pan troglodytes",
|
| 380 |
+
"368": "gibbon, Hylobates lar",
|
| 381 |
+
"369": "siamang, Hylobates syndactylus, Symphalangus syndactylus",
|
| 382 |
+
"370": "guenon, guenon monkey",
|
| 383 |
+
"371": "patas, hussar monkey, Erythrocebus patas",
|
| 384 |
+
"372": "baboon",
|
| 385 |
+
"373": "macaque",
|
| 386 |
+
"374": "langur",
|
| 387 |
+
"375": "colobus, colobus monkey",
|
| 388 |
+
"376": "proboscis monkey, Nasalis larvatus",
|
| 389 |
+
"377": "marmoset",
|
| 390 |
+
"378": "capuchin, ringtail, Cebus capucinus",
|
| 391 |
+
"379": "howler monkey, howler",
|
| 392 |
+
"380": "titi, titi monkey",
|
| 393 |
+
"381": "spider monkey, Ateles geoffroyi",
|
| 394 |
+
"382": "squirrel monkey, Saimiri sciureus",
|
| 395 |
+
"383": "Madagascar cat, ring-tailed lemur, Lemur catta",
|
| 396 |
+
"384": "indri, indris, Indri indri, Indri brevicaudatus",
|
| 397 |
+
"385": "Indian elephant, Elephas maximus",
|
| 398 |
+
"386": "African elephant, Loxodonta africana",
|
| 399 |
+
"387": "lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens",
|
| 400 |
+
"388": "giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca",
|
| 401 |
+
"389": "barracouta, snoek",
|
| 402 |
+
"390": "eel",
|
| 403 |
+
"391": "coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch",
|
| 404 |
+
"392": "rock beauty, Holocanthus tricolor",
|
| 405 |
+
"393": "anemone fish",
|
| 406 |
+
"394": "sturgeon",
|
| 407 |
+
"395": "gar, garfish, garpike, billfish, Lepisosteus osseus",
|
| 408 |
+
"396": "lionfish",
|
| 409 |
+
"397": "puffer, pufferfish, blowfish, globefish",
|
| 410 |
+
"398": "abacus",
|
| 411 |
+
"399": "abaya",
|
| 412 |
+
"400": "academic gown, academic robe, judge robe",
|
| 413 |
+
"401": "accordion, piano accordion, squeeze box",
|
| 414 |
+
"402": "acoustic guitar",
|
| 415 |
+
"403": "aircraft carrier, carrier, flattop, attack aircraft carrier",
|
| 416 |
+
"404": "airliner",
|
| 417 |
+
"405": "airship, dirigible",
|
| 418 |
+
"406": "altar",
|
| 419 |
+
"407": "ambulance",
|
| 420 |
+
"408": "amphibian, amphibious vehicle",
|
| 421 |
+
"409": "analog clock",
|
| 422 |
+
"410": "apiary, bee house",
|
| 423 |
+
"411": "apron",
|
| 424 |
+
"412": "ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin",
|
| 425 |
+
"413": "assault rifle, assault gun",
|
| 426 |
+
"414": "backpack, back pack, knapsack, packsack, rucksack, haversack",
|
| 427 |
+
"415": "bakery, bakeshop, bakehouse",
|
| 428 |
+
"416": "balance beam, beam",
|
| 429 |
+
"417": "balloon",
|
| 430 |
+
"418": "ballpoint, ballpoint pen, ballpen, Biro",
|
| 431 |
+
"419": "Band Aid",
|
| 432 |
+
"420": "banjo",
|
| 433 |
+
"421": "bannister, banister, balustrade, balusters, handrail",
|
| 434 |
+
"422": "barbell",
|
| 435 |
+
"423": "barber chair",
|
| 436 |
+
"424": "barbershop",
|
| 437 |
+
"425": "barn",
|
| 438 |
+
"426": "barometer",
|
| 439 |
+
"427": "barrel, cask",
|
| 440 |
+
"428": "barrow, garden cart, lawn cart, wheelbarrow",
|
| 441 |
+
"429": "baseball",
|
| 442 |
+
"430": "basketball",
|
| 443 |
+
"431": "bassinet",
|
| 444 |
+
"432": "bassoon",
|
| 445 |
+
"433": "bathing cap, swimming cap",
|
| 446 |
+
"434": "bath towel",
|
| 447 |
+
"435": "bathtub, bathing tub, bath, tub",
|
| 448 |
+
"436": "beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon",
|
| 449 |
+
"437": "beacon, lighthouse, beacon light, pharos",
|
| 450 |
+
"438": "beaker",
|
| 451 |
+
"439": "bearskin, busby, shako",
|
| 452 |
+
"440": "beer bottle",
|
| 453 |
+
"441": "beer glass",
|
| 454 |
+
"442": "bell cote, bell cot",
|
| 455 |
+
"443": "bib",
|
| 456 |
+
"444": "bicycle-built-for-two, tandem bicycle, tandem",
|
| 457 |
+
"445": "bikini, two-piece",
|
| 458 |
+
"446": "binder, ring-binder",
|
| 459 |
+
"447": "binoculars, field glasses, opera glasses",
|
| 460 |
+
"448": "birdhouse",
|
| 461 |
+
"449": "boathouse",
|
| 462 |
+
"450": "bobsled, bobsleigh, bob",
|
| 463 |
+
"451": "bolo tie, bolo, bola tie, bola",
|
| 464 |
+
"452": "bonnet, poke bonnet",
|
| 465 |
+
"453": "bookcase",
|
| 466 |
+
"454": "bookshop, bookstore, bookstall",
|
| 467 |
+
"455": "bottlecap",
|
| 468 |
+
"456": "bow",
|
| 469 |
+
"457": "bow tie, bow-tie, bowtie",
|
| 470 |
+
"458": "brass, memorial tablet, plaque",
|
| 471 |
+
"459": "brassiere, bra, bandeau",
|
| 472 |
+
"460": "breakwater, groin, groyne, mole, bulwark, seawall, jetty",
|
| 473 |
+
"461": "breastplate, aegis, egis",
|
| 474 |
+
"462": "broom",
|
| 475 |
+
"463": "bucket, pail",
|
| 476 |
+
"464": "buckle",
|
| 477 |
+
"465": "bulletproof vest",
|
| 478 |
+
"466": "bullet train, bullet",
|
| 479 |
+
"467": "butcher shop, meat market",
|
| 480 |
+
"468": "cab, hack, taxi, taxicab",
|
| 481 |
+
"469": "caldron, cauldron",
|
| 482 |
+
"470": "candle, taper, wax light",
|
| 483 |
+
"471": "cannon",
|
| 484 |
+
"472": "canoe",
|
| 485 |
+
"473": "can opener, tin opener",
|
| 486 |
+
"474": "cardigan",
|
| 487 |
+
"475": "car mirror",
|
| 488 |
+
"476": "carousel, carrousel, merry-go-round, roundabout, whirligig",
|
| 489 |
+
"477": "carpenters kit, tool kit",
|
| 490 |
+
"478": "carton",
|
| 491 |
+
"479": "car wheel",
|
| 492 |
+
"480": "cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM",
|
| 493 |
+
"481": "cassette",
|
| 494 |
+
"482": "cassette player",
|
| 495 |
+
"483": "castle",
|
| 496 |
+
"484": "catamaran",
|
| 497 |
+
"485": "CD player",
|
| 498 |
+
"486": "cello, violoncello",
|
| 499 |
+
"487": "cellular telephone, cellular phone, cellphone, cell, mobile phone",
|
| 500 |
+
"488": "chain",
|
| 501 |
+
"489": "chainlink fence",
|
| 502 |
+
"490": "chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour",
|
| 503 |
+
"491": "chain saw, chainsaw",
|
| 504 |
+
"492": "chest",
|
| 505 |
+
"493": "chiffonier, commode",
|
| 506 |
+
"494": "chime, bell, gong",
|
| 507 |
+
"495": "china cabinet, china closet",
|
| 508 |
+
"496": "Christmas stocking",
|
| 509 |
+
"497": "church, church building",
|
| 510 |
+
"498": "cinema, movie theater, movie theatre, movie house, picture palace",
|
| 511 |
+
"499": "cleaver, meat cleaver, chopper",
|
| 512 |
+
"500": "cliff dwelling",
|
| 513 |
+
"501": "cloak",
|
| 514 |
+
"502": "clog, geta, patten, sabot",
|
| 515 |
+
"503": "cocktail shaker",
|
| 516 |
+
"504": "coffee mug",
|
| 517 |
+
"505": "coffeepot",
|
| 518 |
+
"506": "coil, spiral, volute, whorl, helix",
|
| 519 |
+
"507": "combination lock",
|
| 520 |
+
"508": "computer keyboard, keypad",
|
| 521 |
+
"509": "confectionery, confectionary, candy store",
|
| 522 |
+
"510": "container ship, containership, container vessel",
|
| 523 |
+
"511": "convertible",
|
| 524 |
+
"512": "corkscrew, bottle screw",
|
| 525 |
+
"513": "cornet, horn, trumpet, trump",
|
| 526 |
+
"514": "cowboy boot",
|
| 527 |
+
"515": "cowboy hat, ten-gallon hat",
|
| 528 |
+
"516": "cradle",
|
| 529 |
+
"517": "crane",
|
| 530 |
+
"518": "crash helmet",
|
| 531 |
+
"519": "crate",
|
| 532 |
+
"520": "crib, cot",
|
| 533 |
+
"521": "Crock Pot",
|
| 534 |
+
"522": "croquet ball",
|
| 535 |
+
"523": "crutch",
|
| 536 |
+
"524": "cuirass",
|
| 537 |
+
"525": "dam, dike, dyke",
|
| 538 |
+
"526": "desk",
|
| 539 |
+
"527": "desktop computer",
|
| 540 |
+
"528": "dial telephone, dial phone",
|
| 541 |
+
"529": "diaper, nappy, napkin",
|
| 542 |
+
"530": "digital clock",
|
| 543 |
+
"531": "digital watch",
|
| 544 |
+
"532": "dining table, board",
|
| 545 |
+
"533": "dishrag, dishcloth",
|
| 546 |
+
"534": "dishwasher, dish washer, dishwashing machine",
|
| 547 |
+
"535": "disk brake, disc brake",
|
| 548 |
+
"536": "dock, dockage, docking facility",
|
| 549 |
+
"537": "dogsled, dog sled, dog sleigh",
|
| 550 |
+
"538": "dome",
|
| 551 |
+
"539": "doormat, welcome mat",
|
| 552 |
+
"540": "drilling platform, offshore rig",
|
| 553 |
+
"541": "drum, membranophone, tympan",
|
| 554 |
+
"542": "drumstick",
|
| 555 |
+
"543": "dumbbell",
|
| 556 |
+
"544": "Dutch oven",
|
| 557 |
+
"545": "electric fan, blower",
|
| 558 |
+
"546": "electric guitar",
|
| 559 |
+
"547": "electric locomotive",
|
| 560 |
+
"548": "entertainment center",
|
| 561 |
+
"549": "envelope",
|
| 562 |
+
"550": "espresso maker",
|
| 563 |
+
"551": "face powder",
|
| 564 |
+
"552": "feather boa, boa",
|
| 565 |
+
"553": "file, file cabinet, filing cabinet",
|
| 566 |
+
"554": "fireboat",
|
| 567 |
+
"555": "fire engine, fire truck",
|
| 568 |
+
"556": "fire screen, fireguard",
|
| 569 |
+
"557": "flagpole, flagstaff",
|
| 570 |
+
"558": "flute, transverse flute",
|
| 571 |
+
"559": "folding chair",
|
| 572 |
+
"560": "football helmet",
|
| 573 |
+
"561": "forklift",
|
| 574 |
+
"562": "fountain",
|
| 575 |
+
"563": "fountain pen",
|
| 576 |
+
"564": "four-poster",
|
| 577 |
+
"565": "freight car",
|
| 578 |
+
"566": "French horn, horn",
|
| 579 |
+
"567": "frying pan, frypan, skillet",
|
| 580 |
+
"568": "fur coat",
|
| 581 |
+
"569": "garbage truck, dustcart",
|
| 582 |
+
"570": "gasmask, respirator, gas helmet",
|
| 583 |
+
"571": "gas pump, gasoline pump, petrol pump, island dispenser",
|
| 584 |
+
"572": "goblet",
|
| 585 |
+
"573": "go-kart",
|
| 586 |
+
"574": "golf ball",
|
| 587 |
+
"575": "golfcart, golf cart",
|
| 588 |
+
"576": "gondola",
|
| 589 |
+
"577": "gong, tam-tam",
|
| 590 |
+
"578": "gown",
|
| 591 |
+
"579": "grand piano, grand",
|
| 592 |
+
"580": "greenhouse, nursery, glasshouse",
|
| 593 |
+
"581": "grille, radiator grille",
|
| 594 |
+
"582": "grocery store, grocery, food market, market",
|
| 595 |
+
"583": "guillotine",
|
| 596 |
+
"584": "hair slide",
|
| 597 |
+
"585": "hair spray",
|
| 598 |
+
"586": "half track",
|
| 599 |
+
"587": "hammer",
|
| 600 |
+
"588": "hamper",
|
| 601 |
+
"589": "hand blower, blow dryer, blow drier, hair dryer, hair drier",
|
| 602 |
+
"590": "hand-held computer, hand-held microcomputer",
|
| 603 |
+
"591": "handkerchief, hankie, hanky, hankey",
|
| 604 |
+
"592": "hard disc, hard disk, fixed disk",
|
| 605 |
+
"593": "harmonica, mouth organ, harp, mouth harp",
|
| 606 |
+
"594": "harp",
|
| 607 |
+
"595": "harvester, reaper",
|
| 608 |
+
"596": "hatchet",
|
| 609 |
+
"597": "holster",
|
| 610 |
+
"598": "home theater, home theatre",
|
| 611 |
+
"599": "honeycomb",
|
| 612 |
+
"600": "hook, claw",
|
| 613 |
+
"601": "hoopskirt, crinoline",
|
| 614 |
+
"602": "horizontal bar, high bar",
|
| 615 |
+
"603": "horse cart, horse-cart",
|
| 616 |
+
"604": "hourglass",
|
| 617 |
+
"605": "iPod",
|
| 618 |
+
"606": "iron, smoothing iron",
|
| 619 |
+
"607": "jack-o-lantern",
|
| 620 |
+
"608": "jean, blue jean, denim",
|
| 621 |
+
"609": "jeep, landrover",
|
| 622 |
+
"610": "jersey, T-shirt, tee shirt",
|
| 623 |
+
"611": "jigsaw puzzle",
|
| 624 |
+
"612": "jinrikisha, ricksha, rickshaw",
|
| 625 |
+
"613": "joystick",
|
| 626 |
+
"614": "kimono",
|
| 627 |
+
"615": "knee pad",
|
| 628 |
+
"616": "knot",
|
| 629 |
+
"617": "lab coat, laboratory coat",
|
| 630 |
+
"618": "ladle",
|
| 631 |
+
"619": "lampshade, lamp shade",
|
| 632 |
+
"620": "laptop, laptop computer",
|
| 633 |
+
"621": "lawn mower, mower",
|
| 634 |
+
"622": "lens cap, lens cover",
|
| 635 |
+
"623": "letter opener, paper knife, paperknife",
|
| 636 |
+
"624": "library",
|
| 637 |
+
"625": "lifeboat",
|
| 638 |
+
"626": "lighter, light, igniter, ignitor",
|
| 639 |
+
"627": "limousine, limo",
|
| 640 |
+
"628": "liner, ocean liner",
|
| 641 |
+
"629": "lipstick, lip rouge",
|
| 642 |
+
"630": "Loafer",
|
| 643 |
+
"631": "lotion",
|
| 644 |
+
"632": "loudspeaker, speaker, speaker unit, loudspeaker system, speaker system",
|
| 645 |
+
"633": "loupe, jewelers loupe",
|
| 646 |
+
"634": "lumbermill, sawmill",
|
| 647 |
+
"635": "magnetic compass",
|
| 648 |
+
"636": "mailbag, postbag",
|
| 649 |
+
"637": "mailbox, letter box",
|
| 650 |
+
"638": "maillot",
|
| 651 |
+
"639": "maillot, tank suit",
|
| 652 |
+
"640": "manhole cover",
|
| 653 |
+
"641": "maraca",
|
| 654 |
+
"642": "marimba, xylophone",
|
| 655 |
+
"643": "mask",
|
| 656 |
+
"644": "matchstick",
|
| 657 |
+
"645": "maypole",
|
| 658 |
+
"646": "maze, labyrinth",
|
| 659 |
+
"647": "measuring cup",
|
| 660 |
+
"648": "medicine chest, medicine cabinet",
|
| 661 |
+
"649": "megalith, megalithic structure",
|
| 662 |
+
"650": "microphone, mike",
|
| 663 |
+
"651": "microwave, microwave oven",
|
| 664 |
+
"652": "military uniform",
|
| 665 |
+
"653": "milk can",
|
| 666 |
+
"654": "minibus",
|
| 667 |
+
"655": "miniskirt, mini",
|
| 668 |
+
"656": "minivan",
|
| 669 |
+
"657": "missile",
|
| 670 |
+
"658": "mitten",
|
| 671 |
+
"659": "mixing bowl",
|
| 672 |
+
"660": "mobile home, manufactured home",
|
| 673 |
+
"661": "Model T",
|
| 674 |
+
"662": "modem",
|
| 675 |
+
"663": "monastery",
|
| 676 |
+
"664": "monitor",
|
| 677 |
+
"665": "moped",
|
| 678 |
+
"666": "mortar",
|
| 679 |
+
"667": "mortarboard",
|
| 680 |
+
"668": "mosque",
|
| 681 |
+
"669": "mosquito net",
|
| 682 |
+
"670": "motor scooter, scooter",
|
| 683 |
+
"671": "mountain bike, all-terrain bike, off-roader",
|
| 684 |
+
"672": "mountain tent",
|
| 685 |
+
"673": "mouse, computer mouse",
|
| 686 |
+
"674": "mousetrap",
|
| 687 |
+
"675": "moving van",
|
| 688 |
+
"676": "muzzle",
|
| 689 |
+
"677": "nail",
|
| 690 |
+
"678": "neck brace",
|
| 691 |
+
"679": "necklace",
|
| 692 |
+
"680": "nipple",
|
| 693 |
+
"681": "notebook, notebook computer",
|
| 694 |
+
"682": "obelisk",
|
| 695 |
+
"683": "oboe, hautboy, hautbois",
|
| 696 |
+
"684": "ocarina, sweet potato",
|
| 697 |
+
"685": "odometer, hodometer, mileometer, milometer",
|
| 698 |
+
"686": "oil filter",
|
| 699 |
+
"687": "organ, pipe organ",
|
| 700 |
+
"688": "oscilloscope, scope, cathode-ray oscilloscope, CRO",
|
| 701 |
+
"689": "overskirt",
|
| 702 |
+
"690": "oxcart",
|
| 703 |
+
"691": "oxygen mask",
|
| 704 |
+
"692": "packet",
|
| 705 |
+
"693": "paddle, boat paddle",
|
| 706 |
+
"694": "paddlewheel, paddle wheel",
|
| 707 |
+
"695": "padlock",
|
| 708 |
+
"696": "paintbrush",
|
| 709 |
+
"697": "pajama, pyjama, pjs, jammies",
|
| 710 |
+
"698": "palace",
|
| 711 |
+
"699": "panpipe, pandean pipe, syrinx",
|
| 712 |
+
"700": "paper towel",
|
| 713 |
+
"701": "parachute, chute",
|
| 714 |
+
"702": "parallel bars, bars",
|
| 715 |
+
"703": "park bench",
|
| 716 |
+
"704": "parking meter",
|
| 717 |
+
"705": "passenger car, coach, carriage",
|
| 718 |
+
"706": "patio, terrace",
|
| 719 |
+
"707": "pay-phone, pay-station",
|
| 720 |
+
"708": "pedestal, plinth, footstall",
|
| 721 |
+
"709": "pencil box, pencil case",
|
| 722 |
+
"710": "pencil sharpener",
|
| 723 |
+
"711": "perfume, essence",
|
| 724 |
+
"712": "Petri dish",
|
| 725 |
+
"713": "photocopier",
|
| 726 |
+
"714": "pick, plectrum, plectron",
|
| 727 |
+
"715": "pickelhaube",
|
| 728 |
+
"716": "picket fence, paling",
|
| 729 |
+
"717": "pickup, pickup truck",
|
| 730 |
+
"718": "pier",
|
| 731 |
+
"719": "piggy bank, penny bank",
|
| 732 |
+
"720": "pill bottle",
|
| 733 |
+
"721": "pillow",
|
| 734 |
+
"722": "ping-pong ball",
|
| 735 |
+
"723": "pinwheel",
|
| 736 |
+
"724": "pirate, pirate ship",
|
| 737 |
+
"725": "pitcher, ewer",
|
| 738 |
+
"726": "plane, carpenters plane, woodworking plane",
|
| 739 |
+
"727": "planetarium",
|
| 740 |
+
"728": "plastic bag",
|
| 741 |
+
"729": "plate rack",
|
| 742 |
+
"730": "plow, plough",
|
| 743 |
+
"731": "plunger, plumbers helper",
|
| 744 |
+
"732": "Polaroid camera, Polaroid Land camera",
|
| 745 |
+
"733": "pole",
|
| 746 |
+
"734": "police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria",
|
| 747 |
+
"735": "poncho",
|
| 748 |
+
"736": "pool table, billiard table, snooker table",
|
| 749 |
+
"737": "pop bottle, soda bottle",
|
| 750 |
+
"738": "pot, flowerpot",
|
| 751 |
+
"739": "potters wheel",
|
| 752 |
+
"740": "power drill",
|
| 753 |
+
"741": "prayer rug, prayer mat",
|
| 754 |
+
"742": "printer",
|
| 755 |
+
"743": "prison, prison house",
|
| 756 |
+
"744": "projectile, missile",
|
| 757 |
+
"745": "projector",
|
| 758 |
+
"746": "puck, hockey puck",
|
| 759 |
+
"747": "punching bag, punch bag, punching ball, punchball",
|
| 760 |
+
"748": "purse",
|
| 761 |
+
"749": "quill, quill pen",
|
| 762 |
+
"750": "quilt, comforter, comfort, puff",
|
| 763 |
+
"751": "racer, race car, racing car",
|
| 764 |
+
"752": "racket, racquet",
|
| 765 |
+
"753": "radiator",
|
| 766 |
+
"754": "radio, wireless",
|
| 767 |
+
"755": "radio telescope, radio reflector",
|
| 768 |
+
"756": "rain barrel",
|
| 769 |
+
"757": "recreational vehicle, RV, R.V.",
|
| 770 |
+
"758": "reel",
|
| 771 |
+
"759": "reflex camera",
|
| 772 |
+
"760": "refrigerator, icebox",
|
| 773 |
+
"761": "remote control, remote",
|
| 774 |
+
"762": "restaurant, eating house, eating place, eatery",
|
| 775 |
+
"763": "revolver, six-gun, six-shooter",
|
| 776 |
+
"764": "rifle",
|
| 777 |
+
"765": "rocking chair, rocker",
|
| 778 |
+
"766": "rotisserie",
|
| 779 |
+
"767": "rubber eraser, rubber, pencil eraser",
|
| 780 |
+
"768": "rugby ball",
|
| 781 |
+
"769": "rule, ruler",
|
| 782 |
+
"770": "running shoe",
|
| 783 |
+
"771": "safe",
|
| 784 |
+
"772": "safety pin",
|
| 785 |
+
"773": "saltshaker, salt shaker",
|
| 786 |
+
"774": "sandal",
|
| 787 |
+
"775": "sarong",
|
| 788 |
+
"776": "sax, saxophone",
|
| 789 |
+
"777": "scabbard",
|
| 790 |
+
"778": "scale, weighing machine",
|
| 791 |
+
"779": "school bus",
|
| 792 |
+
"780": "schooner",
|
| 793 |
+
"781": "scoreboard",
|
| 794 |
+
"782": "screen, CRT screen",
|
| 795 |
+
"783": "screw",
|
| 796 |
+
"784": "screwdriver",
|
| 797 |
+
"785": "seat belt, seatbelt",
|
| 798 |
+
"786": "sewing machine",
|
| 799 |
+
"787": "shield, buckler",
|
| 800 |
+
"788": "shoe shop, shoe-shop, shoe store",
|
| 801 |
+
"789": "shoji",
|
| 802 |
+
"790": "shopping basket",
|
| 803 |
+
"791": "shopping cart",
|
| 804 |
+
"792": "shovel",
|
| 805 |
+
"793": "shower cap",
|
| 806 |
+
"794": "shower curtain",
|
| 807 |
+
"795": "ski",
|
| 808 |
+
"796": "ski mask",
|
| 809 |
+
"797": "sleeping bag",
|
| 810 |
+
"798": "slide rule, slipstick",
|
| 811 |
+
"799": "sliding door",
|
| 812 |
+
"800": "slot, one-armed bandit",
|
| 813 |
+
"801": "snorkel",
|
| 814 |
+
"802": "snowmobile",
|
| 815 |
+
"803": "snowplow, snowplough",
|
| 816 |
+
"804": "soap dispenser",
|
| 817 |
+
"805": "soccer ball",
|
| 818 |
+
"806": "sock",
|
| 819 |
+
"807": "solar dish, solar collector, solar furnace",
|
| 820 |
+
"808": "sombrero",
|
| 821 |
+
"809": "soup bowl",
|
| 822 |
+
"810": "space bar",
|
| 823 |
+
"811": "space heater",
|
| 824 |
+
"812": "space shuttle",
|
| 825 |
+
"813": "spatula",
|
| 826 |
+
"814": "speedboat",
|
| 827 |
+
"815": "spider web, spiders web",
|
| 828 |
+
"816": "spindle",
|
| 829 |
+
"817": "sports car, sport car",
|
| 830 |
+
"818": "spotlight, spot",
|
| 831 |
+
"819": "stage",
|
| 832 |
+
"820": "steam locomotive",
|
| 833 |
+
"821": "steel arch bridge",
|
| 834 |
+
"822": "steel drum",
|
| 835 |
+
"823": "stethoscope",
|
| 836 |
+
"824": "stole",
|
| 837 |
+
"825": "stone wall",
|
| 838 |
+
"826": "stopwatch, stop watch",
|
| 839 |
+
"827": "stove",
|
| 840 |
+
"828": "strainer",
|
| 841 |
+
"829": "streetcar, tram, tramcar, trolley, trolley car",
|
| 842 |
+
"830": "stretcher",
|
| 843 |
+
"831": "studio couch, day bed",
|
| 844 |
+
"832": "stupa, tope",
|
| 845 |
+
"833": "submarine, pigboat, sub, U-boat",
|
| 846 |
+
"834": "suit, suit of clothes",
|
| 847 |
+
"835": "sundial",
|
| 848 |
+
"836": "sunglass",
|
| 849 |
+
"837": "sunglasses, dark glasses, shades",
|
| 850 |
+
"838": "sunscreen, sunblock, sun blocker",
|
| 851 |
+
"839": "suspension bridge",
|
| 852 |
+
"840": "swab, swob, mop",
|
| 853 |
+
"841": "sweatshirt",
|
| 854 |
+
"842": "swimming trunks, bathing trunks",
|
| 855 |
+
"843": "swing",
|
| 856 |
+
"844": "switch, electric switch, electrical switch",
|
| 857 |
+
"845": "syringe",
|
| 858 |
+
"846": "table lamp",
|
| 859 |
+
"847": "tank, army tank, armored combat vehicle, armoured combat vehicle",
|
| 860 |
+
"848": "tape player",
|
| 861 |
+
"849": "teapot",
|
| 862 |
+
"850": "teddy, teddy bear",
|
| 863 |
+
"851": "television, television system",
|
| 864 |
+
"852": "tennis ball",
|
| 865 |
+
"853": "thatch, thatched roof",
|
| 866 |
+
"854": "theater curtain, theatre curtain",
|
| 867 |
+
"855": "thimble",
|
| 868 |
+
"856": "thresher, thrasher, threshing machine",
|
| 869 |
+
"857": "throne",
|
| 870 |
+
"858": "tile roof",
|
| 871 |
+
"859": "toaster",
|
| 872 |
+
"860": "tobacco shop, tobacconist shop, tobacconist",
|
| 873 |
+
"861": "toilet seat",
|
| 874 |
+
"862": "torch",
|
| 875 |
+
"863": "totem pole",
|
| 876 |
+
"864": "tow truck, tow car, wrecker",
|
| 877 |
+
"865": "toyshop",
|
| 878 |
+
"866": "tractor",
|
| 879 |
+
"867": "trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi",
|
| 880 |
+
"868": "tray",
|
| 881 |
+
"869": "trench coat",
|
| 882 |
+
"870": "tricycle, trike, velocipede",
|
| 883 |
+
"871": "trimaran",
|
| 884 |
+
"872": "tripod",
|
| 885 |
+
"873": "triumphal arch",
|
| 886 |
+
"874": "trolleybus, trolley coach, trackless trolley",
|
| 887 |
+
"875": "trombone",
|
| 888 |
+
"876": "tub, vat",
|
| 889 |
+
"877": "turnstile",
|
| 890 |
+
"878": "typewriter keyboard",
|
| 891 |
+
"879": "umbrella",
|
| 892 |
+
"880": "unicycle, monocycle",
|
| 893 |
+
"881": "upright, upright piano",
|
| 894 |
+
"882": "vacuum, vacuum cleaner",
|
| 895 |
+
"883": "vase",
|
| 896 |
+
"884": "vault",
|
| 897 |
+
"885": "velvet",
|
| 898 |
+
"886": "vending machine",
|
| 899 |
+
"887": "vestment",
|
| 900 |
+
"888": "viaduct",
|
| 901 |
+
"889": "violin, fiddle",
|
| 902 |
+
"890": "volleyball",
|
| 903 |
+
"891": "waffle iron",
|
| 904 |
+
"892": "wall clock",
|
| 905 |
+
"893": "wallet, billfold, notecase, pocketbook",
|
| 906 |
+
"894": "wardrobe, closet, press",
|
| 907 |
+
"895": "warplane, military plane",
|
| 908 |
+
"896": "washbasin, handbasin, washbowl, lavabo, wash-hand basin",
|
| 909 |
+
"897": "washer, automatic washer, washing machine",
|
| 910 |
+
"898": "water bottle",
|
| 911 |
+
"899": "water jug",
|
| 912 |
+
"900": "water tower",
|
| 913 |
+
"901": "whiskey jug",
|
| 914 |
+
"902": "whistle",
|
| 915 |
+
"903": "wig",
|
| 916 |
+
"904": "window screen",
|
| 917 |
+
"905": "window shade",
|
| 918 |
+
"906": "Windsor tie",
|
| 919 |
+
"907": "wine bottle",
|
| 920 |
+
"908": "wing",
|
| 921 |
+
"909": "wok",
|
| 922 |
+
"910": "wooden spoon",
|
| 923 |
+
"911": "wool, woolen, woollen",
|
| 924 |
+
"912": "worm fence, snake fence, snake-rail fence, Virginia fence",
|
| 925 |
+
"913": "wreck",
|
| 926 |
+
"914": "yawl",
|
| 927 |
+
"915": "yurt",
|
| 928 |
+
"916": "web site, website, internet site, site",
|
| 929 |
+
"917": "comic book",
|
| 930 |
+
"918": "crossword puzzle, crossword",
|
| 931 |
+
"919": "street sign",
|
| 932 |
+
"920": "traffic light, traffic signal, stoplight",
|
| 933 |
+
"921": "book jacket, dust cover, dust jacket, dust wrapper",
|
| 934 |
+
"922": "menu",
|
| 935 |
+
"923": "plate",
|
| 936 |
+
"924": "guacamole",
|
| 937 |
+
"925": "consomme",
|
| 938 |
+
"926": "hot pot, hotpot",
|
| 939 |
+
"927": "trifle",
|
| 940 |
+
"928": "ice cream, icecream",
|
| 941 |
+
"929": "ice lolly, lolly, lollipop, popsicle",
|
| 942 |
+
"930": "French loaf",
|
| 943 |
+
"931": "bagel, beigel",
|
| 944 |
+
"932": "pretzel",
|
| 945 |
+
"933": "cheeseburger",
|
| 946 |
+
"934": "hotdog, hot dog, red hot",
|
| 947 |
+
"935": "mashed potato",
|
| 948 |
+
"936": "head cabbage",
|
| 949 |
+
"937": "broccoli",
|
| 950 |
+
"938": "cauliflower",
|
| 951 |
+
"939": "zucchini, courgette",
|
| 952 |
+
"940": "spaghetti squash",
|
| 953 |
+
"941": "acorn squash",
|
| 954 |
+
"942": "butternut squash",
|
| 955 |
+
"943": "cucumber, cuke",
|
| 956 |
+
"944": "artichoke, globe artichoke",
|
| 957 |
+
"945": "bell pepper",
|
| 958 |
+
"946": "cardoon",
|
| 959 |
+
"947": "mushroom",
|
| 960 |
+
"948": "Granny Smith",
|
| 961 |
+
"949": "strawberry",
|
| 962 |
+
"950": "orange",
|
| 963 |
+
"951": "lemon",
|
| 964 |
+
"952": "fig",
|
| 965 |
+
"953": "pineapple, ananas",
|
| 966 |
+
"954": "banana",
|
| 967 |
+
"955": "jackfruit, jak, jack",
|
| 968 |
+
"956": "custard apple",
|
| 969 |
+
"957": "pomegranate",
|
| 970 |
+
"958": "hay",
|
| 971 |
+
"959": "carbonara",
|
| 972 |
+
"960": "chocolate sauce, chocolate syrup",
|
| 973 |
+
"961": "dough",
|
| 974 |
+
"962": "meat loaf, meatloaf",
|
| 975 |
+
"963": "pizza, pizza pie",
|
| 976 |
+
"964": "potpie",
|
| 977 |
+
"965": "burrito",
|
| 978 |
+
"966": "red wine",
|
| 979 |
+
"967": "espresso",
|
| 980 |
+
"968": "cup",
|
| 981 |
+
"969": "eggnog",
|
| 982 |
+
"970": "alp",
|
| 983 |
+
"971": "bubble",
|
| 984 |
+
"972": "cliff, drop, drop-off",
|
| 985 |
+
"973": "coral reef",
|
| 986 |
+
"974": "geyser",
|
| 987 |
+
"975": "lakeside, lakeshore",
|
| 988 |
+
"976": "promontory, headland, head, foreland",
|
| 989 |
+
"977": "sandbar, sand bar",
|
| 990 |
+
"978": "seashore, coast, seacoast, sea-coast",
|
| 991 |
+
"979": "valley, vale",
|
| 992 |
+
"980": "volcano",
|
| 993 |
+
"981": "ballplayer, baseball player",
|
| 994 |
+
"982": "groom, bridegroom",
|
| 995 |
+
"983": "scuba diver",
|
| 996 |
+
"984": "rapeseed",
|
| 997 |
+
"985": "daisy",
|
| 998 |
+
"986": "yellow ladys slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum",
|
| 999 |
+
"987": "corn",
|
| 1000 |
+
"988": "acorn",
|
| 1001 |
+
"989": "hip, rose hip, rosehip",
|
| 1002 |
+
"990": "buckeye, horse chestnut, conker",
|
| 1003 |
+
"991": "coral fungus",
|
| 1004 |
+
"992": "agaric",
|
| 1005 |
+
"993": "gyromitra",
|
| 1006 |
+
"994": "stinkhorn, carrion fungus",
|
| 1007 |
+
"995": "earthstar",
|
| 1008 |
+
"996": "hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa",
|
| 1009 |
+
"997": "bolete",
|
| 1010 |
+
"998": "ear, spike, capitulum",
|
| 1011 |
+
"999": "toilet tissue, toilet paper, bathroom tissue"
|
| 1012 |
+
},
|
| 1013 |
+
"scheduler": [
|
| 1014 |
+
"scheduling_flow_match_pae",
|
| 1015 |
+
"PAEFlowMatchScheduler"
|
| 1016 |
+
],
|
| 1017 |
+
"transformers": [
|
| 1018 |
+
"transformer_lightning_dit",
|
| 1019 |
+
"LightningDiT2DModel"
|
| 1020 |
+
]
|
| 1021 |
+
}
|
pae-dinov2-large-d32/pipeline.py
ADDED
|
@@ -0,0 +1,530 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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eline: PAEPipeline.
|
| 2 |
+
Load with native Hugging Face diffusers and trust_remote_code=True.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
# Copyright 2026 The HuggingFace Team and PAE authors. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import inspect
|
| 24 |
+
import json
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 27 |
+
|
| 28 |
+
import torch
|
| 29 |
+
|
| 30 |
+
from diffusers.image_processor import VaeImageProcessor
|
| 31 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
|
| 32 |
+
from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers
|
| 33 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 34 |
+
|
| 35 |
+
EXAMPLE_DOC_STRING = """
|
| 36 |
+
Examples:
|
| 37 |
+
```py
|
| 38 |
+
>>> from pathlib import Path
|
| 39 |
+
>>> from diffusers import DiffusionPipeline
|
| 40 |
+
>>> import torch
|
| 41 |
+
|
| 42 |
+
>>> model_dir = Path("./pae-dinov2-large-d32").resolve()
|
| 43 |
+
>>> pipe = DiffusionPipeline.from_pretrained(
|
| 44 |
+
... str(model_dir),
|
| 45 |
+
... local_files_only=True,
|
| 46 |
+
... custom_pipeline=str(model_dir / "pipeline.py"),
|
| 47 |
+
... trust_remote_code=True,
|
| 48 |
+
... torch_dtype=torch.bfloat16,
|
| 49 |
+
... )
|
| 50 |
+
>>> pipe.to("cuda")
|
| 51 |
+
|
| 52 |
+
>>> print(pipe.id2label[207])
|
| 53 |
+
>>> print(pipe.get_label_ids("golden retriever"))
|
| 54 |
+
|
| 55 |
+
>>> generator = torch.Generator(device="cuda").manual_seed(42)
|
| 56 |
+
>>> image = pipe(
|
| 57 |
+
... class_labels="golden retriever",
|
| 58 |
+
... generator=generator,
|
| 59 |
+
... ).images[0]
|
| 60 |
+
```
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class PAEPipeline(DiffusionPipeline):
|
| 65 |
+
r"""
|
| 66 |
+
Pipeline for class-conditional image generation with PAE tokenizers and LightningDiT.
|
| 67 |
+
|
| 68 |
+
This model inherits from [`DiffusionPipeline`]. Components are stored in separate subfolders
|
| 69 |
+
(`transformers/`, `scheduler/`, `decoder/`) and loaded via `DiffusionPipeline.from_pretrained`.
|
| 70 |
+
|
| 71 |
+
Parameters:
|
| 72 |
+
transformers ([`LightningDiT2DModel`]):
|
| 73 |
+
Class-conditional LightningDiT transformer that predicts flow-matching velocity in PAE latent space.
|
| 74 |
+
scheduler ([`PAEFlowMatchScheduler`]):
|
| 75 |
+
Flow-matching ODE/SDE scheduler. Other [`KarrasDiffusionSchedulers`] can be swapped at inference time
|
| 76 |
+
when their `step` API is compatible.
|
| 77 |
+
decoder ([`PAEDecoder`]):
|
| 78 |
+
Prior-Aligned Autoencoder decoder stack (decompressor + pixel decoder).
|
| 79 |
+
|
| 80 |
+
ImageNet `id2label` mappings are read lazily from `model_index.json` when label helpers are used.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
model_cpu_offload_seq = "transformers->decoder"
|
| 84 |
+
_optional_components = ["decoder"]
|
| 85 |
+
|
| 86 |
+
@staticmethod
|
| 87 |
+
def prepare_extra_step_kwargs(
|
| 88 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 89 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 90 |
+
eta: Optional[float] = None,
|
| 91 |
+
) -> Dict[str, object]:
|
| 92 |
+
r"""
|
| 93 |
+
Build kwargs forwarded to `scheduler.step` when supported.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
scheduler:
|
| 97 |
+
Active diffusion scheduler instance.
|
| 98 |
+
generator:
|
| 99 |
+
Optional RNG passed through to stochastic scheduler steps.
|
| 100 |
+
eta:
|
| 101 |
+
Optional DDIM-style eta when the scheduler accepts it.
|
| 102 |
+
"""
|
| 103 |
+
kwargs: Dict[str, object] = {}
|
| 104 |
+
step_params = set(inspect.signature(scheduler.step).parameters.keys())
|
| 105 |
+
if "generator" in step_params:
|
| 106 |
+
kwargs["generator"] = generator
|
| 107 |
+
if eta is not None and "eta" in step_params:
|
| 108 |
+
kwargs["eta"] = eta
|
| 109 |
+
return kwargs
|
| 110 |
+
|
| 111 |
+
def __init__(
|
| 112 |
+
self,
|
| 113 |
+
transformers,
|
| 114 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 115 |
+
decoder=None,
|
| 116 |
+
transformer=None,
|
| 117 |
+
) -> None:
|
| 118 |
+
if transformer is not None and transformers is None:
|
| 119 |
+
transformers = transformer
|
| 120 |
+
super().__init__()
|
| 121 |
+
self.register_modules(transformers=transformers, scheduler=scheduler, decoder=decoder)
|
| 122 |
+
# PAE decoders already return pixels in [0, 1]; disable VAE-style [-1, 1] denormalization.
|
| 123 |
+
self.image_processor = VaeImageProcessor(do_normalize=False)
|
| 124 |
+
self._id2label: Dict[int, str] = {}
|
| 125 |
+
self.labels: Dict[str, int] = {}
|
| 126 |
+
self._labels_loaded_from_model_index = False
|
| 127 |
+
|
| 128 |
+
@property
|
| 129 |
+
def transformer(self):
|
| 130 |
+
"""Backward-compatible alias for `transformers`."""
|
| 131 |
+
return self.transformers
|
| 132 |
+
|
| 133 |
+
@staticmethod
|
| 134 |
+
def _normalize_id2label(id2label: Optional[Dict[Union[int, str], str]]) -> Dict[int, str]:
|
| 135 |
+
if not id2label:
|
| 136 |
+
return {}
|
| 137 |
+
return {int(key): value for key, value in id2label.items()}
|
| 138 |
+
|
| 139 |
+
@staticmethod
|
| 140 |
+
def _read_model_index(variant_path: Optional[str]) -> Dict[str, Any]:
|
| 141 |
+
if not variant_path:
|
| 142 |
+
return {}
|
| 143 |
+
variant_dir = Path(variant_path).resolve()
|
| 144 |
+
model_index_path = variant_dir / "model_index.json"
|
| 145 |
+
if not model_index_path.is_file():
|
| 146 |
+
return {}
|
| 147 |
+
raw = json.loads(model_index_path.read_text(encoding="utf-8"))
|
| 148 |
+
return raw if isinstance(raw, dict) else {}
|
| 149 |
+
|
| 150 |
+
@staticmethod
|
| 151 |
+
def _read_id2label_from_model_index(variant_path: Optional[str]) -> Dict[int, str]:
|
| 152 |
+
id2label = PAEPipeline._read_model_index(variant_path).get("id2label")
|
| 153 |
+
if not isinstance(id2label, dict):
|
| 154 |
+
return {}
|
| 155 |
+
return {int(key): value for key, value in id2label.items()}
|
| 156 |
+
|
| 157 |
+
def _get_downsample_ratio(self) -> int:
|
| 158 |
+
override = getattr(self.config, "downsample_ratio", None)
|
| 159 |
+
if override is not None:
|
| 160 |
+
return int(override)
|
| 161 |
+
|
| 162 |
+
encoder_input_size = None
|
| 163 |
+
if self.decoder is not None:
|
| 164 |
+
encoder_input_size = getattr(self.decoder.config, "encoder_input_size", None)
|
| 165 |
+
|
| 166 |
+
if encoder_input_size is not None:
|
| 167 |
+
return int(encoder_input_size) // int(self.transformers.config.input_size)
|
| 168 |
+
return 16
|
| 169 |
+
|
| 170 |
+
def _resolve_latent_stats(
|
| 171 |
+
self,
|
| 172 |
+
latent_mean: Optional[torch.Tensor],
|
| 173 |
+
latent_std: Optional[torch.Tensor],
|
| 174 |
+
latent_multiplier: Optional[float],
|
| 175 |
+
device: torch.device,
|
| 176 |
+
dtype: torch.dtype,
|
| 177 |
+
) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], float]:
|
| 178 |
+
if latent_mean is not None and latent_std is not None:
|
| 179 |
+
return latent_mean, latent_std, float(latent_multiplier if latent_multiplier is not None else 1.0)
|
| 180 |
+
|
| 181 |
+
decoder_cfg = getattr(self.decoder, "config", None) if self.decoder is not None else None
|
| 182 |
+
if decoder_cfg is not None:
|
| 183 |
+
mean = getattr(decoder_cfg, "latent_mean", None)
|
| 184 |
+
std = getattr(decoder_cfg, "latent_std", None)
|
| 185 |
+
if mean is not None and std is not None:
|
| 186 |
+
multiplier = getattr(decoder_cfg, "latent_multiplier", 1.0)
|
| 187 |
+
mean_tensor = torch.tensor(mean, device=device, dtype=dtype).view(1, -1, 1, 1)
|
| 188 |
+
std_tensor = torch.tensor(std, device=device, dtype=dtype).view(1, -1, 1, 1)
|
| 189 |
+
return mean_tensor, std_tensor, float(multiplier)
|
| 190 |
+
|
| 191 |
+
return latent_mean, latent_std, float(latent_multiplier if latent_multiplier is not None else 1.0)
|
| 192 |
+
|
| 193 |
+
@staticmethod
|
| 194 |
+
def _build_label2id(id2label: Dict[int, str]) -> Dict[str, int]:
|
| 195 |
+
label2id: Dict[str, int] = {}
|
| 196 |
+
for class_id, value in id2label.items():
|
| 197 |
+
for synonym in value.split(","):
|
| 198 |
+
synonym = synonym.strip()
|
| 199 |
+
if synonym:
|
| 200 |
+
label2id[synonym] = int(class_id)
|
| 201 |
+
return dict(sorted(label2id.items()))
|
| 202 |
+
|
| 203 |
+
def _ensure_labels_loaded(self) -> None:
|
| 204 |
+
if self._labels_loaded_from_model_index:
|
| 205 |
+
return
|
| 206 |
+
loaded = self._read_id2label_from_model_index(getattr(self.config, "_name_or_path", None))
|
| 207 |
+
if loaded:
|
| 208 |
+
self._id2label = loaded
|
| 209 |
+
self.labels = self._build_label2id(self._id2label)
|
| 210 |
+
self._labels_loaded_from_model_index = True
|
| 211 |
+
|
| 212 |
+
@property
|
| 213 |
+
def id2label(self) -> Dict[int, str]:
|
| 214 |
+
r"""ImageNet class id to English label string (comma-separated synonyms)."""
|
| 215 |
+
self._ensure_labels_loaded()
|
| 216 |
+
return self._id2label
|
| 217 |
+
|
| 218 |
+
def get_label_ids(self, label: Union[str, List[str]]) -> List[int]:
|
| 219 |
+
r"""
|
| 220 |
+
Map ImageNet label strings to class ids.
|
| 221 |
+
|
| 222 |
+
Args:
|
| 223 |
+
label:
|
| 224 |
+
One or more English label strings. Each string must match a synonym in `id2label`.
|
| 225 |
+
|
| 226 |
+
Returns:
|
| 227 |
+
Matching ImageNet class ids.
|
| 228 |
+
"""
|
| 229 |
+
self._ensure_labels_loaded()
|
| 230 |
+
label2id = self.labels
|
| 231 |
+
if not label2id:
|
| 232 |
+
raise ValueError("No English labels loaded. Ensure `id2label` exists in model_index.json.")
|
| 233 |
+
|
| 234 |
+
if isinstance(label, str):
|
| 235 |
+
label = [label]
|
| 236 |
+
|
| 237 |
+
missing = [item for item in label if item not in label2id]
|
| 238 |
+
if missing:
|
| 239 |
+
preview = ", ".join(list(label2id.keys())[:8])
|
| 240 |
+
raise ValueError(f"Unknown English label(s): {missing}. Example valid labels: {preview}, ...")
|
| 241 |
+
return [label2id[item] for item in label]
|
| 242 |
+
|
| 243 |
+
def _default_image_size(self) -> int:
|
| 244 |
+
return int(self.transformers.config.input_size) * self._get_downsample_ratio()
|
| 245 |
+
|
| 246 |
+
def _normalize_class_labels(
|
| 247 |
+
self,
|
| 248 |
+
class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
|
| 249 |
+
) -> torch.LongTensor:
|
| 250 |
+
if torch.is_tensor(class_labels):
|
| 251 |
+
return class_labels.to(device=self._execution_device, dtype=torch.long).reshape(-1)
|
| 252 |
+
|
| 253 |
+
if isinstance(class_labels, int):
|
| 254 |
+
class_label_ids = [class_labels]
|
| 255 |
+
elif isinstance(class_labels, str):
|
| 256 |
+
class_label_ids = self.get_label_ids(class_labels)
|
| 257 |
+
elif class_labels and isinstance(class_labels[0], str):
|
| 258 |
+
class_label_ids = self.get_label_ids(class_labels)
|
| 259 |
+
else:
|
| 260 |
+
class_label_ids = list(class_labels)
|
| 261 |
+
|
| 262 |
+
return torch.tensor(class_label_ids, device=self._execution_device, dtype=torch.long).reshape(-1)
|
| 263 |
+
|
| 264 |
+
def check_inputs(
|
| 265 |
+
self,
|
| 266 |
+
height: int,
|
| 267 |
+
width: int,
|
| 268 |
+
num_inference_steps: int,
|
| 269 |
+
output_type: str,
|
| 270 |
+
mode: str,
|
| 271 |
+
) -> None:
|
| 272 |
+
if num_inference_steps < 1:
|
| 273 |
+
raise ValueError("num_inference_steps must be >= 1.")
|
| 274 |
+
if output_type not in {"pil", "np", "pt", "latent"}:
|
| 275 |
+
raise ValueError("output_type must be one of: 'pil', 'np', 'pt', 'latent'.")
|
| 276 |
+
if mode not in {"ode", "sde"}:
|
| 277 |
+
raise ValueError("mode must be either 'ode' or 'sde'.")
|
| 278 |
+
|
| 279 |
+
downsample = self._get_downsample_ratio()
|
| 280 |
+
if height % downsample != 0 or width % downsample != 0:
|
| 281 |
+
raise ValueError(
|
| 282 |
+
f"height and width must be divisible by the PAE downsample factor {downsample}."
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
latent_height = height // downsample
|
| 286 |
+
latent_width = width // downsample
|
| 287 |
+
expected_size = int(self.transformers.config.input_size)
|
| 288 |
+
if latent_height != expected_size or latent_width != expected_size:
|
| 289 |
+
raise ValueError(
|
| 290 |
+
f"Requested latent size {(latent_height, latent_width)} does not match the pretrained "
|
| 291 |
+
f"transformer input_size={expected_size}. Use height=width={self._default_image_size()}."
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
def prepare_latents(
|
| 295 |
+
self,
|
| 296 |
+
batch_size: int,
|
| 297 |
+
height: int,
|
| 298 |
+
width: int,
|
| 299 |
+
dtype: torch.dtype,
|
| 300 |
+
device: torch.device,
|
| 301 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 302 |
+
) -> torch.Tensor:
|
| 303 |
+
downsample = self._get_downsample_ratio()
|
| 304 |
+
latent_height = height // downsample
|
| 305 |
+
latent_width = width // downsample
|
| 306 |
+
return randn_tensor(
|
| 307 |
+
(batch_size, self.transformers.config.in_channels, latent_height, latent_width),
|
| 308 |
+
generator=generator,
|
| 309 |
+
device=device,
|
| 310 |
+
dtype=dtype,
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
@staticmethod
|
| 314 |
+
def _denormalize_latents(
|
| 315 |
+
latents: torch.Tensor,
|
| 316 |
+
latent_mean: Optional[torch.Tensor],
|
| 317 |
+
latent_std: Optional[torch.Tensor],
|
| 318 |
+
latent_multiplier: Optional[float],
|
| 319 |
+
) -> torch.Tensor:
|
| 320 |
+
if latent_mean is None or latent_std is None:
|
| 321 |
+
return latents
|
| 322 |
+
multiplier = 1.0 if latent_multiplier is None else float(latent_multiplier)
|
| 323 |
+
mean = latent_mean.to(device=latents.device, dtype=latents.dtype)
|
| 324 |
+
std = latent_std.to(device=latents.device, dtype=latents.dtype)
|
| 325 |
+
return (latents * std) / multiplier + mean
|
| 326 |
+
|
| 327 |
+
@staticmethod
|
| 328 |
+
def _apply_cfg(
|
| 329 |
+
model_output: torch.Tensor,
|
| 330 |
+
guidance_scale: float,
|
| 331 |
+
guidance_active: bool,
|
| 332 |
+
cfg_channels: int,
|
| 333 |
+
) -> torch.Tensor:
|
| 334 |
+
if guidance_scale <= 1.0 or not guidance_active:
|
| 335 |
+
return model_output
|
| 336 |
+
eps, rest = model_output[:, :cfg_channels], model_output[:, cfg_channels:]
|
| 337 |
+
cond_eps, uncond_eps = torch.chunk(eps, 2, dim=0)
|
| 338 |
+
half_eps = uncond_eps + guidance_scale * (cond_eps - uncond_eps)
|
| 339 |
+
if rest.shape[1] == 0:
|
| 340 |
+
return half_eps
|
| 341 |
+
return torch.cat([half_eps, rest], dim=1)
|
| 342 |
+
|
| 343 |
+
def decode_latents(
|
| 344 |
+
self,
|
| 345 |
+
latents: torch.Tensor,
|
| 346 |
+
output_type: str = "pil",
|
| 347 |
+
latent_mean: Optional[torch.Tensor] = None,
|
| 348 |
+
latent_std: Optional[torch.Tensor] = None,
|
| 349 |
+
latent_multiplier: Optional[float] = None,
|
| 350 |
+
):
|
| 351 |
+
if output_type == "latent":
|
| 352 |
+
return latents
|
| 353 |
+
if self.decoder is None:
|
| 354 |
+
raise ValueError("PAEPipeline requires a PAE decoder component for decoding.")
|
| 355 |
+
|
| 356 |
+
latent_mean, latent_std, latent_multiplier = self._resolve_latent_stats(
|
| 357 |
+
latent_mean,
|
| 358 |
+
latent_std,
|
| 359 |
+
latent_multiplier,
|
| 360 |
+
device=latents.device,
|
| 361 |
+
dtype=latents.dtype,
|
| 362 |
+
)
|
| 363 |
+
latents = self._denormalize_latents(latents, latent_mean, latent_std, latent_multiplier)
|
| 364 |
+
image = self.decoder.decode(latents)
|
| 365 |
+
image = torch.clamp(image, 0.0, 1.0)
|
| 366 |
+
if output_type == "pt":
|
| 367 |
+
return image
|
| 368 |
+
return self.image_processor.postprocess(image, output_type=output_type, do_denormalize=[False] * image.shape[0])
|
| 369 |
+
|
| 370 |
+
@torch.inference_mode()
|
| 371 |
+
def __call__(
|
| 372 |
+
self,
|
| 373 |
+
class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
|
| 374 |
+
height: Optional[int] = None,
|
| 375 |
+
width: Optional[int] = None,
|
| 376 |
+
num_inference_steps: int = 250,
|
| 377 |
+
guidance_scale: float = 3.3,
|
| 378 |
+
guidance_interval: Tuple[float, float] = (0.0, 1.0),
|
| 379 |
+
cfg_interval_start: float = 0.3,
|
| 380 |
+
timestep_shift: float = 0.4,
|
| 381 |
+
mode: str = "ode",
|
| 382 |
+
heun: bool = False,
|
| 383 |
+
latent_mean: Optional[torch.Tensor] = None,
|
| 384 |
+
latent_std: Optional[torch.Tensor] = None,
|
| 385 |
+
latent_multiplier: Optional[float] = None,
|
| 386 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 387 |
+
output_type: str = "pil",
|
| 388 |
+
return_dict: bool = True,
|
| 389 |
+
) -> Union[ImagePipelineOutput, Tuple]:
|
| 390 |
+
r"""
|
| 391 |
+
Generate class-conditional images with PAE + LightningDiT.
|
| 392 |
+
|
| 393 |
+
Args:
|
| 394 |
+
class_labels:
|
| 395 |
+
ImageNet class indices or human-readable English label strings.
|
| 396 |
+
height:
|
| 397 |
+
Output image height in pixels. Defaults to the pretrained native resolution.
|
| 398 |
+
width:
|
| 399 |
+
Output image width in pixels. Defaults to the pretrained native resolution.
|
| 400 |
+
num_inference_steps:
|
| 401 |
+
Number of flow-matching integration steps.
|
| 402 |
+
guidance_scale:
|
| 403 |
+
Classifier-free guidance scale. Active when `guidance_scale > 1.0`.
|
| 404 |
+
guidance_interval:
|
| 405 |
+
Timestep interval `(low, high)` where CFG is applied.
|
| 406 |
+
cfg_interval_start:
|
| 407 |
+
Disable CFG below this normalized timestep value. Default `0.3` matches DiT training configs.
|
| 408 |
+
timestep_shift:
|
| 409 |
+
Timestep warping used by LightningDiT ODE sampling. Default `0.4` matches DiT training configs.
|
| 410 |
+
mode:
|
| 411 |
+
Sampling mode passed to the PAE flow scheduler: `"ode"` or `"sde"`.
|
| 412 |
+
heun:
|
| 413 |
+
Use Heun integration for ODE sampling when True.
|
| 414 |
+
latent_mean:
|
| 415 |
+
Optional latent mean tensor for denormalization before PAE decode. Defaults to
|
| 416 |
+
`latent_mean` in `decoder/config.json` when omitted.
|
| 417 |
+
latent_std:
|
| 418 |
+
Optional latent std tensor for denormalization before PAE decode. Defaults to
|
| 419 |
+
`latent_std` in `decoder/config.json` when omitted.
|
| 420 |
+
latent_multiplier:
|
| 421 |
+
Divisor applied with `latent_std` during denormalization. Defaults to
|
| 422 |
+
`latent_multiplier` in `decoder/config.json` or `1.0`.
|
| 423 |
+
generator:
|
| 424 |
+
RNG for reproducibility.
|
| 425 |
+
output_type:
|
| 426 |
+
`"pil"`, `"np"`, `"pt"`, or `"latent"`.
|
| 427 |
+
return_dict:
|
| 428 |
+
Return [`ImagePipelineOutput`] if True.
|
| 429 |
+
"""
|
| 430 |
+
default_size = self._default_image_size()
|
| 431 |
+
height = int(height or default_size)
|
| 432 |
+
width = int(width or default_size)
|
| 433 |
+
self.check_inputs(height, width, num_inference_steps, output_type, mode)
|
| 434 |
+
|
| 435 |
+
device = self._execution_device
|
| 436 |
+
model_dtype = next(self.transformers.parameters()).dtype
|
| 437 |
+
class_labels_tensor = self._normalize_class_labels(class_labels)
|
| 438 |
+
batch_size = class_labels_tensor.numel()
|
| 439 |
+
null_label = int(self.transformers.config.num_classes)
|
| 440 |
+
null_labels = torch.full((batch_size,), null_label, device=device, dtype=torch.long)
|
| 441 |
+
cfg_channels = int(self.transformers.config.in_channels)
|
| 442 |
+
|
| 443 |
+
latents = self.prepare_latents(
|
| 444 |
+
batch_size=batch_size,
|
| 445 |
+
height=height,
|
| 446 |
+
width=width,
|
| 447 |
+
dtype=model_dtype,
|
| 448 |
+
device=device,
|
| 449 |
+
generator=generator,
|
| 450 |
+
)
|
| 451 |
+
timesteps = self.scheduler.set_timesteps(
|
| 452 |
+
num_inference_steps, device=device, mode=mode, timestep_shift=timestep_shift
|
| 453 |
+
)
|
| 454 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(self.scheduler, generator=generator)
|
| 455 |
+
|
| 456 |
+
for index, timestep in enumerate(timesteps[:-1]):
|
| 457 |
+
next_timestep = timesteps[index + 1]
|
| 458 |
+
t_value = float(timestep)
|
| 459 |
+
guidance_active = guidance_scale > 1.0 and guidance_interval[0] <= t_value <= guidance_interval[1]
|
| 460 |
+
if cfg_interval_start is not None and t_value < cfg_interval_start:
|
| 461 |
+
guidance_active = False
|
| 462 |
+
|
| 463 |
+
if guidance_active:
|
| 464 |
+
model_input = torch.cat([latents, latents], dim=0)
|
| 465 |
+
labels = torch.cat([class_labels_tensor, null_labels], dim=0)
|
| 466 |
+
else:
|
| 467 |
+
model_input = latents
|
| 468 |
+
labels = class_labels_tensor
|
| 469 |
+
|
| 470 |
+
timestep_batch = torch.full((labels.shape[0],), t_value, device=device, dtype=model_dtype)
|
| 471 |
+
model_output = self.transformers(
|
| 472 |
+
model_input.to(dtype=model_dtype),
|
| 473 |
+
timestep=timestep_batch,
|
| 474 |
+
class_labels=labels,
|
| 475 |
+
return_dict=True,
|
| 476 |
+
).sample
|
| 477 |
+
model_output = self._apply_cfg(model_output, guidance_scale, guidance_active, cfg_channels)
|
| 478 |
+
|
| 479 |
+
if heun and mode == "ode" and index < len(timesteps) - 2:
|
| 480 |
+
provisional = self.scheduler.step(
|
| 481 |
+
model_output,
|
| 482 |
+
timestep[None],
|
| 483 |
+
latents,
|
| 484 |
+
next_timestep[None],
|
| 485 |
+
**extra_step_kwargs,
|
| 486 |
+
).prev_sample
|
| 487 |
+
if guidance_active:
|
| 488 |
+
prime_input = torch.cat([provisional, provisional], dim=0)
|
| 489 |
+
prime_labels = torch.cat([class_labels_tensor, null_labels], dim=0)
|
| 490 |
+
else:
|
| 491 |
+
prime_input = provisional
|
| 492 |
+
prime_labels = class_labels_tensor
|
| 493 |
+
next_timestep_batch = torch.full(
|
| 494 |
+
(prime_labels.shape[0],), float(next_timestep), device=device, dtype=model_dtype
|
| 495 |
+
)
|
| 496 |
+
next_output = self.transformers(
|
| 497 |
+
prime_input.to(dtype=model_dtype),
|
| 498 |
+
timestep=next_timestep_batch,
|
| 499 |
+
class_labels=prime_labels,
|
| 500 |
+
return_dict=True,
|
| 501 |
+
).sample
|
| 502 |
+
next_output = self._apply_cfg(next_output, guidance_scale, guidance_active, cfg_channels)
|
| 503 |
+
latents = self.scheduler.step_heun(
|
| 504 |
+
model_output, next_output, timestep[None], latents, next_timestep[None]
|
| 505 |
+
).prev_sample
|
| 506 |
+
else:
|
| 507 |
+
latents = self.scheduler.step(
|
| 508 |
+
model_output,
|
| 509 |
+
timestep[None],
|
| 510 |
+
latents,
|
| 511 |
+
next_timestep[None],
|
| 512 |
+
**extra_step_kwargs,
|
| 513 |
+
).prev_sample
|
| 514 |
+
|
| 515 |
+
image = self.decode_latents(
|
| 516 |
+
latents.to(dtype=model_dtype),
|
| 517 |
+
output_type=output_type,
|
| 518 |
+
latent_mean=latent_mean,
|
| 519 |
+
latent_std=latent_std,
|
| 520 |
+
latent_multiplier=latent_multiplier,
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
self.maybe_free_model_hooks()
|
| 524 |
+
if not return_dict:
|
| 525 |
+
return (image,)
|
| 526 |
+
return ImagePipelineOutput(images=image)
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
# Backward-compatible alias used by earlier PAE-diffusers releases.
|
| 530 |
+
PAEPipelineOutput = ImagePipelineOutput
|
pae-dinov2-large-d32/scheduler/scheduler_config.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "PAEFlowMatchScheduler",
|
| 3 |
+
"_diffusers_version": "0.31.0",
|
| 4 |
+
"mode": "ode",
|
| 5 |
+
"path_type": "linear",
|
| 6 |
+
"num_train_timesteps": 1000
|
| 7 |
+
}
|
pae-dinov2-large-d32/scheduler/scheduling_flow_match_pae.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from typing import Optional, Tuple
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 14 |
+
from diffusers.schedulers.scheduling_utils import SchedulerMixin
|
| 15 |
+
from diffusers.utils import BaseOutput
|
| 16 |
+
except Exception: # pragma: no cover - importable without an installed diffusers checkout.
|
| 17 |
+
class BaseOutput(dict):
|
| 18 |
+
def __post_init__(self):
|
| 19 |
+
self.update(self.__dict__)
|
| 20 |
+
|
| 21 |
+
class ConfigMixin:
|
| 22 |
+
config_name = "scheduler_config.json"
|
| 23 |
+
|
| 24 |
+
class SchedulerMixin:
|
| 25 |
+
pass
|
| 26 |
+
|
| 27 |
+
def register_to_config(init):
|
| 28 |
+
return init
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass
|
| 32 |
+
class PAEFlowMatchSchedulerOutput(BaseOutput):
|
| 33 |
+
prev_sample: torch.FloatTensor
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class PAEFlowMatchScheduler(SchedulerMixin, ConfigMixin):
|
| 37 |
+
"""
|
| 38 |
+
Flow-matching ODE/SDE scheduler used by PAE + LightningDiT pipelines.
|
| 39 |
+
|
| 40 |
+
The model predicts velocity with a linear path by default. ODE timesteps run from 0 to 1
|
| 41 |
+
(noise to data), matching LightningDiT transport sampling.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
config_name = "scheduler_config.json"
|
| 45 |
+
order = 1
|
| 46 |
+
|
| 47 |
+
@register_to_config
|
| 48 |
+
def __init__(
|
| 49 |
+
self,
|
| 50 |
+
mode: str = "ode",
|
| 51 |
+
path_type: str = "linear",
|
| 52 |
+
num_train_timesteps: int = 1000,
|
| 53 |
+
):
|
| 54 |
+
if mode not in {"ode", "sde"}:
|
| 55 |
+
raise ValueError("mode must be either 'ode' or 'sde'.")
|
| 56 |
+
if path_type not in {"linear", "cosine"}:
|
| 57 |
+
raise ValueError("path_type must be either 'linear' or 'cosine'.")
|
| 58 |
+
self.mode = mode
|
| 59 |
+
self.path_type = path_type
|
| 60 |
+
self.num_train_timesteps = num_train_timesteps
|
| 61 |
+
# Native NiT integrates in float64 for better numerical stability.
|
| 62 |
+
self.timesteps = torch.from_numpy(np.linspace(0.0, 1.0, num_train_timesteps + 1)).to(dtype=torch.float64)
|
| 63 |
+
|
| 64 |
+
@staticmethod
|
| 65 |
+
def _apply_timestep_shift(timesteps: torch.Tensor, timestep_shift: float) -> torch.Tensor:
|
| 66 |
+
if timestep_shift <= 0:
|
| 67 |
+
return timesteps
|
| 68 |
+
return timestep_shift * timesteps / (1 + (timestep_shift - 1) * timesteps)
|
| 69 |
+
|
| 70 |
+
def set_timesteps(
|
| 71 |
+
self,
|
| 72 |
+
num_inference_steps: int,
|
| 73 |
+
device: Optional[torch.device] = None,
|
| 74 |
+
mode: Optional[str] = None,
|
| 75 |
+
timestep_shift: float = 0.0,
|
| 76 |
+
):
|
| 77 |
+
mode = mode or self.mode
|
| 78 |
+
dtype = self.timesteps.dtype
|
| 79 |
+
if mode == "sde":
|
| 80 |
+
timesteps = torch.linspace(1.0, 0.04, num_inference_steps, dtype=dtype)
|
| 81 |
+
timesteps = torch.cat([timesteps, torch.zeros(1, dtype=dtype)])
|
| 82 |
+
elif mode == "ode":
|
| 83 |
+
timesteps = torch.linspace(0.0, 1.0, num_inference_steps + 1, dtype=dtype)
|
| 84 |
+
timesteps = self._apply_timestep_shift(timesteps, timestep_shift)
|
| 85 |
+
else:
|
| 86 |
+
raise ValueError("mode must be either 'ode' or 'sde'.")
|
| 87 |
+
self.mode = mode
|
| 88 |
+
self.timesteps = timesteps.to(device=device)
|
| 89 |
+
return self.timesteps
|
| 90 |
+
|
| 91 |
+
@staticmethod
|
| 92 |
+
def _expand_t_like_sample(timestep: torch.Tensor, sample: torch.Tensor, image_sizes: torch.LongTensor):
|
| 93 |
+
dims = [1] * (sample.ndim - 1)
|
| 94 |
+
seqlens = image_sizes[:, 0] * image_sizes[:, 1]
|
| 95 |
+
if timestep.numel() == 1:
|
| 96 |
+
timestep = timestep.repeat(image_sizes.shape[0])
|
| 97 |
+
return torch.cat(
|
| 98 |
+
[timestep[i].reshape(1, *dims).repeat(int(seqlens[i]), *dims) for i in range(image_sizes.shape[0])]
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
def _get_score_from_velocity(
|
| 102 |
+
self,
|
| 103 |
+
model_output: torch.Tensor,
|
| 104 |
+
sample: torch.Tensor,
|
| 105 |
+
timestep: torch.Tensor,
|
| 106 |
+
image_sizes: torch.LongTensor,
|
| 107 |
+
):
|
| 108 |
+
timestep = self._expand_t_like_sample(timestep, sample, image_sizes)
|
| 109 |
+
if self.path_type == "linear":
|
| 110 |
+
alpha_t, d_alpha_t = 1 - timestep, torch.ones_like(timestep) * -1
|
| 111 |
+
sigma_t, d_sigma_t = timestep, torch.ones_like(timestep)
|
| 112 |
+
elif self.path_type == "cosine":
|
| 113 |
+
alpha_t = torch.cos(timestep * np.pi / 2)
|
| 114 |
+
sigma_t = torch.sin(timestep * np.pi / 2)
|
| 115 |
+
d_alpha_t = -np.pi / 2 * torch.sin(timestep * np.pi / 2)
|
| 116 |
+
d_sigma_t = np.pi / 2 * torch.cos(timestep * np.pi / 2)
|
| 117 |
+
else:
|
| 118 |
+
raise ValueError(f"Unsupported path_type: {self.path_type}")
|
| 119 |
+
reverse_alpha_ratio = alpha_t / d_alpha_t
|
| 120 |
+
variance = sigma_t**2 - reverse_alpha_ratio * d_sigma_t * sigma_t
|
| 121 |
+
return (reverse_alpha_ratio * model_output - sample) / variance
|
| 122 |
+
|
| 123 |
+
@staticmethod
|
| 124 |
+
def _compute_diffusion(timestep: torch.Tensor):
|
| 125 |
+
return 2 * timestep
|
| 126 |
+
|
| 127 |
+
@staticmethod
|
| 128 |
+
def _promote_dtypes(*tensors: torch.Tensor) -> torch.dtype:
|
| 129 |
+
dtype = None
|
| 130 |
+
for tensor in tensors:
|
| 131 |
+
if tensor.is_floating_point() or tensor.is_complex():
|
| 132 |
+
dtype = tensor.dtype if dtype is None else torch.promote_types(dtype, tensor.dtype)
|
| 133 |
+
return dtype if dtype is not None else torch.get_default_dtype()
|
| 134 |
+
|
| 135 |
+
def step(
|
| 136 |
+
self,
|
| 137 |
+
model_output: torch.Tensor,
|
| 138 |
+
timestep: torch.Tensor,
|
| 139 |
+
sample: torch.Tensor,
|
| 140 |
+
next_timestep: torch.Tensor,
|
| 141 |
+
image_sizes: Optional[torch.LongTensor] = None,
|
| 142 |
+
generator: Optional[torch.Generator] = None,
|
| 143 |
+
return_dict: bool = True,
|
| 144 |
+
) -> PAEFlowMatchSchedulerOutput:
|
| 145 |
+
sample_dtype = sample.dtype
|
| 146 |
+
compute_dtype = torch.float64
|
| 147 |
+
sample = sample.to(dtype=compute_dtype)
|
| 148 |
+
model_output = model_output.to(dtype=compute_dtype)
|
| 149 |
+
timestep = timestep.to(device=sample.device, dtype=compute_dtype).flatten()
|
| 150 |
+
next_timestep = next_timestep.to(device=sample.device, dtype=compute_dtype).flatten()
|
| 151 |
+
|
| 152 |
+
if self.mode == "ode":
|
| 153 |
+
prev_sample = sample + (next_timestep[0] - timestep[0]) * model_output
|
| 154 |
+
else:
|
| 155 |
+
if image_sizes is None:
|
| 156 |
+
batch = sample.shape[0]
|
| 157 |
+
side = int(sample.shape[-1])
|
| 158 |
+
image_sizes = torch.tensor([[side, side]] * batch, device=sample.device, dtype=torch.long)
|
| 159 |
+
image_sizes = image_sizes.to(device=sample.device, dtype=torch.long)
|
| 160 |
+
diffusion = self._compute_diffusion(timestep[0])
|
| 161 |
+
score = self._get_score_from_velocity(model_output, sample, timestep, image_sizes)
|
| 162 |
+
drift = model_output - 0.5 * diffusion * score
|
| 163 |
+
dt = next_timestep[0] - timestep[0]
|
| 164 |
+
if torch.allclose(next_timestep[0], torch.zeros_like(next_timestep[0])):
|
| 165 |
+
prev_sample = sample + drift * dt
|
| 166 |
+
else:
|
| 167 |
+
if generator is not None:
|
| 168 |
+
noise = torch.randn(sample.shape, generator=generator, device=sample.device, dtype=sample.dtype)
|
| 169 |
+
else:
|
| 170 |
+
noise = torch.randn_like(sample)
|
| 171 |
+
prev_sample = sample + drift * dt + torch.sqrt(diffusion) * noise * torch.sqrt(torch.abs(dt))
|
| 172 |
+
|
| 173 |
+
prev_sample = prev_sample.to(sample_dtype)
|
| 174 |
+
if not return_dict:
|
| 175 |
+
return (prev_sample,)
|
| 176 |
+
return PAEFlowMatchSchedulerOutput(prev_sample=prev_sample)
|
| 177 |
+
|
| 178 |
+
def step_heun(
|
| 179 |
+
self,
|
| 180 |
+
model_output: torch.Tensor,
|
| 181 |
+
next_model_output: torch.Tensor,
|
| 182 |
+
timestep: torch.Tensor,
|
| 183 |
+
sample: torch.Tensor,
|
| 184 |
+
next_timestep: torch.Tensor,
|
| 185 |
+
return_dict: bool = True,
|
| 186 |
+
) -> PAEFlowMatchSchedulerOutput:
|
| 187 |
+
if self.mode != "ode":
|
| 188 |
+
raise ValueError("Heun correction is only defined for ODE sampling.")
|
| 189 |
+
sample_dtype = sample.dtype
|
| 190 |
+
compute_dtype = torch.float64
|
| 191 |
+
sample = sample.to(dtype=compute_dtype)
|
| 192 |
+
model_output = model_output.to(dtype=compute_dtype)
|
| 193 |
+
next_model_output = next_model_output.to(dtype=compute_dtype)
|
| 194 |
+
timestep = timestep.to(device=sample.device, dtype=compute_dtype).flatten()
|
| 195 |
+
next_timestep = next_timestep.to(device=sample.device, dtype=compute_dtype).flatten()
|
| 196 |
+
prev_sample = sample + (next_timestep[0] - timestep[0]) * (0.5 * model_output + 0.5 * next_model_output)
|
| 197 |
+
prev_sample = prev_sample.to(sample_dtype)
|
| 198 |
+
if not return_dict:
|
| 199 |
+
return (prev_sample,)
|
| 200 |
+
return PAEFlowMatchSchedulerOutput(prev_sample=prev_sample)
|
pae-dinov2-large-d32/transformers/__pycache__/transformer_lightning_dit.cpython-311.pyc
ADDED
|
Binary file (44.6 kB). View file
|
|
|
pae-dinov2-large-d32/transformers/config.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "LightningDiT2DModel",
|
| 3 |
+
"depth": 28,
|
| 4 |
+
"hidden_size": 1152,
|
| 5 |
+
"in_channels": 32,
|
| 6 |
+
"input_size": 16,
|
| 7 |
+
"num_classes": 1000,
|
| 8 |
+
"num_heads": 16,
|
| 9 |
+
"patch_size": 1,
|
| 10 |
+
"use_qknorm": true,
|
| 11 |
+
"use_rmsnorm": true,
|
| 12 |
+
"use_rope": true,
|
| 13 |
+
"use_swiglu": true,
|
| 14 |
+
"wo_shift": false
|
| 15 |
+
}
|
pae-dinov2-large-d32/transformers/diffusion_pytorch_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ef0c13279e80947042b013465bfb7ccac0328c5c30d4eb5326b548d32e47892e
|
| 3 |
+
size 2701230752
|
pae-dinov2-large-d32/transformers/transformer_lightning_dit.py
ADDED
|
@@ -0,0 +1,794 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from torch import nn
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class RMSNorm(torch.nn.Module):
|
| 9 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
| 10 |
+
super().__init__()
|
| 11 |
+
self.eps = eps
|
| 12 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 13 |
+
|
| 14 |
+
def _norm(self, x: torch.Tensor) -> torch.Tensor:
|
| 15 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 16 |
+
|
| 17 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 18 |
+
output = self._norm(x.float()).type_as(x)
|
| 19 |
+
return output * self.weight
|
| 20 |
+
|
| 21 |
+
from math import pi
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
from torch import nn
|
| 25 |
+
|
| 26 |
+
from einops import rearrange, repeat
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def broadcat(tensors, dim = -1):
|
| 31 |
+
num_tensors = len(tensors)
|
| 32 |
+
shape_lens = set(list(map(lambda t: len(t.shape), tensors)))
|
| 33 |
+
assert len(shape_lens) == 1, 'tensors must all have the same number of dimensions'
|
| 34 |
+
shape_len = list(shape_lens)[0]
|
| 35 |
+
dim = (dim + shape_len) if dim < 0 else dim
|
| 36 |
+
dims = list(zip(*map(lambda t: list(t.shape), tensors)))
|
| 37 |
+
expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim]
|
| 38 |
+
assert all([*map(lambda t: len(set(t[1])) <= 2, expandable_dims)]), 'invalid dimensions for broadcastable concatentation'
|
| 39 |
+
max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims))
|
| 40 |
+
expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims))
|
| 41 |
+
expanded_dims.insert(dim, (dim, dims[dim]))
|
| 42 |
+
expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims)))
|
| 43 |
+
tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes)))
|
| 44 |
+
return torch.cat(tensors, dim = dim)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def rotate_half(x):
|
| 49 |
+
x = rearrange(x, '... (d r) -> ... d r', r = 2)
|
| 50 |
+
x1, x2 = x.unbind(dim = -1)
|
| 51 |
+
x = torch.stack((-x2, x1), dim = -1)
|
| 52 |
+
return rearrange(x, '... d r -> ... (d r)')
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class VisionRotaryEmbedding(nn.Module):
|
| 57 |
+
def __init__(
|
| 58 |
+
self,
|
| 59 |
+
dim,
|
| 60 |
+
pt_seq_len,
|
| 61 |
+
ft_seq_len=None,
|
| 62 |
+
custom_freqs = None,
|
| 63 |
+
freqs_for = 'lang',
|
| 64 |
+
theta = 10000,
|
| 65 |
+
max_freq = 10,
|
| 66 |
+
num_freqs = 1,
|
| 67 |
+
):
|
| 68 |
+
super().__init__()
|
| 69 |
+
if custom_freqs:
|
| 70 |
+
freqs = custom_freqs
|
| 71 |
+
elif freqs_for == 'lang':
|
| 72 |
+
freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim))
|
| 73 |
+
elif freqs_for == 'pixel':
|
| 74 |
+
freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi
|
| 75 |
+
elif freqs_for == 'constant':
|
| 76 |
+
freqs = torch.ones(num_freqs).float()
|
| 77 |
+
else:
|
| 78 |
+
raise ValueError(f'unknown modality {freqs_for}')
|
| 79 |
+
|
| 80 |
+
if ft_seq_len is None: ft_seq_len = pt_seq_len
|
| 81 |
+
t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len
|
| 82 |
+
|
| 83 |
+
freqs_h = torch.einsum('..., f -> ... f', t, freqs)
|
| 84 |
+
freqs_h = repeat(freqs_h, '... n -> ... (n r)', r = 2)
|
| 85 |
+
|
| 86 |
+
freqs_w = torch.einsum('..., f -> ... f', t, freqs)
|
| 87 |
+
freqs_w = repeat(freqs_w, '... n -> ... (n r)', r = 2)
|
| 88 |
+
|
| 89 |
+
freqs = broadcat((freqs_h[:, None, :], freqs_w[None, :, :]), dim = -1)
|
| 90 |
+
|
| 91 |
+
self.register_buffer("freqs_cos", freqs.cos())
|
| 92 |
+
self.register_buffer("freqs_sin", freqs.sin())
|
| 93 |
+
|
| 94 |
+
# print('======== shape of rope freq', self.freqs_cos.shape, '========')
|
| 95 |
+
|
| 96 |
+
def forward(self, t, start_index = 0):
|
| 97 |
+
rot_dim = self.freqs_cos.shape[-1]
|
| 98 |
+
end_index = start_index + rot_dim
|
| 99 |
+
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}'
|
| 100 |
+
t_left, t, t_right = t[..., :start_index], t[..., start_index:end_index], t[..., end_index:]
|
| 101 |
+
t = (t * self.freqs_cos) + (rotate_half(t) * self.freqs_sin)
|
| 102 |
+
return torch.cat((t_left, t, t_right), dim = -1)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class VisionRotaryEmbeddingFast(nn.Module):
|
| 107 |
+
def __init__(
|
| 108 |
+
self,
|
| 109 |
+
dim,
|
| 110 |
+
pt_seq_len=16,
|
| 111 |
+
ft_seq_len=None,
|
| 112 |
+
custom_freqs = None,
|
| 113 |
+
freqs_for = 'lang',
|
| 114 |
+
theta = 10000,
|
| 115 |
+
max_freq = 10,
|
| 116 |
+
num_freqs = 1,
|
| 117 |
+
):
|
| 118 |
+
super().__init__()
|
| 119 |
+
if custom_freqs:
|
| 120 |
+
freqs = custom_freqs
|
| 121 |
+
elif freqs_for == 'lang':
|
| 122 |
+
freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim))
|
| 123 |
+
elif freqs_for == 'pixel':
|
| 124 |
+
freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi
|
| 125 |
+
elif freqs_for == 'constant':
|
| 126 |
+
freqs = torch.ones(num_freqs).float()
|
| 127 |
+
else:
|
| 128 |
+
raise ValueError(f'unknown modality {freqs_for}')
|
| 129 |
+
|
| 130 |
+
if ft_seq_len is None: ft_seq_len = pt_seq_len
|
| 131 |
+
t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len
|
| 132 |
+
|
| 133 |
+
freqs = torch.einsum('..., f -> ... f', t, freqs)
|
| 134 |
+
freqs = repeat(freqs, '... n -> ... (n r)', r = 2)
|
| 135 |
+
freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim = -1)
|
| 136 |
+
|
| 137 |
+
freqs_cos = freqs.cos().view(-1, freqs.shape[-1])
|
| 138 |
+
freqs_sin = freqs.sin().view(-1, freqs.shape[-1])
|
| 139 |
+
|
| 140 |
+
self.register_buffer("freqs_cos", freqs_cos)
|
| 141 |
+
self.register_buffer("freqs_sin", freqs_sin)
|
| 142 |
+
|
| 143 |
+
# print('======== shape of rope freq', self.freqs_cos.shape, '========')
|
| 144 |
+
|
| 145 |
+
def forward(self, t): return t * self.freqs_cos + rotate_half(t) * self.freqs_sin
|
| 146 |
+
|
| 147 |
+
import os
|
| 148 |
+
import torch
|
| 149 |
+
from typing import Callable, Optional
|
| 150 |
+
import warnings
|
| 151 |
+
|
| 152 |
+
from torch import Tensor, nn
|
| 153 |
+
import torch.nn.functional as F
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class SwiGLUFFN(nn.Module):
|
| 157 |
+
def __init__(
|
| 158 |
+
self,
|
| 159 |
+
in_features: int,
|
| 160 |
+
hidden_features: Optional[int] = None,
|
| 161 |
+
out_features: Optional[int] = None,
|
| 162 |
+
act_layer: Callable[..., nn.Module] = None,
|
| 163 |
+
drop: float = 0.0,
|
| 164 |
+
bias: bool = True,
|
| 165 |
+
) -> None:
|
| 166 |
+
super().__init__()
|
| 167 |
+
out_features = out_features or in_features
|
| 168 |
+
hidden_features = hidden_features or in_features
|
| 169 |
+
self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias)
|
| 170 |
+
self.w3 = nn.Linear(hidden_features, out_features, bias=bias)
|
| 171 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 172 |
+
x12 = self.w12(x)
|
| 173 |
+
x1, x2 = x12.chunk(2, dim=-1)
|
| 174 |
+
hidden = F.silu(x1) * x2
|
| 175 |
+
return self.w3(hidden)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None
|
| 179 |
+
try:
|
| 180 |
+
if XFORMERS_ENABLED:
|
| 181 |
+
from xformers.ops import SwiGLU
|
| 182 |
+
|
| 183 |
+
XFORMERS_AVAILABLE = True
|
| 184 |
+
# warnings.warn("xFormers is available (SwiGLU)")
|
| 185 |
+
else:
|
| 186 |
+
# warnings.warn("xFormers is disabled (SwiGLU)")
|
| 187 |
+
raise ImportError
|
| 188 |
+
except ImportError:
|
| 189 |
+
SwiGLU = SwiGLUFFN
|
| 190 |
+
XFORMERS_AVAILABLE = False
|
| 191 |
+
|
| 192 |
+
# warnings.warn("xFormers is not available (SwiGLU)")
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class SwiGLUFFNFused(SwiGLU):
|
| 196 |
+
def __init__(
|
| 197 |
+
self,
|
| 198 |
+
in_features: int,
|
| 199 |
+
hidden_features: Optional[int] = None,
|
| 200 |
+
out_features: Optional[int] = None,
|
| 201 |
+
act_layer: Callable[..., nn.Module] = None,
|
| 202 |
+
drop: float = 0.0,
|
| 203 |
+
bias: bool = True,
|
| 204 |
+
) -> None:
|
| 205 |
+
out_features = out_features or in_features
|
| 206 |
+
hidden_features = hidden_features or in_features
|
| 207 |
+
hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
|
| 208 |
+
super().__init__(
|
| 209 |
+
in_features=in_features,
|
| 210 |
+
hidden_features=hidden_features,
|
| 211 |
+
out_features=out_features,
|
| 212 |
+
bias=bias,
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
from dataclasses import dataclass
|
| 216 |
+
from typing import Optional, Tuple, Union
|
| 217 |
+
|
| 218 |
+
import torch
|
| 219 |
+
|
| 220 |
+
try:
|
| 221 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 222 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 223 |
+
from diffusers.utils import BaseOutput
|
| 224 |
+
except Exception: # pragma: no cover
|
| 225 |
+
class BaseOutput(dict):
|
| 226 |
+
def __post_init__(self):
|
| 227 |
+
self.update(self.__dict__)
|
| 228 |
+
|
| 229 |
+
class ConfigMixin:
|
| 230 |
+
config_name = "config.json"
|
| 231 |
+
|
| 232 |
+
class ModelMixin(torch.nn.Module):
|
| 233 |
+
pass
|
| 234 |
+
|
| 235 |
+
def register_to_config(init):
|
| 236 |
+
return init
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
@dataclass
|
| 240 |
+
class LightningDiT2DModelOutput(BaseOutput):
|
| 241 |
+
sample: torch.FloatTensor
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
import os
|
| 245 |
+
import math
|
| 246 |
+
import numpy as np
|
| 247 |
+
|
| 248 |
+
import torch
|
| 249 |
+
import torch.nn as nn
|
| 250 |
+
import torch.nn.functional as F
|
| 251 |
+
from torch.utils.checkpoint import checkpoint
|
| 252 |
+
|
| 253 |
+
from timm.models.vision_transformer import PatchEmbed, Mlp
|
| 254 |
+
def modulate(x, shift, scale):
|
| 255 |
+
if shift is None:
|
| 256 |
+
return x * (1 + scale.unsqueeze(1))
|
| 257 |
+
return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
|
| 258 |
+
|
| 259 |
+
class Attention(nn.Module):
|
| 260 |
+
"""
|
| 261 |
+
Attention module of LightningDiT.
|
| 262 |
+
"""
|
| 263 |
+
def __init__(
|
| 264 |
+
self,
|
| 265 |
+
dim: int,
|
| 266 |
+
num_heads: int = 8,
|
| 267 |
+
qkv_bias: bool = False,
|
| 268 |
+
qk_norm: bool = False,
|
| 269 |
+
attn_drop: float = 0.,
|
| 270 |
+
proj_drop: float = 0.,
|
| 271 |
+
norm_layer: nn.Module = nn.LayerNorm,
|
| 272 |
+
fused_attn: bool = True,
|
| 273 |
+
use_rmsnorm: bool = False,
|
| 274 |
+
) -> None:
|
| 275 |
+
super().__init__()
|
| 276 |
+
assert dim % num_heads == 0, 'dim should be divisible by num_heads'
|
| 277 |
+
|
| 278 |
+
self.num_heads = num_heads
|
| 279 |
+
self.head_dim = dim // num_heads
|
| 280 |
+
self.scale = self.head_dim ** -0.5
|
| 281 |
+
self.fused_attn = fused_attn
|
| 282 |
+
|
| 283 |
+
if use_rmsnorm:
|
| 284 |
+
norm_layer = RMSNorm
|
| 285 |
+
|
| 286 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
| 287 |
+
self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
|
| 288 |
+
self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
|
| 289 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 290 |
+
self.proj = nn.Linear(dim, dim)
|
| 291 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 292 |
+
|
| 293 |
+
def forward(self, x: torch.Tensor, rope=None) -> torch.Tensor:
|
| 294 |
+
B, N, C = x.shape
|
| 295 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
|
| 296 |
+
q, k, v = qkv.unbind(0)
|
| 297 |
+
q, k = self.q_norm(q), self.k_norm(k)
|
| 298 |
+
|
| 299 |
+
if rope is not None:
|
| 300 |
+
q = rope(q)
|
| 301 |
+
k = rope(k)
|
| 302 |
+
|
| 303 |
+
if self.fused_attn:
|
| 304 |
+
x = F.scaled_dot_product_attention(
|
| 305 |
+
q, k, v,
|
| 306 |
+
dropout_p=self.attn_drop.p if self.training else 0.,
|
| 307 |
+
)
|
| 308 |
+
else:
|
| 309 |
+
q = q * self.scale
|
| 310 |
+
attn = q @ k.transpose(-2, -1)
|
| 311 |
+
attn = attn.softmax(dim=-1)
|
| 312 |
+
attn = self.attn_drop(attn)
|
| 313 |
+
x = attn @ v
|
| 314 |
+
|
| 315 |
+
x = x.transpose(1, 2).reshape(B, N, C)
|
| 316 |
+
x = self.proj(x)
|
| 317 |
+
x = self.proj_drop(x)
|
| 318 |
+
return x
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
class TimestepEmbedder(nn.Module):
|
| 322 |
+
"""
|
| 323 |
+
Embeds scalar timesteps into vector representations.
|
| 324 |
+
Same as DiT.
|
| 325 |
+
"""
|
| 326 |
+
def __init__(self, hidden_size: int, frequency_embedding_size: int = 256) -> None:
|
| 327 |
+
super().__init__()
|
| 328 |
+
self.frequency_embedding_size = frequency_embedding_size
|
| 329 |
+
self.mlp = nn.Sequential(
|
| 330 |
+
nn.Linear(frequency_embedding_size, hidden_size, bias=True),
|
| 331 |
+
nn.SiLU(),
|
| 332 |
+
nn.Linear(hidden_size, hidden_size, bias=True),
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
@staticmethod
|
| 336 |
+
def timestep_embedding(t: torch.Tensor, dim: int, max_period: int = 10000) -> torch.Tensor:
|
| 337 |
+
"""
|
| 338 |
+
Create sinusoidal timestep embeddings.
|
| 339 |
+
Args:
|
| 340 |
+
t: A 1-D Tensor of N indices, one per batch element. These may be fractional.
|
| 341 |
+
dim: The dimension of the output.
|
| 342 |
+
max_period: Controls the minimum frequency of the embeddings.
|
| 343 |
+
Returns:
|
| 344 |
+
An (N, D) Tensor of positional embeddings.
|
| 345 |
+
"""
|
| 346 |
+
# https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
|
| 347 |
+
half = dim // 2
|
| 348 |
+
freqs = torch.exp(
|
| 349 |
+
-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
|
| 350 |
+
).to(device=t.device)
|
| 351 |
+
|
| 352 |
+
args = t[:, None].float() * freqs[None]
|
| 353 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 354 |
+
|
| 355 |
+
if dim % 2:
|
| 356 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
| 357 |
+
|
| 358 |
+
return embedding
|
| 359 |
+
def forward(self, t: torch.Tensor) -> torch.Tensor:
|
| 360 |
+
t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
|
| 361 |
+
t_emb = self.mlp(t_freq)
|
| 362 |
+
return t_emb
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
class LabelEmbedder(nn.Module):
|
| 366 |
+
"""
|
| 367 |
+
Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.
|
| 368 |
+
Same as DiT.
|
| 369 |
+
"""
|
| 370 |
+
def __init__(self, num_classes, hidden_size, dropout_prob):
|
| 371 |
+
super().__init__()
|
| 372 |
+
use_cfg_embedding = dropout_prob > 0
|
| 373 |
+
self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size)
|
| 374 |
+
self.num_classes = num_classes
|
| 375 |
+
self.dropout_prob = dropout_prob
|
| 376 |
+
|
| 377 |
+
def token_drop(self, labels, force_drop_ids=None):
|
| 378 |
+
"""
|
| 379 |
+
Drops labels to enable classifier-free guidance.
|
| 380 |
+
"""
|
| 381 |
+
if force_drop_ids is None:
|
| 382 |
+
drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob
|
| 383 |
+
else:
|
| 384 |
+
drop_ids = force_drop_ids == 1
|
| 385 |
+
labels = torch.where(drop_ids, self.num_classes, labels)
|
| 386 |
+
return labels
|
| 387 |
+
def forward(self, labels, train, force_drop_ids=None):
|
| 388 |
+
use_dropout = self.dropout_prob > 0
|
| 389 |
+
if (train and use_dropout) or (force_drop_ids is not None):
|
| 390 |
+
labels = self.token_drop(labels, force_drop_ids)
|
| 391 |
+
embeddings = self.embedding_table(labels)
|
| 392 |
+
return embeddings
|
| 393 |
+
|
| 394 |
+
class LightningDiTBlock(nn.Module):
|
| 395 |
+
"""
|
| 396 |
+
Lightning DiT Block. We add features including:
|
| 397 |
+
- ROPE
|
| 398 |
+
- QKNorm
|
| 399 |
+
- RMSNorm
|
| 400 |
+
- SwiGLU
|
| 401 |
+
- No shift AdaLN.
|
| 402 |
+
Not all of them are used in the final model, please refer to the paper for more details.
|
| 403 |
+
"""
|
| 404 |
+
def __init__(
|
| 405 |
+
self,
|
| 406 |
+
hidden_size,
|
| 407 |
+
num_heads,
|
| 408 |
+
mlp_ratio=4.0,
|
| 409 |
+
use_qknorm=False,
|
| 410 |
+
use_swiglu=False,
|
| 411 |
+
use_rmsnorm=False,
|
| 412 |
+
wo_shift=False,
|
| 413 |
+
**block_kwargs
|
| 414 |
+
):
|
| 415 |
+
super().__init__()
|
| 416 |
+
|
| 417 |
+
# Initialize normalization layers
|
| 418 |
+
if not use_rmsnorm:
|
| 419 |
+
self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 420 |
+
self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 421 |
+
else:
|
| 422 |
+
self.norm1 = RMSNorm(hidden_size)
|
| 423 |
+
self.norm2 = RMSNorm(hidden_size)
|
| 424 |
+
|
| 425 |
+
# Initialize attention layer
|
| 426 |
+
self.attn = Attention(
|
| 427 |
+
hidden_size,
|
| 428 |
+
num_heads=num_heads,
|
| 429 |
+
qkv_bias=True,
|
| 430 |
+
qk_norm=use_qknorm,
|
| 431 |
+
use_rmsnorm=use_rmsnorm,
|
| 432 |
+
**block_kwargs
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
# Initialize MLP layer
|
| 436 |
+
mlp_hidden_dim = int(hidden_size * mlp_ratio)
|
| 437 |
+
approx_gelu = lambda: nn.GELU(approximate="tanh")
|
| 438 |
+
if use_swiglu:
|
| 439 |
+
# here we did not use SwiGLU from xformers because it is not compatible with torch.compile for now.
|
| 440 |
+
self.mlp = SwiGLUFFN(hidden_size, int(2/3 * mlp_hidden_dim))
|
| 441 |
+
else:
|
| 442 |
+
self.mlp = Mlp(
|
| 443 |
+
in_features=hidden_size,
|
| 444 |
+
hidden_features=mlp_hidden_dim,
|
| 445 |
+
act_layer=approx_gelu,
|
| 446 |
+
drop=0
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
# Initialize AdaLN modulation
|
| 450 |
+
if wo_shift:
|
| 451 |
+
self.adaLN_modulation = nn.Sequential(
|
| 452 |
+
nn.SiLU(),
|
| 453 |
+
nn.Linear(hidden_size, 4 * hidden_size, bias=True)
|
| 454 |
+
)
|
| 455 |
+
else:
|
| 456 |
+
self.adaLN_modulation = nn.Sequential(
|
| 457 |
+
nn.SiLU(),
|
| 458 |
+
nn.Linear(hidden_size, 6 * hidden_size, bias=True)
|
| 459 |
+
)
|
| 460 |
+
self.wo_shift = wo_shift
|
| 461 |
+
def forward(self, x, c, feat_rope=None):
|
| 462 |
+
if self.wo_shift:
|
| 463 |
+
scale_msa, gate_msa, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(4, dim=1)
|
| 464 |
+
shift_msa = None
|
| 465 |
+
shift_mlp = None
|
| 466 |
+
else:
|
| 467 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=1)
|
| 468 |
+
|
| 469 |
+
x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa), rope=feat_rope)
|
| 470 |
+
x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))
|
| 471 |
+
return x
|
| 472 |
+
|
| 473 |
+
class FinalLayer(nn.Module):
|
| 474 |
+
"""
|
| 475 |
+
The final layer of LightningDiT.
|
| 476 |
+
"""
|
| 477 |
+
def __init__(self, hidden_size, patch_size, out_channels, use_rmsnorm=False):
|
| 478 |
+
super().__init__()
|
| 479 |
+
if not use_rmsnorm:
|
| 480 |
+
self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 481 |
+
else:
|
| 482 |
+
self.norm_final = RMSNorm(hidden_size)
|
| 483 |
+
self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
|
| 484 |
+
self.adaLN_modulation = nn.Sequential(
|
| 485 |
+
nn.SiLU(),
|
| 486 |
+
nn.Linear(hidden_size, 2 * hidden_size, bias=True)
|
| 487 |
+
)
|
| 488 |
+
def forward(self, x, c):
|
| 489 |
+
shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
|
| 490 |
+
x = modulate(self.norm_final(x), shift, scale)
|
| 491 |
+
x = self.linear(x)
|
| 492 |
+
return x
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
class LightningDiT2DModel(ModelMixin, ConfigMixin):
|
| 496 |
+
"""
|
| 497 |
+
Diffusion model with a Transformer backbone.
|
| 498 |
+
"""
|
| 499 |
+
@register_to_config
|
| 500 |
+
def __init__(
|
| 501 |
+
self,
|
| 502 |
+
input_size: int = 32,
|
| 503 |
+
patch_size=2,
|
| 504 |
+
in_channels=32,
|
| 505 |
+
hidden_size=1152,
|
| 506 |
+
depth=28,
|
| 507 |
+
num_heads=16,
|
| 508 |
+
mlp_ratio=4.0,
|
| 509 |
+
class_dropout_prob=0.1,
|
| 510 |
+
num_classes=1000,
|
| 511 |
+
learn_sigma=False,
|
| 512 |
+
use_qknorm=False,
|
| 513 |
+
use_swiglu=False,
|
| 514 |
+
use_rope=False,
|
| 515 |
+
use_rmsnorm=False,
|
| 516 |
+
wo_shift=False,
|
| 517 |
+
use_checkpoint=False,
|
| 518 |
+
use_abs_pos=True,
|
| 519 |
+
):
|
| 520 |
+
super().__init__()
|
| 521 |
+
self.use_abs_pos = use_abs_pos
|
| 522 |
+
self.learn_sigma = learn_sigma
|
| 523 |
+
self.in_channels = in_channels
|
| 524 |
+
self.out_channels = in_channels if not learn_sigma else in_channels * 2
|
| 525 |
+
self.patch_size = patch_size
|
| 526 |
+
self.num_heads = num_heads
|
| 527 |
+
self.use_rope = use_rope
|
| 528 |
+
self.use_rmsnorm = use_rmsnorm
|
| 529 |
+
self.depth = depth
|
| 530 |
+
self.hidden_size = hidden_size
|
| 531 |
+
self.use_checkpoint = use_checkpoint
|
| 532 |
+
self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size, bias=True)
|
| 533 |
+
self.t_embedder = TimestepEmbedder(hidden_size)
|
| 534 |
+
self.y_embedder = LabelEmbedder(num_classes, hidden_size, class_dropout_prob)
|
| 535 |
+
num_patches = self.x_embedder.num_patches
|
| 536 |
+
# Will use fixed sin-cos embedding:
|
| 537 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False)
|
| 538 |
+
|
| 539 |
+
if not self.use_abs_pos and not self.use_rope:
|
| 540 |
+
import warnings
|
| 541 |
+
warnings.warn("Warning: Both Absolute Position Embedding and RoPE are disabled. "
|
| 542 |
+
"The model will be permutation-invariant (orderless)!")
|
| 543 |
+
|
| 544 |
+
# use rotary position encoding, borrow from EVA
|
| 545 |
+
if self.use_rope:
|
| 546 |
+
half_head_dim = hidden_size // num_heads // 2
|
| 547 |
+
hw_seq_len = input_size // patch_size
|
| 548 |
+
self.feat_rope = VisionRotaryEmbeddingFast(
|
| 549 |
+
dim=half_head_dim,
|
| 550 |
+
pt_seq_len=hw_seq_len,
|
| 551 |
+
)
|
| 552 |
+
else:
|
| 553 |
+
self.feat_rope = None
|
| 554 |
+
|
| 555 |
+
self.blocks = nn.ModuleList([
|
| 556 |
+
LightningDiTBlock(hidden_size,
|
| 557 |
+
num_heads,
|
| 558 |
+
mlp_ratio=mlp_ratio,
|
| 559 |
+
use_qknorm=use_qknorm,
|
| 560 |
+
use_swiglu=use_swiglu,
|
| 561 |
+
use_rmsnorm=use_rmsnorm,
|
| 562 |
+
wo_shift=wo_shift,
|
| 563 |
+
) for _ in range(depth)
|
| 564 |
+
])
|
| 565 |
+
self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels, use_rmsnorm=use_rmsnorm)
|
| 566 |
+
self.initialize_weights()
|
| 567 |
+
if hasattr(self, "register_to_config"):
|
| 568 |
+
self.register_to_config(
|
| 569 |
+
input_size=input_size,
|
| 570 |
+
patch_size=patch_size,
|
| 571 |
+
in_channels=in_channels,
|
| 572 |
+
hidden_size=hidden_size,
|
| 573 |
+
depth=depth,
|
| 574 |
+
num_heads=num_heads,
|
| 575 |
+
mlp_ratio=mlp_ratio,
|
| 576 |
+
class_dropout_prob=class_dropout_prob,
|
| 577 |
+
num_classes=num_classes,
|
| 578 |
+
learn_sigma=learn_sigma,
|
| 579 |
+
use_qknorm=use_qknorm,
|
| 580 |
+
use_swiglu=use_swiglu,
|
| 581 |
+
use_rope=use_rope,
|
| 582 |
+
use_rmsnorm=use_rmsnorm,
|
| 583 |
+
wo_shift=wo_shift,
|
| 584 |
+
use_checkpoint=use_checkpoint,
|
| 585 |
+
use_abs_pos=use_abs_pos,
|
| 586 |
+
)
|
| 587 |
+
|
| 588 |
+
def initialize_weights(self):
|
| 589 |
+
# Initialize transformer layers:
|
| 590 |
+
def _basic_init(module):
|
| 591 |
+
if isinstance(module, nn.Linear):
|
| 592 |
+
torch.nn.init.xavier_uniform_(module.weight)
|
| 593 |
+
if module.bias is not None:
|
| 594 |
+
nn.init.constant_(module.bias, 0)
|
| 595 |
+
self.apply(_basic_init)
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
if self.use_abs_pos:
|
| 599 |
+
pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5))
|
| 600 |
+
self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
|
| 601 |
+
else:
|
| 602 |
+
nn.init.constant_(self.pos_embed, 0)
|
| 603 |
+
|
| 604 |
+
# Initialize patch_embed like nn.Linear (instead of nn.Conv2d):
|
| 605 |
+
w = self.x_embedder.proj.weight.data
|
| 606 |
+
nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
|
| 607 |
+
nn.init.constant_(self.x_embedder.proj.bias, 0)
|
| 608 |
+
|
| 609 |
+
# Initialize label embedding table:
|
| 610 |
+
nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02)
|
| 611 |
+
|
| 612 |
+
# Initialize timestep embedding MLP:
|
| 613 |
+
nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
|
| 614 |
+
nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
|
| 615 |
+
|
| 616 |
+
# Zero-out adaLN modulation layers in LightningDiT blocks:
|
| 617 |
+
for block in self.blocks:
|
| 618 |
+
nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
|
| 619 |
+
nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
|
| 620 |
+
|
| 621 |
+
# Zero-out output layers:
|
| 622 |
+
nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
|
| 623 |
+
nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)
|
| 624 |
+
nn.init.constant_(self.final_layer.linear.weight, 0)
|
| 625 |
+
nn.init.constant_(self.final_layer.linear.bias, 0)
|
| 626 |
+
|
| 627 |
+
def unpatchify(self, x):
|
| 628 |
+
"""
|
| 629 |
+
x: (N, T, patch_size**2 * C)
|
| 630 |
+
imgs: (N, H, W, C)
|
| 631 |
+
"""
|
| 632 |
+
c = self.out_channels
|
| 633 |
+
p = self.x_embedder.patch_size[0]
|
| 634 |
+
h = w = int(x.shape[1] ** 0.5)
|
| 635 |
+
assert h * w == x.shape[1]
|
| 636 |
+
|
| 637 |
+
x = x.reshape(shape=(x.shape[0], h, w, p, p, c))
|
| 638 |
+
x = torch.einsum('nhwpqc->nchpwq', x)
|
| 639 |
+
imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p))
|
| 640 |
+
return imgs
|
| 641 |
+
|
| 642 |
+
def forward(
|
| 643 |
+
self,
|
| 644 |
+
hidden_states: torch.Tensor,
|
| 645 |
+
timestep: Optional[torch.LongTensor] = None,
|
| 646 |
+
class_labels: Optional[torch.LongTensor] = None,
|
| 647 |
+
return_dict: bool = True,
|
| 648 |
+
):
|
| 649 |
+
x = hidden_states
|
| 650 |
+
t = timestep
|
| 651 |
+
y = class_labels
|
| 652 |
+
"""
|
| 653 |
+
Forward pass of LightningDiT.
|
| 654 |
+
x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)
|
| 655 |
+
t: (N,) tensor of diffusion timesteps
|
| 656 |
+
y: (N,) tensor of class labels
|
| 657 |
+
use_checkpoint: boolean to toggle checkpointing
|
| 658 |
+
"""
|
| 659 |
+
|
| 660 |
+
use_checkpoint = self.use_checkpoint
|
| 661 |
+
|
| 662 |
+
x = self.x_embedder(x)
|
| 663 |
+
if self.use_abs_pos:
|
| 664 |
+
x = x + self.pos_embed
|
| 665 |
+
t = self.t_embedder(t) # (N, D)
|
| 666 |
+
y = self.y_embedder(y, self.training) # (N, D)
|
| 667 |
+
c = t + y # (N, D)
|
| 668 |
+
|
| 669 |
+
for block in self.blocks:
|
| 670 |
+
if use_checkpoint:
|
| 671 |
+
x = checkpoint(block, x, c, self.feat_rope, use_reentrant=True)
|
| 672 |
+
else:
|
| 673 |
+
x = block(x, c, self.feat_rope)
|
| 674 |
+
|
| 675 |
+
x = self.final_layer(x, c) # (N, T, patch_size ** 2 * out_channels)
|
| 676 |
+
x = self.unpatchify(x) # (N, out_channels, H, W)
|
| 677 |
+
|
| 678 |
+
if self.learn_sigma:
|
| 679 |
+
x, _ = x.chunk(2, dim=1)
|
| 680 |
+
if not return_dict:
|
| 681 |
+
return (x,)
|
| 682 |
+
return LightningDiT2DModelOutput(sample=x)
|
| 683 |
+
|
| 684 |
+
def forward_with_cfg(self, x, t, y, cfg_scale, cfg_interval=None, cfg_interval_start=None):
|
| 685 |
+
"""
|
| 686 |
+
Forward pass of LightningDiT, but also batches the unconditional forward pass for classifier-free guidance.
|
| 687 |
+
"""
|
| 688 |
+
# https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb
|
| 689 |
+
combined = torch.cat([x, x], dim=0)
|
| 690 |
+
model_out = self.forward(combined, t, y, return_dict=False)[0]
|
| 691 |
+
# For exact reproducibility reasons, we apply classifier-free guidance on only
|
| 692 |
+
# three channels by default. The standard approach to cfg applies it to all channels.
|
| 693 |
+
# This can be done by uncommenting the following line and commenting-out the line following that.
|
| 694 |
+
eps, rest = model_out[:, :self.in_channels], model_out[:, self.in_channels:]
|
| 695 |
+
# eps, rest = model_out[:, :3], model_out[:, 3:]
|
| 696 |
+
cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
|
| 697 |
+
half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps)
|
| 698 |
+
|
| 699 |
+
if cfg_interval is True:
|
| 700 |
+
timestep = t[0]
|
| 701 |
+
if timestep < cfg_interval_start:
|
| 702 |
+
half_eps = cond_eps
|
| 703 |
+
|
| 704 |
+
eps = torch.cat([half_eps, half_eps], dim=0)
|
| 705 |
+
return torch.cat([eps, rest], dim=1)
|
| 706 |
+
|
| 707 |
+
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0):
|
| 708 |
+
"""
|
| 709 |
+
grid_size: int of the grid height and width
|
| 710 |
+
return:
|
| 711 |
+
pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
|
| 712 |
+
"""
|
| 713 |
+
grid_h = np.arange(grid_size, dtype=np.float32)
|
| 714 |
+
grid_w = np.arange(grid_size, dtype=np.float32)
|
| 715 |
+
grid = np.meshgrid(grid_w, grid_h) # here w goes first
|
| 716 |
+
grid = np.stack(grid, axis=0)
|
| 717 |
+
|
| 718 |
+
grid = grid.reshape([2, 1, grid_size, grid_size])
|
| 719 |
+
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
| 720 |
+
if cls_token and extra_tokens > 0:
|
| 721 |
+
pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
|
| 722 |
+
return pos_embed
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
|
| 726 |
+
assert embed_dim % 2 == 0
|
| 727 |
+
|
| 728 |
+
# use half of dimensions to encode grid_h
|
| 729 |
+
emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
|
| 730 |
+
emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
|
| 731 |
+
|
| 732 |
+
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
|
| 733 |
+
return emb
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
|
| 737 |
+
"""
|
| 738 |
+
embed_dim: output dimension for each position
|
| 739 |
+
pos: a list of positions to be encoded: size (M,)
|
| 740 |
+
out: (M, D)
|
| 741 |
+
"""
|
| 742 |
+
assert embed_dim % 2 == 0
|
| 743 |
+
omega = np.arange(embed_dim // 2, dtype=np.float64)
|
| 744 |
+
omega /= embed_dim / 2.
|
| 745 |
+
omega = 1. / 10000**omega # (D/2,)
|
| 746 |
+
|
| 747 |
+
pos = pos.reshape(-1) # (M,)
|
| 748 |
+
out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
|
| 749 |
+
|
| 750 |
+
emb_sin = np.sin(out) # (M, D/2)
|
| 751 |
+
emb_cos = np.cos(out) # (M, D/2)
|
| 752 |
+
|
| 753 |
+
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
|
| 754 |
+
return emb
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
#################################################################################
|
| 758 |
+
# LightningDiT Configs #
|
| 759 |
+
#################################################################################
|
| 760 |
+
|
| 761 |
+
def _lightning_dit_XL_1(**kwargs):
|
| 762 |
+
return LightningDiT2DModel(depth=28, hidden_size=1152, patch_size=1, num_heads=16, **kwargs)
|
| 763 |
+
|
| 764 |
+
def _lightning_dit_XL_2(**kwargs):
|
| 765 |
+
return LightningDiT2DModel(depth=28, hidden_size=1152, patch_size=2, num_heads=16, **kwargs)
|
| 766 |
+
|
| 767 |
+
def _lightning_dit_L_2(**kwargs):
|
| 768 |
+
return LightningDiT2DModel(depth=24, hidden_size=1024, patch_size=2, num_heads=16, **kwargs)
|
| 769 |
+
|
| 770 |
+
def _lightning_dit_B_1(**kwargs):
|
| 771 |
+
return LightningDiT2DModel(depth=12, hidden_size=768, patch_size=1, num_heads=12, **kwargs)
|
| 772 |
+
|
| 773 |
+
def _lightning_dit_B_2(**kwargs):
|
| 774 |
+
return LightningDiT2DModel(depth=12, hidden_size=768, patch_size=2, num_heads=12, **kwargs)
|
| 775 |
+
|
| 776 |
+
def _lightning_dit_1p0B_1(**kwargs):
|
| 777 |
+
return LightningDiT2DModel(depth=24, hidden_size=1536, patch_size=1, num_heads=24, **kwargs)
|
| 778 |
+
|
| 779 |
+
def _lightning_dit_1p0B_2(**kwargs):
|
| 780 |
+
return LightningDiT2DModel(depth=24, hidden_size=1536, patch_size=2, num_heads=24, **kwargs)
|
| 781 |
+
|
| 782 |
+
def _lightning_dit_1p6B_1(**kwargs):
|
| 783 |
+
return LightningDiT2DModel(depth=28, hidden_size=1792, patch_size=1, num_heads=28, **kwargs)
|
| 784 |
+
|
| 785 |
+
def _lightning_dit_1p6B_2(**kwargs):
|
| 786 |
+
return LightningDiT2DModel(depth=28, hidden_size=1792, patch_size=2, num_heads=28, **kwargs)
|
| 787 |
+
|
| 788 |
+
LIGHTNING_DIT_PRESETS = {
|
| 789 |
+
'LightningDiT-B/1': _lightning_dit_B_1, 'LightningDiT-B/2': _lightning_dit_B_2,
|
| 790 |
+
'LightningDiT-L/2': _lightning_dit_L_2,
|
| 791 |
+
'LightningDiT-XL/1': _lightning_dit_XL_1, 'LightningDiT-XL/2': _lightning_dit_XL_2,
|
| 792 |
+
'LightningDiT-1p0B/1': _lightning_dit_1p0B_1, 'LightningDiT-1p0B/2': _lightning_dit_1p0B_2,
|
| 793 |
+
'LightningDiT-1p6B/1': _lightning_dit_1p6B_1, 'LightningDiT-1p6B/2': _lightning_dit_1p6B_2,
|
| 794 |
+
}
|
pae-dinov3-large-d32/decoder/config.json
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "PAEDecoder",
|
| 3 |
+
"decoder_patch_size": 16,
|
| 4 |
+
"encoder_config_path": "facebook/dinov3-vitl16-pretrain-lvd1689m",
|
| 5 |
+
"encoder_hidden_size": 1024,
|
| 6 |
+
"encoder_input_size": 256,
|
| 7 |
+
"encoder_num_heads": 16,
|
| 8 |
+
"encoder_patch_size": 16,
|
| 9 |
+
"latent_dim": 32,
|
| 10 |
+
"latent_mean": [
|
| 11 |
+
-1.140625,
|
| 12 |
+
0.03759765625,
|
| 13 |
+
-0.275390625,
|
| 14 |
+
-0.34375,
|
| 15 |
+
-0.265625,
|
| 16 |
+
0.015869140625,
|
| 17 |
+
0.1884765625,
|
| 18 |
+
0.0087890625,
|
| 19 |
+
1.625,
|
| 20 |
+
-0.005279541015625,
|
| 21 |
+
0.34765625,
|
| 22 |
+
-1.03125,
|
| 23 |
+
0.47265625,
|
| 24 |
+
-1.4375,
|
| 25 |
+
0.00604248046875,
|
| 26 |
+
0.484375,
|
| 27 |
+
-0.1328125,
|
| 28 |
+
0.5234375,
|
| 29 |
+
-0.11865234375,
|
| 30 |
+
-0.37109375,
|
| 31 |
+
0.474609375,
|
| 32 |
+
-1.5390625,
|
| 33 |
+
0.7734375,
|
| 34 |
+
-0.087890625,
|
| 35 |
+
0.039794921875,
|
| 36 |
+
0.734375,
|
| 37 |
+
-0.030517578125,
|
| 38 |
+
-0.158203125,
|
| 39 |
+
-3.078125,
|
| 40 |
+
0.0869140625,
|
| 41 |
+
0.138671875,
|
| 42 |
+
-0.74609375
|
| 43 |
+
],
|
| 44 |
+
"latent_multiplier": 1.0,
|
| 45 |
+
"latent_std": [
|
| 46 |
+
0.5390625,
|
| 47 |
+
0.53515625,
|
| 48 |
+
0.62109375,
|
| 49 |
+
0.5546875,
|
| 50 |
+
0.53125,
|
| 51 |
+
0.44140625,
|
| 52 |
+
0.53125,
|
| 53 |
+
0.53125,
|
| 54 |
+
0.55078125,
|
| 55 |
+
0.58203125,
|
| 56 |
+
0.74609375,
|
| 57 |
+
0.48046875,
|
| 58 |
+
0.49609375,
|
| 59 |
+
0.5390625,
|
| 60 |
+
0.59765625,
|
| 61 |
+
0.5703125,
|
| 62 |
+
0.55859375,
|
| 63 |
+
0.66015625,
|
| 64 |
+
0.55859375,
|
| 65 |
+
0.50390625,
|
| 66 |
+
0.55078125,
|
| 67 |
+
0.490234375,
|
| 68 |
+
0.7109375,
|
| 69 |
+
0.55859375,
|
| 70 |
+
0.53515625,
|
| 71 |
+
0.486328125,
|
| 72 |
+
0.5234375,
|
| 73 |
+
0.515625,
|
| 74 |
+
0.466796875,
|
| 75 |
+
0.5390625,
|
| 76 |
+
0.59375,
|
| 77 |
+
0.51171875
|
| 78 |
+
]
|
| 79 |
+
}
|
pae-dinov3-large-d32/decoder/decoder_pae.py
ADDED
|
@@ -0,0 +1,1105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 4 |
+
from transformers.utils import (
|
| 5 |
+
ModelOutput,
|
| 6 |
+
)
|
| 7 |
+
from transformers.activations import ACT2FN
|
| 8 |
+
class ViTMAEConfig(PretrainedConfig):
|
| 9 |
+
r"""
|
| 10 |
+
This is the configuration class to store the configuration of a [`ViTMAEModel`]. It is used to instantiate an ViT
|
| 11 |
+
MAE model according to the specified arguments, defining the model architecture. Instantiating a configuration with
|
| 12 |
+
the defaults will yield a similar configuration to that of the ViT
|
| 13 |
+
[facebook/vit-mae-base](https://huggingface.co/facebook/vit-mae-base) architecture.
|
| 14 |
+
|
| 15 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 16 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 21 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 22 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 23 |
+
Number of hidden layers in the Transformer encoder.
|
| 24 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 25 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 26 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 27 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 28 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 29 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 30 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 31 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 32 |
+
The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.
|
| 33 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 34 |
+
The dropout ratio for the attention probabilities.
|
| 35 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 36 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 37 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 38 |
+
The epsilon used by the layer normalization layers.
|
| 39 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 40 |
+
The size (resolution) of each image.
|
| 41 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 42 |
+
The size (resolution) of each patch.
|
| 43 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 44 |
+
The number of input channels.
|
| 45 |
+
qkv_bias (`bool`, *optional*, defaults to `True`):
|
| 46 |
+
Whether to add a bias to the queries, keys and values.
|
| 47 |
+
decoder_num_attention_heads (`int`, *optional*, defaults to 16):
|
| 48 |
+
Number of attention heads for each attention layer in the decoder.
|
| 49 |
+
decoder_hidden_size (`int`, *optional*, defaults to 512):
|
| 50 |
+
Dimensionality of the decoder.
|
| 51 |
+
decoder_num_hidden_layers (`int`, *optional*, defaults to 8):
|
| 52 |
+
Number of hidden layers in the decoder.
|
| 53 |
+
decoder_intermediate_size (`int`, *optional*, defaults to 2048):
|
| 54 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the decoder.
|
| 55 |
+
mask_ratio (`float`, *optional*, defaults to 0.75):
|
| 56 |
+
The ratio of the number of masked tokens in the input sequence.
|
| 57 |
+
norm_pix_loss (`bool`, *optional*, defaults to `False`):
|
| 58 |
+
Whether or not to train with normalized pixels (see Table 3 in the paper). Using normalized pixels improved
|
| 59 |
+
representation quality in the experiments of the authors.
|
| 60 |
+
|
| 61 |
+
Example:
|
| 62 |
+
|
| 63 |
+
```python
|
| 64 |
+
>>> from transformers import ViTMAEConfig, ViTMAEModel
|
| 65 |
+
|
| 66 |
+
>>> # Initializing a ViT MAE vit-mae-base style configuration
|
| 67 |
+
>>> configuration = ViTMAEConfig()
|
| 68 |
+
|
| 69 |
+
>>> # Initializing a model (with random weights) from the vit-mae-base style configuration
|
| 70 |
+
>>> model = ViTMAEModel(configuration)
|
| 71 |
+
|
| 72 |
+
>>> # Accessing the model configuration
|
| 73 |
+
>>> configuration = model.config
|
| 74 |
+
```"""
|
| 75 |
+
|
| 76 |
+
model_type = "vit_mae"
|
| 77 |
+
|
| 78 |
+
def __init__(
|
| 79 |
+
self,
|
| 80 |
+
hidden_size=768,
|
| 81 |
+
num_hidden_layers=12,
|
| 82 |
+
num_attention_heads=12,
|
| 83 |
+
intermediate_size=3072,
|
| 84 |
+
hidden_act="gelu",
|
| 85 |
+
hidden_dropout_prob=0.0,
|
| 86 |
+
attention_probs_dropout_prob=0.0,
|
| 87 |
+
initializer_range=0.02,
|
| 88 |
+
layer_norm_eps=1e-12,
|
| 89 |
+
image_size=224,
|
| 90 |
+
patch_size=16,
|
| 91 |
+
num_channels=3,
|
| 92 |
+
qkv_bias=True,
|
| 93 |
+
decoder_num_attention_heads=16,
|
| 94 |
+
decoder_hidden_size=512,
|
| 95 |
+
decoder_num_hidden_layers=8,
|
| 96 |
+
decoder_intermediate_size=2048,
|
| 97 |
+
mask_ratio=0.75,
|
| 98 |
+
norm_pix_loss=False,
|
| 99 |
+
**kwargs,
|
| 100 |
+
):
|
| 101 |
+
super().__init__(**kwargs)
|
| 102 |
+
|
| 103 |
+
self.hidden_size = hidden_size
|
| 104 |
+
self.num_hidden_layers = num_hidden_layers
|
| 105 |
+
self.num_attention_heads = num_attention_heads
|
| 106 |
+
self.intermediate_size = intermediate_size
|
| 107 |
+
self.hidden_act = hidden_act
|
| 108 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 109 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 110 |
+
self.initializer_range = initializer_range
|
| 111 |
+
self.layer_norm_eps = layer_norm_eps
|
| 112 |
+
self.image_size = image_size
|
| 113 |
+
self.patch_size = patch_size
|
| 114 |
+
self.num_channels = num_channels
|
| 115 |
+
self.qkv_bias = qkv_bias
|
| 116 |
+
self.decoder_num_attention_heads = decoder_num_attention_heads
|
| 117 |
+
self.decoder_hidden_size = decoder_hidden_size
|
| 118 |
+
self.decoder_num_hidden_layers = decoder_num_hidden_layers
|
| 119 |
+
self.decoder_intermediate_size = decoder_intermediate_size
|
| 120 |
+
self.mask_ratio = mask_ratio
|
| 121 |
+
self.norm_pix_loss = norm_pix_loss
|
| 122 |
+
|
| 123 |
+
# coding=utf-8
|
| 124 |
+
# Copyright 2022 Facebook AI and The HuggingFace Inc. team. All rights reserved.
|
| 125 |
+
#
|
| 126 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 127 |
+
# you may not use this file except in compliance with the License.
|
| 128 |
+
# You may obtain a copy of the License at
|
| 129 |
+
#
|
| 130 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 131 |
+
#
|
| 132 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 133 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 134 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 135 |
+
# See the License for the specific language governing permissions and
|
| 136 |
+
# limitations under the License.
|
| 137 |
+
"""PyTorch ViT MAE (masked autoencoder) model."""
|
| 138 |
+
|
| 139 |
+
import collections.abc
|
| 140 |
+
import math
|
| 141 |
+
from copy import deepcopy
|
| 142 |
+
from dataclasses import dataclass
|
| 143 |
+
from typing import Optional, Set, Tuple, Union
|
| 144 |
+
|
| 145 |
+
import numpy as np
|
| 146 |
+
import torch
|
| 147 |
+
from torch import nn
|
| 148 |
+
# correct the above import to the following
|
| 149 |
+
from transformers.modeling_outputs import BaseModelOutput
|
| 150 |
+
|
| 151 |
+
try:
|
| 152 |
+
from flash_attn import flash_attn_func
|
| 153 |
+
HAS_FLASH_ATTN = True # if set to False, FlashAttention is unavailable
|
| 154 |
+
except:
|
| 155 |
+
print('FlashAttention is not installed.')
|
| 156 |
+
HAS_FLASH_ATTN = False
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@dataclass
|
| 160 |
+
class ViTMAEModelOutput(ModelOutput):
|
| 161 |
+
"""
|
| 162 |
+
Class for ViTMAEModel's outputs, with potential hidden states and attentions.
|
| 163 |
+
|
| 164 |
+
Args:
|
| 165 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 166 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 167 |
+
mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
|
| 168 |
+
Tensor indicating which patches are masked (1) and which are not (0).
|
| 169 |
+
ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 170 |
+
Tensor containing the original index of the (shuffled) masked patches.
|
| 171 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 172 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 173 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 174 |
+
plus the initial embedding outputs.
|
| 175 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 176 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 177 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 178 |
+
the self-attention heads.
|
| 179 |
+
"""
|
| 180 |
+
|
| 181 |
+
last_hidden_state: torch.FloatTensor = None
|
| 182 |
+
mask: torch.LongTensor = None
|
| 183 |
+
ids_restore: torch.LongTensor = None
|
| 184 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 185 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
@dataclass
|
| 189 |
+
class ViTMAEDecoderOutput(ModelOutput):
|
| 190 |
+
"""
|
| 191 |
+
Class for ViTMAEDecoder's outputs, with potential hidden states and attentions.
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`):
|
| 195 |
+
Pixel reconstruction logits.
|
| 196 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 197 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 198 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 199 |
+
plus the initial embedding outputs.
|
| 200 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 201 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 202 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 203 |
+
the self-attention heads.
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
logits: torch.FloatTensor = None
|
| 207 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 208 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
@dataclass
|
| 212 |
+
class ViTMAEForPreTrainingOutput(ModelOutput):
|
| 213 |
+
"""
|
| 214 |
+
Class for ViTMAEForPreTraining's outputs, with potential hidden states and attentions.
|
| 215 |
+
|
| 216 |
+
Args:
|
| 217 |
+
loss (`torch.FloatTensor` of shape `(1,)`):
|
| 218 |
+
Pixel reconstruction loss.
|
| 219 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`):
|
| 220 |
+
Pixel reconstruction logits.
|
| 221 |
+
mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
|
| 222 |
+
Tensor indicating which patches are masked (1) and which are not (0).
|
| 223 |
+
ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 224 |
+
Tensor containing the original index of the (shuffled) masked patches.
|
| 225 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 226 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 227 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 228 |
+
plus the initial embedding outputs.
|
| 229 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 230 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 231 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 232 |
+
the self-attention heads.
|
| 233 |
+
"""
|
| 234 |
+
|
| 235 |
+
loss: Optional[torch.FloatTensor] = None
|
| 236 |
+
logits: torch.FloatTensor = None
|
| 237 |
+
mask: torch.LongTensor = None
|
| 238 |
+
ids_restore: torch.LongTensor = None
|
| 239 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 240 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def get_2d_sincos_pos_embed(embed_dim, grid_size, add_cls_token=False):
|
| 244 |
+
"""
|
| 245 |
+
Create 2D sin/cos positional embeddings.
|
| 246 |
+
|
| 247 |
+
Args:
|
| 248 |
+
embed_dim (`int`):
|
| 249 |
+
Embedding dimension.
|
| 250 |
+
grid_size (`int`):
|
| 251 |
+
The grid height and width.
|
| 252 |
+
add_cls_token (`bool`, *optional*, defaults to `False`):
|
| 253 |
+
Whether or not to add a classification (CLS) token.
|
| 254 |
+
|
| 255 |
+
Returns:
|
| 256 |
+
(`torch.FloatTensor` of shape (grid_size*grid_size, embed_dim) or (1+grid_size*grid_size, embed_dim): the
|
| 257 |
+
position embeddings (with or without classification token)
|
| 258 |
+
"""
|
| 259 |
+
grid_h = np.arange(grid_size, dtype=np.float32)
|
| 260 |
+
grid_w = np.arange(grid_size, dtype=np.float32)
|
| 261 |
+
grid = np.meshgrid(grid_w, grid_h) # here w goes first
|
| 262 |
+
grid = np.stack(grid, axis=0)
|
| 263 |
+
|
| 264 |
+
grid = grid.reshape([2, 1, grid_size, grid_size])
|
| 265 |
+
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
| 266 |
+
if add_cls_token:
|
| 267 |
+
pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
|
| 268 |
+
return pos_embed
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
|
| 272 |
+
if embed_dim % 2 != 0:
|
| 273 |
+
raise ValueError("embed_dim must be even")
|
| 274 |
+
|
| 275 |
+
# use half of dimensions to encode grid_h
|
| 276 |
+
emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
|
| 277 |
+
emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
|
| 278 |
+
|
| 279 |
+
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
|
| 280 |
+
return emb
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
|
| 284 |
+
"""
|
| 285 |
+
embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D)
|
| 286 |
+
"""
|
| 287 |
+
if embed_dim % 2 != 0:
|
| 288 |
+
raise ValueError("embed_dim must be even")
|
| 289 |
+
|
| 290 |
+
omega = np.arange(embed_dim // 2, dtype=float)
|
| 291 |
+
omega /= embed_dim / 2.0
|
| 292 |
+
omega = 1.0 / 10000**omega # (D/2,)
|
| 293 |
+
|
| 294 |
+
pos = pos.reshape(-1) # (M,)
|
| 295 |
+
out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
|
| 296 |
+
|
| 297 |
+
emb_sin = np.sin(out) # (M, D/2)
|
| 298 |
+
emb_cos = np.cos(out) # (M, D/2)
|
| 299 |
+
|
| 300 |
+
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
|
| 301 |
+
return emb
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
class ViTMAEEmbeddings(nn.Module):
|
| 305 |
+
"""
|
| 306 |
+
Construct the CLS token, position and patch embeddings.
|
| 307 |
+
|
| 308 |
+
"""
|
| 309 |
+
|
| 310 |
+
def __init__(self, config):
|
| 311 |
+
super().__init__()
|
| 312 |
+
|
| 313 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 314 |
+
self.patch_embeddings = ViTMAEPatchEmbeddings(config)
|
| 315 |
+
self.num_patches = self.patch_embeddings.num_patches
|
| 316 |
+
# fixed sin-cos embedding
|
| 317 |
+
self.position_embeddings = nn.Parameter(
|
| 318 |
+
torch.zeros(1, self.num_patches + 1, config.hidden_size), requires_grad=False
|
| 319 |
+
)
|
| 320 |
+
self.config = config
|
| 321 |
+
self.initialize_weights()
|
| 322 |
+
|
| 323 |
+
def initialize_weights(self):
|
| 324 |
+
# initialize (and freeze) position embeddings by sin-cos embedding
|
| 325 |
+
pos_embed = get_2d_sincos_pos_embed(
|
| 326 |
+
self.position_embeddings.shape[-1], int(self.patch_embeddings.num_patches**0.5), add_cls_token=True
|
| 327 |
+
)
|
| 328 |
+
self.position_embeddings.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
|
| 329 |
+
|
| 330 |
+
# initialize patch_embeddings like nn.Linear (instead of nn.Conv2d)
|
| 331 |
+
w = self.patch_embeddings.projection.weight.data
|
| 332 |
+
torch.nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
|
| 333 |
+
|
| 334 |
+
# timm's trunc_normal_(std=.02) is effectively normal_(std=0.02) as cutoff is too big (2.)
|
| 335 |
+
torch.nn.init.normal_(self.cls_token, std=self.config.initializer_range)
|
| 336 |
+
|
| 337 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
| 338 |
+
"""
|
| 339 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher
|
| 340 |
+
resolution images.
|
| 341 |
+
|
| 342 |
+
Source:
|
| 343 |
+
https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174
|
| 344 |
+
"""
|
| 345 |
+
num_patches = embeddings.shape[1] - 1
|
| 346 |
+
num_positions = self.position_embeddings.shape[1] - 1
|
| 347 |
+
|
| 348 |
+
if num_patches == num_positions and height == width:
|
| 349 |
+
return self.position_embeddings
|
| 350 |
+
|
| 351 |
+
class_pos_embed = self.position_embeddings[:, 0, :]
|
| 352 |
+
patch_pos_embed = self.position_embeddings[:, 1:, :]
|
| 353 |
+
dim = embeddings.shape[-1]
|
| 354 |
+
h0 = height // self.config.patch_size
|
| 355 |
+
w0 = width // self.config.patch_size
|
| 356 |
+
# we add a small number to avoid floating point error in the interpolation
|
| 357 |
+
# see discussion at https://github.com/facebookresearch/dino/issues/8
|
| 358 |
+
h0, w0 = h0 + 0.1, w0 + 0.1
|
| 359 |
+
patch_pos_embed = patch_pos_embed.reshape(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim)
|
| 360 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 361 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 362 |
+
patch_pos_embed,
|
| 363 |
+
scale_factor=(h0 / math.sqrt(num_positions), w0 / math.sqrt(num_positions)),
|
| 364 |
+
mode="bicubic",
|
| 365 |
+
align_corners=False,
|
| 366 |
+
)
|
| 367 |
+
if int(h0) != patch_pos_embed.shape[-2] or int(w0) != patch_pos_embed.shape[-1]:
|
| 368 |
+
raise ValueError("Width or height does not match with the interpolated position embeddings")
|
| 369 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 370 |
+
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
|
| 371 |
+
|
| 372 |
+
def random_masking(self, sequence, noise=None):
|
| 373 |
+
"""
|
| 374 |
+
Perform per-sample random masking by per-sample shuffling. Per-sample shuffling is done by argsort random
|
| 375 |
+
noise.
|
| 376 |
+
|
| 377 |
+
Args:
|
| 378 |
+
sequence (`torch.LongTensor` of shape `(batch_size, sequence_length, dim)`)
|
| 379 |
+
noise (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*) which is
|
| 380 |
+
mainly used for testing purposes to control randomness and maintain the reproducibility
|
| 381 |
+
"""
|
| 382 |
+
batch_size, seq_length, dim = sequence.shape
|
| 383 |
+
len_keep = int(seq_length * (1 - self.config.mask_ratio))
|
| 384 |
+
|
| 385 |
+
if noise is None:
|
| 386 |
+
noise = torch.rand(batch_size, seq_length, device=sequence.device) # noise in [0, 1]
|
| 387 |
+
|
| 388 |
+
# sort noise for each sample
|
| 389 |
+
ids_shuffle = torch.argsort(noise, dim=1).to(sequence.device) # ascend: small is keep, large is remove
|
| 390 |
+
ids_restore = torch.argsort(ids_shuffle, dim=1).to(sequence.device)
|
| 391 |
+
|
| 392 |
+
# keep the first subset
|
| 393 |
+
ids_keep = ids_shuffle[:, :len_keep]
|
| 394 |
+
sequence_unmasked = torch.gather(sequence, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, dim))
|
| 395 |
+
|
| 396 |
+
# generate the binary mask: 0 is keep, 1 is remove
|
| 397 |
+
mask = torch.ones([batch_size, seq_length], device=sequence.device)
|
| 398 |
+
mask[:, :len_keep] = 0
|
| 399 |
+
# unshuffle to get the binary mask
|
| 400 |
+
mask = torch.gather(mask, dim=1, index=ids_restore)
|
| 401 |
+
|
| 402 |
+
return sequence_unmasked, mask, ids_restore
|
| 403 |
+
|
| 404 |
+
def forward(self, pixel_values, noise=None, interpolate_pos_encoding: bool = False):
|
| 405 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 406 |
+
embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
|
| 407 |
+
if interpolate_pos_encoding:
|
| 408 |
+
position_embeddings = self.interpolate_pos_encoding(embeddings, height, width)
|
| 409 |
+
else:
|
| 410 |
+
position_embeddings = self.position_embeddings
|
| 411 |
+
|
| 412 |
+
# add position embeddings w/o cls token
|
| 413 |
+
embeddings = embeddings + position_embeddings[:, 1:, :]
|
| 414 |
+
|
| 415 |
+
# masking: length -> length * config.mask_ratio
|
| 416 |
+
embeddings, mask, ids_restore = self.random_masking(embeddings, noise)
|
| 417 |
+
|
| 418 |
+
# append cls token
|
| 419 |
+
cls_token = self.cls_token + position_embeddings[:, :1, :]
|
| 420 |
+
cls_tokens = cls_token.expand(embeddings.shape[0], -1, -1)
|
| 421 |
+
embeddings = torch.cat((cls_tokens, embeddings), dim=1)
|
| 422 |
+
|
| 423 |
+
return embeddings, mask, ids_restore
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
class ViTMAEPatchEmbeddings(nn.Module):
|
| 427 |
+
"""
|
| 428 |
+
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
|
| 429 |
+
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
|
| 430 |
+
Transformer.
|
| 431 |
+
"""
|
| 432 |
+
|
| 433 |
+
def __init__(self, config):
|
| 434 |
+
super().__init__()
|
| 435 |
+
image_size, patch_size = config.image_size, config.patch_size
|
| 436 |
+
num_channels, hidden_size = config.num_channels, config.hidden_size
|
| 437 |
+
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
|
| 438 |
+
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 439 |
+
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
| 440 |
+
self.image_size = image_size
|
| 441 |
+
self.patch_size = patch_size
|
| 442 |
+
self.num_channels = num_channels
|
| 443 |
+
self.num_patches = num_patches
|
| 444 |
+
|
| 445 |
+
self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
|
| 446 |
+
|
| 447 |
+
def forward(self, pixel_values, interpolate_pos_encoding: bool = False):
|
| 448 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 449 |
+
if num_channels != self.num_channels:
|
| 450 |
+
raise ValueError(
|
| 451 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
if not interpolate_pos_encoding and (height != self.image_size[0] or width != self.image_size[1]):
|
| 455 |
+
raise ValueError(
|
| 456 |
+
f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
|
| 457 |
+
)
|
| 458 |
+
x = self.projection(pixel_values).flatten(2).transpose(1, 2)
|
| 459 |
+
return x
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
# Copied from transformers.models.vit.modeling_vit.ViTSelfAttention ViT->ViTMAE
|
| 463 |
+
class ViTMAESelfAttention(nn.Module):
|
| 464 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 465 |
+
super().__init__()
|
| 466 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 467 |
+
raise ValueError(
|
| 468 |
+
f"The hidden size {config.hidden_size,} is not a multiple of the number of attention "
|
| 469 |
+
f"heads {config.num_attention_heads}."
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
self.has_flash_attn = HAS_FLASH_ATTN
|
| 473 |
+
self.num_attention_heads = config.num_attention_heads
|
| 474 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 475 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 476 |
+
|
| 477 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 478 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 479 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 480 |
+
|
| 481 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 482 |
+
self.attention_probs_dropout_prob = config.attention_probs_dropout_prob
|
| 483 |
+
|
| 484 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
| 485 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 486 |
+
x = x.view(new_x_shape)
|
| 487 |
+
return x.permute(0, 2, 1, 3)
|
| 488 |
+
|
| 489 |
+
def reshape_for_flash(self, x: torch.Tensor) -> torch.Tensor:
|
| 490 |
+
"""Reshape to (B, N, num_heads, head_dim) for flash_attn_func."""
|
| 491 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 492 |
+
return x.view(new_x_shape)
|
| 493 |
+
|
| 494 |
+
def forward(
|
| 495 |
+
self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
|
| 496 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 497 |
+
# Use FlashAttention when available and no special outputs are needed
|
| 498 |
+
if self.has_flash_attn and not output_attentions and head_mask is None:
|
| 499 |
+
query_layer = self.reshape_for_flash(self.query(hidden_states))
|
| 500 |
+
key_layer = self.reshape_for_flash(self.key(hidden_states))
|
| 501 |
+
value_layer = self.reshape_for_flash(self.value(hidden_states))
|
| 502 |
+
|
| 503 |
+
context_layer = flash_attn_func(
|
| 504 |
+
query_layer, key_layer, value_layer,
|
| 505 |
+
dropout_p=self.attention_probs_dropout_prob if self.training else 0.0,
|
| 506 |
+
causal=False, deterministic=True
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
context_layer = context_layer.reshape(hidden_states.size(0), -1, self.all_head_size)
|
| 510 |
+
return (context_layer,)
|
| 511 |
+
|
| 512 |
+
# Fallback: manual attention computation
|
| 513 |
+
mixed_query_layer = self.query(hidden_states)
|
| 514 |
+
|
| 515 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 516 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 517 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 518 |
+
|
| 519 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 520 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 521 |
+
|
| 522 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 523 |
+
attention_probs = self.dropout(attention_probs)
|
| 524 |
+
|
| 525 |
+
if head_mask is not None:
|
| 526 |
+
attention_probs = attention_probs * head_mask
|
| 527 |
+
|
| 528 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 529 |
+
|
| 530 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 531 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 532 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 533 |
+
|
| 534 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 535 |
+
|
| 536 |
+
return outputs
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
# Copied from transformers.models.vit.modeling_vit.ViTSdpaSelfAttention ViT->ViTMAE
|
| 540 |
+
class ViTMAESdpaSelfAttention(ViTMAESelfAttention):
|
| 541 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 542 |
+
super().__init__(config)
|
| 543 |
+
self.attention_probs_dropout_prob = config.attention_probs_dropout_prob
|
| 544 |
+
|
| 545 |
+
def forward(
|
| 546 |
+
self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
|
| 547 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 548 |
+
# Use FlashAttention when available and no special outputs are needed
|
| 549 |
+
if self.has_flash_attn and not output_attentions and head_mask is None:
|
| 550 |
+
query_layer = self.reshape_for_flash(self.query(hidden_states))
|
| 551 |
+
key_layer = self.reshape_for_flash(self.key(hidden_states))
|
| 552 |
+
value_layer = self.reshape_for_flash(self.value(hidden_states))
|
| 553 |
+
|
| 554 |
+
context_layer = flash_attn_func(
|
| 555 |
+
query_layer, key_layer, value_layer,
|
| 556 |
+
dropout_p=self.attention_probs_dropout_prob if self.training else 0.0,
|
| 557 |
+
causal=False, deterministic=True
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
context_layer = context_layer.reshape(hidden_states.size(0), -1, self.all_head_size)
|
| 561 |
+
return context_layer, None
|
| 562 |
+
|
| 563 |
+
# Fallback: PyTorch SDPA
|
| 564 |
+
mixed_query_layer = self.query(hidden_states)
|
| 565 |
+
|
| 566 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 567 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 568 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 569 |
+
|
| 570 |
+
context_layer = torch.nn.functional.scaled_dot_product_attention(
|
| 571 |
+
query_layer,
|
| 572 |
+
key_layer,
|
| 573 |
+
value_layer,
|
| 574 |
+
head_mask,
|
| 575 |
+
self.attention_probs_dropout_prob if self.training else 0.0,
|
| 576 |
+
is_causal=False,
|
| 577 |
+
scale=None,
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 581 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 582 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 583 |
+
|
| 584 |
+
return context_layer, None
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
# Copied from transformers.models.vit.modeling_vit.ViTSelfOutput with ViT->ViTMAE
|
| 588 |
+
class ViTMAESelfOutput(nn.Module):
|
| 589 |
+
"""
|
| 590 |
+
The residual connection is defined in ViTMAELayer instead of here (as is the case with other models), due to the
|
| 591 |
+
layernorm applied before each block.
|
| 592 |
+
"""
|
| 593 |
+
|
| 594 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 595 |
+
super().__init__()
|
| 596 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 597 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 598 |
+
|
| 599 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 600 |
+
hidden_states = self.dense(hidden_states)
|
| 601 |
+
hidden_states = self.dropout(hidden_states)
|
| 602 |
+
|
| 603 |
+
return hidden_states
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
# Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->ViTMAE
|
| 607 |
+
class ViTMAEAttention(nn.Module):
|
| 608 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 609 |
+
super().__init__()
|
| 610 |
+
self.attention = ViTMAESelfAttention(config)
|
| 611 |
+
self.output = ViTMAESelfOutput(config)
|
| 612 |
+
|
| 613 |
+
def forward(
|
| 614 |
+
self,
|
| 615 |
+
hidden_states: torch.Tensor,
|
| 616 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 617 |
+
output_attentions: bool = False,
|
| 618 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 619 |
+
self_outputs = self.attention(hidden_states, head_mask, output_attentions)
|
| 620 |
+
|
| 621 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 622 |
+
|
| 623 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 624 |
+
return outputs
|
| 625 |
+
|
| 626 |
+
# Copied from transformers.models.vit.modeling_vit.ViTIntermediate ViT->ViTMAE
|
| 627 |
+
class ViTMAEIntermediate(nn.Module):
|
| 628 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 629 |
+
super().__init__()
|
| 630 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 631 |
+
if isinstance(config.hidden_act, str):
|
| 632 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 633 |
+
else:
|
| 634 |
+
self.intermediate_act_fn = config.hidden_act
|
| 635 |
+
|
| 636 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 637 |
+
hidden_states = self.dense(hidden_states)
|
| 638 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 639 |
+
|
| 640 |
+
return hidden_states
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
# Copied from transformers.models.vit.modeling_vit.ViTOutput ViT->ViTMAE
|
| 644 |
+
class ViTMAEOutput(nn.Module):
|
| 645 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 646 |
+
super().__init__()
|
| 647 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 648 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 649 |
+
|
| 650 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 651 |
+
hidden_states = self.dense(hidden_states)
|
| 652 |
+
hidden_states = self.dropout(hidden_states)
|
| 653 |
+
|
| 654 |
+
hidden_states = hidden_states + input_tensor
|
| 655 |
+
|
| 656 |
+
return hidden_states
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
# Copied from transformers.models.vit.modeling_vit.ViTLayer with ViT->ViTMAE,VIT->VITMAE
|
| 661 |
+
class ViTMAELayer(nn.Module):
|
| 662 |
+
"""This corresponds to the Block class in the timm implementation."""
|
| 663 |
+
|
| 664 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 665 |
+
super().__init__()
|
| 666 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 667 |
+
self.seq_len_dim = 1
|
| 668 |
+
self.attention = ViTMAEAttention(config) # no SPDA by default
|
| 669 |
+
self.intermediate = ViTMAEIntermediate(config)
|
| 670 |
+
self.output = ViTMAEOutput(config)
|
| 671 |
+
self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 672 |
+
self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 673 |
+
|
| 674 |
+
def forward(
|
| 675 |
+
self,
|
| 676 |
+
hidden_states: torch.Tensor,
|
| 677 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 678 |
+
output_attentions: bool = False,
|
| 679 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 680 |
+
self_attention_outputs = self.attention(
|
| 681 |
+
self.layernorm_before(hidden_states), # in ViTMAE, layernorm is applied before self-attention
|
| 682 |
+
head_mask,
|
| 683 |
+
output_attentions=output_attentions,
|
| 684 |
+
)
|
| 685 |
+
attention_output = self_attention_outputs[0]
|
| 686 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 687 |
+
|
| 688 |
+
# first residual connection
|
| 689 |
+
hidden_states = attention_output + hidden_states
|
| 690 |
+
|
| 691 |
+
# in ViTMAE, layernorm is also applied after self-attention
|
| 692 |
+
layer_output = self.layernorm_after(hidden_states)
|
| 693 |
+
layer_output = self.intermediate(layer_output)
|
| 694 |
+
|
| 695 |
+
# second residual connection is done here
|
| 696 |
+
layer_output = self.output(layer_output, hidden_states)
|
| 697 |
+
|
| 698 |
+
outputs = (layer_output,) + outputs
|
| 699 |
+
|
| 700 |
+
return outputs
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
class GeneralDecoder(nn.Module):
|
| 704 |
+
def __init__(self, config, num_patches):
|
| 705 |
+
super().__init__()
|
| 706 |
+
self.decoder_embed = nn.Linear(config.hidden_size, config.decoder_hidden_size, bias=True)
|
| 707 |
+
self.decoder_pos_embed = nn.Parameter(
|
| 708 |
+
torch.zeros(1, num_patches + 1, config.decoder_hidden_size), requires_grad=False
|
| 709 |
+
) # fixed sin-cos embedding
|
| 710 |
+
|
| 711 |
+
decoder_config = deepcopy(config)
|
| 712 |
+
decoder_config.hidden_size = config.decoder_hidden_size
|
| 713 |
+
decoder_config.num_hidden_layers = config.decoder_num_hidden_layers
|
| 714 |
+
decoder_config.num_attention_heads = config.decoder_num_attention_heads
|
| 715 |
+
decoder_config.intermediate_size = config.decoder_intermediate_size
|
| 716 |
+
self.decoder_layers = nn.ModuleList(
|
| 717 |
+
[ViTMAELayer(decoder_config) for _ in range(config.decoder_num_hidden_layers)]
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
self.decoder_norm = nn.LayerNorm(config.decoder_hidden_size, eps=config.layer_norm_eps)
|
| 721 |
+
self.decoder_pred = nn.Linear(
|
| 722 |
+
config.decoder_hidden_size, config.patch_size**2 * config.num_channels, bias=True
|
| 723 |
+
) # encoder to decoder
|
| 724 |
+
self.gradient_checkpointing = False
|
| 725 |
+
self.config = config
|
| 726 |
+
self.num_patches = num_patches
|
| 727 |
+
self.initialize_weights(num_patches)
|
| 728 |
+
self.decoder_config = decoder_config
|
| 729 |
+
self.set_trainable_cls_token()
|
| 730 |
+
def set_trainable_cls_token(self, tensor: Optional[torch.Tensor] = None):
|
| 731 |
+
# register a trainable CLS token
|
| 732 |
+
tensor = torch.zeros(1, 1, self.decoder_config.hidden_size) if tensor is None else tensor
|
| 733 |
+
self.trainable_cls_token = nn.Parameter(tensor)
|
| 734 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor) -> torch.Tensor:
|
| 735 |
+
"""
|
| 736 |
+
This method is a modified version of the interpolation function for ViT-mae model at the deocder, that
|
| 737 |
+
allows to interpolate the pre-trained decoder position encodings, to be able to use the model on higher
|
| 738 |
+
resolution images.
|
| 739 |
+
|
| 740 |
+
Source:
|
| 741 |
+
https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174
|
| 742 |
+
"""
|
| 743 |
+
|
| 744 |
+
# -1 removes the class dimension since we later append it without interpolation
|
| 745 |
+
embeddings_positions = embeddings.shape[1] - 1
|
| 746 |
+
num_positions = self.decoder_pos_embed.shape[1] - 1
|
| 747 |
+
|
| 748 |
+
# Separation of class token and patch tokens
|
| 749 |
+
class_pos_embed = self.decoder_pos_embed[:, 0, :]
|
| 750 |
+
patch_pos_embed = self.decoder_pos_embed[:, 1:, :]
|
| 751 |
+
|
| 752 |
+
# To retain the final 3d tensor with the required dimensions
|
| 753 |
+
dim = self.decoder_pos_embed.shape[-1]
|
| 754 |
+
|
| 755 |
+
# Increasing a dimension to enable bicubic interpolation
|
| 756 |
+
patch_pos_embed = patch_pos_embed.reshape(1, 1, -1, dim)
|
| 757 |
+
|
| 758 |
+
# permute to bring the dimension to be interpolated, to the last
|
| 759 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 760 |
+
|
| 761 |
+
# Interpolating the decoder position embeddings shape wrt embeddings shape i.e (x).
|
| 762 |
+
# 1 keeps the other dimension constant
|
| 763 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 764 |
+
patch_pos_embed,
|
| 765 |
+
scale_factor=(1, embeddings_positions / num_positions),
|
| 766 |
+
mode="bicubic",
|
| 767 |
+
align_corners=False,
|
| 768 |
+
)
|
| 769 |
+
|
| 770 |
+
# Converting back to the original shape
|
| 771 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 772 |
+
# Adding the class token back
|
| 773 |
+
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
|
| 774 |
+
def interpolate_latent(self, x: torch.Tensor) -> torch.Tensor:
|
| 775 |
+
b, l, c = x.shape
|
| 776 |
+
if l == self.num_patches:
|
| 777 |
+
return x
|
| 778 |
+
# interpolate the latent
|
| 779 |
+
#print(f"interpolating latent from {l} to {self.num_patches}, x.shape = {x.shape}")
|
| 780 |
+
h, w = int(l**0.5), int(l**0.5)
|
| 781 |
+
x = x.reshape(b, h, w, c)
|
| 782 |
+
x = x.permute(0, 3, 1, 2)
|
| 783 |
+
target_size = (int(self.num_patches**0.5), int(self.num_patches**0.5))
|
| 784 |
+
x = nn.functional.interpolate(x, size=target_size, mode="bilinear", align_corners=False)
|
| 785 |
+
x = x.permute(0, 2, 3, 1).contiguous().view(b, self.num_patches, c)
|
| 786 |
+
return x
|
| 787 |
+
|
| 788 |
+
def initialize_weights(self, num_patches):
|
| 789 |
+
# initialize (and freeze) position embeddings by sin-cos embedding
|
| 790 |
+
decoder_pos_embed = get_2d_sincos_pos_embed(
|
| 791 |
+
self.decoder_pos_embed.shape[-1], int(num_patches**0.5), add_cls_token=True
|
| 792 |
+
)
|
| 793 |
+
self.decoder_pos_embed.data.copy_(torch.from_numpy(decoder_pos_embed).float().unsqueeze(0))
|
| 794 |
+
|
| 795 |
+
# timm's trunc_normal_(std=.02) is effectively normal_(std=0.02) as cutoff is too big (2.)
|
| 796 |
+
# torch.nn.init.normal_(self.mask_token, std=self.config.initializer_range)
|
| 797 |
+
def unpatchify(self, patchified_pixel_values, original_image_size: Optional[Tuple[int, int]] = None):
|
| 798 |
+
"""
|
| 799 |
+
Args:
|
| 800 |
+
patchified_pixel_values (`torch.FloatTensor` of shape `(batch_size, num_patches, patch_size**2 * num_channels)`:
|
| 801 |
+
Patchified pixel values.
|
| 802 |
+
original_image_size (`Tuple[int, int]`, *optional*):
|
| 803 |
+
Original image size.
|
| 804 |
+
|
| 805 |
+
Returns:
|
| 806 |
+
`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`:
|
| 807 |
+
Pixel values.
|
| 808 |
+
"""
|
| 809 |
+
patch_size, num_channels = self.config.patch_size, self.config.num_channels
|
| 810 |
+
original_image_size = (
|
| 811 |
+
original_image_size
|
| 812 |
+
if original_image_size is not None
|
| 813 |
+
else (self.config.image_size, self.config.image_size)
|
| 814 |
+
)
|
| 815 |
+
original_height, original_width = original_image_size
|
| 816 |
+
num_patches_h = original_height // patch_size
|
| 817 |
+
num_patches_w = original_width // patch_size
|
| 818 |
+
# sanity check
|
| 819 |
+
if num_patches_h * num_patches_w != patchified_pixel_values.shape[1]:
|
| 820 |
+
raise ValueError(
|
| 821 |
+
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}"
|
| 822 |
+
)
|
| 823 |
+
|
| 824 |
+
# unpatchify
|
| 825 |
+
batch_size = patchified_pixel_values.shape[0]
|
| 826 |
+
patchified_pixel_values = patchified_pixel_values.reshape(
|
| 827 |
+
batch_size,
|
| 828 |
+
num_patches_h,
|
| 829 |
+
num_patches_w,
|
| 830 |
+
patch_size,
|
| 831 |
+
patch_size,
|
| 832 |
+
num_channels,
|
| 833 |
+
)
|
| 834 |
+
patchified_pixel_values = torch.einsum("nhwpqc->nchpwq", patchified_pixel_values)
|
| 835 |
+
pixel_values = patchified_pixel_values.reshape(
|
| 836 |
+
batch_size,
|
| 837 |
+
num_channels,
|
| 838 |
+
num_patches_h * patch_size,
|
| 839 |
+
num_patches_w * patch_size,
|
| 840 |
+
)
|
| 841 |
+
return pixel_values
|
| 842 |
+
|
| 843 |
+
def forward(
|
| 844 |
+
self,
|
| 845 |
+
hidden_states,
|
| 846 |
+
output_attentions=False,
|
| 847 |
+
output_hidden_states=False,
|
| 848 |
+
return_dict=True,
|
| 849 |
+
interpolate_pos_encoding: bool = False,
|
| 850 |
+
drop_cls_token: bool = False,
|
| 851 |
+
):
|
| 852 |
+
# embed tokens
|
| 853 |
+
x = self.decoder_embed(hidden_states)
|
| 854 |
+
#print(f"x.shape = {x.shape}")
|
| 855 |
+
if drop_cls_token:
|
| 856 |
+
x_ = x[:, 1:, :] # no cls token
|
| 857 |
+
x_ = self.interpolate_latent(x_)
|
| 858 |
+
else:
|
| 859 |
+
x_ = self.interpolate_latent(x) # interpolate the whole latent
|
| 860 |
+
cls_token = self.trainable_cls_token.expand(x_.shape[0], -1, -1)
|
| 861 |
+
x = torch.cat([cls_token, x_], dim=1)
|
| 862 |
+
|
| 863 |
+
# add pos embed
|
| 864 |
+
if interpolate_pos_encoding:
|
| 865 |
+
assert drop_cls_token, "interpolate_pos_encoding only works with drop_cls_token=True"
|
| 866 |
+
decoder_pos_embed = self.interpolate_pos_encoding(x)
|
| 867 |
+
else:
|
| 868 |
+
decoder_pos_embed = self.decoder_pos_embed
|
| 869 |
+
hidden_states = x + decoder_pos_embed
|
| 870 |
+
#print(f"hidden_states.shape = {hidden_states.shape}")
|
| 871 |
+
# apply Transformer layers (blocks)
|
| 872 |
+
all_hidden_states = () if output_hidden_states else None
|
| 873 |
+
all_self_attentions = () if output_attentions else None
|
| 874 |
+
for i, layer_module in enumerate(self.decoder_layers):
|
| 875 |
+
if output_hidden_states:
|
| 876 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 877 |
+
|
| 878 |
+
if self.gradient_checkpointing and self.training:
|
| 879 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 880 |
+
layer_module.__call__,
|
| 881 |
+
hidden_states,
|
| 882 |
+
None,
|
| 883 |
+
output_attentions,
|
| 884 |
+
)
|
| 885 |
+
else:
|
| 886 |
+
layer_outputs = layer_module(hidden_states, head_mask=None, output_attentions=output_attentions)
|
| 887 |
+
|
| 888 |
+
hidden_states = layer_outputs[0]
|
| 889 |
+
|
| 890 |
+
if output_attentions:
|
| 891 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 892 |
+
|
| 893 |
+
if output_hidden_states:
|
| 894 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 895 |
+
|
| 896 |
+
hidden_states = self.decoder_norm(hidden_states)
|
| 897 |
+
|
| 898 |
+
# predictor projection
|
| 899 |
+
logits = self.decoder_pred(hidden_states)
|
| 900 |
+
|
| 901 |
+
# remove cls token
|
| 902 |
+
logits = logits[:, 1:, :]
|
| 903 |
+
|
| 904 |
+
if not return_dict:
|
| 905 |
+
return tuple(v for v in [logits, all_hidden_states, all_self_attentions] if v is not None)
|
| 906 |
+
return ViTMAEDecoderOutput(
|
| 907 |
+
logits=logits,
|
| 908 |
+
hidden_states=all_hidden_states,
|
| 909 |
+
attentions=all_self_attentions,
|
| 910 |
+
)
|
| 911 |
+
|
| 912 |
+
import json
|
| 913 |
+
from math import sqrt
|
| 914 |
+
from pathlib import Path
|
| 915 |
+
from typing import Any, Dict, Optional
|
| 916 |
+
|
| 917 |
+
import torch
|
| 918 |
+
import torch.nn as nn
|
| 919 |
+
from timm.models.vision_transformer import Attention
|
| 920 |
+
from transformers import AutoConfig, AutoImageProcessor
|
| 921 |
+
|
| 922 |
+
try:
|
| 923 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 924 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 925 |
+
except Exception: # pragma: no cover
|
| 926 |
+
class ConfigMixin:
|
| 927 |
+
config_name = "config.json"
|
| 928 |
+
|
| 929 |
+
class ModelMixin(nn.Module):
|
| 930 |
+
pass
|
| 931 |
+
|
| 932 |
+
def register_to_config(init):
|
| 933 |
+
return init
|
| 934 |
+
|
| 935 |
+
|
| 936 |
+
_PIXEL_DECODER_DEFAULTS: Dict[str, Any] = {
|
| 937 |
+
"decoder_hidden_size": 1024,
|
| 938 |
+
"decoder_intermediate_size": 4096,
|
| 939 |
+
"decoder_num_attention_heads": 16,
|
| 940 |
+
"decoder_num_hidden_layers": 24,
|
| 941 |
+
"layer_norm_eps": 1e-12,
|
| 942 |
+
"num_channels": 3,
|
| 943 |
+
"hidden_act": "gelu",
|
| 944 |
+
"qkv_bias": True,
|
| 945 |
+
"hidden_dropout_prob": 0.0,
|
| 946 |
+
"attention_probs_dropout_prob": 0.0,
|
| 947 |
+
"initializer_range": 0.02,
|
| 948 |
+
}
|
| 949 |
+
|
| 950 |
+
|
| 951 |
+
def _resolve_local_asset_path(path: str, model_root: Optional[Path] = None) -> str:
|
| 952 |
+
candidate = Path(path)
|
| 953 |
+
if candidate.is_file():
|
| 954 |
+
return str(candidate)
|
| 955 |
+
search_roots = []
|
| 956 |
+
if model_root is not None:
|
| 957 |
+
search_roots.extend([model_root, model_root.parent])
|
| 958 |
+
for root in search_roots:
|
| 959 |
+
for probe in (root / candidate, root / candidate.name, root / "decoder_config" / "config.json"):
|
| 960 |
+
if probe.is_file():
|
| 961 |
+
return str(probe)
|
| 962 |
+
return path
|
| 963 |
+
|
| 964 |
+
|
| 965 |
+
def _build_pixel_decoder_config(
|
| 966 |
+
*,
|
| 967 |
+
encoder_hidden_size: int,
|
| 968 |
+
decoder_patch_size: int,
|
| 969 |
+
base_patches: int,
|
| 970 |
+
decoder_config_path: Optional[str] = None,
|
| 971 |
+
overrides: Optional[Dict[str, Any]] = None,
|
| 972 |
+
) -> ViTMAEConfig:
|
| 973 |
+
pixel_decoder = dict(_PIXEL_DECODER_DEFAULTS)
|
| 974 |
+
if decoder_config_path is not None:
|
| 975 |
+
resolved = _resolve_local_asset_path(decoder_config_path)
|
| 976 |
+
if Path(resolved).is_file():
|
| 977 |
+
with open(resolved, encoding="utf-8") as handle:
|
| 978 |
+
pixel_decoder.update(json.load(handle))
|
| 979 |
+
if overrides:
|
| 980 |
+
pixel_decoder.update({key: value for key, value in overrides.items() if value is not None})
|
| 981 |
+
|
| 982 |
+
return ViTMAEConfig(
|
| 983 |
+
hidden_size=encoder_hidden_size,
|
| 984 |
+
patch_size=decoder_patch_size,
|
| 985 |
+
image_size=int(decoder_patch_size * sqrt(base_patches)),
|
| 986 |
+
**pixel_decoder,
|
| 987 |
+
)
|
| 988 |
+
|
| 989 |
+
|
| 990 |
+
def _load_image_normalization(encoder_config_path: str) -> tuple[list[float], list[float]]:
|
| 991 |
+
try:
|
| 992 |
+
proc = AutoImageProcessor.from_pretrained(encoder_config_path, use_fast=True, local_files_only=True)
|
| 993 |
+
return proc.image_mean, proc.image_std
|
| 994 |
+
except Exception:
|
| 995 |
+
pass
|
| 996 |
+
try:
|
| 997 |
+
proc = AutoImageProcessor.from_pretrained(encoder_config_path, use_fast=True, local_files_only=False)
|
| 998 |
+
return proc.image_mean, proc.image_std
|
| 999 |
+
except Exception:
|
| 1000 |
+
if "siglip" in encoder_config_path.lower():
|
| 1001 |
+
return [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]
|
| 1002 |
+
return [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
|
| 1003 |
+
|
| 1004 |
+
|
| 1005 |
+
class PAEDecoder(ModelMixin, ConfigMixin):
|
| 1006 |
+
"""PAE decoder: latent decompressor + ViT-MAE pixel decoder."""
|
| 1007 |
+
|
| 1008 |
+
@register_to_config
|
| 1009 |
+
def __init__(
|
| 1010 |
+
self,
|
| 1011 |
+
encoder_hidden_size: int = 1024,
|
| 1012 |
+
encoder_num_heads: int = 16,
|
| 1013 |
+
encoder_input_size: int = 224,
|
| 1014 |
+
encoder_patch_size: int = 14,
|
| 1015 |
+
encoder_config_path: str = "facebook/dinov2-with-registers-large",
|
| 1016 |
+
latent_dim: int = 32,
|
| 1017 |
+
decoder_patch_size: int = 16,
|
| 1018 |
+
decoder_config_path: Optional[str] = None,
|
| 1019 |
+
decoder_hidden_size: int = 1024,
|
| 1020 |
+
decoder_intermediate_size: int = 4096,
|
| 1021 |
+
decoder_num_attention_heads: int = 16,
|
| 1022 |
+
decoder_num_hidden_layers: int = 24,
|
| 1023 |
+
layer_norm_eps: float = 1e-12,
|
| 1024 |
+
num_channels: int = 3,
|
| 1025 |
+
hidden_act: str = "gelu",
|
| 1026 |
+
qkv_bias: bool = True,
|
| 1027 |
+
hidden_dropout_prob: float = 0.0,
|
| 1028 |
+
attention_probs_dropout_prob: float = 0.0,
|
| 1029 |
+
initializer_range: float = 0.02,
|
| 1030 |
+
image_mean: Optional[list[float]] = None,
|
| 1031 |
+
image_std: Optional[list[float]] = None,
|
| 1032 |
+
latent_mean: Optional[list[float]] = None,
|
| 1033 |
+
latent_std: Optional[list[float]] = None,
|
| 1034 |
+
latent_multiplier: float = 1.0,
|
| 1035 |
+
**kwargs,
|
| 1036 |
+
) -> None:
|
| 1037 |
+
super().__init__()
|
| 1038 |
+
if image_mean is not None and image_std is not None:
|
| 1039 |
+
norm_mean, norm_std = image_mean, image_std
|
| 1040 |
+
else:
|
| 1041 |
+
norm_mean, norm_std = _load_image_normalization(encoder_config_path)
|
| 1042 |
+
self.register_buffer("encoder_mean", torch.tensor(norm_mean).view(1, 3, 1, 1), persistent=True)
|
| 1043 |
+
self.register_buffer("encoder_std", torch.tensor(norm_std).view(1, 3, 1, 1), persistent=True)
|
| 1044 |
+
|
| 1045 |
+
self.encoder_input_size = encoder_input_size
|
| 1046 |
+
self.encoder_patch_size = encoder_patch_size
|
| 1047 |
+
self.base_patches = (self.encoder_input_size // self.encoder_patch_size) ** 2
|
| 1048 |
+
self.latent_dim = latent_dim
|
| 1049 |
+
|
| 1050 |
+
self.latent_decompressor = nn.ModuleList(
|
| 1051 |
+
[
|
| 1052 |
+
nn.Conv2d(latent_dim, encoder_hidden_size, kernel_size=3, padding=1),
|
| 1053 |
+
Attention(dim=encoder_hidden_size, num_heads=encoder_num_heads),
|
| 1054 |
+
]
|
| 1055 |
+
)
|
| 1056 |
+
|
| 1057 |
+
pixel_decoder_config = _build_pixel_decoder_config(
|
| 1058 |
+
encoder_hidden_size=encoder_hidden_size,
|
| 1059 |
+
decoder_patch_size=decoder_patch_size,
|
| 1060 |
+
base_patches=self.base_patches,
|
| 1061 |
+
decoder_config_path=decoder_config_path,
|
| 1062 |
+
overrides={
|
| 1063 |
+
"decoder_hidden_size": decoder_hidden_size,
|
| 1064 |
+
"decoder_intermediate_size": decoder_intermediate_size,
|
| 1065 |
+
"decoder_num_attention_heads": decoder_num_attention_heads,
|
| 1066 |
+
"decoder_num_hidden_layers": decoder_num_hidden_layers,
|
| 1067 |
+
"layer_norm_eps": layer_norm_eps,
|
| 1068 |
+
"num_channels": num_channels,
|
| 1069 |
+
"hidden_act": hidden_act,
|
| 1070 |
+
"qkv_bias": qkv_bias,
|
| 1071 |
+
"hidden_dropout_prob": hidden_dropout_prob,
|
| 1072 |
+
"attention_probs_dropout_prob": attention_probs_dropout_prob,
|
| 1073 |
+
"initializer_range": initializer_range,
|
| 1074 |
+
},
|
| 1075 |
+
)
|
| 1076 |
+
self.decoder = GeneralDecoder(pixel_decoder_config, num_patches=self.base_patches)
|
| 1077 |
+
|
| 1078 |
+
@classmethod
|
| 1079 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 1080 |
+
model_root = Path(pretrained_model_name_or_path)
|
| 1081 |
+
config_file = model_root / cls.config_name
|
| 1082 |
+
if config_file.is_file():
|
| 1083 |
+
with open(config_file, encoding="utf-8") as handle:
|
| 1084 |
+
config = json.load(handle)
|
| 1085 |
+
decoder_config_path = config.get("decoder_config_path")
|
| 1086 |
+
if decoder_config_path is not None:
|
| 1087 |
+
resolved = _resolve_local_asset_path(decoder_config_path, model_root=model_root)
|
| 1088 |
+
if resolved != decoder_config_path:
|
| 1089 |
+
kwargs.setdefault("decoder_config_path", resolved)
|
| 1090 |
+
return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
|
| 1091 |
+
|
| 1092 |
+
def decode(self, latents: torch.Tensor) -> torch.Tensor:
|
| 1093 |
+
hidden_states = self.latent_decompressor[0](latents)
|
| 1094 |
+
batch_size, channels, height, width = hidden_states.shape
|
| 1095 |
+
num_tokens = height * width
|
| 1096 |
+
hidden_states = hidden_states.view(batch_size, channels, num_tokens).transpose(1, 2)
|
| 1097 |
+
hidden_states = self.latent_decompressor[1](hidden_states)
|
| 1098 |
+
|
| 1099 |
+
output = self.decoder(hidden_states, drop_cls_token=False).logits
|
| 1100 |
+
x_rec = self.decoder.unpatchify(output)
|
| 1101 |
+
x_rec = x_rec * self.encoder_std.to(x_rec.device) + self.encoder_mean.to(x_rec.device)
|
| 1102 |
+
return x_rec
|
| 1103 |
+
|
| 1104 |
+
def forward(self, latents: torch.Tensor) -> torch.Tensor:
|
| 1105 |
+
return self.decode(latents)
|
pae-dinov3-large-d32/decoder/diffusion_pytorch_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:57842b0b1aaa90793d74c7fa959e9c242a553798320271cde5bf0cd6a372d608
|
| 3 |
+
size 1235663744
|
pae-dinov3-large-d32/demo.png
ADDED
|
pae-dinov3-large-d32/model_index.json
ADDED
|
@@ -0,0 +1,1021 @@
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
"pipeline",
|
| 4 |
+
"PAEPipeline"
|
| 5 |
+
],
|
| 6 |
+
"_diffusers_version": "0.31.0",
|
| 7 |
+
"decoder": [
|
| 8 |
+
"decoder_pae",
|
| 9 |
+
"PAEDecoder"
|
| 10 |
+
],
|
| 11 |
+
"id2label": {
|
| 12 |
+
"0": "tench, Tinca tinca",
|
| 13 |
+
"1": "goldfish, Carassius auratus",
|
| 14 |
+
"2": "great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias",
|
| 15 |
+
"3": "tiger shark, Galeocerdo cuvieri",
|
| 16 |
+
"4": "hammerhead, hammerhead shark",
|
| 17 |
+
"5": "electric ray, crampfish, numbfish, torpedo",
|
| 18 |
+
"6": "stingray",
|
| 19 |
+
"7": "cock",
|
| 20 |
+
"8": "hen",
|
| 21 |
+
"9": "ostrich, Struthio camelus",
|
| 22 |
+
"10": "brambling, Fringilla montifringilla",
|
| 23 |
+
"11": "goldfinch, Carduelis carduelis",
|
| 24 |
+
"12": "house finch, linnet, Carpodacus mexicanus",
|
| 25 |
+
"13": "junco, snowbird",
|
| 26 |
+
"14": "indigo bunting, indigo finch, indigo bird, Passerina cyanea",
|
| 27 |
+
"15": "robin, American robin, Turdus migratorius",
|
| 28 |
+
"16": "bulbul",
|
| 29 |
+
"17": "jay",
|
| 30 |
+
"18": "magpie",
|
| 31 |
+
"19": "chickadee",
|
| 32 |
+
"20": "water ouzel, dipper",
|
| 33 |
+
"21": "kite",
|
| 34 |
+
"22": "bald eagle, American eagle, Haliaeetus leucocephalus",
|
| 35 |
+
"23": "vulture",
|
| 36 |
+
"24": "great grey owl, great gray owl, Strix nebulosa",
|
| 37 |
+
"25": "European fire salamander, Salamandra salamandra",
|
| 38 |
+
"26": "common newt, Triturus vulgaris",
|
| 39 |
+
"27": "eft",
|
| 40 |
+
"28": "spotted salamander, Ambystoma maculatum",
|
| 41 |
+
"29": "axolotl, mud puppy, Ambystoma mexicanum",
|
| 42 |
+
"30": "bullfrog, Rana catesbeiana",
|
| 43 |
+
"31": "tree frog, tree-frog",
|
| 44 |
+
"32": "tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui",
|
| 45 |
+
"33": "loggerhead, loggerhead turtle, Caretta caretta",
|
| 46 |
+
"34": "leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea",
|
| 47 |
+
"35": "mud turtle",
|
| 48 |
+
"36": "terrapin",
|
| 49 |
+
"37": "box turtle, box tortoise",
|
| 50 |
+
"38": "banded gecko",
|
| 51 |
+
"39": "common iguana, iguana, Iguana iguana",
|
| 52 |
+
"40": "American chameleon, anole, Anolis carolinensis",
|
| 53 |
+
"41": "whiptail, whiptail lizard",
|
| 54 |
+
"42": "agama",
|
| 55 |
+
"43": "frilled lizard, Chlamydosaurus kingi",
|
| 56 |
+
"44": "alligator lizard",
|
| 57 |
+
"45": "Gila monster, Heloderma suspectum",
|
| 58 |
+
"46": "green lizard, Lacerta viridis",
|
| 59 |
+
"47": "African chameleon, Chamaeleo chamaeleon",
|
| 60 |
+
"48": "Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis",
|
| 61 |
+
"49": "African crocodile, Nile crocodile, Crocodylus niloticus",
|
| 62 |
+
"50": "American alligator, Alligator mississipiensis",
|
| 63 |
+
"51": "triceratops",
|
| 64 |
+
"52": "thunder snake, worm snake, Carphophis amoenus",
|
| 65 |
+
"53": "ringneck snake, ring-necked snake, ring snake",
|
| 66 |
+
"54": "hognose snake, puff adder, sand viper",
|
| 67 |
+
"55": "green snake, grass snake",
|
| 68 |
+
"56": "king snake, kingsnake",
|
| 69 |
+
"57": "garter snake, grass snake",
|
| 70 |
+
"58": "water snake",
|
| 71 |
+
"59": "vine snake",
|
| 72 |
+
"60": "night snake, Hypsiglena torquata",
|
| 73 |
+
"61": "boa constrictor, Constrictor constrictor",
|
| 74 |
+
"62": "rock python, rock snake, Python sebae",
|
| 75 |
+
"63": "Indian cobra, Naja naja",
|
| 76 |
+
"64": "green mamba",
|
| 77 |
+
"65": "sea snake",
|
| 78 |
+
"66": "horned viper, cerastes, sand viper, horned asp, Cerastes cornutus",
|
| 79 |
+
"67": "diamondback, diamondback rattlesnake, Crotalus adamanteus",
|
| 80 |
+
"68": "sidewinder, horned rattlesnake, Crotalus cerastes",
|
| 81 |
+
"69": "trilobite",
|
| 82 |
+
"70": "harvestman, daddy longlegs, Phalangium opilio",
|
| 83 |
+
"71": "scorpion",
|
| 84 |
+
"72": "black and gold garden spider, Argiope aurantia",
|
| 85 |
+
"73": "barn spider, Araneus cavaticus",
|
| 86 |
+
"74": "garden spider, Aranea diademata",
|
| 87 |
+
"75": "black widow, Latrodectus mactans",
|
| 88 |
+
"76": "tarantula",
|
| 89 |
+
"77": "wolf spider, hunting spider",
|
| 90 |
+
"78": "tick",
|
| 91 |
+
"79": "centipede",
|
| 92 |
+
"80": "black grouse",
|
| 93 |
+
"81": "ptarmigan",
|
| 94 |
+
"82": "ruffed grouse, partridge, Bonasa umbellus",
|
| 95 |
+
"83": "prairie chicken, prairie grouse, prairie fowl",
|
| 96 |
+
"84": "peacock",
|
| 97 |
+
"85": "quail",
|
| 98 |
+
"86": "partridge",
|
| 99 |
+
"87": "African grey, African gray, Psittacus erithacus",
|
| 100 |
+
"88": "macaw",
|
| 101 |
+
"89": "sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita",
|
| 102 |
+
"90": "lorikeet",
|
| 103 |
+
"91": "coucal",
|
| 104 |
+
"92": "bee eater",
|
| 105 |
+
"93": "hornbill",
|
| 106 |
+
"94": "hummingbird",
|
| 107 |
+
"95": "jacamar",
|
| 108 |
+
"96": "toucan",
|
| 109 |
+
"97": "drake",
|
| 110 |
+
"98": "red-breasted merganser, Mergus serrator",
|
| 111 |
+
"99": "goose",
|
| 112 |
+
"100": "black swan, Cygnus atratus",
|
| 113 |
+
"101": "tusker",
|
| 114 |
+
"102": "echidna, spiny anteater, anteater",
|
| 115 |
+
"103": "platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus",
|
| 116 |
+
"104": "wallaby, brush kangaroo",
|
| 117 |
+
"105": "koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus",
|
| 118 |
+
"106": "wombat",
|
| 119 |
+
"107": "jellyfish",
|
| 120 |
+
"108": "sea anemone, anemone",
|
| 121 |
+
"109": "brain coral",
|
| 122 |
+
"110": "flatworm, platyhelminth",
|
| 123 |
+
"111": "nematode, nematode worm, roundworm",
|
| 124 |
+
"112": "conch",
|
| 125 |
+
"113": "snail",
|
| 126 |
+
"114": "slug",
|
| 127 |
+
"115": "sea slug, nudibranch",
|
| 128 |
+
"116": "chiton, coat-of-mail shell, sea cradle, polyplacophore",
|
| 129 |
+
"117": "chambered nautilus, pearly nautilus, nautilus",
|
| 130 |
+
"118": "Dungeness crab, Cancer magister",
|
| 131 |
+
"119": "rock crab, Cancer irroratus",
|
| 132 |
+
"120": "fiddler crab",
|
| 133 |
+
"121": "king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica",
|
| 134 |
+
"122": "American lobster, Northern lobster, Maine lobster, Homarus americanus",
|
| 135 |
+
"123": "spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish",
|
| 136 |
+
"124": "crayfish, crawfish, crawdad, crawdaddy",
|
| 137 |
+
"125": "hermit crab",
|
| 138 |
+
"126": "isopod",
|
| 139 |
+
"127": "white stork, Ciconia ciconia",
|
| 140 |
+
"128": "black stork, Ciconia nigra",
|
| 141 |
+
"129": "spoonbill",
|
| 142 |
+
"130": "flamingo",
|
| 143 |
+
"131": "little blue heron, Egretta caerulea",
|
| 144 |
+
"132": "American egret, great white heron, Egretta albus",
|
| 145 |
+
"133": "bittern",
|
| 146 |
+
"134": "crane",
|
| 147 |
+
"135": "limpkin, Aramus pictus",
|
| 148 |
+
"136": "European gallinule, Porphyrio porphyrio",
|
| 149 |
+
"137": "American coot, marsh hen, mud hen, water hen, Fulica americana",
|
| 150 |
+
"138": "bustard",
|
| 151 |
+
"139": "ruddy turnstone, Arenaria interpres",
|
| 152 |
+
"140": "red-backed sandpiper, dunlin, Erolia alpina",
|
| 153 |
+
"141": "redshank, Tringa totanus",
|
| 154 |
+
"142": "dowitcher",
|
| 155 |
+
"143": "oystercatcher, oyster catcher",
|
| 156 |
+
"144": "pelican",
|
| 157 |
+
"145": "king penguin, Aptenodytes patagonica",
|
| 158 |
+
"146": "albatross, mollymawk",
|
| 159 |
+
"147": "grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus",
|
| 160 |
+
"148": "killer whale, killer, orca, grampus, sea wolf, Orcinus orca",
|
| 161 |
+
"149": "dugong, Dugong dugon",
|
| 162 |
+
"150": "sea lion",
|
| 163 |
+
"151": "Chihuahua",
|
| 164 |
+
"152": "Japanese spaniel",
|
| 165 |
+
"153": "Maltese dog, Maltese terrier, Maltese",
|
| 166 |
+
"154": "Pekinese, Pekingese, Peke",
|
| 167 |
+
"155": "Shih-Tzu",
|
| 168 |
+
"156": "Blenheim spaniel",
|
| 169 |
+
"157": "papillon",
|
| 170 |
+
"158": "toy terrier",
|
| 171 |
+
"159": "Rhodesian ridgeback",
|
| 172 |
+
"160": "Afghan hound, Afghan",
|
| 173 |
+
"161": "basset, basset hound",
|
| 174 |
+
"162": "beagle",
|
| 175 |
+
"163": "bloodhound, sleuthhound",
|
| 176 |
+
"164": "bluetick",
|
| 177 |
+
"165": "black-and-tan coonhound",
|
| 178 |
+
"166": "Walker hound, Walker foxhound",
|
| 179 |
+
"167": "English foxhound",
|
| 180 |
+
"168": "redbone",
|
| 181 |
+
"169": "borzoi, Russian wolfhound",
|
| 182 |
+
"170": "Irish wolfhound",
|
| 183 |
+
"171": "Italian greyhound",
|
| 184 |
+
"172": "whippet",
|
| 185 |
+
"173": "Ibizan hound, Ibizan Podenco",
|
| 186 |
+
"174": "Norwegian elkhound, elkhound",
|
| 187 |
+
"175": "otterhound, otter hound",
|
| 188 |
+
"176": "Saluki, gazelle hound",
|
| 189 |
+
"177": "Scottish deerhound, deerhound",
|
| 190 |
+
"178": "Weimaraner",
|
| 191 |
+
"179": "Staffordshire bullterrier, Staffordshire bull terrier",
|
| 192 |
+
"180": "American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier",
|
| 193 |
+
"181": "Bedlington terrier",
|
| 194 |
+
"182": "Border terrier",
|
| 195 |
+
"183": "Kerry blue terrier",
|
| 196 |
+
"184": "Irish terrier",
|
| 197 |
+
"185": "Norfolk terrier",
|
| 198 |
+
"186": "Norwich terrier",
|
| 199 |
+
"187": "Yorkshire terrier",
|
| 200 |
+
"188": "wire-haired fox terrier",
|
| 201 |
+
"189": "Lakeland terrier",
|
| 202 |
+
"190": "Sealyham terrier, Sealyham",
|
| 203 |
+
"191": "Airedale, Airedale terrier",
|
| 204 |
+
"192": "cairn, cairn terrier",
|
| 205 |
+
"193": "Australian terrier",
|
| 206 |
+
"194": "Dandie Dinmont, Dandie Dinmont terrier",
|
| 207 |
+
"195": "Boston bull, Boston terrier",
|
| 208 |
+
"196": "miniature schnauzer",
|
| 209 |
+
"197": "giant schnauzer",
|
| 210 |
+
"198": "standard schnauzer",
|
| 211 |
+
"199": "Scotch terrier, Scottish terrier, Scottie",
|
| 212 |
+
"200": "Tibetan terrier, chrysanthemum dog",
|
| 213 |
+
"201": "silky terrier, Sydney silky",
|
| 214 |
+
"202": "soft-coated wheaten terrier",
|
| 215 |
+
"203": "West Highland white terrier",
|
| 216 |
+
"204": "Lhasa, Lhasa apso",
|
| 217 |
+
"205": "flat-coated retriever",
|
| 218 |
+
"206": "curly-coated retriever",
|
| 219 |
+
"207": "golden retriever",
|
| 220 |
+
"208": "Labrador retriever",
|
| 221 |
+
"209": "Chesapeake Bay retriever",
|
| 222 |
+
"210": "German short-haired pointer",
|
| 223 |
+
"211": "vizsla, Hungarian pointer",
|
| 224 |
+
"212": "English setter",
|
| 225 |
+
"213": "Irish setter, red setter",
|
| 226 |
+
"214": "Gordon setter",
|
| 227 |
+
"215": "Brittany spaniel",
|
| 228 |
+
"216": "clumber, clumber spaniel",
|
| 229 |
+
"217": "English springer, English springer spaniel",
|
| 230 |
+
"218": "Welsh springer spaniel",
|
| 231 |
+
"219": "cocker spaniel, English cocker spaniel, cocker",
|
| 232 |
+
"220": "Sussex spaniel",
|
| 233 |
+
"221": "Irish water spaniel",
|
| 234 |
+
"222": "kuvasz",
|
| 235 |
+
"223": "schipperke",
|
| 236 |
+
"224": "groenendael",
|
| 237 |
+
"225": "malinois",
|
| 238 |
+
"226": "briard",
|
| 239 |
+
"227": "kelpie",
|
| 240 |
+
"228": "komondor",
|
| 241 |
+
"229": "Old English sheepdog, bobtail",
|
| 242 |
+
"230": "Shetland sheepdog, Shetland sheep dog, Shetland",
|
| 243 |
+
"231": "collie",
|
| 244 |
+
"232": "Border collie",
|
| 245 |
+
"233": "Bouvier des Flandres, Bouviers des Flandres",
|
| 246 |
+
"234": "Rottweiler",
|
| 247 |
+
"235": "German shepherd, German shepherd dog, German police dog, alsatian",
|
| 248 |
+
"236": "Doberman, Doberman pinscher",
|
| 249 |
+
"237": "miniature pinscher",
|
| 250 |
+
"238": "Greater Swiss Mountain dog",
|
| 251 |
+
"239": "Bernese mountain dog",
|
| 252 |
+
"240": "Appenzeller",
|
| 253 |
+
"241": "EntleBucher",
|
| 254 |
+
"242": "boxer",
|
| 255 |
+
"243": "bull mastiff",
|
| 256 |
+
"244": "Tibetan mastiff",
|
| 257 |
+
"245": "French bulldog",
|
| 258 |
+
"246": "Great Dane",
|
| 259 |
+
"247": "Saint Bernard, St Bernard",
|
| 260 |
+
"248": "Eskimo dog, husky",
|
| 261 |
+
"249": "malamute, malemute, Alaskan malamute",
|
| 262 |
+
"250": "Siberian husky",
|
| 263 |
+
"251": "dalmatian, coach dog, carriage dog",
|
| 264 |
+
"252": "affenpinscher, monkey pinscher, monkey dog",
|
| 265 |
+
"253": "basenji",
|
| 266 |
+
"254": "pug, pug-dog",
|
| 267 |
+
"255": "Leonberg",
|
| 268 |
+
"256": "Newfoundland, Newfoundland dog",
|
| 269 |
+
"257": "Great Pyrenees",
|
| 270 |
+
"258": "Samoyed, Samoyede",
|
| 271 |
+
"259": "Pomeranian",
|
| 272 |
+
"260": "chow, chow chow",
|
| 273 |
+
"261": "keeshond",
|
| 274 |
+
"262": "Brabancon griffon",
|
| 275 |
+
"263": "Pembroke, Pembroke Welsh corgi",
|
| 276 |
+
"264": "Cardigan, Cardigan Welsh corgi",
|
| 277 |
+
"265": "toy poodle",
|
| 278 |
+
"266": "miniature poodle",
|
| 279 |
+
"267": "standard poodle",
|
| 280 |
+
"268": "Mexican hairless",
|
| 281 |
+
"269": "timber wolf, grey wolf, gray wolf, Canis lupus",
|
| 282 |
+
"270": "white wolf, Arctic wolf, Canis lupus tundrarum",
|
| 283 |
+
"271": "red wolf, maned wolf, Canis rufus, Canis niger",
|
| 284 |
+
"272": "coyote, prairie wolf, brush wolf, Canis latrans",
|
| 285 |
+
"273": "dingo, warrigal, warragal, Canis dingo",
|
| 286 |
+
"274": "dhole, Cuon alpinus",
|
| 287 |
+
"275": "African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus",
|
| 288 |
+
"276": "hyena, hyaena",
|
| 289 |
+
"277": "red fox, Vulpes vulpes",
|
| 290 |
+
"278": "kit fox, Vulpes macrotis",
|
| 291 |
+
"279": "Arctic fox, white fox, Alopex lagopus",
|
| 292 |
+
"280": "grey fox, gray fox, Urocyon cinereoargenteus",
|
| 293 |
+
"281": "tabby, tabby cat",
|
| 294 |
+
"282": "tiger cat",
|
| 295 |
+
"283": "Persian cat",
|
| 296 |
+
"284": "Siamese cat, Siamese",
|
| 297 |
+
"285": "Egyptian cat",
|
| 298 |
+
"286": "cougar, puma, catamount, mountain lion, painter, panther, Felis concolor",
|
| 299 |
+
"287": "lynx, catamount",
|
| 300 |
+
"288": "leopard, Panthera pardus",
|
| 301 |
+
"289": "snow leopard, ounce, Panthera uncia",
|
| 302 |
+
"290": "jaguar, panther, Panthera onca, Felis onca",
|
| 303 |
+
"291": "lion, king of beasts, Panthera leo",
|
| 304 |
+
"292": "tiger, Panthera tigris",
|
| 305 |
+
"293": "cheetah, chetah, Acinonyx jubatus",
|
| 306 |
+
"294": "brown bear, bruin, Ursus arctos",
|
| 307 |
+
"295": "American black bear, black bear, Ursus americanus, Euarctos americanus",
|
| 308 |
+
"296": "ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus",
|
| 309 |
+
"297": "sloth bear, Melursus ursinus, Ursus ursinus",
|
| 310 |
+
"298": "mongoose",
|
| 311 |
+
"299": "meerkat, mierkat",
|
| 312 |
+
"300": "tiger beetle",
|
| 313 |
+
"301": "ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle",
|
| 314 |
+
"302": "ground beetle, carabid beetle",
|
| 315 |
+
"303": "long-horned beetle, longicorn, longicorn beetle",
|
| 316 |
+
"304": "leaf beetle, chrysomelid",
|
| 317 |
+
"305": "dung beetle",
|
| 318 |
+
"306": "rhinoceros beetle",
|
| 319 |
+
"307": "weevil",
|
| 320 |
+
"308": "fly",
|
| 321 |
+
"309": "bee",
|
| 322 |
+
"310": "ant, emmet, pismire",
|
| 323 |
+
"311": "grasshopper, hopper",
|
| 324 |
+
"312": "cricket",
|
| 325 |
+
"313": "walking stick, walkingstick, stick insect",
|
| 326 |
+
"314": "cockroach, roach",
|
| 327 |
+
"315": "mantis, mantid",
|
| 328 |
+
"316": "cicada, cicala",
|
| 329 |
+
"317": "leafhopper",
|
| 330 |
+
"318": "lacewing, lacewing fly",
|
| 331 |
+
"319": "dragonfly, darning needle, devils darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk",
|
| 332 |
+
"320": "damselfly",
|
| 333 |
+
"321": "admiral",
|
| 334 |
+
"322": "ringlet, ringlet butterfly",
|
| 335 |
+
"323": "monarch, monarch butterfly, milkweed butterfly, Danaus plexippus",
|
| 336 |
+
"324": "cabbage butterfly",
|
| 337 |
+
"325": "sulphur butterfly, sulfur butterfly",
|
| 338 |
+
"326": "lycaenid, lycaenid butterfly",
|
| 339 |
+
"327": "starfish, sea star",
|
| 340 |
+
"328": "sea urchin",
|
| 341 |
+
"329": "sea cucumber, holothurian",
|
| 342 |
+
"330": "wood rabbit, cottontail, cottontail rabbit",
|
| 343 |
+
"331": "hare",
|
| 344 |
+
"332": "Angora, Angora rabbit",
|
| 345 |
+
"333": "hamster",
|
| 346 |
+
"334": "porcupine, hedgehog",
|
| 347 |
+
"335": "fox squirrel, eastern fox squirrel, Sciurus niger",
|
| 348 |
+
"336": "marmot",
|
| 349 |
+
"337": "beaver",
|
| 350 |
+
"338": "guinea pig, Cavia cobaya",
|
| 351 |
+
"339": "sorrel",
|
| 352 |
+
"340": "zebra",
|
| 353 |
+
"341": "hog, pig, grunter, squealer, Sus scrofa",
|
| 354 |
+
"342": "wild boar, boar, Sus scrofa",
|
| 355 |
+
"343": "warthog",
|
| 356 |
+
"344": "hippopotamus, hippo, river horse, Hippopotamus amphibius",
|
| 357 |
+
"345": "ox",
|
| 358 |
+
"346": "water buffalo, water ox, Asiatic buffalo, Bubalus bubalis",
|
| 359 |
+
"347": "bison",
|
| 360 |
+
"348": "ram, tup",
|
| 361 |
+
"349": "bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis",
|
| 362 |
+
"350": "ibex, Capra ibex",
|
| 363 |
+
"351": "hartebeest",
|
| 364 |
+
"352": "impala, Aepyceros melampus",
|
| 365 |
+
"353": "gazelle",
|
| 366 |
+
"354": "Arabian camel, dromedary, Camelus dromedarius",
|
| 367 |
+
"355": "llama",
|
| 368 |
+
"356": "weasel",
|
| 369 |
+
"357": "mink",
|
| 370 |
+
"358": "polecat, fitch, foulmart, foumart, Mustela putorius",
|
| 371 |
+
"359": "black-footed ferret, ferret, Mustela nigripes",
|
| 372 |
+
"360": "otter",
|
| 373 |
+
"361": "skunk, polecat, wood pussy",
|
| 374 |
+
"362": "badger",
|
| 375 |
+
"363": "armadillo",
|
| 376 |
+
"364": "three-toed sloth, ai, Bradypus tridactylus",
|
| 377 |
+
"365": "orangutan, orang, orangutang, Pongo pygmaeus",
|
| 378 |
+
"366": "gorilla, Gorilla gorilla",
|
| 379 |
+
"367": "chimpanzee, chimp, Pan troglodytes",
|
| 380 |
+
"368": "gibbon, Hylobates lar",
|
| 381 |
+
"369": "siamang, Hylobates syndactylus, Symphalangus syndactylus",
|
| 382 |
+
"370": "guenon, guenon monkey",
|
| 383 |
+
"371": "patas, hussar monkey, Erythrocebus patas",
|
| 384 |
+
"372": "baboon",
|
| 385 |
+
"373": "macaque",
|
| 386 |
+
"374": "langur",
|
| 387 |
+
"375": "colobus, colobus monkey",
|
| 388 |
+
"376": "proboscis monkey, Nasalis larvatus",
|
| 389 |
+
"377": "marmoset",
|
| 390 |
+
"378": "capuchin, ringtail, Cebus capucinus",
|
| 391 |
+
"379": "howler monkey, howler",
|
| 392 |
+
"380": "titi, titi monkey",
|
| 393 |
+
"381": "spider monkey, Ateles geoffroyi",
|
| 394 |
+
"382": "squirrel monkey, Saimiri sciureus",
|
| 395 |
+
"383": "Madagascar cat, ring-tailed lemur, Lemur catta",
|
| 396 |
+
"384": "indri, indris, Indri indri, Indri brevicaudatus",
|
| 397 |
+
"385": "Indian elephant, Elephas maximus",
|
| 398 |
+
"386": "African elephant, Loxodonta africana",
|
| 399 |
+
"387": "lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens",
|
| 400 |
+
"388": "giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca",
|
| 401 |
+
"389": "barracouta, snoek",
|
| 402 |
+
"390": "eel",
|
| 403 |
+
"391": "coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch",
|
| 404 |
+
"392": "rock beauty, Holocanthus tricolor",
|
| 405 |
+
"393": "anemone fish",
|
| 406 |
+
"394": "sturgeon",
|
| 407 |
+
"395": "gar, garfish, garpike, billfish, Lepisosteus osseus",
|
| 408 |
+
"396": "lionfish",
|
| 409 |
+
"397": "puffer, pufferfish, blowfish, globefish",
|
| 410 |
+
"398": "abacus",
|
| 411 |
+
"399": "abaya",
|
| 412 |
+
"400": "academic gown, academic robe, judge robe",
|
| 413 |
+
"401": "accordion, piano accordion, squeeze box",
|
| 414 |
+
"402": "acoustic guitar",
|
| 415 |
+
"403": "aircraft carrier, carrier, flattop, attack aircraft carrier",
|
| 416 |
+
"404": "airliner",
|
| 417 |
+
"405": "airship, dirigible",
|
| 418 |
+
"406": "altar",
|
| 419 |
+
"407": "ambulance",
|
| 420 |
+
"408": "amphibian, amphibious vehicle",
|
| 421 |
+
"409": "analog clock",
|
| 422 |
+
"410": "apiary, bee house",
|
| 423 |
+
"411": "apron",
|
| 424 |
+
"412": "ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin",
|
| 425 |
+
"413": "assault rifle, assault gun",
|
| 426 |
+
"414": "backpack, back pack, knapsack, packsack, rucksack, haversack",
|
| 427 |
+
"415": "bakery, bakeshop, bakehouse",
|
| 428 |
+
"416": "balance beam, beam",
|
| 429 |
+
"417": "balloon",
|
| 430 |
+
"418": "ballpoint, ballpoint pen, ballpen, Biro",
|
| 431 |
+
"419": "Band Aid",
|
| 432 |
+
"420": "banjo",
|
| 433 |
+
"421": "bannister, banister, balustrade, balusters, handrail",
|
| 434 |
+
"422": "barbell",
|
| 435 |
+
"423": "barber chair",
|
| 436 |
+
"424": "barbershop",
|
| 437 |
+
"425": "barn",
|
| 438 |
+
"426": "barometer",
|
| 439 |
+
"427": "barrel, cask",
|
| 440 |
+
"428": "barrow, garden cart, lawn cart, wheelbarrow",
|
| 441 |
+
"429": "baseball",
|
| 442 |
+
"430": "basketball",
|
| 443 |
+
"431": "bassinet",
|
| 444 |
+
"432": "bassoon",
|
| 445 |
+
"433": "bathing cap, swimming cap",
|
| 446 |
+
"434": "bath towel",
|
| 447 |
+
"435": "bathtub, bathing tub, bath, tub",
|
| 448 |
+
"436": "beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon",
|
| 449 |
+
"437": "beacon, lighthouse, beacon light, pharos",
|
| 450 |
+
"438": "beaker",
|
| 451 |
+
"439": "bearskin, busby, shako",
|
| 452 |
+
"440": "beer bottle",
|
| 453 |
+
"441": "beer glass",
|
| 454 |
+
"442": "bell cote, bell cot",
|
| 455 |
+
"443": "bib",
|
| 456 |
+
"444": "bicycle-built-for-two, tandem bicycle, tandem",
|
| 457 |
+
"445": "bikini, two-piece",
|
| 458 |
+
"446": "binder, ring-binder",
|
| 459 |
+
"447": "binoculars, field glasses, opera glasses",
|
| 460 |
+
"448": "birdhouse",
|
| 461 |
+
"449": "boathouse",
|
| 462 |
+
"450": "bobsled, bobsleigh, bob",
|
| 463 |
+
"451": "bolo tie, bolo, bola tie, bola",
|
| 464 |
+
"452": "bonnet, poke bonnet",
|
| 465 |
+
"453": "bookcase",
|
| 466 |
+
"454": "bookshop, bookstore, bookstall",
|
| 467 |
+
"455": "bottlecap",
|
| 468 |
+
"456": "bow",
|
| 469 |
+
"457": "bow tie, bow-tie, bowtie",
|
| 470 |
+
"458": "brass, memorial tablet, plaque",
|
| 471 |
+
"459": "brassiere, bra, bandeau",
|
| 472 |
+
"460": "breakwater, groin, groyne, mole, bulwark, seawall, jetty",
|
| 473 |
+
"461": "breastplate, aegis, egis",
|
| 474 |
+
"462": "broom",
|
| 475 |
+
"463": "bucket, pail",
|
| 476 |
+
"464": "buckle",
|
| 477 |
+
"465": "bulletproof vest",
|
| 478 |
+
"466": "bullet train, bullet",
|
| 479 |
+
"467": "butcher shop, meat market",
|
| 480 |
+
"468": "cab, hack, taxi, taxicab",
|
| 481 |
+
"469": "caldron, cauldron",
|
| 482 |
+
"470": "candle, taper, wax light",
|
| 483 |
+
"471": "cannon",
|
| 484 |
+
"472": "canoe",
|
| 485 |
+
"473": "can opener, tin opener",
|
| 486 |
+
"474": "cardigan",
|
| 487 |
+
"475": "car mirror",
|
| 488 |
+
"476": "carousel, carrousel, merry-go-round, roundabout, whirligig",
|
| 489 |
+
"477": "carpenters kit, tool kit",
|
| 490 |
+
"478": "carton",
|
| 491 |
+
"479": "car wheel",
|
| 492 |
+
"480": "cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM",
|
| 493 |
+
"481": "cassette",
|
| 494 |
+
"482": "cassette player",
|
| 495 |
+
"483": "castle",
|
| 496 |
+
"484": "catamaran",
|
| 497 |
+
"485": "CD player",
|
| 498 |
+
"486": "cello, violoncello",
|
| 499 |
+
"487": "cellular telephone, cellular phone, cellphone, cell, mobile phone",
|
| 500 |
+
"488": "chain",
|
| 501 |
+
"489": "chainlink fence",
|
| 502 |
+
"490": "chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour",
|
| 503 |
+
"491": "chain saw, chainsaw",
|
| 504 |
+
"492": "chest",
|
| 505 |
+
"493": "chiffonier, commode",
|
| 506 |
+
"494": "chime, bell, gong",
|
| 507 |
+
"495": "china cabinet, china closet",
|
| 508 |
+
"496": "Christmas stocking",
|
| 509 |
+
"497": "church, church building",
|
| 510 |
+
"498": "cinema, movie theater, movie theatre, movie house, picture palace",
|
| 511 |
+
"499": "cleaver, meat cleaver, chopper",
|
| 512 |
+
"500": "cliff dwelling",
|
| 513 |
+
"501": "cloak",
|
| 514 |
+
"502": "clog, geta, patten, sabot",
|
| 515 |
+
"503": "cocktail shaker",
|
| 516 |
+
"504": "coffee mug",
|
| 517 |
+
"505": "coffeepot",
|
| 518 |
+
"506": "coil, spiral, volute, whorl, helix",
|
| 519 |
+
"507": "combination lock",
|
| 520 |
+
"508": "computer keyboard, keypad",
|
| 521 |
+
"509": "confectionery, confectionary, candy store",
|
| 522 |
+
"510": "container ship, containership, container vessel",
|
| 523 |
+
"511": "convertible",
|
| 524 |
+
"512": "corkscrew, bottle screw",
|
| 525 |
+
"513": "cornet, horn, trumpet, trump",
|
| 526 |
+
"514": "cowboy boot",
|
| 527 |
+
"515": "cowboy hat, ten-gallon hat",
|
| 528 |
+
"516": "cradle",
|
| 529 |
+
"517": "crane",
|
| 530 |
+
"518": "crash helmet",
|
| 531 |
+
"519": "crate",
|
| 532 |
+
"520": "crib, cot",
|
| 533 |
+
"521": "Crock Pot",
|
| 534 |
+
"522": "croquet ball",
|
| 535 |
+
"523": "crutch",
|
| 536 |
+
"524": "cuirass",
|
| 537 |
+
"525": "dam, dike, dyke",
|
| 538 |
+
"526": "desk",
|
| 539 |
+
"527": "desktop computer",
|
| 540 |
+
"528": "dial telephone, dial phone",
|
| 541 |
+
"529": "diaper, nappy, napkin",
|
| 542 |
+
"530": "digital clock",
|
| 543 |
+
"531": "digital watch",
|
| 544 |
+
"532": "dining table, board",
|
| 545 |
+
"533": "dishrag, dishcloth",
|
| 546 |
+
"534": "dishwasher, dish washer, dishwashing machine",
|
| 547 |
+
"535": "disk brake, disc brake",
|
| 548 |
+
"536": "dock, dockage, docking facility",
|
| 549 |
+
"537": "dogsled, dog sled, dog sleigh",
|
| 550 |
+
"538": "dome",
|
| 551 |
+
"539": "doormat, welcome mat",
|
| 552 |
+
"540": "drilling platform, offshore rig",
|
| 553 |
+
"541": "drum, membranophone, tympan",
|
| 554 |
+
"542": "drumstick",
|
| 555 |
+
"543": "dumbbell",
|
| 556 |
+
"544": "Dutch oven",
|
| 557 |
+
"545": "electric fan, blower",
|
| 558 |
+
"546": "electric guitar",
|
| 559 |
+
"547": "electric locomotive",
|
| 560 |
+
"548": "entertainment center",
|
| 561 |
+
"549": "envelope",
|
| 562 |
+
"550": "espresso maker",
|
| 563 |
+
"551": "face powder",
|
| 564 |
+
"552": "feather boa, boa",
|
| 565 |
+
"553": "file, file cabinet, filing cabinet",
|
| 566 |
+
"554": "fireboat",
|
| 567 |
+
"555": "fire engine, fire truck",
|
| 568 |
+
"556": "fire screen, fireguard",
|
| 569 |
+
"557": "flagpole, flagstaff",
|
| 570 |
+
"558": "flute, transverse flute",
|
| 571 |
+
"559": "folding chair",
|
| 572 |
+
"560": "football helmet",
|
| 573 |
+
"561": "forklift",
|
| 574 |
+
"562": "fountain",
|
| 575 |
+
"563": "fountain pen",
|
| 576 |
+
"564": "four-poster",
|
| 577 |
+
"565": "freight car",
|
| 578 |
+
"566": "French horn, horn",
|
| 579 |
+
"567": "frying pan, frypan, skillet",
|
| 580 |
+
"568": "fur coat",
|
| 581 |
+
"569": "garbage truck, dustcart",
|
| 582 |
+
"570": "gasmask, respirator, gas helmet",
|
| 583 |
+
"571": "gas pump, gasoline pump, petrol pump, island dispenser",
|
| 584 |
+
"572": "goblet",
|
| 585 |
+
"573": "go-kart",
|
| 586 |
+
"574": "golf ball",
|
| 587 |
+
"575": "golfcart, golf cart",
|
| 588 |
+
"576": "gondola",
|
| 589 |
+
"577": "gong, tam-tam",
|
| 590 |
+
"578": "gown",
|
| 591 |
+
"579": "grand piano, grand",
|
| 592 |
+
"580": "greenhouse, nursery, glasshouse",
|
| 593 |
+
"581": "grille, radiator grille",
|
| 594 |
+
"582": "grocery store, grocery, food market, market",
|
| 595 |
+
"583": "guillotine",
|
| 596 |
+
"584": "hair slide",
|
| 597 |
+
"585": "hair spray",
|
| 598 |
+
"586": "half track",
|
| 599 |
+
"587": "hammer",
|
| 600 |
+
"588": "hamper",
|
| 601 |
+
"589": "hand blower, blow dryer, blow drier, hair dryer, hair drier",
|
| 602 |
+
"590": "hand-held computer, hand-held microcomputer",
|
| 603 |
+
"591": "handkerchief, hankie, hanky, hankey",
|
| 604 |
+
"592": "hard disc, hard disk, fixed disk",
|
| 605 |
+
"593": "harmonica, mouth organ, harp, mouth harp",
|
| 606 |
+
"594": "harp",
|
| 607 |
+
"595": "harvester, reaper",
|
| 608 |
+
"596": "hatchet",
|
| 609 |
+
"597": "holster",
|
| 610 |
+
"598": "home theater, home theatre",
|
| 611 |
+
"599": "honeycomb",
|
| 612 |
+
"600": "hook, claw",
|
| 613 |
+
"601": "hoopskirt, crinoline",
|
| 614 |
+
"602": "horizontal bar, high bar",
|
| 615 |
+
"603": "horse cart, horse-cart",
|
| 616 |
+
"604": "hourglass",
|
| 617 |
+
"605": "iPod",
|
| 618 |
+
"606": "iron, smoothing iron",
|
| 619 |
+
"607": "jack-o-lantern",
|
| 620 |
+
"608": "jean, blue jean, denim",
|
| 621 |
+
"609": "jeep, landrover",
|
| 622 |
+
"610": "jersey, T-shirt, tee shirt",
|
| 623 |
+
"611": "jigsaw puzzle",
|
| 624 |
+
"612": "jinrikisha, ricksha, rickshaw",
|
| 625 |
+
"613": "joystick",
|
| 626 |
+
"614": "kimono",
|
| 627 |
+
"615": "knee pad",
|
| 628 |
+
"616": "knot",
|
| 629 |
+
"617": "lab coat, laboratory coat",
|
| 630 |
+
"618": "ladle",
|
| 631 |
+
"619": "lampshade, lamp shade",
|
| 632 |
+
"620": "laptop, laptop computer",
|
| 633 |
+
"621": "lawn mower, mower",
|
| 634 |
+
"622": "lens cap, lens cover",
|
| 635 |
+
"623": "letter opener, paper knife, paperknife",
|
| 636 |
+
"624": "library",
|
| 637 |
+
"625": "lifeboat",
|
| 638 |
+
"626": "lighter, light, igniter, ignitor",
|
| 639 |
+
"627": "limousine, limo",
|
| 640 |
+
"628": "liner, ocean liner",
|
| 641 |
+
"629": "lipstick, lip rouge",
|
| 642 |
+
"630": "Loafer",
|
| 643 |
+
"631": "lotion",
|
| 644 |
+
"632": "loudspeaker, speaker, speaker unit, loudspeaker system, speaker system",
|
| 645 |
+
"633": "loupe, jewelers loupe",
|
| 646 |
+
"634": "lumbermill, sawmill",
|
| 647 |
+
"635": "magnetic compass",
|
| 648 |
+
"636": "mailbag, postbag",
|
| 649 |
+
"637": "mailbox, letter box",
|
| 650 |
+
"638": "maillot",
|
| 651 |
+
"639": "maillot, tank suit",
|
| 652 |
+
"640": "manhole cover",
|
| 653 |
+
"641": "maraca",
|
| 654 |
+
"642": "marimba, xylophone",
|
| 655 |
+
"643": "mask",
|
| 656 |
+
"644": "matchstick",
|
| 657 |
+
"645": "maypole",
|
| 658 |
+
"646": "maze, labyrinth",
|
| 659 |
+
"647": "measuring cup",
|
| 660 |
+
"648": "medicine chest, medicine cabinet",
|
| 661 |
+
"649": "megalith, megalithic structure",
|
| 662 |
+
"650": "microphone, mike",
|
| 663 |
+
"651": "microwave, microwave oven",
|
| 664 |
+
"652": "military uniform",
|
| 665 |
+
"653": "milk can",
|
| 666 |
+
"654": "minibus",
|
| 667 |
+
"655": "miniskirt, mini",
|
| 668 |
+
"656": "minivan",
|
| 669 |
+
"657": "missile",
|
| 670 |
+
"658": "mitten",
|
| 671 |
+
"659": "mixing bowl",
|
| 672 |
+
"660": "mobile home, manufactured home",
|
| 673 |
+
"661": "Model T",
|
| 674 |
+
"662": "modem",
|
| 675 |
+
"663": "monastery",
|
| 676 |
+
"664": "monitor",
|
| 677 |
+
"665": "moped",
|
| 678 |
+
"666": "mortar",
|
| 679 |
+
"667": "mortarboard",
|
| 680 |
+
"668": "mosque",
|
| 681 |
+
"669": "mosquito net",
|
| 682 |
+
"670": "motor scooter, scooter",
|
| 683 |
+
"671": "mountain bike, all-terrain bike, off-roader",
|
| 684 |
+
"672": "mountain tent",
|
| 685 |
+
"673": "mouse, computer mouse",
|
| 686 |
+
"674": "mousetrap",
|
| 687 |
+
"675": "moving van",
|
| 688 |
+
"676": "muzzle",
|
| 689 |
+
"677": "nail",
|
| 690 |
+
"678": "neck brace",
|
| 691 |
+
"679": "necklace",
|
| 692 |
+
"680": "nipple",
|
| 693 |
+
"681": "notebook, notebook computer",
|
| 694 |
+
"682": "obelisk",
|
| 695 |
+
"683": "oboe, hautboy, hautbois",
|
| 696 |
+
"684": "ocarina, sweet potato",
|
| 697 |
+
"685": "odometer, hodometer, mileometer, milometer",
|
| 698 |
+
"686": "oil filter",
|
| 699 |
+
"687": "organ, pipe organ",
|
| 700 |
+
"688": "oscilloscope, scope, cathode-ray oscilloscope, CRO",
|
| 701 |
+
"689": "overskirt",
|
| 702 |
+
"690": "oxcart",
|
| 703 |
+
"691": "oxygen mask",
|
| 704 |
+
"692": "packet",
|
| 705 |
+
"693": "paddle, boat paddle",
|
| 706 |
+
"694": "paddlewheel, paddle wheel",
|
| 707 |
+
"695": "padlock",
|
| 708 |
+
"696": "paintbrush",
|
| 709 |
+
"697": "pajama, pyjama, pjs, jammies",
|
| 710 |
+
"698": "palace",
|
| 711 |
+
"699": "panpipe, pandean pipe, syrinx",
|
| 712 |
+
"700": "paper towel",
|
| 713 |
+
"701": "parachute, chute",
|
| 714 |
+
"702": "parallel bars, bars",
|
| 715 |
+
"703": "park bench",
|
| 716 |
+
"704": "parking meter",
|
| 717 |
+
"705": "passenger car, coach, carriage",
|
| 718 |
+
"706": "patio, terrace",
|
| 719 |
+
"707": "pay-phone, pay-station",
|
| 720 |
+
"708": "pedestal, plinth, footstall",
|
| 721 |
+
"709": "pencil box, pencil case",
|
| 722 |
+
"710": "pencil sharpener",
|
| 723 |
+
"711": "perfume, essence",
|
| 724 |
+
"712": "Petri dish",
|
| 725 |
+
"713": "photocopier",
|
| 726 |
+
"714": "pick, plectrum, plectron",
|
| 727 |
+
"715": "pickelhaube",
|
| 728 |
+
"716": "picket fence, paling",
|
| 729 |
+
"717": "pickup, pickup truck",
|
| 730 |
+
"718": "pier",
|
| 731 |
+
"719": "piggy bank, penny bank",
|
| 732 |
+
"720": "pill bottle",
|
| 733 |
+
"721": "pillow",
|
| 734 |
+
"722": "ping-pong ball",
|
| 735 |
+
"723": "pinwheel",
|
| 736 |
+
"724": "pirate, pirate ship",
|
| 737 |
+
"725": "pitcher, ewer",
|
| 738 |
+
"726": "plane, carpenters plane, woodworking plane",
|
| 739 |
+
"727": "planetarium",
|
| 740 |
+
"728": "plastic bag",
|
| 741 |
+
"729": "plate rack",
|
| 742 |
+
"730": "plow, plough",
|
| 743 |
+
"731": "plunger, plumbers helper",
|
| 744 |
+
"732": "Polaroid camera, Polaroid Land camera",
|
| 745 |
+
"733": "pole",
|
| 746 |
+
"734": "police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria",
|
| 747 |
+
"735": "poncho",
|
| 748 |
+
"736": "pool table, billiard table, snooker table",
|
| 749 |
+
"737": "pop bottle, soda bottle",
|
| 750 |
+
"738": "pot, flowerpot",
|
| 751 |
+
"739": "potters wheel",
|
| 752 |
+
"740": "power drill",
|
| 753 |
+
"741": "prayer rug, prayer mat",
|
| 754 |
+
"742": "printer",
|
| 755 |
+
"743": "prison, prison house",
|
| 756 |
+
"744": "projectile, missile",
|
| 757 |
+
"745": "projector",
|
| 758 |
+
"746": "puck, hockey puck",
|
| 759 |
+
"747": "punching bag, punch bag, punching ball, punchball",
|
| 760 |
+
"748": "purse",
|
| 761 |
+
"749": "quill, quill pen",
|
| 762 |
+
"750": "quilt, comforter, comfort, puff",
|
| 763 |
+
"751": "racer, race car, racing car",
|
| 764 |
+
"752": "racket, racquet",
|
| 765 |
+
"753": "radiator",
|
| 766 |
+
"754": "radio, wireless",
|
| 767 |
+
"755": "radio telescope, radio reflector",
|
| 768 |
+
"756": "rain barrel",
|
| 769 |
+
"757": "recreational vehicle, RV, R.V.",
|
| 770 |
+
"758": "reel",
|
| 771 |
+
"759": "reflex camera",
|
| 772 |
+
"760": "refrigerator, icebox",
|
| 773 |
+
"761": "remote control, remote",
|
| 774 |
+
"762": "restaurant, eating house, eating place, eatery",
|
| 775 |
+
"763": "revolver, six-gun, six-shooter",
|
| 776 |
+
"764": "rifle",
|
| 777 |
+
"765": "rocking chair, rocker",
|
| 778 |
+
"766": "rotisserie",
|
| 779 |
+
"767": "rubber eraser, rubber, pencil eraser",
|
| 780 |
+
"768": "rugby ball",
|
| 781 |
+
"769": "rule, ruler",
|
| 782 |
+
"770": "running shoe",
|
| 783 |
+
"771": "safe",
|
| 784 |
+
"772": "safety pin",
|
| 785 |
+
"773": "saltshaker, salt shaker",
|
| 786 |
+
"774": "sandal",
|
| 787 |
+
"775": "sarong",
|
| 788 |
+
"776": "sax, saxophone",
|
| 789 |
+
"777": "scabbard",
|
| 790 |
+
"778": "scale, weighing machine",
|
| 791 |
+
"779": "school bus",
|
| 792 |
+
"780": "schooner",
|
| 793 |
+
"781": "scoreboard",
|
| 794 |
+
"782": "screen, CRT screen",
|
| 795 |
+
"783": "screw",
|
| 796 |
+
"784": "screwdriver",
|
| 797 |
+
"785": "seat belt, seatbelt",
|
| 798 |
+
"786": "sewing machine",
|
| 799 |
+
"787": "shield, buckler",
|
| 800 |
+
"788": "shoe shop, shoe-shop, shoe store",
|
| 801 |
+
"789": "shoji",
|
| 802 |
+
"790": "shopping basket",
|
| 803 |
+
"791": "shopping cart",
|
| 804 |
+
"792": "shovel",
|
| 805 |
+
"793": "shower cap",
|
| 806 |
+
"794": "shower curtain",
|
| 807 |
+
"795": "ski",
|
| 808 |
+
"796": "ski mask",
|
| 809 |
+
"797": "sleeping bag",
|
| 810 |
+
"798": "slide rule, slipstick",
|
| 811 |
+
"799": "sliding door",
|
| 812 |
+
"800": "slot, one-armed bandit",
|
| 813 |
+
"801": "snorkel",
|
| 814 |
+
"802": "snowmobile",
|
| 815 |
+
"803": "snowplow, snowplough",
|
| 816 |
+
"804": "soap dispenser",
|
| 817 |
+
"805": "soccer ball",
|
| 818 |
+
"806": "sock",
|
| 819 |
+
"807": "solar dish, solar collector, solar furnace",
|
| 820 |
+
"808": "sombrero",
|
| 821 |
+
"809": "soup bowl",
|
| 822 |
+
"810": "space bar",
|
| 823 |
+
"811": "space heater",
|
| 824 |
+
"812": "space shuttle",
|
| 825 |
+
"813": "spatula",
|
| 826 |
+
"814": "speedboat",
|
| 827 |
+
"815": "spider web, spiders web",
|
| 828 |
+
"816": "spindle",
|
| 829 |
+
"817": "sports car, sport car",
|
| 830 |
+
"818": "spotlight, spot",
|
| 831 |
+
"819": "stage",
|
| 832 |
+
"820": "steam locomotive",
|
| 833 |
+
"821": "steel arch bridge",
|
| 834 |
+
"822": "steel drum",
|
| 835 |
+
"823": "stethoscope",
|
| 836 |
+
"824": "stole",
|
| 837 |
+
"825": "stone wall",
|
| 838 |
+
"826": "stopwatch, stop watch",
|
| 839 |
+
"827": "stove",
|
| 840 |
+
"828": "strainer",
|
| 841 |
+
"829": "streetcar, tram, tramcar, trolley, trolley car",
|
| 842 |
+
"830": "stretcher",
|
| 843 |
+
"831": "studio couch, day bed",
|
| 844 |
+
"832": "stupa, tope",
|
| 845 |
+
"833": "submarine, pigboat, sub, U-boat",
|
| 846 |
+
"834": "suit, suit of clothes",
|
| 847 |
+
"835": "sundial",
|
| 848 |
+
"836": "sunglass",
|
| 849 |
+
"837": "sunglasses, dark glasses, shades",
|
| 850 |
+
"838": "sunscreen, sunblock, sun blocker",
|
| 851 |
+
"839": "suspension bridge",
|
| 852 |
+
"840": "swab, swob, mop",
|
| 853 |
+
"841": "sweatshirt",
|
| 854 |
+
"842": "swimming trunks, bathing trunks",
|
| 855 |
+
"843": "swing",
|
| 856 |
+
"844": "switch, electric switch, electrical switch",
|
| 857 |
+
"845": "syringe",
|
| 858 |
+
"846": "table lamp",
|
| 859 |
+
"847": "tank, army tank, armored combat vehicle, armoured combat vehicle",
|
| 860 |
+
"848": "tape player",
|
| 861 |
+
"849": "teapot",
|
| 862 |
+
"850": "teddy, teddy bear",
|
| 863 |
+
"851": "television, television system",
|
| 864 |
+
"852": "tennis ball",
|
| 865 |
+
"853": "thatch, thatched roof",
|
| 866 |
+
"854": "theater curtain, theatre curtain",
|
| 867 |
+
"855": "thimble",
|
| 868 |
+
"856": "thresher, thrasher, threshing machine",
|
| 869 |
+
"857": "throne",
|
| 870 |
+
"858": "tile roof",
|
| 871 |
+
"859": "toaster",
|
| 872 |
+
"860": "tobacco shop, tobacconist shop, tobacconist",
|
| 873 |
+
"861": "toilet seat",
|
| 874 |
+
"862": "torch",
|
| 875 |
+
"863": "totem pole",
|
| 876 |
+
"864": "tow truck, tow car, wrecker",
|
| 877 |
+
"865": "toyshop",
|
| 878 |
+
"866": "tractor",
|
| 879 |
+
"867": "trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi",
|
| 880 |
+
"868": "tray",
|
| 881 |
+
"869": "trench coat",
|
| 882 |
+
"870": "tricycle, trike, velocipede",
|
| 883 |
+
"871": "trimaran",
|
| 884 |
+
"872": "tripod",
|
| 885 |
+
"873": "triumphal arch",
|
| 886 |
+
"874": "trolleybus, trolley coach, trackless trolley",
|
| 887 |
+
"875": "trombone",
|
| 888 |
+
"876": "tub, vat",
|
| 889 |
+
"877": "turnstile",
|
| 890 |
+
"878": "typewriter keyboard",
|
| 891 |
+
"879": "umbrella",
|
| 892 |
+
"880": "unicycle, monocycle",
|
| 893 |
+
"881": "upright, upright piano",
|
| 894 |
+
"882": "vacuum, vacuum cleaner",
|
| 895 |
+
"883": "vase",
|
| 896 |
+
"884": "vault",
|
| 897 |
+
"885": "velvet",
|
| 898 |
+
"886": "vending machine",
|
| 899 |
+
"887": "vestment",
|
| 900 |
+
"888": "viaduct",
|
| 901 |
+
"889": "violin, fiddle",
|
| 902 |
+
"890": "volleyball",
|
| 903 |
+
"891": "waffle iron",
|
| 904 |
+
"892": "wall clock",
|
| 905 |
+
"893": "wallet, billfold, notecase, pocketbook",
|
| 906 |
+
"894": "wardrobe, closet, press",
|
| 907 |
+
"895": "warplane, military plane",
|
| 908 |
+
"896": "washbasin, handbasin, washbowl, lavabo, wash-hand basin",
|
| 909 |
+
"897": "washer, automatic washer, washing machine",
|
| 910 |
+
"898": "water bottle",
|
| 911 |
+
"899": "water jug",
|
| 912 |
+
"900": "water tower",
|
| 913 |
+
"901": "whiskey jug",
|
| 914 |
+
"902": "whistle",
|
| 915 |
+
"903": "wig",
|
| 916 |
+
"904": "window screen",
|
| 917 |
+
"905": "window shade",
|
| 918 |
+
"906": "Windsor tie",
|
| 919 |
+
"907": "wine bottle",
|
| 920 |
+
"908": "wing",
|
| 921 |
+
"909": "wok",
|
| 922 |
+
"910": "wooden spoon",
|
| 923 |
+
"911": "wool, woolen, woollen",
|
| 924 |
+
"912": "worm fence, snake fence, snake-rail fence, Virginia fence",
|
| 925 |
+
"913": "wreck",
|
| 926 |
+
"914": "yawl",
|
| 927 |
+
"915": "yurt",
|
| 928 |
+
"916": "web site, website, internet site, site",
|
| 929 |
+
"917": "comic book",
|
| 930 |
+
"918": "crossword puzzle, crossword",
|
| 931 |
+
"919": "street sign",
|
| 932 |
+
"920": "traffic light, traffic signal, stoplight",
|
| 933 |
+
"921": "book jacket, dust cover, dust jacket, dust wrapper",
|
| 934 |
+
"922": "menu",
|
| 935 |
+
"923": "plate",
|
| 936 |
+
"924": "guacamole",
|
| 937 |
+
"925": "consomme",
|
| 938 |
+
"926": "hot pot, hotpot",
|
| 939 |
+
"927": "trifle",
|
| 940 |
+
"928": "ice cream, icecream",
|
| 941 |
+
"929": "ice lolly, lolly, lollipop, popsicle",
|
| 942 |
+
"930": "French loaf",
|
| 943 |
+
"931": "bagel, beigel",
|
| 944 |
+
"932": "pretzel",
|
| 945 |
+
"933": "cheeseburger",
|
| 946 |
+
"934": "hotdog, hot dog, red hot",
|
| 947 |
+
"935": "mashed potato",
|
| 948 |
+
"936": "head cabbage",
|
| 949 |
+
"937": "broccoli",
|
| 950 |
+
"938": "cauliflower",
|
| 951 |
+
"939": "zucchini, courgette",
|
| 952 |
+
"940": "spaghetti squash",
|
| 953 |
+
"941": "acorn squash",
|
| 954 |
+
"942": "butternut squash",
|
| 955 |
+
"943": "cucumber, cuke",
|
| 956 |
+
"944": "artichoke, globe artichoke",
|
| 957 |
+
"945": "bell pepper",
|
| 958 |
+
"946": "cardoon",
|
| 959 |
+
"947": "mushroom",
|
| 960 |
+
"948": "Granny Smith",
|
| 961 |
+
"949": "strawberry",
|
| 962 |
+
"950": "orange",
|
| 963 |
+
"951": "lemon",
|
| 964 |
+
"952": "fig",
|
| 965 |
+
"953": "pineapple, ananas",
|
| 966 |
+
"954": "banana",
|
| 967 |
+
"955": "jackfruit, jak, jack",
|
| 968 |
+
"956": "custard apple",
|
| 969 |
+
"957": "pomegranate",
|
| 970 |
+
"958": "hay",
|
| 971 |
+
"959": "carbonara",
|
| 972 |
+
"960": "chocolate sauce, chocolate syrup",
|
| 973 |
+
"961": "dough",
|
| 974 |
+
"962": "meat loaf, meatloaf",
|
| 975 |
+
"963": "pizza, pizza pie",
|
| 976 |
+
"964": "potpie",
|
| 977 |
+
"965": "burrito",
|
| 978 |
+
"966": "red wine",
|
| 979 |
+
"967": "espresso",
|
| 980 |
+
"968": "cup",
|
| 981 |
+
"969": "eggnog",
|
| 982 |
+
"970": "alp",
|
| 983 |
+
"971": "bubble",
|
| 984 |
+
"972": "cliff, drop, drop-off",
|
| 985 |
+
"973": "coral reef",
|
| 986 |
+
"974": "geyser",
|
| 987 |
+
"975": "lakeside, lakeshore",
|
| 988 |
+
"976": "promontory, headland, head, foreland",
|
| 989 |
+
"977": "sandbar, sand bar",
|
| 990 |
+
"978": "seashore, coast, seacoast, sea-coast",
|
| 991 |
+
"979": "valley, vale",
|
| 992 |
+
"980": "volcano",
|
| 993 |
+
"981": "ballplayer, baseball player",
|
| 994 |
+
"982": "groom, bridegroom",
|
| 995 |
+
"983": "scuba diver",
|
| 996 |
+
"984": "rapeseed",
|
| 997 |
+
"985": "daisy",
|
| 998 |
+
"986": "yellow ladys slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum",
|
| 999 |
+
"987": "corn",
|
| 1000 |
+
"988": "acorn",
|
| 1001 |
+
"989": "hip, rose hip, rosehip",
|
| 1002 |
+
"990": "buckeye, horse chestnut, conker",
|
| 1003 |
+
"991": "coral fungus",
|
| 1004 |
+
"992": "agaric",
|
| 1005 |
+
"993": "gyromitra",
|
| 1006 |
+
"994": "stinkhorn, carrion fungus",
|
| 1007 |
+
"995": "earthstar",
|
| 1008 |
+
"996": "hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa",
|
| 1009 |
+
"997": "bolete",
|
| 1010 |
+
"998": "ear, spike, capitulum",
|
| 1011 |
+
"999": "toilet tissue, toilet paper, bathroom tissue"
|
| 1012 |
+
},
|
| 1013 |
+
"scheduler": [
|
| 1014 |
+
"scheduling_flow_match_pae",
|
| 1015 |
+
"PAEFlowMatchScheduler"
|
| 1016 |
+
],
|
| 1017 |
+
"transformers": [
|
| 1018 |
+
"transformer_lightning_dit",
|
| 1019 |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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hub custom pipeline: PAEPipeline.
|
| 2 |
+
Load with native Hugging Face diffusers and trust_remote_code=True.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
# Copyright 2026 The HuggingFace Team and PAE authors. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import inspect
|
| 24 |
+
import json
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 27 |
+
|
| 28 |
+
import torch
|
| 29 |
+
|
| 30 |
+
from diffusers.image_processor import VaeImageProcessor
|
| 31 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
|
| 32 |
+
from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers
|
| 33 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 34 |
+
|
| 35 |
+
EXAMPLE_DOC_STRING = """
|
| 36 |
+
Examples:
|
| 37 |
+
```py
|
| 38 |
+
>>> from pathlib import Path
|
| 39 |
+
>>> from diffusers import DiffusionPipeline
|
| 40 |
+
>>> import torch
|
| 41 |
+
|
| 42 |
+
>>> model_dir = Path("./pae-dinov2-large-d32").resolve()
|
| 43 |
+
>>> pipe = DiffusionPipeline.from_pretrained(
|
| 44 |
+
... str(model_dir),
|
| 45 |
+
... local_files_only=True,
|
| 46 |
+
... custom_pipeline=str(model_dir / "pipeline.py"),
|
| 47 |
+
... trust_remote_code=True,
|
| 48 |
+
... torch_dtype=torch.bfloat16,
|
| 49 |
+
... )
|
| 50 |
+
>>> pipe.to("cuda")
|
| 51 |
+
|
| 52 |
+
>>> print(pipe.id2label[207])
|
| 53 |
+
>>> print(pipe.get_label_ids("golden retriever"))
|
| 54 |
+
|
| 55 |
+
>>> generator = torch.Generator(device="cuda").manual_seed(42)
|
| 56 |
+
>>> image = pipe(
|
| 57 |
+
... class_labels="golden retriever",
|
| 58 |
+
... generator=generator,
|
| 59 |
+
... ).images[0]
|
| 60 |
+
```
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class PAEPipeline(DiffusionPipeline):
|
| 65 |
+
r"""
|
| 66 |
+
Pipeline for class-conditional image generation with PAE tokenizers and LightningDiT.
|
| 67 |
+
|
| 68 |
+
This model inherits from [`DiffusionPipeline`]. Components are stored in separate subfolders
|
| 69 |
+
(`transformers/`, `scheduler/`, `decoder/`) and loaded via `DiffusionPipeline.from_pretrained`.
|
| 70 |
+
|
| 71 |
+
Parameters:
|
| 72 |
+
transformers ([`LightningDiT2DModel`]):
|
| 73 |
+
Class-conditional LightningDiT transformer that predicts flow-matching velocity in PAE latent space.
|
| 74 |
+
scheduler ([`PAEFlowMatchScheduler`]):
|
| 75 |
+
Flow-matching ODE/SDE scheduler. Other [`KarrasDiffusionSchedulers`] can be swapped at inference time
|
| 76 |
+
when their `step` API is compatible.
|
| 77 |
+
decoder ([`PAEDecoder`]):
|
| 78 |
+
Prior-Aligned Autoencoder decoder stack (decompressor + pixel decoder).
|
| 79 |
+
|
| 80 |
+
ImageNet `id2label` mappings are read lazily from `model_index.json` when label helpers are used.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
model_cpu_offload_seq = "transformers->decoder"
|
| 84 |
+
_optional_components = ["decoder"]
|
| 85 |
+
|
| 86 |
+
@staticmethod
|
| 87 |
+
def prepare_extra_step_kwargs(
|
| 88 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 89 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 90 |
+
eta: Optional[float] = None,
|
| 91 |
+
) -> Dict[str, object]:
|
| 92 |
+
r"""
|
| 93 |
+
Build kwargs forwarded to `scheduler.step` when supported.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
scheduler:
|
| 97 |
+
Active diffusion scheduler instance.
|
| 98 |
+
generator:
|
| 99 |
+
Optional RNG passed through to stochastic scheduler steps.
|
| 100 |
+
eta:
|
| 101 |
+
Optional DDIM-style eta when the scheduler accepts it.
|
| 102 |
+
"""
|
| 103 |
+
kwargs: Dict[str, object] = {}
|
| 104 |
+
step_params = set(inspect.signature(scheduler.step).parameters.keys())
|
| 105 |
+
if "generator" in step_params:
|
| 106 |
+
kwargs["generator"] = generator
|
| 107 |
+
if eta is not None and "eta" in step_params:
|
| 108 |
+
kwargs["eta"] = eta
|
| 109 |
+
return kwargs
|
| 110 |
+
|
| 111 |
+
def __init__(
|
| 112 |
+
self,
|
| 113 |
+
transformers,
|
| 114 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 115 |
+
decoder=None,
|
| 116 |
+
transformer=None,
|
| 117 |
+
) -> None:
|
| 118 |
+
if transformer is not None and transformers is None:
|
| 119 |
+
transformers = transformer
|
| 120 |
+
super().__init__()
|
| 121 |
+
self.register_modules(transformers=transformers, scheduler=scheduler, decoder=decoder)
|
| 122 |
+
# PAE decoders already return pixels in [0, 1]; disable VAE-style [-1, 1] denormalization.
|
| 123 |
+
self.image_processor = VaeImageProcessor(do_normalize=False)
|
| 124 |
+
self._id2label: Dict[int, str] = {}
|
| 125 |
+
self.labels: Dict[str, int] = {}
|
| 126 |
+
self._labels_loaded_from_model_index = False
|
| 127 |
+
|
| 128 |
+
@property
|
| 129 |
+
def transformer(self):
|
| 130 |
+
"""Backward-compatible alias for `transformers`."""
|
| 131 |
+
return self.transformers
|
| 132 |
+
|
| 133 |
+
@staticmethod
|
| 134 |
+
def _normalize_id2label(id2label: Optional[Dict[Union[int, str], str]]) -> Dict[int, str]:
|
| 135 |
+
if not id2label:
|
| 136 |
+
return {}
|
| 137 |
+
return {int(key): value for key, value in id2label.items()}
|
| 138 |
+
|
| 139 |
+
@staticmethod
|
| 140 |
+
def _read_model_index(variant_path: Optional[str]) -> Dict[str, Any]:
|
| 141 |
+
if not variant_path:
|
| 142 |
+
return {}
|
| 143 |
+
variant_dir = Path(variant_path).resolve()
|
| 144 |
+
model_index_path = variant_dir / "model_index.json"
|
| 145 |
+
if not model_index_path.is_file():
|
| 146 |
+
return {}
|
| 147 |
+
raw = json.loads(model_index_path.read_text(encoding="utf-8"))
|
| 148 |
+
return raw if isinstance(raw, dict) else {}
|
| 149 |
+
|
| 150 |
+
@staticmethod
|
| 151 |
+
def _read_id2label_from_model_index(variant_path: Optional[str]) -> Dict[int, str]:
|
| 152 |
+
id2label = PAEPipeline._read_model_index(variant_path).get("id2label")
|
| 153 |
+
if not isinstance(id2label, dict):
|
| 154 |
+
return {}
|
| 155 |
+
return {int(key): value for key, value in id2label.items()}
|
| 156 |
+
|
| 157 |
+
def _get_downsample_ratio(self) -> int:
|
| 158 |
+
override = getattr(self.config, "downsample_ratio", None)
|
| 159 |
+
if override is not None:
|
| 160 |
+
return int(override)
|
| 161 |
+
|
| 162 |
+
encoder_input_size = None
|
| 163 |
+
if self.decoder is not None:
|
| 164 |
+
encoder_input_size = getattr(self.decoder.config, "encoder_input_size", None)
|
| 165 |
+
|
| 166 |
+
if encoder_input_size is not None:
|
| 167 |
+
return int(encoder_input_size) // int(self.transformers.config.input_size)
|
| 168 |
+
return 16
|
| 169 |
+
|
| 170 |
+
def _resolve_latent_stats(
|
| 171 |
+
self,
|
| 172 |
+
latent_mean: Optional[torch.Tensor],
|
| 173 |
+
latent_std: Optional[torch.Tensor],
|
| 174 |
+
latent_multiplier: Optional[float],
|
| 175 |
+
device: torch.device,
|
| 176 |
+
dtype: torch.dtype,
|
| 177 |
+
) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], float]:
|
| 178 |
+
if latent_mean is not None and latent_std is not None:
|
| 179 |
+
return latent_mean, latent_std, float(latent_multiplier if latent_multiplier is not None else 1.0)
|
| 180 |
+
|
| 181 |
+
decoder_cfg = getattr(self.decoder, "config", None) if self.decoder is not None else None
|
| 182 |
+
if decoder_cfg is not None:
|
| 183 |
+
mean = getattr(decoder_cfg, "latent_mean", None)
|
| 184 |
+
std = getattr(decoder_cfg, "latent_std", None)
|
| 185 |
+
if mean is not None and std is not None:
|
| 186 |
+
multiplier = getattr(decoder_cfg, "latent_multiplier", 1.0)
|
| 187 |
+
mean_tensor = torch.tensor(mean, device=device, dtype=dtype).view(1, -1, 1, 1)
|
| 188 |
+
std_tensor = torch.tensor(std, device=device, dtype=dtype).view(1, -1, 1, 1)
|
| 189 |
+
return mean_tensor, std_tensor, float(multiplier)
|
| 190 |
+
|
| 191 |
+
return latent_mean, latent_std, float(latent_multiplier if latent_multiplier is not None else 1.0)
|
| 192 |
+
|
| 193 |
+
@staticmethod
|
| 194 |
+
def _build_label2id(id2label: Dict[int, str]) -> Dict[str, int]:
|
| 195 |
+
label2id: Dict[str, int] = {}
|
| 196 |
+
for class_id, value in id2label.items():
|
| 197 |
+
for synonym in value.split(","):
|
| 198 |
+
synonym = synonym.strip()
|
| 199 |
+
if synonym:
|
| 200 |
+
label2id[synonym] = int(class_id)
|
| 201 |
+
return dict(sorted(label2id.items()))
|
| 202 |
+
|
| 203 |
+
def _ensure_labels_loaded(self) -> None:
|
| 204 |
+
if self._labels_loaded_from_model_index:
|
| 205 |
+
return
|
| 206 |
+
loaded = self._read_id2label_from_model_index(getattr(self.config, "_name_or_path", None))
|
| 207 |
+
if loaded:
|
| 208 |
+
self._id2label = loaded
|
| 209 |
+
self.labels = self._build_label2id(self._id2label)
|
| 210 |
+
self._labels_loaded_from_model_index = True
|
| 211 |
+
|
| 212 |
+
@property
|
| 213 |
+
def id2label(self) -> Dict[int, str]:
|
| 214 |
+
r"""ImageNet class id to English label string (comma-separated synonyms)."""
|
| 215 |
+
self._ensure_labels_loaded()
|
| 216 |
+
return self._id2label
|
| 217 |
+
|
| 218 |
+
def get_label_ids(self, label: Union[str, List[str]]) -> List[int]:
|
| 219 |
+
r"""
|
| 220 |
+
Map ImageNet label strings to class ids.
|
| 221 |
+
|
| 222 |
+
Args:
|
| 223 |
+
label:
|
| 224 |
+
One or more English label strings. Each string must match a synonym in `id2label`.
|
| 225 |
+
|
| 226 |
+
Returns:
|
| 227 |
+
Matching ImageNet class ids.
|
| 228 |
+
"""
|
| 229 |
+
self._ensure_labels_loaded()
|
| 230 |
+
label2id = self.labels
|
| 231 |
+
if not label2id:
|
| 232 |
+
raise ValueError("No English labels loaded. Ensure `id2label` exists in model_index.json.")
|
| 233 |
+
|
| 234 |
+
if isinstance(label, str):
|
| 235 |
+
label = [label]
|
| 236 |
+
|
| 237 |
+
missing = [item for item in label if item not in label2id]
|
| 238 |
+
if missing:
|
| 239 |
+
preview = ", ".join(list(label2id.keys())[:8])
|
| 240 |
+
raise ValueError(f"Unknown English label(s): {missing}. Example valid labels: {preview}, ...")
|
| 241 |
+
return [label2id[item] for item in label]
|
| 242 |
+
|
| 243 |
+
def _default_image_size(self) -> int:
|
| 244 |
+
return int(self.transformers.config.input_size) * self._get_downsample_ratio()
|
| 245 |
+
|
| 246 |
+
def _normalize_class_labels(
|
| 247 |
+
self,
|
| 248 |
+
class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
|
| 249 |
+
) -> torch.LongTensor:
|
| 250 |
+
if torch.is_tensor(class_labels):
|
| 251 |
+
return class_labels.to(device=self._execution_device, dtype=torch.long).reshape(-1)
|
| 252 |
+
|
| 253 |
+
if isinstance(class_labels, int):
|
| 254 |
+
class_label_ids = [class_labels]
|
| 255 |
+
elif isinstance(class_labels, str):
|
| 256 |
+
class_label_ids = self.get_label_ids(class_labels)
|
| 257 |
+
elif class_labels and isinstance(class_labels[0], str):
|
| 258 |
+
class_label_ids = self.get_label_ids(class_labels)
|
| 259 |
+
else:
|
| 260 |
+
class_label_ids = list(class_labels)
|
| 261 |
+
|
| 262 |
+
return torch.tensor(class_label_ids, device=self._execution_device, dtype=torch.long).reshape(-1)
|
| 263 |
+
|
| 264 |
+
def check_inputs(
|
| 265 |
+
self,
|
| 266 |
+
height: int,
|
| 267 |
+
width: int,
|
| 268 |
+
num_inference_steps: int,
|
| 269 |
+
output_type: str,
|
| 270 |
+
mode: str,
|
| 271 |
+
) -> None:
|
| 272 |
+
if num_inference_steps < 1:
|
| 273 |
+
raise ValueError("num_inference_steps must be >= 1.")
|
| 274 |
+
if output_type not in {"pil", "np", "pt", "latent"}:
|
| 275 |
+
raise ValueError("output_type must be one of: 'pil', 'np', 'pt', 'latent'.")
|
| 276 |
+
if mode not in {"ode", "sde"}:
|
| 277 |
+
raise ValueError("mode must be either 'ode' or 'sde'.")
|
| 278 |
+
|
| 279 |
+
downsample = self._get_downsample_ratio()
|
| 280 |
+
if height % downsample != 0 or width % downsample != 0:
|
| 281 |
+
raise ValueError(
|
| 282 |
+
f"height and width must be divisible by the PAE downsample factor {downsample}."
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
latent_height = height // downsample
|
| 286 |
+
latent_width = width // downsample
|
| 287 |
+
expected_size = int(self.transformers.config.input_size)
|
| 288 |
+
if latent_height != expected_size or latent_width != expected_size:
|
| 289 |
+
raise ValueError(
|
| 290 |
+
f"Requested latent size {(latent_height, latent_width)} does not match the pretrained "
|
| 291 |
+
f"transformer input_size={expected_size}. Use height=width={self._default_image_size()}."
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
def prepare_latents(
|
| 295 |
+
self,
|
| 296 |
+
batch_size: int,
|
| 297 |
+
height: int,
|
| 298 |
+
width: int,
|
| 299 |
+
dtype: torch.dtype,
|
| 300 |
+
device: torch.device,
|
| 301 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 302 |
+
) -> torch.Tensor:
|
| 303 |
+
downsample = self._get_downsample_ratio()
|
| 304 |
+
latent_height = height // downsample
|
| 305 |
+
latent_width = width // downsample
|
| 306 |
+
return randn_tensor(
|
| 307 |
+
(batch_size, self.transformers.config.in_channels, latent_height, latent_width),
|
| 308 |
+
generator=generator,
|
| 309 |
+
device=device,
|
| 310 |
+
dtype=dtype,
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
@staticmethod
|
| 314 |
+
def _denormalize_latents(
|
| 315 |
+
latents: torch.Tensor,
|
| 316 |
+
latent_mean: Optional[torch.Tensor],
|
| 317 |
+
latent_std: Optional[torch.Tensor],
|
| 318 |
+
latent_multiplier: Optional[float],
|
| 319 |
+
) -> torch.Tensor:
|
| 320 |
+
if latent_mean is None or latent_std is None:
|
| 321 |
+
return latents
|
| 322 |
+
multiplier = 1.0 if latent_multiplier is None else float(latent_multiplier)
|
| 323 |
+
mean = latent_mean.to(device=latents.device, dtype=latents.dtype)
|
| 324 |
+
std = latent_std.to(device=latents.device, dtype=latents.dtype)
|
| 325 |
+
return (latents * std) / multiplier + mean
|
| 326 |
+
|
| 327 |
+
@staticmethod
|
| 328 |
+
def _apply_cfg(
|
| 329 |
+
model_output: torch.Tensor,
|
| 330 |
+
guidance_scale: float,
|
| 331 |
+
guidance_active: bool,
|
| 332 |
+
cfg_channels: int,
|
| 333 |
+
) -> torch.Tensor:
|
| 334 |
+
if guidance_scale <= 1.0 or not guidance_active:
|
| 335 |
+
return model_output
|
| 336 |
+
eps, rest = model_output[:, :cfg_channels], model_output[:, cfg_channels:]
|
| 337 |
+
cond_eps, uncond_eps = torch.chunk(eps, 2, dim=0)
|
| 338 |
+
half_eps = uncond_eps + guidance_scale * (cond_eps - uncond_eps)
|
| 339 |
+
if rest.shape[1] == 0:
|
| 340 |
+
return half_eps
|
| 341 |
+
return torch.cat([half_eps, rest], dim=1)
|
| 342 |
+
|
| 343 |
+
def decode_latents(
|
| 344 |
+
self,
|
| 345 |
+
latents: torch.Tensor,
|
| 346 |
+
output_type: str = "pil",
|
| 347 |
+
latent_mean: Optional[torch.Tensor] = None,
|
| 348 |
+
latent_std: Optional[torch.Tensor] = None,
|
| 349 |
+
latent_multiplier: Optional[float] = None,
|
| 350 |
+
):
|
| 351 |
+
if output_type == "latent":
|
| 352 |
+
return latents
|
| 353 |
+
if self.decoder is None:
|
| 354 |
+
raise ValueError("PAEPipeline requires a PAE decoder component for decoding.")
|
| 355 |
+
|
| 356 |
+
latent_mean, latent_std, latent_multiplier = self._resolve_latent_stats(
|
| 357 |
+
latent_mean,
|
| 358 |
+
latent_std,
|
| 359 |
+
latent_multiplier,
|
| 360 |
+
device=latents.device,
|
| 361 |
+
dtype=latents.dtype,
|
| 362 |
+
)
|
| 363 |
+
latents = self._denormalize_latents(latents, latent_mean, latent_std, latent_multiplier)
|
| 364 |
+
image = self.decoder.decode(latents)
|
| 365 |
+
image = torch.clamp(image, 0.0, 1.0)
|
| 366 |
+
if output_type == "pt":
|
| 367 |
+
return image
|
| 368 |
+
return self.image_processor.postprocess(image, output_type=output_type, do_denormalize=[False] * image.shape[0])
|
| 369 |
+
|
| 370 |
+
@torch.inference_mode()
|
| 371 |
+
def __call__(
|
| 372 |
+
self,
|
| 373 |
+
class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
|
| 374 |
+
height: Optional[int] = None,
|
| 375 |
+
width: Optional[int] = None,
|
| 376 |
+
num_inference_steps: int = 250,
|
| 377 |
+
guidance_scale: float = 3.3,
|
| 378 |
+
guidance_interval: Tuple[float, float] = (0.0, 1.0),
|
| 379 |
+
cfg_interval_start: float = 0.3,
|
| 380 |
+
timestep_shift: float = 0.4,
|
| 381 |
+
mode: str = "ode",
|
| 382 |
+
heun: bool = False,
|
| 383 |
+
latent_mean: Optional[torch.Tensor] = None,
|
| 384 |
+
latent_std: Optional[torch.Tensor] = None,
|
| 385 |
+
latent_multiplier: Optional[float] = None,
|
| 386 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 387 |
+
output_type: str = "pil",
|
| 388 |
+
return_dict: bool = True,
|
| 389 |
+
) -> Union[ImagePipelineOutput, Tuple]:
|
| 390 |
+
r"""
|
| 391 |
+
Generate class-conditional images with PAE + LightningDiT.
|
| 392 |
+
|
| 393 |
+
Args:
|
| 394 |
+
class_labels:
|
| 395 |
+
ImageNet class indices or human-readable English label strings.
|
| 396 |
+
height:
|
| 397 |
+
Output image height in pixels. Defaults to the pretrained native resolution.
|
| 398 |
+
width:
|
| 399 |
+
Output image width in pixels. Defaults to the pretrained native resolution.
|
| 400 |
+
num_inference_steps:
|
| 401 |
+
Number of flow-matching integration steps.
|
| 402 |
+
guidance_scale:
|
| 403 |
+
Classifier-free guidance scale. Active when `guidance_scale > 1.0`.
|
| 404 |
+
guidance_interval:
|
| 405 |
+
Timestep interval `(low, high)` where CFG is applied.
|
| 406 |
+
cfg_interval_start:
|
| 407 |
+
Disable CFG below this normalized timestep value. Default `0.3` matches DiT training configs.
|
| 408 |
+
timestep_shift:
|
| 409 |
+
Timestep warping used by LightningDiT ODE sampling. Default `0.4` matches DiT training configs.
|
| 410 |
+
mode:
|
| 411 |
+
Sampling mode passed to the PAE flow scheduler: `"ode"` or `"sde"`.
|
| 412 |
+
heun:
|
| 413 |
+
Use Heun integration for ODE sampling when True.
|
| 414 |
+
latent_mean:
|
| 415 |
+
Optional latent mean tensor for denormalization before PAE decode. Defaults to
|
| 416 |
+
`latent_mean` in `decoder/config.json` when omitted.
|
| 417 |
+
latent_std:
|
| 418 |
+
Optional latent std tensor for denormalization before PAE decode. Defaults to
|
| 419 |
+
`latent_std` in `decoder/config.json` when omitted.
|
| 420 |
+
latent_multiplier:
|
| 421 |
+
Divisor applied with `latent_std` during denormalization. Defaults to
|
| 422 |
+
`latent_multiplier` in `decoder/config.json` or `1.0`.
|
| 423 |
+
generator:
|
| 424 |
+
RNG for reproducibility.
|
| 425 |
+
output_type:
|
| 426 |
+
`"pil"`, `"np"`, `"pt"`, or `"latent"`.
|
| 427 |
+
return_dict:
|
| 428 |
+
Return [`ImagePipelineOutput`] if True.
|
| 429 |
+
"""
|
| 430 |
+
default_size = self._default_image_size()
|
| 431 |
+
height = int(height or default_size)
|
| 432 |
+
width = int(width or default_size)
|
| 433 |
+
self.check_inputs(height, width, num_inference_steps, output_type, mode)
|
| 434 |
+
|
| 435 |
+
device = self._execution_device
|
| 436 |
+
model_dtype = next(self.transformers.parameters()).dtype
|
| 437 |
+
class_labels_tensor = self._normalize_class_labels(class_labels)
|
| 438 |
+
batch_size = class_labels_tensor.numel()
|
| 439 |
+
null_label = int(self.transformers.config.num_classes)
|
| 440 |
+
null_labels = torch.full((batch_size,), null_label, device=device, dtype=torch.long)
|
| 441 |
+
cfg_channels = int(self.transformers.config.in_channels)
|
| 442 |
+
|
| 443 |
+
latents = self.prepare_latents(
|
| 444 |
+
batch_size=batch_size,
|
| 445 |
+
height=height,
|
| 446 |
+
width=width,
|
| 447 |
+
dtype=model_dtype,
|
| 448 |
+
device=device,
|
| 449 |
+
generator=generator,
|
| 450 |
+
)
|
| 451 |
+
timesteps = self.scheduler.set_timesteps(
|
| 452 |
+
num_inference_steps, device=device, mode=mode, timestep_shift=timestep_shift
|
| 453 |
+
)
|
| 454 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(self.scheduler, generator=generator)
|
| 455 |
+
|
| 456 |
+
for index, timestep in enumerate(timesteps[:-1]):
|
| 457 |
+
next_timestep = timesteps[index + 1]
|
| 458 |
+
t_value = float(timestep)
|
| 459 |
+
guidance_active = guidance_scale > 1.0 and guidance_interval[0] <= t_value <= guidance_interval[1]
|
| 460 |
+
if cfg_interval_start is not None and t_value < cfg_interval_start:
|
| 461 |
+
guidance_active = False
|
| 462 |
+
|
| 463 |
+
if guidance_active:
|
| 464 |
+
model_input = torch.cat([latents, latents], dim=0)
|
| 465 |
+
labels = torch.cat([class_labels_tensor, null_labels], dim=0)
|
| 466 |
+
else:
|
| 467 |
+
model_input = latents
|
| 468 |
+
labels = class_labels_tensor
|
| 469 |
+
|
| 470 |
+
timestep_batch = torch.full((labels.shape[0],), t_value, device=device, dtype=model_dtype)
|
| 471 |
+
model_output = self.transformers(
|
| 472 |
+
model_input.to(dtype=model_dtype),
|
| 473 |
+
timestep=timestep_batch,
|
| 474 |
+
class_labels=labels,
|
| 475 |
+
return_dict=True,
|
| 476 |
+
).sample
|
| 477 |
+
model_output = self._apply_cfg(model_output, guidance_scale, guidance_active, cfg_channels)
|
| 478 |
+
|
| 479 |
+
if heun and mode == "ode" and index < len(timesteps) - 2:
|
| 480 |
+
provisional = self.scheduler.step(
|
| 481 |
+
model_output,
|
| 482 |
+
timestep[None],
|
| 483 |
+
latents,
|
| 484 |
+
next_timestep[None],
|
| 485 |
+
**extra_step_kwargs,
|
| 486 |
+
).prev_sample
|
| 487 |
+
if guidance_active:
|
| 488 |
+
prime_input = torch.cat([provisional, provisional], dim=0)
|
| 489 |
+
prime_labels = torch.cat([class_labels_tensor, null_labels], dim=0)
|
| 490 |
+
else:
|
| 491 |
+
prime_input = provisional
|
| 492 |
+
prime_labels = class_labels_tensor
|
| 493 |
+
next_timestep_batch = torch.full(
|
| 494 |
+
(prime_labels.shape[0],), float(next_timestep), device=device, dtype=model_dtype
|
| 495 |
+
)
|
| 496 |
+
next_output = self.transformers(
|
| 497 |
+
prime_input.to(dtype=model_dtype),
|
| 498 |
+
timestep=next_timestep_batch,
|
| 499 |
+
class_labels=prime_labels,
|
| 500 |
+
return_dict=True,
|
| 501 |
+
).sample
|
| 502 |
+
next_output = self._apply_cfg(next_output, guidance_scale, guidance_active, cfg_channels)
|
| 503 |
+
latents = self.scheduler.step_heun(
|
| 504 |
+
model_output, next_output, timestep[None], latents, next_timestep[None]
|
| 505 |
+
).prev_sample
|
| 506 |
+
else:
|
| 507 |
+
latents = self.scheduler.step(
|
| 508 |
+
model_output,
|
| 509 |
+
timestep[None],
|
| 510 |
+
latents,
|
| 511 |
+
next_timestep[None],
|
| 512 |
+
**extra_step_kwargs,
|
| 513 |
+
).prev_sample
|
| 514 |
+
|
| 515 |
+
image = self.decode_latents(
|
| 516 |
+
latents.to(dtype=model_dtype),
|
| 517 |
+
output_type=output_type,
|
| 518 |
+
latent_mean=latent_mean,
|
| 519 |
+
latent_std=latent_std,
|
| 520 |
+
latent_multiplier=latent_multiplier,
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
self.maybe_free_model_hooks()
|
| 524 |
+
if not return_dict:
|
| 525 |
+
return (image,)
|
| 526 |
+
return ImagePipelineOutput(images=image)
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
# Backward-compatible alias used by earlier PAE-diffusers releases.
|
| 530 |
+
PAEPipelineOutput = ImagePipelineOutput
|
pae-dinov3-large-d32/scheduler/scheduler_config.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "PAEFlowMatchScheduler",
|
| 3 |
+
"_diffusers_version": "0.31.0",
|
| 4 |
+
"mode": "ode",
|
| 5 |
+
"path_type": "linear",
|
| 6 |
+
"num_train_timesteps": 1000
|
| 7 |
+
}
|
pae-dinov3-large-d32/scheduler/scheduling_flow_match_pae.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from typing import Optional, Tuple
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 14 |
+
from diffusers.schedulers.scheduling_utils import SchedulerMixin
|
| 15 |
+
from diffusers.utils import BaseOutput
|
| 16 |
+
except Exception: # pragma: no cover - importable without an installed diffusers checkout.
|
| 17 |
+
class BaseOutput(dict):
|
| 18 |
+
def __post_init__(self):
|
| 19 |
+
self.update(self.__dict__)
|
| 20 |
+
|
| 21 |
+
class ConfigMixin:
|
| 22 |
+
config_name = "scheduler_config.json"
|
| 23 |
+
|
| 24 |
+
class SchedulerMixin:
|
| 25 |
+
pass
|
| 26 |
+
|
| 27 |
+
def register_to_config(init):
|
| 28 |
+
return init
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass
|
| 32 |
+
class PAEFlowMatchSchedulerOutput(BaseOutput):
|
| 33 |
+
prev_sample: torch.FloatTensor
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class PAEFlowMatchScheduler(SchedulerMixin, ConfigMixin):
|
| 37 |
+
"""
|
| 38 |
+
Flow-matching ODE/SDE scheduler used by PAE + LightningDiT pipelines.
|
| 39 |
+
|
| 40 |
+
The model predicts velocity with a linear path by default. ODE timesteps run from 0 to 1
|
| 41 |
+
(noise to data), matching LightningDiT transport sampling.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
config_name = "scheduler_config.json"
|
| 45 |
+
order = 1
|
| 46 |
+
|
| 47 |
+
@register_to_config
|
| 48 |
+
def __init__(
|
| 49 |
+
self,
|
| 50 |
+
mode: str = "ode",
|
| 51 |
+
path_type: str = "linear",
|
| 52 |
+
num_train_timesteps: int = 1000,
|
| 53 |
+
):
|
| 54 |
+
if mode not in {"ode", "sde"}:
|
| 55 |
+
raise ValueError("mode must be either 'ode' or 'sde'.")
|
| 56 |
+
if path_type not in {"linear", "cosine"}:
|
| 57 |
+
raise ValueError("path_type must be either 'linear' or 'cosine'.")
|
| 58 |
+
self.mode = mode
|
| 59 |
+
self.path_type = path_type
|
| 60 |
+
self.num_train_timesteps = num_train_timesteps
|
| 61 |
+
# Native NiT integrates in float64 for better numerical stability.
|
| 62 |
+
self.timesteps = torch.from_numpy(np.linspace(0.0, 1.0, num_train_timesteps + 1)).to(dtype=torch.float64)
|
| 63 |
+
|
| 64 |
+
@staticmethod
|
| 65 |
+
def _apply_timestep_shift(timesteps: torch.Tensor, timestep_shift: float) -> torch.Tensor:
|
| 66 |
+
if timestep_shift <= 0:
|
| 67 |
+
return timesteps
|
| 68 |
+
return timestep_shift * timesteps / (1 + (timestep_shift - 1) * timesteps)
|
| 69 |
+
|
| 70 |
+
def set_timesteps(
|
| 71 |
+
self,
|
| 72 |
+
num_inference_steps: int,
|
| 73 |
+
device: Optional[torch.device] = None,
|
| 74 |
+
mode: Optional[str] = None,
|
| 75 |
+
timestep_shift: float = 0.0,
|
| 76 |
+
):
|
| 77 |
+
mode = mode or self.mode
|
| 78 |
+
dtype = self.timesteps.dtype
|
| 79 |
+
if mode == "sde":
|
| 80 |
+
timesteps = torch.linspace(1.0, 0.04, num_inference_steps, dtype=dtype)
|
| 81 |
+
timesteps = torch.cat([timesteps, torch.zeros(1, dtype=dtype)])
|
| 82 |
+
elif mode == "ode":
|
| 83 |
+
timesteps = torch.linspace(0.0, 1.0, num_inference_steps + 1, dtype=dtype)
|
| 84 |
+
timesteps = self._apply_timestep_shift(timesteps, timestep_shift)
|
| 85 |
+
else:
|
| 86 |
+
raise ValueError("mode must be either 'ode' or 'sde'.")
|
| 87 |
+
self.mode = mode
|
| 88 |
+
self.timesteps = timesteps.to(device=device)
|
| 89 |
+
return self.timesteps
|
| 90 |
+
|
| 91 |
+
@staticmethod
|
| 92 |
+
def _expand_t_like_sample(timestep: torch.Tensor, sample: torch.Tensor, image_sizes: torch.LongTensor):
|
| 93 |
+
dims = [1] * (sample.ndim - 1)
|
| 94 |
+
seqlens = image_sizes[:, 0] * image_sizes[:, 1]
|
| 95 |
+
if timestep.numel() == 1:
|
| 96 |
+
timestep = timestep.repeat(image_sizes.shape[0])
|
| 97 |
+
return torch.cat(
|
| 98 |
+
[timestep[i].reshape(1, *dims).repeat(int(seqlens[i]), *dims) for i in range(image_sizes.shape[0])]
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
def _get_score_from_velocity(
|
| 102 |
+
self,
|
| 103 |
+
model_output: torch.Tensor,
|
| 104 |
+
sample: torch.Tensor,
|
| 105 |
+
timestep: torch.Tensor,
|
| 106 |
+
image_sizes: torch.LongTensor,
|
| 107 |
+
):
|
| 108 |
+
timestep = self._expand_t_like_sample(timestep, sample, image_sizes)
|
| 109 |
+
if self.path_type == "linear":
|
| 110 |
+
alpha_t, d_alpha_t = 1 - timestep, torch.ones_like(timestep) * -1
|
| 111 |
+
sigma_t, d_sigma_t = timestep, torch.ones_like(timestep)
|
| 112 |
+
elif self.path_type == "cosine":
|
| 113 |
+
alpha_t = torch.cos(timestep * np.pi / 2)
|
| 114 |
+
sigma_t = torch.sin(timestep * np.pi / 2)
|
| 115 |
+
d_alpha_t = -np.pi / 2 * torch.sin(timestep * np.pi / 2)
|
| 116 |
+
d_sigma_t = np.pi / 2 * torch.cos(timestep * np.pi / 2)
|
| 117 |
+
else:
|
| 118 |
+
raise ValueError(f"Unsupported path_type: {self.path_type}")
|
| 119 |
+
reverse_alpha_ratio = alpha_t / d_alpha_t
|
| 120 |
+
variance = sigma_t**2 - reverse_alpha_ratio * d_sigma_t * sigma_t
|
| 121 |
+
return (reverse_alpha_ratio * model_output - sample) / variance
|
| 122 |
+
|
| 123 |
+
@staticmethod
|
| 124 |
+
def _compute_diffusion(timestep: torch.Tensor):
|
| 125 |
+
return 2 * timestep
|
| 126 |
+
|
| 127 |
+
@staticmethod
|
| 128 |
+
def _promote_dtypes(*tensors: torch.Tensor) -> torch.dtype:
|
| 129 |
+
dtype = None
|
| 130 |
+
for tensor in tensors:
|
| 131 |
+
if tensor.is_floating_point() or tensor.is_complex():
|
| 132 |
+
dtype = tensor.dtype if dtype is None else torch.promote_types(dtype, tensor.dtype)
|
| 133 |
+
return dtype if dtype is not None else torch.get_default_dtype()
|
| 134 |
+
|
| 135 |
+
def step(
|
| 136 |
+
self,
|
| 137 |
+
model_output: torch.Tensor,
|
| 138 |
+
timestep: torch.Tensor,
|
| 139 |
+
sample: torch.Tensor,
|
| 140 |
+
next_timestep: torch.Tensor,
|
| 141 |
+
image_sizes: Optional[torch.LongTensor] = None,
|
| 142 |
+
generator: Optional[torch.Generator] = None,
|
| 143 |
+
return_dict: bool = True,
|
| 144 |
+
) -> PAEFlowMatchSchedulerOutput:
|
| 145 |
+
sample_dtype = sample.dtype
|
| 146 |
+
compute_dtype = torch.float64
|
| 147 |
+
sample = sample.to(dtype=compute_dtype)
|
| 148 |
+
model_output = model_output.to(dtype=compute_dtype)
|
| 149 |
+
timestep = timestep.to(device=sample.device, dtype=compute_dtype).flatten()
|
| 150 |
+
next_timestep = next_timestep.to(device=sample.device, dtype=compute_dtype).flatten()
|
| 151 |
+
|
| 152 |
+
if self.mode == "ode":
|
| 153 |
+
prev_sample = sample + (next_timestep[0] - timestep[0]) * model_output
|
| 154 |
+
else:
|
| 155 |
+
if image_sizes is None:
|
| 156 |
+
batch = sample.shape[0]
|
| 157 |
+
side = int(sample.shape[-1])
|
| 158 |
+
image_sizes = torch.tensor([[side, side]] * batch, device=sample.device, dtype=torch.long)
|
| 159 |
+
image_sizes = image_sizes.to(device=sample.device, dtype=torch.long)
|
| 160 |
+
diffusion = self._compute_diffusion(timestep[0])
|
| 161 |
+
score = self._get_score_from_velocity(model_output, sample, timestep, image_sizes)
|
| 162 |
+
drift = model_output - 0.5 * diffusion * score
|
| 163 |
+
dt = next_timestep[0] - timestep[0]
|
| 164 |
+
if torch.allclose(next_timestep[0], torch.zeros_like(next_timestep[0])):
|
| 165 |
+
prev_sample = sample + drift * dt
|
| 166 |
+
else:
|
| 167 |
+
if generator is not None:
|
| 168 |
+
noise = torch.randn(sample.shape, generator=generator, device=sample.device, dtype=sample.dtype)
|
| 169 |
+
else:
|
| 170 |
+
noise = torch.randn_like(sample)
|
| 171 |
+
prev_sample = sample + drift * dt + torch.sqrt(diffusion) * noise * torch.sqrt(torch.abs(dt))
|
| 172 |
+
|
| 173 |
+
prev_sample = prev_sample.to(sample_dtype)
|
| 174 |
+
if not return_dict:
|
| 175 |
+
return (prev_sample,)
|
| 176 |
+
return PAEFlowMatchSchedulerOutput(prev_sample=prev_sample)
|
| 177 |
+
|
| 178 |
+
def step_heun(
|
| 179 |
+
self,
|
| 180 |
+
model_output: torch.Tensor,
|
| 181 |
+
next_model_output: torch.Tensor,
|
| 182 |
+
timestep: torch.Tensor,
|
| 183 |
+
sample: torch.Tensor,
|
| 184 |
+
next_timestep: torch.Tensor,
|
| 185 |
+
return_dict: bool = True,
|
| 186 |
+
) -> PAEFlowMatchSchedulerOutput:
|
| 187 |
+
if self.mode != "ode":
|
| 188 |
+
raise ValueError("Heun correction is only defined for ODE sampling.")
|
| 189 |
+
sample_dtype = sample.dtype
|
| 190 |
+
compute_dtype = torch.float64
|
| 191 |
+
sample = sample.to(dtype=compute_dtype)
|
| 192 |
+
model_output = model_output.to(dtype=compute_dtype)
|
| 193 |
+
next_model_output = next_model_output.to(dtype=compute_dtype)
|
| 194 |
+
timestep = timestep.to(device=sample.device, dtype=compute_dtype).flatten()
|
| 195 |
+
next_timestep = next_timestep.to(device=sample.device, dtype=compute_dtype).flatten()
|
| 196 |
+
prev_sample = sample + (next_timestep[0] - timestep[0]) * (0.5 * model_output + 0.5 * next_model_output)
|
| 197 |
+
prev_sample = prev_sample.to(sample_dtype)
|
| 198 |
+
if not return_dict:
|
| 199 |
+
return (prev_sample,)
|
| 200 |
+
return PAEFlowMatchSchedulerOutput(prev_sample=prev_sample)
|
pae-dinov3-large-d32/transformers/config.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "LightningDiT2DModel",
|
| 3 |
+
"depth": 28,
|
| 4 |
+
"hidden_size": 1152,
|
| 5 |
+
"in_channels": 32,
|
| 6 |
+
"input_size": 16,
|
| 7 |
+
"num_classes": 1000,
|
| 8 |
+
"num_heads": 16,
|
| 9 |
+
"patch_size": 1,
|
| 10 |
+
"use_qknorm": true,
|
| 11 |
+
"use_rmsnorm": true,
|
| 12 |
+
"use_rope": true,
|
| 13 |
+
"use_swiglu": true,
|
| 14 |
+
"wo_shift": false
|
| 15 |
+
}
|
pae-dinov3-large-d32/transformers/diffusion_pytorch_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:81b9436b33326a31de395fd17b4bad4f93b75fd8498beeac7574ca91760fc681
|
| 3 |
+
size 2701230752
|
pae-dinov3-large-d32/transformers/transformer_lightning_dit.py
ADDED
|
@@ -0,0 +1,794 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from torch import nn
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class RMSNorm(torch.nn.Module):
|
| 9 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
| 10 |
+
super().__init__()
|
| 11 |
+
self.eps = eps
|
| 12 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 13 |
+
|
| 14 |
+
def _norm(self, x: torch.Tensor) -> torch.Tensor:
|
| 15 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 16 |
+
|
| 17 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 18 |
+
output = self._norm(x.float()).type_as(x)
|
| 19 |
+
return output * self.weight
|
| 20 |
+
|
| 21 |
+
from math import pi
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
from torch import nn
|
| 25 |
+
|
| 26 |
+
from einops import rearrange, repeat
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def broadcat(tensors, dim = -1):
|
| 31 |
+
num_tensors = len(tensors)
|
| 32 |
+
shape_lens = set(list(map(lambda t: len(t.shape), tensors)))
|
| 33 |
+
assert len(shape_lens) == 1, 'tensors must all have the same number of dimensions'
|
| 34 |
+
shape_len = list(shape_lens)[0]
|
| 35 |
+
dim = (dim + shape_len) if dim < 0 else dim
|
| 36 |
+
dims = list(zip(*map(lambda t: list(t.shape), tensors)))
|
| 37 |
+
expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim]
|
| 38 |
+
assert all([*map(lambda t: len(set(t[1])) <= 2, expandable_dims)]), 'invalid dimensions for broadcastable concatentation'
|
| 39 |
+
max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims))
|
| 40 |
+
expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims))
|
| 41 |
+
expanded_dims.insert(dim, (dim, dims[dim]))
|
| 42 |
+
expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims)))
|
| 43 |
+
tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes)))
|
| 44 |
+
return torch.cat(tensors, dim = dim)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def rotate_half(x):
|
| 49 |
+
x = rearrange(x, '... (d r) -> ... d r', r = 2)
|
| 50 |
+
x1, x2 = x.unbind(dim = -1)
|
| 51 |
+
x = torch.stack((-x2, x1), dim = -1)
|
| 52 |
+
return rearrange(x, '... d r -> ... (d r)')
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class VisionRotaryEmbedding(nn.Module):
|
| 57 |
+
def __init__(
|
| 58 |
+
self,
|
| 59 |
+
dim,
|
| 60 |
+
pt_seq_len,
|
| 61 |
+
ft_seq_len=None,
|
| 62 |
+
custom_freqs = None,
|
| 63 |
+
freqs_for = 'lang',
|
| 64 |
+
theta = 10000,
|
| 65 |
+
max_freq = 10,
|
| 66 |
+
num_freqs = 1,
|
| 67 |
+
):
|
| 68 |
+
super().__init__()
|
| 69 |
+
if custom_freqs:
|
| 70 |
+
freqs = custom_freqs
|
| 71 |
+
elif freqs_for == 'lang':
|
| 72 |
+
freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim))
|
| 73 |
+
elif freqs_for == 'pixel':
|
| 74 |
+
freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi
|
| 75 |
+
elif freqs_for == 'constant':
|
| 76 |
+
freqs = torch.ones(num_freqs).float()
|
| 77 |
+
else:
|
| 78 |
+
raise ValueError(f'unknown modality {freqs_for}')
|
| 79 |
+
|
| 80 |
+
if ft_seq_len is None: ft_seq_len = pt_seq_len
|
| 81 |
+
t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len
|
| 82 |
+
|
| 83 |
+
freqs_h = torch.einsum('..., f -> ... f', t, freqs)
|
| 84 |
+
freqs_h = repeat(freqs_h, '... n -> ... (n r)', r = 2)
|
| 85 |
+
|
| 86 |
+
freqs_w = torch.einsum('..., f -> ... f', t, freqs)
|
| 87 |
+
freqs_w = repeat(freqs_w, '... n -> ... (n r)', r = 2)
|
| 88 |
+
|
| 89 |
+
freqs = broadcat((freqs_h[:, None, :], freqs_w[None, :, :]), dim = -1)
|
| 90 |
+
|
| 91 |
+
self.register_buffer("freqs_cos", freqs.cos())
|
| 92 |
+
self.register_buffer("freqs_sin", freqs.sin())
|
| 93 |
+
|
| 94 |
+
# print('======== shape of rope freq', self.freqs_cos.shape, '========')
|
| 95 |
+
|
| 96 |
+
def forward(self, t, start_index = 0):
|
| 97 |
+
rot_dim = self.freqs_cos.shape[-1]
|
| 98 |
+
end_index = start_index + rot_dim
|
| 99 |
+
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}'
|
| 100 |
+
t_left, t, t_right = t[..., :start_index], t[..., start_index:end_index], t[..., end_index:]
|
| 101 |
+
t = (t * self.freqs_cos) + (rotate_half(t) * self.freqs_sin)
|
| 102 |
+
return torch.cat((t_left, t, t_right), dim = -1)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class VisionRotaryEmbeddingFast(nn.Module):
|
| 107 |
+
def __init__(
|
| 108 |
+
self,
|
| 109 |
+
dim,
|
| 110 |
+
pt_seq_len=16,
|
| 111 |
+
ft_seq_len=None,
|
| 112 |
+
custom_freqs = None,
|
| 113 |
+
freqs_for = 'lang',
|
| 114 |
+
theta = 10000,
|
| 115 |
+
max_freq = 10,
|
| 116 |
+
num_freqs = 1,
|
| 117 |
+
):
|
| 118 |
+
super().__init__()
|
| 119 |
+
if custom_freqs:
|
| 120 |
+
freqs = custom_freqs
|
| 121 |
+
elif freqs_for == 'lang':
|
| 122 |
+
freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim))
|
| 123 |
+
elif freqs_for == 'pixel':
|
| 124 |
+
freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi
|
| 125 |
+
elif freqs_for == 'constant':
|
| 126 |
+
freqs = torch.ones(num_freqs).float()
|
| 127 |
+
else:
|
| 128 |
+
raise ValueError(f'unknown modality {freqs_for}')
|
| 129 |
+
|
| 130 |
+
if ft_seq_len is None: ft_seq_len = pt_seq_len
|
| 131 |
+
t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len
|
| 132 |
+
|
| 133 |
+
freqs = torch.einsum('..., f -> ... f', t, freqs)
|
| 134 |
+
freqs = repeat(freqs, '... n -> ... (n r)', r = 2)
|
| 135 |
+
freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim = -1)
|
| 136 |
+
|
| 137 |
+
freqs_cos = freqs.cos().view(-1, freqs.shape[-1])
|
| 138 |
+
freqs_sin = freqs.sin().view(-1, freqs.shape[-1])
|
| 139 |
+
|
| 140 |
+
self.register_buffer("freqs_cos", freqs_cos)
|
| 141 |
+
self.register_buffer("freqs_sin", freqs_sin)
|
| 142 |
+
|
| 143 |
+
# print('======== shape of rope freq', self.freqs_cos.shape, '========')
|
| 144 |
+
|
| 145 |
+
def forward(self, t): return t * self.freqs_cos + rotate_half(t) * self.freqs_sin
|
| 146 |
+
|
| 147 |
+
import os
|
| 148 |
+
import torch
|
| 149 |
+
from typing import Callable, Optional
|
| 150 |
+
import warnings
|
| 151 |
+
|
| 152 |
+
from torch import Tensor, nn
|
| 153 |
+
import torch.nn.functional as F
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class SwiGLUFFN(nn.Module):
|
| 157 |
+
def __init__(
|
| 158 |
+
self,
|
| 159 |
+
in_features: int,
|
| 160 |
+
hidden_features: Optional[int] = None,
|
| 161 |
+
out_features: Optional[int] = None,
|
| 162 |
+
act_layer: Callable[..., nn.Module] = None,
|
| 163 |
+
drop: float = 0.0,
|
| 164 |
+
bias: bool = True,
|
| 165 |
+
) -> None:
|
| 166 |
+
super().__init__()
|
| 167 |
+
out_features = out_features or in_features
|
| 168 |
+
hidden_features = hidden_features or in_features
|
| 169 |
+
self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias)
|
| 170 |
+
self.w3 = nn.Linear(hidden_features, out_features, bias=bias)
|
| 171 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 172 |
+
x12 = self.w12(x)
|
| 173 |
+
x1, x2 = x12.chunk(2, dim=-1)
|
| 174 |
+
hidden = F.silu(x1) * x2
|
| 175 |
+
return self.w3(hidden)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None
|
| 179 |
+
try:
|
| 180 |
+
if XFORMERS_ENABLED:
|
| 181 |
+
from xformers.ops import SwiGLU
|
| 182 |
+
|
| 183 |
+
XFORMERS_AVAILABLE = True
|
| 184 |
+
# warnings.warn("xFormers is available (SwiGLU)")
|
| 185 |
+
else:
|
| 186 |
+
# warnings.warn("xFormers is disabled (SwiGLU)")
|
| 187 |
+
raise ImportError
|
| 188 |
+
except ImportError:
|
| 189 |
+
SwiGLU = SwiGLUFFN
|
| 190 |
+
XFORMERS_AVAILABLE = False
|
| 191 |
+
|
| 192 |
+
# warnings.warn("xFormers is not available (SwiGLU)")
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class SwiGLUFFNFused(SwiGLU):
|
| 196 |
+
def __init__(
|
| 197 |
+
self,
|
| 198 |
+
in_features: int,
|
| 199 |
+
hidden_features: Optional[int] = None,
|
| 200 |
+
out_features: Optional[int] = None,
|
| 201 |
+
act_layer: Callable[..., nn.Module] = None,
|
| 202 |
+
drop: float = 0.0,
|
| 203 |
+
bias: bool = True,
|
| 204 |
+
) -> None:
|
| 205 |
+
out_features = out_features or in_features
|
| 206 |
+
hidden_features = hidden_features or in_features
|
| 207 |
+
hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
|
| 208 |
+
super().__init__(
|
| 209 |
+
in_features=in_features,
|
| 210 |
+
hidden_features=hidden_features,
|
| 211 |
+
out_features=out_features,
|
| 212 |
+
bias=bias,
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
from dataclasses import dataclass
|
| 216 |
+
from typing import Optional, Tuple, Union
|
| 217 |
+
|
| 218 |
+
import torch
|
| 219 |
+
|
| 220 |
+
try:
|
| 221 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 222 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 223 |
+
from diffusers.utils import BaseOutput
|
| 224 |
+
except Exception: # pragma: no cover
|
| 225 |
+
class BaseOutput(dict):
|
| 226 |
+
def __post_init__(self):
|
| 227 |
+
self.update(self.__dict__)
|
| 228 |
+
|
| 229 |
+
class ConfigMixin:
|
| 230 |
+
config_name = "config.json"
|
| 231 |
+
|
| 232 |
+
class ModelMixin(torch.nn.Module):
|
| 233 |
+
pass
|
| 234 |
+
|
| 235 |
+
def register_to_config(init):
|
| 236 |
+
return init
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
@dataclass
|
| 240 |
+
class LightningDiT2DModelOutput(BaseOutput):
|
| 241 |
+
sample: torch.FloatTensor
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
import os
|
| 245 |
+
import math
|
| 246 |
+
import numpy as np
|
| 247 |
+
|
| 248 |
+
import torch
|
| 249 |
+
import torch.nn as nn
|
| 250 |
+
import torch.nn.functional as F
|
| 251 |
+
from torch.utils.checkpoint import checkpoint
|
| 252 |
+
|
| 253 |
+
from timm.models.vision_transformer import PatchEmbed, Mlp
|
| 254 |
+
def modulate(x, shift, scale):
|
| 255 |
+
if shift is None:
|
| 256 |
+
return x * (1 + scale.unsqueeze(1))
|
| 257 |
+
return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
|
| 258 |
+
|
| 259 |
+
class Attention(nn.Module):
|
| 260 |
+
"""
|
| 261 |
+
Attention module of LightningDiT.
|
| 262 |
+
"""
|
| 263 |
+
def __init__(
|
| 264 |
+
self,
|
| 265 |
+
dim: int,
|
| 266 |
+
num_heads: int = 8,
|
| 267 |
+
qkv_bias: bool = False,
|
| 268 |
+
qk_norm: bool = False,
|
| 269 |
+
attn_drop: float = 0.,
|
| 270 |
+
proj_drop: float = 0.,
|
| 271 |
+
norm_layer: nn.Module = nn.LayerNorm,
|
| 272 |
+
fused_attn: bool = True,
|
| 273 |
+
use_rmsnorm: bool = False,
|
| 274 |
+
) -> None:
|
| 275 |
+
super().__init__()
|
| 276 |
+
assert dim % num_heads == 0, 'dim should be divisible by num_heads'
|
| 277 |
+
|
| 278 |
+
self.num_heads = num_heads
|
| 279 |
+
self.head_dim = dim // num_heads
|
| 280 |
+
self.scale = self.head_dim ** -0.5
|
| 281 |
+
self.fused_attn = fused_attn
|
| 282 |
+
|
| 283 |
+
if use_rmsnorm:
|
| 284 |
+
norm_layer = RMSNorm
|
| 285 |
+
|
| 286 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
| 287 |
+
self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
|
| 288 |
+
self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
|
| 289 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 290 |
+
self.proj = nn.Linear(dim, dim)
|
| 291 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 292 |
+
|
| 293 |
+
def forward(self, x: torch.Tensor, rope=None) -> torch.Tensor:
|
| 294 |
+
B, N, C = x.shape
|
| 295 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
|
| 296 |
+
q, k, v = qkv.unbind(0)
|
| 297 |
+
q, k = self.q_norm(q), self.k_norm(k)
|
| 298 |
+
|
| 299 |
+
if rope is not None:
|
| 300 |
+
q = rope(q)
|
| 301 |
+
k = rope(k)
|
| 302 |
+
|
| 303 |
+
if self.fused_attn:
|
| 304 |
+
x = F.scaled_dot_product_attention(
|
| 305 |
+
q, k, v,
|
| 306 |
+
dropout_p=self.attn_drop.p if self.training else 0.,
|
| 307 |
+
)
|
| 308 |
+
else:
|
| 309 |
+
q = q * self.scale
|
| 310 |
+
attn = q @ k.transpose(-2, -1)
|
| 311 |
+
attn = attn.softmax(dim=-1)
|
| 312 |
+
attn = self.attn_drop(attn)
|
| 313 |
+
x = attn @ v
|
| 314 |
+
|
| 315 |
+
x = x.transpose(1, 2).reshape(B, N, C)
|
| 316 |
+
x = self.proj(x)
|
| 317 |
+
x = self.proj_drop(x)
|
| 318 |
+
return x
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
class TimestepEmbedder(nn.Module):
|
| 322 |
+
"""
|
| 323 |
+
Embeds scalar timesteps into vector representations.
|
| 324 |
+
Same as DiT.
|
| 325 |
+
"""
|
| 326 |
+
def __init__(self, hidden_size: int, frequency_embedding_size: int = 256) -> None:
|
| 327 |
+
super().__init__()
|
| 328 |
+
self.frequency_embedding_size = frequency_embedding_size
|
| 329 |
+
self.mlp = nn.Sequential(
|
| 330 |
+
nn.Linear(frequency_embedding_size, hidden_size, bias=True),
|
| 331 |
+
nn.SiLU(),
|
| 332 |
+
nn.Linear(hidden_size, hidden_size, bias=True),
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
@staticmethod
|
| 336 |
+
def timestep_embedding(t: torch.Tensor, dim: int, max_period: int = 10000) -> torch.Tensor:
|
| 337 |
+
"""
|
| 338 |
+
Create sinusoidal timestep embeddings.
|
| 339 |
+
Args:
|
| 340 |
+
t: A 1-D Tensor of N indices, one per batch element. These may be fractional.
|
| 341 |
+
dim: The dimension of the output.
|
| 342 |
+
max_period: Controls the minimum frequency of the embeddings.
|
| 343 |
+
Returns:
|
| 344 |
+
An (N, D) Tensor of positional embeddings.
|
| 345 |
+
"""
|
| 346 |
+
# https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
|
| 347 |
+
half = dim // 2
|
| 348 |
+
freqs = torch.exp(
|
| 349 |
+
-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
|
| 350 |
+
).to(device=t.device)
|
| 351 |
+
|
| 352 |
+
args = t[:, None].float() * freqs[None]
|
| 353 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 354 |
+
|
| 355 |
+
if dim % 2:
|
| 356 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
| 357 |
+
|
| 358 |
+
return embedding
|
| 359 |
+
def forward(self, t: torch.Tensor) -> torch.Tensor:
|
| 360 |
+
t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
|
| 361 |
+
t_emb = self.mlp(t_freq)
|
| 362 |
+
return t_emb
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
class LabelEmbedder(nn.Module):
|
| 366 |
+
"""
|
| 367 |
+
Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.
|
| 368 |
+
Same as DiT.
|
| 369 |
+
"""
|
| 370 |
+
def __init__(self, num_classes, hidden_size, dropout_prob):
|
| 371 |
+
super().__init__()
|
| 372 |
+
use_cfg_embedding = dropout_prob > 0
|
| 373 |
+
self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size)
|
| 374 |
+
self.num_classes = num_classes
|
| 375 |
+
self.dropout_prob = dropout_prob
|
| 376 |
+
|
| 377 |
+
def token_drop(self, labels, force_drop_ids=None):
|
| 378 |
+
"""
|
| 379 |
+
Drops labels to enable classifier-free guidance.
|
| 380 |
+
"""
|
| 381 |
+
if force_drop_ids is None:
|
| 382 |
+
drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob
|
| 383 |
+
else:
|
| 384 |
+
drop_ids = force_drop_ids == 1
|
| 385 |
+
labels = torch.where(drop_ids, self.num_classes, labels)
|
| 386 |
+
return labels
|
| 387 |
+
def forward(self, labels, train, force_drop_ids=None):
|
| 388 |
+
use_dropout = self.dropout_prob > 0
|
| 389 |
+
if (train and use_dropout) or (force_drop_ids is not None):
|
| 390 |
+
labels = self.token_drop(labels, force_drop_ids)
|
| 391 |
+
embeddings = self.embedding_table(labels)
|
| 392 |
+
return embeddings
|
| 393 |
+
|
| 394 |
+
class LightningDiTBlock(nn.Module):
|
| 395 |
+
"""
|
| 396 |
+
Lightning DiT Block. We add features including:
|
| 397 |
+
- ROPE
|
| 398 |
+
- QKNorm
|
| 399 |
+
- RMSNorm
|
| 400 |
+
- SwiGLU
|
| 401 |
+
- No shift AdaLN.
|
| 402 |
+
Not all of them are used in the final model, please refer to the paper for more details.
|
| 403 |
+
"""
|
| 404 |
+
def __init__(
|
| 405 |
+
self,
|
| 406 |
+
hidden_size,
|
| 407 |
+
num_heads,
|
| 408 |
+
mlp_ratio=4.0,
|
| 409 |
+
use_qknorm=False,
|
| 410 |
+
use_swiglu=False,
|
| 411 |
+
use_rmsnorm=False,
|
| 412 |
+
wo_shift=False,
|
| 413 |
+
**block_kwargs
|
| 414 |
+
):
|
| 415 |
+
super().__init__()
|
| 416 |
+
|
| 417 |
+
# Initialize normalization layers
|
| 418 |
+
if not use_rmsnorm:
|
| 419 |
+
self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 420 |
+
self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 421 |
+
else:
|
| 422 |
+
self.norm1 = RMSNorm(hidden_size)
|
| 423 |
+
self.norm2 = RMSNorm(hidden_size)
|
| 424 |
+
|
| 425 |
+
# Initialize attention layer
|
| 426 |
+
self.attn = Attention(
|
| 427 |
+
hidden_size,
|
| 428 |
+
num_heads=num_heads,
|
| 429 |
+
qkv_bias=True,
|
| 430 |
+
qk_norm=use_qknorm,
|
| 431 |
+
use_rmsnorm=use_rmsnorm,
|
| 432 |
+
**block_kwargs
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
# Initialize MLP layer
|
| 436 |
+
mlp_hidden_dim = int(hidden_size * mlp_ratio)
|
| 437 |
+
approx_gelu = lambda: nn.GELU(approximate="tanh")
|
| 438 |
+
if use_swiglu:
|
| 439 |
+
# here we did not use SwiGLU from xformers because it is not compatible with torch.compile for now.
|
| 440 |
+
self.mlp = SwiGLUFFN(hidden_size, int(2/3 * mlp_hidden_dim))
|
| 441 |
+
else:
|
| 442 |
+
self.mlp = Mlp(
|
| 443 |
+
in_features=hidden_size,
|
| 444 |
+
hidden_features=mlp_hidden_dim,
|
| 445 |
+
act_layer=approx_gelu,
|
| 446 |
+
drop=0
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
# Initialize AdaLN modulation
|
| 450 |
+
if wo_shift:
|
| 451 |
+
self.adaLN_modulation = nn.Sequential(
|
| 452 |
+
nn.SiLU(),
|
| 453 |
+
nn.Linear(hidden_size, 4 * hidden_size, bias=True)
|
| 454 |
+
)
|
| 455 |
+
else:
|
| 456 |
+
self.adaLN_modulation = nn.Sequential(
|
| 457 |
+
nn.SiLU(),
|
| 458 |
+
nn.Linear(hidden_size, 6 * hidden_size, bias=True)
|
| 459 |
+
)
|
| 460 |
+
self.wo_shift = wo_shift
|
| 461 |
+
def forward(self, x, c, feat_rope=None):
|
| 462 |
+
if self.wo_shift:
|
| 463 |
+
scale_msa, gate_msa, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(4, dim=1)
|
| 464 |
+
shift_msa = None
|
| 465 |
+
shift_mlp = None
|
| 466 |
+
else:
|
| 467 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=1)
|
| 468 |
+
|
| 469 |
+
x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa), rope=feat_rope)
|
| 470 |
+
x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))
|
| 471 |
+
return x
|
| 472 |
+
|
| 473 |
+
class FinalLayer(nn.Module):
|
| 474 |
+
"""
|
| 475 |
+
The final layer of LightningDiT.
|
| 476 |
+
"""
|
| 477 |
+
def __init__(self, hidden_size, patch_size, out_channels, use_rmsnorm=False):
|
| 478 |
+
super().__init__()
|
| 479 |
+
if not use_rmsnorm:
|
| 480 |
+
self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 481 |
+
else:
|
| 482 |
+
self.norm_final = RMSNorm(hidden_size)
|
| 483 |
+
self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
|
| 484 |
+
self.adaLN_modulation = nn.Sequential(
|
| 485 |
+
nn.SiLU(),
|
| 486 |
+
nn.Linear(hidden_size, 2 * hidden_size, bias=True)
|
| 487 |
+
)
|
| 488 |
+
def forward(self, x, c):
|
| 489 |
+
shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
|
| 490 |
+
x = modulate(self.norm_final(x), shift, scale)
|
| 491 |
+
x = self.linear(x)
|
| 492 |
+
return x
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
class LightningDiT2DModel(ModelMixin, ConfigMixin):
|
| 496 |
+
"""
|
| 497 |
+
Diffusion model with a Transformer backbone.
|
| 498 |
+
"""
|
| 499 |
+
@register_to_config
|
| 500 |
+
def __init__(
|
| 501 |
+
self,
|
| 502 |
+
input_size: int = 32,
|
| 503 |
+
patch_size=2,
|
| 504 |
+
in_channels=32,
|
| 505 |
+
hidden_size=1152,
|
| 506 |
+
depth=28,
|
| 507 |
+
num_heads=16,
|
| 508 |
+
mlp_ratio=4.0,
|
| 509 |
+
class_dropout_prob=0.1,
|
| 510 |
+
num_classes=1000,
|
| 511 |
+
learn_sigma=False,
|
| 512 |
+
use_qknorm=False,
|
| 513 |
+
use_swiglu=False,
|
| 514 |
+
use_rope=False,
|
| 515 |
+
use_rmsnorm=False,
|
| 516 |
+
wo_shift=False,
|
| 517 |
+
use_checkpoint=False,
|
| 518 |
+
use_abs_pos=True,
|
| 519 |
+
):
|
| 520 |
+
super().__init__()
|
| 521 |
+
self.use_abs_pos = use_abs_pos
|
| 522 |
+
self.learn_sigma = learn_sigma
|
| 523 |
+
self.in_channels = in_channels
|
| 524 |
+
self.out_channels = in_channels if not learn_sigma else in_channels * 2
|
| 525 |
+
self.patch_size = patch_size
|
| 526 |
+
self.num_heads = num_heads
|
| 527 |
+
self.use_rope = use_rope
|
| 528 |
+
self.use_rmsnorm = use_rmsnorm
|
| 529 |
+
self.depth = depth
|
| 530 |
+
self.hidden_size = hidden_size
|
| 531 |
+
self.use_checkpoint = use_checkpoint
|
| 532 |
+
self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size, bias=True)
|
| 533 |
+
self.t_embedder = TimestepEmbedder(hidden_size)
|
| 534 |
+
self.y_embedder = LabelEmbedder(num_classes, hidden_size, class_dropout_prob)
|
| 535 |
+
num_patches = self.x_embedder.num_patches
|
| 536 |
+
# Will use fixed sin-cos embedding:
|
| 537 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False)
|
| 538 |
+
|
| 539 |
+
if not self.use_abs_pos and not self.use_rope:
|
| 540 |
+
import warnings
|
| 541 |
+
warnings.warn("Warning: Both Absolute Position Embedding and RoPE are disabled. "
|
| 542 |
+
"The model will be permutation-invariant (orderless)!")
|
| 543 |
+
|
| 544 |
+
# use rotary position encoding, borrow from EVA
|
| 545 |
+
if self.use_rope:
|
| 546 |
+
half_head_dim = hidden_size // num_heads // 2
|
| 547 |
+
hw_seq_len = input_size // patch_size
|
| 548 |
+
self.feat_rope = VisionRotaryEmbeddingFast(
|
| 549 |
+
dim=half_head_dim,
|
| 550 |
+
pt_seq_len=hw_seq_len,
|
| 551 |
+
)
|
| 552 |
+
else:
|
| 553 |
+
self.feat_rope = None
|
| 554 |
+
|
| 555 |
+
self.blocks = nn.ModuleList([
|
| 556 |
+
LightningDiTBlock(hidden_size,
|
| 557 |
+
num_heads,
|
| 558 |
+
mlp_ratio=mlp_ratio,
|
| 559 |
+
use_qknorm=use_qknorm,
|
| 560 |
+
use_swiglu=use_swiglu,
|
| 561 |
+
use_rmsnorm=use_rmsnorm,
|
| 562 |
+
wo_shift=wo_shift,
|
| 563 |
+
) for _ in range(depth)
|
| 564 |
+
])
|
| 565 |
+
self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels, use_rmsnorm=use_rmsnorm)
|
| 566 |
+
self.initialize_weights()
|
| 567 |
+
if hasattr(self, "register_to_config"):
|
| 568 |
+
self.register_to_config(
|
| 569 |
+
input_size=input_size,
|
| 570 |
+
patch_size=patch_size,
|
| 571 |
+
in_channels=in_channels,
|
| 572 |
+
hidden_size=hidden_size,
|
| 573 |
+
depth=depth,
|
| 574 |
+
num_heads=num_heads,
|
| 575 |
+
mlp_ratio=mlp_ratio,
|
| 576 |
+
class_dropout_prob=class_dropout_prob,
|
| 577 |
+
num_classes=num_classes,
|
| 578 |
+
learn_sigma=learn_sigma,
|
| 579 |
+
use_qknorm=use_qknorm,
|
| 580 |
+
use_swiglu=use_swiglu,
|
| 581 |
+
use_rope=use_rope,
|
| 582 |
+
use_rmsnorm=use_rmsnorm,
|
| 583 |
+
wo_shift=wo_shift,
|
| 584 |
+
use_checkpoint=use_checkpoint,
|
| 585 |
+
use_abs_pos=use_abs_pos,
|
| 586 |
+
)
|
| 587 |
+
|
| 588 |
+
def initialize_weights(self):
|
| 589 |
+
# Initialize transformer layers:
|
| 590 |
+
def _basic_init(module):
|
| 591 |
+
if isinstance(module, nn.Linear):
|
| 592 |
+
torch.nn.init.xavier_uniform_(module.weight)
|
| 593 |
+
if module.bias is not None:
|
| 594 |
+
nn.init.constant_(module.bias, 0)
|
| 595 |
+
self.apply(_basic_init)
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
if self.use_abs_pos:
|
| 599 |
+
pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5))
|
| 600 |
+
self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
|
| 601 |
+
else:
|
| 602 |
+
nn.init.constant_(self.pos_embed, 0)
|
| 603 |
+
|
| 604 |
+
# Initialize patch_embed like nn.Linear (instead of nn.Conv2d):
|
| 605 |
+
w = self.x_embedder.proj.weight.data
|
| 606 |
+
nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
|
| 607 |
+
nn.init.constant_(self.x_embedder.proj.bias, 0)
|
| 608 |
+
|
| 609 |
+
# Initialize label embedding table:
|
| 610 |
+
nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02)
|
| 611 |
+
|
| 612 |
+
# Initialize timestep embedding MLP:
|
| 613 |
+
nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
|
| 614 |
+
nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
|
| 615 |
+
|
| 616 |
+
# Zero-out adaLN modulation layers in LightningDiT blocks:
|
| 617 |
+
for block in self.blocks:
|
| 618 |
+
nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
|
| 619 |
+
nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
|
| 620 |
+
|
| 621 |
+
# Zero-out output layers:
|
| 622 |
+
nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
|
| 623 |
+
nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)
|
| 624 |
+
nn.init.constant_(self.final_layer.linear.weight, 0)
|
| 625 |
+
nn.init.constant_(self.final_layer.linear.bias, 0)
|
| 626 |
+
|
| 627 |
+
def unpatchify(self, x):
|
| 628 |
+
"""
|
| 629 |
+
x: (N, T, patch_size**2 * C)
|
| 630 |
+
imgs: (N, H, W, C)
|
| 631 |
+
"""
|
| 632 |
+
c = self.out_channels
|
| 633 |
+
p = self.x_embedder.patch_size[0]
|
| 634 |
+
h = w = int(x.shape[1] ** 0.5)
|
| 635 |
+
assert h * w == x.shape[1]
|
| 636 |
+
|
| 637 |
+
x = x.reshape(shape=(x.shape[0], h, w, p, p, c))
|
| 638 |
+
x = torch.einsum('nhwpqc->nchpwq', x)
|
| 639 |
+
imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p))
|
| 640 |
+
return imgs
|
| 641 |
+
|
| 642 |
+
def forward(
|
| 643 |
+
self,
|
| 644 |
+
hidden_states: torch.Tensor,
|
| 645 |
+
timestep: Optional[torch.LongTensor] = None,
|
| 646 |
+
class_labels: Optional[torch.LongTensor] = None,
|
| 647 |
+
return_dict: bool = True,
|
| 648 |
+
):
|
| 649 |
+
x = hidden_states
|
| 650 |
+
t = timestep
|
| 651 |
+
y = class_labels
|
| 652 |
+
"""
|
| 653 |
+
Forward pass of LightningDiT.
|
| 654 |
+
x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)
|
| 655 |
+
t: (N,) tensor of diffusion timesteps
|
| 656 |
+
y: (N,) tensor of class labels
|
| 657 |
+
use_checkpoint: boolean to toggle checkpointing
|
| 658 |
+
"""
|
| 659 |
+
|
| 660 |
+
use_checkpoint = self.use_checkpoint
|
| 661 |
+
|
| 662 |
+
x = self.x_embedder(x)
|
| 663 |
+
if self.use_abs_pos:
|
| 664 |
+
x = x + self.pos_embed
|
| 665 |
+
t = self.t_embedder(t) # (N, D)
|
| 666 |
+
y = self.y_embedder(y, self.training) # (N, D)
|
| 667 |
+
c = t + y # (N, D)
|
| 668 |
+
|
| 669 |
+
for block in self.blocks:
|
| 670 |
+
if use_checkpoint:
|
| 671 |
+
x = checkpoint(block, x, c, self.feat_rope, use_reentrant=True)
|
| 672 |
+
else:
|
| 673 |
+
x = block(x, c, self.feat_rope)
|
| 674 |
+
|
| 675 |
+
x = self.final_layer(x, c) # (N, T, patch_size ** 2 * out_channels)
|
| 676 |
+
x = self.unpatchify(x) # (N, out_channels, H, W)
|
| 677 |
+
|
| 678 |
+
if self.learn_sigma:
|
| 679 |
+
x, _ = x.chunk(2, dim=1)
|
| 680 |
+
if not return_dict:
|
| 681 |
+
return (x,)
|
| 682 |
+
return LightningDiT2DModelOutput(sample=x)
|
| 683 |
+
|
| 684 |
+
def forward_with_cfg(self, x, t, y, cfg_scale, cfg_interval=None, cfg_interval_start=None):
|
| 685 |
+
"""
|
| 686 |
+
Forward pass of LightningDiT, but also batches the unconditional forward pass for classifier-free guidance.
|
| 687 |
+
"""
|
| 688 |
+
# https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb
|
| 689 |
+
combined = torch.cat([x, x], dim=0)
|
| 690 |
+
model_out = self.forward(combined, t, y, return_dict=False)[0]
|
| 691 |
+
# For exact reproducibility reasons, we apply classifier-free guidance on only
|
| 692 |
+
# three channels by default. The standard approach to cfg applies it to all channels.
|
| 693 |
+
# This can be done by uncommenting the following line and commenting-out the line following that.
|
| 694 |
+
eps, rest = model_out[:, :self.in_channels], model_out[:, self.in_channels:]
|
| 695 |
+
# eps, rest = model_out[:, :3], model_out[:, 3:]
|
| 696 |
+
cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
|
| 697 |
+
half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps)
|
| 698 |
+
|
| 699 |
+
if cfg_interval is True:
|
| 700 |
+
timestep = t[0]
|
| 701 |
+
if timestep < cfg_interval_start:
|
| 702 |
+
half_eps = cond_eps
|
| 703 |
+
|
| 704 |
+
eps = torch.cat([half_eps, half_eps], dim=0)
|
| 705 |
+
return torch.cat([eps, rest], dim=1)
|
| 706 |
+
|
| 707 |
+
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0):
|
| 708 |
+
"""
|
| 709 |
+
grid_size: int of the grid height and width
|
| 710 |
+
return:
|
| 711 |
+
pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
|
| 712 |
+
"""
|
| 713 |
+
grid_h = np.arange(grid_size, dtype=np.float32)
|
| 714 |
+
grid_w = np.arange(grid_size, dtype=np.float32)
|
| 715 |
+
grid = np.meshgrid(grid_w, grid_h) # here w goes first
|
| 716 |
+
grid = np.stack(grid, axis=0)
|
| 717 |
+
|
| 718 |
+
grid = grid.reshape([2, 1, grid_size, grid_size])
|
| 719 |
+
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
| 720 |
+
if cls_token and extra_tokens > 0:
|
| 721 |
+
pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
|
| 722 |
+
return pos_embed
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
|
| 726 |
+
assert embed_dim % 2 == 0
|
| 727 |
+
|
| 728 |
+
# use half of dimensions to encode grid_h
|
| 729 |
+
emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
|
| 730 |
+
emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
|
| 731 |
+
|
| 732 |
+
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
|
| 733 |
+
return emb
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
|
| 737 |
+
"""
|
| 738 |
+
embed_dim: output dimension for each position
|
| 739 |
+
pos: a list of positions to be encoded: size (M,)
|
| 740 |
+
out: (M, D)
|
| 741 |
+
"""
|
| 742 |
+
assert embed_dim % 2 == 0
|
| 743 |
+
omega = np.arange(embed_dim // 2, dtype=np.float64)
|
| 744 |
+
omega /= embed_dim / 2.
|
| 745 |
+
omega = 1. / 10000**omega # (D/2,)
|
| 746 |
+
|
| 747 |
+
pos = pos.reshape(-1) # (M,)
|
| 748 |
+
out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
|
| 749 |
+
|
| 750 |
+
emb_sin = np.sin(out) # (M, D/2)
|
| 751 |
+
emb_cos = np.cos(out) # (M, D/2)
|
| 752 |
+
|
| 753 |
+
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
|
| 754 |
+
return emb
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
#################################################################################
|
| 758 |
+
# LightningDiT Configs #
|
| 759 |
+
#################################################################################
|
| 760 |
+
|
| 761 |
+
def _lightning_dit_XL_1(**kwargs):
|
| 762 |
+
return LightningDiT2DModel(depth=28, hidden_size=1152, patch_size=1, num_heads=16, **kwargs)
|
| 763 |
+
|
| 764 |
+
def _lightning_dit_XL_2(**kwargs):
|
| 765 |
+
return LightningDiT2DModel(depth=28, hidden_size=1152, patch_size=2, num_heads=16, **kwargs)
|
| 766 |
+
|
| 767 |
+
def _lightning_dit_L_2(**kwargs):
|
| 768 |
+
return LightningDiT2DModel(depth=24, hidden_size=1024, patch_size=2, num_heads=16, **kwargs)
|
| 769 |
+
|
| 770 |
+
def _lightning_dit_B_1(**kwargs):
|
| 771 |
+
return LightningDiT2DModel(depth=12, hidden_size=768, patch_size=1, num_heads=12, **kwargs)
|
| 772 |
+
|
| 773 |
+
def _lightning_dit_B_2(**kwargs):
|
| 774 |
+
return LightningDiT2DModel(depth=12, hidden_size=768, patch_size=2, num_heads=12, **kwargs)
|
| 775 |
+
|
| 776 |
+
def _lightning_dit_1p0B_1(**kwargs):
|
| 777 |
+
return LightningDiT2DModel(depth=24, hidden_size=1536, patch_size=1, num_heads=24, **kwargs)
|
| 778 |
+
|
| 779 |
+
def _lightning_dit_1p0B_2(**kwargs):
|
| 780 |
+
return LightningDiT2DModel(depth=24, hidden_size=1536, patch_size=2, num_heads=24, **kwargs)
|
| 781 |
+
|
| 782 |
+
def _lightning_dit_1p6B_1(**kwargs):
|
| 783 |
+
return LightningDiT2DModel(depth=28, hidden_size=1792, patch_size=1, num_heads=28, **kwargs)
|
| 784 |
+
|
| 785 |
+
def _lightning_dit_1p6B_2(**kwargs):
|
| 786 |
+
return LightningDiT2DModel(depth=28, hidden_size=1792, patch_size=2, num_heads=28, **kwargs)
|
| 787 |
+
|
| 788 |
+
LIGHTNING_DIT_PRESETS = {
|
| 789 |
+
'LightningDiT-B/1': _lightning_dit_B_1, 'LightningDiT-B/2': _lightning_dit_B_2,
|
| 790 |
+
'LightningDiT-L/2': _lightning_dit_L_2,
|
| 791 |
+
'LightningDiT-XL/1': _lightning_dit_XL_1, 'LightningDiT-XL/2': _lightning_dit_XL_2,
|
| 792 |
+
'LightningDiT-1p0B/1': _lightning_dit_1p0B_1, 'LightningDiT-1p0B/2': _lightning_dit_1p0B_2,
|
| 793 |
+
'LightningDiT-1p6B/1': _lightning_dit_1p6B_1, 'LightningDiT-1p6B/2': _lightning_dit_1p6B_2,
|
| 794 |
+
}
|
pae-mae-large-d32/decoder/config.json
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "PAEDecoder",
|
| 3 |
+
"decoder_patch_size": 16,
|
| 4 |
+
"encoder_config_path": "facebook/vit-mae-large",
|
| 5 |
+
"encoder_hidden_size": 1024,
|
| 6 |
+
"encoder_input_size": 256,
|
| 7 |
+
"encoder_num_heads": 16,
|
| 8 |
+
"encoder_patch_size": 16,
|
| 9 |
+
"latent_dim": 32,
|
| 10 |
+
"latent_mean": [
|
| 11 |
+
0.6328125,
|
| 12 |
+
1.1171875,
|
| 13 |
+
-1.140625,
|
| 14 |
+
0.95703125,
|
| 15 |
+
0.80859375,
|
| 16 |
+
-0.8046875,
|
| 17 |
+
0.43359375,
|
| 18 |
+
-0.263671875,
|
| 19 |
+
1.28125,
|
| 20 |
+
0.341796875,
|
| 21 |
+
-0.291015625,
|
| 22 |
+
-0.80859375,
|
| 23 |
+
0.71484375,
|
| 24 |
+
-0.89453125,
|
| 25 |
+
-1.046875,
|
| 26 |
+
0.96875,
|
| 27 |
+
-1.484375,
|
| 28 |
+
0.71875,
|
| 29 |
+
0.1767578125,
|
| 30 |
+
0.9140625,
|
| 31 |
+
0.9453125,
|
| 32 |
+
-1.0,
|
| 33 |
+
1.0859375,
|
| 34 |
+
-1.3515625,
|
| 35 |
+
-1.1015625,
|
| 36 |
+
-0.625,
|
| 37 |
+
0.53125,
|
| 38 |
+
0.640625,
|
| 39 |
+
-1.3984375,
|
| 40 |
+
0.4921875,
|
| 41 |
+
1.1015625,
|
| 42 |
+
0.515625
|
| 43 |
+
],
|
| 44 |
+
"latent_multiplier": 1.0,
|
| 45 |
+
"latent_std": [
|
| 46 |
+
0.5546875,
|
| 47 |
+
0.328125,
|
| 48 |
+
0.32421875,
|
| 49 |
+
0.3203125,
|
| 50 |
+
0.458984375,
|
| 51 |
+
0.3515625,
|
| 52 |
+
0.55078125,
|
| 53 |
+
0.470703125,
|
| 54 |
+
0.38671875,
|
| 55 |
+
0.51171875,
|
| 56 |
+
0.490234375,
|
| 57 |
+
0.515625,
|
| 58 |
+
0.380859375,
|
| 59 |
+
0.486328125,
|
| 60 |
+
0.3515625,
|
| 61 |
+
0.5390625,
|
| 62 |
+
0.3046875,
|
| 63 |
+
0.6015625,
|
| 64 |
+
0.404296875,
|
| 65 |
+
0.482421875,
|
| 66 |
+
0.3828125,
|
| 67 |
+
0.373046875,
|
| 68 |
+
0.408203125,
|
| 69 |
+
0.447265625,
|
| 70 |
+
0.4765625,
|
| 71 |
+
0.390625,
|
| 72 |
+
0.45703125,
|
| 73 |
+
0.45703125,
|
| 74 |
+
0.4375,
|
| 75 |
+
0.416015625,
|
| 76 |
+
0.45703125,
|
| 77 |
+
0.484375
|
| 78 |
+
]
|
| 79 |
+
}
|
pae-mae-large-d32/decoder/decoder_pae.py
ADDED
|
@@ -0,0 +1,1105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
|
| 3 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 4 |
+
from transformers.utils import (
|
| 5 |
+
ModelOutput,
|
| 6 |
+
)
|
| 7 |
+
from transformers.activations import ACT2FN
|
| 8 |
+
class ViTMAEConfig(PretrainedConfig):
|
| 9 |
+
r"""
|
| 10 |
+
This is the configuration class to store the configuration of a [`ViTMAEModel`]. It is used to instantiate an ViT
|
| 11 |
+
MAE model according to the specified arguments, defining the model architecture. Instantiating a configuration with
|
| 12 |
+
the defaults will yield a similar configuration to that of the ViT
|
| 13 |
+
[facebook/vit-mae-base](https://huggingface.co/facebook/vit-mae-base) architecture.
|
| 14 |
+
|
| 15 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 16 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 21 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 22 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 23 |
+
Number of hidden layers in the Transformer encoder.
|
| 24 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 25 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 26 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 27 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 28 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 29 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 30 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 31 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 32 |
+
The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.
|
| 33 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 34 |
+
The dropout ratio for the attention probabilities.
|
| 35 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 36 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 37 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 38 |
+
The epsilon used by the layer normalization layers.
|
| 39 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 40 |
+
The size (resolution) of each image.
|
| 41 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 42 |
+
The size (resolution) of each patch.
|
| 43 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 44 |
+
The number of input channels.
|
| 45 |
+
qkv_bias (`bool`, *optional*, defaults to `True`):
|
| 46 |
+
Whether to add a bias to the queries, keys and values.
|
| 47 |
+
decoder_num_attention_heads (`int`, *optional*, defaults to 16):
|
| 48 |
+
Number of attention heads for each attention layer in the decoder.
|
| 49 |
+
decoder_hidden_size (`int`, *optional*, defaults to 512):
|
| 50 |
+
Dimensionality of the decoder.
|
| 51 |
+
decoder_num_hidden_layers (`int`, *optional*, defaults to 8):
|
| 52 |
+
Number of hidden layers in the decoder.
|
| 53 |
+
decoder_intermediate_size (`int`, *optional*, defaults to 2048):
|
| 54 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the decoder.
|
| 55 |
+
mask_ratio (`float`, *optional*, defaults to 0.75):
|
| 56 |
+
The ratio of the number of masked tokens in the input sequence.
|
| 57 |
+
norm_pix_loss (`bool`, *optional*, defaults to `False`):
|
| 58 |
+
Whether or not to train with normalized pixels (see Table 3 in the paper). Using normalized pixels improved
|
| 59 |
+
representation quality in the experiments of the authors.
|
| 60 |
+
|
| 61 |
+
Example:
|
| 62 |
+
|
| 63 |
+
```python
|
| 64 |
+
>>> from transformers import ViTMAEConfig, ViTMAEModel
|
| 65 |
+
|
| 66 |
+
>>> # Initializing a ViT MAE vit-mae-base style configuration
|
| 67 |
+
>>> configuration = ViTMAEConfig()
|
| 68 |
+
|
| 69 |
+
>>> # Initializing a model (with random weights) from the vit-mae-base style configuration
|
| 70 |
+
>>> model = ViTMAEModel(configuration)
|
| 71 |
+
|
| 72 |
+
>>> # Accessing the model configuration
|
| 73 |
+
>>> configuration = model.config
|
| 74 |
+
```"""
|
| 75 |
+
|
| 76 |
+
model_type = "vit_mae"
|
| 77 |
+
|
| 78 |
+
def __init__(
|
| 79 |
+
self,
|
| 80 |
+
hidden_size=768,
|
| 81 |
+
num_hidden_layers=12,
|
| 82 |
+
num_attention_heads=12,
|
| 83 |
+
intermediate_size=3072,
|
| 84 |
+
hidden_act="gelu",
|
| 85 |
+
hidden_dropout_prob=0.0,
|
| 86 |
+
attention_probs_dropout_prob=0.0,
|
| 87 |
+
initializer_range=0.02,
|
| 88 |
+
layer_norm_eps=1e-12,
|
| 89 |
+
image_size=224,
|
| 90 |
+
patch_size=16,
|
| 91 |
+
num_channels=3,
|
| 92 |
+
qkv_bias=True,
|
| 93 |
+
decoder_num_attention_heads=16,
|
| 94 |
+
decoder_hidden_size=512,
|
| 95 |
+
decoder_num_hidden_layers=8,
|
| 96 |
+
decoder_intermediate_size=2048,
|
| 97 |
+
mask_ratio=0.75,
|
| 98 |
+
norm_pix_loss=False,
|
| 99 |
+
**kwargs,
|
| 100 |
+
):
|
| 101 |
+
super().__init__(**kwargs)
|
| 102 |
+
|
| 103 |
+
self.hidden_size = hidden_size
|
| 104 |
+
self.num_hidden_layers = num_hidden_layers
|
| 105 |
+
self.num_attention_heads = num_attention_heads
|
| 106 |
+
self.intermediate_size = intermediate_size
|
| 107 |
+
self.hidden_act = hidden_act
|
| 108 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 109 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 110 |
+
self.initializer_range = initializer_range
|
| 111 |
+
self.layer_norm_eps = layer_norm_eps
|
| 112 |
+
self.image_size = image_size
|
| 113 |
+
self.patch_size = patch_size
|
| 114 |
+
self.num_channels = num_channels
|
| 115 |
+
self.qkv_bias = qkv_bias
|
| 116 |
+
self.decoder_num_attention_heads = decoder_num_attention_heads
|
| 117 |
+
self.decoder_hidden_size = decoder_hidden_size
|
| 118 |
+
self.decoder_num_hidden_layers = decoder_num_hidden_layers
|
| 119 |
+
self.decoder_intermediate_size = decoder_intermediate_size
|
| 120 |
+
self.mask_ratio = mask_ratio
|
| 121 |
+
self.norm_pix_loss = norm_pix_loss
|
| 122 |
+
|
| 123 |
+
# coding=utf-8
|
| 124 |
+
# Copyright 2022 Facebook AI and The HuggingFace Inc. team. All rights reserved.
|
| 125 |
+
#
|
| 126 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 127 |
+
# you may not use this file except in compliance with the License.
|
| 128 |
+
# You may obtain a copy of the License at
|
| 129 |
+
#
|
| 130 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 131 |
+
#
|
| 132 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 133 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 134 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 135 |
+
# See the License for the specific language governing permissions and
|
| 136 |
+
# limitations under the License.
|
| 137 |
+
"""PyTorch ViT MAE (masked autoencoder) model."""
|
| 138 |
+
|
| 139 |
+
import collections.abc
|
| 140 |
+
import math
|
| 141 |
+
from copy import deepcopy
|
| 142 |
+
from dataclasses import dataclass
|
| 143 |
+
from typing import Optional, Set, Tuple, Union
|
| 144 |
+
|
| 145 |
+
import numpy as np
|
| 146 |
+
import torch
|
| 147 |
+
from torch import nn
|
| 148 |
+
# correct the above import to the following
|
| 149 |
+
from transformers.modeling_outputs import BaseModelOutput
|
| 150 |
+
|
| 151 |
+
try:
|
| 152 |
+
from flash_attn import flash_attn_func
|
| 153 |
+
HAS_FLASH_ATTN = True # if set to False, FlashAttention is unavailable
|
| 154 |
+
except:
|
| 155 |
+
print('FlashAttention is not installed.')
|
| 156 |
+
HAS_FLASH_ATTN = False
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@dataclass
|
| 160 |
+
class ViTMAEModelOutput(ModelOutput):
|
| 161 |
+
"""
|
| 162 |
+
Class for ViTMAEModel's outputs, with potential hidden states and attentions.
|
| 163 |
+
|
| 164 |
+
Args:
|
| 165 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 166 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 167 |
+
mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
|
| 168 |
+
Tensor indicating which patches are masked (1) and which are not (0).
|
| 169 |
+
ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 170 |
+
Tensor containing the original index of the (shuffled) masked patches.
|
| 171 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 172 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 173 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 174 |
+
plus the initial embedding outputs.
|
| 175 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 176 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 177 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 178 |
+
the self-attention heads.
|
| 179 |
+
"""
|
| 180 |
+
|
| 181 |
+
last_hidden_state: torch.FloatTensor = None
|
| 182 |
+
mask: torch.LongTensor = None
|
| 183 |
+
ids_restore: torch.LongTensor = None
|
| 184 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 185 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
@dataclass
|
| 189 |
+
class ViTMAEDecoderOutput(ModelOutput):
|
| 190 |
+
"""
|
| 191 |
+
Class for ViTMAEDecoder's outputs, with potential hidden states and attentions.
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`):
|
| 195 |
+
Pixel reconstruction logits.
|
| 196 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 197 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 198 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 199 |
+
plus the initial embedding outputs.
|
| 200 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 201 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 202 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 203 |
+
the self-attention heads.
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
logits: torch.FloatTensor = None
|
| 207 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 208 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
@dataclass
|
| 212 |
+
class ViTMAEForPreTrainingOutput(ModelOutput):
|
| 213 |
+
"""
|
| 214 |
+
Class for ViTMAEForPreTraining's outputs, with potential hidden states and attentions.
|
| 215 |
+
|
| 216 |
+
Args:
|
| 217 |
+
loss (`torch.FloatTensor` of shape `(1,)`):
|
| 218 |
+
Pixel reconstruction loss.
|
| 219 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`):
|
| 220 |
+
Pixel reconstruction logits.
|
| 221 |
+
mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
|
| 222 |
+
Tensor indicating which patches are masked (1) and which are not (0).
|
| 223 |
+
ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 224 |
+
Tensor containing the original index of the (shuffled) masked patches.
|
| 225 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 226 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 227 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 228 |
+
plus the initial embedding outputs.
|
| 229 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 230 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 231 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 232 |
+
the self-attention heads.
|
| 233 |
+
"""
|
| 234 |
+
|
| 235 |
+
loss: Optional[torch.FloatTensor] = None
|
| 236 |
+
logits: torch.FloatTensor = None
|
| 237 |
+
mask: torch.LongTensor = None
|
| 238 |
+
ids_restore: torch.LongTensor = None
|
| 239 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 240 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def get_2d_sincos_pos_embed(embed_dim, grid_size, add_cls_token=False):
|
| 244 |
+
"""
|
| 245 |
+
Create 2D sin/cos positional embeddings.
|
| 246 |
+
|
| 247 |
+
Args:
|
| 248 |
+
embed_dim (`int`):
|
| 249 |
+
Embedding dimension.
|
| 250 |
+
grid_size (`int`):
|
| 251 |
+
The grid height and width.
|
| 252 |
+
add_cls_token (`bool`, *optional*, defaults to `False`):
|
| 253 |
+
Whether or not to add a classification (CLS) token.
|
| 254 |
+
|
| 255 |
+
Returns:
|
| 256 |
+
(`torch.FloatTensor` of shape (grid_size*grid_size, embed_dim) or (1+grid_size*grid_size, embed_dim): the
|
| 257 |
+
position embeddings (with or without classification token)
|
| 258 |
+
"""
|
| 259 |
+
grid_h = np.arange(grid_size, dtype=np.float32)
|
| 260 |
+
grid_w = np.arange(grid_size, dtype=np.float32)
|
| 261 |
+
grid = np.meshgrid(grid_w, grid_h) # here w goes first
|
| 262 |
+
grid = np.stack(grid, axis=0)
|
| 263 |
+
|
| 264 |
+
grid = grid.reshape([2, 1, grid_size, grid_size])
|
| 265 |
+
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
| 266 |
+
if add_cls_token:
|
| 267 |
+
pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
|
| 268 |
+
return pos_embed
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
|
| 272 |
+
if embed_dim % 2 != 0:
|
| 273 |
+
raise ValueError("embed_dim must be even")
|
| 274 |
+
|
| 275 |
+
# use half of dimensions to encode grid_h
|
| 276 |
+
emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
|
| 277 |
+
emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
|
| 278 |
+
|
| 279 |
+
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
|
| 280 |
+
return emb
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
|
| 284 |
+
"""
|
| 285 |
+
embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D)
|
| 286 |
+
"""
|
| 287 |
+
if embed_dim % 2 != 0:
|
| 288 |
+
raise ValueError("embed_dim must be even")
|
| 289 |
+
|
| 290 |
+
omega = np.arange(embed_dim // 2, dtype=float)
|
| 291 |
+
omega /= embed_dim / 2.0
|
| 292 |
+
omega = 1.0 / 10000**omega # (D/2,)
|
| 293 |
+
|
| 294 |
+
pos = pos.reshape(-1) # (M,)
|
| 295 |
+
out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
|
| 296 |
+
|
| 297 |
+
emb_sin = np.sin(out) # (M, D/2)
|
| 298 |
+
emb_cos = np.cos(out) # (M, D/2)
|
| 299 |
+
|
| 300 |
+
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
|
| 301 |
+
return emb
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
class ViTMAEEmbeddings(nn.Module):
|
| 305 |
+
"""
|
| 306 |
+
Construct the CLS token, position and patch embeddings.
|
| 307 |
+
|
| 308 |
+
"""
|
| 309 |
+
|
| 310 |
+
def __init__(self, config):
|
| 311 |
+
super().__init__()
|
| 312 |
+
|
| 313 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 314 |
+
self.patch_embeddings = ViTMAEPatchEmbeddings(config)
|
| 315 |
+
self.num_patches = self.patch_embeddings.num_patches
|
| 316 |
+
# fixed sin-cos embedding
|
| 317 |
+
self.position_embeddings = nn.Parameter(
|
| 318 |
+
torch.zeros(1, self.num_patches + 1, config.hidden_size), requires_grad=False
|
| 319 |
+
)
|
| 320 |
+
self.config = config
|
| 321 |
+
self.initialize_weights()
|
| 322 |
+
|
| 323 |
+
def initialize_weights(self):
|
| 324 |
+
# initialize (and freeze) position embeddings by sin-cos embedding
|
| 325 |
+
pos_embed = get_2d_sincos_pos_embed(
|
| 326 |
+
self.position_embeddings.shape[-1], int(self.patch_embeddings.num_patches**0.5), add_cls_token=True
|
| 327 |
+
)
|
| 328 |
+
self.position_embeddings.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
|
| 329 |
+
|
| 330 |
+
# initialize patch_embeddings like nn.Linear (instead of nn.Conv2d)
|
| 331 |
+
w = self.patch_embeddings.projection.weight.data
|
| 332 |
+
torch.nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
|
| 333 |
+
|
| 334 |
+
# timm's trunc_normal_(std=.02) is effectively normal_(std=0.02) as cutoff is too big (2.)
|
| 335 |
+
torch.nn.init.normal_(self.cls_token, std=self.config.initializer_range)
|
| 336 |
+
|
| 337 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
| 338 |
+
"""
|
| 339 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher
|
| 340 |
+
resolution images.
|
| 341 |
+
|
| 342 |
+
Source:
|
| 343 |
+
https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174
|
| 344 |
+
"""
|
| 345 |
+
num_patches = embeddings.shape[1] - 1
|
| 346 |
+
num_positions = self.position_embeddings.shape[1] - 1
|
| 347 |
+
|
| 348 |
+
if num_patches == num_positions and height == width:
|
| 349 |
+
return self.position_embeddings
|
| 350 |
+
|
| 351 |
+
class_pos_embed = self.position_embeddings[:, 0, :]
|
| 352 |
+
patch_pos_embed = self.position_embeddings[:, 1:, :]
|
| 353 |
+
dim = embeddings.shape[-1]
|
| 354 |
+
h0 = height // self.config.patch_size
|
| 355 |
+
w0 = width // self.config.patch_size
|
| 356 |
+
# we add a small number to avoid floating point error in the interpolation
|
| 357 |
+
# see discussion at https://github.com/facebookresearch/dino/issues/8
|
| 358 |
+
h0, w0 = h0 + 0.1, w0 + 0.1
|
| 359 |
+
patch_pos_embed = patch_pos_embed.reshape(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim)
|
| 360 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 361 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 362 |
+
patch_pos_embed,
|
| 363 |
+
scale_factor=(h0 / math.sqrt(num_positions), w0 / math.sqrt(num_positions)),
|
| 364 |
+
mode="bicubic",
|
| 365 |
+
align_corners=False,
|
| 366 |
+
)
|
| 367 |
+
if int(h0) != patch_pos_embed.shape[-2] or int(w0) != patch_pos_embed.shape[-1]:
|
| 368 |
+
raise ValueError("Width or height does not match with the interpolated position embeddings")
|
| 369 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 370 |
+
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
|
| 371 |
+
|
| 372 |
+
def random_masking(self, sequence, noise=None):
|
| 373 |
+
"""
|
| 374 |
+
Perform per-sample random masking by per-sample shuffling. Per-sample shuffling is done by argsort random
|
| 375 |
+
noise.
|
| 376 |
+
|
| 377 |
+
Args:
|
| 378 |
+
sequence (`torch.LongTensor` of shape `(batch_size, sequence_length, dim)`)
|
| 379 |
+
noise (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*) which is
|
| 380 |
+
mainly used for testing purposes to control randomness and maintain the reproducibility
|
| 381 |
+
"""
|
| 382 |
+
batch_size, seq_length, dim = sequence.shape
|
| 383 |
+
len_keep = int(seq_length * (1 - self.config.mask_ratio))
|
| 384 |
+
|
| 385 |
+
if noise is None:
|
| 386 |
+
noise = torch.rand(batch_size, seq_length, device=sequence.device) # noise in [0, 1]
|
| 387 |
+
|
| 388 |
+
# sort noise for each sample
|
| 389 |
+
ids_shuffle = torch.argsort(noise, dim=1).to(sequence.device) # ascend: small is keep, large is remove
|
| 390 |
+
ids_restore = torch.argsort(ids_shuffle, dim=1).to(sequence.device)
|
| 391 |
+
|
| 392 |
+
# keep the first subset
|
| 393 |
+
ids_keep = ids_shuffle[:, :len_keep]
|
| 394 |
+
sequence_unmasked = torch.gather(sequence, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, dim))
|
| 395 |
+
|
| 396 |
+
# generate the binary mask: 0 is keep, 1 is remove
|
| 397 |
+
mask = torch.ones([batch_size, seq_length], device=sequence.device)
|
| 398 |
+
mask[:, :len_keep] = 0
|
| 399 |
+
# unshuffle to get the binary mask
|
| 400 |
+
mask = torch.gather(mask, dim=1, index=ids_restore)
|
| 401 |
+
|
| 402 |
+
return sequence_unmasked, mask, ids_restore
|
| 403 |
+
|
| 404 |
+
def forward(self, pixel_values, noise=None, interpolate_pos_encoding: bool = False):
|
| 405 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 406 |
+
embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
|
| 407 |
+
if interpolate_pos_encoding:
|
| 408 |
+
position_embeddings = self.interpolate_pos_encoding(embeddings, height, width)
|
| 409 |
+
else:
|
| 410 |
+
position_embeddings = self.position_embeddings
|
| 411 |
+
|
| 412 |
+
# add position embeddings w/o cls token
|
| 413 |
+
embeddings = embeddings + position_embeddings[:, 1:, :]
|
| 414 |
+
|
| 415 |
+
# masking: length -> length * config.mask_ratio
|
| 416 |
+
embeddings, mask, ids_restore = self.random_masking(embeddings, noise)
|
| 417 |
+
|
| 418 |
+
# append cls token
|
| 419 |
+
cls_token = self.cls_token + position_embeddings[:, :1, :]
|
| 420 |
+
cls_tokens = cls_token.expand(embeddings.shape[0], -1, -1)
|
| 421 |
+
embeddings = torch.cat((cls_tokens, embeddings), dim=1)
|
| 422 |
+
|
| 423 |
+
return embeddings, mask, ids_restore
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
class ViTMAEPatchEmbeddings(nn.Module):
|
| 427 |
+
"""
|
| 428 |
+
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
|
| 429 |
+
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
|
| 430 |
+
Transformer.
|
| 431 |
+
"""
|
| 432 |
+
|
| 433 |
+
def __init__(self, config):
|
| 434 |
+
super().__init__()
|
| 435 |
+
image_size, patch_size = config.image_size, config.patch_size
|
| 436 |
+
num_channels, hidden_size = config.num_channels, config.hidden_size
|
| 437 |
+
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
|
| 438 |
+
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 439 |
+
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
| 440 |
+
self.image_size = image_size
|
| 441 |
+
self.patch_size = patch_size
|
| 442 |
+
self.num_channels = num_channels
|
| 443 |
+
self.num_patches = num_patches
|
| 444 |
+
|
| 445 |
+
self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
|
| 446 |
+
|
| 447 |
+
def forward(self, pixel_values, interpolate_pos_encoding: bool = False):
|
| 448 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 449 |
+
if num_channels != self.num_channels:
|
| 450 |
+
raise ValueError(
|
| 451 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
if not interpolate_pos_encoding and (height != self.image_size[0] or width != self.image_size[1]):
|
| 455 |
+
raise ValueError(
|
| 456 |
+
f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
|
| 457 |
+
)
|
| 458 |
+
x = self.projection(pixel_values).flatten(2).transpose(1, 2)
|
| 459 |
+
return x
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
# Copied from transformers.models.vit.modeling_vit.ViTSelfAttention ViT->ViTMAE
|
| 463 |
+
class ViTMAESelfAttention(nn.Module):
|
| 464 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 465 |
+
super().__init__()
|
| 466 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 467 |
+
raise ValueError(
|
| 468 |
+
f"The hidden size {config.hidden_size,} is not a multiple of the number of attention "
|
| 469 |
+
f"heads {config.num_attention_heads}."
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
self.has_flash_attn = HAS_FLASH_ATTN
|
| 473 |
+
self.num_attention_heads = config.num_attention_heads
|
| 474 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 475 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 476 |
+
|
| 477 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 478 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 479 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 480 |
+
|
| 481 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 482 |
+
self.attention_probs_dropout_prob = config.attention_probs_dropout_prob
|
| 483 |
+
|
| 484 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
| 485 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 486 |
+
x = x.view(new_x_shape)
|
| 487 |
+
return x.permute(0, 2, 1, 3)
|
| 488 |
+
|
| 489 |
+
def reshape_for_flash(self, x: torch.Tensor) -> torch.Tensor:
|
| 490 |
+
"""Reshape to (B, N, num_heads, head_dim) for flash_attn_func."""
|
| 491 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 492 |
+
return x.view(new_x_shape)
|
| 493 |
+
|
| 494 |
+
def forward(
|
| 495 |
+
self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
|
| 496 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 497 |
+
# Use FlashAttention when available and no special outputs are needed
|
| 498 |
+
if self.has_flash_attn and not output_attentions and head_mask is None:
|
| 499 |
+
query_layer = self.reshape_for_flash(self.query(hidden_states))
|
| 500 |
+
key_layer = self.reshape_for_flash(self.key(hidden_states))
|
| 501 |
+
value_layer = self.reshape_for_flash(self.value(hidden_states))
|
| 502 |
+
|
| 503 |
+
context_layer = flash_attn_func(
|
| 504 |
+
query_layer, key_layer, value_layer,
|
| 505 |
+
dropout_p=self.attention_probs_dropout_prob if self.training else 0.0,
|
| 506 |
+
causal=False, deterministic=True
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
context_layer = context_layer.reshape(hidden_states.size(0), -1, self.all_head_size)
|
| 510 |
+
return (context_layer,)
|
| 511 |
+
|
| 512 |
+
# Fallback: manual attention computation
|
| 513 |
+
mixed_query_layer = self.query(hidden_states)
|
| 514 |
+
|
| 515 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 516 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 517 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 518 |
+
|
| 519 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 520 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 521 |
+
|
| 522 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 523 |
+
attention_probs = self.dropout(attention_probs)
|
| 524 |
+
|
| 525 |
+
if head_mask is not None:
|
| 526 |
+
attention_probs = attention_probs * head_mask
|
| 527 |
+
|
| 528 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 529 |
+
|
| 530 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 531 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 532 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 533 |
+
|
| 534 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 535 |
+
|
| 536 |
+
return outputs
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
# Copied from transformers.models.vit.modeling_vit.ViTSdpaSelfAttention ViT->ViTMAE
|
| 540 |
+
class ViTMAESdpaSelfAttention(ViTMAESelfAttention):
|
| 541 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 542 |
+
super().__init__(config)
|
| 543 |
+
self.attention_probs_dropout_prob = config.attention_probs_dropout_prob
|
| 544 |
+
|
| 545 |
+
def forward(
|
| 546 |
+
self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
|
| 547 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 548 |
+
# Use FlashAttention when available and no special outputs are needed
|
| 549 |
+
if self.has_flash_attn and not output_attentions and head_mask is None:
|
| 550 |
+
query_layer = self.reshape_for_flash(self.query(hidden_states))
|
| 551 |
+
key_layer = self.reshape_for_flash(self.key(hidden_states))
|
| 552 |
+
value_layer = self.reshape_for_flash(self.value(hidden_states))
|
| 553 |
+
|
| 554 |
+
context_layer = flash_attn_func(
|
| 555 |
+
query_layer, key_layer, value_layer,
|
| 556 |
+
dropout_p=self.attention_probs_dropout_prob if self.training else 0.0,
|
| 557 |
+
causal=False, deterministic=True
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
context_layer = context_layer.reshape(hidden_states.size(0), -1, self.all_head_size)
|
| 561 |
+
return context_layer, None
|
| 562 |
+
|
| 563 |
+
# Fallback: PyTorch SDPA
|
| 564 |
+
mixed_query_layer = self.query(hidden_states)
|
| 565 |
+
|
| 566 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 567 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 568 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 569 |
+
|
| 570 |
+
context_layer = torch.nn.functional.scaled_dot_product_attention(
|
| 571 |
+
query_layer,
|
| 572 |
+
key_layer,
|
| 573 |
+
value_layer,
|
| 574 |
+
head_mask,
|
| 575 |
+
self.attention_probs_dropout_prob if self.training else 0.0,
|
| 576 |
+
is_causal=False,
|
| 577 |
+
scale=None,
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 581 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 582 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 583 |
+
|
| 584 |
+
return context_layer, None
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
# Copied from transformers.models.vit.modeling_vit.ViTSelfOutput with ViT->ViTMAE
|
| 588 |
+
class ViTMAESelfOutput(nn.Module):
|
| 589 |
+
"""
|
| 590 |
+
The residual connection is defined in ViTMAELayer instead of here (as is the case with other models), due to the
|
| 591 |
+
layernorm applied before each block.
|
| 592 |
+
"""
|
| 593 |
+
|
| 594 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 595 |
+
super().__init__()
|
| 596 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 597 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 598 |
+
|
| 599 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 600 |
+
hidden_states = self.dense(hidden_states)
|
| 601 |
+
hidden_states = self.dropout(hidden_states)
|
| 602 |
+
|
| 603 |
+
return hidden_states
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
# Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->ViTMAE
|
| 607 |
+
class ViTMAEAttention(nn.Module):
|
| 608 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 609 |
+
super().__init__()
|
| 610 |
+
self.attention = ViTMAESelfAttention(config)
|
| 611 |
+
self.output = ViTMAESelfOutput(config)
|
| 612 |
+
|
| 613 |
+
def forward(
|
| 614 |
+
self,
|
| 615 |
+
hidden_states: torch.Tensor,
|
| 616 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 617 |
+
output_attentions: bool = False,
|
| 618 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 619 |
+
self_outputs = self.attention(hidden_states, head_mask, output_attentions)
|
| 620 |
+
|
| 621 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 622 |
+
|
| 623 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 624 |
+
return outputs
|
| 625 |
+
|
| 626 |
+
# Copied from transformers.models.vit.modeling_vit.ViTIntermediate ViT->ViTMAE
|
| 627 |
+
class ViTMAEIntermediate(nn.Module):
|
| 628 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 629 |
+
super().__init__()
|
| 630 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 631 |
+
if isinstance(config.hidden_act, str):
|
| 632 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 633 |
+
else:
|
| 634 |
+
self.intermediate_act_fn = config.hidden_act
|
| 635 |
+
|
| 636 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 637 |
+
hidden_states = self.dense(hidden_states)
|
| 638 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 639 |
+
|
| 640 |
+
return hidden_states
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
# Copied from transformers.models.vit.modeling_vit.ViTOutput ViT->ViTMAE
|
| 644 |
+
class ViTMAEOutput(nn.Module):
|
| 645 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 646 |
+
super().__init__()
|
| 647 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 648 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 649 |
+
|
| 650 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 651 |
+
hidden_states = self.dense(hidden_states)
|
| 652 |
+
hidden_states = self.dropout(hidden_states)
|
| 653 |
+
|
| 654 |
+
hidden_states = hidden_states + input_tensor
|
| 655 |
+
|
| 656 |
+
return hidden_states
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
# Copied from transformers.models.vit.modeling_vit.ViTLayer with ViT->ViTMAE,VIT->VITMAE
|
| 661 |
+
class ViTMAELayer(nn.Module):
|
| 662 |
+
"""This corresponds to the Block class in the timm implementation."""
|
| 663 |
+
|
| 664 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 665 |
+
super().__init__()
|
| 666 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 667 |
+
self.seq_len_dim = 1
|
| 668 |
+
self.attention = ViTMAEAttention(config) # no SPDA by default
|
| 669 |
+
self.intermediate = ViTMAEIntermediate(config)
|
| 670 |
+
self.output = ViTMAEOutput(config)
|
| 671 |
+
self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 672 |
+
self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 673 |
+
|
| 674 |
+
def forward(
|
| 675 |
+
self,
|
| 676 |
+
hidden_states: torch.Tensor,
|
| 677 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 678 |
+
output_attentions: bool = False,
|
| 679 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 680 |
+
self_attention_outputs = self.attention(
|
| 681 |
+
self.layernorm_before(hidden_states), # in ViTMAE, layernorm is applied before self-attention
|
| 682 |
+
head_mask,
|
| 683 |
+
output_attentions=output_attentions,
|
| 684 |
+
)
|
| 685 |
+
attention_output = self_attention_outputs[0]
|
| 686 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 687 |
+
|
| 688 |
+
# first residual connection
|
| 689 |
+
hidden_states = attention_output + hidden_states
|
| 690 |
+
|
| 691 |
+
# in ViTMAE, layernorm is also applied after self-attention
|
| 692 |
+
layer_output = self.layernorm_after(hidden_states)
|
| 693 |
+
layer_output = self.intermediate(layer_output)
|
| 694 |
+
|
| 695 |
+
# second residual connection is done here
|
| 696 |
+
layer_output = self.output(layer_output, hidden_states)
|
| 697 |
+
|
| 698 |
+
outputs = (layer_output,) + outputs
|
| 699 |
+
|
| 700 |
+
return outputs
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
class GeneralDecoder(nn.Module):
|
| 704 |
+
def __init__(self, config, num_patches):
|
| 705 |
+
super().__init__()
|
| 706 |
+
self.decoder_embed = nn.Linear(config.hidden_size, config.decoder_hidden_size, bias=True)
|
| 707 |
+
self.decoder_pos_embed = nn.Parameter(
|
| 708 |
+
torch.zeros(1, num_patches + 1, config.decoder_hidden_size), requires_grad=False
|
| 709 |
+
) # fixed sin-cos embedding
|
| 710 |
+
|
| 711 |
+
decoder_config = deepcopy(config)
|
| 712 |
+
decoder_config.hidden_size = config.decoder_hidden_size
|
| 713 |
+
decoder_config.num_hidden_layers = config.decoder_num_hidden_layers
|
| 714 |
+
decoder_config.num_attention_heads = config.decoder_num_attention_heads
|
| 715 |
+
decoder_config.intermediate_size = config.decoder_intermediate_size
|
| 716 |
+
self.decoder_layers = nn.ModuleList(
|
| 717 |
+
[ViTMAELayer(decoder_config) for _ in range(config.decoder_num_hidden_layers)]
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
self.decoder_norm = nn.LayerNorm(config.decoder_hidden_size, eps=config.layer_norm_eps)
|
| 721 |
+
self.decoder_pred = nn.Linear(
|
| 722 |
+
config.decoder_hidden_size, config.patch_size**2 * config.num_channels, bias=True
|
| 723 |
+
) # encoder to decoder
|
| 724 |
+
self.gradient_checkpointing = False
|
| 725 |
+
self.config = config
|
| 726 |
+
self.num_patches = num_patches
|
| 727 |
+
self.initialize_weights(num_patches)
|
| 728 |
+
self.decoder_config = decoder_config
|
| 729 |
+
self.set_trainable_cls_token()
|
| 730 |
+
def set_trainable_cls_token(self, tensor: Optional[torch.Tensor] = None):
|
| 731 |
+
# register a trainable CLS token
|
| 732 |
+
tensor = torch.zeros(1, 1, self.decoder_config.hidden_size) if tensor is None else tensor
|
| 733 |
+
self.trainable_cls_token = nn.Parameter(tensor)
|
| 734 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor) -> torch.Tensor:
|
| 735 |
+
"""
|
| 736 |
+
This method is a modified version of the interpolation function for ViT-mae model at the deocder, that
|
| 737 |
+
allows to interpolate the pre-trained decoder position encodings, to be able to use the model on higher
|
| 738 |
+
resolution images.
|
| 739 |
+
|
| 740 |
+
Source:
|
| 741 |
+
https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174
|
| 742 |
+
"""
|
| 743 |
+
|
| 744 |
+
# -1 removes the class dimension since we later append it without interpolation
|
| 745 |
+
embeddings_positions = embeddings.shape[1] - 1
|
| 746 |
+
num_positions = self.decoder_pos_embed.shape[1] - 1
|
| 747 |
+
|
| 748 |
+
# Separation of class token and patch tokens
|
| 749 |
+
class_pos_embed = self.decoder_pos_embed[:, 0, :]
|
| 750 |
+
patch_pos_embed = self.decoder_pos_embed[:, 1:, :]
|
| 751 |
+
|
| 752 |
+
# To retain the final 3d tensor with the required dimensions
|
| 753 |
+
dim = self.decoder_pos_embed.shape[-1]
|
| 754 |
+
|
| 755 |
+
# Increasing a dimension to enable bicubic interpolation
|
| 756 |
+
patch_pos_embed = patch_pos_embed.reshape(1, 1, -1, dim)
|
| 757 |
+
|
| 758 |
+
# permute to bring the dimension to be interpolated, to the last
|
| 759 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 760 |
+
|
| 761 |
+
# Interpolating the decoder position embeddings shape wrt embeddings shape i.e (x).
|
| 762 |
+
# 1 keeps the other dimension constant
|
| 763 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 764 |
+
patch_pos_embed,
|
| 765 |
+
scale_factor=(1, embeddings_positions / num_positions),
|
| 766 |
+
mode="bicubic",
|
| 767 |
+
align_corners=False,
|
| 768 |
+
)
|
| 769 |
+
|
| 770 |
+
# Converting back to the original shape
|
| 771 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 772 |
+
# Adding the class token back
|
| 773 |
+
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
|
| 774 |
+
def interpolate_latent(self, x: torch.Tensor) -> torch.Tensor:
|
| 775 |
+
b, l, c = x.shape
|
| 776 |
+
if l == self.num_patches:
|
| 777 |
+
return x
|
| 778 |
+
# interpolate the latent
|
| 779 |
+
#print(f"interpolating latent from {l} to {self.num_patches}, x.shape = {x.shape}")
|
| 780 |
+
h, w = int(l**0.5), int(l**0.5)
|
| 781 |
+
x = x.reshape(b, h, w, c)
|
| 782 |
+
x = x.permute(0, 3, 1, 2)
|
| 783 |
+
target_size = (int(self.num_patches**0.5), int(self.num_patches**0.5))
|
| 784 |
+
x = nn.functional.interpolate(x, size=target_size, mode="bilinear", align_corners=False)
|
| 785 |
+
x = x.permute(0, 2, 3, 1).contiguous().view(b, self.num_patches, c)
|
| 786 |
+
return x
|
| 787 |
+
|
| 788 |
+
def initialize_weights(self, num_patches):
|
| 789 |
+
# initialize (and freeze) position embeddings by sin-cos embedding
|
| 790 |
+
decoder_pos_embed = get_2d_sincos_pos_embed(
|
| 791 |
+
self.decoder_pos_embed.shape[-1], int(num_patches**0.5), add_cls_token=True
|
| 792 |
+
)
|
| 793 |
+
self.decoder_pos_embed.data.copy_(torch.from_numpy(decoder_pos_embed).float().unsqueeze(0))
|
| 794 |
+
|
| 795 |
+
# timm's trunc_normal_(std=.02) is effectively normal_(std=0.02) as cutoff is too big (2.)
|
| 796 |
+
# torch.nn.init.normal_(self.mask_token, std=self.config.initializer_range)
|
| 797 |
+
def unpatchify(self, patchified_pixel_values, original_image_size: Optional[Tuple[int, int]] = None):
|
| 798 |
+
"""
|
| 799 |
+
Args:
|
| 800 |
+
patchified_pixel_values (`torch.FloatTensor` of shape `(batch_size, num_patches, patch_size**2 * num_channels)`:
|
| 801 |
+
Patchified pixel values.
|
| 802 |
+
original_image_size (`Tuple[int, int]`, *optional*):
|
| 803 |
+
Original image size.
|
| 804 |
+
|
| 805 |
+
Returns:
|
| 806 |
+
`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`:
|
| 807 |
+
Pixel values.
|
| 808 |
+
"""
|
| 809 |
+
patch_size, num_channels = self.config.patch_size, self.config.num_channels
|
| 810 |
+
original_image_size = (
|
| 811 |
+
original_image_size
|
| 812 |
+
if original_image_size is not None
|
| 813 |
+
else (self.config.image_size, self.config.image_size)
|
| 814 |
+
)
|
| 815 |
+
original_height, original_width = original_image_size
|
| 816 |
+
num_patches_h = original_height // patch_size
|
| 817 |
+
num_patches_w = original_width // patch_size
|
| 818 |
+
# sanity check
|
| 819 |
+
if num_patches_h * num_patches_w != patchified_pixel_values.shape[1]:
|
| 820 |
+
raise ValueError(
|
| 821 |
+
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}"
|
| 822 |
+
)
|
| 823 |
+
|
| 824 |
+
# unpatchify
|
| 825 |
+
batch_size = patchified_pixel_values.shape[0]
|
| 826 |
+
patchified_pixel_values = patchified_pixel_values.reshape(
|
| 827 |
+
batch_size,
|
| 828 |
+
num_patches_h,
|
| 829 |
+
num_patches_w,
|
| 830 |
+
patch_size,
|
| 831 |
+
patch_size,
|
| 832 |
+
num_channels,
|
| 833 |
+
)
|
| 834 |
+
patchified_pixel_values = torch.einsum("nhwpqc->nchpwq", patchified_pixel_values)
|
| 835 |
+
pixel_values = patchified_pixel_values.reshape(
|
| 836 |
+
batch_size,
|
| 837 |
+
num_channels,
|
| 838 |
+
num_patches_h * patch_size,
|
| 839 |
+
num_patches_w * patch_size,
|
| 840 |
+
)
|
| 841 |
+
return pixel_values
|
| 842 |
+
|
| 843 |
+
def forward(
|
| 844 |
+
self,
|
| 845 |
+
hidden_states,
|
| 846 |
+
output_attentions=False,
|
| 847 |
+
output_hidden_states=False,
|
| 848 |
+
return_dict=True,
|
| 849 |
+
interpolate_pos_encoding: bool = False,
|
| 850 |
+
drop_cls_token: bool = False,
|
| 851 |
+
):
|
| 852 |
+
# embed tokens
|
| 853 |
+
x = self.decoder_embed(hidden_states)
|
| 854 |
+
#print(f"x.shape = {x.shape}")
|
| 855 |
+
if drop_cls_token:
|
| 856 |
+
x_ = x[:, 1:, :] # no cls token
|
| 857 |
+
x_ = self.interpolate_latent(x_)
|
| 858 |
+
else:
|
| 859 |
+
x_ = self.interpolate_latent(x) # interpolate the whole latent
|
| 860 |
+
cls_token = self.trainable_cls_token.expand(x_.shape[0], -1, -1)
|
| 861 |
+
x = torch.cat([cls_token, x_], dim=1)
|
| 862 |
+
|
| 863 |
+
# add pos embed
|
| 864 |
+
if interpolate_pos_encoding:
|
| 865 |
+
assert drop_cls_token, "interpolate_pos_encoding only works with drop_cls_token=True"
|
| 866 |
+
decoder_pos_embed = self.interpolate_pos_encoding(x)
|
| 867 |
+
else:
|
| 868 |
+
decoder_pos_embed = self.decoder_pos_embed
|
| 869 |
+
hidden_states = x + decoder_pos_embed
|
| 870 |
+
#print(f"hidden_states.shape = {hidden_states.shape}")
|
| 871 |
+
# apply Transformer layers (blocks)
|
| 872 |
+
all_hidden_states = () if output_hidden_states else None
|
| 873 |
+
all_self_attentions = () if output_attentions else None
|
| 874 |
+
for i, layer_module in enumerate(self.decoder_layers):
|
| 875 |
+
if output_hidden_states:
|
| 876 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 877 |
+
|
| 878 |
+
if self.gradient_checkpointing and self.training:
|
| 879 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 880 |
+
layer_module.__call__,
|
| 881 |
+
hidden_states,
|
| 882 |
+
None,
|
| 883 |
+
output_attentions,
|
| 884 |
+
)
|
| 885 |
+
else:
|
| 886 |
+
layer_outputs = layer_module(hidden_states, head_mask=None, output_attentions=output_attentions)
|
| 887 |
+
|
| 888 |
+
hidden_states = layer_outputs[0]
|
| 889 |
+
|
| 890 |
+
if output_attentions:
|
| 891 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 892 |
+
|
| 893 |
+
if output_hidden_states:
|
| 894 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 895 |
+
|
| 896 |
+
hidden_states = self.decoder_norm(hidden_states)
|
| 897 |
+
|
| 898 |
+
# predictor projection
|
| 899 |
+
logits = self.decoder_pred(hidden_states)
|
| 900 |
+
|
| 901 |
+
# remove cls token
|
| 902 |
+
logits = logits[:, 1:, :]
|
| 903 |
+
|
| 904 |
+
if not return_dict:
|
| 905 |
+
return tuple(v for v in [logits, all_hidden_states, all_self_attentions] if v is not None)
|
| 906 |
+
return ViTMAEDecoderOutput(
|
| 907 |
+
logits=logits,
|
| 908 |
+
hidden_states=all_hidden_states,
|
| 909 |
+
attentions=all_self_attentions,
|
| 910 |
+
)
|
| 911 |
+
|
| 912 |
+
import json
|
| 913 |
+
from math import sqrt
|
| 914 |
+
from pathlib import Path
|
| 915 |
+
from typing import Any, Dict, Optional
|
| 916 |
+
|
| 917 |
+
import torch
|
| 918 |
+
import torch.nn as nn
|
| 919 |
+
from timm.models.vision_transformer import Attention
|
| 920 |
+
from transformers import AutoConfig, AutoImageProcessor
|
| 921 |
+
|
| 922 |
+
try:
|
| 923 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 924 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 925 |
+
except Exception: # pragma: no cover
|
| 926 |
+
class ConfigMixin:
|
| 927 |
+
config_name = "config.json"
|
| 928 |
+
|
| 929 |
+
class ModelMixin(nn.Module):
|
| 930 |
+
pass
|
| 931 |
+
|
| 932 |
+
def register_to_config(init):
|
| 933 |
+
return init
|
| 934 |
+
|
| 935 |
+
|
| 936 |
+
_PIXEL_DECODER_DEFAULTS: Dict[str, Any] = {
|
| 937 |
+
"decoder_hidden_size": 1024,
|
| 938 |
+
"decoder_intermediate_size": 4096,
|
| 939 |
+
"decoder_num_attention_heads": 16,
|
| 940 |
+
"decoder_num_hidden_layers": 24,
|
| 941 |
+
"layer_norm_eps": 1e-12,
|
| 942 |
+
"num_channels": 3,
|
| 943 |
+
"hidden_act": "gelu",
|
| 944 |
+
"qkv_bias": True,
|
| 945 |
+
"hidden_dropout_prob": 0.0,
|
| 946 |
+
"attention_probs_dropout_prob": 0.0,
|
| 947 |
+
"initializer_range": 0.02,
|
| 948 |
+
}
|
| 949 |
+
|
| 950 |
+
|
| 951 |
+
def _resolve_local_asset_path(path: str, model_root: Optional[Path] = None) -> str:
|
| 952 |
+
candidate = Path(path)
|
| 953 |
+
if candidate.is_file():
|
| 954 |
+
return str(candidate)
|
| 955 |
+
search_roots = []
|
| 956 |
+
if model_root is not None:
|
| 957 |
+
search_roots.extend([model_root, model_root.parent])
|
| 958 |
+
for root in search_roots:
|
| 959 |
+
for probe in (root / candidate, root / candidate.name, root / "decoder_config" / "config.json"):
|
| 960 |
+
if probe.is_file():
|
| 961 |
+
return str(probe)
|
| 962 |
+
return path
|
| 963 |
+
|
| 964 |
+
|
| 965 |
+
def _build_pixel_decoder_config(
|
| 966 |
+
*,
|
| 967 |
+
encoder_hidden_size: int,
|
| 968 |
+
decoder_patch_size: int,
|
| 969 |
+
base_patches: int,
|
| 970 |
+
decoder_config_path: Optional[str] = None,
|
| 971 |
+
overrides: Optional[Dict[str, Any]] = None,
|
| 972 |
+
) -> ViTMAEConfig:
|
| 973 |
+
pixel_decoder = dict(_PIXEL_DECODER_DEFAULTS)
|
| 974 |
+
if decoder_config_path is not None:
|
| 975 |
+
resolved = _resolve_local_asset_path(decoder_config_path)
|
| 976 |
+
if Path(resolved).is_file():
|
| 977 |
+
with open(resolved, encoding="utf-8") as handle:
|
| 978 |
+
pixel_decoder.update(json.load(handle))
|
| 979 |
+
if overrides:
|
| 980 |
+
pixel_decoder.update({key: value for key, value in overrides.items() if value is not None})
|
| 981 |
+
|
| 982 |
+
return ViTMAEConfig(
|
| 983 |
+
hidden_size=encoder_hidden_size,
|
| 984 |
+
patch_size=decoder_patch_size,
|
| 985 |
+
image_size=int(decoder_patch_size * sqrt(base_patches)),
|
| 986 |
+
**pixel_decoder,
|
| 987 |
+
)
|
| 988 |
+
|
| 989 |
+
|
| 990 |
+
def _load_image_normalization(encoder_config_path: str) -> tuple[list[float], list[float]]:
|
| 991 |
+
try:
|
| 992 |
+
proc = AutoImageProcessor.from_pretrained(encoder_config_path, use_fast=True, local_files_only=True)
|
| 993 |
+
return proc.image_mean, proc.image_std
|
| 994 |
+
except Exception:
|
| 995 |
+
pass
|
| 996 |
+
try:
|
| 997 |
+
proc = AutoImageProcessor.from_pretrained(encoder_config_path, use_fast=True, local_files_only=False)
|
| 998 |
+
return proc.image_mean, proc.image_std
|
| 999 |
+
except Exception:
|
| 1000 |
+
if "siglip" in encoder_config_path.lower():
|
| 1001 |
+
return [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]
|
| 1002 |
+
return [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
|
| 1003 |
+
|
| 1004 |
+
|
| 1005 |
+
class PAEDecoder(ModelMixin, ConfigMixin):
|
| 1006 |
+
"""PAE decoder: latent decompressor + ViT-MAE pixel decoder."""
|
| 1007 |
+
|
| 1008 |
+
@register_to_config
|
| 1009 |
+
def __init__(
|
| 1010 |
+
self,
|
| 1011 |
+
encoder_hidden_size: int = 1024,
|
| 1012 |
+
encoder_num_heads: int = 16,
|
| 1013 |
+
encoder_input_size: int = 224,
|
| 1014 |
+
encoder_patch_size: int = 14,
|
| 1015 |
+
encoder_config_path: str = "facebook/dinov2-with-registers-large",
|
| 1016 |
+
latent_dim: int = 32,
|
| 1017 |
+
decoder_patch_size: int = 16,
|
| 1018 |
+
decoder_config_path: Optional[str] = None,
|
| 1019 |
+
decoder_hidden_size: int = 1024,
|
| 1020 |
+
decoder_intermediate_size: int = 4096,
|
| 1021 |
+
decoder_num_attention_heads: int = 16,
|
| 1022 |
+
decoder_num_hidden_layers: int = 24,
|
| 1023 |
+
layer_norm_eps: float = 1e-12,
|
| 1024 |
+
num_channels: int = 3,
|
| 1025 |
+
hidden_act: str = "gelu",
|
| 1026 |
+
qkv_bias: bool = True,
|
| 1027 |
+
hidden_dropout_prob: float = 0.0,
|
| 1028 |
+
attention_probs_dropout_prob: float = 0.0,
|
| 1029 |
+
initializer_range: float = 0.02,
|
| 1030 |
+
image_mean: Optional[list[float]] = None,
|
| 1031 |
+
image_std: Optional[list[float]] = None,
|
| 1032 |
+
latent_mean: Optional[list[float]] = None,
|
| 1033 |
+
latent_std: Optional[list[float]] = None,
|
| 1034 |
+
latent_multiplier: float = 1.0,
|
| 1035 |
+
**kwargs,
|
| 1036 |
+
) -> None:
|
| 1037 |
+
super().__init__()
|
| 1038 |
+
if image_mean is not None and image_std is not None:
|
| 1039 |
+
norm_mean, norm_std = image_mean, image_std
|
| 1040 |
+
else:
|
| 1041 |
+
norm_mean, norm_std = _load_image_normalization(encoder_config_path)
|
| 1042 |
+
self.register_buffer("encoder_mean", torch.tensor(norm_mean).view(1, 3, 1, 1), persistent=True)
|
| 1043 |
+
self.register_buffer("encoder_std", torch.tensor(norm_std).view(1, 3, 1, 1), persistent=True)
|
| 1044 |
+
|
| 1045 |
+
self.encoder_input_size = encoder_input_size
|
| 1046 |
+
self.encoder_patch_size = encoder_patch_size
|
| 1047 |
+
self.base_patches = (self.encoder_input_size // self.encoder_patch_size) ** 2
|
| 1048 |
+
self.latent_dim = latent_dim
|
| 1049 |
+
|
| 1050 |
+
self.latent_decompressor = nn.ModuleList(
|
| 1051 |
+
[
|
| 1052 |
+
nn.Conv2d(latent_dim, encoder_hidden_size, kernel_size=3, padding=1),
|
| 1053 |
+
Attention(dim=encoder_hidden_size, num_heads=encoder_num_heads),
|
| 1054 |
+
]
|
| 1055 |
+
)
|
| 1056 |
+
|
| 1057 |
+
pixel_decoder_config = _build_pixel_decoder_config(
|
| 1058 |
+
encoder_hidden_size=encoder_hidden_size,
|
| 1059 |
+
decoder_patch_size=decoder_patch_size,
|
| 1060 |
+
base_patches=self.base_patches,
|
| 1061 |
+
decoder_config_path=decoder_config_path,
|
| 1062 |
+
overrides={
|
| 1063 |
+
"decoder_hidden_size": decoder_hidden_size,
|
| 1064 |
+
"decoder_intermediate_size": decoder_intermediate_size,
|
| 1065 |
+
"decoder_num_attention_heads": decoder_num_attention_heads,
|
| 1066 |
+
"decoder_num_hidden_layers": decoder_num_hidden_layers,
|
| 1067 |
+
"layer_norm_eps": layer_norm_eps,
|
| 1068 |
+
"num_channels": num_channels,
|
| 1069 |
+
"hidden_act": hidden_act,
|
| 1070 |
+
"qkv_bias": qkv_bias,
|
| 1071 |
+
"hidden_dropout_prob": hidden_dropout_prob,
|
| 1072 |
+
"attention_probs_dropout_prob": attention_probs_dropout_prob,
|
| 1073 |
+
"initializer_range": initializer_range,
|
| 1074 |
+
},
|
| 1075 |
+
)
|
| 1076 |
+
self.decoder = GeneralDecoder(pixel_decoder_config, num_patches=self.base_patches)
|
| 1077 |
+
|
| 1078 |
+
@classmethod
|
| 1079 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 1080 |
+
model_root = Path(pretrained_model_name_or_path)
|
| 1081 |
+
config_file = model_root / cls.config_name
|
| 1082 |
+
if config_file.is_file():
|
| 1083 |
+
with open(config_file, encoding="utf-8") as handle:
|
| 1084 |
+
config = json.load(handle)
|
| 1085 |
+
decoder_config_path = config.get("decoder_config_path")
|
| 1086 |
+
if decoder_config_path is not None:
|
| 1087 |
+
resolved = _resolve_local_asset_path(decoder_config_path, model_root=model_root)
|
| 1088 |
+
if resolved != decoder_config_path:
|
| 1089 |
+
kwargs.setdefault("decoder_config_path", resolved)
|
| 1090 |
+
return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
|
| 1091 |
+
|
| 1092 |
+
def decode(self, latents: torch.Tensor) -> torch.Tensor:
|
| 1093 |
+
hidden_states = self.latent_decompressor[0](latents)
|
| 1094 |
+
batch_size, channels, height, width = hidden_states.shape
|
| 1095 |
+
num_tokens = height * width
|
| 1096 |
+
hidden_states = hidden_states.view(batch_size, channels, num_tokens).transpose(1, 2)
|
| 1097 |
+
hidden_states = self.latent_decompressor[1](hidden_states)
|
| 1098 |
+
|
| 1099 |
+
output = self.decoder(hidden_states, drop_cls_token=False).logits
|
| 1100 |
+
x_rec = self.decoder.unpatchify(output)
|
| 1101 |
+
x_rec = x_rec * self.encoder_std.to(x_rec.device) + self.encoder_mean.to(x_rec.device)
|
| 1102 |
+
return x_rec
|
| 1103 |
+
|
| 1104 |
+
def forward(self, latents: torch.Tensor) -> torch.Tensor:
|
| 1105 |
+
return self.decode(latents)
|
pae-mae-large-d32/decoder/diffusion_pytorch_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9f80444f2ef4c3f684622bf7fde19c7c0b50a60c7c986de85149398c416b8148
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": [
|
| 3 |
+
"pipeline",
|
| 4 |
+
"PAEPipeline"
|
| 5 |
+
],
|
| 6 |
+
"_diffusers_version": "0.31.0",
|
| 7 |
+
"decoder": [
|
| 8 |
+
"decoder_pae",
|
| 9 |
+
"PAEDecoder"
|
| 10 |
+
],
|
| 11 |
+
"id2label": {
|
| 12 |
+
"0": "tench, Tinca tinca",
|
| 13 |
+
"1": "goldfish, Carassius auratus",
|
| 14 |
+
"2": "great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias",
|
| 15 |
+
"3": "tiger shark, Galeocerdo cuvieri",
|
| 16 |
+
"4": "hammerhead, hammerhead shark",
|
| 17 |
+
"5": "electric ray, crampfish, numbfish, torpedo",
|
| 18 |
+
"6": "stingray",
|
| 19 |
+
"7": "cock",
|
| 20 |
+
"8": "hen",
|
| 21 |
+
"9": "ostrich, Struthio camelus",
|
| 22 |
+
"10": "brambling, Fringilla montifringilla",
|
| 23 |
+
"11": "goldfinch, Carduelis carduelis",
|
| 24 |
+
"12": "house finch, linnet, Carpodacus mexicanus",
|
| 25 |
+
"13": "junco, snowbird",
|
| 26 |
+
"14": "indigo bunting, indigo finch, indigo bird, Passerina cyanea",
|
| 27 |
+
"15": "robin, American robin, Turdus migratorius",
|
| 28 |
+
"16": "bulbul",
|
| 29 |
+
"17": "jay",
|
| 30 |
+
"18": "magpie",
|
| 31 |
+
"19": "chickadee",
|
| 32 |
+
"20": "water ouzel, dipper",
|
| 33 |
+
"21": "kite",
|
| 34 |
+
"22": "bald eagle, American eagle, Haliaeetus leucocephalus",
|
| 35 |
+
"23": "vulture",
|
| 36 |
+
"24": "great grey owl, great gray owl, Strix nebulosa",
|
| 37 |
+
"25": "European fire salamander, Salamandra salamandra",
|
| 38 |
+
"26": "common newt, Triturus vulgaris",
|
| 39 |
+
"27": "eft",
|
| 40 |
+
"28": "spotted salamander, Ambystoma maculatum",
|
| 41 |
+
"29": "axolotl, mud puppy, Ambystoma mexicanum",
|
| 42 |
+
"30": "bullfrog, Rana catesbeiana",
|
| 43 |
+
"31": "tree frog, tree-frog",
|
| 44 |
+
"32": "tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui",
|
| 45 |
+
"33": "loggerhead, loggerhead turtle, Caretta caretta",
|
| 46 |
+
"34": "leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea",
|
| 47 |
+
"35": "mud turtle",
|
| 48 |
+
"36": "terrapin",
|
| 49 |
+
"37": "box turtle, box tortoise",
|
| 50 |
+
"38": "banded gecko",
|
| 51 |
+
"39": "common iguana, iguana, Iguana iguana",
|
| 52 |
+
"40": "American chameleon, anole, Anolis carolinensis",
|
| 53 |
+
"41": "whiptail, whiptail lizard",
|
| 54 |
+
"42": "agama",
|
| 55 |
+
"43": "frilled lizard, Chlamydosaurus kingi",
|
| 56 |
+
"44": "alligator lizard",
|
| 57 |
+
"45": "Gila monster, Heloderma suspectum",
|
| 58 |
+
"46": "green lizard, Lacerta viridis",
|
| 59 |
+
"47": "African chameleon, Chamaeleo chamaeleon",
|
| 60 |
+
"48": "Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis",
|
| 61 |
+
"49": "African crocodile, Nile crocodile, Crocodylus niloticus",
|
| 62 |
+
"50": "American alligator, Alligator mississipiensis",
|
| 63 |
+
"51": "triceratops",
|
| 64 |
+
"52": "thunder snake, worm snake, Carphophis amoenus",
|
| 65 |
+
"53": "ringneck snake, ring-necked snake, ring snake",
|
| 66 |
+
"54": "hognose snake, puff adder, sand viper",
|
| 67 |
+
"55": "green snake, grass snake",
|
| 68 |
+
"56": "king snake, kingsnake",
|
| 69 |
+
"57": "garter snake, grass snake",
|
| 70 |
+
"58": "water snake",
|
| 71 |
+
"59": "vine snake",
|
| 72 |
+
"60": "night snake, Hypsiglena torquata",
|
| 73 |
+
"61": "boa constrictor, Constrictor constrictor",
|
| 74 |
+
"62": "rock python, rock snake, Python sebae",
|
| 75 |
+
"63": "Indian cobra, Naja naja",
|
| 76 |
+
"64": "green mamba",
|
| 77 |
+
"65": "sea snake",
|
| 78 |
+
"66": "horned viper, cerastes, sand viper, horned asp, Cerastes cornutus",
|
| 79 |
+
"67": "diamondback, diamondback rattlesnake, Crotalus adamanteus",
|
| 80 |
+
"68": "sidewinder, horned rattlesnake, Crotalus cerastes",
|
| 81 |
+
"69": "trilobite",
|
| 82 |
+
"70": "harvestman, daddy longlegs, Phalangium opilio",
|
| 83 |
+
"71": "scorpion",
|
| 84 |
+
"72": "black and gold garden spider, Argiope aurantia",
|
| 85 |
+
"73": "barn spider, Araneus cavaticus",
|
| 86 |
+
"74": "garden spider, Aranea diademata",
|
| 87 |
+
"75": "black widow, Latrodectus mactans",
|
| 88 |
+
"76": "tarantula",
|
| 89 |
+
"77": "wolf spider, hunting spider",
|
| 90 |
+
"78": "tick",
|
| 91 |
+
"79": "centipede",
|
| 92 |
+
"80": "black grouse",
|
| 93 |
+
"81": "ptarmigan",
|
| 94 |
+
"82": "ruffed grouse, partridge, Bonasa umbellus",
|
| 95 |
+
"83": "prairie chicken, prairie grouse, prairie fowl",
|
| 96 |
+
"84": "peacock",
|
| 97 |
+
"85": "quail",
|
| 98 |
+
"86": "partridge",
|
| 99 |
+
"87": "African grey, African gray, Psittacus erithacus",
|
| 100 |
+
"88": "macaw",
|
| 101 |
+
"89": "sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita",
|
| 102 |
+
"90": "lorikeet",
|
| 103 |
+
"91": "coucal",
|
| 104 |
+
"92": "bee eater",
|
| 105 |
+
"93": "hornbill",
|
| 106 |
+
"94": "hummingbird",
|
| 107 |
+
"95": "jacamar",
|
| 108 |
+
"96": "toucan",
|
| 109 |
+
"97": "drake",
|
| 110 |
+
"98": "red-breasted merganser, Mergus serrator",
|
| 111 |
+
"99": "goose",
|
| 112 |
+
"100": "black swan, Cygnus atratus",
|
| 113 |
+
"101": "tusker",
|
| 114 |
+
"102": "echidna, spiny anteater, anteater",
|
| 115 |
+
"103": "platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus",
|
| 116 |
+
"104": "wallaby, brush kangaroo",
|
| 117 |
+
"105": "koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus",
|
| 118 |
+
"106": "wombat",
|
| 119 |
+
"107": "jellyfish",
|
| 120 |
+
"108": "sea anemone, anemone",
|
| 121 |
+
"109": "brain coral",
|
| 122 |
+
"110": "flatworm, platyhelminth",
|
| 123 |
+
"111": "nematode, nematode worm, roundworm",
|
| 124 |
+
"112": "conch",
|
| 125 |
+
"113": "snail",
|
| 126 |
+
"114": "slug",
|
| 127 |
+
"115": "sea slug, nudibranch",
|
| 128 |
+
"116": "chiton, coat-of-mail shell, sea cradle, polyplacophore",
|
| 129 |
+
"117": "chambered nautilus, pearly nautilus, nautilus",
|
| 130 |
+
"118": "Dungeness crab, Cancer magister",
|
| 131 |
+
"119": "rock crab, Cancer irroratus",
|
| 132 |
+
"120": "fiddler crab",
|
| 133 |
+
"121": "king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica",
|
| 134 |
+
"122": "American lobster, Northern lobster, Maine lobster, Homarus americanus",
|
| 135 |
+
"123": "spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish",
|
| 136 |
+
"124": "crayfish, crawfish, crawdad, crawdaddy",
|
| 137 |
+
"125": "hermit crab",
|
| 138 |
+
"126": "isopod",
|
| 139 |
+
"127": "white stork, Ciconia ciconia",
|
| 140 |
+
"128": "black stork, Ciconia nigra",
|
| 141 |
+
"129": "spoonbill",
|
| 142 |
+
"130": "flamingo",
|
| 143 |
+
"131": "little blue heron, Egretta caerulea",
|
| 144 |
+
"132": "American egret, great white heron, Egretta albus",
|
| 145 |
+
"133": "bittern",
|
| 146 |
+
"134": "crane",
|
| 147 |
+
"135": "limpkin, Aramus pictus",
|
| 148 |
+
"136": "European gallinule, Porphyrio porphyrio",
|
| 149 |
+
"137": "American coot, marsh hen, mud hen, water hen, Fulica americana",
|
| 150 |
+
"138": "bustard",
|
| 151 |
+
"139": "ruddy turnstone, Arenaria interpres",
|
| 152 |
+
"140": "red-backed sandpiper, dunlin, Erolia alpina",
|
| 153 |
+
"141": "redshank, Tringa totanus",
|
| 154 |
+
"142": "dowitcher",
|
| 155 |
+
"143": "oystercatcher, oyster catcher",
|
| 156 |
+
"144": "pelican",
|
| 157 |
+
"145": "king penguin, Aptenodytes patagonica",
|
| 158 |
+
"146": "albatross, mollymawk",
|
| 159 |
+
"147": "grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus",
|
| 160 |
+
"148": "killer whale, killer, orca, grampus, sea wolf, Orcinus orca",
|
| 161 |
+
"149": "dugong, Dugong dugon",
|
| 162 |
+
"150": "sea lion",
|
| 163 |
+
"151": "Chihuahua",
|
| 164 |
+
"152": "Japanese spaniel",
|
| 165 |
+
"153": "Maltese dog, Maltese terrier, Maltese",
|
| 166 |
+
"154": "Pekinese, Pekingese, Peke",
|
| 167 |
+
"155": "Shih-Tzu",
|
| 168 |
+
"156": "Blenheim spaniel",
|
| 169 |
+
"157": "papillon",
|
| 170 |
+
"158": "toy terrier",
|
| 171 |
+
"159": "Rhodesian ridgeback",
|
| 172 |
+
"160": "Afghan hound, Afghan",
|
| 173 |
+
"161": "basset, basset hound",
|
| 174 |
+
"162": "beagle",
|
| 175 |
+
"163": "bloodhound, sleuthhound",
|
| 176 |
+
"164": "bluetick",
|
| 177 |
+
"165": "black-and-tan coonhound",
|
| 178 |
+
"166": "Walker hound, Walker foxhound",
|
| 179 |
+
"167": "English foxhound",
|
| 180 |
+
"168": "redbone",
|
| 181 |
+
"169": "borzoi, Russian wolfhound",
|
| 182 |
+
"170": "Irish wolfhound",
|
| 183 |
+
"171": "Italian greyhound",
|
| 184 |
+
"172": "whippet",
|
| 185 |
+
"173": "Ibizan hound, Ibizan Podenco",
|
| 186 |
+
"174": "Norwegian elkhound, elkhound",
|
| 187 |
+
"175": "otterhound, otter hound",
|
| 188 |
+
"176": "Saluki, gazelle hound",
|
| 189 |
+
"177": "Scottish deerhound, deerhound",
|
| 190 |
+
"178": "Weimaraner",
|
| 191 |
+
"179": "Staffordshire bullterrier, Staffordshire bull terrier",
|
| 192 |
+
"180": "American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier",
|
| 193 |
+
"181": "Bedlington terrier",
|
| 194 |
+
"182": "Border terrier",
|
| 195 |
+
"183": "Kerry blue terrier",
|
| 196 |
+
"184": "Irish terrier",
|
| 197 |
+
"185": "Norfolk terrier",
|
| 198 |
+
"186": "Norwich terrier",
|
| 199 |
+
"187": "Yorkshire terrier",
|
| 200 |
+
"188": "wire-haired fox terrier",
|
| 201 |
+
"189": "Lakeland terrier",
|
| 202 |
+
"190": "Sealyham terrier, Sealyham",
|
| 203 |
+
"191": "Airedale, Airedale terrier",
|
| 204 |
+
"192": "cairn, cairn terrier",
|
| 205 |
+
"193": "Australian terrier",
|
| 206 |
+
"194": "Dandie Dinmont, Dandie Dinmont terrier",
|
| 207 |
+
"195": "Boston bull, Boston terrier",
|
| 208 |
+
"196": "miniature schnauzer",
|
| 209 |
+
"197": "giant schnauzer",
|
| 210 |
+
"198": "standard schnauzer",
|
| 211 |
+
"199": "Scotch terrier, Scottish terrier, Scottie",
|
| 212 |
+
"200": "Tibetan terrier, chrysanthemum dog",
|
| 213 |
+
"201": "silky terrier, Sydney silky",
|
| 214 |
+
"202": "soft-coated wheaten terrier",
|
| 215 |
+
"203": "West Highland white terrier",
|
| 216 |
+
"204": "Lhasa, Lhasa apso",
|
| 217 |
+
"205": "flat-coated retriever",
|
| 218 |
+
"206": "curly-coated retriever",
|
| 219 |
+
"207": "golden retriever",
|
| 220 |
+
"208": "Labrador retriever",
|
| 221 |
+
"209": "Chesapeake Bay retriever",
|
| 222 |
+
"210": "German short-haired pointer",
|
| 223 |
+
"211": "vizsla, Hungarian pointer",
|
| 224 |
+
"212": "English setter",
|
| 225 |
+
"213": "Irish setter, red setter",
|
| 226 |
+
"214": "Gordon setter",
|
| 227 |
+
"215": "Brittany spaniel",
|
| 228 |
+
"216": "clumber, clumber spaniel",
|
| 229 |
+
"217": "English springer, English springer spaniel",
|
| 230 |
+
"218": "Welsh springer spaniel",
|
| 231 |
+
"219": "cocker spaniel, English cocker spaniel, cocker",
|
| 232 |
+
"220": "Sussex spaniel",
|
| 233 |
+
"221": "Irish water spaniel",
|
| 234 |
+
"222": "kuvasz",
|
| 235 |
+
"223": "schipperke",
|
| 236 |
+
"224": "groenendael",
|
| 237 |
+
"225": "malinois",
|
| 238 |
+
"226": "briard",
|
| 239 |
+
"227": "kelpie",
|
| 240 |
+
"228": "komondor",
|
| 241 |
+
"229": "Old English sheepdog, bobtail",
|
| 242 |
+
"230": "Shetland sheepdog, Shetland sheep dog, Shetland",
|
| 243 |
+
"231": "collie",
|
| 244 |
+
"232": "Border collie",
|
| 245 |
+
"233": "Bouvier des Flandres, Bouviers des Flandres",
|
| 246 |
+
"234": "Rottweiler",
|
| 247 |
+
"235": "German shepherd, German shepherd dog, German police dog, alsatian",
|
| 248 |
+
"236": "Doberman, Doberman pinscher",
|
| 249 |
+
"237": "miniature pinscher",
|
| 250 |
+
"238": "Greater Swiss Mountain dog",
|
| 251 |
+
"239": "Bernese mountain dog",
|
| 252 |
+
"240": "Appenzeller",
|
| 253 |
+
"241": "EntleBucher",
|
| 254 |
+
"242": "boxer",
|
| 255 |
+
"243": "bull mastiff",
|
| 256 |
+
"244": "Tibetan mastiff",
|
| 257 |
+
"245": "French bulldog",
|
| 258 |
+
"246": "Great Dane",
|
| 259 |
+
"247": "Saint Bernard, St Bernard",
|
| 260 |
+
"248": "Eskimo dog, husky",
|
| 261 |
+
"249": "malamute, malemute, Alaskan malamute",
|
| 262 |
+
"250": "Siberian husky",
|
| 263 |
+
"251": "dalmatian, coach dog, carriage dog",
|
| 264 |
+
"252": "affenpinscher, monkey pinscher, monkey dog",
|
| 265 |
+
"253": "basenji",
|
| 266 |
+
"254": "pug, pug-dog",
|
| 267 |
+
"255": "Leonberg",
|
| 268 |
+
"256": "Newfoundland, Newfoundland dog",
|
| 269 |
+
"257": "Great Pyrenees",
|
| 270 |
+
"258": "Samoyed, Samoyede",
|
| 271 |
+
"259": "Pomeranian",
|
| 272 |
+
"260": "chow, chow chow",
|
| 273 |
+
"261": "keeshond",
|
| 274 |
+
"262": "Brabancon griffon",
|
| 275 |
+
"263": "Pembroke, Pembroke Welsh corgi",
|
| 276 |
+
"264": "Cardigan, Cardigan Welsh corgi",
|
| 277 |
+
"265": "toy poodle",
|
| 278 |
+
"266": "miniature poodle",
|
| 279 |
+
"267": "standard poodle",
|
| 280 |
+
"268": "Mexican hairless",
|
| 281 |
+
"269": "timber wolf, grey wolf, gray wolf, Canis lupus",
|
| 282 |
+
"270": "white wolf, Arctic wolf, Canis lupus tundrarum",
|
| 283 |
+
"271": "red wolf, maned wolf, Canis rufus, Canis niger",
|
| 284 |
+
"272": "coyote, prairie wolf, brush wolf, Canis latrans",
|
| 285 |
+
"273": "dingo, warrigal, warragal, Canis dingo",
|
| 286 |
+
"274": "dhole, Cuon alpinus",
|
| 287 |
+
"275": "African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus",
|
| 288 |
+
"276": "hyena, hyaena",
|
| 289 |
+
"277": "red fox, Vulpes vulpes",
|
| 290 |
+
"278": "kit fox, Vulpes macrotis",
|
| 291 |
+
"279": "Arctic fox, white fox, Alopex lagopus",
|
| 292 |
+
"280": "grey fox, gray fox, Urocyon cinereoargenteus",
|
| 293 |
+
"281": "tabby, tabby cat",
|
| 294 |
+
"282": "tiger cat",
|
| 295 |
+
"283": "Persian cat",
|
| 296 |
+
"284": "Siamese cat, Siamese",
|
| 297 |
+
"285": "Egyptian cat",
|
| 298 |
+
"286": "cougar, puma, catamount, mountain lion, painter, panther, Felis concolor",
|
| 299 |
+
"287": "lynx, catamount",
|
| 300 |
+
"288": "leopard, Panthera pardus",
|
| 301 |
+
"289": "snow leopard, ounce, Panthera uncia",
|
| 302 |
+
"290": "jaguar, panther, Panthera onca, Felis onca",
|
| 303 |
+
"291": "lion, king of beasts, Panthera leo",
|
| 304 |
+
"292": "tiger, Panthera tigris",
|
| 305 |
+
"293": "cheetah, chetah, Acinonyx jubatus",
|
| 306 |
+
"294": "brown bear, bruin, Ursus arctos",
|
| 307 |
+
"295": "American black bear, black bear, Ursus americanus, Euarctos americanus",
|
| 308 |
+
"296": "ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus",
|
| 309 |
+
"297": "sloth bear, Melursus ursinus, Ursus ursinus",
|
| 310 |
+
"298": "mongoose",
|
| 311 |
+
"299": "meerkat, mierkat",
|
| 312 |
+
"300": "tiger beetle",
|
| 313 |
+
"301": "ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle",
|
| 314 |
+
"302": "ground beetle, carabid beetle",
|
| 315 |
+
"303": "long-horned beetle, longicorn, longicorn beetle",
|
| 316 |
+
"304": "leaf beetle, chrysomelid",
|
| 317 |
+
"305": "dung beetle",
|
| 318 |
+
"306": "rhinoceros beetle",
|
| 319 |
+
"307": "weevil",
|
| 320 |
+
"308": "fly",
|
| 321 |
+
"309": "bee",
|
| 322 |
+
"310": "ant, emmet, pismire",
|
| 323 |
+
"311": "grasshopper, hopper",
|
| 324 |
+
"312": "cricket",
|
| 325 |
+
"313": "walking stick, walkingstick, stick insect",
|
| 326 |
+
"314": "cockroach, roach",
|
| 327 |
+
"315": "mantis, mantid",
|
| 328 |
+
"316": "cicada, cicala",
|
| 329 |
+
"317": "leafhopper",
|
| 330 |
+
"318": "lacewing, lacewing fly",
|
| 331 |
+
"319": "dragonfly, darning needle, devils darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk",
|
| 332 |
+
"320": "damselfly",
|
| 333 |
+
"321": "admiral",
|
| 334 |
+
"322": "ringlet, ringlet butterfly",
|
| 335 |
+
"323": "monarch, monarch butterfly, milkweed butterfly, Danaus plexippus",
|
| 336 |
+
"324": "cabbage butterfly",
|
| 337 |
+
"325": "sulphur butterfly, sulfur butterfly",
|
| 338 |
+
"326": "lycaenid, lycaenid butterfly",
|
| 339 |
+
"327": "starfish, sea star",
|
| 340 |
+
"328": "sea urchin",
|
| 341 |
+
"329": "sea cucumber, holothurian",
|
| 342 |
+
"330": "wood rabbit, cottontail, cottontail rabbit",
|
| 343 |
+
"331": "hare",
|
| 344 |
+
"332": "Angora, Angora rabbit",
|
| 345 |
+
"333": "hamster",
|
| 346 |
+
"334": "porcupine, hedgehog",
|
| 347 |
+
"335": "fox squirrel, eastern fox squirrel, Sciurus niger",
|
| 348 |
+
"336": "marmot",
|
| 349 |
+
"337": "beaver",
|
| 350 |
+
"338": "guinea pig, Cavia cobaya",
|
| 351 |
+
"339": "sorrel",
|
| 352 |
+
"340": "zebra",
|
| 353 |
+
"341": "hog, pig, grunter, squealer, Sus scrofa",
|
| 354 |
+
"342": "wild boar, boar, Sus scrofa",
|
| 355 |
+
"343": "warthog",
|
| 356 |
+
"344": "hippopotamus, hippo, river horse, Hippopotamus amphibius",
|
| 357 |
+
"345": "ox",
|
| 358 |
+
"346": "water buffalo, water ox, Asiatic buffalo, Bubalus bubalis",
|
| 359 |
+
"347": "bison",
|
| 360 |
+
"348": "ram, tup",
|
| 361 |
+
"349": "bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis",
|
| 362 |
+
"350": "ibex, Capra ibex",
|
| 363 |
+
"351": "hartebeest",
|
| 364 |
+
"352": "impala, Aepyceros melampus",
|
| 365 |
+
"353": "gazelle",
|
| 366 |
+
"354": "Arabian camel, dromedary, Camelus dromedarius",
|
| 367 |
+
"355": "llama",
|
| 368 |
+
"356": "weasel",
|
| 369 |
+
"357": "mink",
|
| 370 |
+
"358": "polecat, fitch, foulmart, foumart, Mustela putorius",
|
| 371 |
+
"359": "black-footed ferret, ferret, Mustela nigripes",
|
| 372 |
+
"360": "otter",
|
| 373 |
+
"361": "skunk, polecat, wood pussy",
|
| 374 |
+
"362": "badger",
|
| 375 |
+
"363": "armadillo",
|
| 376 |
+
"364": "three-toed sloth, ai, Bradypus tridactylus",
|
| 377 |
+
"365": "orangutan, orang, orangutang, Pongo pygmaeus",
|
| 378 |
+
"366": "gorilla, Gorilla gorilla",
|
| 379 |
+
"367": "chimpanzee, chimp, Pan troglodytes",
|
| 380 |
+
"368": "gibbon, Hylobates lar",
|
| 381 |
+
"369": "siamang, Hylobates syndactylus, Symphalangus syndactylus",
|
| 382 |
+
"370": "guenon, guenon monkey",
|
| 383 |
+
"371": "patas, hussar monkey, Erythrocebus patas",
|
| 384 |
+
"372": "baboon",
|
| 385 |
+
"373": "macaque",
|
| 386 |
+
"374": "langur",
|
| 387 |
+
"375": "colobus, colobus monkey",
|
| 388 |
+
"376": "proboscis monkey, Nasalis larvatus",
|
| 389 |
+
"377": "marmoset",
|
| 390 |
+
"378": "capuchin, ringtail, Cebus capucinus",
|
| 391 |
+
"379": "howler monkey, howler",
|
| 392 |
+
"380": "titi, titi monkey",
|
| 393 |
+
"381": "spider monkey, Ateles geoffroyi",
|
| 394 |
+
"382": "squirrel monkey, Saimiri sciureus",
|
| 395 |
+
"383": "Madagascar cat, ring-tailed lemur, Lemur catta",
|
| 396 |
+
"384": "indri, indris, Indri indri, Indri brevicaudatus",
|
| 397 |
+
"385": "Indian elephant, Elephas maximus",
|
| 398 |
+
"386": "African elephant, Loxodonta africana",
|
| 399 |
+
"387": "lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens",
|
| 400 |
+
"388": "giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca",
|
| 401 |
+
"389": "barracouta, snoek",
|
| 402 |
+
"390": "eel",
|
| 403 |
+
"391": "coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch",
|
| 404 |
+
"392": "rock beauty, Holocanthus tricolor",
|
| 405 |
+
"393": "anemone fish",
|
| 406 |
+
"394": "sturgeon",
|
| 407 |
+
"395": "gar, garfish, garpike, billfish, Lepisosteus osseus",
|
| 408 |
+
"396": "lionfish",
|
| 409 |
+
"397": "puffer, pufferfish, blowfish, globefish",
|
| 410 |
+
"398": "abacus",
|
| 411 |
+
"399": "abaya",
|
| 412 |
+
"400": "academic gown, academic robe, judge robe",
|
| 413 |
+
"401": "accordion, piano accordion, squeeze box",
|
| 414 |
+
"402": "acoustic guitar",
|
| 415 |
+
"403": "aircraft carrier, carrier, flattop, attack aircraft carrier",
|
| 416 |
+
"404": "airliner",
|
| 417 |
+
"405": "airship, dirigible",
|
| 418 |
+
"406": "altar",
|
| 419 |
+
"407": "ambulance",
|
| 420 |
+
"408": "amphibian, amphibious vehicle",
|
| 421 |
+
"409": "analog clock",
|
| 422 |
+
"410": "apiary, bee house",
|
| 423 |
+
"411": "apron",
|
| 424 |
+
"412": "ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin",
|
| 425 |
+
"413": "assault rifle, assault gun",
|
| 426 |
+
"414": "backpack, back pack, knapsack, packsack, rucksack, haversack",
|
| 427 |
+
"415": "bakery, bakeshop, bakehouse",
|
| 428 |
+
"416": "balance beam, beam",
|
| 429 |
+
"417": "balloon",
|
| 430 |
+
"418": "ballpoint, ballpoint pen, ballpen, Biro",
|
| 431 |
+
"419": "Band Aid",
|
| 432 |
+
"420": "banjo",
|
| 433 |
+
"421": "bannister, banister, balustrade, balusters, handrail",
|
| 434 |
+
"422": "barbell",
|
| 435 |
+
"423": "barber chair",
|
| 436 |
+
"424": "barbershop",
|
| 437 |
+
"425": "barn",
|
| 438 |
+
"426": "barometer",
|
| 439 |
+
"427": "barrel, cask",
|
| 440 |
+
"428": "barrow, garden cart, lawn cart, wheelbarrow",
|
| 441 |
+
"429": "baseball",
|
| 442 |
+
"430": "basketball",
|
| 443 |
+
"431": "bassinet",
|
| 444 |
+
"432": "bassoon",
|
| 445 |
+
"433": "bathing cap, swimming cap",
|
| 446 |
+
"434": "bath towel",
|
| 447 |
+
"435": "bathtub, bathing tub, bath, tub",
|
| 448 |
+
"436": "beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon",
|
| 449 |
+
"437": "beacon, lighthouse, beacon light, pharos",
|
| 450 |
+
"438": "beaker",
|
| 451 |
+
"439": "bearskin, busby, shako",
|
| 452 |
+
"440": "beer bottle",
|
| 453 |
+
"441": "beer glass",
|
| 454 |
+
"442": "bell cote, bell cot",
|
| 455 |
+
"443": "bib",
|
| 456 |
+
"444": "bicycle-built-for-two, tandem bicycle, tandem",
|
| 457 |
+
"445": "bikini, two-piece",
|
| 458 |
+
"446": "binder, ring-binder",
|
| 459 |
+
"447": "binoculars, field glasses, opera glasses",
|
| 460 |
+
"448": "birdhouse",
|
| 461 |
+
"449": "boathouse",
|
| 462 |
+
"450": "bobsled, bobsleigh, bob",
|
| 463 |
+
"451": "bolo tie, bolo, bola tie, bola",
|
| 464 |
+
"452": "bonnet, poke bonnet",
|
| 465 |
+
"453": "bookcase",
|
| 466 |
+
"454": "bookshop, bookstore, bookstall",
|
| 467 |
+
"455": "bottlecap",
|
| 468 |
+
"456": "bow",
|
| 469 |
+
"457": "bow tie, bow-tie, bowtie",
|
| 470 |
+
"458": "brass, memorial tablet, plaque",
|
| 471 |
+
"459": "brassiere, bra, bandeau",
|
| 472 |
+
"460": "breakwater, groin, groyne, mole, bulwark, seawall, jetty",
|
| 473 |
+
"461": "breastplate, aegis, egis",
|
| 474 |
+
"462": "broom",
|
| 475 |
+
"463": "bucket, pail",
|
| 476 |
+
"464": "buckle",
|
| 477 |
+
"465": "bulletproof vest",
|
| 478 |
+
"466": "bullet train, bullet",
|
| 479 |
+
"467": "butcher shop, meat market",
|
| 480 |
+
"468": "cab, hack, taxi, taxicab",
|
| 481 |
+
"469": "caldron, cauldron",
|
| 482 |
+
"470": "candle, taper, wax light",
|
| 483 |
+
"471": "cannon",
|
| 484 |
+
"472": "canoe",
|
| 485 |
+
"473": "can opener, tin opener",
|
| 486 |
+
"474": "cardigan",
|
| 487 |
+
"475": "car mirror",
|
| 488 |
+
"476": "carousel, carrousel, merry-go-round, roundabout, whirligig",
|
| 489 |
+
"477": "carpenters kit, tool kit",
|
| 490 |
+
"478": "carton",
|
| 491 |
+
"479": "car wheel",
|
| 492 |
+
"480": "cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM",
|
| 493 |
+
"481": "cassette",
|
| 494 |
+
"482": "cassette player",
|
| 495 |
+
"483": "castle",
|
| 496 |
+
"484": "catamaran",
|
| 497 |
+
"485": "CD player",
|
| 498 |
+
"486": "cello, violoncello",
|
| 499 |
+
"487": "cellular telephone, cellular phone, cellphone, cell, mobile phone",
|
| 500 |
+
"488": "chain",
|
| 501 |
+
"489": "chainlink fence",
|
| 502 |
+
"490": "chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour",
|
| 503 |
+
"491": "chain saw, chainsaw",
|
| 504 |
+
"492": "chest",
|
| 505 |
+
"493": "chiffonier, commode",
|
| 506 |
+
"494": "chime, bell, gong",
|
| 507 |
+
"495": "china cabinet, china closet",
|
| 508 |
+
"496": "Christmas stocking",
|
| 509 |
+
"497": "church, church building",
|
| 510 |
+
"498": "cinema, movie theater, movie theatre, movie house, picture palace",
|
| 511 |
+
"499": "cleaver, meat cleaver, chopper",
|
| 512 |
+
"500": "cliff dwelling",
|
| 513 |
+
"501": "cloak",
|
| 514 |
+
"502": "clog, geta, patten, sabot",
|
| 515 |
+
"503": "cocktail shaker",
|
| 516 |
+
"504": "coffee mug",
|
| 517 |
+
"505": "coffeepot",
|
| 518 |
+
"506": "coil, spiral, volute, whorl, helix",
|
| 519 |
+
"507": "combination lock",
|
| 520 |
+
"508": "computer keyboard, keypad",
|
| 521 |
+
"509": "confectionery, confectionary, candy store",
|
| 522 |
+
"510": "container ship, containership, container vessel",
|
| 523 |
+
"511": "convertible",
|
| 524 |
+
"512": "corkscrew, bottle screw",
|
| 525 |
+
"513": "cornet, horn, trumpet, trump",
|
| 526 |
+
"514": "cowboy boot",
|
| 527 |
+
"515": "cowboy hat, ten-gallon hat",
|
| 528 |
+
"516": "cradle",
|
| 529 |
+
"517": "crane",
|
| 530 |
+
"518": "crash helmet",
|
| 531 |
+
"519": "crate",
|
| 532 |
+
"520": "crib, cot",
|
| 533 |
+
"521": "Crock Pot",
|
| 534 |
+
"522": "croquet ball",
|
| 535 |
+
"523": "crutch",
|
| 536 |
+
"524": "cuirass",
|
| 537 |
+
"525": "dam, dike, dyke",
|
| 538 |
+
"526": "desk",
|
| 539 |
+
"527": "desktop computer",
|
| 540 |
+
"528": "dial telephone, dial phone",
|
| 541 |
+
"529": "diaper, nappy, napkin",
|
| 542 |
+
"530": "digital clock",
|
| 543 |
+
"531": "digital watch",
|
| 544 |
+
"532": "dining table, board",
|
| 545 |
+
"533": "dishrag, dishcloth",
|
| 546 |
+
"534": "dishwasher, dish washer, dishwashing machine",
|
| 547 |
+
"535": "disk brake, disc brake",
|
| 548 |
+
"536": "dock, dockage, docking facility",
|
| 549 |
+
"537": "dogsled, dog sled, dog sleigh",
|
| 550 |
+
"538": "dome",
|
| 551 |
+
"539": "doormat, welcome mat",
|
| 552 |
+
"540": "drilling platform, offshore rig",
|
| 553 |
+
"541": "drum, membranophone, tympan",
|
| 554 |
+
"542": "drumstick",
|
| 555 |
+
"543": "dumbbell",
|
| 556 |
+
"544": "Dutch oven",
|
| 557 |
+
"545": "electric fan, blower",
|
| 558 |
+
"546": "electric guitar",
|
| 559 |
+
"547": "electric locomotive",
|
| 560 |
+
"548": "entertainment center",
|
| 561 |
+
"549": "envelope",
|
| 562 |
+
"550": "espresso maker",
|
| 563 |
+
"551": "face powder",
|
| 564 |
+
"552": "feather boa, boa",
|
| 565 |
+
"553": "file, file cabinet, filing cabinet",
|
| 566 |
+
"554": "fireboat",
|
| 567 |
+
"555": "fire engine, fire truck",
|
| 568 |
+
"556": "fire screen, fireguard",
|
| 569 |
+
"557": "flagpole, flagstaff",
|
| 570 |
+
"558": "flute, transverse flute",
|
| 571 |
+
"559": "folding chair",
|
| 572 |
+
"560": "football helmet",
|
| 573 |
+
"561": "forklift",
|
| 574 |
+
"562": "fountain",
|
| 575 |
+
"563": "fountain pen",
|
| 576 |
+
"564": "four-poster",
|
| 577 |
+
"565": "freight car",
|
| 578 |
+
"566": "French horn, horn",
|
| 579 |
+
"567": "frying pan, frypan, skillet",
|
| 580 |
+
"568": "fur coat",
|
| 581 |
+
"569": "garbage truck, dustcart",
|
| 582 |
+
"570": "gasmask, respirator, gas helmet",
|
| 583 |
+
"571": "gas pump, gasoline pump, petrol pump, island dispenser",
|
| 584 |
+
"572": "goblet",
|
| 585 |
+
"573": "go-kart",
|
| 586 |
+
"574": "golf ball",
|
| 587 |
+
"575": "golfcart, golf cart",
|
| 588 |
+
"576": "gondola",
|
| 589 |
+
"577": "gong, tam-tam",
|
| 590 |
+
"578": "gown",
|
| 591 |
+
"579": "grand piano, grand",
|
| 592 |
+
"580": "greenhouse, nursery, glasshouse",
|
| 593 |
+
"581": "grille, radiator grille",
|
| 594 |
+
"582": "grocery store, grocery, food market, market",
|
| 595 |
+
"583": "guillotine",
|
| 596 |
+
"584": "hair slide",
|
| 597 |
+
"585": "hair spray",
|
| 598 |
+
"586": "half track",
|
| 599 |
+
"587": "hammer",
|
| 600 |
+
"588": "hamper",
|
| 601 |
+
"589": "hand blower, blow dryer, blow drier, hair dryer, hair drier",
|
| 602 |
+
"590": "hand-held computer, hand-held microcomputer",
|
| 603 |
+
"591": "handkerchief, hankie, hanky, hankey",
|
| 604 |
+
"592": "hard disc, hard disk, fixed disk",
|
| 605 |
+
"593": "harmonica, mouth organ, harp, mouth harp",
|
| 606 |
+
"594": "harp",
|
| 607 |
+
"595": "harvester, reaper",
|
| 608 |
+
"596": "hatchet",
|
| 609 |
+
"597": "holster",
|
| 610 |
+
"598": "home theater, home theatre",
|
| 611 |
+
"599": "honeycomb",
|
| 612 |
+
"600": "hook, claw",
|
| 613 |
+
"601": "hoopskirt, crinoline",
|
| 614 |
+
"602": "horizontal bar, high bar",
|
| 615 |
+
"603": "horse cart, horse-cart",
|
| 616 |
+
"604": "hourglass",
|
| 617 |
+
"605": "iPod",
|
| 618 |
+
"606": "iron, smoothing iron",
|
| 619 |
+
"607": "jack-o-lantern",
|
| 620 |
+
"608": "jean, blue jean, denim",
|
| 621 |
+
"609": "jeep, landrover",
|
| 622 |
+
"610": "jersey, T-shirt, tee shirt",
|
| 623 |
+
"611": "jigsaw puzzle",
|
| 624 |
+
"612": "jinrikisha, ricksha, rickshaw",
|
| 625 |
+
"613": "joystick",
|
| 626 |
+
"614": "kimono",
|
| 627 |
+
"615": "knee pad",
|
| 628 |
+
"616": "knot",
|
| 629 |
+
"617": "lab coat, laboratory coat",
|
| 630 |
+
"618": "ladle",
|
| 631 |
+
"619": "lampshade, lamp shade",
|
| 632 |
+
"620": "laptop, laptop computer",
|
| 633 |
+
"621": "lawn mower, mower",
|
| 634 |
+
"622": "lens cap, lens cover",
|
| 635 |
+
"623": "letter opener, paper knife, paperknife",
|
| 636 |
+
"624": "library",
|
| 637 |
+
"625": "lifeboat",
|
| 638 |
+
"626": "lighter, light, igniter, ignitor",
|
| 639 |
+
"627": "limousine, limo",
|
| 640 |
+
"628": "liner, ocean liner",
|
| 641 |
+
"629": "lipstick, lip rouge",
|
| 642 |
+
"630": "Loafer",
|
| 643 |
+
"631": "lotion",
|
| 644 |
+
"632": "loudspeaker, speaker, speaker unit, loudspeaker system, speaker system",
|
| 645 |
+
"633": "loupe, jewelers loupe",
|
| 646 |
+
"634": "lumbermill, sawmill",
|
| 647 |
+
"635": "magnetic compass",
|
| 648 |
+
"636": "mailbag, postbag",
|
| 649 |
+
"637": "mailbox, letter box",
|
| 650 |
+
"638": "maillot",
|
| 651 |
+
"639": "maillot, tank suit",
|
| 652 |
+
"640": "manhole cover",
|
| 653 |
+
"641": "maraca",
|
| 654 |
+
"642": "marimba, xylophone",
|
| 655 |
+
"643": "mask",
|
| 656 |
+
"644": "matchstick",
|
| 657 |
+
"645": "maypole",
|
| 658 |
+
"646": "maze, labyrinth",
|
| 659 |
+
"647": "measuring cup",
|
| 660 |
+
"648": "medicine chest, medicine cabinet",
|
| 661 |
+
"649": "megalith, megalithic structure",
|
| 662 |
+
"650": "microphone, mike",
|
| 663 |
+
"651": "microwave, microwave oven",
|
| 664 |
+
"652": "military uniform",
|
| 665 |
+
"653": "milk can",
|
| 666 |
+
"654": "minibus",
|
| 667 |
+
"655": "miniskirt, mini",
|
| 668 |
+
"656": "minivan",
|
| 669 |
+
"657": "missile",
|
| 670 |
+
"658": "mitten",
|
| 671 |
+
"659": "mixing bowl",
|
| 672 |
+
"660": "mobile home, manufactured home",
|
| 673 |
+
"661": "Model T",
|
| 674 |
+
"662": "modem",
|
| 675 |
+
"663": "monastery",
|
| 676 |
+
"664": "monitor",
|
| 677 |
+
"665": "moped",
|
| 678 |
+
"666": "mortar",
|
| 679 |
+
"667": "mortarboard",
|
| 680 |
+
"668": "mosque",
|
| 681 |
+
"669": "mosquito net",
|
| 682 |
+
"670": "motor scooter, scooter",
|
| 683 |
+
"671": "mountain bike, all-terrain bike, off-roader",
|
| 684 |
+
"672": "mountain tent",
|
| 685 |
+
"673": "mouse, computer mouse",
|
| 686 |
+
"674": "mousetrap",
|
| 687 |
+
"675": "moving van",
|
| 688 |
+
"676": "muzzle",
|
| 689 |
+
"677": "nail",
|
| 690 |
+
"678": "neck brace",
|
| 691 |
+
"679": "necklace",
|
| 692 |
+
"680": "nipple",
|
| 693 |
+
"681": "notebook, notebook computer",
|
| 694 |
+
"682": "obelisk",
|
| 695 |
+
"683": "oboe, hautboy, hautbois",
|
| 696 |
+
"684": "ocarina, sweet potato",
|
| 697 |
+
"685": "odometer, hodometer, mileometer, milometer",
|
| 698 |
+
"686": "oil filter",
|
| 699 |
+
"687": "organ, pipe organ",
|
| 700 |
+
"688": "oscilloscope, scope, cathode-ray oscilloscope, CRO",
|
| 701 |
+
"689": "overskirt",
|
| 702 |
+
"690": "oxcart",
|
| 703 |
+
"691": "oxygen mask",
|
| 704 |
+
"692": "packet",
|
| 705 |
+
"693": "paddle, boat paddle",
|
| 706 |
+
"694": "paddlewheel, paddle wheel",
|
| 707 |
+
"695": "padlock",
|
| 708 |
+
"696": "paintbrush",
|
| 709 |
+
"697": "pajama, pyjama, pjs, jammies",
|
| 710 |
+
"698": "palace",
|
| 711 |
+
"699": "panpipe, pandean pipe, syrinx",
|
| 712 |
+
"700": "paper towel",
|
| 713 |
+
"701": "parachute, chute",
|
| 714 |
+
"702": "parallel bars, bars",
|
| 715 |
+
"703": "park bench",
|
| 716 |
+
"704": "parking meter",
|
| 717 |
+
"705": "passenger car, coach, carriage",
|
| 718 |
+
"706": "patio, terrace",
|
| 719 |
+
"707": "pay-phone, pay-station",
|
| 720 |
+
"708": "pedestal, plinth, footstall",
|
| 721 |
+
"709": "pencil box, pencil case",
|
| 722 |
+
"710": "pencil sharpener",
|
| 723 |
+
"711": "perfume, essence",
|
| 724 |
+
"712": "Petri dish",
|
| 725 |
+
"713": "photocopier",
|
| 726 |
+
"714": "pick, plectrum, plectron",
|
| 727 |
+
"715": "pickelhaube",
|
| 728 |
+
"716": "picket fence, paling",
|
| 729 |
+
"717": "pickup, pickup truck",
|
| 730 |
+
"718": "pier",
|
| 731 |
+
"719": "piggy bank, penny bank",
|
| 732 |
+
"720": "pill bottle",
|
| 733 |
+
"721": "pillow",
|
| 734 |
+
"722": "ping-pong ball",
|
| 735 |
+
"723": "pinwheel",
|
| 736 |
+
"724": "pirate, pirate ship",
|
| 737 |
+
"725": "pitcher, ewer",
|
| 738 |
+
"726": "plane, carpenters plane, woodworking plane",
|
| 739 |
+
"727": "planetarium",
|
| 740 |
+
"728": "plastic bag",
|
| 741 |
+
"729": "plate rack",
|
| 742 |
+
"730": "plow, plough",
|
| 743 |
+
"731": "plunger, plumbers helper",
|
| 744 |
+
"732": "Polaroid camera, Polaroid Land camera",
|
| 745 |
+
"733": "pole",
|
| 746 |
+
"734": "police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria",
|
| 747 |
+
"735": "poncho",
|
| 748 |
+
"736": "pool table, billiard table, snooker table",
|
| 749 |
+
"737": "pop bottle, soda bottle",
|
| 750 |
+
"738": "pot, flowerpot",
|
| 751 |
+
"739": "potters wheel",
|
| 752 |
+
"740": "power drill",
|
| 753 |
+
"741": "prayer rug, prayer mat",
|
| 754 |
+
"742": "printer",
|
| 755 |
+
"743": "prison, prison house",
|
| 756 |
+
"744": "projectile, missile",
|
| 757 |
+
"745": "projector",
|
| 758 |
+
"746": "puck, hockey puck",
|
| 759 |
+
"747": "punching bag, punch bag, punching ball, punchball",
|
| 760 |
+
"748": "purse",
|
| 761 |
+
"749": "quill, quill pen",
|
| 762 |
+
"750": "quilt, comforter, comfort, puff",
|
| 763 |
+
"751": "racer, race car, racing car",
|
| 764 |
+
"752": "racket, racquet",
|
| 765 |
+
"753": "radiator",
|
| 766 |
+
"754": "radio, wireless",
|
| 767 |
+
"755": "radio telescope, radio reflector",
|
| 768 |
+
"756": "rain barrel",
|
| 769 |
+
"757": "recreational vehicle, RV, R.V.",
|
| 770 |
+
"758": "reel",
|
| 771 |
+
"759": "reflex camera",
|
| 772 |
+
"760": "refrigerator, icebox",
|
| 773 |
+
"761": "remote control, remote",
|
| 774 |
+
"762": "restaurant, eating house, eating place, eatery",
|
| 775 |
+
"763": "revolver, six-gun, six-shooter",
|
| 776 |
+
"764": "rifle",
|
| 777 |
+
"765": "rocking chair, rocker",
|
| 778 |
+
"766": "rotisserie",
|
| 779 |
+
"767": "rubber eraser, rubber, pencil eraser",
|
| 780 |
+
"768": "rugby ball",
|
| 781 |
+
"769": "rule, ruler",
|
| 782 |
+
"770": "running shoe",
|
| 783 |
+
"771": "safe",
|
| 784 |
+
"772": "safety pin",
|
| 785 |
+
"773": "saltshaker, salt shaker",
|
| 786 |
+
"774": "sandal",
|
| 787 |
+
"775": "sarong",
|
| 788 |
+
"776": "sax, saxophone",
|
| 789 |
+
"777": "scabbard",
|
| 790 |
+
"778": "scale, weighing machine",
|
| 791 |
+
"779": "school bus",
|
| 792 |
+
"780": "schooner",
|
| 793 |
+
"781": "scoreboard",
|
| 794 |
+
"782": "screen, CRT screen",
|
| 795 |
+
"783": "screw",
|
| 796 |
+
"784": "screwdriver",
|
| 797 |
+
"785": "seat belt, seatbelt",
|
| 798 |
+
"786": "sewing machine",
|
| 799 |
+
"787": "shield, buckler",
|
| 800 |
+
"788": "shoe shop, shoe-shop, shoe store",
|
| 801 |
+
"789": "shoji",
|
| 802 |
+
"790": "shopping basket",
|
| 803 |
+
"791": "shopping cart",
|
| 804 |
+
"792": "shovel",
|
| 805 |
+
"793": "shower cap",
|
| 806 |
+
"794": "shower curtain",
|
| 807 |
+
"795": "ski",
|
| 808 |
+
"796": "ski mask",
|
| 809 |
+
"797": "sleeping bag",
|
| 810 |
+
"798": "slide rule, slipstick",
|
| 811 |
+
"799": "sliding door",
|
| 812 |
+
"800": "slot, one-armed bandit",
|
| 813 |
+
"801": "snorkel",
|
| 814 |
+
"802": "snowmobile",
|
| 815 |
+
"803": "snowplow, snowplough",
|
| 816 |
+
"804": "soap dispenser",
|
| 817 |
+
"805": "soccer ball",
|
| 818 |
+
"806": "sock",
|
| 819 |
+
"807": "solar dish, solar collector, solar furnace",
|
| 820 |
+
"808": "sombrero",
|
| 821 |
+
"809": "soup bowl",
|
| 822 |
+
"810": "space bar",
|
| 823 |
+
"811": "space heater",
|
| 824 |
+
"812": "space shuttle",
|
| 825 |
+
"813": "spatula",
|
| 826 |
+
"814": "speedboat",
|
| 827 |
+
"815": "spider web, spiders web",
|
| 828 |
+
"816": "spindle",
|
| 829 |
+
"817": "sports car, sport car",
|
| 830 |
+
"818": "spotlight, spot",
|
| 831 |
+
"819": "stage",
|
| 832 |
+
"820": "steam locomotive",
|
| 833 |
+
"821": "steel arch bridge",
|
| 834 |
+
"822": "steel drum",
|
| 835 |
+
"823": "stethoscope",
|
| 836 |
+
"824": "stole",
|
| 837 |
+
"825": "stone wall",
|
| 838 |
+
"826": "stopwatch, stop watch",
|
| 839 |
+
"827": "stove",
|
| 840 |
+
"828": "strainer",
|
| 841 |
+
"829": "streetcar, tram, tramcar, trolley, trolley car",
|
| 842 |
+
"830": "stretcher",
|
| 843 |
+
"831": "studio couch, day bed",
|
| 844 |
+
"832": "stupa, tope",
|
| 845 |
+
"833": "submarine, pigboat, sub, U-boat",
|
| 846 |
+
"834": "suit, suit of clothes",
|
| 847 |
+
"835": "sundial",
|
| 848 |
+
"836": "sunglass",
|
| 849 |
+
"837": "sunglasses, dark glasses, shades",
|
| 850 |
+
"838": "sunscreen, sunblock, sun blocker",
|
| 851 |
+
"839": "suspension bridge",
|
| 852 |
+
"840": "swab, swob, mop",
|
| 853 |
+
"841": "sweatshirt",
|
| 854 |
+
"842": "swimming trunks, bathing trunks",
|
| 855 |
+
"843": "swing",
|
| 856 |
+
"844": "switch, electric switch, electrical switch",
|
| 857 |
+
"845": "syringe",
|
| 858 |
+
"846": "table lamp",
|
| 859 |
+
"847": "tank, army tank, armored combat vehicle, armoured combat vehicle",
|
| 860 |
+
"848": "tape player",
|
| 861 |
+
"849": "teapot",
|
| 862 |
+
"850": "teddy, teddy bear",
|
| 863 |
+
"851": "television, television system",
|
| 864 |
+
"852": "tennis ball",
|
| 865 |
+
"853": "thatch, thatched roof",
|
| 866 |
+
"854": "theater curtain, theatre curtain",
|
| 867 |
+
"855": "thimble",
|
| 868 |
+
"856": "thresher, thrasher, threshing machine",
|
| 869 |
+
"857": "throne",
|
| 870 |
+
"858": "tile roof",
|
| 871 |
+
"859": "toaster",
|
| 872 |
+
"860": "tobacco shop, tobacconist shop, tobacconist",
|
| 873 |
+
"861": "toilet seat",
|
| 874 |
+
"862": "torch",
|
| 875 |
+
"863": "totem pole",
|
| 876 |
+
"864": "tow truck, tow car, wrecker",
|
| 877 |
+
"865": "toyshop",
|
| 878 |
+
"866": "tractor",
|
| 879 |
+
"867": "trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi",
|
| 880 |
+
"868": "tray",
|
| 881 |
+
"869": "trench coat",
|
| 882 |
+
"870": "tricycle, trike, velocipede",
|
| 883 |
+
"871": "trimaran",
|
| 884 |
+
"872": "tripod",
|
| 885 |
+
"873": "triumphal arch",
|
| 886 |
+
"874": "trolleybus, trolley coach, trackless trolley",
|
| 887 |
+
"875": "trombone",
|
| 888 |
+
"876": "tub, vat",
|
| 889 |
+
"877": "turnstile",
|
| 890 |
+
"878": "typewriter keyboard",
|
| 891 |
+
"879": "umbrella",
|
| 892 |
+
"880": "unicycle, monocycle",
|
| 893 |
+
"881": "upright, upright piano",
|
| 894 |
+
"882": "vacuum, vacuum cleaner",
|
| 895 |
+
"883": "vase",
|
| 896 |
+
"884": "vault",
|
| 897 |
+
"885": "velvet",
|
| 898 |
+
"886": "vending machine",
|
| 899 |
+
"887": "vestment",
|
| 900 |
+
"888": "viaduct",
|
| 901 |
+
"889": "violin, fiddle",
|
| 902 |
+
"890": "volleyball",
|
| 903 |
+
"891": "waffle iron",
|
| 904 |
+
"892": "wall clock",
|
| 905 |
+
"893": "wallet, billfold, notecase, pocketbook",
|
| 906 |
+
"894": "wardrobe, closet, press",
|
| 907 |
+
"895": "warplane, military plane",
|
| 908 |
+
"896": "washbasin, handbasin, washbowl, lavabo, wash-hand basin",
|
| 909 |
+
"897": "washer, automatic washer, washing machine",
|
| 910 |
+
"898": "water bottle",
|
| 911 |
+
"899": "water jug",
|
| 912 |
+
"900": "water tower",
|
| 913 |
+
"901": "whiskey jug",
|
| 914 |
+
"902": "whistle",
|
| 915 |
+
"903": "wig",
|
| 916 |
+
"904": "window screen",
|
| 917 |
+
"905": "window shade",
|
| 918 |
+
"906": "Windsor tie",
|
| 919 |
+
"907": "wine bottle",
|
| 920 |
+
"908": "wing",
|
| 921 |
+
"909": "wok",
|
| 922 |
+
"910": "wooden spoon",
|
| 923 |
+
"911": "wool, woolen, woollen",
|
| 924 |
+
"912": "worm fence, snake fence, snake-rail fence, Virginia fence",
|
| 925 |
+
"913": "wreck",
|
| 926 |
+
"914": "yawl",
|
| 927 |
+
"915": "yurt",
|
| 928 |
+
"916": "web site, website, internet site, site",
|
| 929 |
+
"917": "comic book",
|
| 930 |
+
"918": "crossword puzzle, crossword",
|
| 931 |
+
"919": "street sign",
|
| 932 |
+
"920": "traffic light, traffic signal, stoplight",
|
| 933 |
+
"921": "book jacket, dust cover, dust jacket, dust wrapper",
|
| 934 |
+
"922": "menu",
|
| 935 |
+
"923": "plate",
|
| 936 |
+
"924": "guacamole",
|
| 937 |
+
"925": "consomme",
|
| 938 |
+
"926": "hot pot, hotpot",
|
| 939 |
+
"927": "trifle",
|
| 940 |
+
"928": "ice cream, icecream",
|
| 941 |
+
"929": "ice lolly, lolly, lollipop, popsicle",
|
| 942 |
+
"930": "French loaf",
|
| 943 |
+
"931": "bagel, beigel",
|
| 944 |
+
"932": "pretzel",
|
| 945 |
+
"933": "cheeseburger",
|
| 946 |
+
"934": "hotdog, hot dog, red hot",
|
| 947 |
+
"935": "mashed potato",
|
| 948 |
+
"936": "head cabbage",
|
| 949 |
+
"937": "broccoli",
|
| 950 |
+
"938": "cauliflower",
|
| 951 |
+
"939": "zucchini, courgette",
|
| 952 |
+
"940": "spaghetti squash",
|
| 953 |
+
"941": "acorn squash",
|
| 954 |
+
"942": "butternut squash",
|
| 955 |
+
"943": "cucumber, cuke",
|
| 956 |
+
"944": "artichoke, globe artichoke",
|
| 957 |
+
"945": "bell pepper",
|
| 958 |
+
"946": "cardoon",
|
| 959 |
+
"947": "mushroom",
|
| 960 |
+
"948": "Granny Smith",
|
| 961 |
+
"949": "strawberry",
|
| 962 |
+
"950": "orange",
|
| 963 |
+
"951": "lemon",
|
| 964 |
+
"952": "fig",
|
| 965 |
+
"953": "pineapple, ananas",
|
| 966 |
+
"954": "banana",
|
| 967 |
+
"955": "jackfruit, jak, jack",
|
| 968 |
+
"956": "custard apple",
|
| 969 |
+
"957": "pomegranate",
|
| 970 |
+
"958": "hay",
|
| 971 |
+
"959": "carbonara",
|
| 972 |
+
"960": "chocolate sauce, chocolate syrup",
|
| 973 |
+
"961": "dough",
|
| 974 |
+
"962": "meat loaf, meatloaf",
|
| 975 |
+
"963": "pizza, pizza pie",
|
| 976 |
+
"964": "potpie",
|
| 977 |
+
"965": "burrito",
|
| 978 |
+
"966": "red wine",
|
| 979 |
+
"967": "espresso",
|
| 980 |
+
"968": "cup",
|
| 981 |
+
"969": "eggnog",
|
| 982 |
+
"970": "alp",
|
| 983 |
+
"971": "bubble",
|
| 984 |
+
"972": "cliff, drop, drop-off",
|
| 985 |
+
"973": "coral reef",
|
| 986 |
+
"974": "geyser",
|
| 987 |
+
"975": "lakeside, lakeshore",
|
| 988 |
+
"976": "promontory, headland, head, foreland",
|
| 989 |
+
"977": "sandbar, sand bar",
|
| 990 |
+
"978": "seashore, coast, seacoast, sea-coast",
|
| 991 |
+
"979": "valley, vale",
|
| 992 |
+
"980": "volcano",
|
| 993 |
+
"981": "ballplayer, baseball player",
|
| 994 |
+
"982": "groom, bridegroom",
|
| 995 |
+
"983": "scuba diver",
|
| 996 |
+
"984": "rapeseed",
|
| 997 |
+
"985": "daisy",
|
| 998 |
+
"986": "yellow ladys slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum",
|
| 999 |
+
"987": "corn",
|
| 1000 |
+
"988": "acorn",
|
| 1001 |
+
"989": "hip, rose hip, rosehip",
|
| 1002 |
+
"990": "buckeye, horse chestnut, conker",
|
| 1003 |
+
"991": "coral fungus",
|
| 1004 |
+
"992": "agaric",
|
| 1005 |
+
"993": "gyromitra",
|
| 1006 |
+
"994": "stinkhorn, carrion fungus",
|
| 1007 |
+
"995": "earthstar",
|
| 1008 |
+
"996": "hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa",
|
| 1009 |
+
"997": "bolete",
|
| 1010 |
+
"998": "ear, spike, capitulum",
|
| 1011 |
+
"999": "toilet tissue, toilet paper, bathroom tissue"
|
| 1012 |
+
},
|
| 1013 |
+
"scheduler": [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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hub custom pipeline: PAEPipeline.
|
| 2 |
+
Load with native Hugging Face diffusers and trust_remote_code=True.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
# Copyright 2026 The HuggingFace Team and PAE authors. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import inspect
|
| 24 |
+
import json
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 27 |
+
|
| 28 |
+
import torch
|
| 29 |
+
|
| 30 |
+
from diffusers.image_processor import VaeImageProcessor
|
| 31 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
|
| 32 |
+
from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers
|
| 33 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 34 |
+
|
| 35 |
+
EXAMPLE_DOC_STRING = """
|
| 36 |
+
Examples:
|
| 37 |
+
```py
|
| 38 |
+
>>> from pathlib import Path
|
| 39 |
+
>>> from diffusers import DiffusionPipeline
|
| 40 |
+
>>> import torch
|
| 41 |
+
|
| 42 |
+
>>> model_dir = Path("./pae-dinov2-large-d32").resolve()
|
| 43 |
+
>>> pipe = DiffusionPipeline.from_pretrained(
|
| 44 |
+
... str(model_dir),
|
| 45 |
+
... local_files_only=True,
|
| 46 |
+
... custom_pipeline=str(model_dir / "pipeline.py"),
|
| 47 |
+
... trust_remote_code=True,
|
| 48 |
+
... torch_dtype=torch.bfloat16,
|
| 49 |
+
... )
|
| 50 |
+
>>> pipe.to("cuda")
|
| 51 |
+
|
| 52 |
+
>>> print(pipe.id2label[207])
|
| 53 |
+
>>> print(pipe.get_label_ids("golden retriever"))
|
| 54 |
+
|
| 55 |
+
>>> generator = torch.Generator(device="cuda").manual_seed(42)
|
| 56 |
+
>>> image = pipe(
|
| 57 |
+
... class_labels="golden retriever",
|
| 58 |
+
... generator=generator,
|
| 59 |
+
... ).images[0]
|
| 60 |
+
```
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class PAEPipeline(DiffusionPipeline):
|
| 65 |
+
r"""
|
| 66 |
+
Pipeline for class-conditional image generation with PAE tokenizers and LightningDiT.
|
| 67 |
+
|
| 68 |
+
This model inherits from [`DiffusionPipeline`]. Components are stored in separate subfolders
|
| 69 |
+
(`transformers/`, `scheduler/`, `decoder/`) and loaded via `DiffusionPipeline.from_pretrained`.
|
| 70 |
+
|
| 71 |
+
Parameters:
|
| 72 |
+
transformers ([`LightningDiT2DModel`]):
|
| 73 |
+
Class-conditional LightningDiT transformer that predicts flow-matching velocity in PAE latent space.
|
| 74 |
+
scheduler ([`PAEFlowMatchScheduler`]):
|
| 75 |
+
Flow-matching ODE/SDE scheduler. Other [`KarrasDiffusionSchedulers`] can be swapped at inference time
|
| 76 |
+
when their `step` API is compatible.
|
| 77 |
+
decoder ([`PAEDecoder`]):
|
| 78 |
+
Prior-Aligned Autoencoder decoder stack (decompressor + pixel decoder).
|
| 79 |
+
|
| 80 |
+
ImageNet `id2label` mappings are read lazily from `model_index.json` when label helpers are used.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
model_cpu_offload_seq = "transformers->decoder"
|
| 84 |
+
_optional_components = ["decoder"]
|
| 85 |
+
|
| 86 |
+
@staticmethod
|
| 87 |
+
def prepare_extra_step_kwargs(
|
| 88 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 89 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 90 |
+
eta: Optional[float] = None,
|
| 91 |
+
) -> Dict[str, object]:
|
| 92 |
+
r"""
|
| 93 |
+
Build kwargs forwarded to `scheduler.step` when supported.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
scheduler:
|
| 97 |
+
Active diffusion scheduler instance.
|
| 98 |
+
generator:
|
| 99 |
+
Optional RNG passed through to stochastic scheduler steps.
|
| 100 |
+
eta:
|
| 101 |
+
Optional DDIM-style eta when the scheduler accepts it.
|
| 102 |
+
"""
|
| 103 |
+
kwargs: Dict[str, object] = {}
|
| 104 |
+
step_params = set(inspect.signature(scheduler.step).parameters.keys())
|
| 105 |
+
if "generator" in step_params:
|
| 106 |
+
kwargs["generator"] = generator
|
| 107 |
+
if eta is not None and "eta" in step_params:
|
| 108 |
+
kwargs["eta"] = eta
|
| 109 |
+
return kwargs
|
| 110 |
+
|
| 111 |
+
def __init__(
|
| 112 |
+
self,
|
| 113 |
+
transformers,
|
| 114 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 115 |
+
decoder=None,
|
| 116 |
+
transformer=None,
|
| 117 |
+
) -> None:
|
| 118 |
+
if transformer is not None and transformers is None:
|
| 119 |
+
transformers = transformer
|
| 120 |
+
super().__init__()
|
| 121 |
+
self.register_modules(transformers=transformers, scheduler=scheduler, decoder=decoder)
|
| 122 |
+
# PAE decoders already return pixels in [0, 1]; disable VAE-style [-1, 1] denormalization.
|
| 123 |
+
self.image_processor = VaeImageProcessor(do_normalize=False)
|
| 124 |
+
self._id2label: Dict[int, str] = {}
|
| 125 |
+
self.labels: Dict[str, int] = {}
|
| 126 |
+
self._labels_loaded_from_model_index = False
|
| 127 |
+
|
| 128 |
+
@property
|
| 129 |
+
def transformer(self):
|
| 130 |
+
"""Backward-compatible alias for `transformers`."""
|
| 131 |
+
return self.transformers
|
| 132 |
+
|
| 133 |
+
@staticmethod
|
| 134 |
+
def _normalize_id2label(id2label: Optional[Dict[Union[int, str], str]]) -> Dict[int, str]:
|
| 135 |
+
if not id2label:
|
| 136 |
+
return {}
|
| 137 |
+
return {int(key): value for key, value in id2label.items()}
|
| 138 |
+
|
| 139 |
+
@staticmethod
|
| 140 |
+
def _read_model_index(variant_path: Optional[str]) -> Dict[str, Any]:
|
| 141 |
+
if not variant_path:
|
| 142 |
+
return {}
|
| 143 |
+
variant_dir = Path(variant_path).resolve()
|
| 144 |
+
model_index_path = variant_dir / "model_index.json"
|
| 145 |
+
if not model_index_path.is_file():
|
| 146 |
+
return {}
|
| 147 |
+
raw = json.loads(model_index_path.read_text(encoding="utf-8"))
|
| 148 |
+
return raw if isinstance(raw, dict) else {}
|
| 149 |
+
|
| 150 |
+
@staticmethod
|
| 151 |
+
def _read_id2label_from_model_index(variant_path: Optional[str]) -> Dict[int, str]:
|
| 152 |
+
id2label = PAEPipeline._read_model_index(variant_path).get("id2label")
|
| 153 |
+
if not isinstance(id2label, dict):
|
| 154 |
+
return {}
|
| 155 |
+
return {int(key): value for key, value in id2label.items()}
|
| 156 |
+
|
| 157 |
+
def _get_downsample_ratio(self) -> int:
|
| 158 |
+
override = getattr(self.config, "downsample_ratio", None)
|
| 159 |
+
if override is not None:
|
| 160 |
+
return int(override)
|
| 161 |
+
|
| 162 |
+
encoder_input_size = None
|
| 163 |
+
if self.decoder is not None:
|
| 164 |
+
encoder_input_size = getattr(self.decoder.config, "encoder_input_size", None)
|
| 165 |
+
|
| 166 |
+
if encoder_input_size is not None:
|
| 167 |
+
return int(encoder_input_size) // int(self.transformers.config.input_size)
|
| 168 |
+
return 16
|
| 169 |
+
|
| 170 |
+
def _resolve_latent_stats(
|
| 171 |
+
self,
|
| 172 |
+
latent_mean: Optional[torch.Tensor],
|
| 173 |
+
latent_std: Optional[torch.Tensor],
|
| 174 |
+
latent_multiplier: Optional[float],
|
| 175 |
+
device: torch.device,
|
| 176 |
+
dtype: torch.dtype,
|
| 177 |
+
) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], float]:
|
| 178 |
+
if latent_mean is not None and latent_std is not None:
|
| 179 |
+
return latent_mean, latent_std, float(latent_multiplier if latent_multiplier is not None else 1.0)
|
| 180 |
+
|
| 181 |
+
decoder_cfg = getattr(self.decoder, "config", None) if self.decoder is not None else None
|
| 182 |
+
if decoder_cfg is not None:
|
| 183 |
+
mean = getattr(decoder_cfg, "latent_mean", None)
|
| 184 |
+
std = getattr(decoder_cfg, "latent_std", None)
|
| 185 |
+
if mean is not None and std is not None:
|
| 186 |
+
multiplier = getattr(decoder_cfg, "latent_multiplier", 1.0)
|
| 187 |
+
mean_tensor = torch.tensor(mean, device=device, dtype=dtype).view(1, -1, 1, 1)
|
| 188 |
+
std_tensor = torch.tensor(std, device=device, dtype=dtype).view(1, -1, 1, 1)
|
| 189 |
+
return mean_tensor, std_tensor, float(multiplier)
|
| 190 |
+
|
| 191 |
+
return latent_mean, latent_std, float(latent_multiplier if latent_multiplier is not None else 1.0)
|
| 192 |
+
|
| 193 |
+
@staticmethod
|
| 194 |
+
def _build_label2id(id2label: Dict[int, str]) -> Dict[str, int]:
|
| 195 |
+
label2id: Dict[str, int] = {}
|
| 196 |
+
for class_id, value in id2label.items():
|
| 197 |
+
for synonym in value.split(","):
|
| 198 |
+
synonym = synonym.strip()
|
| 199 |
+
if synonym:
|
| 200 |
+
label2id[synonym] = int(class_id)
|
| 201 |
+
return dict(sorted(label2id.items()))
|
| 202 |
+
|
| 203 |
+
def _ensure_labels_loaded(self) -> None:
|
| 204 |
+
if self._labels_loaded_from_model_index:
|
| 205 |
+
return
|
| 206 |
+
loaded = self._read_id2label_from_model_index(getattr(self.config, "_name_or_path", None))
|
| 207 |
+
if loaded:
|
| 208 |
+
self._id2label = loaded
|
| 209 |
+
self.labels = self._build_label2id(self._id2label)
|
| 210 |
+
self._labels_loaded_from_model_index = True
|
| 211 |
+
|
| 212 |
+
@property
|
| 213 |
+
def id2label(self) -> Dict[int, str]:
|
| 214 |
+
r"""ImageNet class id to English label string (comma-separated synonyms)."""
|
| 215 |
+
self._ensure_labels_loaded()
|
| 216 |
+
return self._id2label
|
| 217 |
+
|
| 218 |
+
def get_label_ids(self, label: Union[str, List[str]]) -> List[int]:
|
| 219 |
+
r"""
|
| 220 |
+
Map ImageNet label strings to class ids.
|
| 221 |
+
|
| 222 |
+
Args:
|
| 223 |
+
label:
|
| 224 |
+
One or more English label strings. Each string must match a synonym in `id2label`.
|
| 225 |
+
|
| 226 |
+
Returns:
|
| 227 |
+
Matching ImageNet class ids.
|
| 228 |
+
"""
|
| 229 |
+
self._ensure_labels_loaded()
|
| 230 |
+
label2id = self.labels
|
| 231 |
+
if not label2id:
|
| 232 |
+
raise ValueError("No English labels loaded. Ensure `id2label` exists in model_index.json.")
|
| 233 |
+
|
| 234 |
+
if isinstance(label, str):
|
| 235 |
+
label = [label]
|
| 236 |
+
|
| 237 |
+
missing = [item for item in label if item not in label2id]
|
| 238 |
+
if missing:
|
| 239 |
+
preview = ", ".join(list(label2id.keys())[:8])
|
| 240 |
+
raise ValueError(f"Unknown English label(s): {missing}. Example valid labels: {preview}, ...")
|
| 241 |
+
return [label2id[item] for item in label]
|
| 242 |
+
|
| 243 |
+
def _default_image_size(self) -> int:
|
| 244 |
+
return int(self.transformers.config.input_size) * self._get_downsample_ratio()
|
| 245 |
+
|
| 246 |
+
def _normalize_class_labels(
|
| 247 |
+
self,
|
| 248 |
+
class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
|
| 249 |
+
) -> torch.LongTensor:
|
| 250 |
+
if torch.is_tensor(class_labels):
|
| 251 |
+
return class_labels.to(device=self._execution_device, dtype=torch.long).reshape(-1)
|
| 252 |
+
|
| 253 |
+
if isinstance(class_labels, int):
|
| 254 |
+
class_label_ids = [class_labels]
|
| 255 |
+
elif isinstance(class_labels, str):
|
| 256 |
+
class_label_ids = self.get_label_ids(class_labels)
|
| 257 |
+
elif class_labels and isinstance(class_labels[0], str):
|
| 258 |
+
class_label_ids = self.get_label_ids(class_labels)
|
| 259 |
+
else:
|
| 260 |
+
class_label_ids = list(class_labels)
|
| 261 |
+
|
| 262 |
+
return torch.tensor(class_label_ids, device=self._execution_device, dtype=torch.long).reshape(-1)
|
| 263 |
+
|
| 264 |
+
def check_inputs(
|
| 265 |
+
self,
|
| 266 |
+
height: int,
|
| 267 |
+
width: int,
|
| 268 |
+
num_inference_steps: int,
|
| 269 |
+
output_type: str,
|
| 270 |
+
mode: str,
|
| 271 |
+
) -> None:
|
| 272 |
+
if num_inference_steps < 1:
|
| 273 |
+
raise ValueError("num_inference_steps must be >= 1.")
|
| 274 |
+
if output_type not in {"pil", "np", "pt", "latent"}:
|
| 275 |
+
raise ValueError("output_type must be one of: 'pil', 'np', 'pt', 'latent'.")
|
| 276 |
+
if mode not in {"ode", "sde"}:
|
| 277 |
+
raise ValueError("mode must be either 'ode' or 'sde'.")
|
| 278 |
+
|
| 279 |
+
downsample = self._get_downsample_ratio()
|
| 280 |
+
if height % downsample != 0 or width % downsample != 0:
|
| 281 |
+
raise ValueError(
|
| 282 |
+
f"height and width must be divisible by the PAE downsample factor {downsample}."
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
latent_height = height // downsample
|
| 286 |
+
latent_width = width // downsample
|
| 287 |
+
expected_size = int(self.transformers.config.input_size)
|
| 288 |
+
if latent_height != expected_size or latent_width != expected_size:
|
| 289 |
+
raise ValueError(
|
| 290 |
+
f"Requested latent size {(latent_height, latent_width)} does not match the pretrained "
|
| 291 |
+
f"transformer input_size={expected_size}. Use height=width={self._default_image_size()}."
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
def prepare_latents(
|
| 295 |
+
self,
|
| 296 |
+
batch_size: int,
|
| 297 |
+
height: int,
|
| 298 |
+
width: int,
|
| 299 |
+
dtype: torch.dtype,
|
| 300 |
+
device: torch.device,
|
| 301 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 302 |
+
) -> torch.Tensor:
|
| 303 |
+
downsample = self._get_downsample_ratio()
|
| 304 |
+
latent_height = height // downsample
|
| 305 |
+
latent_width = width // downsample
|
| 306 |
+
return randn_tensor(
|
| 307 |
+
(batch_size, self.transformers.config.in_channels, latent_height, latent_width),
|
| 308 |
+
generator=generator,
|
| 309 |
+
device=device,
|
| 310 |
+
dtype=dtype,
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
@staticmethod
|
| 314 |
+
def _denormalize_latents(
|
| 315 |
+
latents: torch.Tensor,
|
| 316 |
+
latent_mean: Optional[torch.Tensor],
|
| 317 |
+
latent_std: Optional[torch.Tensor],
|
| 318 |
+
latent_multiplier: Optional[float],
|
| 319 |
+
) -> torch.Tensor:
|
| 320 |
+
if latent_mean is None or latent_std is None:
|
| 321 |
+
return latents
|
| 322 |
+
multiplier = 1.0 if latent_multiplier is None else float(latent_multiplier)
|
| 323 |
+
mean = latent_mean.to(device=latents.device, dtype=latents.dtype)
|
| 324 |
+
std = latent_std.to(device=latents.device, dtype=latents.dtype)
|
| 325 |
+
return (latents * std) / multiplier + mean
|
| 326 |
+
|
| 327 |
+
@staticmethod
|
| 328 |
+
def _apply_cfg(
|
| 329 |
+
model_output: torch.Tensor,
|
| 330 |
+
guidance_scale: float,
|
| 331 |
+
guidance_active: bool,
|
| 332 |
+
cfg_channels: int,
|
| 333 |
+
) -> torch.Tensor:
|
| 334 |
+
if guidance_scale <= 1.0 or not guidance_active:
|
| 335 |
+
return model_output
|
| 336 |
+
eps, rest = model_output[:, :cfg_channels], model_output[:, cfg_channels:]
|
| 337 |
+
cond_eps, uncond_eps = torch.chunk(eps, 2, dim=0)
|
| 338 |
+
half_eps = uncond_eps + guidance_scale * (cond_eps - uncond_eps)
|
| 339 |
+
if rest.shape[1] == 0:
|
| 340 |
+
return half_eps
|
| 341 |
+
return torch.cat([half_eps, rest], dim=1)
|
| 342 |
+
|
| 343 |
+
def decode_latents(
|
| 344 |
+
self,
|
| 345 |
+
latents: torch.Tensor,
|
| 346 |
+
output_type: str = "pil",
|
| 347 |
+
latent_mean: Optional[torch.Tensor] = None,
|
| 348 |
+
latent_std: Optional[torch.Tensor] = None,
|
| 349 |
+
latent_multiplier: Optional[float] = None,
|
| 350 |
+
):
|
| 351 |
+
if output_type == "latent":
|
| 352 |
+
return latents
|
| 353 |
+
if self.decoder is None:
|
| 354 |
+
raise ValueError("PAEPipeline requires a PAE decoder component for decoding.")
|
| 355 |
+
|
| 356 |
+
latent_mean, latent_std, latent_multiplier = self._resolve_latent_stats(
|
| 357 |
+
latent_mean,
|
| 358 |
+
latent_std,
|
| 359 |
+
latent_multiplier,
|
| 360 |
+
device=latents.device,
|
| 361 |
+
dtype=latents.dtype,
|
| 362 |
+
)
|
| 363 |
+
latents = self._denormalize_latents(latents, latent_mean, latent_std, latent_multiplier)
|
| 364 |
+
image = self.decoder.decode(latents)
|
| 365 |
+
image = torch.clamp(image, 0.0, 1.0)
|
| 366 |
+
if output_type == "pt":
|
| 367 |
+
return image
|
| 368 |
+
return self.image_processor.postprocess(image, output_type=output_type, do_denormalize=[False] * image.shape[0])
|
| 369 |
+
|
| 370 |
+
@torch.inference_mode()
|
| 371 |
+
def __call__(
|
| 372 |
+
self,
|
| 373 |
+
class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
|
| 374 |
+
height: Optional[int] = None,
|
| 375 |
+
width: Optional[int] = None,
|
| 376 |
+
num_inference_steps: int = 250,
|
| 377 |
+
guidance_scale: float = 3.3,
|
| 378 |
+
guidance_interval: Tuple[float, float] = (0.0, 1.0),
|
| 379 |
+
cfg_interval_start: float = 0.3,
|
| 380 |
+
timestep_shift: float = 0.4,
|
| 381 |
+
mode: str = "ode",
|
| 382 |
+
heun: bool = False,
|
| 383 |
+
latent_mean: Optional[torch.Tensor] = None,
|
| 384 |
+
latent_std: Optional[torch.Tensor] = None,
|
| 385 |
+
latent_multiplier: Optional[float] = None,
|
| 386 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 387 |
+
output_type: str = "pil",
|
| 388 |
+
return_dict: bool = True,
|
| 389 |
+
) -> Union[ImagePipelineOutput, Tuple]:
|
| 390 |
+
r"""
|
| 391 |
+
Generate class-conditional images with PAE + LightningDiT.
|
| 392 |
+
|
| 393 |
+
Args:
|
| 394 |
+
class_labels:
|
| 395 |
+
ImageNet class indices or human-readable English label strings.
|
| 396 |
+
height:
|
| 397 |
+
Output image height in pixels. Defaults to the pretrained native resolution.
|
| 398 |
+
width:
|
| 399 |
+
Output image width in pixels. Defaults to the pretrained native resolution.
|
| 400 |
+
num_inference_steps:
|
| 401 |
+
Number of flow-matching integration steps.
|
| 402 |
+
guidance_scale:
|
| 403 |
+
Classifier-free guidance scale. Active when `guidance_scale > 1.0`.
|
| 404 |
+
guidance_interval:
|
| 405 |
+
Timestep interval `(low, high)` where CFG is applied.
|
| 406 |
+
cfg_interval_start:
|
| 407 |
+
Disable CFG below this normalized timestep value. Default `0.3` matches DiT training configs.
|
| 408 |
+
timestep_shift:
|
| 409 |
+
Timestep warping used by LightningDiT ODE sampling. Default `0.4` matches DiT training configs.
|
| 410 |
+
mode:
|
| 411 |
+
Sampling mode passed to the PAE flow scheduler: `"ode"` or `"sde"`.
|
| 412 |
+
heun:
|
| 413 |
+
Use Heun integration for ODE sampling when True.
|
| 414 |
+
latent_mean:
|
| 415 |
+
Optional latent mean tensor for denormalization before PAE decode. Defaults to
|
| 416 |
+
`latent_mean` in `decoder/config.json` when omitted.
|
| 417 |
+
latent_std:
|
| 418 |
+
Optional latent std tensor for denormalization before PAE decode. Defaults to
|
| 419 |
+
`latent_std` in `decoder/config.json` when omitted.
|
| 420 |
+
latent_multiplier:
|
| 421 |
+
Divisor applied with `latent_std` during denormalization. Defaults to
|
| 422 |
+
`latent_multiplier` in `decoder/config.json` or `1.0`.
|
| 423 |
+
generator:
|
| 424 |
+
RNG for reproducibility.
|
| 425 |
+
output_type:
|
| 426 |
+
`"pil"`, `"np"`, `"pt"`, or `"latent"`.
|
| 427 |
+
return_dict:
|
| 428 |
+
Return [`ImagePipelineOutput`] if True.
|
| 429 |
+
"""
|
| 430 |
+
default_size = self._default_image_size()
|
| 431 |
+
height = int(height or default_size)
|
| 432 |
+
width = int(width or default_size)
|
| 433 |
+
self.check_inputs(height, width, num_inference_steps, output_type, mode)
|
| 434 |
+
|
| 435 |
+
device = self._execution_device
|
| 436 |
+
model_dtype = next(self.transformers.parameters()).dtype
|
| 437 |
+
class_labels_tensor = self._normalize_class_labels(class_labels)
|
| 438 |
+
batch_size = class_labels_tensor.numel()
|
| 439 |
+
null_label = int(self.transformers.config.num_classes)
|
| 440 |
+
null_labels = torch.full((batch_size,), null_label, device=device, dtype=torch.long)
|
| 441 |
+
cfg_channels = int(self.transformers.config.in_channels)
|
| 442 |
+
|
| 443 |
+
latents = self.prepare_latents(
|
| 444 |
+
batch_size=batch_size,
|
| 445 |
+
height=height,
|
| 446 |
+
width=width,
|
| 447 |
+
dtype=model_dtype,
|
| 448 |
+
device=device,
|
| 449 |
+
generator=generator,
|
| 450 |
+
)
|
| 451 |
+
timesteps = self.scheduler.set_timesteps(
|
| 452 |
+
num_inference_steps, device=device, mode=mode, timestep_shift=timestep_shift
|
| 453 |
+
)
|
| 454 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(self.scheduler, generator=generator)
|
| 455 |
+
|
| 456 |
+
for index, timestep in enumerate(timesteps[:-1]):
|
| 457 |
+
next_timestep = timesteps[index + 1]
|
| 458 |
+
t_value = float(timestep)
|
| 459 |
+
guidance_active = guidance_scale > 1.0 and guidance_interval[0] <= t_value <= guidance_interval[1]
|
| 460 |
+
if cfg_interval_start is not None and t_value < cfg_interval_start:
|
| 461 |
+
guidance_active = False
|
| 462 |
+
|
| 463 |
+
if guidance_active:
|
| 464 |
+
model_input = torch.cat([latents, latents], dim=0)
|
| 465 |
+
labels = torch.cat([class_labels_tensor, null_labels], dim=0)
|
| 466 |
+
else:
|
| 467 |
+
model_input = latents
|
| 468 |
+
labels = class_labels_tensor
|
| 469 |
+
|
| 470 |
+
timestep_batch = torch.full((labels.shape[0],), t_value, device=device, dtype=model_dtype)
|
| 471 |
+
model_output = self.transformers(
|
| 472 |
+
model_input.to(dtype=model_dtype),
|
| 473 |
+
timestep=timestep_batch,
|
| 474 |
+
class_labels=labels,
|
| 475 |
+
return_dict=True,
|
| 476 |
+
).sample
|
| 477 |
+
model_output = self._apply_cfg(model_output, guidance_scale, guidance_active, cfg_channels)
|
| 478 |
+
|
| 479 |
+
if heun and mode == "ode" and index < len(timesteps) - 2:
|
| 480 |
+
provisional = self.scheduler.step(
|
| 481 |
+
model_output,
|
| 482 |
+
timestep[None],
|
| 483 |
+
latents,
|
| 484 |
+
next_timestep[None],
|
| 485 |
+
**extra_step_kwargs,
|
| 486 |
+
).prev_sample
|
| 487 |
+
if guidance_active:
|
| 488 |
+
prime_input = torch.cat([provisional, provisional], dim=0)
|
| 489 |
+
prime_labels = torch.cat([class_labels_tensor, null_labels], dim=0)
|
| 490 |
+
else:
|
| 491 |
+
prime_input = provisional
|
| 492 |
+
prime_labels = class_labels_tensor
|
| 493 |
+
next_timestep_batch = torch.full(
|
| 494 |
+
(prime_labels.shape[0],), float(next_timestep), device=device, dtype=model_dtype
|
| 495 |
+
)
|
| 496 |
+
next_output = self.transformers(
|
| 497 |
+
prime_input.to(dtype=model_dtype),
|
| 498 |
+
timestep=next_timestep_batch,
|
| 499 |
+
class_labels=prime_labels,
|
| 500 |
+
return_dict=True,
|
| 501 |
+
).sample
|
| 502 |
+
next_output = self._apply_cfg(next_output, guidance_scale, guidance_active, cfg_channels)
|
| 503 |
+
latents = self.scheduler.step_heun(
|
| 504 |
+
model_output, next_output, timestep[None], latents, next_timestep[None]
|
| 505 |
+
).prev_sample
|
| 506 |
+
else:
|
| 507 |
+
latents = self.scheduler.step(
|
| 508 |
+
model_output,
|
| 509 |
+
timestep[None],
|
| 510 |
+
latents,
|
| 511 |
+
next_timestep[None],
|
| 512 |
+
**extra_step_kwargs,
|
| 513 |
+
).prev_sample
|
| 514 |
+
|
| 515 |
+
image = self.decode_latents(
|
| 516 |
+
latents.to(dtype=model_dtype),
|
| 517 |
+
output_type=output_type,
|
| 518 |
+
latent_mean=latent_mean,
|
| 519 |
+
latent_std=latent_std,
|
| 520 |
+
latent_multiplier=latent_multiplier,
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
self.maybe_free_model_hooks()
|
| 524 |
+
if not return_dict:
|
| 525 |
+
return (image,)
|
| 526 |
+
return ImagePipelineOutput(images=image)
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
# Backward-compatible alias used by earlier PAE-diffusers releases.
|
| 530 |
+
PAEPipelineOutput = ImagePipelineOutput
|
pae-mae-large-d32/scheduler/scheduler_config.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "PAEFlowMatchScheduler",
|
| 3 |
+
"_diffusers_version": "0.31.0",
|
| 4 |
+
"mode": "ode",
|
| 5 |
+
"path_type": "linear",
|
| 6 |
+
"num_train_timesteps": 1000
|
| 7 |
+
}
|
pae-mae-large-d32/scheduler/scheduling_flow_match_pae.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from typing import Optional, Tuple
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 14 |
+
from diffusers.schedulers.scheduling_utils import SchedulerMixin
|
| 15 |
+
from diffusers.utils import BaseOutput
|
| 16 |
+
except Exception: # pragma: no cover - importable without an installed diffusers checkout.
|
| 17 |
+
class BaseOutput(dict):
|
| 18 |
+
def __post_init__(self):
|
| 19 |
+
self.update(self.__dict__)
|
| 20 |
+
|
| 21 |
+
class ConfigMixin:
|
| 22 |
+
config_name = "scheduler_config.json"
|
| 23 |
+
|
| 24 |
+
class SchedulerMixin:
|
| 25 |
+
pass
|
| 26 |
+
|
| 27 |
+
def register_to_config(init):
|
| 28 |
+
return init
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass
|
| 32 |
+
class PAEFlowMatchSchedulerOutput(BaseOutput):
|
| 33 |
+
prev_sample: torch.FloatTensor
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class PAEFlowMatchScheduler(SchedulerMixin, ConfigMixin):
|
| 37 |
+
"""
|
| 38 |
+
Flow-matching ODE/SDE scheduler used by PAE + LightningDiT pipelines.
|
| 39 |
+
|
| 40 |
+
The model predicts velocity with a linear path by default. ODE timesteps run from 0 to 1
|
| 41 |
+
(noise to data), matching LightningDiT transport sampling.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
config_name = "scheduler_config.json"
|
| 45 |
+
order = 1
|
| 46 |
+
|
| 47 |
+
@register_to_config
|
| 48 |
+
def __init__(
|
| 49 |
+
self,
|
| 50 |
+
mode: str = "ode",
|
| 51 |
+
path_type: str = "linear",
|
| 52 |
+
num_train_timesteps: int = 1000,
|
| 53 |
+
):
|
| 54 |
+
if mode not in {"ode", "sde"}:
|
| 55 |
+
raise ValueError("mode must be either 'ode' or 'sde'.")
|
| 56 |
+
if path_type not in {"linear", "cosine"}:
|
| 57 |
+
raise ValueError("path_type must be either 'linear' or 'cosine'.")
|
| 58 |
+
self.mode = mode
|
| 59 |
+
self.path_type = path_type
|
| 60 |
+
self.num_train_timesteps = num_train_timesteps
|
| 61 |
+
# Native NiT integrates in float64 for better numerical stability.
|
| 62 |
+
self.timesteps = torch.from_numpy(np.linspace(0.0, 1.0, num_train_timesteps + 1)).to(dtype=torch.float64)
|
| 63 |
+
|
| 64 |
+
@staticmethod
|
| 65 |
+
def _apply_timestep_shift(timesteps: torch.Tensor, timestep_shift: float) -> torch.Tensor:
|
| 66 |
+
if timestep_shift <= 0:
|
| 67 |
+
return timesteps
|
| 68 |
+
return timestep_shift * timesteps / (1 + (timestep_shift - 1) * timesteps)
|
| 69 |
+
|
| 70 |
+
def set_timesteps(
|
| 71 |
+
self,
|
| 72 |
+
num_inference_steps: int,
|
| 73 |
+
device: Optional[torch.device] = None,
|
| 74 |
+
mode: Optional[str] = None,
|
| 75 |
+
timestep_shift: float = 0.0,
|
| 76 |
+
):
|
| 77 |
+
mode = mode or self.mode
|
| 78 |
+
dtype = self.timesteps.dtype
|
| 79 |
+
if mode == "sde":
|
| 80 |
+
timesteps = torch.linspace(1.0, 0.04, num_inference_steps, dtype=dtype)
|
| 81 |
+
timesteps = torch.cat([timesteps, torch.zeros(1, dtype=dtype)])
|
| 82 |
+
elif mode == "ode":
|
| 83 |
+
timesteps = torch.linspace(0.0, 1.0, num_inference_steps + 1, dtype=dtype)
|
| 84 |
+
timesteps = self._apply_timestep_shift(timesteps, timestep_shift)
|
| 85 |
+
else:
|
| 86 |
+
raise ValueError("mode must be either 'ode' or 'sde'.")
|
| 87 |
+
self.mode = mode
|
| 88 |
+
self.timesteps = timesteps.to(device=device)
|
| 89 |
+
return self.timesteps
|
| 90 |
+
|
| 91 |
+
@staticmethod
|
| 92 |
+
def _expand_t_like_sample(timestep: torch.Tensor, sample: torch.Tensor, image_sizes: torch.LongTensor):
|
| 93 |
+
dims = [1] * (sample.ndim - 1)
|
| 94 |
+
seqlens = image_sizes[:, 0] * image_sizes[:, 1]
|
| 95 |
+
if timestep.numel() == 1:
|
| 96 |
+
timestep = timestep.repeat(image_sizes.shape[0])
|
| 97 |
+
return torch.cat(
|
| 98 |
+
[timestep[i].reshape(1, *dims).repeat(int(seqlens[i]), *dims) for i in range(image_sizes.shape[0])]
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
def _get_score_from_velocity(
|
| 102 |
+
self,
|
| 103 |
+
model_output: torch.Tensor,
|
| 104 |
+
sample: torch.Tensor,
|
| 105 |
+
timestep: torch.Tensor,
|
| 106 |
+
image_sizes: torch.LongTensor,
|
| 107 |
+
):
|
| 108 |
+
timestep = self._expand_t_like_sample(timestep, sample, image_sizes)
|
| 109 |
+
if self.path_type == "linear":
|
| 110 |
+
alpha_t, d_alpha_t = 1 - timestep, torch.ones_like(timestep) * -1
|
| 111 |
+
sigma_t, d_sigma_t = timestep, torch.ones_like(timestep)
|
| 112 |
+
elif self.path_type == "cosine":
|
| 113 |
+
alpha_t = torch.cos(timestep * np.pi / 2)
|
| 114 |
+
sigma_t = torch.sin(timestep * np.pi / 2)
|
| 115 |
+
d_alpha_t = -np.pi / 2 * torch.sin(timestep * np.pi / 2)
|
| 116 |
+
d_sigma_t = np.pi / 2 * torch.cos(timestep * np.pi / 2)
|
| 117 |
+
else:
|
| 118 |
+
raise ValueError(f"Unsupported path_type: {self.path_type}")
|
| 119 |
+
reverse_alpha_ratio = alpha_t / d_alpha_t
|
| 120 |
+
variance = sigma_t**2 - reverse_alpha_ratio * d_sigma_t * sigma_t
|
| 121 |
+
return (reverse_alpha_ratio * model_output - sample) / variance
|
| 122 |
+
|
| 123 |
+
@staticmethod
|
| 124 |
+
def _compute_diffusion(timestep: torch.Tensor):
|
| 125 |
+
return 2 * timestep
|
| 126 |
+
|
| 127 |
+
@staticmethod
|
| 128 |
+
def _promote_dtypes(*tensors: torch.Tensor) -> torch.dtype:
|
| 129 |
+
dtype = None
|
| 130 |
+
for tensor in tensors:
|
| 131 |
+
if tensor.is_floating_point() or tensor.is_complex():
|
| 132 |
+
dtype = tensor.dtype if dtype is None else torch.promote_types(dtype, tensor.dtype)
|
| 133 |
+
return dtype if dtype is not None else torch.get_default_dtype()
|
| 134 |
+
|
| 135 |
+
def step(
|
| 136 |
+
self,
|
| 137 |
+
model_output: torch.Tensor,
|
| 138 |
+
timestep: torch.Tensor,
|
| 139 |
+
sample: torch.Tensor,
|
| 140 |
+
next_timestep: torch.Tensor,
|
| 141 |
+
image_sizes: Optional[torch.LongTensor] = None,
|
| 142 |
+
generator: Optional[torch.Generator] = None,
|
| 143 |
+
return_dict: bool = True,
|
| 144 |
+
) -> PAEFlowMatchSchedulerOutput:
|
| 145 |
+
sample_dtype = sample.dtype
|
| 146 |
+
compute_dtype = torch.float64
|
| 147 |
+
sample = sample.to(dtype=compute_dtype)
|
| 148 |
+
model_output = model_output.to(dtype=compute_dtype)
|
| 149 |
+
timestep = timestep.to(device=sample.device, dtype=compute_dtype).flatten()
|
| 150 |
+
next_timestep = next_timestep.to(device=sample.device, dtype=compute_dtype).flatten()
|
| 151 |
+
|
| 152 |
+
if self.mode == "ode":
|
| 153 |
+
prev_sample = sample + (next_timestep[0] - timestep[0]) * model_output
|
| 154 |
+
else:
|
| 155 |
+
if image_sizes is None:
|
| 156 |
+
batch = sample.shape[0]
|
| 157 |
+
side = int(sample.shape[-1])
|
| 158 |
+
image_sizes = torch.tensor([[side, side]] * batch, device=sample.device, dtype=torch.long)
|
| 159 |
+
image_sizes = image_sizes.to(device=sample.device, dtype=torch.long)
|
| 160 |
+
diffusion = self._compute_diffusion(timestep[0])
|
| 161 |
+
score = self._get_score_from_velocity(model_output, sample, timestep, image_sizes)
|
| 162 |
+
drift = model_output - 0.5 * diffusion * score
|
| 163 |
+
dt = next_timestep[0] - timestep[0]
|
| 164 |
+
if torch.allclose(next_timestep[0], torch.zeros_like(next_timestep[0])):
|
| 165 |
+
prev_sample = sample + drift * dt
|
| 166 |
+
else:
|
| 167 |
+
if generator is not None:
|
| 168 |
+
noise = torch.randn(sample.shape, generator=generator, device=sample.device, dtype=sample.dtype)
|
| 169 |
+
else:
|
| 170 |
+
noise = torch.randn_like(sample)
|
| 171 |
+
prev_sample = sample + drift * dt + torch.sqrt(diffusion) * noise * torch.sqrt(torch.abs(dt))
|
| 172 |
+
|
| 173 |
+
prev_sample = prev_sample.to(sample_dtype)
|
| 174 |
+
if not return_dict:
|
| 175 |
+
return (prev_sample,)
|
| 176 |
+
return PAEFlowMatchSchedulerOutput(prev_sample=prev_sample)
|
| 177 |
+
|
| 178 |
+
def step_heun(
|
| 179 |
+
self,
|
| 180 |
+
model_output: torch.Tensor,
|
| 181 |
+
next_model_output: torch.Tensor,
|
| 182 |
+
timestep: torch.Tensor,
|
| 183 |
+
sample: torch.Tensor,
|
| 184 |
+
next_timestep: torch.Tensor,
|
| 185 |
+
return_dict: bool = True,
|
| 186 |
+
) -> PAEFlowMatchSchedulerOutput:
|
| 187 |
+
if self.mode != "ode":
|
| 188 |
+
raise ValueError("Heun correction is only defined for ODE sampling.")
|
| 189 |
+
sample_dtype = sample.dtype
|
| 190 |
+
compute_dtype = torch.float64
|
| 191 |
+
sample = sample.to(dtype=compute_dtype)
|
| 192 |
+
model_output = model_output.to(dtype=compute_dtype)
|
| 193 |
+
next_model_output = next_model_output.to(dtype=compute_dtype)
|
| 194 |
+
timestep = timestep.to(device=sample.device, dtype=compute_dtype).flatten()
|
| 195 |
+
next_timestep = next_timestep.to(device=sample.device, dtype=compute_dtype).flatten()
|
| 196 |
+
prev_sample = sample + (next_timestep[0] - timestep[0]) * (0.5 * model_output + 0.5 * next_model_output)
|
| 197 |
+
prev_sample = prev_sample.to(sample_dtype)
|
| 198 |
+
if not return_dict:
|
| 199 |
+
return (prev_sample,)
|
| 200 |
+
return PAEFlowMatchSchedulerOutput(prev_sample=prev_sample)
|
pae-mae-large-d32/transformers/config.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "LightningDiT2DModel",
|
| 3 |
+
"depth": 28,
|
| 4 |
+
"hidden_size": 1152,
|
| 5 |
+
"in_channels": 32,
|
| 6 |
+
"input_size": 16,
|
| 7 |
+
"num_classes": 1000,
|
| 8 |
+
"num_heads": 16,
|
| 9 |
+
"patch_size": 1,
|
| 10 |
+
"use_qknorm": true,
|
| 11 |
+
"use_rmsnorm": true,
|
| 12 |
+
"use_rope": true,
|
| 13 |
+
"use_swiglu": true,
|
| 14 |
+
"wo_shift": false
|
| 15 |
+
}
|
pae-mae-large-d32/transformers/diffusion_pytorch_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:acc704ff0e386b2c71b4a576b3d5e9bff103c8047b61dad3f9dfaeb70d27c750
|
| 3 |
+
size 2701230752
|
pae-mae-large-d32/transformers/transformer_lightning_dit.py
ADDED
|
@@ -0,0 +1,794 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from torch import nn
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class RMSNorm(torch.nn.Module):
|
| 9 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
| 10 |
+
super().__init__()
|
| 11 |
+
self.eps = eps
|
| 12 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 13 |
+
|
| 14 |
+
def _norm(self, x: torch.Tensor) -> torch.Tensor:
|
| 15 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 16 |
+
|
| 17 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 18 |
+
output = self._norm(x.float()).type_as(x)
|
| 19 |
+
return output * self.weight
|
| 20 |
+
|
| 21 |
+
from math import pi
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
from torch import nn
|
| 25 |
+
|
| 26 |
+
from einops import rearrange, repeat
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def broadcat(tensors, dim = -1):
|
| 31 |
+
num_tensors = len(tensors)
|
| 32 |
+
shape_lens = set(list(map(lambda t: len(t.shape), tensors)))
|
| 33 |
+
assert len(shape_lens) == 1, 'tensors must all have the same number of dimensions'
|
| 34 |
+
shape_len = list(shape_lens)[0]
|
| 35 |
+
dim = (dim + shape_len) if dim < 0 else dim
|
| 36 |
+
dims = list(zip(*map(lambda t: list(t.shape), tensors)))
|
| 37 |
+
expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim]
|
| 38 |
+
assert all([*map(lambda t: len(set(t[1])) <= 2, expandable_dims)]), 'invalid dimensions for broadcastable concatentation'
|
| 39 |
+
max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims))
|
| 40 |
+
expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims))
|
| 41 |
+
expanded_dims.insert(dim, (dim, dims[dim]))
|
| 42 |
+
expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims)))
|
| 43 |
+
tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes)))
|
| 44 |
+
return torch.cat(tensors, dim = dim)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def rotate_half(x):
|
| 49 |
+
x = rearrange(x, '... (d r) -> ... d r', r = 2)
|
| 50 |
+
x1, x2 = x.unbind(dim = -1)
|
| 51 |
+
x = torch.stack((-x2, x1), dim = -1)
|
| 52 |
+
return rearrange(x, '... d r -> ... (d r)')
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class VisionRotaryEmbedding(nn.Module):
|
| 57 |
+
def __init__(
|
| 58 |
+
self,
|
| 59 |
+
dim,
|
| 60 |
+
pt_seq_len,
|
| 61 |
+
ft_seq_len=None,
|
| 62 |
+
custom_freqs = None,
|
| 63 |
+
freqs_for = 'lang',
|
| 64 |
+
theta = 10000,
|
| 65 |
+
max_freq = 10,
|
| 66 |
+
num_freqs = 1,
|
| 67 |
+
):
|
| 68 |
+
super().__init__()
|
| 69 |
+
if custom_freqs:
|
| 70 |
+
freqs = custom_freqs
|
| 71 |
+
elif freqs_for == 'lang':
|
| 72 |
+
freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim))
|
| 73 |
+
elif freqs_for == 'pixel':
|
| 74 |
+
freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi
|
| 75 |
+
elif freqs_for == 'constant':
|
| 76 |
+
freqs = torch.ones(num_freqs).float()
|
| 77 |
+
else:
|
| 78 |
+
raise ValueError(f'unknown modality {freqs_for}')
|
| 79 |
+
|
| 80 |
+
if ft_seq_len is None: ft_seq_len = pt_seq_len
|
| 81 |
+
t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len
|
| 82 |
+
|
| 83 |
+
freqs_h = torch.einsum('..., f -> ... f', t, freqs)
|
| 84 |
+
freqs_h = repeat(freqs_h, '... n -> ... (n r)', r = 2)
|
| 85 |
+
|
| 86 |
+
freqs_w = torch.einsum('..., f -> ... f', t, freqs)
|
| 87 |
+
freqs_w = repeat(freqs_w, '... n -> ... (n r)', r = 2)
|
| 88 |
+
|
| 89 |
+
freqs = broadcat((freqs_h[:, None, :], freqs_w[None, :, :]), dim = -1)
|
| 90 |
+
|
| 91 |
+
self.register_buffer("freqs_cos", freqs.cos())
|
| 92 |
+
self.register_buffer("freqs_sin", freqs.sin())
|
| 93 |
+
|
| 94 |
+
# print('======== shape of rope freq', self.freqs_cos.shape, '========')
|
| 95 |
+
|
| 96 |
+
def forward(self, t, start_index = 0):
|
| 97 |
+
rot_dim = self.freqs_cos.shape[-1]
|
| 98 |
+
end_index = start_index + rot_dim
|
| 99 |
+
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}'
|
| 100 |
+
t_left, t, t_right = t[..., :start_index], t[..., start_index:end_index], t[..., end_index:]
|
| 101 |
+
t = (t * self.freqs_cos) + (rotate_half(t) * self.freqs_sin)
|
| 102 |
+
return torch.cat((t_left, t, t_right), dim = -1)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class VisionRotaryEmbeddingFast(nn.Module):
|
| 107 |
+
def __init__(
|
| 108 |
+
self,
|
| 109 |
+
dim,
|
| 110 |
+
pt_seq_len=16,
|
| 111 |
+
ft_seq_len=None,
|
| 112 |
+
custom_freqs = None,
|
| 113 |
+
freqs_for = 'lang',
|
| 114 |
+
theta = 10000,
|
| 115 |
+
max_freq = 10,
|
| 116 |
+
num_freqs = 1,
|
| 117 |
+
):
|
| 118 |
+
super().__init__()
|
| 119 |
+
if custom_freqs:
|
| 120 |
+
freqs = custom_freqs
|
| 121 |
+
elif freqs_for == 'lang':
|
| 122 |
+
freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim))
|
| 123 |
+
elif freqs_for == 'pixel':
|
| 124 |
+
freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi
|
| 125 |
+
elif freqs_for == 'constant':
|
| 126 |
+
freqs = torch.ones(num_freqs).float()
|
| 127 |
+
else:
|
| 128 |
+
raise ValueError(f'unknown modality {freqs_for}')
|
| 129 |
+
|
| 130 |
+
if ft_seq_len is None: ft_seq_len = pt_seq_len
|
| 131 |
+
t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len
|
| 132 |
+
|
| 133 |
+
freqs = torch.einsum('..., f -> ... f', t, freqs)
|
| 134 |
+
freqs = repeat(freqs, '... n -> ... (n r)', r = 2)
|
| 135 |
+
freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim = -1)
|
| 136 |
+
|
| 137 |
+
freqs_cos = freqs.cos().view(-1, freqs.shape[-1])
|
| 138 |
+
freqs_sin = freqs.sin().view(-1, freqs.shape[-1])
|
| 139 |
+
|
| 140 |
+
self.register_buffer("freqs_cos", freqs_cos)
|
| 141 |
+
self.register_buffer("freqs_sin", freqs_sin)
|
| 142 |
+
|
| 143 |
+
# print('======== shape of rope freq', self.freqs_cos.shape, '========')
|
| 144 |
+
|
| 145 |
+
def forward(self, t): return t * self.freqs_cos + rotate_half(t) * self.freqs_sin
|
| 146 |
+
|
| 147 |
+
import os
|
| 148 |
+
import torch
|
| 149 |
+
from typing import Callable, Optional
|
| 150 |
+
import warnings
|
| 151 |
+
|
| 152 |
+
from torch import Tensor, nn
|
| 153 |
+
import torch.nn.functional as F
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class SwiGLUFFN(nn.Module):
|
| 157 |
+
def __init__(
|
| 158 |
+
self,
|
| 159 |
+
in_features: int,
|
| 160 |
+
hidden_features: Optional[int] = None,
|
| 161 |
+
out_features: Optional[int] = None,
|
| 162 |
+
act_layer: Callable[..., nn.Module] = None,
|
| 163 |
+
drop: float = 0.0,
|
| 164 |
+
bias: bool = True,
|
| 165 |
+
) -> None:
|
| 166 |
+
super().__init__()
|
| 167 |
+
out_features = out_features or in_features
|
| 168 |
+
hidden_features = hidden_features or in_features
|
| 169 |
+
self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias)
|
| 170 |
+
self.w3 = nn.Linear(hidden_features, out_features, bias=bias)
|
| 171 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 172 |
+
x12 = self.w12(x)
|
| 173 |
+
x1, x2 = x12.chunk(2, dim=-1)
|
| 174 |
+
hidden = F.silu(x1) * x2
|
| 175 |
+
return self.w3(hidden)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None
|
| 179 |
+
try:
|
| 180 |
+
if XFORMERS_ENABLED:
|
| 181 |
+
from xformers.ops import SwiGLU
|
| 182 |
+
|
| 183 |
+
XFORMERS_AVAILABLE = True
|
| 184 |
+
# warnings.warn("xFormers is available (SwiGLU)")
|
| 185 |
+
else:
|
| 186 |
+
# warnings.warn("xFormers is disabled (SwiGLU)")
|
| 187 |
+
raise ImportError
|
| 188 |
+
except ImportError:
|
| 189 |
+
SwiGLU = SwiGLUFFN
|
| 190 |
+
XFORMERS_AVAILABLE = False
|
| 191 |
+
|
| 192 |
+
# warnings.warn("xFormers is not available (SwiGLU)")
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class SwiGLUFFNFused(SwiGLU):
|
| 196 |
+
def __init__(
|
| 197 |
+
self,
|
| 198 |
+
in_features: int,
|
| 199 |
+
hidden_features: Optional[int] = None,
|
| 200 |
+
out_features: Optional[int] = None,
|
| 201 |
+
act_layer: Callable[..., nn.Module] = None,
|
| 202 |
+
drop: float = 0.0,
|
| 203 |
+
bias: bool = True,
|
| 204 |
+
) -> None:
|
| 205 |
+
out_features = out_features or in_features
|
| 206 |
+
hidden_features = hidden_features or in_features
|
| 207 |
+
hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
|
| 208 |
+
super().__init__(
|
| 209 |
+
in_features=in_features,
|
| 210 |
+
hidden_features=hidden_features,
|
| 211 |
+
out_features=out_features,
|
| 212 |
+
bias=bias,
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
from dataclasses import dataclass
|
| 216 |
+
from typing import Optional, Tuple, Union
|
| 217 |
+
|
| 218 |
+
import torch
|
| 219 |
+
|
| 220 |
+
try:
|
| 221 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 222 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 223 |
+
from diffusers.utils import BaseOutput
|
| 224 |
+
except Exception: # pragma: no cover
|
| 225 |
+
class BaseOutput(dict):
|
| 226 |
+
def __post_init__(self):
|
| 227 |
+
self.update(self.__dict__)
|
| 228 |
+
|
| 229 |
+
class ConfigMixin:
|
| 230 |
+
config_name = "config.json"
|
| 231 |
+
|
| 232 |
+
class ModelMixin(torch.nn.Module):
|
| 233 |
+
pass
|
| 234 |
+
|
| 235 |
+
def register_to_config(init):
|
| 236 |
+
return init
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
@dataclass
|
| 240 |
+
class LightningDiT2DModelOutput(BaseOutput):
|
| 241 |
+
sample: torch.FloatTensor
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
import os
|
| 245 |
+
import math
|
| 246 |
+
import numpy as np
|
| 247 |
+
|
| 248 |
+
import torch
|
| 249 |
+
import torch.nn as nn
|
| 250 |
+
import torch.nn.functional as F
|
| 251 |
+
from torch.utils.checkpoint import checkpoint
|
| 252 |
+
|
| 253 |
+
from timm.models.vision_transformer import PatchEmbed, Mlp
|
| 254 |
+
def modulate(x, shift, scale):
|
| 255 |
+
if shift is None:
|
| 256 |
+
return x * (1 + scale.unsqueeze(1))
|
| 257 |
+
return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
|
| 258 |
+
|
| 259 |
+
class Attention(nn.Module):
|
| 260 |
+
"""
|
| 261 |
+
Attention module of LightningDiT.
|
| 262 |
+
"""
|
| 263 |
+
def __init__(
|
| 264 |
+
self,
|
| 265 |
+
dim: int,
|
| 266 |
+
num_heads: int = 8,
|
| 267 |
+
qkv_bias: bool = False,
|
| 268 |
+
qk_norm: bool = False,
|
| 269 |
+
attn_drop: float = 0.,
|
| 270 |
+
proj_drop: float = 0.,
|
| 271 |
+
norm_layer: nn.Module = nn.LayerNorm,
|
| 272 |
+
fused_attn: bool = True,
|
| 273 |
+
use_rmsnorm: bool = False,
|
| 274 |
+
) -> None:
|
| 275 |
+
super().__init__()
|
| 276 |
+
assert dim % num_heads == 0, 'dim should be divisible by num_heads'
|
| 277 |
+
|
| 278 |
+
self.num_heads = num_heads
|
| 279 |
+
self.head_dim = dim // num_heads
|
| 280 |
+
self.scale = self.head_dim ** -0.5
|
| 281 |
+
self.fused_attn = fused_attn
|
| 282 |
+
|
| 283 |
+
if use_rmsnorm:
|
| 284 |
+
norm_layer = RMSNorm
|
| 285 |
+
|
| 286 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
| 287 |
+
self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
|
| 288 |
+
self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
|
| 289 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 290 |
+
self.proj = nn.Linear(dim, dim)
|
| 291 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 292 |
+
|
| 293 |
+
def forward(self, x: torch.Tensor, rope=None) -> torch.Tensor:
|
| 294 |
+
B, N, C = x.shape
|
| 295 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
|
| 296 |
+
q, k, v = qkv.unbind(0)
|
| 297 |
+
q, k = self.q_norm(q), self.k_norm(k)
|
| 298 |
+
|
| 299 |
+
if rope is not None:
|
| 300 |
+
q = rope(q)
|
| 301 |
+
k = rope(k)
|
| 302 |
+
|
| 303 |
+
if self.fused_attn:
|
| 304 |
+
x = F.scaled_dot_product_attention(
|
| 305 |
+
q, k, v,
|
| 306 |
+
dropout_p=self.attn_drop.p if self.training else 0.,
|
| 307 |
+
)
|
| 308 |
+
else:
|
| 309 |
+
q = q * self.scale
|
| 310 |
+
attn = q @ k.transpose(-2, -1)
|
| 311 |
+
attn = attn.softmax(dim=-1)
|
| 312 |
+
attn = self.attn_drop(attn)
|
| 313 |
+
x = attn @ v
|
| 314 |
+
|
| 315 |
+
x = x.transpose(1, 2).reshape(B, N, C)
|
| 316 |
+
x = self.proj(x)
|
| 317 |
+
x = self.proj_drop(x)
|
| 318 |
+
return x
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
class TimestepEmbedder(nn.Module):
|
| 322 |
+
"""
|
| 323 |
+
Embeds scalar timesteps into vector representations.
|
| 324 |
+
Same as DiT.
|
| 325 |
+
"""
|
| 326 |
+
def __init__(self, hidden_size: int, frequency_embedding_size: int = 256) -> None:
|
| 327 |
+
super().__init__()
|
| 328 |
+
self.frequency_embedding_size = frequency_embedding_size
|
| 329 |
+
self.mlp = nn.Sequential(
|
| 330 |
+
nn.Linear(frequency_embedding_size, hidden_size, bias=True),
|
| 331 |
+
nn.SiLU(),
|
| 332 |
+
nn.Linear(hidden_size, hidden_size, bias=True),
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
@staticmethod
|
| 336 |
+
def timestep_embedding(t: torch.Tensor, dim: int, max_period: int = 10000) -> torch.Tensor:
|
| 337 |
+
"""
|
| 338 |
+
Create sinusoidal timestep embeddings.
|
| 339 |
+
Args:
|
| 340 |
+
t: A 1-D Tensor of N indices, one per batch element. These may be fractional.
|
| 341 |
+
dim: The dimension of the output.
|
| 342 |
+
max_period: Controls the minimum frequency of the embeddings.
|
| 343 |
+
Returns:
|
| 344 |
+
An (N, D) Tensor of positional embeddings.
|
| 345 |
+
"""
|
| 346 |
+
# https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
|
| 347 |
+
half = dim // 2
|
| 348 |
+
freqs = torch.exp(
|
| 349 |
+
-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
|
| 350 |
+
).to(device=t.device)
|
| 351 |
+
|
| 352 |
+
args = t[:, None].float() * freqs[None]
|
| 353 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 354 |
+
|
| 355 |
+
if dim % 2:
|
| 356 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
| 357 |
+
|
| 358 |
+
return embedding
|
| 359 |
+
def forward(self, t: torch.Tensor) -> torch.Tensor:
|
| 360 |
+
t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
|
| 361 |
+
t_emb = self.mlp(t_freq)
|
| 362 |
+
return t_emb
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
class LabelEmbedder(nn.Module):
|
| 366 |
+
"""
|
| 367 |
+
Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.
|
| 368 |
+
Same as DiT.
|
| 369 |
+
"""
|
| 370 |
+
def __init__(self, num_classes, hidden_size, dropout_prob):
|
| 371 |
+
super().__init__()
|
| 372 |
+
use_cfg_embedding = dropout_prob > 0
|
| 373 |
+
self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size)
|
| 374 |
+
self.num_classes = num_classes
|
| 375 |
+
self.dropout_prob = dropout_prob
|
| 376 |
+
|
| 377 |
+
def token_drop(self, labels, force_drop_ids=None):
|
| 378 |
+
"""
|
| 379 |
+
Drops labels to enable classifier-free guidance.
|
| 380 |
+
"""
|
| 381 |
+
if force_drop_ids is None:
|
| 382 |
+
drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob
|
| 383 |
+
else:
|
| 384 |
+
drop_ids = force_drop_ids == 1
|
| 385 |
+
labels = torch.where(drop_ids, self.num_classes, labels)
|
| 386 |
+
return labels
|
| 387 |
+
def forward(self, labels, train, force_drop_ids=None):
|
| 388 |
+
use_dropout = self.dropout_prob > 0
|
| 389 |
+
if (train and use_dropout) or (force_drop_ids is not None):
|
| 390 |
+
labels = self.token_drop(labels, force_drop_ids)
|
| 391 |
+
embeddings = self.embedding_table(labels)
|
| 392 |
+
return embeddings
|
| 393 |
+
|
| 394 |
+
class LightningDiTBlock(nn.Module):
|
| 395 |
+
"""
|
| 396 |
+
Lightning DiT Block. We add features including:
|
| 397 |
+
- ROPE
|
| 398 |
+
- QKNorm
|
| 399 |
+
- RMSNorm
|
| 400 |
+
- SwiGLU
|
| 401 |
+
- No shift AdaLN.
|
| 402 |
+
Not all of them are used in the final model, please refer to the paper for more details.
|
| 403 |
+
"""
|
| 404 |
+
def __init__(
|
| 405 |
+
self,
|
| 406 |
+
hidden_size,
|
| 407 |
+
num_heads,
|
| 408 |
+
mlp_ratio=4.0,
|
| 409 |
+
use_qknorm=False,
|
| 410 |
+
use_swiglu=False,
|
| 411 |
+
use_rmsnorm=False,
|
| 412 |
+
wo_shift=False,
|
| 413 |
+
**block_kwargs
|
| 414 |
+
):
|
| 415 |
+
super().__init__()
|
| 416 |
+
|
| 417 |
+
# Initialize normalization layers
|
| 418 |
+
if not use_rmsnorm:
|
| 419 |
+
self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 420 |
+
self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 421 |
+
else:
|
| 422 |
+
self.norm1 = RMSNorm(hidden_size)
|
| 423 |
+
self.norm2 = RMSNorm(hidden_size)
|
| 424 |
+
|
| 425 |
+
# Initialize attention layer
|
| 426 |
+
self.attn = Attention(
|
| 427 |
+
hidden_size,
|
| 428 |
+
num_heads=num_heads,
|
| 429 |
+
qkv_bias=True,
|
| 430 |
+
qk_norm=use_qknorm,
|
| 431 |
+
use_rmsnorm=use_rmsnorm,
|
| 432 |
+
**block_kwargs
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
# Initialize MLP layer
|
| 436 |
+
mlp_hidden_dim = int(hidden_size * mlp_ratio)
|
| 437 |
+
approx_gelu = lambda: nn.GELU(approximate="tanh")
|
| 438 |
+
if use_swiglu:
|
| 439 |
+
# here we did not use SwiGLU from xformers because it is not compatible with torch.compile for now.
|
| 440 |
+
self.mlp = SwiGLUFFN(hidden_size, int(2/3 * mlp_hidden_dim))
|
| 441 |
+
else:
|
| 442 |
+
self.mlp = Mlp(
|
| 443 |
+
in_features=hidden_size,
|
| 444 |
+
hidden_features=mlp_hidden_dim,
|
| 445 |
+
act_layer=approx_gelu,
|
| 446 |
+
drop=0
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
# Initialize AdaLN modulation
|
| 450 |
+
if wo_shift:
|
| 451 |
+
self.adaLN_modulation = nn.Sequential(
|
| 452 |
+
nn.SiLU(),
|
| 453 |
+
nn.Linear(hidden_size, 4 * hidden_size, bias=True)
|
| 454 |
+
)
|
| 455 |
+
else:
|
| 456 |
+
self.adaLN_modulation = nn.Sequential(
|
| 457 |
+
nn.SiLU(),
|
| 458 |
+
nn.Linear(hidden_size, 6 * hidden_size, bias=True)
|
| 459 |
+
)
|
| 460 |
+
self.wo_shift = wo_shift
|
| 461 |
+
def forward(self, x, c, feat_rope=None):
|
| 462 |
+
if self.wo_shift:
|
| 463 |
+
scale_msa, gate_msa, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(4, dim=1)
|
| 464 |
+
shift_msa = None
|
| 465 |
+
shift_mlp = None
|
| 466 |
+
else:
|
| 467 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=1)
|
| 468 |
+
|
| 469 |
+
x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa), rope=feat_rope)
|
| 470 |
+
x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))
|
| 471 |
+
return x
|
| 472 |
+
|
| 473 |
+
class FinalLayer(nn.Module):
|
| 474 |
+
"""
|
| 475 |
+
The final layer of LightningDiT.
|
| 476 |
+
"""
|
| 477 |
+
def __init__(self, hidden_size, patch_size, out_channels, use_rmsnorm=False):
|
| 478 |
+
super().__init__()
|
| 479 |
+
if not use_rmsnorm:
|
| 480 |
+
self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 481 |
+
else:
|
| 482 |
+
self.norm_final = RMSNorm(hidden_size)
|
| 483 |
+
self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
|
| 484 |
+
self.adaLN_modulation = nn.Sequential(
|
| 485 |
+
nn.SiLU(),
|
| 486 |
+
nn.Linear(hidden_size, 2 * hidden_size, bias=True)
|
| 487 |
+
)
|
| 488 |
+
def forward(self, x, c):
|
| 489 |
+
shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
|
| 490 |
+
x = modulate(self.norm_final(x), shift, scale)
|
| 491 |
+
x = self.linear(x)
|
| 492 |
+
return x
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
class LightningDiT2DModel(ModelMixin, ConfigMixin):
|
| 496 |
+
"""
|
| 497 |
+
Diffusion model with a Transformer backbone.
|
| 498 |
+
"""
|
| 499 |
+
@register_to_config
|
| 500 |
+
def __init__(
|
| 501 |
+
self,
|
| 502 |
+
input_size: int = 32,
|
| 503 |
+
patch_size=2,
|
| 504 |
+
in_channels=32,
|
| 505 |
+
hidden_size=1152,
|
| 506 |
+
depth=28,
|
| 507 |
+
num_heads=16,
|
| 508 |
+
mlp_ratio=4.0,
|
| 509 |
+
class_dropout_prob=0.1,
|
| 510 |
+
num_classes=1000,
|
| 511 |
+
learn_sigma=False,
|
| 512 |
+
use_qknorm=False,
|
| 513 |
+
use_swiglu=False,
|
| 514 |
+
use_rope=False,
|
| 515 |
+
use_rmsnorm=False,
|
| 516 |
+
wo_shift=False,
|
| 517 |
+
use_checkpoint=False,
|
| 518 |
+
use_abs_pos=True,
|
| 519 |
+
):
|
| 520 |
+
super().__init__()
|
| 521 |
+
self.use_abs_pos = use_abs_pos
|
| 522 |
+
self.learn_sigma = learn_sigma
|
| 523 |
+
self.in_channels = in_channels
|
| 524 |
+
self.out_channels = in_channels if not learn_sigma else in_channels * 2
|
| 525 |
+
self.patch_size = patch_size
|
| 526 |
+
self.num_heads = num_heads
|
| 527 |
+
self.use_rope = use_rope
|
| 528 |
+
self.use_rmsnorm = use_rmsnorm
|
| 529 |
+
self.depth = depth
|
| 530 |
+
self.hidden_size = hidden_size
|
| 531 |
+
self.use_checkpoint = use_checkpoint
|
| 532 |
+
self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size, bias=True)
|
| 533 |
+
self.t_embedder = TimestepEmbedder(hidden_size)
|
| 534 |
+
self.y_embedder = LabelEmbedder(num_classes, hidden_size, class_dropout_prob)
|
| 535 |
+
num_patches = self.x_embedder.num_patches
|
| 536 |
+
# Will use fixed sin-cos embedding:
|
| 537 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False)
|
| 538 |
+
|
| 539 |
+
if not self.use_abs_pos and not self.use_rope:
|
| 540 |
+
import warnings
|
| 541 |
+
warnings.warn("Warning: Both Absolute Position Embedding and RoPE are disabled. "
|
| 542 |
+
"The model will be permutation-invariant (orderless)!")
|
| 543 |
+
|
| 544 |
+
# use rotary position encoding, borrow from EVA
|
| 545 |
+
if self.use_rope:
|
| 546 |
+
half_head_dim = hidden_size // num_heads // 2
|
| 547 |
+
hw_seq_len = input_size // patch_size
|
| 548 |
+
self.feat_rope = VisionRotaryEmbeddingFast(
|
| 549 |
+
dim=half_head_dim,
|
| 550 |
+
pt_seq_len=hw_seq_len,
|
| 551 |
+
)
|
| 552 |
+
else:
|
| 553 |
+
self.feat_rope = None
|
| 554 |
+
|
| 555 |
+
self.blocks = nn.ModuleList([
|
| 556 |
+
LightningDiTBlock(hidden_size,
|
| 557 |
+
num_heads,
|
| 558 |
+
mlp_ratio=mlp_ratio,
|
| 559 |
+
use_qknorm=use_qknorm,
|
| 560 |
+
use_swiglu=use_swiglu,
|
| 561 |
+
use_rmsnorm=use_rmsnorm,
|
| 562 |
+
wo_shift=wo_shift,
|
| 563 |
+
) for _ in range(depth)
|
| 564 |
+
])
|
| 565 |
+
self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels, use_rmsnorm=use_rmsnorm)
|
| 566 |
+
self.initialize_weights()
|
| 567 |
+
if hasattr(self, "register_to_config"):
|
| 568 |
+
self.register_to_config(
|
| 569 |
+
input_size=input_size,
|
| 570 |
+
patch_size=patch_size,
|
| 571 |
+
in_channels=in_channels,
|
| 572 |
+
hidden_size=hidden_size,
|
| 573 |
+
depth=depth,
|
| 574 |
+
num_heads=num_heads,
|
| 575 |
+
mlp_ratio=mlp_ratio,
|
| 576 |
+
class_dropout_prob=class_dropout_prob,
|
| 577 |
+
num_classes=num_classes,
|
| 578 |
+
learn_sigma=learn_sigma,
|
| 579 |
+
use_qknorm=use_qknorm,
|
| 580 |
+
use_swiglu=use_swiglu,
|
| 581 |
+
use_rope=use_rope,
|
| 582 |
+
use_rmsnorm=use_rmsnorm,
|
| 583 |
+
wo_shift=wo_shift,
|
| 584 |
+
use_checkpoint=use_checkpoint,
|
| 585 |
+
use_abs_pos=use_abs_pos,
|
| 586 |
+
)
|
| 587 |
+
|
| 588 |
+
def initialize_weights(self):
|
| 589 |
+
# Initialize transformer layers:
|
| 590 |
+
def _basic_init(module):
|
| 591 |
+
if isinstance(module, nn.Linear):
|
| 592 |
+
torch.nn.init.xavier_uniform_(module.weight)
|
| 593 |
+
if module.bias is not None:
|
| 594 |
+
nn.init.constant_(module.bias, 0)
|
| 595 |
+
self.apply(_basic_init)
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
if self.use_abs_pos:
|
| 599 |
+
pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5))
|
| 600 |
+
self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
|
| 601 |
+
else:
|
| 602 |
+
nn.init.constant_(self.pos_embed, 0)
|
| 603 |
+
|
| 604 |
+
# Initialize patch_embed like nn.Linear (instead of nn.Conv2d):
|
| 605 |
+
w = self.x_embedder.proj.weight.data
|
| 606 |
+
nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
|
| 607 |
+
nn.init.constant_(self.x_embedder.proj.bias, 0)
|
| 608 |
+
|
| 609 |
+
# Initialize label embedding table:
|
| 610 |
+
nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02)
|
| 611 |
+
|
| 612 |
+
# Initialize timestep embedding MLP:
|
| 613 |
+
nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
|
| 614 |
+
nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
|
| 615 |
+
|
| 616 |
+
# Zero-out adaLN modulation layers in LightningDiT blocks:
|
| 617 |
+
for block in self.blocks:
|
| 618 |
+
nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
|
| 619 |
+
nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
|
| 620 |
+
|
| 621 |
+
# Zero-out output layers:
|
| 622 |
+
nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
|
| 623 |
+
nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)
|
| 624 |
+
nn.init.constant_(self.final_layer.linear.weight, 0)
|
| 625 |
+
nn.init.constant_(self.final_layer.linear.bias, 0)
|
| 626 |
+
|
| 627 |
+
def unpatchify(self, x):
|
| 628 |
+
"""
|
| 629 |
+
x: (N, T, patch_size**2 * C)
|
| 630 |
+
imgs: (N, H, W, C)
|
| 631 |
+
"""
|
| 632 |
+
c = self.out_channels
|
| 633 |
+
p = self.x_embedder.patch_size[0]
|
| 634 |
+
h = w = int(x.shape[1] ** 0.5)
|
| 635 |
+
assert h * w == x.shape[1]
|
| 636 |
+
|
| 637 |
+
x = x.reshape(shape=(x.shape[0], h, w, p, p, c))
|
| 638 |
+
x = torch.einsum('nhwpqc->nchpwq', x)
|
| 639 |
+
imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p))
|
| 640 |
+
return imgs
|
| 641 |
+
|
| 642 |
+
def forward(
|
| 643 |
+
self,
|
| 644 |
+
hidden_states: torch.Tensor,
|
| 645 |
+
timestep: Optional[torch.LongTensor] = None,
|
| 646 |
+
class_labels: Optional[torch.LongTensor] = None,
|
| 647 |
+
return_dict: bool = True,
|
| 648 |
+
):
|
| 649 |
+
x = hidden_states
|
| 650 |
+
t = timestep
|
| 651 |
+
y = class_labels
|
| 652 |
+
"""
|
| 653 |
+
Forward pass of LightningDiT.
|
| 654 |
+
x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)
|
| 655 |
+
t: (N,) tensor of diffusion timesteps
|
| 656 |
+
y: (N,) tensor of class labels
|
| 657 |
+
use_checkpoint: boolean to toggle checkpointing
|
| 658 |
+
"""
|
| 659 |
+
|
| 660 |
+
use_checkpoint = self.use_checkpoint
|
| 661 |
+
|
| 662 |
+
x = self.x_embedder(x)
|
| 663 |
+
if self.use_abs_pos:
|
| 664 |
+
x = x + self.pos_embed
|
| 665 |
+
t = self.t_embedder(t) # (N, D)
|
| 666 |
+
y = self.y_embedder(y, self.training) # (N, D)
|
| 667 |
+
c = t + y # (N, D)
|
| 668 |
+
|
| 669 |
+
for block in self.blocks:
|
| 670 |
+
if use_checkpoint:
|
| 671 |
+
x = checkpoint(block, x, c, self.feat_rope, use_reentrant=True)
|
| 672 |
+
else:
|
| 673 |
+
x = block(x, c, self.feat_rope)
|
| 674 |
+
|
| 675 |
+
x = self.final_layer(x, c) # (N, T, patch_size ** 2 * out_channels)
|
| 676 |
+
x = self.unpatchify(x) # (N, out_channels, H, W)
|
| 677 |
+
|
| 678 |
+
if self.learn_sigma:
|
| 679 |
+
x, _ = x.chunk(2, dim=1)
|
| 680 |
+
if not return_dict:
|
| 681 |
+
return (x,)
|
| 682 |
+
return LightningDiT2DModelOutput(sample=x)
|
| 683 |
+
|
| 684 |
+
def forward_with_cfg(self, x, t, y, cfg_scale, cfg_interval=None, cfg_interval_start=None):
|
| 685 |
+
"""
|
| 686 |
+
Forward pass of LightningDiT, but also batches the unconditional forward pass for classifier-free guidance.
|
| 687 |
+
"""
|
| 688 |
+
# https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb
|
| 689 |
+
combined = torch.cat([x, x], dim=0)
|
| 690 |
+
model_out = self.forward(combined, t, y, return_dict=False)[0]
|
| 691 |
+
# For exact reproducibility reasons, we apply classifier-free guidance on only
|
| 692 |
+
# three channels by default. The standard approach to cfg applies it to all channels.
|
| 693 |
+
# This can be done by uncommenting the following line and commenting-out the line following that.
|
| 694 |
+
eps, rest = model_out[:, :self.in_channels], model_out[:, self.in_channels:]
|
| 695 |
+
# eps, rest = model_out[:, :3], model_out[:, 3:]
|
| 696 |
+
cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
|
| 697 |
+
half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps)
|
| 698 |
+
|
| 699 |
+
if cfg_interval is True:
|
| 700 |
+
timestep = t[0]
|
| 701 |
+
if timestep < cfg_interval_start:
|
| 702 |
+
half_eps = cond_eps
|
| 703 |
+
|
| 704 |
+
eps = torch.cat([half_eps, half_eps], dim=0)
|
| 705 |
+
return torch.cat([eps, rest], dim=1)
|
| 706 |
+
|
| 707 |
+
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0):
|
| 708 |
+
"""
|
| 709 |
+
grid_size: int of the grid height and width
|
| 710 |
+
return:
|
| 711 |
+
pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
|
| 712 |
+
"""
|
| 713 |
+
grid_h = np.arange(grid_size, dtype=np.float32)
|
| 714 |
+
grid_w = np.arange(grid_size, dtype=np.float32)
|
| 715 |
+
grid = np.meshgrid(grid_w, grid_h) # here w goes first
|
| 716 |
+
grid = np.stack(grid, axis=0)
|
| 717 |
+
|
| 718 |
+
grid = grid.reshape([2, 1, grid_size, grid_size])
|
| 719 |
+
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
| 720 |
+
if cls_token and extra_tokens > 0:
|
| 721 |
+
pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
|
| 722 |
+
return pos_embed
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
|
| 726 |
+
assert embed_dim % 2 == 0
|
| 727 |
+
|
| 728 |
+
# use half of dimensions to encode grid_h
|
| 729 |
+
emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
|
| 730 |
+
emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
|
| 731 |
+
|
| 732 |
+
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
|
| 733 |
+
return emb
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
|
| 737 |
+
"""
|
| 738 |
+
embed_dim: output dimension for each position
|
| 739 |
+
pos: a list of positions to be encoded: size (M,)
|
| 740 |
+
out: (M, D)
|
| 741 |
+
"""
|
| 742 |
+
assert embed_dim % 2 == 0
|
| 743 |
+
omega = np.arange(embed_dim // 2, dtype=np.float64)
|
| 744 |
+
omega /= embed_dim / 2.
|
| 745 |
+
omega = 1. / 10000**omega # (D/2,)
|
| 746 |
+
|
| 747 |
+
pos = pos.reshape(-1) # (M,)
|
| 748 |
+
out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
|
| 749 |
+
|
| 750 |
+
emb_sin = np.sin(out) # (M, D/2)
|
| 751 |
+
emb_cos = np.cos(out) # (M, D/2)
|
| 752 |
+
|
| 753 |
+
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
|
| 754 |
+
return emb
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
#################################################################################
|
| 758 |
+
# LightningDiT Configs #
|
| 759 |
+
#################################################################################
|
| 760 |
+
|
| 761 |
+
def _lightning_dit_XL_1(**kwargs):
|
| 762 |
+
return LightningDiT2DModel(depth=28, hidden_size=1152, patch_size=1, num_heads=16, **kwargs)
|
| 763 |
+
|
| 764 |
+
def _lightning_dit_XL_2(**kwargs):
|
| 765 |
+
return LightningDiT2DModel(depth=28, hidden_size=1152, patch_size=2, num_heads=16, **kwargs)
|
| 766 |
+
|
| 767 |
+
def _lightning_dit_L_2(**kwargs):
|
| 768 |
+
return LightningDiT2DModel(depth=24, hidden_size=1024, patch_size=2, num_heads=16, **kwargs)
|
| 769 |
+
|
| 770 |
+
def _lightning_dit_B_1(**kwargs):
|
| 771 |
+
return LightningDiT2DModel(depth=12, hidden_size=768, patch_size=1, num_heads=12, **kwargs)
|
| 772 |
+
|
| 773 |
+
def _lightning_dit_B_2(**kwargs):
|
| 774 |
+
return LightningDiT2DModel(depth=12, hidden_size=768, patch_size=2, num_heads=12, **kwargs)
|
| 775 |
+
|
| 776 |
+
def _lightning_dit_1p0B_1(**kwargs):
|
| 777 |
+
return LightningDiT2DModel(depth=24, hidden_size=1536, patch_size=1, num_heads=24, **kwargs)
|
| 778 |
+
|
| 779 |
+
def _lightning_dit_1p0B_2(**kwargs):
|
| 780 |
+
return LightningDiT2DModel(depth=24, hidden_size=1536, patch_size=2, num_heads=24, **kwargs)
|
| 781 |
+
|
| 782 |
+
def _lightning_dit_1p6B_1(**kwargs):
|
| 783 |
+
return LightningDiT2DModel(depth=28, hidden_size=1792, patch_size=1, num_heads=28, **kwargs)
|
| 784 |
+
|
| 785 |
+
def _lightning_dit_1p6B_2(**kwargs):
|
| 786 |
+
return LightningDiT2DModel(depth=28, hidden_size=1792, patch_size=2, num_heads=28, **kwargs)
|
| 787 |
+
|
| 788 |
+
LIGHTNING_DIT_PRESETS = {
|
| 789 |
+
'LightningDiT-B/1': _lightning_dit_B_1, 'LightningDiT-B/2': _lightning_dit_B_2,
|
| 790 |
+
'LightningDiT-L/2': _lightning_dit_L_2,
|
| 791 |
+
'LightningDiT-XL/1': _lightning_dit_XL_1, 'LightningDiT-XL/2': _lightning_dit_XL_2,
|
| 792 |
+
'LightningDiT-1p0B/1': _lightning_dit_1p0B_1, 'LightningDiT-1p0B/2': _lightning_dit_1p0B_2,
|
| 793 |
+
'LightningDiT-1p6B/1': _lightning_dit_1p6B_1, 'LightningDiT-1p6B/2': _lightning_dit_1p6B_2,
|
| 794 |
+
}
|
pae-siglip2-so400m-d32/__pycache__/pipeline.cpython-311.pyc
ADDED
|
Binary file (26.3 kB). View file
|
|
|
pae-siglip2-so400m-d32/decoder/__pycache__/decoder_pae.cpython-311.pyc
ADDED
|
Binary file (59.6 kB). View file
|
|
|
pae-siglip2-so400m-d32/decoder/config.json
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "PAEDecoder",
|
| 3 |
+
"decoder_patch_size": 16,
|
| 4 |
+
"encoder_config_path": "google/siglip2-so400m-patch16-256",
|
| 5 |
+
"encoder_hidden_size": 1152,
|
| 6 |
+
"encoder_input_size": 256,
|
| 7 |
+
"encoder_num_heads": 16,
|
| 8 |
+
"encoder_patch_size": 16,
|
| 9 |
+
"image_mean": [
|
| 10 |
+
0.5,
|
| 11 |
+
0.5,
|
| 12 |
+
0.5
|
| 13 |
+
],
|
| 14 |
+
"image_std": [
|
| 15 |
+
0.5,
|
| 16 |
+
0.5,
|
| 17 |
+
0.5
|
| 18 |
+
],
|
| 19 |
+
"latent_dim": 32,
|
| 20 |
+
"latent_mean": [
|
| 21 |
+
-0.035400390625,
|
| 22 |
+
-0.038818359375,
|
| 23 |
+
-0.0220947265625,
|
| 24 |
+
0.06884765625,
|
| 25 |
+
-0.52734375,
|
| 26 |
+
0.03076171875,
|
| 27 |
+
-0.29296875,
|
| 28 |
+
0.314453125,
|
| 29 |
+
-0.294921875,
|
| 30 |
+
-0.04296875,
|
| 31 |
+
-0.86328125,
|
| 32 |
+
-0.057373046875,
|
| 33 |
+
-1.6484375,
|
| 34 |
+
0.2890625,
|
| 35 |
+
-1.8671875,
|
| 36 |
+
0.05517578125,
|
| 37 |
+
-1.6484375,
|
| 38 |
+
1.3203125,
|
| 39 |
+
1.2890625,
|
| 40 |
+
0.333984375,
|
| 41 |
+
0.1396484375,
|
| 42 |
+
-0.458984375,
|
| 43 |
+
-0.61328125,
|
| 44 |
+
0.326171875,
|
| 45 |
+
0.11181640625,
|
| 46 |
+
-0.1923828125,
|
| 47 |
+
-0.248046875,
|
| 48 |
+
-1.40625,
|
| 49 |
+
1.546875,
|
| 50 |
+
0.037353515625,
|
| 51 |
+
0.19140625,
|
| 52 |
+
2.796875
|
| 53 |
+
],
|
| 54 |
+
"latent_multiplier": 1.0,
|
| 55 |
+
"latent_std": [
|
| 56 |
+
0.357421875,
|
| 57 |
+
0.375,
|
| 58 |
+
0.388671875,
|
| 59 |
+
0.353515625,
|
| 60 |
+
0.349609375,
|
| 61 |
+
0.380859375,
|
| 62 |
+
0.38671875,
|
| 63 |
+
0.44921875,
|
| 64 |
+
0.439453125,
|
| 65 |
+
0.38671875,
|
| 66 |
+
0.431640625,
|
| 67 |
+
0.39453125,
|
| 68 |
+
0.39453125,
|
| 69 |
+
0.40234375,
|
| 70 |
+
0.34765625,
|
| 71 |
+
0.404296875,
|
| 72 |
+
0.458984375,
|
| 73 |
+
0.376953125,
|
| 74 |
+
0.3984375,
|
| 75 |
+
0.435546875,
|
| 76 |
+
0.408203125,
|
| 77 |
+
0.357421875,
|
| 78 |
+
0.41796875,
|
| 79 |
+
0.44140625,
|
| 80 |
+
0.40625,
|
| 81 |
+
0.380859375,
|
| 82 |
+
0.37890625,
|
| 83 |
+
0.515625,
|
| 84 |
+
0.380859375,
|
| 85 |
+
0.388671875,
|
| 86 |
+
0.375,
|
| 87 |
+
0.439453125
|
| 88 |
+
]
|
| 89 |
+
}
|
pae-siglip2-so400m-d32/decoder/decoder_pae.py
ADDED
|
@@ -0,0 +1,1105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 4 |
+
from transformers.utils import (
|
| 5 |
+
ModelOutput,
|
| 6 |
+
)
|
| 7 |
+
from transformers.activations import ACT2FN
|
| 8 |
+
class ViTMAEConfig(PretrainedConfig):
|
| 9 |
+
r"""
|
| 10 |
+
This is the configuration class to store the configuration of a [`ViTMAEModel`]. It is used to instantiate an ViT
|
| 11 |
+
MAE model according to the specified arguments, defining the model architecture. Instantiating a configuration with
|
| 12 |
+
the defaults will yield a similar configuration to that of the ViT
|
| 13 |
+
[facebook/vit-mae-base](https://huggingface.co/facebook/vit-mae-base) architecture.
|
| 14 |
+
|
| 15 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 16 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 21 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 22 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 23 |
+
Number of hidden layers in the Transformer encoder.
|
| 24 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 25 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 26 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 27 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 28 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 29 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 30 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 31 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 32 |
+
The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.
|
| 33 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 34 |
+
The dropout ratio for the attention probabilities.
|
| 35 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 36 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 37 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 38 |
+
The epsilon used by the layer normalization layers.
|
| 39 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 40 |
+
The size (resolution) of each image.
|
| 41 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 42 |
+
The size (resolution) of each patch.
|
| 43 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 44 |
+
The number of input channels.
|
| 45 |
+
qkv_bias (`bool`, *optional*, defaults to `True`):
|
| 46 |
+
Whether to add a bias to the queries, keys and values.
|
| 47 |
+
decoder_num_attention_heads (`int`, *optional*, defaults to 16):
|
| 48 |
+
Number of attention heads for each attention layer in the decoder.
|
| 49 |
+
decoder_hidden_size (`int`, *optional*, defaults to 512):
|
| 50 |
+
Dimensionality of the decoder.
|
| 51 |
+
decoder_num_hidden_layers (`int`, *optional*, defaults to 8):
|
| 52 |
+
Number of hidden layers in the decoder.
|
| 53 |
+
decoder_intermediate_size (`int`, *optional*, defaults to 2048):
|
| 54 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the decoder.
|
| 55 |
+
mask_ratio (`float`, *optional*, defaults to 0.75):
|
| 56 |
+
The ratio of the number of masked tokens in the input sequence.
|
| 57 |
+
norm_pix_loss (`bool`, *optional*, defaults to `False`):
|
| 58 |
+
Whether or not to train with normalized pixels (see Table 3 in the paper). Using normalized pixels improved
|
| 59 |
+
representation quality in the experiments of the authors.
|
| 60 |
+
|
| 61 |
+
Example:
|
| 62 |
+
|
| 63 |
+
```python
|
| 64 |
+
>>> from transformers import ViTMAEConfig, ViTMAEModel
|
| 65 |
+
|
| 66 |
+
>>> # Initializing a ViT MAE vit-mae-base style configuration
|
| 67 |
+
>>> configuration = ViTMAEConfig()
|
| 68 |
+
|
| 69 |
+
>>> # Initializing a model (with random weights) from the vit-mae-base style configuration
|
| 70 |
+
>>> model = ViTMAEModel(configuration)
|
| 71 |
+
|
| 72 |
+
>>> # Accessing the model configuration
|
| 73 |
+
>>> configuration = model.config
|
| 74 |
+
```"""
|
| 75 |
+
|
| 76 |
+
model_type = "vit_mae"
|
| 77 |
+
|
| 78 |
+
def __init__(
|
| 79 |
+
self,
|
| 80 |
+
hidden_size=768,
|
| 81 |
+
num_hidden_layers=12,
|
| 82 |
+
num_attention_heads=12,
|
| 83 |
+
intermediate_size=3072,
|
| 84 |
+
hidden_act="gelu",
|
| 85 |
+
hidden_dropout_prob=0.0,
|
| 86 |
+
attention_probs_dropout_prob=0.0,
|
| 87 |
+
initializer_range=0.02,
|
| 88 |
+
layer_norm_eps=1e-12,
|
| 89 |
+
image_size=224,
|
| 90 |
+
patch_size=16,
|
| 91 |
+
num_channels=3,
|
| 92 |
+
qkv_bias=True,
|
| 93 |
+
decoder_num_attention_heads=16,
|
| 94 |
+
decoder_hidden_size=512,
|
| 95 |
+
decoder_num_hidden_layers=8,
|
| 96 |
+
decoder_intermediate_size=2048,
|
| 97 |
+
mask_ratio=0.75,
|
| 98 |
+
norm_pix_loss=False,
|
| 99 |
+
**kwargs,
|
| 100 |
+
):
|
| 101 |
+
super().__init__(**kwargs)
|
| 102 |
+
|
| 103 |
+
self.hidden_size = hidden_size
|
| 104 |
+
self.num_hidden_layers = num_hidden_layers
|
| 105 |
+
self.num_attention_heads = num_attention_heads
|
| 106 |
+
self.intermediate_size = intermediate_size
|
| 107 |
+
self.hidden_act = hidden_act
|
| 108 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 109 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 110 |
+
self.initializer_range = initializer_range
|
| 111 |
+
self.layer_norm_eps = layer_norm_eps
|
| 112 |
+
self.image_size = image_size
|
| 113 |
+
self.patch_size = patch_size
|
| 114 |
+
self.num_channels = num_channels
|
| 115 |
+
self.qkv_bias = qkv_bias
|
| 116 |
+
self.decoder_num_attention_heads = decoder_num_attention_heads
|
| 117 |
+
self.decoder_hidden_size = decoder_hidden_size
|
| 118 |
+
self.decoder_num_hidden_layers = decoder_num_hidden_layers
|
| 119 |
+
self.decoder_intermediate_size = decoder_intermediate_size
|
| 120 |
+
self.mask_ratio = mask_ratio
|
| 121 |
+
self.norm_pix_loss = norm_pix_loss
|
| 122 |
+
|
| 123 |
+
# coding=utf-8
|
| 124 |
+
# Copyright 2022 Facebook AI and The HuggingFace Inc. team. All rights reserved.
|
| 125 |
+
#
|
| 126 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 127 |
+
# you may not use this file except in compliance with the License.
|
| 128 |
+
# You may obtain a copy of the License at
|
| 129 |
+
#
|
| 130 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 131 |
+
#
|
| 132 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 133 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 134 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 135 |
+
# See the License for the specific language governing permissions and
|
| 136 |
+
# limitations under the License.
|
| 137 |
+
"""PyTorch ViT MAE (masked autoencoder) model."""
|
| 138 |
+
|
| 139 |
+
import collections.abc
|
| 140 |
+
import math
|
| 141 |
+
from copy import deepcopy
|
| 142 |
+
from dataclasses import dataclass
|
| 143 |
+
from typing import Optional, Set, Tuple, Union
|
| 144 |
+
|
| 145 |
+
import numpy as np
|
| 146 |
+
import torch
|
| 147 |
+
from torch import nn
|
| 148 |
+
# correct the above import to the following
|
| 149 |
+
from transformers.modeling_outputs import BaseModelOutput
|
| 150 |
+
|
| 151 |
+
try:
|
| 152 |
+
from flash_attn import flash_attn_func
|
| 153 |
+
HAS_FLASH_ATTN = True # if set to False, FlashAttention is unavailable
|
| 154 |
+
except:
|
| 155 |
+
print('FlashAttention is not installed.')
|
| 156 |
+
HAS_FLASH_ATTN = False
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@dataclass
|
| 160 |
+
class ViTMAEModelOutput(ModelOutput):
|
| 161 |
+
"""
|
| 162 |
+
Class for ViTMAEModel's outputs, with potential hidden states and attentions.
|
| 163 |
+
|
| 164 |
+
Args:
|
| 165 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 166 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 167 |
+
mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
|
| 168 |
+
Tensor indicating which patches are masked (1) and which are not (0).
|
| 169 |
+
ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 170 |
+
Tensor containing the original index of the (shuffled) masked patches.
|
| 171 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 172 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 173 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 174 |
+
plus the initial embedding outputs.
|
| 175 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 176 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 177 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 178 |
+
the self-attention heads.
|
| 179 |
+
"""
|
| 180 |
+
|
| 181 |
+
last_hidden_state: torch.FloatTensor = None
|
| 182 |
+
mask: torch.LongTensor = None
|
| 183 |
+
ids_restore: torch.LongTensor = None
|
| 184 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 185 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
@dataclass
|
| 189 |
+
class ViTMAEDecoderOutput(ModelOutput):
|
| 190 |
+
"""
|
| 191 |
+
Class for ViTMAEDecoder's outputs, with potential hidden states and attentions.
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`):
|
| 195 |
+
Pixel reconstruction logits.
|
| 196 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 197 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 198 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 199 |
+
plus the initial embedding outputs.
|
| 200 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 201 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 202 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 203 |
+
the self-attention heads.
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
logits: torch.FloatTensor = None
|
| 207 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 208 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
@dataclass
|
| 212 |
+
class ViTMAEForPreTrainingOutput(ModelOutput):
|
| 213 |
+
"""
|
| 214 |
+
Class for ViTMAEForPreTraining's outputs, with potential hidden states and attentions.
|
| 215 |
+
|
| 216 |
+
Args:
|
| 217 |
+
loss (`torch.FloatTensor` of shape `(1,)`):
|
| 218 |
+
Pixel reconstruction loss.
|
| 219 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`):
|
| 220 |
+
Pixel reconstruction logits.
|
| 221 |
+
mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
|
| 222 |
+
Tensor indicating which patches are masked (1) and which are not (0).
|
| 223 |
+
ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 224 |
+
Tensor containing the original index of the (shuffled) masked patches.
|
| 225 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 226 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 227 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 228 |
+
plus the initial embedding outputs.
|
| 229 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 230 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 231 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 232 |
+
the self-attention heads.
|
| 233 |
+
"""
|
| 234 |
+
|
| 235 |
+
loss: Optional[torch.FloatTensor] = None
|
| 236 |
+
logits: torch.FloatTensor = None
|
| 237 |
+
mask: torch.LongTensor = None
|
| 238 |
+
ids_restore: torch.LongTensor = None
|
| 239 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 240 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def get_2d_sincos_pos_embed(embed_dim, grid_size, add_cls_token=False):
|
| 244 |
+
"""
|
| 245 |
+
Create 2D sin/cos positional embeddings.
|
| 246 |
+
|
| 247 |
+
Args:
|
| 248 |
+
embed_dim (`int`):
|
| 249 |
+
Embedding dimension.
|
| 250 |
+
grid_size (`int`):
|
| 251 |
+
The grid height and width.
|
| 252 |
+
add_cls_token (`bool`, *optional*, defaults to `False`):
|
| 253 |
+
Whether or not to add a classification (CLS) token.
|
| 254 |
+
|
| 255 |
+
Returns:
|
| 256 |
+
(`torch.FloatTensor` of shape (grid_size*grid_size, embed_dim) or (1+grid_size*grid_size, embed_dim): the
|
| 257 |
+
position embeddings (with or without classification token)
|
| 258 |
+
"""
|
| 259 |
+
grid_h = np.arange(grid_size, dtype=np.float32)
|
| 260 |
+
grid_w = np.arange(grid_size, dtype=np.float32)
|
| 261 |
+
grid = np.meshgrid(grid_w, grid_h) # here w goes first
|
| 262 |
+
grid = np.stack(grid, axis=0)
|
| 263 |
+
|
| 264 |
+
grid = grid.reshape([2, 1, grid_size, grid_size])
|
| 265 |
+
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
| 266 |
+
if add_cls_token:
|
| 267 |
+
pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
|
| 268 |
+
return pos_embed
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
|
| 272 |
+
if embed_dim % 2 != 0:
|
| 273 |
+
raise ValueError("embed_dim must be even")
|
| 274 |
+
|
| 275 |
+
# use half of dimensions to encode grid_h
|
| 276 |
+
emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
|
| 277 |
+
emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
|
| 278 |
+
|
| 279 |
+
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
|
| 280 |
+
return emb
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
|
| 284 |
+
"""
|
| 285 |
+
embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D)
|
| 286 |
+
"""
|
| 287 |
+
if embed_dim % 2 != 0:
|
| 288 |
+
raise ValueError("embed_dim must be even")
|
| 289 |
+
|
| 290 |
+
omega = np.arange(embed_dim // 2, dtype=float)
|
| 291 |
+
omega /= embed_dim / 2.0
|
| 292 |
+
omega = 1.0 / 10000**omega # (D/2,)
|
| 293 |
+
|
| 294 |
+
pos = pos.reshape(-1) # (M,)
|
| 295 |
+
out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
|
| 296 |
+
|
| 297 |
+
emb_sin = np.sin(out) # (M, D/2)
|
| 298 |
+
emb_cos = np.cos(out) # (M, D/2)
|
| 299 |
+
|
| 300 |
+
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
|
| 301 |
+
return emb
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
class ViTMAEEmbeddings(nn.Module):
|
| 305 |
+
"""
|
| 306 |
+
Construct the CLS token, position and patch embeddings.
|
| 307 |
+
|
| 308 |
+
"""
|
| 309 |
+
|
| 310 |
+
def __init__(self, config):
|
| 311 |
+
super().__init__()
|
| 312 |
+
|
| 313 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 314 |
+
self.patch_embeddings = ViTMAEPatchEmbeddings(config)
|
| 315 |
+
self.num_patches = self.patch_embeddings.num_patches
|
| 316 |
+
# fixed sin-cos embedding
|
| 317 |
+
self.position_embeddings = nn.Parameter(
|
| 318 |
+
torch.zeros(1, self.num_patches + 1, config.hidden_size), requires_grad=False
|
| 319 |
+
)
|
| 320 |
+
self.config = config
|
| 321 |
+
self.initialize_weights()
|
| 322 |
+
|
| 323 |
+
def initialize_weights(self):
|
| 324 |
+
# initialize (and freeze) position embeddings by sin-cos embedding
|
| 325 |
+
pos_embed = get_2d_sincos_pos_embed(
|
| 326 |
+
self.position_embeddings.shape[-1], int(self.patch_embeddings.num_patches**0.5), add_cls_token=True
|
| 327 |
+
)
|
| 328 |
+
self.position_embeddings.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
|
| 329 |
+
|
| 330 |
+
# initialize patch_embeddings like nn.Linear (instead of nn.Conv2d)
|
| 331 |
+
w = self.patch_embeddings.projection.weight.data
|
| 332 |
+
torch.nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
|
| 333 |
+
|
| 334 |
+
# timm's trunc_normal_(std=.02) is effectively normal_(std=0.02) as cutoff is too big (2.)
|
| 335 |
+
torch.nn.init.normal_(self.cls_token, std=self.config.initializer_range)
|
| 336 |
+
|
| 337 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
| 338 |
+
"""
|
| 339 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher
|
| 340 |
+
resolution images.
|
| 341 |
+
|
| 342 |
+
Source:
|
| 343 |
+
https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174
|
| 344 |
+
"""
|
| 345 |
+
num_patches = embeddings.shape[1] - 1
|
| 346 |
+
num_positions = self.position_embeddings.shape[1] - 1
|
| 347 |
+
|
| 348 |
+
if num_patches == num_positions and height == width:
|
| 349 |
+
return self.position_embeddings
|
| 350 |
+
|
| 351 |
+
class_pos_embed = self.position_embeddings[:, 0, :]
|
| 352 |
+
patch_pos_embed = self.position_embeddings[:, 1:, :]
|
| 353 |
+
dim = embeddings.shape[-1]
|
| 354 |
+
h0 = height // self.config.patch_size
|
| 355 |
+
w0 = width // self.config.patch_size
|
| 356 |
+
# we add a small number to avoid floating point error in the interpolation
|
| 357 |
+
# see discussion at https://github.com/facebookresearch/dino/issues/8
|
| 358 |
+
h0, w0 = h0 + 0.1, w0 + 0.1
|
| 359 |
+
patch_pos_embed = patch_pos_embed.reshape(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim)
|
| 360 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 361 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 362 |
+
patch_pos_embed,
|
| 363 |
+
scale_factor=(h0 / math.sqrt(num_positions), w0 / math.sqrt(num_positions)),
|
| 364 |
+
mode="bicubic",
|
| 365 |
+
align_corners=False,
|
| 366 |
+
)
|
| 367 |
+
if int(h0) != patch_pos_embed.shape[-2] or int(w0) != patch_pos_embed.shape[-1]:
|
| 368 |
+
raise ValueError("Width or height does not match with the interpolated position embeddings")
|
| 369 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 370 |
+
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
|
| 371 |
+
|
| 372 |
+
def random_masking(self, sequence, noise=None):
|
| 373 |
+
"""
|
| 374 |
+
Perform per-sample random masking by per-sample shuffling. Per-sample shuffling is done by argsort random
|
| 375 |
+
noise.
|
| 376 |
+
|
| 377 |
+
Args:
|
| 378 |
+
sequence (`torch.LongTensor` of shape `(batch_size, sequence_length, dim)`)
|
| 379 |
+
noise (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*) which is
|
| 380 |
+
mainly used for testing purposes to control randomness and maintain the reproducibility
|
| 381 |
+
"""
|
| 382 |
+
batch_size, seq_length, dim = sequence.shape
|
| 383 |
+
len_keep = int(seq_length * (1 - self.config.mask_ratio))
|
| 384 |
+
|
| 385 |
+
if noise is None:
|
| 386 |
+
noise = torch.rand(batch_size, seq_length, device=sequence.device) # noise in [0, 1]
|
| 387 |
+
|
| 388 |
+
# sort noise for each sample
|
| 389 |
+
ids_shuffle = torch.argsort(noise, dim=1).to(sequence.device) # ascend: small is keep, large is remove
|
| 390 |
+
ids_restore = torch.argsort(ids_shuffle, dim=1).to(sequence.device)
|
| 391 |
+
|
| 392 |
+
# keep the first subset
|
| 393 |
+
ids_keep = ids_shuffle[:, :len_keep]
|
| 394 |
+
sequence_unmasked = torch.gather(sequence, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, dim))
|
| 395 |
+
|
| 396 |
+
# generate the binary mask: 0 is keep, 1 is remove
|
| 397 |
+
mask = torch.ones([batch_size, seq_length], device=sequence.device)
|
| 398 |
+
mask[:, :len_keep] = 0
|
| 399 |
+
# unshuffle to get the binary mask
|
| 400 |
+
mask = torch.gather(mask, dim=1, index=ids_restore)
|
| 401 |
+
|
| 402 |
+
return sequence_unmasked, mask, ids_restore
|
| 403 |
+
|
| 404 |
+
def forward(self, pixel_values, noise=None, interpolate_pos_encoding: bool = False):
|
| 405 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 406 |
+
embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
|
| 407 |
+
if interpolate_pos_encoding:
|
| 408 |
+
position_embeddings = self.interpolate_pos_encoding(embeddings, height, width)
|
| 409 |
+
else:
|
| 410 |
+
position_embeddings = self.position_embeddings
|
| 411 |
+
|
| 412 |
+
# add position embeddings w/o cls token
|
| 413 |
+
embeddings = embeddings + position_embeddings[:, 1:, :]
|
| 414 |
+
|
| 415 |
+
# masking: length -> length * config.mask_ratio
|
| 416 |
+
embeddings, mask, ids_restore = self.random_masking(embeddings, noise)
|
| 417 |
+
|
| 418 |
+
# append cls token
|
| 419 |
+
cls_token = self.cls_token + position_embeddings[:, :1, :]
|
| 420 |
+
cls_tokens = cls_token.expand(embeddings.shape[0], -1, -1)
|
| 421 |
+
embeddings = torch.cat((cls_tokens, embeddings), dim=1)
|
| 422 |
+
|
| 423 |
+
return embeddings, mask, ids_restore
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
class ViTMAEPatchEmbeddings(nn.Module):
|
| 427 |
+
"""
|
| 428 |
+
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
|
| 429 |
+
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
|
| 430 |
+
Transformer.
|
| 431 |
+
"""
|
| 432 |
+
|
| 433 |
+
def __init__(self, config):
|
| 434 |
+
super().__init__()
|
| 435 |
+
image_size, patch_size = config.image_size, config.patch_size
|
| 436 |
+
num_channels, hidden_size = config.num_channels, config.hidden_size
|
| 437 |
+
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
|
| 438 |
+
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 439 |
+
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
| 440 |
+
self.image_size = image_size
|
| 441 |
+
self.patch_size = patch_size
|
| 442 |
+
self.num_channels = num_channels
|
| 443 |
+
self.num_patches = num_patches
|
| 444 |
+
|
| 445 |
+
self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
|
| 446 |
+
|
| 447 |
+
def forward(self, pixel_values, interpolate_pos_encoding: bool = False):
|
| 448 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 449 |
+
if num_channels != self.num_channels:
|
| 450 |
+
raise ValueError(
|
| 451 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
if not interpolate_pos_encoding and (height != self.image_size[0] or width != self.image_size[1]):
|
| 455 |
+
raise ValueError(
|
| 456 |
+
f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
|
| 457 |
+
)
|
| 458 |
+
x = self.projection(pixel_values).flatten(2).transpose(1, 2)
|
| 459 |
+
return x
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
# Copied from transformers.models.vit.modeling_vit.ViTSelfAttention ViT->ViTMAE
|
| 463 |
+
class ViTMAESelfAttention(nn.Module):
|
| 464 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 465 |
+
super().__init__()
|
| 466 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 467 |
+
raise ValueError(
|
| 468 |
+
f"The hidden size {config.hidden_size,} is not a multiple of the number of attention "
|
| 469 |
+
f"heads {config.num_attention_heads}."
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
self.has_flash_attn = HAS_FLASH_ATTN
|
| 473 |
+
self.num_attention_heads = config.num_attention_heads
|
| 474 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 475 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 476 |
+
|
| 477 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 478 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 479 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 480 |
+
|
| 481 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 482 |
+
self.attention_probs_dropout_prob = config.attention_probs_dropout_prob
|
| 483 |
+
|
| 484 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
| 485 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 486 |
+
x = x.view(new_x_shape)
|
| 487 |
+
return x.permute(0, 2, 1, 3)
|
| 488 |
+
|
| 489 |
+
def reshape_for_flash(self, x: torch.Tensor) -> torch.Tensor:
|
| 490 |
+
"""Reshape to (B, N, num_heads, head_dim) for flash_attn_func."""
|
| 491 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 492 |
+
return x.view(new_x_shape)
|
| 493 |
+
|
| 494 |
+
def forward(
|
| 495 |
+
self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
|
| 496 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 497 |
+
# Use FlashAttention when available and no special outputs are needed
|
| 498 |
+
if self.has_flash_attn and not output_attentions and head_mask is None:
|
| 499 |
+
query_layer = self.reshape_for_flash(self.query(hidden_states))
|
| 500 |
+
key_layer = self.reshape_for_flash(self.key(hidden_states))
|
| 501 |
+
value_layer = self.reshape_for_flash(self.value(hidden_states))
|
| 502 |
+
|
| 503 |
+
context_layer = flash_attn_func(
|
| 504 |
+
query_layer, key_layer, value_layer,
|
| 505 |
+
dropout_p=self.attention_probs_dropout_prob if self.training else 0.0,
|
| 506 |
+
causal=False, deterministic=True
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
context_layer = context_layer.reshape(hidden_states.size(0), -1, self.all_head_size)
|
| 510 |
+
return (context_layer,)
|
| 511 |
+
|
| 512 |
+
# Fallback: manual attention computation
|
| 513 |
+
mixed_query_layer = self.query(hidden_states)
|
| 514 |
+
|
| 515 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 516 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 517 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 518 |
+
|
| 519 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 520 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 521 |
+
|
| 522 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 523 |
+
attention_probs = self.dropout(attention_probs)
|
| 524 |
+
|
| 525 |
+
if head_mask is not None:
|
| 526 |
+
attention_probs = attention_probs * head_mask
|
| 527 |
+
|
| 528 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 529 |
+
|
| 530 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 531 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 532 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 533 |
+
|
| 534 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 535 |
+
|
| 536 |
+
return outputs
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
# Copied from transformers.models.vit.modeling_vit.ViTSdpaSelfAttention ViT->ViTMAE
|
| 540 |
+
class ViTMAESdpaSelfAttention(ViTMAESelfAttention):
|
| 541 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 542 |
+
super().__init__(config)
|
| 543 |
+
self.attention_probs_dropout_prob = config.attention_probs_dropout_prob
|
| 544 |
+
|
| 545 |
+
def forward(
|
| 546 |
+
self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
|
| 547 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 548 |
+
# Use FlashAttention when available and no special outputs are needed
|
| 549 |
+
if self.has_flash_attn and not output_attentions and head_mask is None:
|
| 550 |
+
query_layer = self.reshape_for_flash(self.query(hidden_states))
|
| 551 |
+
key_layer = self.reshape_for_flash(self.key(hidden_states))
|
| 552 |
+
value_layer = self.reshape_for_flash(self.value(hidden_states))
|
| 553 |
+
|
| 554 |
+
context_layer = flash_attn_func(
|
| 555 |
+
query_layer, key_layer, value_layer,
|
| 556 |
+
dropout_p=self.attention_probs_dropout_prob if self.training else 0.0,
|
| 557 |
+
causal=False, deterministic=True
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
context_layer = context_layer.reshape(hidden_states.size(0), -1, self.all_head_size)
|
| 561 |
+
return context_layer, None
|
| 562 |
+
|
| 563 |
+
# Fallback: PyTorch SDPA
|
| 564 |
+
mixed_query_layer = self.query(hidden_states)
|
| 565 |
+
|
| 566 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 567 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 568 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 569 |
+
|
| 570 |
+
context_layer = torch.nn.functional.scaled_dot_product_attention(
|
| 571 |
+
query_layer,
|
| 572 |
+
key_layer,
|
| 573 |
+
value_layer,
|
| 574 |
+
head_mask,
|
| 575 |
+
self.attention_probs_dropout_prob if self.training else 0.0,
|
| 576 |
+
is_causal=False,
|
| 577 |
+
scale=None,
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 581 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 582 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 583 |
+
|
| 584 |
+
return context_layer, None
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
# Copied from transformers.models.vit.modeling_vit.ViTSelfOutput with ViT->ViTMAE
|
| 588 |
+
class ViTMAESelfOutput(nn.Module):
|
| 589 |
+
"""
|
| 590 |
+
The residual connection is defined in ViTMAELayer instead of here (as is the case with other models), due to the
|
| 591 |
+
layernorm applied before each block.
|
| 592 |
+
"""
|
| 593 |
+
|
| 594 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 595 |
+
super().__init__()
|
| 596 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 597 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 598 |
+
|
| 599 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 600 |
+
hidden_states = self.dense(hidden_states)
|
| 601 |
+
hidden_states = self.dropout(hidden_states)
|
| 602 |
+
|
| 603 |
+
return hidden_states
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
# Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->ViTMAE
|
| 607 |
+
class ViTMAEAttention(nn.Module):
|
| 608 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 609 |
+
super().__init__()
|
| 610 |
+
self.attention = ViTMAESelfAttention(config)
|
| 611 |
+
self.output = ViTMAESelfOutput(config)
|
| 612 |
+
|
| 613 |
+
def forward(
|
| 614 |
+
self,
|
| 615 |
+
hidden_states: torch.Tensor,
|
| 616 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 617 |
+
output_attentions: bool = False,
|
| 618 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 619 |
+
self_outputs = self.attention(hidden_states, head_mask, output_attentions)
|
| 620 |
+
|
| 621 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 622 |
+
|
| 623 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 624 |
+
return outputs
|
| 625 |
+
|
| 626 |
+
# Copied from transformers.models.vit.modeling_vit.ViTIntermediate ViT->ViTMAE
|
| 627 |
+
class ViTMAEIntermediate(nn.Module):
|
| 628 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 629 |
+
super().__init__()
|
| 630 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 631 |
+
if isinstance(config.hidden_act, str):
|
| 632 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 633 |
+
else:
|
| 634 |
+
self.intermediate_act_fn = config.hidden_act
|
| 635 |
+
|
| 636 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 637 |
+
hidden_states = self.dense(hidden_states)
|
| 638 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 639 |
+
|
| 640 |
+
return hidden_states
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
# Copied from transformers.models.vit.modeling_vit.ViTOutput ViT->ViTMAE
|
| 644 |
+
class ViTMAEOutput(nn.Module):
|
| 645 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 646 |
+
super().__init__()
|
| 647 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 648 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 649 |
+
|
| 650 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 651 |
+
hidden_states = self.dense(hidden_states)
|
| 652 |
+
hidden_states = self.dropout(hidden_states)
|
| 653 |
+
|
| 654 |
+
hidden_states = hidden_states + input_tensor
|
| 655 |
+
|
| 656 |
+
return hidden_states
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
# Copied from transformers.models.vit.modeling_vit.ViTLayer with ViT->ViTMAE,VIT->VITMAE
|
| 661 |
+
class ViTMAELayer(nn.Module):
|
| 662 |
+
"""This corresponds to the Block class in the timm implementation."""
|
| 663 |
+
|
| 664 |
+
def __init__(self, config: ViTMAEConfig) -> None:
|
| 665 |
+
super().__init__()
|
| 666 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 667 |
+
self.seq_len_dim = 1
|
| 668 |
+
self.attention = ViTMAEAttention(config) # no SPDA by default
|
| 669 |
+
self.intermediate = ViTMAEIntermediate(config)
|
| 670 |
+
self.output = ViTMAEOutput(config)
|
| 671 |
+
self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 672 |
+
self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 673 |
+
|
| 674 |
+
def forward(
|
| 675 |
+
self,
|
| 676 |
+
hidden_states: torch.Tensor,
|
| 677 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 678 |
+
output_attentions: bool = False,
|
| 679 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 680 |
+
self_attention_outputs = self.attention(
|
| 681 |
+
self.layernorm_before(hidden_states), # in ViTMAE, layernorm is applied before self-attention
|
| 682 |
+
head_mask,
|
| 683 |
+
output_attentions=output_attentions,
|
| 684 |
+
)
|
| 685 |
+
attention_output = self_attention_outputs[0]
|
| 686 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 687 |
+
|
| 688 |
+
# first residual connection
|
| 689 |
+
hidden_states = attention_output + hidden_states
|
| 690 |
+
|
| 691 |
+
# in ViTMAE, layernorm is also applied after self-attention
|
| 692 |
+
layer_output = self.layernorm_after(hidden_states)
|
| 693 |
+
layer_output = self.intermediate(layer_output)
|
| 694 |
+
|
| 695 |
+
# second residual connection is done here
|
| 696 |
+
layer_output = self.output(layer_output, hidden_states)
|
| 697 |
+
|
| 698 |
+
outputs = (layer_output,) + outputs
|
| 699 |
+
|
| 700 |
+
return outputs
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
class GeneralDecoder(nn.Module):
|
| 704 |
+
def __init__(self, config, num_patches):
|
| 705 |
+
super().__init__()
|
| 706 |
+
self.decoder_embed = nn.Linear(config.hidden_size, config.decoder_hidden_size, bias=True)
|
| 707 |
+
self.decoder_pos_embed = nn.Parameter(
|
| 708 |
+
torch.zeros(1, num_patches + 1, config.decoder_hidden_size), requires_grad=False
|
| 709 |
+
) # fixed sin-cos embedding
|
| 710 |
+
|
| 711 |
+
decoder_config = deepcopy(config)
|
| 712 |
+
decoder_config.hidden_size = config.decoder_hidden_size
|
| 713 |
+
decoder_config.num_hidden_layers = config.decoder_num_hidden_layers
|
| 714 |
+
decoder_config.num_attention_heads = config.decoder_num_attention_heads
|
| 715 |
+
decoder_config.intermediate_size = config.decoder_intermediate_size
|
| 716 |
+
self.decoder_layers = nn.ModuleList(
|
| 717 |
+
[ViTMAELayer(decoder_config) for _ in range(config.decoder_num_hidden_layers)]
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
self.decoder_norm = nn.LayerNorm(config.decoder_hidden_size, eps=config.layer_norm_eps)
|
| 721 |
+
self.decoder_pred = nn.Linear(
|
| 722 |
+
config.decoder_hidden_size, config.patch_size**2 * config.num_channels, bias=True
|
| 723 |
+
) # encoder to decoder
|
| 724 |
+
self.gradient_checkpointing = False
|
| 725 |
+
self.config = config
|
| 726 |
+
self.num_patches = num_patches
|
| 727 |
+
self.initialize_weights(num_patches)
|
| 728 |
+
self.decoder_config = decoder_config
|
| 729 |
+
self.set_trainable_cls_token()
|
| 730 |
+
def set_trainable_cls_token(self, tensor: Optional[torch.Tensor] = None):
|
| 731 |
+
# register a trainable CLS token
|
| 732 |
+
tensor = torch.zeros(1, 1, self.decoder_config.hidden_size) if tensor is None else tensor
|
| 733 |
+
self.trainable_cls_token = nn.Parameter(tensor)
|
| 734 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor) -> torch.Tensor:
|
| 735 |
+
"""
|
| 736 |
+
This method is a modified version of the interpolation function for ViT-mae model at the deocder, that
|
| 737 |
+
allows to interpolate the pre-trained decoder position encodings, to be able to use the model on higher
|
| 738 |
+
resolution images.
|
| 739 |
+
|
| 740 |
+
Source:
|
| 741 |
+
https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174
|
| 742 |
+
"""
|
| 743 |
+
|
| 744 |
+
# -1 removes the class dimension since we later append it without interpolation
|
| 745 |
+
embeddings_positions = embeddings.shape[1] - 1
|
| 746 |
+
num_positions = self.decoder_pos_embed.shape[1] - 1
|
| 747 |
+
|
| 748 |
+
# Separation of class token and patch tokens
|
| 749 |
+
class_pos_embed = self.decoder_pos_embed[:, 0, :]
|
| 750 |
+
patch_pos_embed = self.decoder_pos_embed[:, 1:, :]
|
| 751 |
+
|
| 752 |
+
# To retain the final 3d tensor with the required dimensions
|
| 753 |
+
dim = self.decoder_pos_embed.shape[-1]
|
| 754 |
+
|
| 755 |
+
# Increasing a dimension to enable bicubic interpolation
|
| 756 |
+
patch_pos_embed = patch_pos_embed.reshape(1, 1, -1, dim)
|
| 757 |
+
|
| 758 |
+
# permute to bring the dimension to be interpolated, to the last
|
| 759 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 760 |
+
|
| 761 |
+
# Interpolating the decoder position embeddings shape wrt embeddings shape i.e (x).
|
| 762 |
+
# 1 keeps the other dimension constant
|
| 763 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 764 |
+
patch_pos_embed,
|
| 765 |
+
scale_factor=(1, embeddings_positions / num_positions),
|
| 766 |
+
mode="bicubic",
|
| 767 |
+
align_corners=False,
|
| 768 |
+
)
|
| 769 |
+
|
| 770 |
+
# Converting back to the original shape
|
| 771 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 772 |
+
# Adding the class token back
|
| 773 |
+
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
|
| 774 |
+
def interpolate_latent(self, x: torch.Tensor) -> torch.Tensor:
|
| 775 |
+
b, l, c = x.shape
|
| 776 |
+
if l == self.num_patches:
|
| 777 |
+
return x
|
| 778 |
+
# interpolate the latent
|
| 779 |
+
#print(f"interpolating latent from {l} to {self.num_patches}, x.shape = {x.shape}")
|
| 780 |
+
h, w = int(l**0.5), int(l**0.5)
|
| 781 |
+
x = x.reshape(b, h, w, c)
|
| 782 |
+
x = x.permute(0, 3, 1, 2)
|
| 783 |
+
target_size = (int(self.num_patches**0.5), int(self.num_patches**0.5))
|
| 784 |
+
x = nn.functional.interpolate(x, size=target_size, mode="bilinear", align_corners=False)
|
| 785 |
+
x = x.permute(0, 2, 3, 1).contiguous().view(b, self.num_patches, c)
|
| 786 |
+
return x
|
| 787 |
+
|
| 788 |
+
def initialize_weights(self, num_patches):
|
| 789 |
+
# initialize (and freeze) position embeddings by sin-cos embedding
|
| 790 |
+
decoder_pos_embed = get_2d_sincos_pos_embed(
|
| 791 |
+
self.decoder_pos_embed.shape[-1], int(num_patches**0.5), add_cls_token=True
|
| 792 |
+
)
|
| 793 |
+
self.decoder_pos_embed.data.copy_(torch.from_numpy(decoder_pos_embed).float().unsqueeze(0))
|
| 794 |
+
|
| 795 |
+
# timm's trunc_normal_(std=.02) is effectively normal_(std=0.02) as cutoff is too big (2.)
|
| 796 |
+
# torch.nn.init.normal_(self.mask_token, std=self.config.initializer_range)
|
| 797 |
+
def unpatchify(self, patchified_pixel_values, original_image_size: Optional[Tuple[int, int]] = None):
|
| 798 |
+
"""
|
| 799 |
+
Args:
|
| 800 |
+
patchified_pixel_values (`torch.FloatTensor` of shape `(batch_size, num_patches, patch_size**2 * num_channels)`:
|
| 801 |
+
Patchified pixel values.
|
| 802 |
+
original_image_size (`Tuple[int, int]`, *optional*):
|
| 803 |
+
Original image size.
|
| 804 |
+
|
| 805 |
+
Returns:
|
| 806 |
+
`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`:
|
| 807 |
+
Pixel values.
|
| 808 |
+
"""
|
| 809 |
+
patch_size, num_channels = self.config.patch_size, self.config.num_channels
|
| 810 |
+
original_image_size = (
|
| 811 |
+
original_image_size
|
| 812 |
+
if original_image_size is not None
|
| 813 |
+
else (self.config.image_size, self.config.image_size)
|
| 814 |
+
)
|
| 815 |
+
original_height, original_width = original_image_size
|
| 816 |
+
num_patches_h = original_height // patch_size
|
| 817 |
+
num_patches_w = original_width // patch_size
|
| 818 |
+
# sanity check
|
| 819 |
+
if num_patches_h * num_patches_w != patchified_pixel_values.shape[1]:
|
| 820 |
+
raise ValueError(
|
| 821 |
+
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}"
|
| 822 |
+
)
|
| 823 |
+
|
| 824 |
+
# unpatchify
|
| 825 |
+
batch_size = patchified_pixel_values.shape[0]
|
| 826 |
+
patchified_pixel_values = patchified_pixel_values.reshape(
|
| 827 |
+
batch_size,
|
| 828 |
+
num_patches_h,
|
| 829 |
+
num_patches_w,
|
| 830 |
+
patch_size,
|
| 831 |
+
patch_size,
|
| 832 |
+
num_channels,
|
| 833 |
+
)
|
| 834 |
+
patchified_pixel_values = torch.einsum("nhwpqc->nchpwq", patchified_pixel_values)
|
| 835 |
+
pixel_values = patchified_pixel_values.reshape(
|
| 836 |
+
batch_size,
|
| 837 |
+
num_channels,
|
| 838 |
+
num_patches_h * patch_size,
|
| 839 |
+
num_patches_w * patch_size,
|
| 840 |
+
)
|
| 841 |
+
return pixel_values
|
| 842 |
+
|
| 843 |
+
def forward(
|
| 844 |
+
self,
|
| 845 |
+
hidden_states,
|
| 846 |
+
output_attentions=False,
|
| 847 |
+
output_hidden_states=False,
|
| 848 |
+
return_dict=True,
|
| 849 |
+
interpolate_pos_encoding: bool = False,
|
| 850 |
+
drop_cls_token: bool = False,
|
| 851 |
+
):
|
| 852 |
+
# embed tokens
|
| 853 |
+
x = self.decoder_embed(hidden_states)
|
| 854 |
+
#print(f"x.shape = {x.shape}")
|
| 855 |
+
if drop_cls_token:
|
| 856 |
+
x_ = x[:, 1:, :] # no cls token
|
| 857 |
+
x_ = self.interpolate_latent(x_)
|
| 858 |
+
else:
|
| 859 |
+
x_ = self.interpolate_latent(x) # interpolate the whole latent
|
| 860 |
+
cls_token = self.trainable_cls_token.expand(x_.shape[0], -1, -1)
|
| 861 |
+
x = torch.cat([cls_token, x_], dim=1)
|
| 862 |
+
|
| 863 |
+
# add pos embed
|
| 864 |
+
if interpolate_pos_encoding:
|
| 865 |
+
assert drop_cls_token, "interpolate_pos_encoding only works with drop_cls_token=True"
|
| 866 |
+
decoder_pos_embed = self.interpolate_pos_encoding(x)
|
| 867 |
+
else:
|
| 868 |
+
decoder_pos_embed = self.decoder_pos_embed
|
| 869 |
+
hidden_states = x + decoder_pos_embed
|
| 870 |
+
#print(f"hidden_states.shape = {hidden_states.shape}")
|
| 871 |
+
# apply Transformer layers (blocks)
|
| 872 |
+
all_hidden_states = () if output_hidden_states else None
|
| 873 |
+
all_self_attentions = () if output_attentions else None
|
| 874 |
+
for i, layer_module in enumerate(self.decoder_layers):
|
| 875 |
+
if output_hidden_states:
|
| 876 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 877 |
+
|
| 878 |
+
if self.gradient_checkpointing and self.training:
|
| 879 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 880 |
+
layer_module.__call__,
|
| 881 |
+
hidden_states,
|
| 882 |
+
None,
|
| 883 |
+
output_attentions,
|
| 884 |
+
)
|
| 885 |
+
else:
|
| 886 |
+
layer_outputs = layer_module(hidden_states, head_mask=None, output_attentions=output_attentions)
|
| 887 |
+
|
| 888 |
+
hidden_states = layer_outputs[0]
|
| 889 |
+
|
| 890 |
+
if output_attentions:
|
| 891 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 892 |
+
|
| 893 |
+
if output_hidden_states:
|
| 894 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 895 |
+
|
| 896 |
+
hidden_states = self.decoder_norm(hidden_states)
|
| 897 |
+
|
| 898 |
+
# predictor projection
|
| 899 |
+
logits = self.decoder_pred(hidden_states)
|
| 900 |
+
|
| 901 |
+
# remove cls token
|
| 902 |
+
logits = logits[:, 1:, :]
|
| 903 |
+
|
| 904 |
+
if not return_dict:
|
| 905 |
+
return tuple(v for v in [logits, all_hidden_states, all_self_attentions] if v is not None)
|
| 906 |
+
return ViTMAEDecoderOutput(
|
| 907 |
+
logits=logits,
|
| 908 |
+
hidden_states=all_hidden_states,
|
| 909 |
+
attentions=all_self_attentions,
|
| 910 |
+
)
|
| 911 |
+
|
| 912 |
+
import json
|
| 913 |
+
from math import sqrt
|
| 914 |
+
from pathlib import Path
|
| 915 |
+
from typing import Any, Dict, Optional
|
| 916 |
+
|
| 917 |
+
import torch
|
| 918 |
+
import torch.nn as nn
|
| 919 |
+
from timm.models.vision_transformer import Attention
|
| 920 |
+
from transformers import AutoConfig, AutoImageProcessor
|
| 921 |
+
|
| 922 |
+
try:
|
| 923 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 924 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 925 |
+
except Exception: # pragma: no cover
|
| 926 |
+
class ConfigMixin:
|
| 927 |
+
config_name = "config.json"
|
| 928 |
+
|
| 929 |
+
class ModelMixin(nn.Module):
|
| 930 |
+
pass
|
| 931 |
+
|
| 932 |
+
def register_to_config(init):
|
| 933 |
+
return init
|
| 934 |
+
|
| 935 |
+
|
| 936 |
+
_PIXEL_DECODER_DEFAULTS: Dict[str, Any] = {
|
| 937 |
+
"decoder_hidden_size": 1024,
|
| 938 |
+
"decoder_intermediate_size": 4096,
|
| 939 |
+
"decoder_num_attention_heads": 16,
|
| 940 |
+
"decoder_num_hidden_layers": 24,
|
| 941 |
+
"layer_norm_eps": 1e-12,
|
| 942 |
+
"num_channels": 3,
|
| 943 |
+
"hidden_act": "gelu",
|
| 944 |
+
"qkv_bias": True,
|
| 945 |
+
"hidden_dropout_prob": 0.0,
|
| 946 |
+
"attention_probs_dropout_prob": 0.0,
|
| 947 |
+
"initializer_range": 0.02,
|
| 948 |
+
}
|
| 949 |
+
|
| 950 |
+
|
| 951 |
+
def _resolve_local_asset_path(path: str, model_root: Optional[Path] = None) -> str:
|
| 952 |
+
candidate = Path(path)
|
| 953 |
+
if candidate.is_file():
|
| 954 |
+
return str(candidate)
|
| 955 |
+
search_roots = []
|
| 956 |
+
if model_root is not None:
|
| 957 |
+
search_roots.extend([model_root, model_root.parent])
|
| 958 |
+
for root in search_roots:
|
| 959 |
+
for probe in (root / candidate, root / candidate.name, root / "decoder_config" / "config.json"):
|
| 960 |
+
if probe.is_file():
|
| 961 |
+
return str(probe)
|
| 962 |
+
return path
|
| 963 |
+
|
| 964 |
+
|
| 965 |
+
def _build_pixel_decoder_config(
|
| 966 |
+
*,
|
| 967 |
+
encoder_hidden_size: int,
|
| 968 |
+
decoder_patch_size: int,
|
| 969 |
+
base_patches: int,
|
| 970 |
+
decoder_config_path: Optional[str] = None,
|
| 971 |
+
overrides: Optional[Dict[str, Any]] = None,
|
| 972 |
+
) -> ViTMAEConfig:
|
| 973 |
+
pixel_decoder = dict(_PIXEL_DECODER_DEFAULTS)
|
| 974 |
+
if decoder_config_path is not None:
|
| 975 |
+
resolved = _resolve_local_asset_path(decoder_config_path)
|
| 976 |
+
if Path(resolved).is_file():
|
| 977 |
+
with open(resolved, encoding="utf-8") as handle:
|
| 978 |
+
pixel_decoder.update(json.load(handle))
|
| 979 |
+
if overrides:
|
| 980 |
+
pixel_decoder.update({key: value for key, value in overrides.items() if value is not None})
|
| 981 |
+
|
| 982 |
+
return ViTMAEConfig(
|
| 983 |
+
hidden_size=encoder_hidden_size,
|
| 984 |
+
patch_size=decoder_patch_size,
|
| 985 |
+
image_size=int(decoder_patch_size * sqrt(base_patches)),
|
| 986 |
+
**pixel_decoder,
|
| 987 |
+
)
|
| 988 |
+
|
| 989 |
+
|
| 990 |
+
def _load_image_normalization(encoder_config_path: str) -> tuple[list[float], list[float]]:
|
| 991 |
+
try:
|
| 992 |
+
proc = AutoImageProcessor.from_pretrained(encoder_config_path, use_fast=True, local_files_only=True)
|
| 993 |
+
return proc.image_mean, proc.image_std
|
| 994 |
+
except Exception:
|
| 995 |
+
pass
|
| 996 |
+
try:
|
| 997 |
+
proc = AutoImageProcessor.from_pretrained(encoder_config_path, use_fast=True, local_files_only=False)
|
| 998 |
+
return proc.image_mean, proc.image_std
|
| 999 |
+
except Exception:
|
| 1000 |
+
if "siglip" in encoder_config_path.lower():
|
| 1001 |
+
return [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]
|
| 1002 |
+
return [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
|
| 1003 |
+
|
| 1004 |
+
|
| 1005 |
+
class PAEDecoder(ModelMixin, ConfigMixin):
|
| 1006 |
+
"""PAE decoder: latent decompressor + ViT-MAE pixel decoder."""
|
| 1007 |
+
|
| 1008 |
+
@register_to_config
|
| 1009 |
+
def __init__(
|
| 1010 |
+
self,
|
| 1011 |
+
encoder_hidden_size: int = 1024,
|
| 1012 |
+
encoder_num_heads: int = 16,
|
| 1013 |
+
encoder_input_size: int = 224,
|
| 1014 |
+
encoder_patch_size: int = 14,
|
| 1015 |
+
encoder_config_path: str = "facebook/dinov2-with-registers-large",
|
| 1016 |
+
latent_dim: int = 32,
|
| 1017 |
+
decoder_patch_size: int = 16,
|
| 1018 |
+
decoder_config_path: Optional[str] = None,
|
| 1019 |
+
decoder_hidden_size: int = 1024,
|
| 1020 |
+
decoder_intermediate_size: int = 4096,
|
| 1021 |
+
decoder_num_attention_heads: int = 16,
|
| 1022 |
+
decoder_num_hidden_layers: int = 24,
|
| 1023 |
+
layer_norm_eps: float = 1e-12,
|
| 1024 |
+
num_channels: int = 3,
|
| 1025 |
+
hidden_act: str = "gelu",
|
| 1026 |
+
qkv_bias: bool = True,
|
| 1027 |
+
hidden_dropout_prob: float = 0.0,
|
| 1028 |
+
attention_probs_dropout_prob: float = 0.0,
|
| 1029 |
+
initializer_range: float = 0.02,
|
| 1030 |
+
image_mean: Optional[list[float]] = None,
|
| 1031 |
+
image_std: Optional[list[float]] = None,
|
| 1032 |
+
latent_mean: Optional[list[float]] = None,
|
| 1033 |
+
latent_std: Optional[list[float]] = None,
|
| 1034 |
+
latent_multiplier: float = 1.0,
|
| 1035 |
+
**kwargs,
|
| 1036 |
+
) -> None:
|
| 1037 |
+
super().__init__()
|
| 1038 |
+
if image_mean is not None and image_std is not None:
|
| 1039 |
+
norm_mean, norm_std = image_mean, image_std
|
| 1040 |
+
else:
|
| 1041 |
+
norm_mean, norm_std = _load_image_normalization(encoder_config_path)
|
| 1042 |
+
self.register_buffer("encoder_mean", torch.tensor(norm_mean).view(1, 3, 1, 1), persistent=True)
|
| 1043 |
+
self.register_buffer("encoder_std", torch.tensor(norm_std).view(1, 3, 1, 1), persistent=True)
|
| 1044 |
+
|
| 1045 |
+
self.encoder_input_size = encoder_input_size
|
| 1046 |
+
self.encoder_patch_size = encoder_patch_size
|
| 1047 |
+
self.base_patches = (self.encoder_input_size // self.encoder_patch_size) ** 2
|
| 1048 |
+
self.latent_dim = latent_dim
|
| 1049 |
+
|
| 1050 |
+
self.latent_decompressor = nn.ModuleList(
|
| 1051 |
+
[
|
| 1052 |
+
nn.Conv2d(latent_dim, encoder_hidden_size, kernel_size=3, padding=1),
|
| 1053 |
+
Attention(dim=encoder_hidden_size, num_heads=encoder_num_heads),
|
| 1054 |
+
]
|
| 1055 |
+
)
|
| 1056 |
+
|
| 1057 |
+
pixel_decoder_config = _build_pixel_decoder_config(
|
| 1058 |
+
encoder_hidden_size=encoder_hidden_size,
|
| 1059 |
+
decoder_patch_size=decoder_patch_size,
|
| 1060 |
+
base_patches=self.base_patches,
|
| 1061 |
+
decoder_config_path=decoder_config_path,
|
| 1062 |
+
overrides={
|
| 1063 |
+
"decoder_hidden_size": decoder_hidden_size,
|
| 1064 |
+
"decoder_intermediate_size": decoder_intermediate_size,
|
| 1065 |
+
"decoder_num_attention_heads": decoder_num_attention_heads,
|
| 1066 |
+
"decoder_num_hidden_layers": decoder_num_hidden_layers,
|
| 1067 |
+
"layer_norm_eps": layer_norm_eps,
|
| 1068 |
+
"num_channels": num_channels,
|
| 1069 |
+
"hidden_act": hidden_act,
|
| 1070 |
+
"qkv_bias": qkv_bias,
|
| 1071 |
+
"hidden_dropout_prob": hidden_dropout_prob,
|
| 1072 |
+
"attention_probs_dropout_prob": attention_probs_dropout_prob,
|
| 1073 |
+
"initializer_range": initializer_range,
|
| 1074 |
+
},
|
| 1075 |
+
)
|
| 1076 |
+
self.decoder = GeneralDecoder(pixel_decoder_config, num_patches=self.base_patches)
|
| 1077 |
+
|
| 1078 |
+
@classmethod
|
| 1079 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 1080 |
+
model_root = Path(pretrained_model_name_or_path)
|
| 1081 |
+
config_file = model_root / cls.config_name
|
| 1082 |
+
if config_file.is_file():
|
| 1083 |
+
with open(config_file, encoding="utf-8") as handle:
|
| 1084 |
+
config = json.load(handle)
|
| 1085 |
+
decoder_config_path = config.get("decoder_config_path")
|
| 1086 |
+
if decoder_config_path is not None:
|
| 1087 |
+
resolved = _resolve_local_asset_path(decoder_config_path, model_root=model_root)
|
| 1088 |
+
if resolved != decoder_config_path:
|
| 1089 |
+
kwargs.setdefault("decoder_config_path", resolved)
|
| 1090 |
+
return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
|
| 1091 |
+
|
| 1092 |
+
def decode(self, latents: torch.Tensor) -> torch.Tensor:
|
| 1093 |
+
hidden_states = self.latent_decompressor[0](latents)
|
| 1094 |
+
batch_size, channels, height, width = hidden_states.shape
|
| 1095 |
+
num_tokens = height * width
|
| 1096 |
+
hidden_states = hidden_states.view(batch_size, channels, num_tokens).transpose(1, 2)
|
| 1097 |
+
hidden_states = self.latent_decompressor[1](hidden_states)
|
| 1098 |
+
|
| 1099 |
+
output = self.decoder(hidden_states, drop_cls_token=False).logits
|
| 1100 |
+
x_rec = self.decoder.unpatchify(output)
|
| 1101 |
+
x_rec = x_rec * self.encoder_std.to(x_rec.device) + self.encoder_mean.to(x_rec.device)
|
| 1102 |
+
return x_rec
|
| 1103 |
+
|
| 1104 |
+
def forward(self, latents: torch.Tensor) -> torch.Tensor:
|
| 1105 |
+
return self.decode(latents)
|
pae-siglip2-so400m-d32/decoder/diffusion_pytorch_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e1ff5e7b81fa169348b91fc9833bf4c66059e73393794934514eceb4c94f18d8
|
| 3 |
+
size 1240792960
|
pae-siglip2-so400m-d32/demo.png
ADDED
|
Git LFS Details
|
pae-siglip2-so400m-d32/model_index.json
ADDED
|
@@ -0,0 +1,1021 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": [
|
| 3 |
+
"pipeline",
|
| 4 |
+
"PAEPipeline"
|
| 5 |
+
],
|
| 6 |
+
"_diffusers_version": "0.31.0",
|
| 7 |
+
"decoder": [
|
| 8 |
+
"decoder_pae",
|
| 9 |
+
"PAEDecoder"
|
| 10 |
+
],
|
| 11 |
+
"id2label": {
|
| 12 |
+
"0": "tench, Tinca tinca",
|
| 13 |
+
"1": "goldfish, Carassius auratus",
|
| 14 |
+
"2": "great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias",
|
| 15 |
+
"3": "tiger shark, Galeocerdo cuvieri",
|
| 16 |
+
"4": "hammerhead, hammerhead shark",
|
| 17 |
+
"5": "electric ray, crampfish, numbfish, torpedo",
|
| 18 |
+
"6": "stingray",
|
| 19 |
+
"7": "cock",
|
| 20 |
+
"8": "hen",
|
| 21 |
+
"9": "ostrich, Struthio camelus",
|
| 22 |
+
"10": "brambling, Fringilla montifringilla",
|
| 23 |
+
"11": "goldfinch, Carduelis carduelis",
|
| 24 |
+
"12": "house finch, linnet, Carpodacus mexicanus",
|
| 25 |
+
"13": "junco, snowbird",
|
| 26 |
+
"14": "indigo bunting, indigo finch, indigo bird, Passerina cyanea",
|
| 27 |
+
"15": "robin, American robin, Turdus migratorius",
|
| 28 |
+
"16": "bulbul",
|
| 29 |
+
"17": "jay",
|
| 30 |
+
"18": "magpie",
|
| 31 |
+
"19": "chickadee",
|
| 32 |
+
"20": "water ouzel, dipper",
|
| 33 |
+
"21": "kite",
|
| 34 |
+
"22": "bald eagle, American eagle, Haliaeetus leucocephalus",
|
| 35 |
+
"23": "vulture",
|
| 36 |
+
"24": "great grey owl, great gray owl, Strix nebulosa",
|
| 37 |
+
"25": "European fire salamander, Salamandra salamandra",
|
| 38 |
+
"26": "common newt, Triturus vulgaris",
|
| 39 |
+
"27": "eft",
|
| 40 |
+
"28": "spotted salamander, Ambystoma maculatum",
|
| 41 |
+
"29": "axolotl, mud puppy, Ambystoma mexicanum",
|
| 42 |
+
"30": "bullfrog, Rana catesbeiana",
|
| 43 |
+
"31": "tree frog, tree-frog",
|
| 44 |
+
"32": "tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui",
|
| 45 |
+
"33": "loggerhead, loggerhead turtle, Caretta caretta",
|
| 46 |
+
"34": "leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea",
|
| 47 |
+
"35": "mud turtle",
|
| 48 |
+
"36": "terrapin",
|
| 49 |
+
"37": "box turtle, box tortoise",
|
| 50 |
+
"38": "banded gecko",
|
| 51 |
+
"39": "common iguana, iguana, Iguana iguana",
|
| 52 |
+
"40": "American chameleon, anole, Anolis carolinensis",
|
| 53 |
+
"41": "whiptail, whiptail lizard",
|
| 54 |
+
"42": "agama",
|
| 55 |
+
"43": "frilled lizard, Chlamydosaurus kingi",
|
| 56 |
+
"44": "alligator lizard",
|
| 57 |
+
"45": "Gila monster, Heloderma suspectum",
|
| 58 |
+
"46": "green lizard, Lacerta viridis",
|
| 59 |
+
"47": "African chameleon, Chamaeleo chamaeleon",
|
| 60 |
+
"48": "Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis",
|
| 61 |
+
"49": "African crocodile, Nile crocodile, Crocodylus niloticus",
|
| 62 |
+
"50": "American alligator, Alligator mississipiensis",
|
| 63 |
+
"51": "triceratops",
|
| 64 |
+
"52": "thunder snake, worm snake, Carphophis amoenus",
|
| 65 |
+
"53": "ringneck snake, ring-necked snake, ring snake",
|
| 66 |
+
"54": "hognose snake, puff adder, sand viper",
|
| 67 |
+
"55": "green snake, grass snake",
|
| 68 |
+
"56": "king snake, kingsnake",
|
| 69 |
+
"57": "garter snake, grass snake",
|
| 70 |
+
"58": "water snake",
|
| 71 |
+
"59": "vine snake",
|
| 72 |
+
"60": "night snake, Hypsiglena torquata",
|
| 73 |
+
"61": "boa constrictor, Constrictor constrictor",
|
| 74 |
+
"62": "rock python, rock snake, Python sebae",
|
| 75 |
+
"63": "Indian cobra, Naja naja",
|
| 76 |
+
"64": "green mamba",
|
| 77 |
+
"65": "sea snake",
|
| 78 |
+
"66": "horned viper, cerastes, sand viper, horned asp, Cerastes cornutus",
|
| 79 |
+
"67": "diamondback, diamondback rattlesnake, Crotalus adamanteus",
|
| 80 |
+
"68": "sidewinder, horned rattlesnake, Crotalus cerastes",
|
| 81 |
+
"69": "trilobite",
|
| 82 |
+
"70": "harvestman, daddy longlegs, Phalangium opilio",
|
| 83 |
+
"71": "scorpion",
|
| 84 |
+
"72": "black and gold garden spider, Argiope aurantia",
|
| 85 |
+
"73": "barn spider, Araneus cavaticus",
|
| 86 |
+
"74": "garden spider, Aranea diademata",
|
| 87 |
+
"75": "black widow, Latrodectus mactans",
|
| 88 |
+
"76": "tarantula",
|
| 89 |
+
"77": "wolf spider, hunting spider",
|
| 90 |
+
"78": "tick",
|
| 91 |
+
"79": "centipede",
|
| 92 |
+
"80": "black grouse",
|
| 93 |
+
"81": "ptarmigan",
|
| 94 |
+
"82": "ruffed grouse, partridge, Bonasa umbellus",
|
| 95 |
+
"83": "prairie chicken, prairie grouse, prairie fowl",
|
| 96 |
+
"84": "peacock",
|
| 97 |
+
"85": "quail",
|
| 98 |
+
"86": "partridge",
|
| 99 |
+
"87": "African grey, African gray, Psittacus erithacus",
|
| 100 |
+
"88": "macaw",
|
| 101 |
+
"89": "sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita",
|
| 102 |
+
"90": "lorikeet",
|
| 103 |
+
"91": "coucal",
|
| 104 |
+
"92": "bee eater",
|
| 105 |
+
"93": "hornbill",
|
| 106 |
+
"94": "hummingbird",
|
| 107 |
+
"95": "jacamar",
|
| 108 |
+
"96": "toucan",
|
| 109 |
+
"97": "drake",
|
| 110 |
+
"98": "red-breasted merganser, Mergus serrator",
|
| 111 |
+
"99": "goose",
|
| 112 |
+
"100": "black swan, Cygnus atratus",
|
| 113 |
+
"101": "tusker",
|
| 114 |
+
"102": "echidna, spiny anteater, anteater",
|
| 115 |
+
"103": "platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus",
|
| 116 |
+
"104": "wallaby, brush kangaroo",
|
| 117 |
+
"105": "koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus",
|
| 118 |
+
"106": "wombat",
|
| 119 |
+
"107": "jellyfish",
|
| 120 |
+
"108": "sea anemone, anemone",
|
| 121 |
+
"109": "brain coral",
|
| 122 |
+
"110": "flatworm, platyhelminth",
|
| 123 |
+
"111": "nematode, nematode worm, roundworm",
|
| 124 |
+
"112": "conch",
|
| 125 |
+
"113": "snail",
|
| 126 |
+
"114": "slug",
|
| 127 |
+
"115": "sea slug, nudibranch",
|
| 128 |
+
"116": "chiton, coat-of-mail shell, sea cradle, polyplacophore",
|
| 129 |
+
"117": "chambered nautilus, pearly nautilus, nautilus",
|
| 130 |
+
"118": "Dungeness crab, Cancer magister",
|
| 131 |
+
"119": "rock crab, Cancer irroratus",
|
| 132 |
+
"120": "fiddler crab",
|
| 133 |
+
"121": "king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica",
|
| 134 |
+
"122": "American lobster, Northern lobster, Maine lobster, Homarus americanus",
|
| 135 |
+
"123": "spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish",
|
| 136 |
+
"124": "crayfish, crawfish, crawdad, crawdaddy",
|
| 137 |
+
"125": "hermit crab",
|
| 138 |
+
"126": "isopod",
|
| 139 |
+
"127": "white stork, Ciconia ciconia",
|
| 140 |
+
"128": "black stork, Ciconia nigra",
|
| 141 |
+
"129": "spoonbill",
|
| 142 |
+
"130": "flamingo",
|
| 143 |
+
"131": "little blue heron, Egretta caerulea",
|
| 144 |
+
"132": "American egret, great white heron, Egretta albus",
|
| 145 |
+
"133": "bittern",
|
| 146 |
+
"134": "crane",
|
| 147 |
+
"135": "limpkin, Aramus pictus",
|
| 148 |
+
"136": "European gallinule, Porphyrio porphyrio",
|
| 149 |
+
"137": "American coot, marsh hen, mud hen, water hen, Fulica americana",
|
| 150 |
+
"138": "bustard",
|
| 151 |
+
"139": "ruddy turnstone, Arenaria interpres",
|
| 152 |
+
"140": "red-backed sandpiper, dunlin, Erolia alpina",
|
| 153 |
+
"141": "redshank, Tringa totanus",
|
| 154 |
+
"142": "dowitcher",
|
| 155 |
+
"143": "oystercatcher, oyster catcher",
|
| 156 |
+
"144": "pelican",
|
| 157 |
+
"145": "king penguin, Aptenodytes patagonica",
|
| 158 |
+
"146": "albatross, mollymawk",
|
| 159 |
+
"147": "grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus",
|
| 160 |
+
"148": "killer whale, killer, orca, grampus, sea wolf, Orcinus orca",
|
| 161 |
+
"149": "dugong, Dugong dugon",
|
| 162 |
+
"150": "sea lion",
|
| 163 |
+
"151": "Chihuahua",
|
| 164 |
+
"152": "Japanese spaniel",
|
| 165 |
+
"153": "Maltese dog, Maltese terrier, Maltese",
|
| 166 |
+
"154": "Pekinese, Pekingese, Peke",
|
| 167 |
+
"155": "Shih-Tzu",
|
| 168 |
+
"156": "Blenheim spaniel",
|
| 169 |
+
"157": "papillon",
|
| 170 |
+
"158": "toy terrier",
|
| 171 |
+
"159": "Rhodesian ridgeback",
|
| 172 |
+
"160": "Afghan hound, Afghan",
|
| 173 |
+
"161": "basset, basset hound",
|
| 174 |
+
"162": "beagle",
|
| 175 |
+
"163": "bloodhound, sleuthhound",
|
| 176 |
+
"164": "bluetick",
|
| 177 |
+
"165": "black-and-tan coonhound",
|
| 178 |
+
"166": "Walker hound, Walker foxhound",
|
| 179 |
+
"167": "English foxhound",
|
| 180 |
+
"168": "redbone",
|
| 181 |
+
"169": "borzoi, Russian wolfhound",
|
| 182 |
+
"170": "Irish wolfhound",
|
| 183 |
+
"171": "Italian greyhound",
|
| 184 |
+
"172": "whippet",
|
| 185 |
+
"173": "Ibizan hound, Ibizan Podenco",
|
| 186 |
+
"174": "Norwegian elkhound, elkhound",
|
| 187 |
+
"175": "otterhound, otter hound",
|
| 188 |
+
"176": "Saluki, gazelle hound",
|
| 189 |
+
"177": "Scottish deerhound, deerhound",
|
| 190 |
+
"178": "Weimaraner",
|
| 191 |
+
"179": "Staffordshire bullterrier, Staffordshire bull terrier",
|
| 192 |
+
"180": "American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier",
|
| 193 |
+
"181": "Bedlington terrier",
|
| 194 |
+
"182": "Border terrier",
|
| 195 |
+
"183": "Kerry blue terrier",
|
| 196 |
+
"184": "Irish terrier",
|
| 197 |
+
"185": "Norfolk terrier",
|
| 198 |
+
"186": "Norwich terrier",
|
| 199 |
+
"187": "Yorkshire terrier",
|
| 200 |
+
"188": "wire-haired fox terrier",
|
| 201 |
+
"189": "Lakeland terrier",
|
| 202 |
+
"190": "Sealyham terrier, Sealyham",
|
| 203 |
+
"191": "Airedale, Airedale terrier",
|
| 204 |
+
"192": "cairn, cairn terrier",
|
| 205 |
+
"193": "Australian terrier",
|
| 206 |
+
"194": "Dandie Dinmont, Dandie Dinmont terrier",
|
| 207 |
+
"195": "Boston bull, Boston terrier",
|
| 208 |
+
"196": "miniature schnauzer",
|
| 209 |
+
"197": "giant schnauzer",
|
| 210 |
+
"198": "standard schnauzer",
|
| 211 |
+
"199": "Scotch terrier, Scottish terrier, Scottie",
|
| 212 |
+
"200": "Tibetan terrier, chrysanthemum dog",
|
| 213 |
+
"201": "silky terrier, Sydney silky",
|
| 214 |
+
"202": "soft-coated wheaten terrier",
|
| 215 |
+
"203": "West Highland white terrier",
|
| 216 |
+
"204": "Lhasa, Lhasa apso",
|
| 217 |
+
"205": "flat-coated retriever",
|
| 218 |
+
"206": "curly-coated retriever",
|
| 219 |
+
"207": "golden retriever",
|
| 220 |
+
"208": "Labrador retriever",
|
| 221 |
+
"209": "Chesapeake Bay retriever",
|
| 222 |
+
"210": "German short-haired pointer",
|
| 223 |
+
"211": "vizsla, Hungarian pointer",
|
| 224 |
+
"212": "English setter",
|
| 225 |
+
"213": "Irish setter, red setter",
|
| 226 |
+
"214": "Gordon setter",
|
| 227 |
+
"215": "Brittany spaniel",
|
| 228 |
+
"216": "clumber, clumber spaniel",
|
| 229 |
+
"217": "English springer, English springer spaniel",
|
| 230 |
+
"218": "Welsh springer spaniel",
|
| 231 |
+
"219": "cocker spaniel, English cocker spaniel, cocker",
|
| 232 |
+
"220": "Sussex spaniel",
|
| 233 |
+
"221": "Irish water spaniel",
|
| 234 |
+
"222": "kuvasz",
|
| 235 |
+
"223": "schipperke",
|
| 236 |
+
"224": "groenendael",
|
| 237 |
+
"225": "malinois",
|
| 238 |
+
"226": "briard",
|
| 239 |
+
"227": "kelpie",
|
| 240 |
+
"228": "komondor",
|
| 241 |
+
"229": "Old English sheepdog, bobtail",
|
| 242 |
+
"230": "Shetland sheepdog, Shetland sheep dog, Shetland",
|
| 243 |
+
"231": "collie",
|
| 244 |
+
"232": "Border collie",
|
| 245 |
+
"233": "Bouvier des Flandres, Bouviers des Flandres",
|
| 246 |
+
"234": "Rottweiler",
|
| 247 |
+
"235": "German shepherd, German shepherd dog, German police dog, alsatian",
|
| 248 |
+
"236": "Doberman, Doberman pinscher",
|
| 249 |
+
"237": "miniature pinscher",
|
| 250 |
+
"238": "Greater Swiss Mountain dog",
|
| 251 |
+
"239": "Bernese mountain dog",
|
| 252 |
+
"240": "Appenzeller",
|
| 253 |
+
"241": "EntleBucher",
|
| 254 |
+
"242": "boxer",
|
| 255 |
+
"243": "bull mastiff",
|
| 256 |
+
"244": "Tibetan mastiff",
|
| 257 |
+
"245": "French bulldog",
|
| 258 |
+
"246": "Great Dane",
|
| 259 |
+
"247": "Saint Bernard, St Bernard",
|
| 260 |
+
"248": "Eskimo dog, husky",
|
| 261 |
+
"249": "malamute, malemute, Alaskan malamute",
|
| 262 |
+
"250": "Siberian husky",
|
| 263 |
+
"251": "dalmatian, coach dog, carriage dog",
|
| 264 |
+
"252": "affenpinscher, monkey pinscher, monkey dog",
|
| 265 |
+
"253": "basenji",
|
| 266 |
+
"254": "pug, pug-dog",
|
| 267 |
+
"255": "Leonberg",
|
| 268 |
+
"256": "Newfoundland, Newfoundland dog",
|
| 269 |
+
"257": "Great Pyrenees",
|
| 270 |
+
"258": "Samoyed, Samoyede",
|
| 271 |
+
"259": "Pomeranian",
|
| 272 |
+
"260": "chow, chow chow",
|
| 273 |
+
"261": "keeshond",
|
| 274 |
+
"262": "Brabancon griffon",
|
| 275 |
+
"263": "Pembroke, Pembroke Welsh corgi",
|
| 276 |
+
"264": "Cardigan, Cardigan Welsh corgi",
|
| 277 |
+
"265": "toy poodle",
|
| 278 |
+
"266": "miniature poodle",
|
| 279 |
+
"267": "standard poodle",
|
| 280 |
+
"268": "Mexican hairless",
|
| 281 |
+
"269": "timber wolf, grey wolf, gray wolf, Canis lupus",
|
| 282 |
+
"270": "white wolf, Arctic wolf, Canis lupus tundrarum",
|
| 283 |
+
"271": "red wolf, maned wolf, Canis rufus, Canis niger",
|
| 284 |
+
"272": "coyote, prairie wolf, brush wolf, Canis latrans",
|
| 285 |
+
"273": "dingo, warrigal, warragal, Canis dingo",
|
| 286 |
+
"274": "dhole, Cuon alpinus",
|
| 287 |
+
"275": "African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus",
|
| 288 |
+
"276": "hyena, hyaena",
|
| 289 |
+
"277": "red fox, Vulpes vulpes",
|
| 290 |
+
"278": "kit fox, Vulpes macrotis",
|
| 291 |
+
"279": "Arctic fox, white fox, Alopex lagopus",
|
| 292 |
+
"280": "grey fox, gray fox, Urocyon cinereoargenteus",
|
| 293 |
+
"281": "tabby, tabby cat",
|
| 294 |
+
"282": "tiger cat",
|
| 295 |
+
"283": "Persian cat",
|
| 296 |
+
"284": "Siamese cat, Siamese",
|
| 297 |
+
"285": "Egyptian cat",
|
| 298 |
+
"286": "cougar, puma, catamount, mountain lion, painter, panther, Felis concolor",
|
| 299 |
+
"287": "lynx, catamount",
|
| 300 |
+
"288": "leopard, Panthera pardus",
|
| 301 |
+
"289": "snow leopard, ounce, Panthera uncia",
|
| 302 |
+
"290": "jaguar, panther, Panthera onca, Felis onca",
|
| 303 |
+
"291": "lion, king of beasts, Panthera leo",
|
| 304 |
+
"292": "tiger, Panthera tigris",
|
| 305 |
+
"293": "cheetah, chetah, Acinonyx jubatus",
|
| 306 |
+
"294": "brown bear, bruin, Ursus arctos",
|
| 307 |
+
"295": "American black bear, black bear, Ursus americanus, Euarctos americanus",
|
| 308 |
+
"296": "ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus",
|
| 309 |
+
"297": "sloth bear, Melursus ursinus, Ursus ursinus",
|
| 310 |
+
"298": "mongoose",
|
| 311 |
+
"299": "meerkat, mierkat",
|
| 312 |
+
"300": "tiger beetle",
|
| 313 |
+
"301": "ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle",
|
| 314 |
+
"302": "ground beetle, carabid beetle",
|
| 315 |
+
"303": "long-horned beetle, longicorn, longicorn beetle",
|
| 316 |
+
"304": "leaf beetle, chrysomelid",
|
| 317 |
+
"305": "dung beetle",
|
| 318 |
+
"306": "rhinoceros beetle",
|
| 319 |
+
"307": "weevil",
|
| 320 |
+
"308": "fly",
|
| 321 |
+
"309": "bee",
|
| 322 |
+
"310": "ant, emmet, pismire",
|
| 323 |
+
"311": "grasshopper, hopper",
|
| 324 |
+
"312": "cricket",
|
| 325 |
+
"313": "walking stick, walkingstick, stick insect",
|
| 326 |
+
"314": "cockroach, roach",
|
| 327 |
+
"315": "mantis, mantid",
|
| 328 |
+
"316": "cicada, cicala",
|
| 329 |
+
"317": "leafhopper",
|
| 330 |
+
"318": "lacewing, lacewing fly",
|
| 331 |
+
"319": "dragonfly, darning needle, devils darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk",
|
| 332 |
+
"320": "damselfly",
|
| 333 |
+
"321": "admiral",
|
| 334 |
+
"322": "ringlet, ringlet butterfly",
|
| 335 |
+
"323": "monarch, monarch butterfly, milkweed butterfly, Danaus plexippus",
|
| 336 |
+
"324": "cabbage butterfly",
|
| 337 |
+
"325": "sulphur butterfly, sulfur butterfly",
|
| 338 |
+
"326": "lycaenid, lycaenid butterfly",
|
| 339 |
+
"327": "starfish, sea star",
|
| 340 |
+
"328": "sea urchin",
|
| 341 |
+
"329": "sea cucumber, holothurian",
|
| 342 |
+
"330": "wood rabbit, cottontail, cottontail rabbit",
|
| 343 |
+
"331": "hare",
|
| 344 |
+
"332": "Angora, Angora rabbit",
|
| 345 |
+
"333": "hamster",
|
| 346 |
+
"334": "porcupine, hedgehog",
|
| 347 |
+
"335": "fox squirrel, eastern fox squirrel, Sciurus niger",
|
| 348 |
+
"336": "marmot",
|
| 349 |
+
"337": "beaver",
|
| 350 |
+
"338": "guinea pig, Cavia cobaya",
|
| 351 |
+
"339": "sorrel",
|
| 352 |
+
"340": "zebra",
|
| 353 |
+
"341": "hog, pig, grunter, squealer, Sus scrofa",
|
| 354 |
+
"342": "wild boar, boar, Sus scrofa",
|
| 355 |
+
"343": "warthog",
|
| 356 |
+
"344": "hippopotamus, hippo, river horse, Hippopotamus amphibius",
|
| 357 |
+
"345": "ox",
|
| 358 |
+
"346": "water buffalo, water ox, Asiatic buffalo, Bubalus bubalis",
|
| 359 |
+
"347": "bison",
|
| 360 |
+
"348": "ram, tup",
|
| 361 |
+
"349": "bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis",
|
| 362 |
+
"350": "ibex, Capra ibex",
|
| 363 |
+
"351": "hartebeest",
|
| 364 |
+
"352": "impala, Aepyceros melampus",
|
| 365 |
+
"353": "gazelle",
|
| 366 |
+
"354": "Arabian camel, dromedary, Camelus dromedarius",
|
| 367 |
+
"355": "llama",
|
| 368 |
+
"356": "weasel",
|
| 369 |
+
"357": "mink",
|
| 370 |
+
"358": "polecat, fitch, foulmart, foumart, Mustela putorius",
|
| 371 |
+
"359": "black-footed ferret, ferret, Mustela nigripes",
|
| 372 |
+
"360": "otter",
|
| 373 |
+
"361": "skunk, polecat, wood pussy",
|
| 374 |
+
"362": "badger",
|
| 375 |
+
"363": "armadillo",
|
| 376 |
+
"364": "three-toed sloth, ai, Bradypus tridactylus",
|
| 377 |
+
"365": "orangutan, orang, orangutang, Pongo pygmaeus",
|
| 378 |
+
"366": "gorilla, Gorilla gorilla",
|
| 379 |
+
"367": "chimpanzee, chimp, Pan troglodytes",
|
| 380 |
+
"368": "gibbon, Hylobates lar",
|
| 381 |
+
"369": "siamang, Hylobates syndactylus, Symphalangus syndactylus",
|
| 382 |
+
"370": "guenon, guenon monkey",
|
| 383 |
+
"371": "patas, hussar monkey, Erythrocebus patas",
|
| 384 |
+
"372": "baboon",
|
| 385 |
+
"373": "macaque",
|
| 386 |
+
"374": "langur",
|
| 387 |
+
"375": "colobus, colobus monkey",
|
| 388 |
+
"376": "proboscis monkey, Nasalis larvatus",
|
| 389 |
+
"377": "marmoset",
|
| 390 |
+
"378": "capuchin, ringtail, Cebus capucinus",
|
| 391 |
+
"379": "howler monkey, howler",
|
| 392 |
+
"380": "titi, titi monkey",
|
| 393 |
+
"381": "spider monkey, Ateles geoffroyi",
|
| 394 |
+
"382": "squirrel monkey, Saimiri sciureus",
|
| 395 |
+
"383": "Madagascar cat, ring-tailed lemur, Lemur catta",
|
| 396 |
+
"384": "indri, indris, Indri indri, Indri brevicaudatus",
|
| 397 |
+
"385": "Indian elephant, Elephas maximus",
|
| 398 |
+
"386": "African elephant, Loxodonta africana",
|
| 399 |
+
"387": "lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens",
|
| 400 |
+
"388": "giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca",
|
| 401 |
+
"389": "barracouta, snoek",
|
| 402 |
+
"390": "eel",
|
| 403 |
+
"391": "coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch",
|
| 404 |
+
"392": "rock beauty, Holocanthus tricolor",
|
| 405 |
+
"393": "anemone fish",
|
| 406 |
+
"394": "sturgeon",
|
| 407 |
+
"395": "gar, garfish, garpike, billfish, Lepisosteus osseus",
|
| 408 |
+
"396": "lionfish",
|
| 409 |
+
"397": "puffer, pufferfish, blowfish, globefish",
|
| 410 |
+
"398": "abacus",
|
| 411 |
+
"399": "abaya",
|
| 412 |
+
"400": "academic gown, academic robe, judge robe",
|
| 413 |
+
"401": "accordion, piano accordion, squeeze box",
|
| 414 |
+
"402": "acoustic guitar",
|
| 415 |
+
"403": "aircraft carrier, carrier, flattop, attack aircraft carrier",
|
| 416 |
+
"404": "airliner",
|
| 417 |
+
"405": "airship, dirigible",
|
| 418 |
+
"406": "altar",
|
| 419 |
+
"407": "ambulance",
|
| 420 |
+
"408": "amphibian, amphibious vehicle",
|
| 421 |
+
"409": "analog clock",
|
| 422 |
+
"410": "apiary, bee house",
|
| 423 |
+
"411": "apron",
|
| 424 |
+
"412": "ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin",
|
| 425 |
+
"413": "assault rifle, assault gun",
|
| 426 |
+
"414": "backpack, back pack, knapsack, packsack, rucksack, haversack",
|
| 427 |
+
"415": "bakery, bakeshop, bakehouse",
|
| 428 |
+
"416": "balance beam, beam",
|
| 429 |
+
"417": "balloon",
|
| 430 |
+
"418": "ballpoint, ballpoint pen, ballpen, Biro",
|
| 431 |
+
"419": "Band Aid",
|
| 432 |
+
"420": "banjo",
|
| 433 |
+
"421": "bannister, banister, balustrade, balusters, handrail",
|
| 434 |
+
"422": "barbell",
|
| 435 |
+
"423": "barber chair",
|
| 436 |
+
"424": "barbershop",
|
| 437 |
+
"425": "barn",
|
| 438 |
+
"426": "barometer",
|
| 439 |
+
"427": "barrel, cask",
|
| 440 |
+
"428": "barrow, garden cart, lawn cart, wheelbarrow",
|
| 441 |
+
"429": "baseball",
|
| 442 |
+
"430": "basketball",
|
| 443 |
+
"431": "bassinet",
|
| 444 |
+
"432": "bassoon",
|
| 445 |
+
"433": "bathing cap, swimming cap",
|
| 446 |
+
"434": "bath towel",
|
| 447 |
+
"435": "bathtub, bathing tub, bath, tub",
|
| 448 |
+
"436": "beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon",
|
| 449 |
+
"437": "beacon, lighthouse, beacon light, pharos",
|
| 450 |
+
"438": "beaker",
|
| 451 |
+
"439": "bearskin, busby, shako",
|
| 452 |
+
"440": "beer bottle",
|
| 453 |
+
"441": "beer glass",
|
| 454 |
+
"442": "bell cote, bell cot",
|
| 455 |
+
"443": "bib",
|
| 456 |
+
"444": "bicycle-built-for-two, tandem bicycle, tandem",
|
| 457 |
+
"445": "bikini, two-piece",
|
| 458 |
+
"446": "binder, ring-binder",
|
| 459 |
+
"447": "binoculars, field glasses, opera glasses",
|
| 460 |
+
"448": "birdhouse",
|
| 461 |
+
"449": "boathouse",
|
| 462 |
+
"450": "bobsled, bobsleigh, bob",
|
| 463 |
+
"451": "bolo tie, bolo, bola tie, bola",
|
| 464 |
+
"452": "bonnet, poke bonnet",
|
| 465 |
+
"453": "bookcase",
|
| 466 |
+
"454": "bookshop, bookstore, bookstall",
|
| 467 |
+
"455": "bottlecap",
|
| 468 |
+
"456": "bow",
|
| 469 |
+
"457": "bow tie, bow-tie, bowtie",
|
| 470 |
+
"458": "brass, memorial tablet, plaque",
|
| 471 |
+
"459": "brassiere, bra, bandeau",
|
| 472 |
+
"460": "breakwater, groin, groyne, mole, bulwark, seawall, jetty",
|
| 473 |
+
"461": "breastplate, aegis, egis",
|
| 474 |
+
"462": "broom",
|
| 475 |
+
"463": "bucket, pail",
|
| 476 |
+
"464": "buckle",
|
| 477 |
+
"465": "bulletproof vest",
|
| 478 |
+
"466": "bullet train, bullet",
|
| 479 |
+
"467": "butcher shop, meat market",
|
| 480 |
+
"468": "cab, hack, taxi, taxicab",
|
| 481 |
+
"469": "caldron, cauldron",
|
| 482 |
+
"470": "candle, taper, wax light",
|
| 483 |
+
"471": "cannon",
|
| 484 |
+
"472": "canoe",
|
| 485 |
+
"473": "can opener, tin opener",
|
| 486 |
+
"474": "cardigan",
|
| 487 |
+
"475": "car mirror",
|
| 488 |
+
"476": "carousel, carrousel, merry-go-round, roundabout, whirligig",
|
| 489 |
+
"477": "carpenters kit, tool kit",
|
| 490 |
+
"478": "carton",
|
| 491 |
+
"479": "car wheel",
|
| 492 |
+
"480": "cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM",
|
| 493 |
+
"481": "cassette",
|
| 494 |
+
"482": "cassette player",
|
| 495 |
+
"483": "castle",
|
| 496 |
+
"484": "catamaran",
|
| 497 |
+
"485": "CD player",
|
| 498 |
+
"486": "cello, violoncello",
|
| 499 |
+
"487": "cellular telephone, cellular phone, cellphone, cell, mobile phone",
|
| 500 |
+
"488": "chain",
|
| 501 |
+
"489": "chainlink fence",
|
| 502 |
+
"490": "chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour",
|
| 503 |
+
"491": "chain saw, chainsaw",
|
| 504 |
+
"492": "chest",
|
| 505 |
+
"493": "chiffonier, commode",
|
| 506 |
+
"494": "chime, bell, gong",
|
| 507 |
+
"495": "china cabinet, china closet",
|
| 508 |
+
"496": "Christmas stocking",
|
| 509 |
+
"497": "church, church building",
|
| 510 |
+
"498": "cinema, movie theater, movie theatre, movie house, picture palace",
|
| 511 |
+
"499": "cleaver, meat cleaver, chopper",
|
| 512 |
+
"500": "cliff dwelling",
|
| 513 |
+
"501": "cloak",
|
| 514 |
+
"502": "clog, geta, patten, sabot",
|
| 515 |
+
"503": "cocktail shaker",
|
| 516 |
+
"504": "coffee mug",
|
| 517 |
+
"505": "coffeepot",
|
| 518 |
+
"506": "coil, spiral, volute, whorl, helix",
|
| 519 |
+
"507": "combination lock",
|
| 520 |
+
"508": "computer keyboard, keypad",
|
| 521 |
+
"509": "confectionery, confectionary, candy store",
|
| 522 |
+
"510": "container ship, containership, container vessel",
|
| 523 |
+
"511": "convertible",
|
| 524 |
+
"512": "corkscrew, bottle screw",
|
| 525 |
+
"513": "cornet, horn, trumpet, trump",
|
| 526 |
+
"514": "cowboy boot",
|
| 527 |
+
"515": "cowboy hat, ten-gallon hat",
|
| 528 |
+
"516": "cradle",
|
| 529 |
+
"517": "crane",
|
| 530 |
+
"518": "crash helmet",
|
| 531 |
+
"519": "crate",
|
| 532 |
+
"520": "crib, cot",
|
| 533 |
+
"521": "Crock Pot",
|
| 534 |
+
"522": "croquet ball",
|
| 535 |
+
"523": "crutch",
|
| 536 |
+
"524": "cuirass",
|
| 537 |
+
"525": "dam, dike, dyke",
|
| 538 |
+
"526": "desk",
|
| 539 |
+
"527": "desktop computer",
|
| 540 |
+
"528": "dial telephone, dial phone",
|
| 541 |
+
"529": "diaper, nappy, napkin",
|
| 542 |
+
"530": "digital clock",
|
| 543 |
+
"531": "digital watch",
|
| 544 |
+
"532": "dining table, board",
|
| 545 |
+
"533": "dishrag, dishcloth",
|
| 546 |
+
"534": "dishwasher, dish washer, dishwashing machine",
|
| 547 |
+
"535": "disk brake, disc brake",
|
| 548 |
+
"536": "dock, dockage, docking facility",
|
| 549 |
+
"537": "dogsled, dog sled, dog sleigh",
|
| 550 |
+
"538": "dome",
|
| 551 |
+
"539": "doormat, welcome mat",
|
| 552 |
+
"540": "drilling platform, offshore rig",
|
| 553 |
+
"541": "drum, membranophone, tympan",
|
| 554 |
+
"542": "drumstick",
|
| 555 |
+
"543": "dumbbell",
|
| 556 |
+
"544": "Dutch oven",
|
| 557 |
+
"545": "electric fan, blower",
|
| 558 |
+
"546": "electric guitar",
|
| 559 |
+
"547": "electric locomotive",
|
| 560 |
+
"548": "entertainment center",
|
| 561 |
+
"549": "envelope",
|
| 562 |
+
"550": "espresso maker",
|
| 563 |
+
"551": "face powder",
|
| 564 |
+
"552": "feather boa, boa",
|
| 565 |
+
"553": "file, file cabinet, filing cabinet",
|
| 566 |
+
"554": "fireboat",
|
| 567 |
+
"555": "fire engine, fire truck",
|
| 568 |
+
"556": "fire screen, fireguard",
|
| 569 |
+
"557": "flagpole, flagstaff",
|
| 570 |
+
"558": "flute, transverse flute",
|
| 571 |
+
"559": "folding chair",
|
| 572 |
+
"560": "football helmet",
|
| 573 |
+
"561": "forklift",
|
| 574 |
+
"562": "fountain",
|
| 575 |
+
"563": "fountain pen",
|
| 576 |
+
"564": "four-poster",
|
| 577 |
+
"565": "freight car",
|
| 578 |
+
"566": "French horn, horn",
|
| 579 |
+
"567": "frying pan, frypan, skillet",
|
| 580 |
+
"568": "fur coat",
|
| 581 |
+
"569": "garbage truck, dustcart",
|
| 582 |
+
"570": "gasmask, respirator, gas helmet",
|
| 583 |
+
"571": "gas pump, gasoline pump, petrol pump, island dispenser",
|
| 584 |
+
"572": "goblet",
|
| 585 |
+
"573": "go-kart",
|
| 586 |
+
"574": "golf ball",
|
| 587 |
+
"575": "golfcart, golf cart",
|
| 588 |
+
"576": "gondola",
|
| 589 |
+
"577": "gong, tam-tam",
|
| 590 |
+
"578": "gown",
|
| 591 |
+
"579": "grand piano, grand",
|
| 592 |
+
"580": "greenhouse, nursery, glasshouse",
|
| 593 |
+
"581": "grille, radiator grille",
|
| 594 |
+
"582": "grocery store, grocery, food market, market",
|
| 595 |
+
"583": "guillotine",
|
| 596 |
+
"584": "hair slide",
|
| 597 |
+
"585": "hair spray",
|
| 598 |
+
"586": "half track",
|
| 599 |
+
"587": "hammer",
|
| 600 |
+
"588": "hamper",
|
| 601 |
+
"589": "hand blower, blow dryer, blow drier, hair dryer, hair drier",
|
| 602 |
+
"590": "hand-held computer, hand-held microcomputer",
|
| 603 |
+
"591": "handkerchief, hankie, hanky, hankey",
|
| 604 |
+
"592": "hard disc, hard disk, fixed disk",
|
| 605 |
+
"593": "harmonica, mouth organ, harp, mouth harp",
|
| 606 |
+
"594": "harp",
|
| 607 |
+
"595": "harvester, reaper",
|
| 608 |
+
"596": "hatchet",
|
| 609 |
+
"597": "holster",
|
| 610 |
+
"598": "home theater, home theatre",
|
| 611 |
+
"599": "honeycomb",
|
| 612 |
+
"600": "hook, claw",
|
| 613 |
+
"601": "hoopskirt, crinoline",
|
| 614 |
+
"602": "horizontal bar, high bar",
|
| 615 |
+
"603": "horse cart, horse-cart",
|
| 616 |
+
"604": "hourglass",
|
| 617 |
+
"605": "iPod",
|
| 618 |
+
"606": "iron, smoothing iron",
|
| 619 |
+
"607": "jack-o-lantern",
|
| 620 |
+
"608": "jean, blue jean, denim",
|
| 621 |
+
"609": "jeep, landrover",
|
| 622 |
+
"610": "jersey, T-shirt, tee shirt",
|
| 623 |
+
"611": "jigsaw puzzle",
|
| 624 |
+
"612": "jinrikisha, ricksha, rickshaw",
|
| 625 |
+
"613": "joystick",
|
| 626 |
+
"614": "kimono",
|
| 627 |
+
"615": "knee pad",
|
| 628 |
+
"616": "knot",
|
| 629 |
+
"617": "lab coat, laboratory coat",
|
| 630 |
+
"618": "ladle",
|
| 631 |
+
"619": "lampshade, lamp shade",
|
| 632 |
+
"620": "laptop, laptop computer",
|
| 633 |
+
"621": "lawn mower, mower",
|
| 634 |
+
"622": "lens cap, lens cover",
|
| 635 |
+
"623": "letter opener, paper knife, paperknife",
|
| 636 |
+
"624": "library",
|
| 637 |
+
"625": "lifeboat",
|
| 638 |
+
"626": "lighter, light, igniter, ignitor",
|
| 639 |
+
"627": "limousine, limo",
|
| 640 |
+
"628": "liner, ocean liner",
|
| 641 |
+
"629": "lipstick, lip rouge",
|
| 642 |
+
"630": "Loafer",
|
| 643 |
+
"631": "lotion",
|
| 644 |
+
"632": "loudspeaker, speaker, speaker unit, loudspeaker system, speaker system",
|
| 645 |
+
"633": "loupe, jewelers loupe",
|
| 646 |
+
"634": "lumbermill, sawmill",
|
| 647 |
+
"635": "magnetic compass",
|
| 648 |
+
"636": "mailbag, postbag",
|
| 649 |
+
"637": "mailbox, letter box",
|
| 650 |
+
"638": "maillot",
|
| 651 |
+
"639": "maillot, tank suit",
|
| 652 |
+
"640": "manhole cover",
|
| 653 |
+
"641": "maraca",
|
| 654 |
+
"642": "marimba, xylophone",
|
| 655 |
+
"643": "mask",
|
| 656 |
+
"644": "matchstick",
|
| 657 |
+
"645": "maypole",
|
| 658 |
+
"646": "maze, labyrinth",
|
| 659 |
+
"647": "measuring cup",
|
| 660 |
+
"648": "medicine chest, medicine cabinet",
|
| 661 |
+
"649": "megalith, megalithic structure",
|
| 662 |
+
"650": "microphone, mike",
|
| 663 |
+
"651": "microwave, microwave oven",
|
| 664 |
+
"652": "military uniform",
|
| 665 |
+
"653": "milk can",
|
| 666 |
+
"654": "minibus",
|
| 667 |
+
"655": "miniskirt, mini",
|
| 668 |
+
"656": "minivan",
|
| 669 |
+
"657": "missile",
|
| 670 |
+
"658": "mitten",
|
| 671 |
+
"659": "mixing bowl",
|
| 672 |
+
"660": "mobile home, manufactured home",
|
| 673 |
+
"661": "Model T",
|
| 674 |
+
"662": "modem",
|
| 675 |
+
"663": "monastery",
|
| 676 |
+
"664": "monitor",
|
| 677 |
+
"665": "moped",
|
| 678 |
+
"666": "mortar",
|
| 679 |
+
"667": "mortarboard",
|
| 680 |
+
"668": "mosque",
|
| 681 |
+
"669": "mosquito net",
|
| 682 |
+
"670": "motor scooter, scooter",
|
| 683 |
+
"671": "mountain bike, all-terrain bike, off-roader",
|
| 684 |
+
"672": "mountain tent",
|
| 685 |
+
"673": "mouse, computer mouse",
|
| 686 |
+
"674": "mousetrap",
|
| 687 |
+
"675": "moving van",
|
| 688 |
+
"676": "muzzle",
|
| 689 |
+
"677": "nail",
|
| 690 |
+
"678": "neck brace",
|
| 691 |
+
"679": "necklace",
|
| 692 |
+
"680": "nipple",
|
| 693 |
+
"681": "notebook, notebook computer",
|
| 694 |
+
"682": "obelisk",
|
| 695 |
+
"683": "oboe, hautboy, hautbois",
|
| 696 |
+
"684": "ocarina, sweet potato",
|
| 697 |
+
"685": "odometer, hodometer, mileometer, milometer",
|
| 698 |
+
"686": "oil filter",
|
| 699 |
+
"687": "organ, pipe organ",
|
| 700 |
+
"688": "oscilloscope, scope, cathode-ray oscilloscope, CRO",
|
| 701 |
+
"689": "overskirt",
|
| 702 |
+
"690": "oxcart",
|
| 703 |
+
"691": "oxygen mask",
|
| 704 |
+
"692": "packet",
|
| 705 |
+
"693": "paddle, boat paddle",
|
| 706 |
+
"694": "paddlewheel, paddle wheel",
|
| 707 |
+
"695": "padlock",
|
| 708 |
+
"696": "paintbrush",
|
| 709 |
+
"697": "pajama, pyjama, pjs, jammies",
|
| 710 |
+
"698": "palace",
|
| 711 |
+
"699": "panpipe, pandean pipe, syrinx",
|
| 712 |
+
"700": "paper towel",
|
| 713 |
+
"701": "parachute, chute",
|
| 714 |
+
"702": "parallel bars, bars",
|
| 715 |
+
"703": "park bench",
|
| 716 |
+
"704": "parking meter",
|
| 717 |
+
"705": "passenger car, coach, carriage",
|
| 718 |
+
"706": "patio, terrace",
|
| 719 |
+
"707": "pay-phone, pay-station",
|
| 720 |
+
"708": "pedestal, plinth, footstall",
|
| 721 |
+
"709": "pencil box, pencil case",
|
| 722 |
+
"710": "pencil sharpener",
|
| 723 |
+
"711": "perfume, essence",
|
| 724 |
+
"712": "Petri dish",
|
| 725 |
+
"713": "photocopier",
|
| 726 |
+
"714": "pick, plectrum, plectron",
|
| 727 |
+
"715": "pickelhaube",
|
| 728 |
+
"716": "picket fence, paling",
|
| 729 |
+
"717": "pickup, pickup truck",
|
| 730 |
+
"718": "pier",
|
| 731 |
+
"719": "piggy bank, penny bank",
|
| 732 |
+
"720": "pill bottle",
|
| 733 |
+
"721": "pillow",
|
| 734 |
+
"722": "ping-pong ball",
|
| 735 |
+
"723": "pinwheel",
|
| 736 |
+
"724": "pirate, pirate ship",
|
| 737 |
+
"725": "pitcher, ewer",
|
| 738 |
+
"726": "plane, carpenters plane, woodworking plane",
|
| 739 |
+
"727": "planetarium",
|
| 740 |
+
"728": "plastic bag",
|
| 741 |
+
"729": "plate rack",
|
| 742 |
+
"730": "plow, plough",
|
| 743 |
+
"731": "plunger, plumbers helper",
|
| 744 |
+
"732": "Polaroid camera, Polaroid Land camera",
|
| 745 |
+
"733": "pole",
|
| 746 |
+
"734": "police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria",
|
| 747 |
+
"735": "poncho",
|
| 748 |
+
"736": "pool table, billiard table, snooker table",
|
| 749 |
+
"737": "pop bottle, soda bottle",
|
| 750 |
+
"738": "pot, flowerpot",
|
| 751 |
+
"739": "potters wheel",
|
| 752 |
+
"740": "power drill",
|
| 753 |
+
"741": "prayer rug, prayer mat",
|
| 754 |
+
"742": "printer",
|
| 755 |
+
"743": "prison, prison house",
|
| 756 |
+
"744": "projectile, missile",
|
| 757 |
+
"745": "projector",
|
| 758 |
+
"746": "puck, hockey puck",
|
| 759 |
+
"747": "punching bag, punch bag, punching ball, punchball",
|
| 760 |
+
"748": "purse",
|
| 761 |
+
"749": "quill, quill pen",
|
| 762 |
+
"750": "quilt, comforter, comfort, puff",
|
| 763 |
+
"751": "racer, race car, racing car",
|
| 764 |
+
"752": "racket, racquet",
|
| 765 |
+
"753": "radiator",
|
| 766 |
+
"754": "radio, wireless",
|
| 767 |
+
"755": "radio telescope, radio reflector",
|
| 768 |
+
"756": "rain barrel",
|
| 769 |
+
"757": "recreational vehicle, RV, R.V.",
|
| 770 |
+
"758": "reel",
|
| 771 |
+
"759": "reflex camera",
|
| 772 |
+
"760": "refrigerator, icebox",
|
| 773 |
+
"761": "remote control, remote",
|
| 774 |
+
"762": "restaurant, eating house, eating place, eatery",
|
| 775 |
+
"763": "revolver, six-gun, six-shooter",
|
| 776 |
+
"764": "rifle",
|
| 777 |
+
"765": "rocking chair, rocker",
|
| 778 |
+
"766": "rotisserie",
|
| 779 |
+
"767": "rubber eraser, rubber, pencil eraser",
|
| 780 |
+
"768": "rugby ball",
|
| 781 |
+
"769": "rule, ruler",
|
| 782 |
+
"770": "running shoe",
|
| 783 |
+
"771": "safe",
|
| 784 |
+
"772": "safety pin",
|
| 785 |
+
"773": "saltshaker, salt shaker",
|
| 786 |
+
"774": "sandal",
|
| 787 |
+
"775": "sarong",
|
| 788 |
+
"776": "sax, saxophone",
|
| 789 |
+
"777": "scabbard",
|
| 790 |
+
"778": "scale, weighing machine",
|
| 791 |
+
"779": "school bus",
|
| 792 |
+
"780": "schooner",
|
| 793 |
+
"781": "scoreboard",
|
| 794 |
+
"782": "screen, CRT screen",
|
| 795 |
+
"783": "screw",
|
| 796 |
+
"784": "screwdriver",
|
| 797 |
+
"785": "seat belt, seatbelt",
|
| 798 |
+
"786": "sewing machine",
|
| 799 |
+
"787": "shield, buckler",
|
| 800 |
+
"788": "shoe shop, shoe-shop, shoe store",
|
| 801 |
+
"789": "shoji",
|
| 802 |
+
"790": "shopping basket",
|
| 803 |
+
"791": "shopping cart",
|
| 804 |
+
"792": "shovel",
|
| 805 |
+
"793": "shower cap",
|
| 806 |
+
"794": "shower curtain",
|
| 807 |
+
"795": "ski",
|
| 808 |
+
"796": "ski mask",
|
| 809 |
+
"797": "sleeping bag",
|
| 810 |
+
"798": "slide rule, slipstick",
|
| 811 |
+
"799": "sliding door",
|
| 812 |
+
"800": "slot, one-armed bandit",
|
| 813 |
+
"801": "snorkel",
|
| 814 |
+
"802": "snowmobile",
|
| 815 |
+
"803": "snowplow, snowplough",
|
| 816 |
+
"804": "soap dispenser",
|
| 817 |
+
"805": "soccer ball",
|
| 818 |
+
"806": "sock",
|
| 819 |
+
"807": "solar dish, solar collector, solar furnace",
|
| 820 |
+
"808": "sombrero",
|
| 821 |
+
"809": "soup bowl",
|
| 822 |
+
"810": "space bar",
|
| 823 |
+
"811": "space heater",
|
| 824 |
+
"812": "space shuttle",
|
| 825 |
+
"813": "spatula",
|
| 826 |
+
"814": "speedboat",
|
| 827 |
+
"815": "spider web, spiders web",
|
| 828 |
+
"816": "spindle",
|
| 829 |
+
"817": "sports car, sport car",
|
| 830 |
+
"818": "spotlight, spot",
|
| 831 |
+
"819": "stage",
|
| 832 |
+
"820": "steam locomotive",
|
| 833 |
+
"821": "steel arch bridge",
|
| 834 |
+
"822": "steel drum",
|
| 835 |
+
"823": "stethoscope",
|
| 836 |
+
"824": "stole",
|
| 837 |
+
"825": "stone wall",
|
| 838 |
+
"826": "stopwatch, stop watch",
|
| 839 |
+
"827": "stove",
|
| 840 |
+
"828": "strainer",
|
| 841 |
+
"829": "streetcar, tram, tramcar, trolley, trolley car",
|
| 842 |
+
"830": "stretcher",
|
| 843 |
+
"831": "studio couch, day bed",
|
| 844 |
+
"832": "stupa, tope",
|
| 845 |
+
"833": "submarine, pigboat, sub, U-boat",
|
| 846 |
+
"834": "suit, suit of clothes",
|
| 847 |
+
"835": "sundial",
|
| 848 |
+
"836": "sunglass",
|
| 849 |
+
"837": "sunglasses, dark glasses, shades",
|
| 850 |
+
"838": "sunscreen, sunblock, sun blocker",
|
| 851 |
+
"839": "suspension bridge",
|
| 852 |
+
"840": "swab, swob, mop",
|
| 853 |
+
"841": "sweatshirt",
|
| 854 |
+
"842": "swimming trunks, bathing trunks",
|
| 855 |
+
"843": "swing",
|
| 856 |
+
"844": "switch, electric switch, electrical switch",
|
| 857 |
+
"845": "syringe",
|
| 858 |
+
"846": "table lamp",
|
| 859 |
+
"847": "tank, army tank, armored combat vehicle, armoured combat vehicle",
|
| 860 |
+
"848": "tape player",
|
| 861 |
+
"849": "teapot",
|
| 862 |
+
"850": "teddy, teddy bear",
|
| 863 |
+
"851": "television, television system",
|
| 864 |
+
"852": "tennis ball",
|
| 865 |
+
"853": "thatch, thatched roof",
|
| 866 |
+
"854": "theater curtain, theatre curtain",
|
| 867 |
+
"855": "thimble",
|
| 868 |
+
"856": "thresher, thrasher, threshing machine",
|
| 869 |
+
"857": "throne",
|
| 870 |
+
"858": "tile roof",
|
| 871 |
+
"859": "toaster",
|
| 872 |
+
"860": "tobacco shop, tobacconist shop, tobacconist",
|
| 873 |
+
"861": "toilet seat",
|
| 874 |
+
"862": "torch",
|
| 875 |
+
"863": "totem pole",
|
| 876 |
+
"864": "tow truck, tow car, wrecker",
|
| 877 |
+
"865": "toyshop",
|
| 878 |
+
"866": "tractor",
|
| 879 |
+
"867": "trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi",
|
| 880 |
+
"868": "tray",
|
| 881 |
+
"869": "trench coat",
|
| 882 |
+
"870": "tricycle, trike, velocipede",
|
| 883 |
+
"871": "trimaran",
|
| 884 |
+
"872": "tripod",
|
| 885 |
+
"873": "triumphal arch",
|
| 886 |
+
"874": "trolleybus, trolley coach, trackless trolley",
|
| 887 |
+
"875": "trombone",
|
| 888 |
+
"876": "tub, vat",
|
| 889 |
+
"877": "turnstile",
|
| 890 |
+
"878": "typewriter keyboard",
|
| 891 |
+
"879": "umbrella",
|
| 892 |
+
"880": "unicycle, monocycle",
|
| 893 |
+
"881": "upright, upright piano",
|
| 894 |
+
"882": "vacuum, vacuum cleaner",
|
| 895 |
+
"883": "vase",
|
| 896 |
+
"884": "vault",
|
| 897 |
+
"885": "velvet",
|
| 898 |
+
"886": "vending machine",
|
| 899 |
+
"887": "vestment",
|
| 900 |
+
"888": "viaduct",
|
| 901 |
+
"889": "violin, fiddle",
|
| 902 |
+
"890": "volleyball",
|
| 903 |
+
"891": "waffle iron",
|
| 904 |
+
"892": "wall clock",
|
| 905 |
+
"893": "wallet, billfold, notecase, pocketbook",
|
| 906 |
+
"894": "wardrobe, closet, press",
|
| 907 |
+
"895": "warplane, military plane",
|
| 908 |
+
"896": "washbasin, handbasin, washbowl, lavabo, wash-hand basin",
|
| 909 |
+
"897": "washer, automatic washer, washing machine",
|
| 910 |
+
"898": "water bottle",
|
| 911 |
+
"899": "water jug",
|
| 912 |
+
"900": "water tower",
|
| 913 |
+
"901": "whiskey jug",
|
| 914 |
+
"902": "whistle",
|
| 915 |
+
"903": "wig",
|
| 916 |
+
"904": "window screen",
|
| 917 |
+
"905": "window shade",
|
| 918 |
+
"906": "Windsor tie",
|
| 919 |
+
"907": "wine bottle",
|
| 920 |
+
"908": "wing",
|
| 921 |
+
"909": "wok",
|
| 922 |
+
"910": "wooden spoon",
|
| 923 |
+
"911": "wool, woolen, woollen",
|
| 924 |
+
"912": "worm fence, snake fence, snake-rail fence, Virginia fence",
|
| 925 |
+
"913": "wreck",
|
| 926 |
+
"914": "yawl",
|
| 927 |
+
"915": "yurt",
|
| 928 |
+
"916": "web site, website, internet site, site",
|
| 929 |
+
"917": "comic book",
|
| 930 |
+
"918": "crossword puzzle, crossword",
|
| 931 |
+
"919": "street sign",
|
| 932 |
+
"920": "traffic light, traffic signal, stoplight",
|
| 933 |
+
"921": "book jacket, dust cover, dust jacket, dust wrapper",
|
| 934 |
+
"922": "menu",
|
| 935 |
+
"923": "plate",
|
| 936 |
+
"924": "guacamole",
|
| 937 |
+
"925": "consomme",
|
| 938 |
+
"926": "hot pot, hotpot",
|
| 939 |
+
"927": "trifle",
|
| 940 |
+
"928": "ice cream, icecream",
|
| 941 |
+
"929": "ice lolly, lolly, lollipop, popsicle",
|
| 942 |
+
"930": "French loaf",
|
| 943 |
+
"931": "bagel, beigel",
|
| 944 |
+
"932": "pretzel",
|
| 945 |
+
"933": "cheeseburger",
|
| 946 |
+
"934": "hotdog, hot dog, red hot",
|
| 947 |
+
"935": "mashed potato",
|
| 948 |
+
"936": "head cabbage",
|
| 949 |
+
"937": "broccoli",
|
| 950 |
+
"938": "cauliflower",
|
| 951 |
+
"939": "zucchini, courgette",
|
| 952 |
+
"940": "spaghetti squash",
|
| 953 |
+
"941": "acorn squash",
|
| 954 |
+
"942": "butternut squash",
|
| 955 |
+
"943": "cucumber, cuke",
|
| 956 |
+
"944": "artichoke, globe artichoke",
|
| 957 |
+
"945": "bell pepper",
|
| 958 |
+
"946": "cardoon",
|
| 959 |
+
"947": "mushroom",
|
| 960 |
+
"948": "Granny Smith",
|
| 961 |
+
"949": "strawberry",
|
| 962 |
+
"950": "orange",
|
| 963 |
+
"951": "lemon",
|
| 964 |
+
"952": "fig",
|
| 965 |
+
"953": "pineapple, ananas",
|
| 966 |
+
"954": "banana",
|
| 967 |
+
"955": "jackfruit, jak, jack",
|
| 968 |
+
"956": "custard apple",
|
| 969 |
+
"957": "pomegranate",
|
| 970 |
+
"958": "hay",
|
| 971 |
+
"959": "carbonara",
|
| 972 |
+
"960": "chocolate sauce, chocolate syrup",
|
| 973 |
+
"961": "dough",
|
| 974 |
+
"962": "meat loaf, meatloaf",
|
| 975 |
+
"963": "pizza, pizza pie",
|
| 976 |
+
"964": "potpie",
|
| 977 |
+
"965": "burrito",
|
| 978 |
+
"966": "red wine",
|
| 979 |
+
"967": "espresso",
|
| 980 |
+
"968": "cup",
|
| 981 |
+
"969": "eggnog",
|
| 982 |
+
"970": "alp",
|
| 983 |
+
"971": "bubble",
|
| 984 |
+
"972": "cliff, drop, drop-off",
|
| 985 |
+
"973": "coral reef",
|
| 986 |
+
"974": "geyser",
|
| 987 |
+
"975": "lakeside, lakeshore",
|
| 988 |
+
"976": "promontory, headland, head, foreland",
|
| 989 |
+
"977": "sandbar, sand bar",
|
| 990 |
+
"978": "seashore, coast, seacoast, sea-coast",
|
| 991 |
+
"979": "valley, vale",
|
| 992 |
+
"980": "volcano",
|
| 993 |
+
"981": "ballplayer, baseball player",
|
| 994 |
+
"982": "groom, bridegroom",
|
| 995 |
+
"983": "scuba diver",
|
| 996 |
+
"984": "rapeseed",
|
| 997 |
+
"985": "daisy",
|
| 998 |
+
"986": "yellow ladys slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum",
|
| 999 |
+
"987": "corn",
|
| 1000 |
+
"988": "acorn",
|
| 1001 |
+
"989": "hip, rose hip, rosehip",
|
| 1002 |
+
"990": "buckeye, horse chestnut, conker",
|
| 1003 |
+
"991": "coral fungus",
|
| 1004 |
+
"992": "agaric",
|
| 1005 |
+
"993": "gyromitra",
|
| 1006 |
+
"994": "stinkhorn, carrion fungus",
|
| 1007 |
+
"995": "earthstar",
|
| 1008 |
+
"996": "hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa",
|
| 1009 |
+
"997": "bolete",
|
| 1010 |
+
"998": "ear, spike, capitulum",
|
| 1011 |
+
"999": "toilet tissue, toilet paper, bathroom tissue"
|
| 1012 |
+
},
|
| 1013 |
+
"scheduler": [
|
| 1014 |
+
"scheduling_flow_match_pae",
|
| 1015 |
+
"PAEFlowMatchScheduler"
|
| 1016 |
+
],
|
| 1017 |
+
"transformers": [
|
| 1018 |
+
"transformer_lightning_dit",
|
| 1019 |
+
"LightningDiT2DModel"
|
| 1020 |
+
]
|
| 1021 |
+
}
|
pae-siglip2-so400m-d32/pipeline.py
ADDED
|
@@ -0,0 +1,530 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hub custom pipeline: PAEPipeline.
|
| 2 |
+
Load with native Hugging Face diffusers and trust_remote_code=True.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
# Copyright 2026 The HuggingFace Team and PAE authors. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import inspect
|
| 24 |
+
import json
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 27 |
+
|
| 28 |
+
import torch
|
| 29 |
+
|
| 30 |
+
from diffusers.image_processor import VaeImageProcessor
|
| 31 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
|
| 32 |
+
from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers
|
| 33 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 34 |
+
|
| 35 |
+
EXAMPLE_DOC_STRING = """
|
| 36 |
+
Examples:
|
| 37 |
+
```py
|
| 38 |
+
>>> from pathlib import Path
|
| 39 |
+
>>> from diffusers import DiffusionPipeline
|
| 40 |
+
>>> import torch
|
| 41 |
+
|
| 42 |
+
>>> model_dir = Path("./pae-dinov2-large-d32").resolve()
|
| 43 |
+
>>> pipe = DiffusionPipeline.from_pretrained(
|
| 44 |
+
... str(model_dir),
|
| 45 |
+
... local_files_only=True,
|
| 46 |
+
... custom_pipeline=str(model_dir / "pipeline.py"),
|
| 47 |
+
... trust_remote_code=True,
|
| 48 |
+
... torch_dtype=torch.bfloat16,
|
| 49 |
+
... )
|
| 50 |
+
>>> pipe.to("cuda")
|
| 51 |
+
|
| 52 |
+
>>> print(pipe.id2label[207])
|
| 53 |
+
>>> print(pipe.get_label_ids("golden retriever"))
|
| 54 |
+
|
| 55 |
+
>>> generator = torch.Generator(device="cuda").manual_seed(42)
|
| 56 |
+
>>> image = pipe(
|
| 57 |
+
... class_labels="golden retriever",
|
| 58 |
+
... generator=generator,
|
| 59 |
+
... ).images[0]
|
| 60 |
+
```
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class PAEPipeline(DiffusionPipeline):
|
| 65 |
+
r"""
|
| 66 |
+
Pipeline for class-conditional image generation with PAE tokenizers and LightningDiT.
|
| 67 |
+
|
| 68 |
+
This model inherits from [`DiffusionPipeline`]. Components are stored in separate subfolders
|
| 69 |
+
(`transformers/`, `scheduler/`, `decoder/`) and loaded via `DiffusionPipeline.from_pretrained`.
|
| 70 |
+
|
| 71 |
+
Parameters:
|
| 72 |
+
transformers ([`LightningDiT2DModel`]):
|
| 73 |
+
Class-conditional LightningDiT transformer that predicts flow-matching velocity in PAE latent space.
|
| 74 |
+
scheduler ([`PAEFlowMatchScheduler`]):
|
| 75 |
+
Flow-matching ODE/SDE scheduler. Other [`KarrasDiffusionSchedulers`] can be swapped at inference time
|
| 76 |
+
when their `step` API is compatible.
|
| 77 |
+
decoder ([`PAEDecoder`]):
|
| 78 |
+
Prior-Aligned Autoencoder decoder stack (decompressor + pixel decoder).
|
| 79 |
+
|
| 80 |
+
ImageNet `id2label` mappings are read lazily from `model_index.json` when label helpers are used.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
model_cpu_offload_seq = "transformers->decoder"
|
| 84 |
+
_optional_components = ["decoder"]
|
| 85 |
+
|
| 86 |
+
@staticmethod
|
| 87 |
+
def prepare_extra_step_kwargs(
|
| 88 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 89 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 90 |
+
eta: Optional[float] = None,
|
| 91 |
+
) -> Dict[str, object]:
|
| 92 |
+
r"""
|
| 93 |
+
Build kwargs forwarded to `scheduler.step` when supported.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
scheduler:
|
| 97 |
+
Active diffusion scheduler instance.
|
| 98 |
+
generator:
|
| 99 |
+
Optional RNG passed through to stochastic scheduler steps.
|
| 100 |
+
eta:
|
| 101 |
+
Optional DDIM-style eta when the scheduler accepts it.
|
| 102 |
+
"""
|
| 103 |
+
kwargs: Dict[str, object] = {}
|
| 104 |
+
step_params = set(inspect.signature(scheduler.step).parameters.keys())
|
| 105 |
+
if "generator" in step_params:
|
| 106 |
+
kwargs["generator"] = generator
|
| 107 |
+
if eta is not None and "eta" in step_params:
|
| 108 |
+
kwargs["eta"] = eta
|
| 109 |
+
return kwargs
|
| 110 |
+
|
| 111 |
+
def __init__(
|
| 112 |
+
self,
|
| 113 |
+
transformers,
|
| 114 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 115 |
+
decoder=None,
|
| 116 |
+
transformer=None,
|
| 117 |
+
) -> None:
|
| 118 |
+
if transformer is not None and transformers is None:
|
| 119 |
+
transformers = transformer
|
| 120 |
+
super().__init__()
|
| 121 |
+
self.register_modules(transformers=transformers, scheduler=scheduler, decoder=decoder)
|
| 122 |
+
# PAE decoders already return pixels in [0, 1]; disable VAE-style [-1, 1] denormalization.
|
| 123 |
+
self.image_processor = VaeImageProcessor(do_normalize=False)
|
| 124 |
+
self._id2label: Dict[int, str] = {}
|
| 125 |
+
self.labels: Dict[str, int] = {}
|
| 126 |
+
self._labels_loaded_from_model_index = False
|
| 127 |
+
|
| 128 |
+
@property
|
| 129 |
+
def transformer(self):
|
| 130 |
+
"""Backward-compatible alias for `transformers`."""
|
| 131 |
+
return self.transformers
|
| 132 |
+
|
| 133 |
+
@staticmethod
|
| 134 |
+
def _normalize_id2label(id2label: Optional[Dict[Union[int, str], str]]) -> Dict[int, str]:
|
| 135 |
+
if not id2label:
|
| 136 |
+
return {}
|
| 137 |
+
return {int(key): value for key, value in id2label.items()}
|
| 138 |
+
|
| 139 |
+
@staticmethod
|
| 140 |
+
def _read_model_index(variant_path: Optional[str]) -> Dict[str, Any]:
|
| 141 |
+
if not variant_path:
|
| 142 |
+
return {}
|
| 143 |
+
variant_dir = Path(variant_path).resolve()
|
| 144 |
+
model_index_path = variant_dir / "model_index.json"
|
| 145 |
+
if not model_index_path.is_file():
|
| 146 |
+
return {}
|
| 147 |
+
raw = json.loads(model_index_path.read_text(encoding="utf-8"))
|
| 148 |
+
return raw if isinstance(raw, dict) else {}
|
| 149 |
+
|
| 150 |
+
@staticmethod
|
| 151 |
+
def _read_id2label_from_model_index(variant_path: Optional[str]) -> Dict[int, str]:
|
| 152 |
+
id2label = PAEPipeline._read_model_index(variant_path).get("id2label")
|
| 153 |
+
if not isinstance(id2label, dict):
|
| 154 |
+
return {}
|
| 155 |
+
return {int(key): value for key, value in id2label.items()}
|
| 156 |
+
|
| 157 |
+
def _get_downsample_ratio(self) -> int:
|
| 158 |
+
override = getattr(self.config, "downsample_ratio", None)
|
| 159 |
+
if override is not None:
|
| 160 |
+
return int(override)
|
| 161 |
+
|
| 162 |
+
encoder_input_size = None
|
| 163 |
+
if self.decoder is not None:
|
| 164 |
+
encoder_input_size = getattr(self.decoder.config, "encoder_input_size", None)
|
| 165 |
+
|
| 166 |
+
if encoder_input_size is not None:
|
| 167 |
+
return int(encoder_input_size) // int(self.transformers.config.input_size)
|
| 168 |
+
return 16
|
| 169 |
+
|
| 170 |
+
def _resolve_latent_stats(
|
| 171 |
+
self,
|
| 172 |
+
latent_mean: Optional[torch.Tensor],
|
| 173 |
+
latent_std: Optional[torch.Tensor],
|
| 174 |
+
latent_multiplier: Optional[float],
|
| 175 |
+
device: torch.device,
|
| 176 |
+
dtype: torch.dtype,
|
| 177 |
+
) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], float]:
|
| 178 |
+
if latent_mean is not None and latent_std is not None:
|
| 179 |
+
return latent_mean, latent_std, float(latent_multiplier if latent_multiplier is not None else 1.0)
|
| 180 |
+
|
| 181 |
+
decoder_cfg = getattr(self.decoder, "config", None) if self.decoder is not None else None
|
| 182 |
+
if decoder_cfg is not None:
|
| 183 |
+
mean = getattr(decoder_cfg, "latent_mean", None)
|
| 184 |
+
std = getattr(decoder_cfg, "latent_std", None)
|
| 185 |
+
if mean is not None and std is not None:
|
| 186 |
+
multiplier = getattr(decoder_cfg, "latent_multiplier", 1.0)
|
| 187 |
+
mean_tensor = torch.tensor(mean, device=device, dtype=dtype).view(1, -1, 1, 1)
|
| 188 |
+
std_tensor = torch.tensor(std, device=device, dtype=dtype).view(1, -1, 1, 1)
|
| 189 |
+
return mean_tensor, std_tensor, float(multiplier)
|
| 190 |
+
|
| 191 |
+
return latent_mean, latent_std, float(latent_multiplier if latent_multiplier is not None else 1.0)
|
| 192 |
+
|
| 193 |
+
@staticmethod
|
| 194 |
+
def _build_label2id(id2label: Dict[int, str]) -> Dict[str, int]:
|
| 195 |
+
label2id: Dict[str, int] = {}
|
| 196 |
+
for class_id, value in id2label.items():
|
| 197 |
+
for synonym in value.split(","):
|
| 198 |
+
synonym = synonym.strip()
|
| 199 |
+
if synonym:
|
| 200 |
+
label2id[synonym] = int(class_id)
|
| 201 |
+
return dict(sorted(label2id.items()))
|
| 202 |
+
|
| 203 |
+
def _ensure_labels_loaded(self) -> None:
|
| 204 |
+
if self._labels_loaded_from_model_index:
|
| 205 |
+
return
|
| 206 |
+
loaded = self._read_id2label_from_model_index(getattr(self.config, "_name_or_path", None))
|
| 207 |
+
if loaded:
|
| 208 |
+
self._id2label = loaded
|
| 209 |
+
self.labels = self._build_label2id(self._id2label)
|
| 210 |
+
self._labels_loaded_from_model_index = True
|
| 211 |
+
|
| 212 |
+
@property
|
| 213 |
+
def id2label(self) -> Dict[int, str]:
|
| 214 |
+
r"""ImageNet class id to English label string (comma-separated synonyms)."""
|
| 215 |
+
self._ensure_labels_loaded()
|
| 216 |
+
return self._id2label
|
| 217 |
+
|
| 218 |
+
def get_label_ids(self, label: Union[str, List[str]]) -> List[int]:
|
| 219 |
+
r"""
|
| 220 |
+
Map ImageNet label strings to class ids.
|
| 221 |
+
|
| 222 |
+
Args:
|
| 223 |
+
label:
|
| 224 |
+
One or more English label strings. Each string must match a synonym in `id2label`.
|
| 225 |
+
|
| 226 |
+
Returns:
|
| 227 |
+
Matching ImageNet class ids.
|
| 228 |
+
"""
|
| 229 |
+
self._ensure_labels_loaded()
|
| 230 |
+
label2id = self.labels
|
| 231 |
+
if not label2id:
|
| 232 |
+
raise ValueError("No English labels loaded. Ensure `id2label` exists in model_index.json.")
|
| 233 |
+
|
| 234 |
+
if isinstance(label, str):
|
| 235 |
+
label = [label]
|
| 236 |
+
|
| 237 |
+
missing = [item for item in label if item not in label2id]
|
| 238 |
+
if missing:
|
| 239 |
+
preview = ", ".join(list(label2id.keys())[:8])
|
| 240 |
+
raise ValueError(f"Unknown English label(s): {missing}. Example valid labels: {preview}, ...")
|
| 241 |
+
return [label2id[item] for item in label]
|
| 242 |
+
|
| 243 |
+
def _default_image_size(self) -> int:
|
| 244 |
+
return int(self.transformers.config.input_size) * self._get_downsample_ratio()
|
| 245 |
+
|
| 246 |
+
def _normalize_class_labels(
|
| 247 |
+
self,
|
| 248 |
+
class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
|
| 249 |
+
) -> torch.LongTensor:
|
| 250 |
+
if torch.is_tensor(class_labels):
|
| 251 |
+
return class_labels.to(device=self._execution_device, dtype=torch.long).reshape(-1)
|
| 252 |
+
|
| 253 |
+
if isinstance(class_labels, int):
|
| 254 |
+
class_label_ids = [class_labels]
|
| 255 |
+
elif isinstance(class_labels, str):
|
| 256 |
+
class_label_ids = self.get_label_ids(class_labels)
|
| 257 |
+
elif class_labels and isinstance(class_labels[0], str):
|
| 258 |
+
class_label_ids = self.get_label_ids(class_labels)
|
| 259 |
+
else:
|
| 260 |
+
class_label_ids = list(class_labels)
|
| 261 |
+
|
| 262 |
+
return torch.tensor(class_label_ids, device=self._execution_device, dtype=torch.long).reshape(-1)
|
| 263 |
+
|
| 264 |
+
def check_inputs(
|
| 265 |
+
self,
|
| 266 |
+
height: int,
|
| 267 |
+
width: int,
|
| 268 |
+
num_inference_steps: int,
|
| 269 |
+
output_type: str,
|
| 270 |
+
mode: str,
|
| 271 |
+
) -> None:
|
| 272 |
+
if num_inference_steps < 1:
|
| 273 |
+
raise ValueError("num_inference_steps must be >= 1.")
|
| 274 |
+
if output_type not in {"pil", "np", "pt", "latent"}:
|
| 275 |
+
raise ValueError("output_type must be one of: 'pil', 'np', 'pt', 'latent'.")
|
| 276 |
+
if mode not in {"ode", "sde"}:
|
| 277 |
+
raise ValueError("mode must be either 'ode' or 'sde'.")
|
| 278 |
+
|
| 279 |
+
downsample = self._get_downsample_ratio()
|
| 280 |
+
if height % downsample != 0 or width % downsample != 0:
|
| 281 |
+
raise ValueError(
|
| 282 |
+
f"height and width must be divisible by the PAE downsample factor {downsample}."
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
latent_height = height // downsample
|
| 286 |
+
latent_width = width // downsample
|
| 287 |
+
expected_size = int(self.transformers.config.input_size)
|
| 288 |
+
if latent_height != expected_size or latent_width != expected_size:
|
| 289 |
+
raise ValueError(
|
| 290 |
+
f"Requested latent size {(latent_height, latent_width)} does not match the pretrained "
|
| 291 |
+
f"transformer input_size={expected_size}. Use height=width={self._default_image_size()}."
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
def prepare_latents(
|
| 295 |
+
self,
|
| 296 |
+
batch_size: int,
|
| 297 |
+
height: int,
|
| 298 |
+
width: int,
|
| 299 |
+
dtype: torch.dtype,
|
| 300 |
+
device: torch.device,
|
| 301 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 302 |
+
) -> torch.Tensor:
|
| 303 |
+
downsample = self._get_downsample_ratio()
|
| 304 |
+
latent_height = height // downsample
|
| 305 |
+
latent_width = width // downsample
|
| 306 |
+
return randn_tensor(
|
| 307 |
+
(batch_size, self.transformers.config.in_channels, latent_height, latent_width),
|
| 308 |
+
generator=generator,
|
| 309 |
+
device=device,
|
| 310 |
+
dtype=dtype,
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
@staticmethod
|
| 314 |
+
def _denormalize_latents(
|
| 315 |
+
latents: torch.Tensor,
|
| 316 |
+
latent_mean: Optional[torch.Tensor],
|
| 317 |
+
latent_std: Optional[torch.Tensor],
|
| 318 |
+
latent_multiplier: Optional[float],
|
| 319 |
+
) -> torch.Tensor:
|
| 320 |
+
if latent_mean is None or latent_std is None:
|
| 321 |
+
return latents
|
| 322 |
+
multiplier = 1.0 if latent_multiplier is None else float(latent_multiplier)
|
| 323 |
+
mean = latent_mean.to(device=latents.device, dtype=latents.dtype)
|
| 324 |
+
std = latent_std.to(device=latents.device, dtype=latents.dtype)
|
| 325 |
+
return (latents * std) / multiplier + mean
|
| 326 |
+
|
| 327 |
+
@staticmethod
|
| 328 |
+
def _apply_cfg(
|
| 329 |
+
model_output: torch.Tensor,
|
| 330 |
+
guidance_scale: float,
|
| 331 |
+
guidance_active: bool,
|
| 332 |
+
cfg_channels: int,
|
| 333 |
+
) -> torch.Tensor:
|
| 334 |
+
if guidance_scale <= 1.0 or not guidance_active:
|
| 335 |
+
return model_output
|
| 336 |
+
eps, rest = model_output[:, :cfg_channels], model_output[:, cfg_channels:]
|
| 337 |
+
cond_eps, uncond_eps = torch.chunk(eps, 2, dim=0)
|
| 338 |
+
half_eps = uncond_eps + guidance_scale * (cond_eps - uncond_eps)
|
| 339 |
+
if rest.shape[1] == 0:
|
| 340 |
+
return half_eps
|
| 341 |
+
return torch.cat([half_eps, rest], dim=1)
|
| 342 |
+
|
| 343 |
+
def decode_latents(
|
| 344 |
+
self,
|
| 345 |
+
latents: torch.Tensor,
|
| 346 |
+
output_type: str = "pil",
|
| 347 |
+
latent_mean: Optional[torch.Tensor] = None,
|
| 348 |
+
latent_std: Optional[torch.Tensor] = None,
|
| 349 |
+
latent_multiplier: Optional[float] = None,
|
| 350 |
+
):
|
| 351 |
+
if output_type == "latent":
|
| 352 |
+
return latents
|
| 353 |
+
if self.decoder is None:
|
| 354 |
+
raise ValueError("PAEPipeline requires a PAE decoder component for decoding.")
|
| 355 |
+
|
| 356 |
+
latent_mean, latent_std, latent_multiplier = self._resolve_latent_stats(
|
| 357 |
+
latent_mean,
|
| 358 |
+
latent_std,
|
| 359 |
+
latent_multiplier,
|
| 360 |
+
device=latents.device,
|
| 361 |
+
dtype=latents.dtype,
|
| 362 |
+
)
|
| 363 |
+
latents = self._denormalize_latents(latents, latent_mean, latent_std, latent_multiplier)
|
| 364 |
+
image = self.decoder.decode(latents)
|
| 365 |
+
image = torch.clamp(image, 0.0, 1.0)
|
| 366 |
+
if output_type == "pt":
|
| 367 |
+
return image
|
| 368 |
+
return self.image_processor.postprocess(image, output_type=output_type, do_denormalize=[False] * image.shape[0])
|
| 369 |
+
|
| 370 |
+
@torch.inference_mode()
|
| 371 |
+
def __call__(
|
| 372 |
+
self,
|
| 373 |
+
class_labels: Union[int, str, List[Union[int, str]], torch.LongTensor],
|
| 374 |
+
height: Optional[int] = None,
|
| 375 |
+
width: Optional[int] = None,
|
| 376 |
+
num_inference_steps: int = 250,
|
| 377 |
+
guidance_scale: float = 3.3,
|
| 378 |
+
guidance_interval: Tuple[float, float] = (0.0, 1.0),
|
| 379 |
+
cfg_interval_start: float = 0.3,
|
| 380 |
+
timestep_shift: float = 0.4,
|
| 381 |
+
mode: str = "ode",
|
| 382 |
+
heun: bool = False,
|
| 383 |
+
latent_mean: Optional[torch.Tensor] = None,
|
| 384 |
+
latent_std: Optional[torch.Tensor] = None,
|
| 385 |
+
latent_multiplier: Optional[float] = None,
|
| 386 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 387 |
+
output_type: str = "pil",
|
| 388 |
+
return_dict: bool = True,
|
| 389 |
+
) -> Union[ImagePipelineOutput, Tuple]:
|
| 390 |
+
r"""
|
| 391 |
+
Generate class-conditional images with PAE + LightningDiT.
|
| 392 |
+
|
| 393 |
+
Args:
|
| 394 |
+
class_labels:
|
| 395 |
+
ImageNet class indices or human-readable English label strings.
|
| 396 |
+
height:
|
| 397 |
+
Output image height in pixels. Defaults to the pretrained native resolution.
|
| 398 |
+
width:
|
| 399 |
+
Output image width in pixels. Defaults to the pretrained native resolution.
|
| 400 |
+
num_inference_steps:
|
| 401 |
+
Number of flow-matching integration steps.
|
| 402 |
+
guidance_scale:
|
| 403 |
+
Classifier-free guidance scale. Active when `guidance_scale > 1.0`.
|
| 404 |
+
guidance_interval:
|
| 405 |
+
Timestep interval `(low, high)` where CFG is applied.
|
| 406 |
+
cfg_interval_start:
|
| 407 |
+
Disable CFG below this normalized timestep value. Default `0.3` matches DiT training configs.
|
| 408 |
+
timestep_shift:
|
| 409 |
+
Timestep warping used by LightningDiT ODE sampling. Default `0.4` matches DiT training configs.
|
| 410 |
+
mode:
|
| 411 |
+
Sampling mode passed to the PAE flow scheduler: `"ode"` or `"sde"`.
|
| 412 |
+
heun:
|
| 413 |
+
Use Heun integration for ODE sampling when True.
|
| 414 |
+
latent_mean:
|
| 415 |
+
Optional latent mean tensor for denormalization before PAE decode. Defaults to
|
| 416 |
+
`latent_mean` in `decoder/config.json` when omitted.
|
| 417 |
+
latent_std:
|
| 418 |
+
Optional latent std tensor for denormalization before PAE decode. Defaults to
|
| 419 |
+
`latent_std` in `decoder/config.json` when omitted.
|
| 420 |
+
latent_multiplier:
|
| 421 |
+
Divisor applied with `latent_std` during denormalization. Defaults to
|
| 422 |
+
`latent_multiplier` in `decoder/config.json` or `1.0`.
|
| 423 |
+
generator:
|
| 424 |
+
RNG for reproducibility.
|
| 425 |
+
output_type:
|
| 426 |
+
`"pil"`, `"np"`, `"pt"`, or `"latent"`.
|
| 427 |
+
return_dict:
|
| 428 |
+
Return [`ImagePipelineOutput`] if True.
|
| 429 |
+
"""
|
| 430 |
+
default_size = self._default_image_size()
|
| 431 |
+
height = int(height or default_size)
|
| 432 |
+
width = int(width or default_size)
|
| 433 |
+
self.check_inputs(height, width, num_inference_steps, output_type, mode)
|
| 434 |
+
|
| 435 |
+
device = self._execution_device
|
| 436 |
+
model_dtype = next(self.transformers.parameters()).dtype
|
| 437 |
+
class_labels_tensor = self._normalize_class_labels(class_labels)
|
| 438 |
+
batch_size = class_labels_tensor.numel()
|
| 439 |
+
null_label = int(self.transformers.config.num_classes)
|
| 440 |
+
null_labels = torch.full((batch_size,), null_label, device=device, dtype=torch.long)
|
| 441 |
+
cfg_channels = int(self.transformers.config.in_channels)
|
| 442 |
+
|
| 443 |
+
latents = self.prepare_latents(
|
| 444 |
+
batch_size=batch_size,
|
| 445 |
+
height=height,
|
| 446 |
+
width=width,
|
| 447 |
+
dtype=model_dtype,
|
| 448 |
+
device=device,
|
| 449 |
+
generator=generator,
|
| 450 |
+
)
|
| 451 |
+
timesteps = self.scheduler.set_timesteps(
|
| 452 |
+
num_inference_steps, device=device, mode=mode, timestep_shift=timestep_shift
|
| 453 |
+
)
|
| 454 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(self.scheduler, generator=generator)
|
| 455 |
+
|
| 456 |
+
for index, timestep in enumerate(timesteps[:-1]):
|
| 457 |
+
next_timestep = timesteps[index + 1]
|
| 458 |
+
t_value = float(timestep)
|
| 459 |
+
guidance_active = guidance_scale > 1.0 and guidance_interval[0] <= t_value <= guidance_interval[1]
|
| 460 |
+
if cfg_interval_start is not None and t_value < cfg_interval_start:
|
| 461 |
+
guidance_active = False
|
| 462 |
+
|
| 463 |
+
if guidance_active:
|
| 464 |
+
model_input = torch.cat([latents, latents], dim=0)
|
| 465 |
+
labels = torch.cat([class_labels_tensor, null_labels], dim=0)
|
| 466 |
+
else:
|
| 467 |
+
model_input = latents
|
| 468 |
+
labels = class_labels_tensor
|
| 469 |
+
|
| 470 |
+
timestep_batch = torch.full((labels.shape[0],), t_value, device=device, dtype=model_dtype)
|
| 471 |
+
model_output = self.transformers(
|
| 472 |
+
model_input.to(dtype=model_dtype),
|
| 473 |
+
timestep=timestep_batch,
|
| 474 |
+
class_labels=labels,
|
| 475 |
+
return_dict=True,
|
| 476 |
+
).sample
|
| 477 |
+
model_output = self._apply_cfg(model_output, guidance_scale, guidance_active, cfg_channels)
|
| 478 |
+
|
| 479 |
+
if heun and mode == "ode" and index < len(timesteps) - 2:
|
| 480 |
+
provisional = self.scheduler.step(
|
| 481 |
+
model_output,
|
| 482 |
+
timestep[None],
|
| 483 |
+
latents,
|
| 484 |
+
next_timestep[None],
|
| 485 |
+
**extra_step_kwargs,
|
| 486 |
+
).prev_sample
|
| 487 |
+
if guidance_active:
|
| 488 |
+
prime_input = torch.cat([provisional, provisional], dim=0)
|
| 489 |
+
prime_labels = torch.cat([class_labels_tensor, null_labels], dim=0)
|
| 490 |
+
else:
|
| 491 |
+
prime_input = provisional
|
| 492 |
+
prime_labels = class_labels_tensor
|
| 493 |
+
next_timestep_batch = torch.full(
|
| 494 |
+
(prime_labels.shape[0],), float(next_timestep), device=device, dtype=model_dtype
|
| 495 |
+
)
|
| 496 |
+
next_output = self.transformers(
|
| 497 |
+
prime_input.to(dtype=model_dtype),
|
| 498 |
+
timestep=next_timestep_batch,
|
| 499 |
+
class_labels=prime_labels,
|
| 500 |
+
return_dict=True,
|
| 501 |
+
).sample
|
| 502 |
+
next_output = self._apply_cfg(next_output, guidance_scale, guidance_active, cfg_channels)
|
| 503 |
+
latents = self.scheduler.step_heun(
|
| 504 |
+
model_output, next_output, timestep[None], latents, next_timestep[None]
|
| 505 |
+
).prev_sample
|
| 506 |
+
else:
|
| 507 |
+
latents = self.scheduler.step(
|
| 508 |
+
model_output,
|
| 509 |
+
timestep[None],
|
| 510 |
+
latents,
|
| 511 |
+
next_timestep[None],
|
| 512 |
+
**extra_step_kwargs,
|
| 513 |
+
).prev_sample
|
| 514 |
+
|
| 515 |
+
image = self.decode_latents(
|
| 516 |
+
latents.to(dtype=model_dtype),
|
| 517 |
+
output_type=output_type,
|
| 518 |
+
latent_mean=latent_mean,
|
| 519 |
+
latent_std=latent_std,
|
| 520 |
+
latent_multiplier=latent_multiplier,
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
self.maybe_free_model_hooks()
|
| 524 |
+
if not return_dict:
|
| 525 |
+
return (image,)
|
| 526 |
+
return ImagePipelineOutput(images=image)
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
# Backward-compatible alias used by earlier PAE-diffusers releases.
|
| 530 |
+
PAEPipelineOutput = ImagePipelineOutput
|
pae-siglip2-so400m-d32/scheduler/__pycache__/scheduling_flow_match_pae.cpython-311.pyc
ADDED
|
Binary file (12.8 kB). View file
|
|
|
pae-siglip2-so400m-d32/scheduler/scheduler_config.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "PAEFlowMatchScheduler",
|
| 3 |
+
"_diffusers_version": "0.31.0",
|
| 4 |
+
"mode": "ode",
|
| 5 |
+
"path_type": "linear",
|
| 6 |
+
"num_train_timesteps": 1000
|
| 7 |
+
}
|
pae-siglip2-so400m-d32/scheduler/scheduling_flow_match_pae.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from typing import Optional, Tuple
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 14 |
+
from diffusers.schedulers.scheduling_utils import SchedulerMixin
|
| 15 |
+
from diffusers.utils import BaseOutput
|
| 16 |
+
except Exception: # pragma: no cover - importable without an installed diffusers checkout.
|
| 17 |
+
class BaseOutput(dict):
|
| 18 |
+
def __post_init__(self):
|
| 19 |
+
self.update(self.__dict__)
|
| 20 |
+
|
| 21 |
+
class ConfigMixin:
|
| 22 |
+
config_name = "scheduler_config.json"
|
| 23 |
+
|
| 24 |
+
class SchedulerMixin:
|
| 25 |
+
pass
|
| 26 |
+
|
| 27 |
+
def register_to_config(init):
|
| 28 |
+
return init
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass
|
| 32 |
+
class PAEFlowMatchSchedulerOutput(BaseOutput):
|
| 33 |
+
prev_sample: torch.FloatTensor
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class PAEFlowMatchScheduler(SchedulerMixin, ConfigMixin):
|
| 37 |
+
"""
|
| 38 |
+
Flow-matching ODE/SDE scheduler used by PAE + LightningDiT pipelines.
|
| 39 |
+
|
| 40 |
+
The model predicts velocity with a linear path by default. ODE timesteps run from 0 to 1
|
| 41 |
+
(noise to data), matching LightningDiT transport sampling.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
config_name = "scheduler_config.json"
|
| 45 |
+
order = 1
|
| 46 |
+
|
| 47 |
+
@register_to_config
|
| 48 |
+
def __init__(
|
| 49 |
+
self,
|
| 50 |
+
mode: str = "ode",
|
| 51 |
+
path_type: str = "linear",
|
| 52 |
+
num_train_timesteps: int = 1000,
|
| 53 |
+
):
|
| 54 |
+
if mode not in {"ode", "sde"}:
|
| 55 |
+
raise ValueError("mode must be either 'ode' or 'sde'.")
|
| 56 |
+
if path_type not in {"linear", "cosine"}:
|
| 57 |
+
raise ValueError("path_type must be either 'linear' or 'cosine'.")
|
| 58 |
+
self.mode = mode
|
| 59 |
+
self.path_type = path_type
|
| 60 |
+
self.num_train_timesteps = num_train_timesteps
|
| 61 |
+
# Native NiT integrates in float64 for better numerical stability.
|
| 62 |
+
self.timesteps = torch.from_numpy(np.linspace(0.0, 1.0, num_train_timesteps + 1)).to(dtype=torch.float64)
|
| 63 |
+
|
| 64 |
+
@staticmethod
|
| 65 |
+
def _apply_timestep_shift(timesteps: torch.Tensor, timestep_shift: float) -> torch.Tensor:
|
| 66 |
+
if timestep_shift <= 0:
|
| 67 |
+
return timesteps
|
| 68 |
+
return timestep_shift * timesteps / (1 + (timestep_shift - 1) * timesteps)
|
| 69 |
+
|
| 70 |
+
def set_timesteps(
|
| 71 |
+
self,
|
| 72 |
+
num_inference_steps: int,
|
| 73 |
+
device: Optional[torch.device] = None,
|
| 74 |
+
mode: Optional[str] = None,
|
| 75 |
+
timestep_shift: float = 0.0,
|
| 76 |
+
):
|
| 77 |
+
mode = mode or self.mode
|
| 78 |
+
dtype = self.timesteps.dtype
|
| 79 |
+
if mode == "sde":
|
| 80 |
+
timesteps = torch.linspace(1.0, 0.04, num_inference_steps, dtype=dtype)
|
| 81 |
+
timesteps = torch.cat([timesteps, torch.zeros(1, dtype=dtype)])
|
| 82 |
+
elif mode == "ode":
|
| 83 |
+
timesteps = torch.linspace(0.0, 1.0, num_inference_steps + 1, dtype=dtype)
|
| 84 |
+
timesteps = self._apply_timestep_shift(timesteps, timestep_shift)
|
| 85 |
+
else:
|
| 86 |
+
raise ValueError("mode must be either 'ode' or 'sde'.")
|
| 87 |
+
self.mode = mode
|
| 88 |
+
self.timesteps = timesteps.to(device=device)
|
| 89 |
+
return self.timesteps
|
| 90 |
+
|
| 91 |
+
@staticmethod
|
| 92 |
+
def _expand_t_like_sample(timestep: torch.Tensor, sample: torch.Tensor, image_sizes: torch.LongTensor):
|
| 93 |
+
dims = [1] * (sample.ndim - 1)
|
| 94 |
+
seqlens = image_sizes[:, 0] * image_sizes[:, 1]
|
| 95 |
+
if timestep.numel() == 1:
|
| 96 |
+
timestep = timestep.repeat(image_sizes.shape[0])
|
| 97 |
+
return torch.cat(
|
| 98 |
+
[timestep[i].reshape(1, *dims).repeat(int(seqlens[i]), *dims) for i in range(image_sizes.shape[0])]
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
def _get_score_from_velocity(
|
| 102 |
+
self,
|
| 103 |
+
model_output: torch.Tensor,
|
| 104 |
+
sample: torch.Tensor,
|
| 105 |
+
timestep: torch.Tensor,
|
| 106 |
+
image_sizes: torch.LongTensor,
|
| 107 |
+
):
|
| 108 |
+
timestep = self._expand_t_like_sample(timestep, sample, image_sizes)
|
| 109 |
+
if self.path_type == "linear":
|
| 110 |
+
alpha_t, d_alpha_t = 1 - timestep, torch.ones_like(timestep) * -1
|
| 111 |
+
sigma_t, d_sigma_t = timestep, torch.ones_like(timestep)
|
| 112 |
+
elif self.path_type == "cosine":
|
| 113 |
+
alpha_t = torch.cos(timestep * np.pi / 2)
|
| 114 |
+
sigma_t = torch.sin(timestep * np.pi / 2)
|
| 115 |
+
d_alpha_t = -np.pi / 2 * torch.sin(timestep * np.pi / 2)
|
| 116 |
+
d_sigma_t = np.pi / 2 * torch.cos(timestep * np.pi / 2)
|
| 117 |
+
else:
|
| 118 |
+
raise ValueError(f"Unsupported path_type: {self.path_type}")
|
| 119 |
+
reverse_alpha_ratio = alpha_t / d_alpha_t
|
| 120 |
+
variance = sigma_t**2 - reverse_alpha_ratio * d_sigma_t * sigma_t
|
| 121 |
+
return (reverse_alpha_ratio * model_output - sample) / variance
|
| 122 |
+
|
| 123 |
+
@staticmethod
|
| 124 |
+
def _compute_diffusion(timestep: torch.Tensor):
|
| 125 |
+
return 2 * timestep
|
| 126 |
+
|
| 127 |
+
@staticmethod
|
| 128 |
+
def _promote_dtypes(*tensors: torch.Tensor) -> torch.dtype:
|
| 129 |
+
dtype = None
|
| 130 |
+
for tensor in tensors:
|
| 131 |
+
if tensor.is_floating_point() or tensor.is_complex():
|
| 132 |
+
dtype = tensor.dtype if dtype is None else torch.promote_types(dtype, tensor.dtype)
|
| 133 |
+
return dtype if dtype is not None else torch.get_default_dtype()
|
| 134 |
+
|
| 135 |
+
def step(
|
| 136 |
+
self,
|
| 137 |
+
model_output: torch.Tensor,
|
| 138 |
+
timestep: torch.Tensor,
|
| 139 |
+
sample: torch.Tensor,
|
| 140 |
+
next_timestep: torch.Tensor,
|
| 141 |
+
image_sizes: Optional[torch.LongTensor] = None,
|
| 142 |
+
generator: Optional[torch.Generator] = None,
|
| 143 |
+
return_dict: bool = True,
|
| 144 |
+
) -> PAEFlowMatchSchedulerOutput:
|
| 145 |
+
sample_dtype = sample.dtype
|
| 146 |
+
compute_dtype = torch.float64
|
| 147 |
+
sample = sample.to(dtype=compute_dtype)
|
| 148 |
+
model_output = model_output.to(dtype=compute_dtype)
|
| 149 |
+
timestep = timestep.to(device=sample.device, dtype=compute_dtype).flatten()
|
| 150 |
+
next_timestep = next_timestep.to(device=sample.device, dtype=compute_dtype).flatten()
|
| 151 |
+
|
| 152 |
+
if self.mode == "ode":
|
| 153 |
+
prev_sample = sample + (next_timestep[0] - timestep[0]) * model_output
|
| 154 |
+
else:
|
| 155 |
+
if image_sizes is None:
|
| 156 |
+
batch = sample.shape[0]
|
| 157 |
+
side = int(sample.shape[-1])
|
| 158 |
+
image_sizes = torch.tensor([[side, side]] * batch, device=sample.device, dtype=torch.long)
|
| 159 |
+
image_sizes = image_sizes.to(device=sample.device, dtype=torch.long)
|
| 160 |
+
diffusion = self._compute_diffusion(timestep[0])
|
| 161 |
+
score = self._get_score_from_velocity(model_output, sample, timestep, image_sizes)
|
| 162 |
+
drift = model_output - 0.5 * diffusion * score
|
| 163 |
+
dt = next_timestep[0] - timestep[0]
|
| 164 |
+
if torch.allclose(next_timestep[0], torch.zeros_like(next_timestep[0])):
|
| 165 |
+
prev_sample = sample + drift * dt
|
| 166 |
+
else:
|
| 167 |
+
if generator is not None:
|
| 168 |
+
noise = torch.randn(sample.shape, generator=generator, device=sample.device, dtype=sample.dtype)
|
| 169 |
+
else:
|
| 170 |
+
noise = torch.randn_like(sample)
|
| 171 |
+
prev_sample = sample + drift * dt + torch.sqrt(diffusion) * noise * torch.sqrt(torch.abs(dt))
|
| 172 |
+
|
| 173 |
+
prev_sample = prev_sample.to(sample_dtype)
|
| 174 |
+
if not return_dict:
|
| 175 |
+
return (prev_sample,)
|
| 176 |
+
return PAEFlowMatchSchedulerOutput(prev_sample=prev_sample)
|
| 177 |
+
|
| 178 |
+
def step_heun(
|
| 179 |
+
self,
|
| 180 |
+
model_output: torch.Tensor,
|
| 181 |
+
next_model_output: torch.Tensor,
|
| 182 |
+
timestep: torch.Tensor,
|
| 183 |
+
sample: torch.Tensor,
|
| 184 |
+
next_timestep: torch.Tensor,
|
| 185 |
+
return_dict: bool = True,
|
| 186 |
+
) -> PAEFlowMatchSchedulerOutput:
|
| 187 |
+
if self.mode != "ode":
|
| 188 |
+
raise ValueError("Heun correction is only defined for ODE sampling.")
|
| 189 |
+
sample_dtype = sample.dtype
|
| 190 |
+
compute_dtype = torch.float64
|
| 191 |
+
sample = sample.to(dtype=compute_dtype)
|
| 192 |
+
model_output = model_output.to(dtype=compute_dtype)
|
| 193 |
+
next_model_output = next_model_output.to(dtype=compute_dtype)
|
| 194 |
+
timestep = timestep.to(device=sample.device, dtype=compute_dtype).flatten()
|
| 195 |
+
next_timestep = next_timestep.to(device=sample.device, dtype=compute_dtype).flatten()
|
| 196 |
+
prev_sample = sample + (next_timestep[0] - timestep[0]) * (0.5 * model_output + 0.5 * next_model_output)
|
| 197 |
+
prev_sample = prev_sample.to(sample_dtype)
|
| 198 |
+
if not return_dict:
|
| 199 |
+
return (prev_sample,)
|
| 200 |
+
return PAEFlowMatchSchedulerOutput(prev_sample=prev_sample)
|
pae-siglip2-so400m-d32/transformers/__pycache__/transformer_lightning_dit.cpython-311.pyc
ADDED
|
Binary file (44.5 kB). View file
|
|
|