Upload folder using huggingface_hub
Browse files- config.json +113 -0
- config.py +48 -0
- finevit.py +448 -0
- model.safetensors +3 -0
- preprocessor_config.json +27 -0
config.json
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"FineViTModel"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "config.FineViTConfig",
|
| 7 |
+
"AutoModel": "finevit.FineViTModel"
|
| 8 |
+
},
|
| 9 |
+
"backbone_config": {
|
| 10 |
+
"_name_or_path": "facebook/dinov2-with-registers-base",
|
| 11 |
+
"add_cross_attention": false,
|
| 12 |
+
"apply_layernorm": true,
|
| 13 |
+
"architectures": [
|
| 14 |
+
"Dinov2WithRegistersModel"
|
| 15 |
+
],
|
| 16 |
+
"attention_probs_dropout_prob": 0.0,
|
| 17 |
+
"bos_token_id": null,
|
| 18 |
+
"chunk_size_feed_forward": 0,
|
| 19 |
+
"cross_attention_hidden_size": null,
|
| 20 |
+
"decoder_start_token_id": null,
|
| 21 |
+
"drop_path_rate": 0.0,
|
| 22 |
+
"dtype": "float32",
|
| 23 |
+
"eos_token_id": null,
|
| 24 |
+
"finetuning_task": null,
|
| 25 |
+
"hidden_act": "gelu",
|
| 26 |
+
"hidden_dropout_prob": 0.0,
|
| 27 |
+
"hidden_size": 768,
|
| 28 |
+
"id2label": {
|
| 29 |
+
"0": "LABEL_0",
|
| 30 |
+
"1": "LABEL_1"
|
| 31 |
+
},
|
| 32 |
+
"image_size": 518,
|
| 33 |
+
"initializer_range": 0.02,
|
| 34 |
+
"interpolate_antialias": true,
|
| 35 |
+
"interpolate_offset": 0.0,
|
| 36 |
+
"is_decoder": false,
|
| 37 |
+
"is_encoder_decoder": false,
|
| 38 |
+
"label2id": {
|
| 39 |
+
"LABEL_0": 0,
|
| 40 |
+
"LABEL_1": 1
|
| 41 |
+
},
|
| 42 |
+
"layer_norm_eps": 1e-06,
|
| 43 |
+
"layerscale_value": 1.0,
|
| 44 |
+
"mlp_ratio": 4,
|
| 45 |
+
"model_type": "dinov2_with_registers",
|
| 46 |
+
"num_attention_heads": 12,
|
| 47 |
+
"num_channels": 3,
|
| 48 |
+
"num_hidden_layers": 12,
|
| 49 |
+
"num_register_tokens": 4,
|
| 50 |
+
"out_features": [
|
| 51 |
+
"stage12"
|
| 52 |
+
],
|
| 53 |
+
"out_indices": [
|
| 54 |
+
12
|
| 55 |
+
],
|
| 56 |
+
"output_attentions": false,
|
| 57 |
+
"output_hidden_states": false,
|
| 58 |
+
"pad_token_id": null,
|
| 59 |
+
"patch_size": 14,
|
| 60 |
+
"prefix": null,
|
| 61 |
+
"problem_type": null,
|
| 62 |
+
"pruned_heads": {},
|
| 63 |
+
"qkv_bias": true,
|
| 64 |
+
"reshape_hidden_states": true,
|
| 65 |
+
"return_dict": true,
|
| 66 |
+
"sep_token_id": null,
|
| 67 |
+
"stage_names": [
|
| 68 |
+
"stem",
|
| 69 |
+
"stage1",
|
| 70 |
+
"stage2",
|
| 71 |
+
"stage3",
|
| 72 |
+
"stage4",
|
| 73 |
+
"stage5",
|
| 74 |
+
"stage6",
|
| 75 |
+
"stage7",
|
| 76 |
+
"stage8",
|
| 77 |
+
"stage9",
|
| 78 |
+
"stage10",
|
| 79 |
+
"stage11",
|
| 80 |
+
"stage12"
|
| 81 |
+
],
|
| 82 |
+
"task_specific_params": null,
|
| 83 |
+
"tf_legacy_loss": false,
|
| 84 |
+
"tie_encoder_decoder": false,
|
| 85 |
+
"tie_word_embeddings": true,
|
| 86 |
+
"tokenizer_class": null,
|
| 87 |
+
"torchscript": false,
|
| 88 |
+
"transformers_version": "5.8.0",
|
| 89 |
+
"use_bfloat16": false,
|
| 90 |
+
"use_swiglu_ffn": false
|
| 91 |
+
},
|
| 92 |
+
"backbone_model_name": "facebook/dinov2-with-registers-base",
|
| 93 |
+
"checkpoint_epoch": 2,
|
| 94 |
+
"checkpoint_step": 50000,
|
| 95 |
+
"dropout": 0.0,
|
| 96 |
+
"dtype": "bfloat16",
|
| 97 |
+
"image_size": 224,
|
| 98 |
+
"init_backbone_from_pretrained": false,
|
| 99 |
+
"initializer_range": 0.02,
|
| 100 |
+
"latent_encoder_head_dim": 64,
|
| 101 |
+
"latent_encoder_mlp_hidden_dim": 3072,
|
| 102 |
+
"latent_encoder_num_attention_heads": 12,
|
| 103 |
+
"latent_encoder_num_layers": 12,
|
| 104 |
+
"model_type": "finevit",
|
| 105 |
+
"num_latents": 64,
|
| 106 |
+
"patch_decoder_head_dim": 64,
|
| 107 |
+
"patch_decoder_mlp_hidden_dim": 3072,
|
| 108 |
+
"patch_decoder_num_attention_heads": 12,
|
| 109 |
+
"patch_decoder_num_layers": 8,
|
| 110 |
+
"teacher_encoder_type": "dinov2_with_registers",
|
| 111 |
+
"train_encoder": true,
|
| 112 |
+
"transformers_version": "5.8.0"
|
| 113 |
+
}
|
config.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class FineViTConfig(PretrainedConfig):
|
| 5 |
+
model_type = "finevit"
|
| 6 |
+
|
| 7 |
+
def __init__(
|
| 8 |
+
self,
|
| 9 |
+
backbone_model_name: str = "facebook/dinov2-with-registers-base",
|
| 10 |
+
teacher_encoder_type: str = "dinov2_with_registers",
|
| 11 |
+
backbone_config: dict | None = None,
|
| 12 |
+
num_latents: int = 64,
|
| 13 |
+
latent_encoder_num_layers: int = 12,
|
| 14 |
+
latent_encoder_head_dim: int = 64,
|
| 15 |
+
latent_encoder_num_attention_heads: int = 12,
|
| 16 |
+
latent_encoder_mlp_hidden_dim: int = 3072,
|
| 17 |
+
patch_decoder_num_layers: int = 8,
|
| 18 |
+
patch_decoder_head_dim: int = 64,
|
| 19 |
+
patch_decoder_num_attention_heads: int = 12,
|
| 20 |
+
patch_decoder_mlp_hidden_dim: int = 3072,
|
| 21 |
+
dropout: float = 0.0,
|
| 22 |
+
image_size: int = 224,
|
| 23 |
+
train_encoder: bool = False,
|
| 24 |
+
init_backbone_from_pretrained: bool = True,
|
| 25 |
+
initializer_range: float = 0.02,
|
| 26 |
+
**kwargs,
|
| 27 |
+
):
|
| 28 |
+
super().__init__(**kwargs)
|
| 29 |
+
self.backbone_model_name = backbone_model_name
|
| 30 |
+
self.teacher_encoder_type = teacher_encoder_type
|
| 31 |
+
self.backbone_config = backbone_config
|
| 32 |
+
self.num_latents = num_latents
|
| 33 |
+
self.latent_encoder_num_layers = latent_encoder_num_layers
|
| 34 |
+
self.latent_encoder_head_dim = latent_encoder_head_dim
|
| 35 |
+
self.latent_encoder_num_attention_heads = latent_encoder_num_attention_heads
|
| 36 |
+
self.latent_encoder_mlp_hidden_dim = latent_encoder_mlp_hidden_dim
|
| 37 |
+
self.patch_decoder_num_layers = patch_decoder_num_layers
|
| 38 |
+
self.patch_decoder_head_dim = patch_decoder_head_dim
|
| 39 |
+
self.patch_decoder_num_attention_heads = patch_decoder_num_attention_heads
|
| 40 |
+
self.patch_decoder_mlp_hidden_dim = patch_decoder_mlp_hidden_dim
|
| 41 |
+
self.dropout = dropout
|
| 42 |
+
self.image_size = image_size
|
| 43 |
+
self.train_encoder = train_encoder
|
| 44 |
+
self.init_backbone_from_pretrained = init_backbone_from_pretrained
|
| 45 |
+
self.initializer_range = initializer_range
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
FineViTConfig.register_for_auto_class("AutoConfig")
|
finevit.py
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from transformers import AutoConfig, AutoModel, PreTrainedModel
|
| 9 |
+
from transformers.utils import ModelOutput
|
| 10 |
+
|
| 11 |
+
from finevit.models.config import FineViTConfig
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class GatedMLP(nn.Module):
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
input_dim: int,
|
| 18 |
+
hidden_dim: int,
|
| 19 |
+
output_dim: int,
|
| 20 |
+
bias: bool = True,
|
| 21 |
+
):
|
| 22 |
+
super().__init__()
|
| 23 |
+
self.fc_in = nn.Linear(input_dim, 2 * hidden_dim, bias=bias)
|
| 24 |
+
self.fc_out = nn.Linear(hidden_dim, output_dim, bias=bias)
|
| 25 |
+
|
| 26 |
+
def forward(self, x):
|
| 27 |
+
gate, value = self.fc_in(x).chunk(2, dim=-1)
|
| 28 |
+
return self.fc_out(F.silu(gate) * value)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class FourierPositionEncoder(nn.Module):
|
| 32 |
+
def __init__(self, feat_dim: int, hidden_size: int) -> None:
|
| 33 |
+
super().__init__()
|
| 34 |
+
if feat_dim <= 0 or feat_dim % 2 != 0:
|
| 35 |
+
raise ValueError("feat_dim must be a positive even integer.")
|
| 36 |
+
self.embed = nn.Linear(2, feat_dim // 2, bias=False)
|
| 37 |
+
self.proj = nn.Linear(feat_dim, hidden_size, bias=False)
|
| 38 |
+
self.mlp = GatedMLP(hidden_size, hidden_size * 4, hidden_size)
|
| 39 |
+
|
| 40 |
+
def forward(self, coordinates: torch.Tensor) -> torch.Tensor:
|
| 41 |
+
features = 2 * math.pi * self.embed(coordinates)
|
| 42 |
+
features = torch.cat([features.cos(), features.sin()], dim=-1)
|
| 43 |
+
hidden_states = self.proj(features)
|
| 44 |
+
return hidden_states + self.mlp(hidden_states)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class Attention(nn.Module):
|
| 48 |
+
def __init__(
|
| 49 |
+
self,
|
| 50 |
+
hidden_size: int,
|
| 51 |
+
head_dim: int,
|
| 52 |
+
num_attention_heads: int,
|
| 53 |
+
dropout: float = 0.0,
|
| 54 |
+
):
|
| 55 |
+
super().__init__()
|
| 56 |
+
self.head_dim = head_dim
|
| 57 |
+
self.num_attention_heads = num_attention_heads
|
| 58 |
+
self.dropout = dropout
|
| 59 |
+
self.q_norm = nn.RMSNorm(head_dim, eps=1e-6)
|
| 60 |
+
self.k_norm = nn.RMSNorm(head_dim, eps=1e-6)
|
| 61 |
+
self.to_qkv = nn.Linear(
|
| 62 |
+
hidden_size, 3 * head_dim * num_attention_heads, bias=False
|
| 63 |
+
)
|
| 64 |
+
self.to_out = nn.Linear(head_dim * num_attention_heads, hidden_size, bias=False)
|
| 65 |
+
|
| 66 |
+
def forward(self, hidden_states: torch.Tensor):
|
| 67 |
+
batch, seq, _ = hidden_states.shape
|
| 68 |
+
qkv = self.to_qkv(hidden_states).view(
|
| 69 |
+
batch, seq, 3, self.num_attention_heads, self.head_dim
|
| 70 |
+
)
|
| 71 |
+
q, k, v = qkv.permute(0, 2, 3, 1, 4).contiguous().unbind(dim=1)
|
| 72 |
+
attn = (
|
| 73 |
+
F.scaled_dot_product_attention(
|
| 74 |
+
self.q_norm(q),
|
| 75 |
+
self.k_norm(k),
|
| 76 |
+
v,
|
| 77 |
+
dropout_p=self.dropout if self.training else 0.0,
|
| 78 |
+
)
|
| 79 |
+
.transpose(1, 2)
|
| 80 |
+
.contiguous()
|
| 81 |
+
.view(batch, seq, -1)
|
| 82 |
+
)
|
| 83 |
+
return self.to_out(attn)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class CrossAttention(nn.Module):
|
| 87 |
+
def __init__(
|
| 88 |
+
self,
|
| 89 |
+
hidden_size: int,
|
| 90 |
+
head_dim: int,
|
| 91 |
+
num_attention_heads: int,
|
| 92 |
+
dropout: float = 0.0,
|
| 93 |
+
):
|
| 94 |
+
super().__init__()
|
| 95 |
+
self.head_dim = head_dim
|
| 96 |
+
self.num_attention_heads = num_attention_heads
|
| 97 |
+
self.dropout = dropout
|
| 98 |
+
inner_dim = head_dim * num_attention_heads
|
| 99 |
+
self.q_norm = nn.RMSNorm(head_dim, eps=1e-6)
|
| 100 |
+
self.k_norm = nn.RMSNorm(head_dim, eps=1e-6)
|
| 101 |
+
self.to_q = nn.Linear(hidden_size, inner_dim, bias=False)
|
| 102 |
+
self.to_kv = nn.Linear(hidden_size, 2 * inner_dim, bias=False)
|
| 103 |
+
self.to_out = nn.Linear(inner_dim, hidden_size, bias=False)
|
| 104 |
+
|
| 105 |
+
def forward(
|
| 106 |
+
self,
|
| 107 |
+
query_states: torch.Tensor,
|
| 108 |
+
kv_states: torch.Tensor,
|
| 109 |
+
return_weights: bool = False,
|
| 110 |
+
):
|
| 111 |
+
batch, q_seq, _ = query_states.shape
|
| 112 |
+
kv_seq = kv_states.shape[1]
|
| 113 |
+
q = (
|
| 114 |
+
self.to_q(query_states)
|
| 115 |
+
.view(batch, q_seq, self.num_attention_heads, self.head_dim)
|
| 116 |
+
.transpose(1, 2)
|
| 117 |
+
.contiguous()
|
| 118 |
+
)
|
| 119 |
+
kv = self.to_kv(kv_states).view(
|
| 120 |
+
batch, kv_seq, 2, self.num_attention_heads, self.head_dim
|
| 121 |
+
)
|
| 122 |
+
k, v = kv.permute(2, 0, 3, 1, 4).contiguous().unbind(dim=0)
|
| 123 |
+
q = self.q_norm(q)
|
| 124 |
+
k = self.k_norm(k)
|
| 125 |
+
|
| 126 |
+
if return_weights:
|
| 127 |
+
scale = q.shape[-1] ** -0.5
|
| 128 |
+
scores = (q * scale) @ k.transpose(-2, -1)
|
| 129 |
+
weights = scores.softmax(dim=-1)
|
| 130 |
+
if self.training and self.dropout > 0.0:
|
| 131 |
+
attn = F.dropout(weights, p=self.dropout) @ v
|
| 132 |
+
else:
|
| 133 |
+
attn = weights @ v
|
| 134 |
+
else:
|
| 135 |
+
attn = F.scaled_dot_product_attention(
|
| 136 |
+
q, k, v, dropout_p=self.dropout if self.training else 0.0
|
| 137 |
+
)
|
| 138 |
+
weights = None
|
| 139 |
+
|
| 140 |
+
attn = attn.transpose(1, 2).contiguous().view(batch, q_seq, -1)
|
| 141 |
+
out = self.to_out(attn)
|
| 142 |
+
return (out, weights) if return_weights else out
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class TransformerBlock(nn.Module):
|
| 146 |
+
def __init__(
|
| 147 |
+
self,
|
| 148 |
+
hidden_size: int,
|
| 149 |
+
head_dim: int,
|
| 150 |
+
num_attention_heads: int,
|
| 151 |
+
mlp_hidden_dim: int,
|
| 152 |
+
dropout: float = 0.0,
|
| 153 |
+
):
|
| 154 |
+
super().__init__()
|
| 155 |
+
self.attn_norm = nn.LayerNorm(hidden_size)
|
| 156 |
+
self.attention = Attention(hidden_size, head_dim, num_attention_heads, dropout)
|
| 157 |
+
self.mlp_norm = nn.LayerNorm(hidden_size)
|
| 158 |
+
self.mlp = GatedMLP(hidden_size, mlp_hidden_dim, hidden_size)
|
| 159 |
+
|
| 160 |
+
def forward(self, hidden_states: torch.Tensor):
|
| 161 |
+
hidden_states = hidden_states + self.attention(self.attn_norm(hidden_states))
|
| 162 |
+
hidden_states = hidden_states + self.mlp(self.mlp_norm(hidden_states))
|
| 163 |
+
return hidden_states
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class CrossAttentionBlock(nn.Module):
|
| 167 |
+
def __init__(
|
| 168 |
+
self,
|
| 169 |
+
hidden_size: int,
|
| 170 |
+
head_dim: int,
|
| 171 |
+
num_attention_heads: int,
|
| 172 |
+
mlp_hidden_dim: int,
|
| 173 |
+
fused_kv: bool = False,
|
| 174 |
+
dropout: float = 0.0,
|
| 175 |
+
):
|
| 176 |
+
super().__init__()
|
| 177 |
+
self.fused_kv = fused_kv
|
| 178 |
+
self.q_norm = nn.LayerNorm(hidden_size)
|
| 179 |
+
self.kv_norm = nn.LayerNorm(hidden_size)
|
| 180 |
+
self.attention = CrossAttention(
|
| 181 |
+
hidden_size, head_dim, num_attention_heads, dropout
|
| 182 |
+
)
|
| 183 |
+
self.mlp_norm = nn.LayerNorm(hidden_size)
|
| 184 |
+
self.mlp = GatedMLP(hidden_size, mlp_hidden_dim, hidden_size)
|
| 185 |
+
|
| 186 |
+
def forward(
|
| 187 |
+
self,
|
| 188 |
+
query_states: torch.Tensor,
|
| 189 |
+
kv_states: torch.Tensor,
|
| 190 |
+
return_weights: bool = False,
|
| 191 |
+
):
|
| 192 |
+
kv_input = (
|
| 193 |
+
torch.cat([query_states, kv_states], dim=1) if self.fused_kv else kv_states
|
| 194 |
+
)
|
| 195 |
+
attn_out = self.attention(
|
| 196 |
+
self.q_norm(query_states),
|
| 197 |
+
self.kv_norm(kv_input),
|
| 198 |
+
return_weights=return_weights,
|
| 199 |
+
)
|
| 200 |
+
if return_weights:
|
| 201 |
+
attn_out, weights = attn_out
|
| 202 |
+
query_states = query_states + attn_out
|
| 203 |
+
query_states = query_states + self.mlp(self.mlp_norm(query_states))
|
| 204 |
+
return (query_states, weights) if return_weights else query_states
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def _run_layer(layer, *inputs, training: bool):
|
| 208 |
+
if training:
|
| 209 |
+
return torch.utils.checkpoint.checkpoint(layer, *inputs, use_reentrant=False)
|
| 210 |
+
return layer(*inputs)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class LatentEncoder(nn.Module):
|
| 214 |
+
def __init__(
|
| 215 |
+
self,
|
| 216 |
+
num_latents: int,
|
| 217 |
+
num_layers: int,
|
| 218 |
+
hidden_size: int,
|
| 219 |
+
head_dim: int,
|
| 220 |
+
num_attention_heads: int,
|
| 221 |
+
mlp_hidden_dim: int,
|
| 222 |
+
dropout: float = 0.0,
|
| 223 |
+
):
|
| 224 |
+
super().__init__()
|
| 225 |
+
self.latent_tokens = nn.Parameter(torch.zeros(num_latents, hidden_size))
|
| 226 |
+
self.pos_embed = nn.Parameter(torch.zeros(num_latents, hidden_size))
|
| 227 |
+
nn.init.trunc_normal_(self.latent_tokens, std=0.02)
|
| 228 |
+
nn.init.trunc_normal_(self.pos_embed, std=0.02)
|
| 229 |
+
self.cross_block = CrossAttentionBlock(
|
| 230 |
+
hidden_size,
|
| 231 |
+
head_dim,
|
| 232 |
+
num_attention_heads,
|
| 233 |
+
mlp_hidden_dim,
|
| 234 |
+
fused_kv=False,
|
| 235 |
+
dropout=dropout,
|
| 236 |
+
)
|
| 237 |
+
self.layers = nn.ModuleList(
|
| 238 |
+
[
|
| 239 |
+
TransformerBlock(
|
| 240 |
+
hidden_size, head_dim, num_attention_heads, mlp_hidden_dim, dropout
|
| 241 |
+
)
|
| 242 |
+
for _ in range(num_layers)
|
| 243 |
+
]
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
def forward(self, patch_tokens: torch.Tensor, return_weights: bool = False):
|
| 247 |
+
batch = patch_tokens.shape[0]
|
| 248 |
+
latents = self.latent_tokens.expand(batch, -1, -1)
|
| 249 |
+
out = self.cross_block(latents, patch_tokens, return_weights=return_weights)
|
| 250 |
+
if return_weights:
|
| 251 |
+
latents, weights = out
|
| 252 |
+
else:
|
| 253 |
+
latents, weights = out, None
|
| 254 |
+
latents = latents + self.pos_embed
|
| 255 |
+
for layer in self.layers:
|
| 256 |
+
latents = _run_layer(layer, latents, training=self.training)
|
| 257 |
+
return (latents, weights) if return_weights else latents
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class PatchDecoder(nn.Module):
|
| 261 |
+
def __init__(
|
| 262 |
+
self,
|
| 263 |
+
num_layers: int,
|
| 264 |
+
hidden_size: int,
|
| 265 |
+
head_dim: int,
|
| 266 |
+
num_attention_heads: int,
|
| 267 |
+
mlp_hidden_dim: int,
|
| 268 |
+
pos_feat_dim: int,
|
| 269 |
+
dropout: float = 0.0,
|
| 270 |
+
):
|
| 271 |
+
super().__init__()
|
| 272 |
+
self.position_encoder = FourierPositionEncoder(pos_feat_dim, hidden_size)
|
| 273 |
+
self.layers = nn.ModuleList(
|
| 274 |
+
[
|
| 275 |
+
CrossAttentionBlock(
|
| 276 |
+
hidden_size,
|
| 277 |
+
head_dim,
|
| 278 |
+
num_attention_heads,
|
| 279 |
+
mlp_hidden_dim,
|
| 280 |
+
fused_kv=True,
|
| 281 |
+
dropout=dropout,
|
| 282 |
+
)
|
| 283 |
+
for _ in range(num_layers)
|
| 284 |
+
]
|
| 285 |
+
)
|
| 286 |
+
self.out_norm = nn.LayerNorm(hidden_size, elementwise_affine=False)
|
| 287 |
+
|
| 288 |
+
def _coordinates(
|
| 289 |
+
self, seq_length: int, device: torch.device, dtype: torch.dtype
|
| 290 |
+
) -> torch.Tensor:
|
| 291 |
+
side = math.isqrt(seq_length)
|
| 292 |
+
if side * side != seq_length:
|
| 293 |
+
raise ValueError(
|
| 294 |
+
f"PatchDecoder expects a square patch sequence, got length {seq_length}"
|
| 295 |
+
)
|
| 296 |
+
positions = torch.linspace(-1.0, 1.0, side, device=device, dtype=dtype)
|
| 297 |
+
y, x = torch.meshgrid(positions, positions, indexing="ij")
|
| 298 |
+
return torch.stack([x, y], dim=-1).view(1, seq_length, 2)
|
| 299 |
+
|
| 300 |
+
def forward(self, latents: torch.Tensor, target_seq_length: int) -> torch.Tensor:
|
| 301 |
+
coordinates = self._coordinates(
|
| 302 |
+
target_seq_length, latents.device, latents.dtype
|
| 303 |
+
)
|
| 304 |
+
hidden_states = self.position_encoder(coordinates).expand(
|
| 305 |
+
latents.shape[0], -1, -1
|
| 306 |
+
)
|
| 307 |
+
for layer in self.layers:
|
| 308 |
+
hidden_states = _run_layer(
|
| 309 |
+
layer, hidden_states, latents, training=self.training
|
| 310 |
+
)
|
| 311 |
+
return self.out_norm(hidden_states)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
@dataclass
|
| 315 |
+
class FineViTModelOutput(ModelOutput):
|
| 316 |
+
decoded_patches: Optional[torch.FloatTensor] = None
|
| 317 |
+
latents: Optional[torch.FloatTensor] = None
|
| 318 |
+
latent_attention_weights: Optional[torch.FloatTensor] = None
|
| 319 |
+
cls_register_hidden_states: Optional[torch.FloatTensor] = None
|
| 320 |
+
patch_tokens: Optional[torch.FloatTensor] = None
|
| 321 |
+
uncertainty: Optional[torch.FloatTensor] = None
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class FineViTModel(PreTrainedModel):
|
| 325 |
+
config_class = FineViTConfig
|
| 326 |
+
main_input_name = "pixel_values"
|
| 327 |
+
|
| 328 |
+
def __init__(self, config: FineViTConfig):
|
| 329 |
+
super().__init__(config)
|
| 330 |
+
self.encoder = self._build_encoder(config)
|
| 331 |
+
if hasattr(self.encoder, "embeddings"):
|
| 332 |
+
self.encoder.embeddings.mask_token = None
|
| 333 |
+
self.num_register_tokens = int(
|
| 334 |
+
getattr(self.encoder.config, "num_register_tokens", 0)
|
| 335 |
+
)
|
| 336 |
+
hidden_size = int(self.encoder.config.hidden_size)
|
| 337 |
+
|
| 338 |
+
self.uncertainty_head = GatedMLP(hidden_size, hidden_size * 3, 1)
|
| 339 |
+
|
| 340 |
+
self.latent_encoder = LatentEncoder(
|
| 341 |
+
num_latents=config.num_latents,
|
| 342 |
+
num_layers=config.latent_encoder_num_layers,
|
| 343 |
+
hidden_size=hidden_size,
|
| 344 |
+
head_dim=config.latent_encoder_head_dim,
|
| 345 |
+
num_attention_heads=config.latent_encoder_num_attention_heads,
|
| 346 |
+
mlp_hidden_dim=config.latent_encoder_mlp_hidden_dim,
|
| 347 |
+
dropout=config.dropout,
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
self.patch_decoder = PatchDecoder(
|
| 351 |
+
num_layers=config.patch_decoder_num_layers,
|
| 352 |
+
hidden_size=hidden_size,
|
| 353 |
+
head_dim=config.patch_decoder_head_dim,
|
| 354 |
+
num_attention_heads=config.patch_decoder_num_attention_heads,
|
| 355 |
+
mlp_hidden_dim=config.patch_decoder_mlp_hidden_dim,
|
| 356 |
+
pos_feat_dim=hidden_size,
|
| 357 |
+
dropout=config.dropout,
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
self.post_init()
|
| 361 |
+
|
| 362 |
+
def _build_encoder(self, config: FineViTConfig):
|
| 363 |
+
if getattr(config, "init_backbone_from_pretrained", True):
|
| 364 |
+
return AutoModel.from_pretrained(config.backbone_model_name)
|
| 365 |
+
if config.backbone_config is not None:
|
| 366 |
+
backbone_config_dict = dict(config.backbone_config)
|
| 367 |
+
model_type = backbone_config_dict.pop("model_type", None)
|
| 368 |
+
if model_type is not None:
|
| 369 |
+
backbone_config = AutoConfig.for_model(
|
| 370 |
+
model_type, **backbone_config_dict
|
| 371 |
+
)
|
| 372 |
+
return AutoModel.from_config(backbone_config)
|
| 373 |
+
return AutoModel.from_pretrained(config.backbone_model_name)
|
| 374 |
+
|
| 375 |
+
def post_init(self) -> None:
|
| 376 |
+
for module in (
|
| 377 |
+
self.uncertainty_head,
|
| 378 |
+
self.latent_encoder,
|
| 379 |
+
self.patch_decoder,
|
| 380 |
+
):
|
| 381 |
+
module.apply(self._init_weights)
|
| 382 |
+
|
| 383 |
+
def _init_weights(self, module: nn.Module) -> None:
|
| 384 |
+
if isinstance(module, nn.Linear):
|
| 385 |
+
nn.init.trunc_normal_(module.weight, std=self.config.initializer_range)
|
| 386 |
+
if module.bias is not None:
|
| 387 |
+
nn.init.zeros_(module.bias)
|
| 388 |
+
elif isinstance(module, (nn.LayerNorm, nn.RMSNorm)):
|
| 389 |
+
if module.weight is not None:
|
| 390 |
+
nn.init.ones_(module.weight)
|
| 391 |
+
bias = getattr(module, "bias", None)
|
| 392 |
+
if bias is not None:
|
| 393 |
+
nn.init.zeros_(bias)
|
| 394 |
+
|
| 395 |
+
def forward(
|
| 396 |
+
self,
|
| 397 |
+
pixel_values: torch.Tensor,
|
| 398 |
+
return_dict: Optional[bool] = None,
|
| 399 |
+
only_latents: bool = False,
|
| 400 |
+
latents: Optional[torch.Tensor] = None,
|
| 401 |
+
):
|
| 402 |
+
return_dict = (
|
| 403 |
+
return_dict if return_dict is not None else self.config.return_dict
|
| 404 |
+
)
|
| 405 |
+
patch_offset = 1 + self.num_register_tokens
|
| 406 |
+
hidden_states = self.encoder(pixel_values).last_hidden_state
|
| 407 |
+
patch_tokens = hidden_states[:, patch_offset:]
|
| 408 |
+
cls_register_hidden_states = hidden_states[:, :patch_offset]
|
| 409 |
+
|
| 410 |
+
if latents is None:
|
| 411 |
+
latents, latent_attention_weights = self.latent_encoder(
|
| 412 |
+
hidden_states, return_weights=True
|
| 413 |
+
)
|
| 414 |
+
latent_attention_weights = latent_attention_weights[
|
| 415 |
+
:, :, :, -patch_tokens.shape[1] :
|
| 416 |
+
]
|
| 417 |
+
else:
|
| 418 |
+
latent_attention_weights = None
|
| 419 |
+
|
| 420 |
+
if only_latents:
|
| 421 |
+
return latents
|
| 422 |
+
|
| 423 |
+
decoded_patches = self.patch_decoder(
|
| 424 |
+
latents, target_seq_length=patch_tokens.shape[1]
|
| 425 |
+
)
|
| 426 |
+
uncertainty = self.uncertainty_head(patch_tokens)
|
| 427 |
+
|
| 428 |
+
if not return_dict:
|
| 429 |
+
return (
|
| 430 |
+
decoded_patches,
|
| 431 |
+
latents,
|
| 432 |
+
latent_attention_weights,
|
| 433 |
+
cls_register_hidden_states,
|
| 434 |
+
patch_tokens,
|
| 435 |
+
uncertainty,
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
return FineViTModelOutput(
|
| 439 |
+
decoded_patches=decoded_patches,
|
| 440 |
+
latents=latents,
|
| 441 |
+
latent_attention_weights=latent_attention_weights,
|
| 442 |
+
cls_register_hidden_states=cls_register_hidden_states,
|
| 443 |
+
patch_tokens=patch_tokens,
|
| 444 |
+
uncertainty=uncertainty,
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
FineViTModel.register_for_auto_class("AutoModel")
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d7c4f234e6d56e68fff04dbcc1941e0b81dbaa326d44404d767c7d2dc79e5762
|
| 3 |
+
size 592677626
|
preprocessor_config.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"crop_size": {
|
| 3 |
+
"height": 224,
|
| 4 |
+
"width": 224
|
| 5 |
+
},
|
| 6 |
+
"do_center_crop": true,
|
| 7 |
+
"do_convert_rgb": true,
|
| 8 |
+
"do_normalize": true,
|
| 9 |
+
"do_rescale": true,
|
| 10 |
+
"do_resize": true,
|
| 11 |
+
"image_mean": [
|
| 12 |
+
0.485,
|
| 13 |
+
0.456,
|
| 14 |
+
0.406
|
| 15 |
+
],
|
| 16 |
+
"image_processor_type": "BitImageProcessor",
|
| 17 |
+
"image_std": [
|
| 18 |
+
0.229,
|
| 19 |
+
0.224,
|
| 20 |
+
0.225
|
| 21 |
+
],
|
| 22 |
+
"resample": 3,
|
| 23 |
+
"rescale_factor": 0.00392156862745098,
|
| 24 |
+
"size": {
|
| 25 |
+
"shortest_edge": 256
|
| 26 |
+
}
|
| 27 |
+
}
|