Upload 6 files
Browse files- config.json +43 -0
- configuration_uniflow.py +92 -0
- flash_attention.py +76 -0
- model.safetensors +3 -0
- modeling_uniflow.py +845 -0
- preprocessor_config.json +19 -0
config.json
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"UniFlowVisionModel"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_uniflow.UniFlowVisionConfig",
|
| 7 |
+
"AutoModel": "modeling_uniflow.UniFlowVisionModel"
|
| 8 |
+
},
|
| 9 |
+
"attention_dropout": 0.0,
|
| 10 |
+
"drop_path_rate": 0.1,
|
| 11 |
+
"dropout": 0.0,
|
| 12 |
+
"hidden_act": "gelu",
|
| 13 |
+
"hidden_size": 1024,
|
| 14 |
+
"image_size": 448,
|
| 15 |
+
"initializer_factor": 1.0,
|
| 16 |
+
"initializer_range": 0.02,
|
| 17 |
+
"intermediate_size": 4096,
|
| 18 |
+
"layer_norm_eps": 1e-06,
|
| 19 |
+
"model_type": "uniflow",
|
| 20 |
+
"norm_type": "layer_norm",
|
| 21 |
+
"num_attention_heads": 16,
|
| 22 |
+
"num_channels": 3,
|
| 23 |
+
"num_hidden_layers": 24,
|
| 24 |
+
"patch_size": 14,
|
| 25 |
+
"qk_normalization": false,
|
| 26 |
+
"qkv_bias": true,
|
| 27 |
+
"torch_dtype": "bfloat16",
|
| 28 |
+
"transformers_version": "4.37.2",
|
| 29 |
+
"use_flash_attn": true,
|
| 30 |
+
|
| 31 |
+
"vit_hidden_size": 1024,
|
| 32 |
+
"llm_hidden_size": 1536,
|
| 33 |
+
"use_chal_proj": true,
|
| 34 |
+
"latent_ch": 64,
|
| 35 |
+
"use_global_blocks": true,
|
| 36 |
+
"global_blocks_depth": 6,
|
| 37 |
+
|
| 38 |
+
"use_cfg": false,
|
| 39 |
+
"use_disp_loss": false,
|
| 40 |
+
"decoder_type": "mlp",
|
| 41 |
+
"num_decoder_layers": 12,
|
| 42 |
+
"num_sampling_steps": "1"
|
| 43 |
+
}
|
configuration_uniflow.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import Optional, Tuple, Union
|
| 3 |
+
from collections import OrderedDict
|
| 4 |
+
|
| 5 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 6 |
+
from transformers.utils import logging
|
| 7 |
+
|
| 8 |
+
logger = logging.get_logger(__name__)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class UniFlowVisionConfig(PretrainedConfig):
|
| 13 |
+
model_type = 'uniflow'
|
| 14 |
+
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
num_channels=3,
|
| 18 |
+
patch_size=14,
|
| 19 |
+
image_size=224,
|
| 20 |
+
qkv_bias=False,
|
| 21 |
+
hidden_size=3200,
|
| 22 |
+
num_attention_heads=25,
|
| 23 |
+
intermediate_size=12800,
|
| 24 |
+
qk_normalization=True,
|
| 25 |
+
num_hidden_layers=48,
|
| 26 |
+
use_flash_attn=True,
|
| 27 |
+
hidden_act='gelu',
|
| 28 |
+
norm_type='rms_norm',
|
| 29 |
+
layer_norm_eps=1e-6,
|
| 30 |
+
dropout=0.0,
|
| 31 |
+
drop_path_rate=0.0,
|
| 32 |
+
attention_dropout=0.0,
|
| 33 |
+
initializer_range=0.02,
|
| 34 |
+
initializer_factor=0.1,
|
| 35 |
+
# enc_proj
|
| 36 |
+
vit_hidden_size=1024,
|
| 37 |
+
llm_hidden_size=1536,
|
| 38 |
+
latent_ch=64,
|
| 39 |
+
# flow decoder
|
| 40 |
+
use_global_blocks=True,
|
| 41 |
+
global_blocks_depth=6,
|
| 42 |
+
num_decoder_layers=12,
|
| 43 |
+
num_sampling_steps='100',
|
| 44 |
+
use_disp_loss=False,
|
| 45 |
+
**kwargs,
|
| 46 |
+
):
|
| 47 |
+
super().__init__(**kwargs)
|
| 48 |
+
|
| 49 |
+
self.hidden_size = hidden_size
|
| 50 |
+
self.intermediate_size = intermediate_size
|
| 51 |
+
self.dropout = dropout
|
| 52 |
+
self.drop_path_rate = drop_path_rate
|
| 53 |
+
self.num_hidden_layers = num_hidden_layers
|
| 54 |
+
self.num_attention_heads = num_attention_heads
|
| 55 |
+
self.num_channels = num_channels
|
| 56 |
+
self.patch_size = patch_size
|
| 57 |
+
self.image_size = image_size
|
| 58 |
+
self.initializer_range = initializer_range
|
| 59 |
+
self.initializer_factor = initializer_factor
|
| 60 |
+
self.attention_dropout = attention_dropout
|
| 61 |
+
self.layer_norm_eps = layer_norm_eps
|
| 62 |
+
self.hidden_act = hidden_act
|
| 63 |
+
self.norm_type = norm_type
|
| 64 |
+
self.qkv_bias = qkv_bias
|
| 65 |
+
self.qk_normalization = qk_normalization
|
| 66 |
+
self.use_flash_attn = use_flash_attn
|
| 67 |
+
# enc_proj
|
| 68 |
+
self.vit_hidden_size = vit_hidden_size
|
| 69 |
+
self.llm_hidden_size = llm_hidden_size
|
| 70 |
+
self.latent_ch = latent_ch
|
| 71 |
+
self.use_disp_loss = use_disp_loss
|
| 72 |
+
# decoder
|
| 73 |
+
self.global_blocks_depth = global_blocks_depth
|
| 74 |
+
self.num_decoder_layers = num_decoder_layers
|
| 75 |
+
self.num_sampling_steps = num_sampling_steps
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@classmethod
|
| 79 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> 'PretrainedConfig':
|
| 80 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 81 |
+
|
| 82 |
+
if 'vision_config' in config_dict:
|
| 83 |
+
config_dict = config_dict['vision_config']
|
| 84 |
+
|
| 85 |
+
if 'model_type' in config_dict and hasattr(cls, 'model_type') and config_dict['model_type'] != cls.model_type:
|
| 86 |
+
logger.warning(
|
| 87 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
| 88 |
+
f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
return cls.from_dict(config_dict, **kwargs)
|
| 92 |
+
|
flash_attention.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# https://github.com/Dao-AILab/flash-attention/blob/v0.2.8/flash_attn/flash_attention.py
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from einops import rearrange
|
| 5 |
+
|
| 6 |
+
try: # v1
|
| 7 |
+
from flash_attn.flash_attn_interface import \
|
| 8 |
+
flash_attn_unpadded_qkvpacked_func
|
| 9 |
+
except: # v2
|
| 10 |
+
from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func
|
| 11 |
+
|
| 12 |
+
from flash_attn.bert_padding import pad_input, unpad_input
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class FlashAttention(nn.Module):
|
| 16 |
+
"""Implement the scaled dot product attention with softmax.
|
| 17 |
+
Arguments
|
| 18 |
+
---------
|
| 19 |
+
softmax_scale: The temperature to use for the softmax attention.
|
| 20 |
+
(default: 1/sqrt(d_keys) where d_keys is computed at
|
| 21 |
+
runtime)
|
| 22 |
+
attention_dropout: The dropout rate to apply to the attention
|
| 23 |
+
(default: 0.0)
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(self, softmax_scale=None, attention_dropout=0.0, device=None, dtype=None):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.softmax_scale = softmax_scale
|
| 29 |
+
self.dropout_p = attention_dropout
|
| 30 |
+
|
| 31 |
+
def forward(self, qkv, key_padding_mask=None, causal=False, cu_seqlens=None,
|
| 32 |
+
max_s=None, need_weights=False):
|
| 33 |
+
"""Implements the multihead softmax attention.
|
| 34 |
+
Arguments
|
| 35 |
+
---------
|
| 36 |
+
qkv: The tensor containing the query, key, and value. (B, S, 3, H, D) if key_padding_mask is None
|
| 37 |
+
if unpadded: (nnz, 3, h, d)
|
| 38 |
+
key_padding_mask: a bool tensor of shape (B, S)
|
| 39 |
+
"""
|
| 40 |
+
assert not need_weights
|
| 41 |
+
assert qkv.dtype in [torch.float16, torch.bfloat16]
|
| 42 |
+
assert qkv.is_cuda
|
| 43 |
+
|
| 44 |
+
if cu_seqlens is None:
|
| 45 |
+
batch_size = qkv.shape[0]
|
| 46 |
+
seqlen = qkv.shape[1]
|
| 47 |
+
if key_padding_mask is None:
|
| 48 |
+
qkv = rearrange(qkv, 'b s ... -> (b s) ...')
|
| 49 |
+
max_s = seqlen
|
| 50 |
+
cu_seqlens = torch.arange(0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32,
|
| 51 |
+
device=qkv.device)
|
| 52 |
+
output = flash_attn_unpadded_qkvpacked_func(
|
| 53 |
+
qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
|
| 54 |
+
softmax_scale=self.softmax_scale, causal=causal
|
| 55 |
+
)
|
| 56 |
+
output = rearrange(output, '(b s) ... -> b s ...', b=batch_size)
|
| 57 |
+
else:
|
| 58 |
+
nheads = qkv.shape[-2]
|
| 59 |
+
x = rearrange(qkv, 'b s three h d -> b s (three h d)')
|
| 60 |
+
x_unpad, indices, cu_seqlens, max_s = unpad_input(x, key_padding_mask)
|
| 61 |
+
x_unpad = rearrange(x_unpad, 'nnz (three h d) -> nnz three h d', three=3, h=nheads)
|
| 62 |
+
output_unpad = flash_attn_unpadded_qkvpacked_func(
|
| 63 |
+
x_unpad, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
|
| 64 |
+
softmax_scale=self.softmax_scale, causal=causal
|
| 65 |
+
)
|
| 66 |
+
output = rearrange(pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'),
|
| 67 |
+
indices, batch_size, seqlen),
|
| 68 |
+
'b s (h d) -> b s h d', h=nheads)
|
| 69 |
+
else:
|
| 70 |
+
assert max_s is not None
|
| 71 |
+
output = flash_attn_unpadded_qkvpacked_func(
|
| 72 |
+
qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
|
| 73 |
+
softmax_scale=self.softmax_scale, causal=causal
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
return output, None
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d4f441680be8f81ca9d9bad135219ab2e3e92a9a8c82eed60a9a3b2033e2d5e4
|
| 3 |
+
size 1810399952
|
modeling_uniflow.py
ADDED
|
@@ -0,0 +1,845 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------
|
| 2 |
+
# Copyright (c) 2025, OpenGVLab. All rights reserved.
|
| 3 |
+
# Licensed under The MIT License [see LICENSE for details]
|
| 4 |
+
# UniFlow-(InternViT)
|
| 5 |
+
# --------------------------------------------------------
|
| 6 |
+
|
| 7 |
+
import ast
|
| 8 |
+
import math
|
| 9 |
+
import os
|
| 10 |
+
from collections import OrderedDict
|
| 11 |
+
from functools import lru_cache
|
| 12 |
+
from typing import Optional, Tuple, Union
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn as nn
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
from torch.utils.checkpoint import checkpoint
|
| 17 |
+
import numpy as np
|
| 18 |
+
from einops import rearrange
|
| 19 |
+
from timm.models.layers import DropPath, trunc_normal_
|
| 20 |
+
from timm.models.registry import register_model
|
| 21 |
+
from timm.models.vision_transformer import Block
|
| 22 |
+
from transformers.activations import ACT2FN
|
| 23 |
+
from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
|
| 24 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 25 |
+
from transformers.utils import logging
|
| 26 |
+
from .configuration_uniflow import UniFlowVisionConfig
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
from flash_attention import FlashAttention
|
| 30 |
+
has_flash_attn = True
|
| 31 |
+
except:
|
| 32 |
+
print('FlashAttention is not installed.')
|
| 33 |
+
has_flash_attn = False
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
from apex.normalization import FusedRMSNorm
|
| 37 |
+
|
| 38 |
+
UniFlowRMSNorm = FusedRMSNorm # noqa
|
| 39 |
+
|
| 40 |
+
logger.info('Discovered apex.normalization.FusedRMSNorm - will use it instead of UniFlowRMSNorm')
|
| 41 |
+
except ImportError:
|
| 42 |
+
# using the normal UniFlowRMSNorm
|
| 43 |
+
pass
|
| 44 |
+
except Exception:
|
| 45 |
+
logger.warning('discovered apex but it failed to load, falling back to UniFlowRMSNorm')
|
| 46 |
+
pass
|
| 47 |
+
|
| 48 |
+
logger = logging.get_logger(__name__)
|
| 49 |
+
|
| 50 |
+
import warnings
|
| 51 |
+
warnings.filterwarnings("ignore")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
#############################################################
|
| 55 |
+
# UniFlow Modules
|
| 56 |
+
#############################################################
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def p2l_transform_tensor(x, patch_size):
|
| 60 |
+
"""
|
| 61 |
+
Transform from pixel space to latent space
|
| 62 |
+
[B, C, H, W] -> [B, * H//patch_size * W//patch_size, C*patch_size*patch_size]
|
| 63 |
+
"""
|
| 64 |
+
B, C, H, W = x.shape
|
| 65 |
+
return rearrange(
|
| 66 |
+
x,
|
| 67 |
+
"b c (h1 h2) (w1 w2) -> b (h1 w1) (c h2 w2)",
|
| 68 |
+
h1=H // patch_size,
|
| 69 |
+
h2=patch_size,
|
| 70 |
+
w1=W // patch_size,
|
| 71 |
+
w2=patch_size,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def l2p_transform_tensor(x, patch_size, img_size):
|
| 76 |
+
"""
|
| 77 |
+
Transform from latent space to pixel space
|
| 78 |
+
[B, H//patch_size * W//patch_size, C*tubelet_size*patch_size*patch_size] -> [B, C, H, W]
|
| 79 |
+
"""
|
| 80 |
+
B = x.shape[0]
|
| 81 |
+
C = x.shape[2] // (patch_size * patch_size)
|
| 82 |
+
return rearrange(
|
| 83 |
+
x,
|
| 84 |
+
"b (h1 w1) (c h2 w2) -> b c (h1 h2) (w1 w2)",
|
| 85 |
+
h1=img_size // patch_size,
|
| 86 |
+
h2=patch_size,
|
| 87 |
+
w1=img_size // patch_size,
|
| 88 |
+
w2=patch_size,
|
| 89 |
+
c=C,
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
|
| 94 |
+
assert embed_dim % 2 == 0
|
| 95 |
+
|
| 96 |
+
# use half of dimensions to encode grid_h
|
| 97 |
+
emb_h = get_1d_sincos_pos_embed_from_grid(
|
| 98 |
+
embed_dim // 2, grid[0]
|
| 99 |
+
) # (H*W, D/2)
|
| 100 |
+
emb_w = get_1d_sincos_pos_embed_from_grid(
|
| 101 |
+
embed_dim // 2, grid[1]
|
| 102 |
+
) # (H*W, D/2)
|
| 103 |
+
|
| 104 |
+
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
|
| 105 |
+
return emb
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
|
| 109 |
+
"""
|
| 110 |
+
embed_dim: output dimension for each position
|
| 111 |
+
pos: a list of positions to be encoded: size (M,)
|
| 112 |
+
out: (M, D)
|
| 113 |
+
"""
|
| 114 |
+
assert embed_dim % 2 == 0
|
| 115 |
+
omega = np.arange(embed_dim // 2, dtype=np.float32)
|
| 116 |
+
omega /= embed_dim / 2.0
|
| 117 |
+
omega = 1.0 / 10000**omega # (D/2,)
|
| 118 |
+
|
| 119 |
+
pos = pos.reshape(-1) # (M,)
|
| 120 |
+
out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
|
| 121 |
+
|
| 122 |
+
emb_sin = np.sin(out) # (M, D/2)
|
| 123 |
+
emb_cos = np.cos(out) # (M, D/2)
|
| 124 |
+
|
| 125 |
+
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
|
| 126 |
+
return emb
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
|
| 130 |
+
"""
|
| 131 |
+
grid_size: int of the grid height and width
|
| 132 |
+
return:
|
| 133 |
+
pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
|
| 134 |
+
"""
|
| 135 |
+
grid_h = np.arange(grid_size, dtype=np.float32)
|
| 136 |
+
grid_w = np.arange(grid_size, dtype=np.float32)
|
| 137 |
+
grid = np.meshgrid(grid_w, grid_h) # here w goes first
|
| 138 |
+
grid = np.stack(grid, axis=0)
|
| 139 |
+
|
| 140 |
+
grid = grid.reshape([2, 1, grid_size, grid_size])
|
| 141 |
+
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
| 142 |
+
if cls_token:
|
| 143 |
+
pos_embed = np.concatenate(
|
| 144 |
+
[np.zeros([1, embed_dim]), pos_embed], axis=0
|
| 145 |
+
)
|
| 146 |
+
return pos_embed
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class UniFlowRMSNorm(nn.Module):
|
| 150 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 151 |
+
super().__init__()
|
| 152 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 153 |
+
self.variance_epsilon = eps
|
| 154 |
+
|
| 155 |
+
def forward(self, hidden_states):
|
| 156 |
+
input_dtype = hidden_states.dtype
|
| 157 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 158 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 159 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 160 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 161 |
+
|
| 162 |
+
NORM2FN = {
|
| 163 |
+
'rms_norm': UniFlowRMSNorm,
|
| 164 |
+
'layer_norm': nn.LayerNorm,
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
class UniFlowVisionEmbeddings(nn.Module):
|
| 168 |
+
def __init__(self, config: UniFlowVisionConfig):
|
| 169 |
+
super().__init__()
|
| 170 |
+
self.config = config
|
| 171 |
+
self.embed_dim = config.hidden_size
|
| 172 |
+
self.image_size = config.image_size
|
| 173 |
+
self.patch_size = config.patch_size
|
| 174 |
+
|
| 175 |
+
self.class_embedding = nn.Parameter(
|
| 176 |
+
torch.randn(1, 1, self.embed_dim),
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
self.patch_embedding = nn.Conv2d(
|
| 180 |
+
in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
| 184 |
+
self.num_positions = self.num_patches + 1
|
| 185 |
+
|
| 186 |
+
self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
|
| 187 |
+
|
| 188 |
+
def _get_pos_embed(self, pos_embed, H, W):
|
| 189 |
+
target_dtype = pos_embed.dtype
|
| 190 |
+
pos_embed = pos_embed.float().reshape(
|
| 191 |
+
1, self.image_size // self.patch_size, self.image_size // self.patch_size, -1).permute(0, 3, 1, 2)
|
| 192 |
+
pos_embed = F.interpolate(pos_embed, size=(H, W), mode='bicubic', align_corners=False).\
|
| 193 |
+
reshape(1, -1, H * W).permute(0, 2, 1).to(target_dtype)
|
| 194 |
+
return pos_embed
|
| 195 |
+
|
| 196 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
| 197 |
+
target_dtype = self.patch_embedding.weight.dtype
|
| 198 |
+
patch_embeds = self.patch_embedding(pixel_values) # shape = [batch*temporal, channel, width, height] [batch*temporal, channel*patch*patch, width//patch, height//patch]
|
| 199 |
+
batch_size, _, height, width = patch_embeds.shape
|
| 200 |
+
patch_embeds = patch_embeds.flatten(2).transpose(1, 2) # [batch, seq_le=1024, dim]
|
| 201 |
+
class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
|
| 202 |
+
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
| 203 |
+
position_embedding = torch.cat([
|
| 204 |
+
self.position_embedding[:, :1, :],
|
| 205 |
+
self._get_pos_embed(self.position_embedding[:, 1:, :], height, width)
|
| 206 |
+
], dim=1)
|
| 207 |
+
embeddings = embeddings + position_embedding.to(target_dtype)
|
| 208 |
+
return embeddings
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
class UniFlowAttention(nn.Module):
|
| 212 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 213 |
+
|
| 214 |
+
def __init__(self, config: UniFlowVisionConfig):
|
| 215 |
+
super().__init__()
|
| 216 |
+
self.config = config
|
| 217 |
+
self.embed_dim = config.hidden_size
|
| 218 |
+
self.num_heads = config.num_attention_heads
|
| 219 |
+
self.use_flash_attn = config.use_flash_attn and has_flash_attn
|
| 220 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 221 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 222 |
+
raise ValueError(
|
| 223 |
+
f'embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:'
|
| 224 |
+
f' {self.num_heads}).'
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
self.scale = self.head_dim ** -0.5
|
| 228 |
+
self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim, bias=config.qkv_bias)
|
| 229 |
+
self.attn_drop = nn.Dropout(config.attention_dropout)
|
| 230 |
+
self.proj_drop = nn.Dropout(config.dropout)
|
| 231 |
+
|
| 232 |
+
self.qk_normalization = config.qk_normalization
|
| 233 |
+
|
| 234 |
+
if self.qk_normalization:
|
| 235 |
+
self.q_norm = UniFlowRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 236 |
+
self.k_norm = UniFlowRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 237 |
+
|
| 238 |
+
if self.use_flash_attn:
|
| 239 |
+
self.inner_attn = FlashAttention(attention_dropout=config.attention_dropout)
|
| 240 |
+
self.proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 241 |
+
|
| 242 |
+
def _naive_attn(
|
| 243 |
+
self, x,
|
| 244 |
+
attn_mask=None,
|
| 245 |
+
):
|
| 246 |
+
B, N, C = x.shape
|
| 247 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
| 248 |
+
q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
|
| 249 |
+
|
| 250 |
+
if self.qk_normalization:
|
| 251 |
+
B_, H_, N_, D_ = q.shape
|
| 252 |
+
q = self.q_norm(q.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
|
| 253 |
+
k = self.k_norm(k.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
|
| 254 |
+
|
| 255 |
+
attn_bias = torch.zeros(N, N, dtype=q.dtype, device=q.device)
|
| 256 |
+
if attn_mask is not None:
|
| 257 |
+
assert attn_mask.dtype == torch.bool
|
| 258 |
+
attn_bias.masked_fill_(attn_mask.logical_not(), float("-inf"))
|
| 259 |
+
|
| 260 |
+
attn = ((q * self.scale) @ k.transpose(-2, -1))
|
| 261 |
+
attn += attn_bias # masking
|
| 262 |
+
attn = attn.softmax(dim=-1)
|
| 263 |
+
attn = self.attn_drop(attn)
|
| 264 |
+
|
| 265 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
|
| 266 |
+
x = self.proj(x)
|
| 267 |
+
x = self.proj_drop(x)
|
| 268 |
+
return x
|
| 269 |
+
|
| 270 |
+
def _flash_attn(
|
| 271 |
+
self, x, key_padding_mask=None, need_weights=False,
|
| 272 |
+
attn_mask=None,
|
| 273 |
+
):
|
| 274 |
+
qkv = self.qkv(x)
|
| 275 |
+
qkv = rearrange(qkv, 'b s (three h d) -> b s three h d', three=3, h=self.num_heads)
|
| 276 |
+
|
| 277 |
+
if self.qk_normalization:
|
| 278 |
+
q, k, v = qkv.unbind(2)
|
| 279 |
+
q = self.q_norm(q.flatten(-2, -1)).view(q.shape)
|
| 280 |
+
k = self.k_norm(k.flatten(-2, -1)).view(k.shape)
|
| 281 |
+
qkv = torch.stack([q, k, v], dim=2)
|
| 282 |
+
|
| 283 |
+
context, _ = self.inner_attn(
|
| 284 |
+
qkv, key_padding_mask=key_padding_mask, need_weights=need_weights, causal=False,
|
| 285 |
+
)
|
| 286 |
+
outs = self.proj(rearrange(context, 'b s h d -> b s (h d)'))
|
| 287 |
+
outs = self.proj_drop(outs)
|
| 288 |
+
return outs
|
| 289 |
+
|
| 290 |
+
def forward(
|
| 291 |
+
self, hidden_states: torch.Tensor,
|
| 292 |
+
attn_mask=None,
|
| 293 |
+
) -> torch.Tensor:
|
| 294 |
+
x = self._naive_attn(hidden_states, attn_mask=attn_mask) if not self.use_flash_attn \
|
| 295 |
+
else self._flash_attn(hidden_states, attn_mask=attn_mask)
|
| 296 |
+
return x
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
class UniFlowMLP(nn.Module):
|
| 300 |
+
def __init__(self, config: UniFlowVisionConfig):
|
| 301 |
+
super().__init__()
|
| 302 |
+
self.config = config
|
| 303 |
+
self.act = ACT2FN[config.hidden_act]
|
| 304 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 305 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 306 |
+
|
| 307 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 308 |
+
hidden_states = self.fc1(hidden_states)
|
| 309 |
+
hidden_states = self.act(hidden_states)
|
| 310 |
+
hidden_states = self.fc2(hidden_states)
|
| 311 |
+
return hidden_states
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
class UniFlowVisionEncoderLayer(nn.Module):
|
| 315 |
+
def __init__(self, config: UniFlowVisionConfig, drop_path_rate: float):
|
| 316 |
+
super().__init__()
|
| 317 |
+
self.embed_dim = config.hidden_size
|
| 318 |
+
self.intermediate_size = config.intermediate_size
|
| 319 |
+
self.norm_type = config.norm_type
|
| 320 |
+
|
| 321 |
+
self.attn = UniFlowAttention(config)
|
| 322 |
+
self.mlp = UniFlowMLP(config)
|
| 323 |
+
self.norm1 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
|
| 324 |
+
self.norm2 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
|
| 325 |
+
|
| 326 |
+
self.ls1 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
|
| 327 |
+
self.ls2 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
|
| 328 |
+
self.drop_path1 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
|
| 329 |
+
self.drop_path2 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
|
| 330 |
+
|
| 331 |
+
def forward(
|
| 332 |
+
self,
|
| 333 |
+
hidden_states: torch.Tensor,
|
| 334 |
+
attn_mask=None,
|
| 335 |
+
) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor], Optional[Tuple[torch.FloatTensor]]]:
|
| 336 |
+
"""
|
| 337 |
+
Args:
|
| 338 |
+
hidden_states (`Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 339 |
+
"""
|
| 340 |
+
hidden_states = hidden_states + self.drop_path1(self.attn(self.norm1(hidden_states), attn_mask=attn_mask) * self.ls1)
|
| 341 |
+
|
| 342 |
+
hidden_states = hidden_states + self.drop_path2(self.mlp(self.norm2(hidden_states)) * self.ls2)
|
| 343 |
+
|
| 344 |
+
return hidden_states
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
class UniFlowVisionEncoder(nn.Module):
|
| 348 |
+
"""
|
| 349 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 350 |
+
[`UniFlowEncoderLayer`].
|
| 351 |
+
Args:
|
| 352 |
+
config (`UniFlowConfig`):
|
| 353 |
+
The corresponding vision configuration for the `UniFlowEncoder`.
|
| 354 |
+
"""
|
| 355 |
+
|
| 356 |
+
def __init__(self, config: UniFlowVisionConfig):
|
| 357 |
+
super().__init__()
|
| 358 |
+
self.config = config
|
| 359 |
+
# stochastic depth decay rule
|
| 360 |
+
dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)]
|
| 361 |
+
self.layers = nn.ModuleList([
|
| 362 |
+
UniFlowVisionEncoderLayer(config, dpr[idx]) for idx in range(config.num_hidden_layers)])
|
| 363 |
+
self.gradient_checkpointing = False
|
| 364 |
+
|
| 365 |
+
def forward(
|
| 366 |
+
self,
|
| 367 |
+
inputs_embeds,
|
| 368 |
+
output_hidden_states: Optional[bool] = None,
|
| 369 |
+
return_dict: Optional[bool] = None,
|
| 370 |
+
attn_mask=None,
|
| 371 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 372 |
+
r"""
|
| 373 |
+
Args:
|
| 374 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 375 |
+
Embedded representation of the inputs. Should be float, not int tokens.
|
| 376 |
+
output_hidden_states (`bool`, *optional*):
|
| 377 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 378 |
+
for more detail.
|
| 379 |
+
return_dict (`bool`, *optional*):
|
| 380 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 381 |
+
"""
|
| 382 |
+
output_hidden_states = (
|
| 383 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 384 |
+
)
|
| 385 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 386 |
+
|
| 387 |
+
encoder_states = () if output_hidden_states else None
|
| 388 |
+
hidden_states = inputs_embeds
|
| 389 |
+
|
| 390 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 391 |
+
if output_hidden_states:
|
| 392 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 393 |
+
if self.gradient_checkpointing and self.training:
|
| 394 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
| 395 |
+
encoder_layer,
|
| 396 |
+
attn_mask,
|
| 397 |
+
)
|
| 398 |
+
else:
|
| 399 |
+
layer_outputs = encoder_layer(
|
| 400 |
+
hidden_states,
|
| 401 |
+
attn_mask,
|
| 402 |
+
)
|
| 403 |
+
hidden_states = layer_outputs
|
| 404 |
+
|
| 405 |
+
if output_hidden_states:
|
| 406 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 407 |
+
|
| 408 |
+
if not return_dict:
|
| 409 |
+
return tuple(v for v in [hidden_states, encoder_states] if v is not None)
|
| 410 |
+
return BaseModelOutput(
|
| 411 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
class Distill_Adapter(nn.Module):
|
| 416 |
+
def __init__(self, in_channels=1408, out_channels=3200,
|
| 417 |
+
norm_layer=nn.LayerNorm):
|
| 418 |
+
super().__init__()
|
| 419 |
+
|
| 420 |
+
self.head = nn.Linear(in_channels, out_channels)
|
| 421 |
+
self.norm = norm_layer(out_channels)
|
| 422 |
+
|
| 423 |
+
self.apply(self._init_weights)
|
| 424 |
+
|
| 425 |
+
def _init_weights(self, m):
|
| 426 |
+
if isinstance(m, nn.Linear):
|
| 427 |
+
nn.init.xavier_uniform_(m.weight)
|
| 428 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
| 429 |
+
nn.init.constant_(m.bias, 0)
|
| 430 |
+
elif isinstance(m, nn.LayerNorm):
|
| 431 |
+
nn.init.constant_(m.bias, 0)
|
| 432 |
+
nn.init.constant_(m.weight, 1.0)
|
| 433 |
+
|
| 434 |
+
def forward(self, x):
|
| 435 |
+
x = self.norm(self.head(x))
|
| 436 |
+
return x
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
class FlowDecoder(nn.Module):
|
| 440 |
+
""" patch-wise pixel flow decoder (rectified flow) """
|
| 441 |
+
def __init__(
|
| 442 |
+
self, target_channels, z_channels, depth, width, grad_checkpointing=False, num_sampling_steps='10',
|
| 443 |
+
train_schedule='fat_lognormal', use_cfg=False, noise_concat=False, patch_size=14, img_size=224,
|
| 444 |
+
):
|
| 445 |
+
super().__init__()
|
| 446 |
+
self.patch_size = patch_size
|
| 447 |
+
self.img_size = img_size
|
| 448 |
+
|
| 449 |
+
# configs
|
| 450 |
+
self.use_cfg = use_cfg
|
| 451 |
+
self.train_schedule = train_schedule
|
| 452 |
+
self.num_sampling_steps = int(num_sampling_steps)
|
| 453 |
+
self.noise_concat = noise_concat
|
| 454 |
+
print(f"Sampling Step: {self.num_sampling_steps}")
|
| 455 |
+
|
| 456 |
+
# mlp head (latent to pixel)
|
| 457 |
+
self.in_channels = target_channels + z_channels if noise_concat else target_channels
|
| 458 |
+
self.net = SimpleMLPAdaLN(
|
| 459 |
+
in_channels=target_channels,
|
| 460 |
+
model_channels=width,
|
| 461 |
+
out_channels=target_channels,
|
| 462 |
+
z_channels=z_channels,
|
| 463 |
+
num_res_blocks=depth,
|
| 464 |
+
grad_checkpointing=grad_checkpointing
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
@torch.no_grad()
|
| 468 |
+
def forward(self, z, schedule="linear", cfg=1.0, cfg_interval=None):
|
| 469 |
+
|
| 470 |
+
b, n, c_z = z.shape
|
| 471 |
+
z = z.reshape(b*n, c_z)
|
| 472 |
+
sample_steps = self.num_sampling_steps
|
| 473 |
+
|
| 474 |
+
# get all timesteps ts and intervals Δts
|
| 475 |
+
if schedule == "linear":
|
| 476 |
+
ts = torch.arange(1, sample_steps + 1).flip(0) / sample_steps
|
| 477 |
+
dts = torch.ones_like(ts) * (1.0 / sample_steps)
|
| 478 |
+
elif schedule.startswith("pow"): # "pow_0.25"
|
| 479 |
+
p = float(schedule.split("_")[1])
|
| 480 |
+
ts = torch.arange(0, sample_steps + 1).flip(0) ** (1 / p) / sample_steps ** (
|
| 481 |
+
1 / p
|
| 482 |
+
)
|
| 483 |
+
dts = ts[:-1] - ts[1:]
|
| 484 |
+
else:
|
| 485 |
+
raise NotImplementedError
|
| 486 |
+
ts = 1 - ts
|
| 487 |
+
|
| 488 |
+
# cfg interval
|
| 489 |
+
if cfg_interval is None: # cfg_interval = "(.17,1.02)"
|
| 490 |
+
interval = None
|
| 491 |
+
else:
|
| 492 |
+
cfg_lo, cfg_hi = ast.literal_eval(cfg_interval)
|
| 493 |
+
interval = self._edm_to_flow_convention(cfg_lo), self._edm_to_flow_convention(cfg_hi)
|
| 494 |
+
|
| 495 |
+
# sampling (sample_steps) steps: noise X0 -> clean X1
|
| 496 |
+
trajs = []
|
| 497 |
+
x = torch.randn(b*n, self.in_channels).cuda() # noise start [b,n,c]
|
| 498 |
+
x = x.to(z.dtype)
|
| 499 |
+
|
| 500 |
+
null_z = z.clone() * 0.0 if cfg != 1.0 else None
|
| 501 |
+
for i, (t, dt) in enumerate((zip(ts, dts))):
|
| 502 |
+
timesteps = torch.tensor([t] * (b*n)).to(z.device)
|
| 503 |
+
|
| 504 |
+
xc = x
|
| 505 |
+
if self.noise_concat:
|
| 506 |
+
xc = torch.cat([x, z], dim=-1) # c: 192 + 768 = 960
|
| 507 |
+
vc = self.net(x=xc, t=1000*timesteps, c=z) # conditional v
|
| 508 |
+
|
| 509 |
+
# classifier free guidance
|
| 510 |
+
if null_z is not None and (interval is None or ((t.item() >= interval[0]) and (t.item() <= interval[1]))):
|
| 511 |
+
xu = x
|
| 512 |
+
if self.noise_concat:
|
| 513 |
+
xu = torch.cat([x, null_z], dim=-1) # c: 192 + 768=960
|
| 514 |
+
vu = self.net(x=xu, t=1000*timesteps, c=null_z) # unconditional v
|
| 515 |
+
vc = vu + cfg * (vc - vu)
|
| 516 |
+
|
| 517 |
+
# update x
|
| 518 |
+
x = x + dt * vc
|
| 519 |
+
trajs.append(x)
|
| 520 |
+
|
| 521 |
+
sampled_token = trajs[-1]
|
| 522 |
+
sampled_image = l2p_transform_tensor(sampled_token.reshape(b, n, self.in_channels), patch_size=self.patch_size, img_size=self.img_size)
|
| 523 |
+
return sampled_image
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def modulate(x, shift, scale):
|
| 527 |
+
return x * (1 + scale) + shift
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
class TimestepEmbedder(nn.Module):
|
| 531 |
+
"""
|
| 532 |
+
Embeds scalar timesteps into vector representations.
|
| 533 |
+
"""
|
| 534 |
+
def __init__(self, hidden_size, frequency_embedding_size=256):
|
| 535 |
+
super().__init__()
|
| 536 |
+
self.mlp = nn.Sequential(
|
| 537 |
+
nn.Linear(frequency_embedding_size, hidden_size, bias=True),
|
| 538 |
+
nn.SiLU(),
|
| 539 |
+
nn.Linear(hidden_size, hidden_size, bias=True),
|
| 540 |
+
)
|
| 541 |
+
self.frequency_embedding_size = frequency_embedding_size
|
| 542 |
+
|
| 543 |
+
@staticmethod
|
| 544 |
+
def timestep_embedding(t, dim, max_period=10000):
|
| 545 |
+
"""
|
| 546 |
+
Create sinusoidal timestep embeddings.
|
| 547 |
+
:param t: a 1-D Tensor of N indices, one per batch element.
|
| 548 |
+
These may be fractional.
|
| 549 |
+
:param dim: the dimension of the output.
|
| 550 |
+
:param max_period: controls the minimum frequency of the embeddings.
|
| 551 |
+
:return: an (N, D) Tensor of positional embeddings.
|
| 552 |
+
"""
|
| 553 |
+
# https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
|
| 554 |
+
half = dim // 2
|
| 555 |
+
freqs = torch.exp(
|
| 556 |
+
-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
|
| 557 |
+
).to(device=t.device)
|
| 558 |
+
args = t[:, None].float() * freqs[None]
|
| 559 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 560 |
+
if dim % 2:
|
| 561 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
| 562 |
+
return embedding
|
| 563 |
+
|
| 564 |
+
def forward(self, t):
|
| 565 |
+
t_freq = self.timestep_embedding(t, self.frequency_embedding_size).to(self.mlp[0].weight.dtype)
|
| 566 |
+
t_emb = self.mlp(t_freq)
|
| 567 |
+
return t_emb
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
class ResBlock(nn.Module):
|
| 571 |
+
"""
|
| 572 |
+
A residual block that can optionally change the number of channels.
|
| 573 |
+
:param channels: the number of input channels.
|
| 574 |
+
"""
|
| 575 |
+
|
| 576 |
+
def __init__(
|
| 577 |
+
self,
|
| 578 |
+
channels
|
| 579 |
+
):
|
| 580 |
+
super().__init__()
|
| 581 |
+
self.channels = channels
|
| 582 |
+
|
| 583 |
+
self.in_ln = nn.LayerNorm(channels, eps=1e-6)
|
| 584 |
+
self.mlp = nn.Sequential(
|
| 585 |
+
nn.Linear(channels, channels, bias=True),
|
| 586 |
+
nn.SiLU(),
|
| 587 |
+
nn.Linear(channels, channels, bias=True),
|
| 588 |
+
)
|
| 589 |
+
|
| 590 |
+
self.adaLN_modulation = nn.Sequential(
|
| 591 |
+
nn.SiLU(),
|
| 592 |
+
nn.Linear(channels, 3 * channels, bias=True)
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
def forward(self, x, y):
|
| 596 |
+
shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(y).chunk(3, dim=-1)
|
| 597 |
+
h = modulate(self.in_ln(x), shift_mlp, scale_mlp)
|
| 598 |
+
h = self.mlp(h)
|
| 599 |
+
return x + gate_mlp * h
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
class FinalLayer(nn.Module):
|
| 603 |
+
"""
|
| 604 |
+
The final layer adopted from DiT.
|
| 605 |
+
"""
|
| 606 |
+
def __init__(self, model_channels, out_channels):
|
| 607 |
+
super().__init__()
|
| 608 |
+
self.norm_final = nn.LayerNorm(model_channels, elementwise_affine=False, eps=1e-6)
|
| 609 |
+
self.linear = nn.Linear(model_channels, out_channels, bias=True)
|
| 610 |
+
self.adaLN_modulation = nn.Sequential(
|
| 611 |
+
nn.SiLU(),
|
| 612 |
+
nn.Linear(model_channels, 2 * model_channels, bias=True)
|
| 613 |
+
)
|
| 614 |
+
|
| 615 |
+
def forward(self, x, c):
|
| 616 |
+
shift, scale = self.adaLN_modulation(c).chunk(2, dim=-1)
|
| 617 |
+
x = modulate(self.norm_final(x), shift, scale)
|
| 618 |
+
x = self.linear(x)
|
| 619 |
+
return x
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
class SimpleMLPAdaLN(nn.Module):
|
| 623 |
+
"""
|
| 624 |
+
The MLP for Diffusion Loss.
|
| 625 |
+
:param in_channels: channels in the input Tensor.
|
| 626 |
+
:param model_channels: base channel count for the model.
|
| 627 |
+
:param out_channels: channels in the output Tensor.
|
| 628 |
+
:param z_channels: channels in the condition.
|
| 629 |
+
:param num_res_blocks: number of residual blocks per downsample.
|
| 630 |
+
"""
|
| 631 |
+
|
| 632 |
+
def __init__(
|
| 633 |
+
self,
|
| 634 |
+
in_channels,
|
| 635 |
+
model_channels,
|
| 636 |
+
out_channels,
|
| 637 |
+
z_channels,
|
| 638 |
+
num_res_blocks,
|
| 639 |
+
grad_checkpointing=False
|
| 640 |
+
):
|
| 641 |
+
super().__init__()
|
| 642 |
+
|
| 643 |
+
self.in_channels = in_channels
|
| 644 |
+
self.model_channels = model_channels
|
| 645 |
+
self.out_channels = out_channels
|
| 646 |
+
self.num_res_blocks = num_res_blocks
|
| 647 |
+
self.grad_checkpointing = grad_checkpointing
|
| 648 |
+
|
| 649 |
+
self.time_embed = TimestepEmbedder(model_channels)
|
| 650 |
+
self.cond_embed = nn.Linear(z_channels, model_channels)
|
| 651 |
+
|
| 652 |
+
self.input_proj = nn.Linear(in_channels, model_channels)
|
| 653 |
+
|
| 654 |
+
res_blocks = []
|
| 655 |
+
for i in range(num_res_blocks):
|
| 656 |
+
res_blocks.append(ResBlock(
|
| 657 |
+
model_channels,
|
| 658 |
+
))
|
| 659 |
+
|
| 660 |
+
self.res_blocks = nn.ModuleList(res_blocks)
|
| 661 |
+
self.final_layer = FinalLayer(model_channels, out_channels)
|
| 662 |
+
|
| 663 |
+
self.initialize_weights()
|
| 664 |
+
|
| 665 |
+
def initialize_weights(self):
|
| 666 |
+
def _basic_init(module):
|
| 667 |
+
if isinstance(module, nn.Linear):
|
| 668 |
+
torch.nn.init.xavier_uniform_(module.weight)
|
| 669 |
+
if module.bias is not None:
|
| 670 |
+
nn.init.constant_(module.bias, 0)
|
| 671 |
+
self.apply(_basic_init)
|
| 672 |
+
|
| 673 |
+
# Initialize timestep embedding MLP
|
| 674 |
+
nn.init.normal_(self.time_embed.mlp[0].weight, std=0.02)
|
| 675 |
+
nn.init.normal_(self.time_embed.mlp[2].weight, std=0.02)
|
| 676 |
+
|
| 677 |
+
# Zero-out adaLN modulation layers
|
| 678 |
+
for block in self.res_blocks:
|
| 679 |
+
nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
|
| 680 |
+
nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
|
| 681 |
+
|
| 682 |
+
# Zero-out output layers
|
| 683 |
+
nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
|
| 684 |
+
nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)
|
| 685 |
+
nn.init.constant_(self.final_layer.linear.weight, 0)
|
| 686 |
+
nn.init.constant_(self.final_layer.linear.bias, 0)
|
| 687 |
+
|
| 688 |
+
def forward(self, x, t, c):
|
| 689 |
+
"""
|
| 690 |
+
Apply the model to an input batch.
|
| 691 |
+
:param x: an [N x C] Tensor of inputs.
|
| 692 |
+
:param t: a 1-D batch of timesteps.
|
| 693 |
+
:param c: conditioning from AR transformer.
|
| 694 |
+
:return: an [N x C] Tensor of outputs.
|
| 695 |
+
"""
|
| 696 |
+
x = self.input_proj(x)
|
| 697 |
+
t = self.time_embed(t)
|
| 698 |
+
c = self.cond_embed(c)
|
| 699 |
+
|
| 700 |
+
y = t + c
|
| 701 |
+
|
| 702 |
+
if self.grad_checkpointing and not torch.jit.is_scripting():
|
| 703 |
+
for block in self.res_blocks:
|
| 704 |
+
x = checkpoint(block, x, y)
|
| 705 |
+
else:
|
| 706 |
+
for block in self.res_blocks:
|
| 707 |
+
x = block(x, y)
|
| 708 |
+
|
| 709 |
+
return self.final_layer(x, y)
|
| 710 |
+
|
| 711 |
+
#############################################################
|
| 712 |
+
# UniFlowVisionModel
|
| 713 |
+
#############################################################
|
| 714 |
+
|
| 715 |
+
class UniFlowVisionModel(PreTrainedModel):
|
| 716 |
+
main_input_name = 'pixel_values'
|
| 717 |
+
config_class = UniFlowVisionConfig
|
| 718 |
+
|
| 719 |
+
def __init__(self, config: UniFlowVisionConfig):
|
| 720 |
+
super().__init__(config)
|
| 721 |
+
self.config = config
|
| 722 |
+
vit_hidden_size = config.vit_hidden_size
|
| 723 |
+
llm_hidden_size = config.llm_hidden_size
|
| 724 |
+
self.use_disp_loss = config.use_disp_loss
|
| 725 |
+
|
| 726 |
+
# vit encoder
|
| 727 |
+
self.embeddings = UniFlowVisionEmbeddings(config)
|
| 728 |
+
self.encoder = UniFlowVisionEncoder(config)
|
| 729 |
+
|
| 730 |
+
# chal.proj, chal.unporj
|
| 731 |
+
self.use_chal_proj = config.use_chal_proj
|
| 732 |
+
self.latent_ch = config.latent_ch
|
| 733 |
+
if self.use_chal_proj:
|
| 734 |
+
# down project to latent_size
|
| 735 |
+
self.chal_proj = nn.Sequential(OrderedDict([
|
| 736 |
+
("c_fc", nn.Linear(vit_hidden_size, vit_hidden_size)),
|
| 737 |
+
("gelu", nn.GELU()),
|
| 738 |
+
("c_proj", nn.Linear(vit_hidden_size, self.latent_ch)),
|
| 739 |
+
]))
|
| 740 |
+
# up project to hidden_size
|
| 741 |
+
self.chal_unproj = nn.Sequential(
|
| 742 |
+
OrderedDict([
|
| 743 |
+
("c_fc", nn.Linear(self.latent_ch, vit_hidden_size)),
|
| 744 |
+
("gelu", nn.GELU()),
|
| 745 |
+
("c_proj", nn.Linear(vit_hidden_size, vit_hidden_size)),
|
| 746 |
+
]))
|
| 747 |
+
|
| 748 |
+
# global transformer blocks
|
| 749 |
+
self.global_blocks_depth = config.global_blocks_depth
|
| 750 |
+
self.global_block_pos_embed = nn.Parameter(torch.randn(1, self.embeddings.num_patches, vit_hidden_size))
|
| 751 |
+
self.global_blocks = nn.ModuleList([
|
| 752 |
+
Block(dim=vit_hidden_size, num_heads=16, mlp_ratio=4.0, qkv_bias=True, norm_layer=nn.LayerNorm) for _ in range(self.global_blocks_depth)
|
| 753 |
+
])
|
| 754 |
+
# token-level flow head
|
| 755 |
+
self.decoder_pos_embed = nn.Parameter(torch.randn(1, self.embeddings.num_patches, vit_hidden_size))
|
| 756 |
+
self.flow_head = FlowDecoder(
|
| 757 |
+
target_channels=3 * config.patch_size * config.patch_size,
|
| 758 |
+
z_channels=config.vit_hidden_size,
|
| 759 |
+
width=config.vit_hidden_size,
|
| 760 |
+
depth=config.num_decoder_layers,
|
| 761 |
+
num_sampling_steps=config.num_sampling_steps,
|
| 762 |
+
grad_checkpointing=False,
|
| 763 |
+
patch_size=config.patch_size,
|
| 764 |
+
img_size=config.image_size,
|
| 765 |
+
use_cfg=config.use_cfg,
|
| 766 |
+
)
|
| 767 |
+
|
| 768 |
+
# init params
|
| 769 |
+
logger.info("Init pos_embed from sincos pos_embed")
|
| 770 |
+
pos_embed_spatial = get_2d_sincos_pos_embed(
|
| 771 |
+
self.decoder_pos_embed.shape[-1],
|
| 772 |
+
int(self.embeddings.num_patches**0.5), # height or weight
|
| 773 |
+
)
|
| 774 |
+
self.decoder_pos_embed.data.copy_(torch.from_numpy(pos_embed_spatial).float())
|
| 775 |
+
self.global_block_pos_embed.data.copy_(torch.from_numpy(pos_embed_spatial).float())
|
| 776 |
+
self.apply(self._init_weights)
|
| 777 |
+
|
| 778 |
+
def _init_weights(self, m):
|
| 779 |
+
if isinstance(m, nn.Linear):
|
| 780 |
+
trunc_normal_(m.weight, std=.02)
|
| 781 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
| 782 |
+
nn.init.constant_(m.bias, 0)
|
| 783 |
+
elif isinstance(m, nn.LayerNorm):
|
| 784 |
+
if m.bias is not None:
|
| 785 |
+
nn.init.constant_(m.bias, 0)
|
| 786 |
+
if m.weight is not None:
|
| 787 |
+
nn.init.constant_(m.weight, 1.0)
|
| 788 |
+
|
| 789 |
+
def no_weight_decay(self):
|
| 790 |
+
return {}
|
| 791 |
+
|
| 792 |
+
def resize_pos_embeddings(self, old_size, new_size, patch_size):
|
| 793 |
+
pos_emb = self.embeddings.position_embedding
|
| 794 |
+
_, num_positions, embed_dim = pos_emb.shape
|
| 795 |
+
cls_emb = pos_emb[:, :1, :]
|
| 796 |
+
pos_emb = pos_emb[:, 1:, :].reshape(1, old_size // patch_size, old_size // patch_size, -1).permute(0, 3, 1, 2)
|
| 797 |
+
pos_emb = F.interpolate(pos_emb.float(), size=new_size // patch_size, mode='bicubic', align_corners=False)
|
| 798 |
+
pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim, -1).permute(0, 2, 1)
|
| 799 |
+
pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
|
| 800 |
+
self.embeddings.position_embedding = nn.Parameter(pos_emb)
|
| 801 |
+
self.embeddings.image_size = new_size
|
| 802 |
+
logger.info('Resized position embeddings from {} to {}'.format(old_size, new_size))
|
| 803 |
+
|
| 804 |
+
def get_input_embeddings(self):
|
| 805 |
+
return self.embeddings
|
| 806 |
+
|
| 807 |
+
def disp_loss(self, z):
|
| 808 |
+
# Dispersive Loss implementation (InfoNCE-L2 variant)
|
| 809 |
+
z = z.reshape((z.shape[0],-1)) # [B,L,C] flatten to [B,C]
|
| 810 |
+
diff = torch.nn.functional.pdist(z).pow(2)/z.shape[1] # pairwise distance
|
| 811 |
+
diff = torch.concat((diff, diff, torch.zeros(z.shape[0]).cuda())) # match JAX implementation of full BxB matrix
|
| 812 |
+
return torch.log(torch.exp(-diff).mean()) # calculate loss
|
| 813 |
+
|
| 814 |
+
def forward(self, pixel_values):
|
| 815 |
+
|
| 816 |
+
if len(pixel_values.shape) == 4:
|
| 817 |
+
# [B,C,H,W] -> [B,N,C]
|
| 818 |
+
hidden_states = self.embeddings(pixel_values)
|
| 819 |
+
B, N, C = hidden_states.shape
|
| 820 |
+
else:
|
| 821 |
+
raise ValueError(f'wrong pixel_values size: {pixel_values.shape}')
|
| 822 |
+
|
| 823 |
+
encoder_outputs = self.encoder(
|
| 824 |
+
inputs_embeds=hidden_states,
|
| 825 |
+
output_hidden_states=True,
|
| 826 |
+
)
|
| 827 |
+
last_hidden_state = encoder_outputs.last_hidden_state[:, 1:, :] # drop cls token
|
| 828 |
+
|
| 829 |
+
if self.use_chal_proj:
|
| 830 |
+
latent_tokens = self.chal_proj(last_hidden_state)
|
| 831 |
+
condition_tokens = self.chal_unproj(latent_tokens)
|
| 832 |
+
|
| 833 |
+
_, N, _ = condition_tokens.shape
|
| 834 |
+
global_block_pos_embed = self.global_block_pos_embed.repeat(B, 1, 1).view(B, -1, C)
|
| 835 |
+
condition_tokens = condition_tokens + global_block_pos_embed[:,:N]
|
| 836 |
+
for block in self.global_blocks:
|
| 837 |
+
condition_tokens = block(condition_tokens)
|
| 838 |
+
|
| 839 |
+
decoder_pos_embed = self.decoder_pos_embed.repeat(B, 1, 1).view(B, -1, C)
|
| 840 |
+
condition_tokens = condition_tokens + decoder_pos_embed[:,:N]
|
| 841 |
+
# [B, N, C] -> [B, C, H, W]
|
| 842 |
+
reconstructed_image = self.flow_head(z=condition_tokens)
|
| 843 |
+
return reconstructed_image
|
| 844 |
+
|
| 845 |
+
|
preprocessor_config.json
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"crop_size": 448,
|
| 3 |
+
"do_center_crop": true,
|
| 4 |
+
"do_normalize": true,
|
| 5 |
+
"do_resize": true,
|
| 6 |
+
"feature_extractor_type": "CLIPFeatureExtractor",
|
| 7 |
+
"image_mean": [
|
| 8 |
+
0.485,
|
| 9 |
+
0.456,
|
| 10 |
+
0.406
|
| 11 |
+
],
|
| 12 |
+
"image_std": [
|
| 13 |
+
0.229,
|
| 14 |
+
0.224,
|
| 15 |
+
0.225
|
| 16 |
+
],
|
| 17 |
+
"resample": 3,
|
| 18 |
+
"size": 448
|
| 19 |
+
}
|