Instructions to use neggles/dreamsim with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use neggles/dreamsim with Transformers:
# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("neggles/dreamsim", device_map="auto") - Notebooks
- Google Colab
- Kaggle
add code
Browse filesFiles changed (5)
- __init__.pyAdded+9
- common.pyAdded+38
- model.pyAdded+173
- utils.pyAdded+160
- vit.pyAdded+375
123456789from .model import DreamsimEnsemble, DreamsimModelfrom .vit import VisionTransformer, vit_base_dreamsim
__all__ = [ "DreamsimModel", "DreamsimEnsemble", "VisionTransformer", "vit_base_dreamsim",]1234567891011121314151617181920212223242526272829303132333435363738from typing import Callable
import torchfrom torch import Tensor, nnfrom torch.nn import functional as F
def ensure_tuple(val: int | tuple[int, ...], n: int = 2) -> tuple[int, ...]: if isinstance(val, int): return (val,) * n elif len(val) != n: raise ValueError(f"Expected a tuple of {n} values, but got {len(val)}: {val}") return val
def use_fused_attn(): if hasattr(F, "scaled_dot_product_attention"): return True return False
class QuickGELU(nn.Module): """ Applies GELU approximation that is fast but somewhat inaccurate. See: https://github.com/hendrycks/GELUs """
def forward(self, input: Tensor) -> Tensor: return input * torch.sigmoid(1.702 * input)
def get_act_layer(name: str) -> Callable[[], nn.Module]: match name: case "gelu": return nn.GELU case "quick_gelu": return QuickGELU case _: raise ValueError(f"Activation layer {name} not supported.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173import torchfrom diffusers.configuration_utils import ConfigMixin, register_to_configfrom diffusers.models.modeling_utils import ModelMixinfrom torch import Tensorfrom torch.nn import functional as Ffrom torchvision.transforms import v2 as T
from .common import ensure_tuplefrom .vit import VisionTransformer, vit_base_dreamsim
class DreamsimModel(ModelMixin, ConfigMixin): @register_to_config def __init__( self, image_size: int = 224, patch_size: int = 16, layer_norm_eps: float = 1e-6, pre_norm: bool = False, act_layer: str = "gelu", img_mean: tuple[float, float, float] = (0.485, 0.456, 0.406), img_std: tuple[float, float, float] = (0.229, 0.224, 0.225), do_resize: bool = False, ) -> None: super().__init__()
self.image_size = ensure_tuple(image_size, 2) self.patch_size = patch_size self.layer_norm_eps = layer_norm_eps self.pre_norm = pre_norm self.do_resize = do_resize self.img_mean = img_mean self.img_std = img_std
num_classes = 512 if self.pre_norm else 0 self.extractor: VisionTransformer = vit_base_dreamsim( image_size=image_size, patch_size=patch_size, layer_norm_eps=layer_norm_eps, num_classes=num_classes, pre_norm=pre_norm, act_layer=act_layer, )
self.resize = T.Resize( self.image_size, interpolation=T.InterpolationMode.BICUBIC, antialias=True, ) self.img_norm = T.Normalize(mean=self.img_mean, std=self.img_std)
def transforms(self, x: Tensor) -> Tensor: if self.do_resize: x = self.resize(x) return self.img_norm(x)
def forward_features(self, x: Tensor) -> Tensor: if x.ndim == 3: x = x.unsqueeze(0) x = self.transforms(x) x = self.extractor.forward(x, norm=self.pre_norm)
x.div_(x.norm(dim=1, keepdim=True)) x.sub_(x.mean(dim=1, keepdim=True)) return x
def forward(self, x: Tensor) -> Tensor: """Dreamsim forward pass for similarity computation. Args: x (Tensor): Input tensor of shape [2, B, 3, H, W].
Returns: sim (torch.Tensor): dreamsim similarity score of shape [B]. """ all_images = x.view(-1, 3, *x.shape[-2:])
x = self.forward_features(all_images) x = x.view(*x.shape[:2], -1)
return 1 - F.cosine_similarity(x[0], x[1], dim=1)
class DreamsimEnsemble(ModelMixin, ConfigMixin): @register_to_config def __init__( self, image_size: int = 224, patch_size: int = 16, layer_norm_eps: float | tuple[float, ...] = (1e-6, 1e-5, 1e-5), num_classes: tuple[int, int, int] = (0, 512, 512), do_resize: bool = False, ) -> None: super().__init__() if isinstance(layer_norm_eps, float): layer_norm_eps = (layer_norm_eps,) * 3
self.image_size = ensure_tuple(image_size, 2) self.patch_size = patch_size self.do_resize = do_resize
self.dino: VisionTransformer = vit_base_dreamsim( image_size=self.image_size, patch_size=self.patch_size, layer_norm_eps=layer_norm_eps[0], num_classes=num_classes[0], pre_norm=False, act_layer="gelu", ) self.clip1: VisionTransformer = vit_base_dreamsim( image_size=self.image_size, patch_size=self.patch_size, layer_norm_eps=layer_norm_eps[1], num_classes=num_classes[1], pre_norm=True, act_layer="quick_gelu", ) self.clip2: VisionTransformer = vit_base_dreamsim( image_size=self.image_size, patch_size=self.patch_size, layer_norm_eps=layer_norm_eps[2], num_classes=num_classes[2], pre_norm=True, act_layer="gelu", )
self.resize = T.Resize( self.image_size, interpolation=T.InterpolationMode.BICUBIC, antialias=True, ) self.dino_norm = T.Normalize( mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), ) self.clip_norm = T.Normalize( mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711), )
def transforms(self, x: Tensor, resize: bool = False) -> tuple[Tensor, Tensor, Tensor]: if resize: x = self.resize(x) return self.dino_norm(x), self.clip_norm(x), self.clip_norm(x)
def forward_features(self, x: Tensor) -> Tensor: if x.ndim == 3: x = x.unsqueeze(0) x_dino, x_clip1, x_clip2 = self.transforms(x, self.do_resize)
# these expect to always receive a batch, and will return a batch x_dino = self.dino.forward(x_dino, norm=False) x_clip1 = self.clip1.forward(x_clip1, norm=True) x_clip2 = self.clip2.forward(x_clip2, norm=True)
z: Tensor = torch.cat([x_dino, x_clip1, x_clip2], dim=1) z.div_(z.norm(dim=1, keepdim=True)) z.sub_(z.mean(dim=1, keepdim=True)) return z
def forward(self, x: Tensor) -> Tensor: """Dreamsim forward pass for similarity computation. Args: x (Tensor): Input tensor of shape [2, B, 3, H, W].
Returns: sim (torch.Tensor): dreamsim similarity score of shape [B]. """ all_images = x.view(-1, 3, *x.shape[-2:])
x = self.forward_features(all_images) x = x.view(*x.shape[:2], -1)
return 1 - F.cosine_similarity(x[0], x[1], dim=1)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160"""Functions in this file are courtesty of @ashen-sensored on GitHub - thankyou so much! <3
Used to merge DreamSim LoRA weights into the base ViT models manually, so we don't needto use an ancient version of PeFT that is no longer supported (and kind of broken)"""import loggingfrom os import PathLikefrom pathlib import Path
import torchfrom safetensors.torch import load_filefrom torch import Tensor, nn
from .model import DreamsimModel
logger = logging.getLogger(__name__)
@torch.no_grad()def calculate_merged_weight( lora_a: Tensor, lora_b: Tensor, base: Tensor, scale: float, qkv_switches: list[bool],) -> Tensor: n_switches = len(qkv_switches) n_groups = sum(qkv_switches)
qkv_mask = torch.tensor(qkv_switches, dtype=torch.bool).reshape(len(qkv_switches), -1) qkv_mask = qkv_mask.broadcast_to((-1, base.shape[0] // n_switches)).reshape(-1)
lora_b = lora_b.squeeze() delta_w = base.new_zeros(lora_b.shape[0], base.shape[1])
grp_in_ch = lora_a.shape[0] // n_groups grp_out_ch = lora_b.shape[0] // n_groups for i in range(n_groups): islice = slice(i * grp_in_ch, (i + 1) * grp_in_ch) oslice = slice(i * grp_out_ch, (i + 1) * grp_out_ch) delta_w[oslice, :] = lora_b[oslice, :] @ lora_a[islice, :]
delta_w_full = base.new_zeros(base.shape) delta_w_full[qkv_mask, :] = delta_w
merged = base + scale * delta_w_full return merged.to(base)
@torch.no_grad()def merge_dreamsim_lora( base_model: nn.Module, lora_path: PathLike, torch_device: torch.device | str = torch.device("cpu"),): lora_path = Path(lora_path) # make sure model is on device base_model = base_model.eval().requires_grad_(False).to(torch_device)
# load the lora if lora_path.suffix.lower() in [".pt", ".pth", ".bin"]: lora_sd = torch.load(lora_path, map_location=torch_device, weights_only=True) elif lora_path.suffix.lower() == ".safetensors": lora_sd = load_file(lora_path) else: raise ValueError(f"Unsupported file extension '{lora_path.suffix}'")
# these loras were created by a cursed PEFT version, okay? so we have to do some crimes. group_prefix = "base_model.model.base_model.model.model." # get all lora weights for qkv layers, stripping the insane prefix group_weights = {k.replace(group_prefix, ""): v for k, v in lora_sd.items() if k.startswith(group_prefix)} # strip ".lora_X.weight" from keys to match against base model keys group_layers = set([k.rsplit(".", 2)[0] for k in group_weights.keys()])
base_weights = base_model.state_dict() for key in [x for x in base_weights.keys() if "attn.qkv.weight" in x]: param_name = key.rsplit(".", 1)[0] if param_name not in group_layers: logger.warning(f"QKV param '{param_name}' not found in lora weights") continue new_weight = calculate_merged_weight( group_weights[f"{param_name}.lora_A.weight"], group_weights[f"{param_name}.lora_B.weight"], base_weights[key], 0.5 / 16, [True, False, True], ) base_weights[key] = new_weight
base_model.load_state_dict(base_weights) return base_model.requires_grad_(False)
def remap_clip(state_dict: dict[str, Tensor], variant: str) -> dict[str, Tensor]: """Remap keys from the original DreamSim checkpoint to match new model structure."""
def prepend_extractor(state_dict: dict[str, Tensor]) -> dict[str, Tensor]: if variant.endswith("single"): return {f"extractor.{k}": v for k, v in state_dict.items()} return state_dict
if "clip" not in variant: return prepend_extractor(state_dict)
if "patch_embed.proj.bias" in state_dict: _ = state_dict.pop("patch_embed.proj.bias", None) if "pos_drop.weight" in state_dict: state_dict["norm_pre.weight"] = state_dict.pop("pos_drop.weight") state_dict["norm_pre.bias"] = state_dict.pop("pos_drop.bias") if "head.weight" in state_dict and "head.bias" not in state_dict: state_dict["head.bias"] = torch.zeros(state_dict["head.weight"].shape[0])
return prepend_extractor(state_dict)
def convert_dreamsim_single( ckpt_path: PathLike, variant: str, ensemble: bool = False,) -> DreamsimModel: ckpt_path = Path(ckpt_path) if ckpt_path.exists(): if ckpt_path.is_dir(): ckpt_path = ckpt_path.joinpath("ensemble" if ensemble else variant) ckpt_path = ckpt_path.joinpath(f"{variant}_merged.safetensors")
# defaults are for dino, overridden as needed below patch_size = 16 layer_norm_eps = 1e-6 pre_norm = False act_layer = "gelu"
match variant: case "open_clip_vitb16" | "open_clip_vitb32" | "clip_vitb16" | "clip_vitb32": patch_size = 32 if "b32" in variant else 16 layer_norm_eps = 1e-5 pre_norm = True img_mean = (0.48145466, 0.4578275, 0.40821073) img_std = (0.26862954, 0.26130258, 0.27577711) act_layer = "quick_gelu" if variant.startswith("clip_") else "gelu" case "dino_vitb16": img_mean = (0.485, 0.456, 0.406) img_std = (0.229, 0.224, 0.225) case _: raise NotImplementedError(f"Unsupported model variant '{variant}'")
model: DreamsimModel = DreamsimModel( image_size=224, patch_size=patch_size, layer_norm_eps=layer_norm_eps, pre_norm=pre_norm, act_layer=act_layer, img_mean=img_mean, img_std=img_std, ) state_dict = load_file(ckpt_path, device="cpu") state_dict = remap_clip(state_dict) model.extractor.load_state_dict(state_dict) return model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375# Copyright (c) Facebook, Inc. and its affiliates.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Mostly copy-paste from timm library.https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py"""import mathfrom functools import partialfrom typing import Callable, Final, Optional, Sequence
import torchfrom torch import Tensor, nnfrom torch.nn import functional as F
from .common import ensure_tuple, get_act_layer, use_fused_attn
def vit_weights_init(module: nn.Module) -> None: if isinstance(module, nn.Linear): nn.init.trunc_normal_(module.weight, std=0.02) if module.bias is not None: nn.init.zeros_(module.bias) elif isinstance(module, nn.LayerNorm): nn.init.ones_(module.weight) nn.init.zeros_(module.bias)
class DropPath(nn.Module): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
def __init__(self, drop_prob: float = 0.0, scale_by_keep: bool = True): super(DropPath, self).__init__() self.drop_prob = drop_prob self.scale_by_keep = scale_by_keep
def forward(self, x: Tensor) -> Tensor: if self.drop_prob == 0 or not self.training: return x keep_prob = 1 - self.drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets random_tensor = x.new_empty(shape).bernoulli_(keep_prob) if keep_prob > 0.0 and self.scale_by_keep: random_tensor.div_(keep_prob) return x * random_tensor
def extra_repr(self): return f"drop_prob={self.drop_prob:0.3f}"
class Mlp(nn.Module): def __init__( self, in_features: int, hidden_features: Optional[int] = None, out_features: Optional[int] = None, act_layer: Callable[[], nn.Module] = nn.GELU, drop: float = 0.0, ): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) if drop > 0.0 else nn.Identity()
def forward(self, x: Tensor) -> Tensor: x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x
class Attention(nn.Module): fused_attn: Final[bool]
def __init__( self, dim: int, num_heads: int = 8, qkv_bias: bool = False, qk_scale: Optional[float] = None, attn_drop: float = 0.0, proj_drop: float = 0.0, ): super().__init__() self.num_heads = num_heads self.head_dim = dim // num_heads self.scale = qk_scale or self.head_dim**-0.5 self.fused_attn = use_fused_attn()
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) if attn_drop > 0.0 else nn.Identity() self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) if proj_drop > 0.0 else nn.Identity()
def forward(self, x: Tensor) -> Tensor: B, N, C = x.shape qkv: Tensor = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0)
if self.fused_attn: dropout_p = getattr(self.attn_drop, "p", 0.0) if self.training else 0.0 x = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p) else: q = q * self.scale attn = q @ k.transpose(-2, -1) attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = attn @ v
x = x.transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x
class Block(nn.Module): def __init__( self, dim: int, num_heads: int, mlp_ratio: float = 4.0, qkv_bias: bool = False, drop: float = 0.0, attn_drop: float = 0.0, drop_path: float = 0.0, act_layer: Callable[[], nn.Module] = nn.GELU, norm_layer: Callable[[], nn.Module] = nn.LayerNorm, ): super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention( dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop, ) self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp( in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop, )
def forward(self, x: Tensor) -> Tensor: x = x + self.drop_path(self.attn(self.norm1(x))) x = x + self.drop_path(self.mlp(self.norm2(x))) return x
class PatchEmbed(nn.Module): """Image to Patch Embedding"""
def __init__( self, img_size: int | tuple[int, int] = 224, patch_size: int | tuple[int, int] = 16, in_chans: int = 3, embed_dim: int = 768, bias: bool = True, dynamic_pad: bool = False, ): super().__init__() self.img_size = ensure_tuple(img_size) self.patch_size = ensure_tuple(patch_size) self.num_patches = (img_size // patch_size) ** 2
self.dynamic_pad = dynamic_pad
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias)
def forward(self, x: Tensor) -> Tensor: _, _, H, W = x.shape if self.dynamic_pad: pad_h = (self.patch_size[0] - H % self.patch_size[0]) % self.patch_size[0] pad_w = (self.patch_size[1] - W % self.patch_size[1]) % self.patch_size[1] x = F.pad(x, (0, pad_w, 0, pad_h)) x = self.proj(x) x = x.flatten(2).transpose(1, 2) # NCHW -> NLC return x
class VisionTransformer(nn.Module): """Vision Transformer"""
def __init__( self, img_size: int | tuple[int, int] = 224, patch_size: int | tuple[int, int] = 16, in_chans: int = 3, num_classes: int = 0, embed_dim: int = 768, depth: int = 12, num_heads: int = 12, mlp_ratio: float = 4.0, qkv_bias: bool = False, pre_norm: bool = False, drop_rate: float = 0.0, attn_drop_rate: float = 0.0, drop_path_rate: float = 0.0, norm_layer: Callable[[], nn.Module] = nn.LayerNorm, act_layer: Callable[[], nn.Module] = nn.GELU, skip_init: bool = False, dynamic_pad: bool = False, **kwargs, ): super().__init__() self.img_size = img_size self.patch_size = patch_size self.num_classes = num_classes self.num_features = self.embed_dim = embed_dim self.depth = depth
self.patch_embed = PatchEmbed( img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim, bias=not pre_norm, # disable bias if pre-norm is used (e.g. CLIP) dynamic_pad=dynamic_pad, ) num_patches = self.patch_embed.num_patches embed_len = num_patches + 1 # num_patches + 1 for the [CLS] token
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) self.pos_embed = nn.Parameter(torch.zeros(1, embed_len, embed_dim)) self.pos_drop = nn.Dropout(p=drop_rate) if drop_rate > 0.0 else nn.Identity() self.norm_pre = norm_layer(embed_dim) if pre_norm else nn.Identity()
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, self.depth)] # stochastic depth decay rule self.blocks: list[Block] = nn.ModuleList( [ Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], act_layer=act_layer, norm_layer=norm_layer, ) for i in range(self.depth) ] ) self.norm = norm_layer(embed_dim)
# Classifier head self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity()
if not skip_init: self.reset_parameters()
def reset_parameters(self): nn.init.trunc_normal_(self.cls_token, std=0.02) nn.init.trunc_normal_(self.pos_embed, std=0.02) self.apply(vit_weights_init)
def interpolate_pos_encoding(self, x: Tensor, w: Tensor, h: Tensor) -> Tensor: npatch = x.shape[1] - 1 N = self.pos_embed.shape[1] - 1 if npatch == N and w == h: return self.pos_embed class_pos_embed = self.pos_embed[:, 0] patch_pos_embed = self.pos_embed[:, 1:] dim = x.shape[-1] w0 = w // self.patch_embed.patch_size[0] h0 = h // self.patch_embed.patch_size[0] # we add a small number to avoid floating point error in the interpolation # see discussion at https://github.com/facebookresearch/dino/issues/8 w0, h0 = w0 + 0.1, h0 + 0.1 patch_pos_embed = nn.functional.interpolate( patch_pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2), scale_factor=(w0 / math.sqrt(N), h0 / math.sqrt(N)), mode="bicubic", ) if int(w0) != patch_pos_embed.shape[-2] or int(h0) != patch_pos_embed.shape[-1]: raise ValueError("Error in positional encoding interpolation.") patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
def prepare_tokens(self, x: Tensor) -> Tensor: B, _, W, H = x.shape x = self.patch_embed(x) # patch linear embedding
# add the [CLS] token to the embed patch tokens cls_tokens = self.cls_token.expand(B, -1, -1) x = torch.cat((cls_tokens, x), dim=1)
# add positional encoding to each token x = x + self.interpolate_pos_encoding(x, W, H)
return self.pos_drop(x)
def forward(self, x: Tensor, norm: bool = True) -> Tensor: x = self.forward_features(x, norm=norm) x = self.forward_head(x) return x
def forward_features(self, x: Tensor, norm: bool = True) -> Tensor: x = self.prepare_tokens(x) x = self.norm_pre(x) for blk in self.blocks: x = blk(x) if norm: x = self.norm(x) return x[:, 0]
def forward_head(self, x: Tensor) -> Tensor: x = self.head(x) return x
def get_intermediate_layers( self, x: Tensor, n: int | Sequence[int] = 1, norm: bool = True, ) -> list[Tensor]: # we return the output tokens from the `n` last blocks outputs = [] layer_indices = set(range(self.depth - n, self.depth) if isinstance(n, int) else n) x = self.prepare_tokens(x) x = self.norm_pre(x)
for idx, blk in enumerate(self.blocks): x = blk(x) if idx in layer_indices: outputs.append(x) if norm: outputs = [self.norm(x) for x in outputs] return outputs
def vit_base_dreamsim( patch_size: int = 16, layer_norm_eps: float = 1e-6, num_classes: int = 512, act_layer: str | Callable[[], nn.Module] = "gelu", **kwargs,): if isinstance(act_layer, str): act_layer = get_act_layer(act_layer)
model = VisionTransformer( patch_size=patch_size, num_classes=num_classes, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=layer_norm_eps), act_layer=act_layer, **kwargs, ) return model__init__.pyAdded+9
common.pyAdded+38
model.pyAdded+173
utils.pyAdded+160
vit.pyAdded+375