diff --git a/experimental/SimFeatUp/featup/featurizers/maskclip/simple_tokenizer.py b/experimental/SimFeatUp/featup/featurizers/maskclip/simple_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..542b79d4fd44d54ba0933ab349e70ed4f782cea4 --- /dev/null +++ b/experimental/SimFeatUp/featup/featurizers/maskclip/simple_tokenizer.py @@ -0,0 +1,138 @@ +import gzip +import html +import os +from collections.abc import Sequence +from functools import lru_cache + +import ftfy +import regex as re + + +@lru_cache() +def default_bpe(): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz") + + +@lru_cache() +def bytes_to_unicode(): + """ + Returns list of utf-8 byte and a corresponding list of unicode strings. + The reversible bpe codes work on unicode strings. + This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. + When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. + This is a signficant percentage of your normal, say, 32K bpe vocab. + To avoid that, we want lookup tables between utf-8 bytes and unicode strings. + And avoids mapping to whitespace/control characters the bpe code barfs on. + """ + bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1)) + cs = bs[:] + n = 0 + for b in range(2**8): + if b not in bs: + bs.append(b) + cs.append(2**8+n) + n += 1 + cs = [chr(n) for n in cs] + return dict(zip(bs, cs)) + + +def get_pairs(word): + """Return set of symbol pairs in a word. + Word is represented as tuple of symbols (symbols being variable-length strings). + """ + pairs = set() + prev_char = word[0] + for char in word[1:]: + pairs.add((prev_char, char)) + prev_char = char + return pairs + + +def basic_clean(text): + # note: pretty hacky but it is okay! + # ge: bad.this is used by the cli_multi_label.py script + if not isinstance(text, str): + text = ', '.join(text) + + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + +def whitespace_clean(text): + text = re.sub(r'\s+', ' ', text) + text = text.strip() + return text + + +class SimpleTokenizer(object): + def __init__(self, bpe_path: str = default_bpe()): + self.byte_encoder = bytes_to_unicode() + self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} + merges = gzip.open(bpe_path).read().decode("utf-8").split('\n') + merges = merges[1:49152-256-2+1] + merges = [tuple(merge.split()) for merge in merges] + vocab = list(bytes_to_unicode().values()) + vocab = vocab + [v+'' for v in vocab] + for merge in merges: + vocab.append(''.join(merge)) + vocab.extend(['<|startoftext|>', '<|endoftext|>']) + self.encoder = dict(zip(vocab, range(len(vocab)))) + self.decoder = {v: k for k, v in self.encoder.items()} + self.bpe_ranks = dict(zip(merges, range(len(merges)))) + self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'} + self.pat = re.compile(r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE) + + def bpe(self, token): + if token in self.cache: + return self.cache[token] + word = tuple(token[:-1]) + ( token[-1] + '',) + pairs = get_pairs(word) + + if not pairs: + return token+'' + + while True: + bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf'))) + if bigram not in self.bpe_ranks: + break + first, second = bigram + new_word = [] + i = 0 + while i < len(word): + try: + j = word.index(first, i) + new_word.extend(word[i:j]) + i = j + except: + new_word.extend(word[i:]) + break + + if word[i] == first and i < len(word)-1 and word[i+1] == second: + new_word.append(first+second) + i += 2 + else: + new_word.append(word[i]) + i += 1 + new_word = tuple(new_word) + word = new_word + if len(word) == 1: + break + else: + pairs = get_pairs(word) + word = ' '.join(word) + self.cache[token] = word + return word + + def encode(self, text): + bpe_tokens = [] + text = whitespace_clean(basic_clean(text)).lower() + for token in re.findall(self.pat, text): + token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8')) + bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' ')) + return bpe_tokens + + def decode(self, tokens): + text = ''.join([self.decoder[token] for token in tokens]) + text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('', ' ') + return text diff --git a/experimental/SimFeatUp/featup/featurizers/maskclip/xclip.py b/experimental/SimFeatUp/featup/featurizers/maskclip/xclip.py new file mode 100644 index 0000000000000000000000000000000000000000..e0f7652b33eac7f027b46521ad3a1b30b1e82dfe --- /dev/null +++ b/experimental/SimFeatUp/featup/featurizers/maskclip/xclip.py @@ -0,0 +1,247 @@ +import hashlib +import os +import urllib +import warnings +from typing import Any, Union, List +from pkg_resources import packaging + +import torch +from PIL import Image +from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize +from tqdm import tqdm + +from .xmodel import build_model +from .simple_tokenizer import SimpleTokenizer as _Tokenizer + +try: + from torchvision.transforms import InterpolationMode + + BICUBIC = InterpolationMode.BICUBIC +except ImportError: + BICUBIC = Image.BICUBIC + +if packaging.version.parse(torch.__version__) < packaging.version.parse("1.7.1"): + warnings.warn("PyTorch version 1.7.1 or higher is recommended") + +__all__ = ["available_models", "load", "tokenize"] +_tokenizer = _Tokenizer() + +_MODELS = { + "RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt", + "RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt", + "RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt", + "RN50x16": "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt", + "RN50x64": "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt", + "ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt", + "ViT-B/16": "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt", + "ViT-L/14": "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt", + "ViT-L/14@336px": "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt", +} + + +def _download(url: str, root: str): + os.makedirs(root, exist_ok=True) + filename = os.path.basename(url) + + expected_sha256 = url.split("/")[-2] + download_target = os.path.join(root, filename) + + if os.path.exists(download_target) and not os.path.isfile(download_target): + raise RuntimeError(f"{download_target} exists and is not a regular file") + + if os.path.isfile(download_target): + if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256: + return download_target + else: + warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file") + + print(f"Downloading CLIP model from {url}") + with urllib.request.urlopen(url) as source, open(download_target, "wb") as output: + with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True, + unit_divisor=1024) as loop: + while True: + buffer = source.read(8192) + if not buffer: + break + + output.write(buffer) + loop.update(len(buffer)) + + if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256: + raise RuntimeError("Model has been downloaded but the SHA256 checksum does not not match") + + return download_target + + +def _convert_image_to_rgb(image): + return image.convert("RGB") + + +def _transform(n_px): + return Compose([ + Resize(n_px, interpolation=BICUBIC), + CenterCrop(n_px), + _convert_image_to_rgb, + ToTensor(), + Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)), + ]) + + +def available_models() -> List[str]: + """Returns the names of available CLIP models""" + return list(_MODELS.keys()) + + +TORCH_HUB_ROOT = os.path.expandvars(os.getenv("$TORCH_HUB_ROOT", "$HOME/.torch_hub")) + + +def load( + name: str, + device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", + jit: bool = False, + download_root: str = None +): + """Load a CLIP model + + Parameters + ---------- + name : str + A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict + + device : Union[str, torch.device] + The device to put the loaded model + + jit : bool + Whether to load the optimized JIT model or more hackable non-JIT model (default). + + download_root: str + path to download the model files; by default, it uses "~/.torch_hub/clip" + + Returns + ------- + model : torch.nn.Module + The CLIP model + + preprocess : Callable[[PIL.Image], torch.Tensor] + A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input + """ + if name in _MODELS: + model_path = _download(_MODELS[name], download_root or TORCH_HUB_ROOT) + elif os.path.isfile(name): + model_path = name + else: + raise RuntimeError(f"Model {name} not found; available models = {available_models()}") + + with open(model_path, 'rb') as opened_file: + try: + # loading JIT archive + model = torch.jit.load(opened_file, map_location=device if jit else "cpu").eval() + state_dict = None + except RuntimeError: + # loading saved state dict + if jit: + warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead") + jit = False + state_dict = torch.load(opened_file, map_location="cpu") + + if not jit: + model = build_model(state_dict or model.state_dict()).to(device) + if str(device) == "cpu": + model.float() + return model, _transform(model.visual.input_resolution) + + # patch the device names + device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[]) + device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1] + + def patch_device(module): + try: + graphs = [module.graph] if hasattr(module, "graph") else [] + except RuntimeError: + graphs = [] + + if hasattr(module, "forward1"): + graphs.append(module.forward1.graph) + + for graph in graphs: + for node in graph.findAllNodes("prim::Constant"): + if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"): + node.copyAttributes(device_node) + + model.apply(patch_device) + patch_device(model.encode_image) + patch_device(model.encode_text) + + # patch dtype to float32 on CPU + if str(device) == "cpu": + float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[]) + float_input = list(float_holder.graph.findNode("aten::to").inputs())[1] + float_node = float_input.node() + + def patch_float(module): + try: + graphs = [module.graph] if hasattr(module, "graph") else [] + except RuntimeError: + graphs = [] + + if hasattr(module, "forward1"): + graphs.append(module.forward1.graph) + + for graph in graphs: + for node in graph.findAllNodes("aten::to"): + inputs = list(node.inputs()) + for i in [1, 2]: # dtype can be the second or third argument to aten::to() + if inputs[i].node()["value"] == 5: + inputs[i].node().copyAttributes(float_node) + + model.apply(patch_float) + patch_float(model.encode_image) + patch_float(model.encode_text) + + model.float() + + return model, _transform(model.input_resolution.item()) + + +def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = False) -> Union[ + torch.IntTensor, torch.LongTensor]: + """ + Returns the tokenized representation of given input string(s) + + Parameters + ---------- + texts : Union[str, List[str]] + An input string or a list of input strings to tokenize + + context_length : int + The context length to use; all CLIP models use 77 as the context length + + truncate: bool + Whether to truncate the text in case its encoding is longer than the context length + + Returns + ------- + A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length]. + We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long. + """ + if isinstance(texts, str): + texts = [texts] + + sot_token = _tokenizer.encoder["<|startoftext|>"] + eot_token = _tokenizer.encoder["<|endoftext|>"] + all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts] + if packaging.version.parse(torch.__version__) < packaging.version.parse("1.8.0"): + result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) + else: + result = torch.zeros(len(all_tokens), context_length, dtype=torch.int) + + for i, tokens in enumerate(all_tokens): + if len(tokens) > context_length: + if truncate: + tokens = tokens[:context_length] + tokens[-1] = eot_token + else: + raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}") + result[i, :len(tokens)] = torch.tensor(tokens) + + return result diff --git a/experimental/SimFeatUp/featup/featurizers/maskclip/xmodel.py b/experimental/SimFeatUp/featup/featurizers/maskclip/xmodel.py new file mode 100644 index 0000000000000000000000000000000000000000..7ded78f3ef91ca30bfae581a05f1cdd89aacb343 --- /dev/null +++ b/experimental/SimFeatUp/featup/featurizers/maskclip/xmodel.py @@ -0,0 +1,535 @@ +from collections import OrderedDict +from typing import Tuple, Union + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn + +from .interpolate import interpolate_positional_embedding + + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__(self, inplanes, planes, stride=1): + super().__init__() + + # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1 + self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False) + self.bn1 = nn.BatchNorm2d(planes) + self.relu1 = nn.ReLU(inplace=True) + + self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(planes) + self.relu2 = nn.ReLU(inplace=True) + + self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity() + + self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False) + self.bn3 = nn.BatchNorm2d(planes * self.expansion) + self.relu3 = nn.ReLU(inplace=True) + + self.downsample = None + self.stride = stride + + if stride > 1 or inplanes != planes * Bottleneck.expansion: + # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1 + self.downsample = nn.Sequential(OrderedDict([ + ("-1", nn.AvgPool2d(stride)), + ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)), + ("1", nn.BatchNorm2d(planes * self.expansion)) + ])) + + def forward(self, x: torch.Tensor): + identity = x + + out = self.relu1(self.bn1(self.conv1(x))) + out = self.relu2(self.bn2(self.conv2(out))) + out = self.avgpool(out) + out = self.bn3(self.conv3(out)) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + out = self.relu3(out) + return out + + +class AttentionPool2d(nn.Module): + def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None): + super().__init__() + self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5) + self.k_proj = nn.Linear(embed_dim, embed_dim) + self.q_proj = nn.Linear(embed_dim, embed_dim) + self.v_proj = nn.Linear(embed_dim, embed_dim) + self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim) + self.num_heads = num_heads + self.spacial_dim = spacial_dim + + def forward(self, x): + x = x.flatten(start_dim=2).permute(2, 0, 1) # NCHW -> (HW)NC + x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC + x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC + x, _ = F.multi_head_attention_forward( + query=x[:1], key=x, value=x, + embed_dim_to_check=x.shape[-1], + num_heads=self.num_heads, + q_proj_weight=self.q_proj.weight, + k_proj_weight=self.k_proj.weight, + v_proj_weight=self.v_proj.weight, + in_proj_weight=None, + in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]), + bias_k=None, + bias_v=None, + add_zero_attn=False, + dropout_p=0, + out_proj_weight=self.c_proj.weight, + out_proj_bias=self.c_proj.bias, + use_separate_proj_weight=True, + training=self.training, + need_weights=False + ) + return x.squeeze(0) + + def forward_v(self, x: torch.Tensor): + """ + Forward function for computing the value features for dense prediction (i.e., features for every image patch). + """ + _, _, w, h = x.shape + x = x.flatten(start_dim=2).permute(2, 0, 1) # NCHW -> (HW)NC + x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC + + # Interpolate positional embedding to match the size of the input + interpolated_pe = interpolate_positional_embedding(self.positional_embedding, x.permute(1, 0, 2), patch_size=1, w=w, h=h) + x = x + interpolated_pe[:, None, :] # (HW+1)NC + + v_in = F.linear(x, self.v_proj.weight, self.v_proj.bias) + v_out = F.linear(v_in, self.c_proj.weight, self.c_proj.bias) + v_out = v_out.permute(1, 0, 2) # (HW+1)NC -> N(HW+1)C + return v_out + + +class ModifiedResNet(nn.Module): + """ + A ResNet class that is similar to torchvision's but contains the following changes: + - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool. + - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1 + - The final pooling layer is a QKV attention instead of an average pool + """ + + def __init__(self, layers, output_dim, heads, input_resolution=224, width=64): + super().__init__() + self.output_dim = output_dim + self.input_resolution = input_resolution + + # the 3-layer stem + self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False) + self.bn1 = nn.BatchNorm2d(width // 2) + self.relu1 = nn.ReLU(inplace=True) + self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(width // 2) + self.relu2 = nn.ReLU(inplace=True) + self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False) + self.bn3 = nn.BatchNorm2d(width) + self.relu3 = nn.ReLU(inplace=True) + self.avgpool = nn.AvgPool2d(2) + + # residual layers + self._inplanes = width # this is a *mutable* variable used during construction + self.layer1 = self._make_layer(width, layers[0]) + self.layer2 = self._make_layer(width * 2, layers[1], stride=2) + self.layer3 = self._make_layer(width * 4, layers[2], stride=2) + self.layer4 = self._make_layer(width * 8, layers[3], stride=2) + + embed_dim = width * 32 # the ResNet feature dimension + self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim) + + def _make_layer(self, planes, blocks, stride=1): + layers = [Bottleneck(self._inplanes, planes, stride)] + + self._inplanes = planes * Bottleneck.expansion + for _ in range(1, blocks): + layers.append(Bottleneck(self._inplanes, planes)) + + return nn.Sequential(*layers) + + def forward(self, x, patch_output: bool = False): + def stem(x): + x = self.relu1(self.bn1(self.conv1(x))) + x = self.relu2(self.bn2(self.conv2(x))) + x = self.relu3(self.bn3(self.conv3(x))) + x = self.avgpool(x) + return x + + x = x.type(self.conv1.weight.dtype) + x = stem(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + + if patch_output: + x = self.attnpool.forward_v(x) + x = x[:, 1:, :] # remove the cls token + else: + x = self.attnpool(x) + + return x + + +class LayerNorm(nn.LayerNorm): + """Subclass torch's LayerNorm to handle fp16.""" + + def forward(self, x: torch.Tensor): + orig_type = x.dtype + ret = super().forward(x.type(torch.float32)) + return ret.type(orig_type) + + +class QuickGELU(nn.Module): + def forward(self, x: torch.Tensor): + return x * torch.sigmoid(1.702 * x) + + +class ResidualAttentionBlock(nn.Module): + def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None): + super().__init__() + + self.attn = nn.MultiheadAttention(d_model, n_head) + self.ln_1 = LayerNorm(d_model) + self.mlp = nn.Sequential(OrderedDict([ + ("c_fc", nn.Linear(d_model, d_model * 4)), + ("gelu", QuickGELU()), + ("c_proj", nn.Linear(d_model * 4, d_model)) + ])) + self.ln_2 = LayerNorm(d_model) + self.attn_mask = attn_mask + + # self.n_head = n_head + # self.head_dim = d_model // n_head + # self.scale = self.head_dim ** -0.5 + + def attention(self, x: torch.Tensor): + self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None + return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0] + + def forward_x(self, x: torch.Tensor): + """ + Forward function for computing the value features for dense prediction (i.e., features for every image patch). + """ + return x + + def forward(self, x: torch.Tensor): + x = x + self.attention(self.ln_1(x)) + x = x + self.mlp(self.ln_2(x)) + return x + + # TODO: qq, kk, vv forward + def forward_qkv(self, x: torch.Tensor): + """ + Forward function for computing the value features for dense prediction (i.e., features for every image patch). + """ + # Get the weights and biases for the value projection, multihead attention uses 3 * embed_dim for the input projection + # x [197, 4, 768] + _, bsz, embed_dim = x.shape + v_in_proj_weight = self.attn.in_proj_weight[-self.attn.embed_dim:] + v_in_proj_bias = self.attn.in_proj_bias[-self.attn.embed_dim:] + + q_in_proj_weight = self.attn.in_proj_weight[:self.attn.embed_dim] + q_in_proj_bias = self.attn.in_proj_bias[:self.attn.embed_dim:] + + v_in = F.linear(self.ln_1(x), v_in_proj_weight, v_in_proj_bias) + # v_out = F.linear(v_in, self.attn.out_proj.weight, self.attn.out_proj.bias) + + q_in = F.linear(self.ln_1(x), q_in_proj_weight, q_in_proj_bias) + # q_out = F.linear(q_in, self.attn.out_proj.weight, self.attn.out_proj.bias) + + q_in = q_in.contiguous().view(-1, bsz * self.n_head, self.head_dim).transpose(0, 1) + v_in = v_in.contiguous().view(-1, bsz * self.n_head, self.head_dim).transpose(0, 1) + + qq_attn = torch.bmm(q_in, q_in.transpose(1, 2)) * self.scale + attn_weights = F.softmax(qq_attn, dim=-1) + attn_output = torch.bmm(attn_weights, v_in) # [12, 197, 64] + + attn_output = attn_output.transpose(0, 1).contiguous().view(-1, bsz, embed_dim) + out = F.linear(attn_output, self.attn.out_proj.weight, self.attn.out_proj.bias) + + # Using the value features works the best. Adding this to 'x' or feeding 'v' to the LayerNorm then MLP degrades the performance + return out + + + +class Transformer(nn.Module): + def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None): + super().__init__() + self.width = width + self.layers = layers + self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)]) + + def forward(self, x: torch.Tensor): + return self.resblocks(x) + + +class VisionTransformer(nn.Module): + def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int): + super().__init__() + self.input_resolution = input_resolution + self.output_dim = output_dim + self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False) + + scale = width ** -0.5 + self.class_embedding = nn.Parameter(scale * torch.randn(width)) + self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width)) + self.ln_pre = LayerNorm(width) + + self.transformer = Transformer(width, layers, heads) + + self.ln_post = LayerNorm(width) + self.proj = nn.Parameter(scale * torch.randn(width, output_dim)) + + self.patch_size = patch_size + + def forward(self, x: torch.Tensor, patch_output: bool = False): + _, _, w, h = x.shape + + x = self.conv1(x) # shape = [*, width, grid, grid] + x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2] + x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] + x = torch.cat([self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width] + x = x + interpolate_positional_embedding(self.positional_embedding, x, patch_size=self.patch_size, w=w, h=h) + x = self.ln_pre(x) + + x = x.permute(1, 0, 2) # NLD -> LND + + if patch_output: + *layers, last_resblock = self.transformer.resblocks + penultimate = nn.Sequential(*layers) + + x = penultimate(x) + x = last_resblock.forward_x(x) + x = x.permute(1, 0, 2) # LND -> NLD + + # Extract the patch tokens, not the class token + x = x[:, 1:, :] + x = self.ln_post(x) + if self.proj is not None: + # This is equivalent to conv1d + x = x @ self.proj + return x + + x = self.transformer(x) + x = x.permute(1, 0, 2) # LND -> NLD + + x = self.ln_post(x[:, 0, :]) + + if self.proj is not None: + x = x @ self.proj + + return x + + +class CLIP(nn.Module): + def __init__(self, + embed_dim: int, + # vision + image_resolution: int, + vision_layers: Union[Tuple[int, int, int, int], int], + vision_width: int, + vision_patch_size: int, + # text + context_length: int, + vocab_size: int, + transformer_width: int, + transformer_heads: int, + transformer_layers: int + ): + super().__init__() + + self.context_length = context_length + + if isinstance(vision_layers, (tuple, list)): + vision_heads = vision_width * 32 // 64 + self.visual = ModifiedResNet( + layers=vision_layers, + output_dim=embed_dim, + heads=vision_heads, + input_resolution=image_resolution, + width=vision_width + ) + else: + vision_heads = vision_width // 64 + self.visual = VisionTransformer( + input_resolution=image_resolution, + patch_size=vision_patch_size, + width=vision_width, + layers=vision_layers, + heads=vision_heads, + output_dim=embed_dim + ) + + self.transformer = Transformer( + width=transformer_width, + layers=transformer_layers, + heads=transformer_heads, + attn_mask=self.build_attention_mask() + ) + + self.vocab_size = vocab_size + self.token_embedding = nn.Embedding(vocab_size, transformer_width) + self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width)) + self.ln_final = LayerNorm(transformer_width) + + self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim)) + self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) + + self.initialize_parameters() + + def initialize_parameters(self): + nn.init.normal_(self.token_embedding.weight, std=0.02) + nn.init.normal_(self.positional_embedding, std=0.01) + + if isinstance(self.visual, ModifiedResNet): + if self.visual.attnpool is not None: + std = self.visual.attnpool.c_proj.in_features ** -0.5 + nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std) + nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std) + nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std) + nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std) + + for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]: + for name, param in resnet_block.named_parameters(): + if name.endswith("bn3.weight"): + nn.init.zeros_(param) + + proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5) + attn_std = self.transformer.width ** -0.5 + fc_std = (2 * self.transformer.width) ** -0.5 + for block in self.transformer.resblocks: + nn.init.normal_(block.attn.in_proj_weight, std=attn_std) + nn.init.normal_(block.attn.out_proj.weight, std=proj_std) + nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) + nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) + + if self.text_projection is not None: + nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5) + + def build_attention_mask(self): + # lazily create causal attention mask, with full attention between the vision tokens + # pytorch uses additive attention mask; fill with -inf + mask = torch.empty(self.context_length, self.context_length) + mask.fill_(float("-inf")) + mask.triu_(1) # zero out the lower diagonal + return mask + + @property + def dtype(self): + return self.visual.conv1.weight.dtype + + def encode_image(self, image): + return self.visual(image.type(self.dtype)) + + def get_patch_encodings(self, image) -> torch.Tensor: + """ Get the encodings for each patch in the image """ + return self.visual(image.type(self.dtype), patch_output=True) + + def get_image_encoder_projection(self) -> nn.Parameter: + """ Get vision transformer projection matrix.""" + assert isinstance(self.visual, VisionTransformer) + return self.visual.proj + + def encode_text(self, text): + x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model] + + x = x + self.positional_embedding.type(self.dtype) + x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer(x) + x = x.permute(1, 0, 2) # LND -> NLD + x = self.ln_final(x).type(self.dtype) + + # x.shape = [batch_size, n_ctx, transformer.width] + # take features from the eot embedding (eot_token is the highest number in each sequence) + x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection + + return x + + def forward(self, image, text): + image_features = self.encode_image(image) + text_features = self.encode_text(text) + + # normalized features + image_features = image_features / image_features.norm(dim=1, keepdim=True) + text_features = text_features / text_features.norm(dim=1, keepdim=True) + + # cosine similarity as logits + logit_scale = self.logit_scale.exp() + logits_per_image = logit_scale * image_features @ text_features.t() + logits_per_text = logits_per_image.t() + + # shape = [global_batch_size, global_batch_size] + return logits_per_image, logits_per_text + + +def convert_weights(model: nn.Module): + """Convert applicable model parameters to fp16""" + + def _convert_weights_to_fp16(l): + if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): + l.weight.data = l.weight.data.half() + if l.bias is not None: + l.bias.data = l.bias.data.half() + + if isinstance(l, nn.MultiheadAttention): + for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]: + tensor = getattr(l, attr) + if tensor is not None: + tensor.data = tensor.data.half() + + for name in ["text_projection", "proj"]: + if hasattr(l, name): + attr = getattr(l, name) + if attr is not None: + attr.data = attr.data.half() + + model.apply(_convert_weights_to_fp16) + + +def build_model(state_dict: dict): + vit = "visual.proj" in state_dict + + if vit: + vision_width = state_dict["visual.conv1.weight"].shape[0] + vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")]) + vision_patch_size = state_dict["visual.conv1.weight"].shape[-1] + grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5) + image_resolution = vision_patch_size * grid_size + else: + counts: list = [len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]] + vision_layers = tuple(counts) + vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0] + output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5) + vision_patch_size = None + assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0] + image_resolution = output_width * 32 + + embed_dim = state_dict["text_projection"].shape[1] + context_length = state_dict["positional_embedding"].shape[0] + vocab_size = state_dict["token_embedding.weight"].shape[0] + transformer_width = state_dict["ln_final.weight"].shape[0] + transformer_heads = transformer_width // 64 + transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith("transformer.resblocks"))) + + model = CLIP( + embed_dim, + image_resolution, vision_layers, vision_width, vision_patch_size, + context_length, vocab_size, transformer_width, transformer_heads, transformer_layers + ) + + for key in ["input_resolution", "context_length", "vocab_size"]: + if key in state_dict: + del state_dict[key] + + convert_weights(model) + model.load_state_dict(state_dict) + return model.eval() diff --git a/experimental/SimFeatUp/featup/featurizers/modules/__init__.py b/experimental/SimFeatUp/featup/featurizers/modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/experimental/SimFeatUp/featup/featurizers/modules/layers.py b/experimental/SimFeatUp/featup/featurizers/modules/layers.py new file mode 100644 index 0000000000000000000000000000000000000000..b94813a0dcdc971ee34c50d7f9f322803c3d41e6 --- /dev/null +++ b/experimental/SimFeatUp/featup/featurizers/modules/layers.py @@ -0,0 +1,309 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from functools import partial +import math + +__all__ = ['forward_hook', 'AdaptiveAvgPool2d', 'Add', 'AvgPool2d', 'BatchNorm2d', 'Clone', 'Conv2d', 'ConvTranspose2d', + 'Dropout', 'Identity', 'LeakyReLU', 'Linear', 'MaxPool2d', 'Multiply', 'ReLU', 'Sequential', 'safe_divide', + 'ZeroPad2d', 'LayerNorm', 'GELU', 'einsum', 'Softmax'] + + +def safe_divide(a, b): + return a / (b + b.eq(0).type(b.type()) * 1e-9) * b.ne(0).type(b.type()) + + +def forward_hook(self, input, output): + if type(input[0]) in (list, tuple): + self.X = [] + for i in input[0]: + x = i.detach() + x.requires_grad = True + self.X.append(x) + else: + self.X = input[0].detach() + self.X.requires_grad = True + + self.Y = output + + +class RelProp(nn.Module): + def __init__(self): + super(RelProp, self).__init__() + # if not self.training: + self.register_forward_hook(forward_hook) + + def gradprop(self, Z, X, S): + C = torch.autograd.grad(Z, X, S, retain_graph=True) + return C + + def relprop(self, R, alpha=1): + return R + + +class RelPropSimple(RelProp): + def relprop(self, R, alpha=1): + Z = self.forward(self.X) + S = safe_divide(R, Z) + C = self.gradprop(Z, self.X, S) + + if torch.is_tensor(self.X) == False: + outputs = [] + outputs.append(self.X[0] * C[0]) + outputs.append(self.X[1] * C[1]) + else: + outputs = self.X * C[0] + return outputs + + +class Identity(nn.Identity, RelProp): + pass + + +class ReLU(nn.ReLU, RelProp): + pass + + +class GELU(nn.GELU, RelProp): + pass + +class LeakyReLU(nn.LeakyReLU, RelProp): + pass + +class Softmax(nn.Softmax, RelProp): + pass + +class einsum(RelPropSimple): + def __init__(self, equation): + super().__init__() + self.equation = equation + def forward(self, *operands): + return torch.einsum(self.equation, *operands) + +class Dropout(nn.Dropout, RelProp): + pass + + +class MaxPool2d(nn.MaxPool2d, RelPropSimple): + pass + +class LayerNorm(nn.LayerNorm, RelProp): + pass + +class AdaptiveAvgPool2d(nn.AdaptiveAvgPool2d, RelProp): + def relprop(self, R, alpha=1): + px = torch.clamp(self.X, min=0) + + def f(x1): + Z1 = F.adaptive_avg_pool2d(x1, self.output_size) + S1 = safe_divide(R, Z1) + C1 = x1 * self.gradprop(Z1, x1, S1)[0] + return C1 + + activator_relevances = f(px) + out = activator_relevances + return out + + +class ZeroPad2d(nn.ZeroPad2d, RelPropSimple): + def relprop(self, R, alpha=1): + Z = self.forward(self.X) + S = safe_divide(R, Z) + C = self.gradprop(Z, self.X, S) + outputs = self.X * C[0] + return outputs + + +class AvgPool2d(nn.AvgPool2d, RelPropSimple): + pass + + +class Add(RelPropSimple): + def forward(self, inputs): + return torch.add(*inputs) + + def relprop(self, R, alpha): + Z = self.forward(self.X) + S = safe_divide(R, Z) + C = self.gradprop(Z, self.X, S) + + a = self.X[0] * C[0] + b = self.X[1] * C[1] + + a_sum = a.sum() + b_sum = b.sum() + + a_fact = safe_divide(a_sum.abs(), a_sum.abs() + b_sum.abs()) * R.sum() + b_fact = safe_divide(b_sum.abs(), a_sum.abs() + b_sum.abs()) * R.sum() + + a = a * safe_divide(a_fact, a.sum()) + b = b * safe_divide(b_fact, b.sum()) + + outputs = [a, b] + + return outputs + + +class Clone(RelProp): + def forward(self, input, num): + self.__setattr__('num', num) + outputs = [] + for _ in range(num): + outputs.append(input) + + return outputs + + def relprop(self, R, alpha = 1): + Z = [] + for _ in range(self.num): + Z.append(self.X) + S = [safe_divide(r, z) for r, z in zip(R, Z)] + C = self.gradprop(Z, self.X, S)[0] + + R = self.X * C + + return R + + +class Multiply(RelPropSimple): + def forward(self, inputs): + return torch.mul(*inputs) + + def relprop(self, R, alpha=1): + x0 = torch.clamp(self.X[0], min=0) + x1 = torch.clamp(self.X[1], min=0) + x = [x0, x1] + Z = self.forward(x) + S = safe_divide(R, Z) + C = self.gradprop(Z, x, S) + outputs = [] + outputs.append(x[0] * C[0]) + outputs.append(x[1] * C[1]) + return outputs + +class Sequential(nn.Sequential): + def relprop(self, R, alpha=1): + for m in reversed(self._modules.values()): + R = m.relprop(R, alpha) + return R + + + +class BatchNorm2d(nn.BatchNorm2d, RelProp): + def relprop(self, R, alpha=1): + X = self.X + beta = 1 - alpha + weight = self.weight.unsqueeze(0).unsqueeze(2).unsqueeze(3) / ( + (self.running_var.unsqueeze(0).unsqueeze(2).unsqueeze(3).pow(2) + self.eps).pow(0.5)) + Z = X * weight + 1e-9 + S = R / Z + Ca = S * weight + R = self.X * (Ca) + return R + + +class Linear(nn.Linear, RelProp): + def relprop(self, R, alpha=1): + beta = alpha - 1 + pw = torch.clamp(self.weight, min=0) + nw = torch.clamp(self.weight, max=0) + px = torch.clamp(self.X, min=0) + nx = torch.clamp(self.X, max=0) + + # def f(w1, w2, x1, x2): + # Z1 = F.linear(x1, w1) + # Z2 = F.linear(x2, w2) + # S1 = safe_divide(R, Z1) + # S2 = safe_divide(R, Z2) + # C1 = x1 * self.gradprop(Z1, x1, S1)[0] + # C2 = x2 * self.gradprop(Z2, x2, S2)[0] + # return C1 #+ C2 + + def f(w1, w2, x1, x2): + Z1 = F.linear(x1, w1) + Z2 = F.linear(x2, w2) + Z = Z1 + Z2 + S = safe_divide(R, Z) + C1 = x1 * self.gradprop(Z1, x1, S)[0] + C2 = x2 * self.gradprop(Z2, x2, S)[0] + return C1 + C2 + + activator_relevances = f(pw, nw, px, nx) + inhibitor_relevances = f(nw, pw, px, nx) + + out = alpha * activator_relevances - beta * inhibitor_relevances + + return out + + + +class Conv2d(nn.Conv2d, RelProp): + + def relprop(self, R, alpha=1): + if self.X.shape[1] == 3: + pw = torch.clamp(self.weight, min=0) + nw = torch.clamp(self.weight, max=0) + X = self.X + L = self.X * 0 + \ + torch.min(torch.min(torch.min(self.X, dim=1, keepdim=True)[0], dim=2, keepdim=True)[0], dim=3, + keepdim=True)[0] + H = self.X * 0 + \ + torch.max(torch.max(torch.max(self.X, dim=1, keepdim=True)[0], dim=2, keepdim=True)[0], dim=3, + keepdim=True)[0] + Za = torch.conv2d(X, self.weight, bias=None, stride=self.stride, padding=self.padding) - \ + torch.conv2d(L, pw, bias=None, stride=self.stride, padding=self.padding) - \ + torch.conv2d(H, nw, bias=None, stride=self.stride, padding=self.padding) + 1e-9 + + S = R / Za + C = X * self.gradprop2(S, self.weight) - L * self.gradprop2(S, pw) - H * self.gradprop2(S, nw) + R = C + else: + beta = alpha - 1 + pw = torch.clamp(self.weight, min=0) + nw = torch.clamp(self.weight, max=0) + px = torch.clamp(self.X, min=0) + nx = torch.clamp(self.X, max=0) + + def f(w1, w2, x1, x2): + Z1 = F.conv2d(x1, w1, bias=self.bias, stride=self.stride, padding=self.padding, groups=self.groups) + Z2 = F.conv2d(x2, w2, bias=self.bias, stride=self.stride, padding=self.padding, groups=self.groups) + Z = Z1 + Z2 + S = safe_divide(R, Z) + C1 = x1 * self.gradprop(Z1, x1, S)[0] + C2 = x2 * self.gradprop(Z2, x2, S)[0] + return C1 + C2 + + activator_relevances = f(pw, nw, px, nx) + inhibitor_relevances = f(nw, pw, px, nx) + + R = alpha * activator_relevances - beta * inhibitor_relevances + return R + + + +class ConvTranspose2d(nn.ConvTranspose2d, RelProp): + def relprop(self, R, alpha=1): + pw = torch.clamp(self.weight, min=0) + px = torch.clamp(self.X, min=0) + + def f(w1, x1): + Z1 = F.conv_transpose2d(x1, w1, bias=None, stride=self.stride, padding=self.padding, + output_padding=self.output_padding) + S1 = safe_divide(R, Z1) + C1 = x1 * self.gradprop(Z1, x1, S1)[0] + return C1 + + activator_relevances = f(pw, px) + R = activator_relevances + return R + + + +if __name__ == '__main__': + convt = ConvTranspose2d(100, 50, kernel_size=3, stride=2, padding=1, output_padding=1, bias=False).cuda() + + rand = torch.rand((1, 100, 224, 224)).cuda() + out = convt(rand) + rel = convt.relprop(out) + + print(out.shape) diff --git a/experimental/SimFeatUp/featup/featurizers/modules/resnet.py b/experimental/SimFeatUp/featup/featurizers/modules/resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..57af947a23fe6b37dcb73e6b90d4511a46216edd --- /dev/null +++ b/experimental/SimFeatUp/featup/featurizers/modules/resnet.py @@ -0,0 +1,339 @@ +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.model_zoo as model_zoo + +from featup.featurizers.modules.layers import * +import torch + +__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', + 'resnet152'] + +model_urls = { + 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', + 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', + 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', + 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', + 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth', +} + + +def conv3x3(in_planes, out_planes, stride=1): + """3x3 convolution with padding""" + return Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, + padding=1, bias=False) + + +def conv1x1(in_planes, out_planes, stride=1): + """1x1 convolution""" + return Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) + + +class BasicBlock(nn.Module): + expansion = 1 + + def __init__(self, inplanes, planes, stride=1, downsample=None): + super(BasicBlock, self).__init__() + self.clone = Clone() + + self.conv1 = conv3x3(inplanes, planes, stride) + self.bn1 = BatchNorm2d(planes) + self.conv2 = conv3x3(planes, planes) + self.bn2 = BatchNorm2d(planes) + self.downsample = downsample + self.stride = stride + + self.relu1 = ReLU(inplace=True) + self.relu2 = ReLU(inplace=True) + + self.add = Add() + + self.register_forward_hook(forward_hook) + + def forward(self, x): + x1, x2 = self.clone(x, 2) + + out = self.conv1(x1) + out = self.bn1(out) + out = self.relu1(out) + + out = self.conv2(out) + out = self.bn2(out) + + if self.downsample is not None: + x2 = self.downsample(x2) + + out = self.add([out, x2]) + out = self.relu2(out) + + return out + + def relprop(self, R, alpha): + out = self.relu2.relprop(R, alpha) + out, x2 = self.add.relprop(out, alpha) + + if self.downsample is not None: + x2 = self.downsample.relprop(x2, alpha) + + out = self.bn2.relprop(out, alpha) + out = self.conv2.relprop(out, alpha) + + out = self.relu1.relprop(out, alpha) + out = self.bn1.relprop(out, alpha) + x1 = self.conv1.relprop(out, alpha) + + return self.clone.relprop([x1, x2], alpha) + + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__(self, inplanes, planes, stride=1, downsample=None): + super(Bottleneck, self).__init__() + + self.conv1 = conv1x1(inplanes, planes) + self.bn1 = BatchNorm2d(planes) + self.conv2 = conv3x3(planes, planes, stride) + self.bn2 = BatchNorm2d(planes) + self.conv3 = conv1x1(planes, planes * self.expansion) + self.bn3 = BatchNorm2d(planes * self.expansion) + self.downsample = downsample + self.stride = stride + + self.relu1 = ReLU(inplace=True) + self.relu2 = ReLU(inplace=True) + self.relu3 = ReLU(inplace=True) + + self.add = Add() + + self.register_forward_hook(forward_hook) + + def forward(self, x): + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu1(out) + + out = self.conv2(out) + out = self.bn2(out) + out = self.relu2(out) + + out = self.conv3(out) + out = self.bn3(out) + + if self.downsample is not None: + x = self.downsample(x) + + out = self.add([out, x]) + out = self.relu3(out) + + return out + + def relprop(self, R, alpha): + out = self.relu3.relprop(R, alpha) + + out, x = self.add.relprop(out, alpha) + + if self.downsample is not None: + x = self.downsample.relprop(x, alpha) + + out = self.bn3.relprop(out, alpha) + out = self.conv3.relprop(out, alpha) + + out = self.relu2.relprop(out, alpha) + out = self.bn2.relprop(out, alpha) + out = self.conv2.relprop(out, alpha) + + out = self.relu1.relprop(out, alpha) + out = self.bn1.relprop(out, alpha) + x1 = self.conv1.relprop(out, alpha) + + return x1 + x + + +class ResNet(nn.Module): + + def __init__(self, block, layers, num_classes=1000, long=False, zero_init_residual=False): + super(ResNet, self).__init__() + self.inplanes = 64 + self.conv1 = Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) + self.bn1 = BatchNorm2d(64) + self.relu = ReLU(inplace=True) + self.maxpool = MaxPool2d(kernel_size=3, stride=2, padding=1) + self.layer1 = self._make_layer(block, 64, layers[0]) + self.layer2 = self._make_layer(block, 128, layers[1], stride=2) + self.layer3 = self._make_layer(block, 256, layers[2], stride=2) + self.layer4 = self._make_layer(block, 512, layers[3], stride=2) + self.avgpool = AdaptiveAvgPool2d((1, 1)) + self.fc = Linear(512 * block.expansion, num_classes) + self.long = long + self.num_classes = num_classes + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + # Zero-initialize the last BN in each residual branch, + # so that the residual branch starts with zeros, and each residual block behaves like an identity. + # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 + if zero_init_residual: + for m in self.modules(): + if isinstance(m, Bottleneck): + nn.init.constant_(m.bn3.weight, 0) + elif isinstance(m, BasicBlock): + nn.init.constant_(m.bn2.weight, 0) + + def _make_layer(self, block, planes, blocks, stride=1): + downsample = None + if stride != 1 or self.inplanes != planes * block.expansion: + downsample = Sequential( + conv1x1(self.inplanes, planes * block.expansion, stride), + BatchNorm2d(planes * block.expansion), + ) + + layers = [] + layers.append(block(self.inplanes, planes, stride, downsample)) + self.inplanes = planes * block.expansion + for _ in range(1, blocks): + layers.append(block(self.inplanes, planes)) + + return Sequential(*layers) + + def CLRP(self, x): + maxindex = torch.argmax(x, dim=1) + R = torch.ones(x.shape, device=x.device) + R /= -self.num_classes + for i in range(R.size(0)): + R[i, maxindex[i]] = 1 + return R + + def forward(self, img): + x = self.conv1(img) + x = self.bn1(x) + x = self.relu(x) + x = self.maxpool(x) + layer1 = self.layer1(x) + layer2 = self.layer2(layer1) + layer3 = self.layer3(layer2) + layer4 = self.layer4(layer3) + + x = self.avgpool(layer4) + x = x.view(x.size(0), -1) + return self.fc(x) + + def get_layer(self, img, layer_num): + x = self.conv1(img) + x = self.bn1(x) + x = self.relu(x) + x = self.maxpool(x) + layer1 = self.layer1(x) + if layer_num == 1: + return layer1 + layer2 = self.layer2(layer1) + if layer_num == 2: + return layer2 + layer3 = self.layer3(layer2) + if layer_num == 3: + return layer3 + layer4 = self.layer4(layer3) + if layer_num == 4 or layer_num == -1: + return layer4 + if isinstance(layer_num, tuple): + return [[layer1, layer2, layer3, layer4][i-1] for i in layer_num] + + raise ValueError(f"Unknown layer num: {layer_num}") + + def relevance_cam(self, large_img, layer_num, upsampler): + small_img = F.interpolate(large_img, size=(224, 224), mode='bilinear') + layer1, layer2, layer3, layer4 = self.get_layer(small_img, (1, 2, 3, 4)) + x = self.avgpool(layer4) + x = x.view(x.size(0), -1) + z = self.fc(x) + + R = self.CLRP(z) + R = self.fc.relprop(R, 1) + R = R.reshape_as(self.avgpool.Y) + R4 = self.avgpool.relprop(R, 1) + + if layer_num == 4: + r_weight4 = torch.mean(R4, dim=(2, 3), keepdim=True) + r_cam4 = upsampler(large_img, source=layer4) * r_weight4 + r_cam4 = torch.sum(r_cam4, dim=(1), keepdim=True) + return r_cam4 + elif layer_num == 3: + R3 = self.layer4.relprop(R4, 1) + r_weight3 = torch.mean(R3, dim=(2, 3), keepdim=True) + r_cam3 = upsampler(large_img, source=layer3) * r_weight3 + r_cam3 = torch.sum(r_cam3, dim=(1), keepdim=True) + return r_cam3 + elif layer_num == 2: + R3 = self.layer4.relprop(R4, 1) + R2 = self.layer3.relprop(R3, 1) + r_weight2 = torch.mean(R2, dim=(2, 3), keepdim=True) + r_cam2 = upsampler(large_img, source=layer2) * r_weight2 + r_cam2 = torch.sum(r_cam2, dim=(1), keepdim=True) + return r_cam2 + else: + raise ValueError(f"Unknown layer_num: {layer_num}") + + +def resnet18(pretrained=False, **kwargs): + """Constructs a ResNet-18 model. + + Args: + pretrained (bool): If True, returns a model pre-trained on ImageNet + """ + model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) + if pretrained: + model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])) + return model + + +def resnet34(pretrained=False, **kwargs): + """Constructs a ResNet-34 model. + + Args: + pretrained (bool): If True, returns a model pre-trained on ImageNet + """ + model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs) + if pretrained: + model.load_state_dict(model_zoo.load_url(model_urls['resnet34'])) + return model + + +def resnet50(pretrained=False, long=False, **kwargs): + """Constructs a ResNet-50 model. + + Args: + pretrained (bool): If True, returns a model pre-trained on ImageNet + """ + model = ResNet(Bottleneck, [3, 4, 6, 3], long=long, **kwargs) + if pretrained: + model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) + return model + + +def resnet101(pretrained=False, **kwargs): + """Constructs a ResNet-101 model. + + Args: + pretrained (bool): If True, returns a model pre-trained on ImageNet + """ + model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) + if pretrained: + model.load_state_dict(model_zoo.load_url(model_urls['resnet101'])) + return model + + +def resnet152(pretrained=False, **kwargs): + """Constructs a ResNet-152 model. + + Args: + pretrained (bool): If True, returns a model pre-trained on ImageNet + """ + model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs) + if pretrained: + model.load_state_dict(model_zoo.load_url(model_urls['resnet152'])) + return model diff --git a/experimental/SimFeatUp/featup/featurizers/modules/vgg.py b/experimental/SimFeatUp/featup/featurizers/modules/vgg.py new file mode 100644 index 0000000000000000000000000000000000000000..98f157b4d1ff992068f8b1cc4d7abfcbc5e45422 --- /dev/null +++ b/experimental/SimFeatUp/featup/featurizers/modules/vgg.py @@ -0,0 +1,366 @@ +import copy +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.model_zoo as model_zoo +import torch +from featup.featurizers.modules.layers import * + +__all__ = [ + 'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn', + 'vgg19_bn', 'vgg19', +] + + +model_urls = { + 'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth', + 'vgg13': 'https://download.pytorch.org/models/vgg13-c768596a.pth', + 'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth', + 'vgg19': 'https://download.pytorch.org/models/vgg19-dcbb9e9d.pth', + 'vgg11_bn': 'https://download.pytorch.org/models/vgg11_bn-6002323d.pth', + 'vgg13_bn': 'https://download.pytorch.org/models/vgg13_bn-abd245e5.pth', + 'vgg16_bn': 'https://download.pytorch.org/models/vgg16_bn-6c64b313.pth', + 'vgg19_bn': 'https://download.pytorch.org/models/vgg19_bn-c79401a0.pth', +} + +class VGG_spread(nn.Module): + + def __init__(self, features, num_classes=1000, init_weights=True): + super(VGG_spread, self).__init__() + self.features = features + self.avgpool = AdaptiveAvgPool2d((7, 7)) + self.classifier = Sequential( + Linear(512 * 7 * 7, 4096), + ReLU(True), + Dropout(), + Linear(4096, 4096), + ReLU(True), + Dropout(), + Linear(4096, num_classes), + ) + if init_weights: + self._initialize_weights() + + def forward(self, x): + for layer in self.features: + x = layer(x) + x = self.avgpool(x) + x = x.view(x.size(0), -1) + x = self.classifier(x) + return x + + def relprop(self, R, alpha): + x = self.classifier.relprop(R, alpha) + x = x.reshape_as(next(reversed(self.features._modules.values())).Y) + x = self.avgpool.relprop(x, alpha) + x = self.features.relprop(x, alpha) + return x + + def m_relprop(self, R, pred, alpha): + x = self.classifier.m_relprop(R, pred, alpha) + if torch.is_tensor(x) == False: + for i in range(len(x)): + x[i] = x[i].reshape_as(next(reversed(self.features._modules.values())).Y) + else: + x = x.reshape_as(next(reversed(self.features._modules.values())).Y) + x = self.avgpool.m_relprop(x, pred, alpha) + x = self.features.m_relprop(x, pred, alpha) + return x + + def RAP_relprop(self, R): + x1 = self.classifier.RAP_relprop(R) + if torch.is_tensor(x1) == False: + for i in range(len(x1)): + x1[i] = x1[i].reshape_as(next(reversed(self.features._modules.values())).Y) + else: + x1 = x1.reshape_as(next(reversed(self.features._modules.values())).Y) + x1 = self.avgpool.RAP_relprop(x1) + x1 = self.features.RAP_relprop(x1) + return x1 + + def _initialize_weights(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + nn.init.constant_(m.bias, 0) + + +class VGG(nn.Module): + + def __init__(self, features, num_classes=1000, init_weights=True): + super(VGG, self).__init__() + self.features = features + self.avgpool = AdaptiveAvgPool2d((7, 7)) + self.classifier = Sequential( + Linear(512 * 7 * 7, 4096), + ReLU(True), + Dropout(), + Linear(4096, 4096), + ReLU(True), + Dropout(), + Linear(4096, num_classes), + ) + self.num_classes = num_classes + if init_weights: + self._initialize_weights() + + def CLRP(self, x, maxindex = [None]): + if maxindex == [None]: + maxindex = torch.argmax(x, dim=1) + R = torch.ones(x.shape, x.device) + R /= -self.num_classes + for i in range(R.size(0)): + R[i, maxindex[i]] = 1 + return R + + def upsample(self, source, guidance_unscaled, upsampler, scale): + _, _, H, W = source.shape + guidance = F.interpolate(guidance_unscaled, size=(H * scale, W * scale), mode='bilinear') + return upsampler(source, guidance) + + def forward(self, x,mode='output', target_class = [None], upsampler=None, scale=1): + inp = copy.deepcopy(x) + for i, layer in enumerate(self.features): + x = layer(x) + if mode.lstrip('-').isnumeric(): + if int(mode) == i: + target_layer = x + + x = self.avgpool(x) + x = x.view(x.size(0), -1) + x = self.classifier(x) + + if mode == 'output': + return x + + R = self.CLRP(x, target_class) + R = self.classifier.relprop(R) + R = R.reshape_as(next(reversed(self.features._modules.values())).Y) + R = self.avgpool.relprop(R) + + for i in range(len(self.features)-1, int(mode), -1): + R = self.features[i].relprop(R) + + if upsampler is not None: + target_layer = self.upsample(target_layer, inp, upsampler, scale) + + r_weight = torch.mean(R, dim=(2, 3), keepdim=True) + r_cam = target_layer * r_weight + r_cam = torch.sum(r_cam, dim=(1), keepdim=True) + return r_cam, x + + + + def relprop(self, R, alpha, flag=-1): + x = self.classifier.relprop(R, alpha) + x = x.reshape_as(next(reversed(self.features._modules.values())).Y) + x = self.avgpool.relprop(x, alpha) + # x = self.features.relprop(x, alpha) + for i in range(43, flag, -1): + x = self.features[i].relprop(x, alpha) + return x + + def m_relprop(self, R, pred, alpha): + x = self.classifier.m_relprop(R, pred, alpha) + if torch.is_tensor(x) == False: + for i in range(len(x)): + x[i] = x[i].reshape_as(next(reversed(self.features._modules.values())).Y) + else: + x = x.reshape_as(next(reversed(self.features._modules.values())).Y) + x = self.avgpool.m_relprop(x, pred, alpha) + x = self.features.m_relprop(x, pred, alpha) + return x + + def RAP_relprop(self, R): + x1 = self.classifier.RAP_relprop(R) + if torch.is_tensor(x1) == False: + for i in range(len(x1)): + x1[i] = x1[i].reshape_as(next(reversed(self.features._modules.values())).Y) + else: + x1 = x1.reshape_as(next(reversed(self.features._modules.values())).Y) + x1 = self.avgpool.RAP_relprop(x1) + x1 = self.features.RAP_relprop(x1) + + return x1 + def _initialize_weights(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + nn.init.constant_(m.bias, 0) + +def make_layers(cfg, batch_norm=False): + layers = [] + in_channels = 3 + + for v in cfg: + if v == 'M': + layers += [MaxPool2d(kernel_size=2, stride=2)] + else: + conv2d = Conv2d(in_channels, v, kernel_size=3, padding=1) + if batch_norm: + layers += [conv2d, BatchNorm2d(v), ReLU(inplace=True)] + else: + layers += [conv2d, ReLU(inplace=True)] + in_channels = v + + return Sequential(*layers) + +def make_layers_list(cfg, batch_norm=False): + layers = [] + in_channels = 3 + for v in cfg: + if v == 'M': + layers += [MaxPool2d(kernel_size=2, stride=2)] + else: + conv2d = Conv2d(in_channels, v, kernel_size=3, padding=1) + if batch_norm: + layers += [conv2d, BatchNorm2d(v), ReLU(inplace=True)] + else: + layers += [conv2d, ReLU(inplace=True)] + in_channels = v + return layers + + +cfg = { + 'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], + 'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], + 'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'], + 'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'], +} + + +def vgg11(pretrained=False, **kwargs): + """VGG 11-layer model (configuration "A") + + Args: + pretrained (bool): If True, returns a model pre-trained on ImageNet + """ + if pretrained: + kwargs['init_weights'] = False + model = VGG(make_layers(cfg['A']), **kwargs) + if pretrained: + model.load_state_dict(model_zoo.load_url(model_urls['vgg11'])) + return model + + +def vgg11_bn(pretrained=False, **kwargs): + """VGG 11-layer model (configuration "A") with batch normalization + + Args: + pretrained (bool): If True, returns a model pre-trained on ImageNet + """ + if pretrained: + kwargs['init_weights'] = False + model = VGG(make_layers(cfg['A'], batch_norm=True), **kwargs) + if pretrained: + model.load_state_dict(model_zoo.load_url(model_urls['vgg11_bn'])) + return model + + +def vgg13(pretrained=False, **kwargs): + """VGG 13-layer model (configuration "B") + + Args: + pretrained (bool): If True, returns a model pre-trained on ImageNet + """ + if pretrained: + kwargs['init_weights'] = False + model = VGG(make_layers(cfg['B']), **kwargs) + if pretrained: + model.load_state_dict(model_zoo.load_url(model_urls['vgg13'])) + return model + + +def vgg13_bn(pretrained=False, **kwargs): + """VGG 13-layer model (configuration "B") with batch normalization + + Args: + pretrained (bool): If True, returns a model pre-trained on ImageNet + """ + if pretrained: + kwargs['init_weights'] = False + model = VGG(make_layers(cfg['B'], batch_norm=True), **kwargs) + if pretrained: + model.load_state_dict(model_zoo.load_url(model_urls['vgg13_bn'])) + return model + + +def vgg16(pretrained=False, **kwargs): + """VGG 16-layer model (configuration "D") + + Args: + pretrained (bool): If True, returns a model pre-trained on ImageNet + """ + if pretrained: + kwargs['init_weights'] = False + model = VGG(make_layers(cfg['D']), **kwargs) + if pretrained: + model.load_state_dict(model_zoo.load_url(model_urls['vgg16'])) + return model + +def vgg16_spread(pretrained=False, **kwargs): + """VGG 16-layer model (configuration "D") + + Args: + pretrained (bool): If True, returns a model pre-trained on ImageNet + """ + if pretrained: + kwargs['init_weights'] = False + model = VGG_spread(make_layers_list(cfg['D']), **kwargs) + if pretrained: + model.load_state_dict(model_zoo.load_url(model_urls['vgg16'])) + return model + +def vgg16_bn(pretrained=False, **kwargs): + """VGG 16-layer model (configuration "D") with batch normalization + + Args: + pretrained (bool): If True, returns a model pre-trained on ImageNet + """ + if pretrained: + kwargs['init_weights'] = False + model = VGG(make_layers(cfg['D'], batch_norm=True), **kwargs) + if pretrained: + model.load_state_dict(model_zoo.load_url(model_urls['vgg16_bn'])) + return model + + +def vgg19(pretrained=False, **kwargs): + """VGG 19-layer model (configuration "E") + + Args: + pretrained (bool): If True, returns a model pre-trained on ImageNet + """ + if pretrained: + kwargs['init_weights'] = False + model = VGG(make_layers(cfg['E']), **kwargs) + if pretrained: + model.load_state_dict(model_zoo.load_url(model_urls['vgg19'])) + return model + + +def vgg19_bn(pretrained=False, **kwargs): + """VGG 19-layer model (configuration 'E') with batch normalization + + Args: + pretrained (bool): If True, returns a model pre-trained on ImageNet + """ + if pretrained: + kwargs['init_weights'] = False + model = VGG(make_layers(cfg['E'], batch_norm=True), **kwargs) + if pretrained: + model.load_state_dict(model_zoo.load_url(model_urls['vgg19_bn'])) + return model diff --git a/experimental/build_env/declip/download_eva_clip.sh b/experimental/build_env/declip/download_eva_clip.sh new file mode 100644 index 0000000000000000000000000000000000000000..ecbfe28b1e91fe22707b1a4b5a20a4085ec434b8 --- /dev/null +++ b/experimental/build_env/declip/download_eva_clip.sh @@ -0,0 +1,284 @@ +#!/bin/bash +# DeCLIP 环境构建脚本 +# 下载 EVA-CLIP、I-JEPA 预训练权重和 COCO 数据集到 /opt/tiger/xiaomoguhzz/ + +set -e + +# 在任意 cd 之前解析脚本所在目录和项目根目录,避免后续 cd 导致 PROJECT_DIR 错误 +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_DIR="$(dirname "$(dirname "${SCRIPT_DIR}")")" + +BASE_DIR="/opt/tiger/xiaomoguhzz" +COCO_DIR="${BASE_DIR}/standard_coco" +IJEPA_DIR="${BASE_DIR}/ijepa" + +# 创建目录 +mkdir -p "${BASE_DIR}" +mkdir -p "${COCO_DIR}" +mkdir -p "${IJEPA_DIR}" + +echo "================================================" +echo "DeCLIP 环境构建脚本" +echo "目标目录: ${BASE_DIR}" +echo "================================================" + +# ==================== EVA-CLIP 权重下载 ==================== +echo "" +echo "[1/4] 下载 EVA-CLIP 预训练权重..." +echo "------------------------------------------------" + +if [ -f "${BASE_DIR}/EVA02_CLIP_L_336_psz14_s6B.pt" ]; then + echo "EVA02_CLIP_L_336_psz14_s6B.pt 已存在,跳过下载" +else + echo "正在下载 EVA02_CLIP_L_336_psz14_s6B.pt..." + huggingface-cli download QuanSun/EVA-CLIP EVA02_CLIP_L_336_psz14_s6B.pt --local-dir "${BASE_DIR}" --local-dir-use-symlinks False +fi + +if [ -f "${BASE_DIR}/EVA02_CLIP_B_psz16_s8B.pt" ]; then + echo "EVA02_CLIP_B_psz16_s8B.pt 已存在,跳过下载" +else + echo "正在下载 EVA02_CLIP_B_psz16_s8B.pt..." + huggingface-cli download QuanSun/EVA-CLIP EVA02_CLIP_B_psz16_s8B.pt --local-dir "${BASE_DIR}" --local-dir-use-symlinks False +fi + +echo "EVA-CLIP 权重下载完成!" + +# ==================== CLIPSelf proposals 权重下载 ==================== +echo "" +echo "[1.2/4] 下载 CLIPSelf proposals 权重..." +echo "------------------------------------------------" + +if [ -f "${BASE_DIR}/fvit_eva_vitb16_ovcoco_clipself_proposals.pth" ]; then + echo "fvit_eva_vitb16_ovcoco_clipself_proposals.pth 已存在,跳过下载" +else + echo "正在下载 fvit_eva_vitb16_ovcoco_clipself_proposals.pth..." + huggingface-cli download xiaomoguhzz/xiaomogu_pami fvit_eva_vitb16_ovcoco_clipself_proposals.pth --repo-type model --local-dir "${BASE_DIR}" +fi + +if [ -f "${BASE_DIR}/fvit_eva_vitl14_ovcoco_clipself_proposals.pth" ]; then + echo "fvit_eva_vitl14_ovcoco_clipself_proposals.pth 已存在,跳过下载" +else + echo "正在下载 fvit_eva_vitl14_ovcoco_clipself_proposals.pth..." + huggingface-cli download xiaomoguhzz/xiaomogu_pami fvit_eva_vitl14_ovcoco_clipself_proposals.pth --repo-type model --local-dir "${BASE_DIR}" +fi + +echo "CLIPSelf proposals 权重下载完成!" + +# ==================== SAM 权重下载 ==================== +echo "" +echo "[1.5/4] 下载 SAM 预训练权重..." +echo "------------------------------------------------" + +if [ -f "${BASE_DIR}/sam_vit_l_0b3195.pth" ]; then + echo "sam_vit_l_0b3195.pth 已存在,跳过下载" +else + echo "正在下载 SAM-L (约 1.25GB)..." + wget -c https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth -O "${BASE_DIR}/sam_vit_l_0b3195.pth" +fi + +if [ -f "${BASE_DIR}/sam_vit_b_01ec64.pth" ]; then + echo "sam_vit_b_01ec64.pth 已存在,跳过下载" +else + echo "正在下载 SAM-B (约 375MB)..." + wget -c https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth -O "${BASE_DIR}/sam_vit_b_01ec64.pth" +fi + +echo "SAM 权重下载完成!" + +# ==================== I-JEPA 权重下载 ==================== +echo "" +echo "[2/4] 下载 I-JEPA 预训练权重..." +echo "------------------------------------------------" + +if [ -f "${IJEPA_DIR}/IN1K-vit.h.14-300e.pth.tar" ]; then + echo "IN1K-vit.h.14-300e.pth.tar 已存在,跳过下载" +else + echo "正在下载 I-JEPA ViT-H/14 (224x224, ~9.7GB)..." + wget -c https://dl.fbaipublicfiles.com/ijepa/IN1K-vit.h.14-300e.pth.tar -O "${IJEPA_DIR}/IN1K-vit.h.14-300e.pth.tar" +fi + +if [ -f "${IJEPA_DIR}/IN1K-vit.h.16-448px-300e.pth.tar" ]; then + echo "IN1K-vit.h.16-448px-300e.pth.tar 已存在,跳过下载" +else + echo "正在下载 I-JEPA ViT-H/16 (448x448, ~9.7GB)..." + wget -c https://dl.fbaipublicfiles.com/ijepa/IN1K-vit.h.16-448px-300e.pth.tar -O "${IJEPA_DIR}/IN1K-vit.h.16-448px-300e.pth.tar" +fi + +echo "I-JEPA 权重下载完成!" + +# ==================== COCO 数据集下载 ==================== +echo "" +echo "[3/4] 下载 COCO 数据集..." +echo "------------------------------------------------" + +cd "${COCO_DIR}" + +# 定义下载函数 +download_and_extract() { + local url=$1 + local zip_name=$2 + local check_file=$3 + + if [ -f "${check_file}" ] || [ -d "${check_file}" ]; then + echo "${zip_name} 相关文件已存在,跳过" + return 0 + fi + + if [ ! -f "${zip_name}" ]; then + echo "正在下载 ${zip_name}..." + wget -c "${url}" + fi + + echo "正在解压 ${zip_name}..." + unzip -o -q "${zip_name}" + rm -f "${zip_name}" +} + +# 检查图像目录是否完整 (train2017 应有 118287 张, val2017 应有 5000 张) +check_images_exist() { + local dir=$1 + local min_count=$2 + if [ -d "${dir}" ]; then + local count=$(ls "${dir}" 2>/dev/null | wc -l) + if [ "${count}" -ge "${min_count}" ]; then + return 0 + fi + fi + return 1 +} + +# 下载标注文件 +if [ -f "${COCO_DIR}/annotations/instances_train2017.json" ]; then + echo "annotations_trainval2017 已存在,跳过" +else + download_and_extract "http://images.cocodataset.org/annotations/annotations_trainval2017.zip" "annotations_trainval2017.zip" "${COCO_DIR}/annotations/instances_train2017.json" +fi + +if [ -f "${COCO_DIR}/annotations/panoptic_val2017.json" ]; then + echo "panoptic_annotations 已存在,跳过" +else + download_and_extract "http://images.cocodataset.org/annotations/panoptic_annotations_trainval2017.zip" "panoptic_annotations_trainval2017.zip" "${COCO_DIR}/annotations/panoptic_val2017.json" + # 解压内部的 panoptic 分割图像 zip + cd "${COCO_DIR}/annotations" + if [ -f "panoptic_val2017.zip" ]; then + echo "正在解压 panoptic_val2017.zip..." + unzip -o -q panoptic_val2017.zip & + fi + if [ -f "panoptic_train2017.zip" ]; then + echo "正在解压 panoptic_train2017.zip..." + unzip -o -q panoptic_train2017.zip & + fi + wait + rm -f panoptic_val2017.zip panoptic_train2017.zip 2>/dev/null + cd "${COCO_DIR}" +fi + +# 并行下载和解压图像(如果需要) +NEED_TRAIN=false +NEED_VAL=false + +if check_images_exist "${COCO_DIR}/train2017" 100000; then + echo "train2017 已存在 ($(ls ${COCO_DIR}/train2017 | wc -l) 张图像),跳过" +else + NEED_TRAIN=true +fi + +if check_images_exist "${COCO_DIR}/val2017" 4000; then + echo "val2017 已存在 ($(ls ${COCO_DIR}/val2017 | wc -l) 张图像),跳过" +else + NEED_VAL=true +fi + +# 并行下载 +if [ "${NEED_TRAIN}" = true ] || [ "${NEED_VAL}" = true ]; then + echo "开始并行下载图像..." + + if [ "${NEED_TRAIN}" = true ] && [ ! -f "train2017.zip" ]; then + echo "正在下载 train2017.zip (约 18GB)..." + wget -c http://images.cocodataset.org/zips/train2017.zip & + TRAIN_PID=$! + fi + + if [ "${NEED_VAL}" = true ] && [ ! -f "val2017.zip" ]; then + echo "正在下载 val2017.zip (约 1GB)..." + wget -c http://images.cocodataset.org/zips/val2017.zip & + VAL_PID=$! + fi + + # 等待下载完成 + [ -n "${TRAIN_PID}" ] && wait ${TRAIN_PID} + [ -n "${VAL_PID}" ] && wait ${VAL_PID} + + echo "下载完成,开始并行解压..." + + # 并行解压 + if [ "${NEED_TRAIN}" = true ] && [ -f "train2017.zip" ]; then + echo "正在解压 train2017.zip..." + unzip -o -q train2017.zip && rm -f train2017.zip & + TRAIN_UNZIP_PID=$! + fi + + if [ "${NEED_VAL}" = true ] && [ -f "val2017.zip" ]; then + echo "正在解压 val2017.zip..." + unzip -o -q val2017.zip && rm -f val2017.zip & + VAL_UNZIP_PID=$! + fi + + # 等待解压完成 + [ -n "${TRAIN_UNZIP_PID}" ] && wait ${TRAIN_UNZIP_PID} + [ -n "${VAL_UNZIP_PID}" ] && wait ${VAL_UNZIP_PID} +fi + +# ==================== 安装依赖和项目 ==================== +echo "" +echo "[4/4] 安装依赖和 DeCLIP 项目..." +echo "------------------------------------------------" + +# 安装 faiss-cpu (用于特征检索和相似度搜索) +echo "安装 faiss-cpu..." +pip install faiss-cpu + +# 安装 panopticapi (COCO Panoptic 数据集处理工具) +echo "安装 panopticapi..." +pip install git+https://github.com/cocodataset/panopticapi.git + +# 安装 tensorboard (训练可视化) +echo "安装 tensorboard..." +pip install tensorboard + +# 安装 torch 和 xformers (需要匹配版本) +echo "安装 torch==2.6.0+cu124 和 xformers==0.0.29.post2..." +pip install torch==2.6.0+cu124 torchvision --index-url https://download.pytorch.org/whl/cu124 +pip install xformers==0.0.29.post2 + +# 使用脚本开头已解析的项目根目录(避免因前面 cd 到 COCO_DIR 导致 PROJECT_DIR 变成 /opt/tiger) +cd "${PROJECT_DIR}" +echo "项目目录: ${PROJECT_DIR}" + +# 使用 setup.py 安装项目(包名为 open_clip_torch) +# 如果 pyproject.toml 存在,先备份 +if [ -f "pyproject.toml" ]; then + mv pyproject.toml pyproject.toml.bak + echo "已备份 pyproject.toml" +fi + +pip install -e . +echo "DeCLIP 项目安装完成!(包名: open_clip_torch)" + +echo "" +echo "================================================" +echo "环境构建完成!" +echo "================================================" +echo "" +echo "EVA-CLIP 权重位置:" +ls -lh "${BASE_DIR}"/EVA02_CLIP_*.pt 2>/dev/null || echo " (未找到权重文件)" +echo "" +echo "I-JEPA 权重位置:" +ls -lh "${IJEPA_DIR}"/*.pth.tar 2>/dev/null || echo " (未找到权重文件)" +echo "" +echo "COCO 数据集结构:" +echo " ${COCO_DIR}/" +echo " ├── annotations/" +ls "${COCO_DIR}/annotations/" 2>/dev/null | head -10 | sed 's/^/ │ ├── /' +echo " ├── train2017/ ($(ls ${COCO_DIR}/train2017 2>/dev/null | wc -l) 张图像)" +echo " └── val2017/ ($(ls ${COCO_DIR}/val2017 2>/dev/null | wc -l) 张图像)" diff --git a/experimental/build_env/declip/install_mmcv_mmdet.sh b/experimental/build_env/declip/install_mmcv_mmdet.sh new file mode 100644 index 0000000000000000000000000000000000000000..561709c9949c88dfa1494315f8d7bc597a1eb3f8 --- /dev/null +++ b/experimental/build_env/declip/install_mmcv_mmdet.sh @@ -0,0 +1,61 @@ +#!/bin/bash +# 安装 mmcv-full 1.7.2 和 mmdetection v2.28.1 +# 用于 F-ViT OV-COCO 检测评估 +# 环境要求: PyTorch 2.6.x + CUDA 12.4 + +set -e + +INSTALL_DIR=/opt/tiger/xiaomoguhzz + +echo "==========================================" +echo "Installing mmcv-full 1.7.2 and mmdetection v2.28.1" +echo "Install directory: ${INSTALL_DIR}" +echo "==========================================" + +# Step 1: 安装 mmcv-full 1.7.2 (预编译包) +echo "Installing mmcv-full 1.7.2 via pip..." +pip install mmcv-full==1.7.2 -f https://download.openmmlab.com/mmcv/dist/cu124/torch2.6/index.html + +# Step 2: 安装 mmdetection v2.28.1 +cd ${INSTALL_DIR} + +if [ -d "mmdetection" ]; then + echo "mmdetection directory exists, skipping clone..." +else + echo "Cloning mmdetection..." + git clone https://github.com/open-mmlab/mmdetection.git +fi + +cd mmdetection +git checkout v2.28.1 + +echo "Installing mmdetection..." +pip install -e . -v + +echo "==========================================" +echo "Installation complete!" +echo "mmcv-full: 1.7.2 (pip installed)" +echo "mmdetection: ${INSTALL_DIR}/mmdetection" +echo "==========================================" + +# Step 3: 应用 PyTorch 2.6.0 兼容性修复 +echo "" +echo "Applying PyTorch 2.6.0 compatibility fix..." +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +if [ -f "${SCRIPT_DIR}/../fix_mmcv_pytorch26.sh" ]; then + bash "${SCRIPT_DIR}/../fix_mmcv_pytorch26.sh" +else + echo "Warning: fix_mmcv_pytorch26.sh not found, skipping compatibility fix" + echo "If you encounter '_use_replicated_tensor_module' errors, run:" + echo " bash ${SCRIPT_DIR}/../fix_mmcv_pytorch26.sh" +fi + +echo "" +echo "==========================================" +echo "Installation and fixes complete!" +echo "==========================================" + +# 验证安装 +echo "Verifying installation..." +python -c "from mmcv.ops import nms; print('CUDA ops OK'); import mmcv; print(f'mmcv version: {mmcv.__version__}')" +python -c "import mmdet; print(f'mmdet version: {mmdet.__version__}')" diff --git a/experimental/build_env/declip/requirements_verified.txt b/experimental/build_env/declip/requirements_verified.txt new file mode 100644 index 0000000000000000000000000000000000000000..4794ac951c8a634aee4f7fcab047658fb9eda1be --- /dev/null +++ b/experimental/build_env/declip/requirements_verified.txt @@ -0,0 +1,24 @@ +# DeCLIP 验证可行的依赖版本组合 +# 测试环境: Python 3.11, CUDA 12.4 +# 测试日期: 2026-01-18 + +# 核心深度学习框架 +torch==2.6.0+cu124 +torchvision # 需与 torch 版本匹配,pip install torchvision --upgrade +xformers==0.0.29.post2 +flash-attn==2.8.0.post2 + +# 数值计算 +numpy<2 # scipy/sklearn 需要 numpy 1.x,使用 pip install "numpy<2" + +# 数据处理和评估 +faiss-cpu +tensorboard +panopticapi @ git+https://github.com/cocodataset/panopticapi.git + +# 注意事项: +# 1. xformers 和 flash-attn 版本需要匹配,否则会报错: +# - xformers 0.0.32.post1 要求 flash-attn >=2.7.1,<=2.8.2 +# - xformers 0.0.29.post2 兼容 flash-attn 2.8.0.post2 +# 2. numpy 2.x 与 scipy/sklearn 不兼容,需降级到 numpy<2 +# 3. 安装项目本身: pip install -e . --no-deps (在项目根目录执行) diff --git a/experimental/build_env/fix_mmcv_pytorch26.sh b/experimental/build_env/fix_mmcv_pytorch26.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a68b06643887247484c8763c46e0e8556b84570 --- /dev/null +++ b/experimental/build_env/fix_mmcv_pytorch26.sh @@ -0,0 +1,111 @@ +#!/bin/bash +# mmcv-full 1.7.2 与 PyTorch 2.6.0 兼容性修复脚本 +# +# 问题:MMDistributedDataParallel 缺少 _use_replicated_tensor_module 属性检查 +# 解决:添加 hasattr 检查,确保兼容性 +# +# 使用方法: +# bash fix_mmcv_pytorch26.sh + +set -e + +echo "========================================" +echo "mmcv-full 1.7.2 PyTorch 2.6.0 兼容性修复" +echo "========================================" +echo "" + +# 1. 查找 mmcv 安装路径 +echo "[1/4] 查找 mmcv 安装路径..." +MMCV_FILE=$(python3 -c "from mmcv.parallel import MMDistributedDataParallel; import inspect; print(inspect.getfile(MMDistributedDataParallel))" 2>/dev/null) + +if [ -z "$MMCV_FILE" ]; then + echo "❌ 错误:无法找到 mmcv 安装路径" + echo "请确保已安装 mmcv-full" + exit 1 +fi + +echo "✓ 找到 mmcv distributed.py:" +echo " $MMCV_FILE" +echo "" + +# 2. 备份原文件 +echo "[2/4] 备份原文件..." +if [ -f "${MMCV_FILE}.bak" ]; then + echo "✓ 备份文件已存在,跳过备份" +else + cp "$MMCV_FILE" "${MMCV_FILE}.bak" + echo "✓ 备份完成:${MMCV_FILE}.bak" +fi +echo "" + +# 3. 应用修复 +echo "[3/4] 应用修复..." +python3 << EOF +import sys + +file_path = "$MMCV_FILE" + +# 读取文件 +with open(file_path, 'r') as f: + lines = f.readlines() + +# 检查是否需要修复 +if len(lines) <= 160: + print("❌ 错误:文件行数不足,无法修复") + sys.exit(1) + +# 检查是否已经修复过 +if 'hasattr(self, ' in lines[160]: + print("✓ 文件已经修复过,无需重复修复") + sys.exit(0) + +# 检查第160行是否包含需要修复的代码 +if 'self._use_replicated_tensor_module' not in lines[160]: + print("❌ 警告:第160行代码与预期不符") + print("当前第160行内容:") + print(lines[160]) + print("\n可能 mmcv 版本不匹配,请手动检查") + sys.exit(1) + +# 应用修复 +lines[160] = " (hasattr(self, '_use_replicated_tensor_module') and self._use_replicated_tensor_module) else self.module\n" + +# 写回文件 +with open(file_path, 'w') as f: + f.writelines(lines) + +print("✓ 修复应用成功") +EOF + +if [ $? -ne 0 ]; then + echo "" + echo "修复失败,请检查上述错误信息" + exit 1 +fi +echo "" + +# 4. 验证修复 +echo "[4/4] 验证修复..." +echo "修复后的代码(第159-161行):" +echo "---" +sed -n '159,161p' "$MMCV_FILE" +echo "---" +echo "" + +# 检查是否包含 hasattr +if grep -q "hasattr(self, '_use_replicated_tensor_module')" "$MMCV_FILE"; then + echo "✅ 修复验证成功!" + echo "" + echo "========================================" + echo "修复完成!" + echo "========================================" + echo "" + echo "现在可以正常使用多卡分布式训练/推理了" + echo "" + echo "如需恢复原文件,执行:" + echo " cp ${MMCV_FILE}.bak $MMCV_FILE" +else + echo "❌ 修复验证失败" + echo "文件已修改,但未检测到预期的 hasattr 检查" + exit 1 +fi diff --git a/experimental/build_env/fix_mmcv_pytorch26_v2.sh b/experimental/build_env/fix_mmcv_pytorch26_v2.sh new file mode 100644 index 0000000000000000000000000000000000000000..a072499639bf1d0302faa3ca632c1f0307b753e9 --- /dev/null +++ b/experimental/build_env/fix_mmcv_pytorch26_v2.sh @@ -0,0 +1,144 @@ +#!/usr/bin/env bash +# 一键修复 mmcv 与 PyTorch 2.6 兼容问题 +# 修复点: +# 1) mmcv/parallel/_functions.py: int device -> torch.device +# 2) (可选) mmcv/parallel/distributed.py: _use_replicated_tensor_module 兼容 + +set -euo pipefail + +echo "========================================" +echo "mmcv + PyTorch 2.6 兼容性修复 (v2)" +echo "========================================" + +# 1) 定位 mmcv 目录 +MMCV_DIR="$(python3 - <<'PY' +import os +import sys + +def find_mmcv_parallel_path(): + for p in sys.path: + cand = os.path.join(p, "mmcv", "parallel") + if os.path.isfile(os.path.join(cand, "_functions.py")): + return cand + return "" + +print(find_mmcv_parallel_path()) +PY +)" + +if [[ -z "${MMCV_DIR}" ]]; then + echo "❌ 无法定位 mmcv 安装路径" + exit 1 +fi + +FUNC_FILE="${MMCV_DIR}/_functions.py" +DIST_FILE="${MMCV_DIR}/distributed.py" + +echo "[1/4] mmcv 路径:${MMCV_DIR}" +echo "[2/4] 备份文件..." + +if [[ -f "${FUNC_FILE}" && ! -f "${FUNC_FILE}.bak" ]]; then + cp "${FUNC_FILE}" "${FUNC_FILE}.bak" +fi +if [[ -f "${DIST_FILE}" && ! -f "${DIST_FILE}.bak" ]]; then + cp "${DIST_FILE}" "${DIST_FILE}.bak" +fi +echo "✓ 备份完成" + +echo "[3/4] 修复 _functions.py ..." +python3 - <= 0 and lines[j].strip() == "": + j -= 1 + while j >= 0 and not lines[j].rstrip().endswith(":"): + j -= 1 + if j >= 0: + base = re.match(r"^\\s*", lines[j]).group(0) + return base + ("\\t" if "\\t" in base else " ") + return " " + +def _replace_line(idx): + indent = _child_indent(idx) + lines[idx] = (indent + + "streams = [_get_stream(torch.device('cuda', d) if isinstance(d, int) else d) " + + "for d in target_gpus]\\n") + return True + +for i, line in enumerate(lines): + if "streams" in line and "_get_stream" in line and "target_gpus" in line: + patched = _replace_line(i) + break + +if not patched: + for i, line in enumerate(lines): + if "if torch.cuda.is_available()" in line and "target_gpus" in line: + j = i + 1 + while j < len(lines) and lines[j].strip() == "": + j += 1 + if j < len(lines): + patched = _replace_line(j) + break + +if not patched: + print("❌ 未找到可替换的 streams 行,请手动检查 _functions.py") + sys.exit(1) + +if not any(l.strip().startswith("import torch") for l in lines): + lines.insert(0, "import torch\\n") + +with open(func_file, "w") as f: + f.writelines(lines) + +print("✓ _functions.py 修复完成") +PY + +echo "[4/4] (可选) 修复 distributed.py ..." +python3 - < 159 and 'self._use_replicated_tensor_module else self.module' in lines[159]: + lines[159] = " (hasattr(self, '_use_replicated_tensor_module') and self._use_replicated_tensor_module) else self.module\n" + + # 写回文件 + with open(file_path, 'w') as f: + f.writelines(lines) + + print("✅ 修复完成!") + print("\n修改后的代码(第159-162行):") + print(''.join(lines[158:162])) +else: + print("❌ 第160行内容不符,当前内容:") + if len(lines) > 159: + print(lines[159]) + else: + print("文件行数不足") diff --git a/experimental/build_env/mmcv_pytorch26_compatibility_fix.md b/experimental/build_env/mmcv_pytorch26_compatibility_fix.md new file mode 100644 index 0000000000000000000000000000000000000000..e15f4c2c03e0c6b32261463b0c9e50ce23be9ec2 --- /dev/null +++ b/experimental/build_env/mmcv_pytorch26_compatibility_fix.md @@ -0,0 +1,145 @@ +# mmcv-full 1.7.2 与 PyTorch 2.6.0 兼容性修复 + +## 问题描述 + +在 PyTorch 2.6.0 + CUDA 12.4 环境下使用 mmcv-full 1.7.2 进行多卡分布式推理时,会遇到以下错误: + +``` +AttributeError: 'MMDistributedDataParallel' object has no attribute '_use_replicated_tensor_module' +``` + +**错误位置**:`/home/tiger/.local/lib/python3.11/site-packages/mmcv/parallel/distributed.py:160` + +**根本原因**:PyTorch 2.6.0 引入了新的 `_use_replicated_tensor_module` 属性,但 mmcv-full 1.7.2 直接访问该属性而没有检查其是否存在,导致在旧版本 PyTorch 或特定情况下报错。 + +## 修复方案 + +### 方法1:修改 mmcv 源码(推荐) + +修改 `mmcv/parallel/distributed.py` 文件的第160行,添加 `hasattr` 检查: + +**修复步骤**: + +1. **备份原文件**: +```bash +cp /home/tiger/.local/lib/python3.11/site-packages/mmcv/parallel/distributed.py \ + /home/tiger/.local/lib/python3.11/site-packages/mmcv/parallel/distributed.py.bak +``` + +2. **执行修复脚本**: +```bash +python3 << 'EOF' +file_path = "/home/tiger/.local/lib/python3.11/site-packages/mmcv/parallel/distributed.py" + +# 从备份恢复(如果需要) +import shutil +import os +if os.path.exists(file_path + ".bak"): + shutil.copy(file_path + ".bak", file_path) + +# 读取文件 +with open(file_path, 'r') as f: + lines = f.readlines() + +# 修改第159-160行(索引从0开始是158-159) +# 原始代码: +# module_to_run = self._replicated_tensor_module if \ +# self._use_replicated_tensor_module else self.module +# +# 修改为: +lines[159] = " module_to_run = self._replicated_tensor_module if \\\n" +lines[160] = " (hasattr(self, '_use_replicated_tensor_module') and self._use_replicated_tensor_module) else self.module\n" + +# 写回文件 +with open(file_path, 'w') as f: + f.writelines(lines) + +print("✅ 修复完成!") +print("\n修改后的代码(第159-161行):") +print(''.join(lines[158:162])) +EOF +``` + +3. **验证修复**: +```bash +sed -n '159,161p' /home/tiger/.local/lib/python3.11/site-packages/mmcv/parallel/distributed.py +``` + +期望输出: +```python + module_to_run = self._replicated_tensor_module if \ + (hasattr(self, '_use_replicated_tensor_module') and self._use_replicated_tensor_module) else self.module + +``` + +### 方法2:降级 PyTorch(不推荐) + +降级到 PyTorch 2.1.x 或 2.2.x,但会失去新版本的功能和性能优化。 + +## 补充:PyTorch 2.6 + mmcv 1.7.2 的 Scatter 兼容问题 + +### 问题描述 + +在多卡训练/推理时,可能出现以下错误(来自 `mmcv/parallel/_functions.py`): + +``` +AttributeError: 'int' object has no attribute 'type' +``` + +该问题的根因是 `_get_stream` 在 PyTorch 2.6 中期望 `torch.device`, +但 mmcv 传入的是 int 类型的 GPU id。 + +### 一键修复脚本(推荐) + +运行仓库内脚本: + +```bash +bash /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/build_env/fix_mmcv_pytorch26_v2.sh +``` + +该脚本会: + +- 自动定位 `mmcv/parallel/_functions.py` +- 备份原文件(`.bak`) +- 将 `streams = [_get_stream(device) for device in target_gpus]` + 修改为兼容 PyTorch 2.6 的 `torch.device` 写法 +- 可选修复 `distributed.py` 中 `_use_replicated_tensor_module` 的兼容问题 + +### 手工修复要点(仅供参考) + +目标代码片段应类似: + +```python +streams = [ + _get_stream(torch.device('cuda', d) if isinstance(d, int) else d) + for d in target_gpus +] +``` + +## 修复验证 + +修复后,运行多卡推理脚本应该正常工作: + +```bash +cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/failure_case_analysis/scripts +bash run_inference.sh 0 8 +``` + +## 相关问题记录 + +- **日期**:2026-01-24 +- **环境**:PyTorch 2.6.0+cu124, mmcv-full 1.7.2, CUDA 12.4 +- **影响范围**:所有使用 `MMDistributedDataParallel` 的多卡分布式训练/推理代码 +- **修复状态**:已修复并验证 + +## 参考资料 + +- mmcv GitHub Issue: https://github.com/open-mmlab/mmcv/issues +- PyTorch 2.6.0 Release Notes: https://github.com/pytorch/pytorch/releases/tag/v2.6.0 +- mmcv 兼容性说明: https://github.com/open-mmlab/mmcv/blob/master/docs/en/compatibility.md + +## 注意事项 + +1. 该修复是临时方案,建议长期使用 mmcv 2.x 版本以获得更好的兼容性 +2. 如果重新安装 mmcv-full,需要重新应用此修复 +3. 修复后的代码保持向后兼容,不影响旧版本 PyTorch 的使用 diff --git a/experimental/build_env/proxyclip/README.md b/experimental/build_env/proxyclip/README.md new file mode 100644 index 0000000000000000000000000000000000000000..60bbd2ac6172c4b3c68eeae3c314d2194001dbdb --- /dev/null +++ b/experimental/build_env/proxyclip/README.md @@ -0,0 +1,190 @@ +# ProxyCLIP Environment Setup + +This directory contains scripts to set up the ProxyCLIP semantic segmentation environment. + +## Quick Start + +```bash +# 1. Setup environment (one-time) +bash setup_env.sh + +# 2. Activate environment +source activate.sh + +# 3. Download datasets (optional, can select specific ones) +bash download_datasets.sh + +# 4. Run evaluation +cd ../../ProxyCLIP +python eval.py --config ./configs/cfg_voc20.py +``` + +## Environment Details + +The environment includes: +- Python 3.10 +- PyTorch 2.6.0 + CUDA 12.4 +- mmcv 2.1.0 +- mmengine 0.10.4 +- mmdet 3.3.0 +- mmsegmentation 1.2.2 + +## Scripts + +| Script | Description | +|--------|-------------| +| `setup_env.sh` | Creates uv virtual environment and installs all dependencies | +| `activate.sh` | Activates the virtual environment | +| `download_datasets.sh` | Downloads semantic segmentation datasets | +| `setup_data_paths.py` | Helps configure data paths in config files | +| `requirements.txt` | Python dependencies | + +## Datasets + +The following 8 datasets are supported: + +| Dataset | Size | Notes | +|---------|------|-------| +| Pascal VOC 2012 | ~2GB | Automatic download | +| Pascal Context | ~2GB | Requires conversion | +| ADE20K | ~1GB | Automatic download | +| Cityscapes | ~12GB | Manual registration required | +| COCO-Stuff 164K | ~20GB | Automatic download | +| COCO-Object | - | Converted from COCO-Stuff | + +### Cityscapes Download + +Cityscapes requires manual registration: +1. Register at: https://www.cityscapes-dataset.com/register/ +2. Download: `leftImg8bit_trainvaltest.zip` and `gtFine_trainvaltest.zip` +3. Extract to: `data/cityscapes/` + +## Data Directory Structure + +After downloading all datasets, the structure should be: + +``` +data/ +├── VOCdevkit/ +│ ├── VOC2012/ # Pascal VOC 2012 +│ │ ├── JPEGImages/ +│ │ ├── SegmentationClass/ +│ │ └── ImageSets/Segmentation/ +│ └── VOC2010/ # Pascal Context +│ ├── JPEGImages/ +│ ├── SegmentationClassContext/ +│ └── ImageSets/SegmentationContext/ +├── ADEChallengeData2016/ # ADE20K +│ ├── images/ +│ │ └── validation/ +│ └── annotations/ +│ └── validation/ +├── cityscapes/ # Cityscapes +│ ├── leftImg8bit/ +│ │ └── val/ +│ └── gtFine/ +│ └── val/ +├── coco_stuff164k/ # COCO-Stuff 164K +│ ├── images/ +│ │ └── val2017/ +│ └── annotations/ +│ └── val2017/ +└── coco_object/ # COCO-Object + ├── images/ + │ └── val2017/ + └── annotations/ + └── val2017/ +``` + +## Running Experiments + +### Single Dataset Evaluation + +```bash +source activate.sh +cd ../../ProxyCLIP + +# Evaluate on Pascal VOC 20 +python eval.py --config ./configs/cfg_voc20.py --work-dir ./work_logs/ + +# Evaluate on ADE20K +python eval.py --config ./configs/cfg_ade20k.py --work-dir ./work_logs/ +``` + +### Multi-GPU Evaluation + +```bash +# Using 4 GPUs (default) +bash dist_test.sh ./configs/cfg_voc20.py + +# Using 8 GPUs +GPUS=8 bash dist_test.sh ./configs/cfg_voc20.py +``` + +### Evaluate All Datasets + +```bash +python eval_all.py +``` + +This generates `results.xlsx` with metrics for all 8 datasets. + +## Server Data Paths (已配置) + +数据集已下载到服务器 `/opt/tiger/xiaomoguhzz/dataset`,配置文件已更新。 + +### 数据集路径映射 + +| 数据集 | 服务器路径 | +|--------|-----------| +| ADE20K | `/opt/tiger/xiaomoguhzz/dataset/ADEChallengeData2016` | +| Cityscapes | `/opt/tiger/xiaomoguhzz/dataset/cityscapes` | +| COCO-Object | `/opt/tiger/xiaomoguhzz/dataset/coco_obj` | +| COCO-Stuff | `/opt/tiger/xiaomoguhzz/standard_coco` | +| Pascal VOC | `/opt/tiger/xiaomoguhzz/dataset/VOCdevkit/VOC2012` | +| Pascal Context | `/opt/tiger/xiaomoguhzz/dataset/VOCdevkit/VOC2010` | + +### 模型权重路径 + +| 模型 | 路径 | 推理模式 | +|------|------|----------| +| CLIP | `/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt` | vanilla | +| DeCLIP | `/mnt/bn/.../logs/DeCLIP_EVA-B_DINOv2-B_560/checkpoints/epoch_6.pt` | csa | + +### 快速测试 + +```bash +# 进入 ProxyCLIP_TPAMI 目录 +cd ../../ProxyCLIP_TPAMI + +# DeCLIP 评估 +python eval.py --config ./configs/eva_declip/cfg_voc21.py + +# CLIP baseline 评估 +python eval.py --config ./configs/eva_clip/cfg_voc21.py +``` + +--- + +## Troubleshooting + +### CUDA Out of Memory +Reduce the sliding window crop size in the config: +```python +model = dict( + slide_stride=112, + slide_crop=224, # Reduce from 336 to 224 +) +``` + +### Module Not Found +Make sure the environment is activated: +```bash +source activate.sh +``` + +### Data Path Errors +Update the data paths in config files to match your data location: +```bash +python setup_data_paths.py --data-root /path/to/your/data +``` diff --git a/experimental/build_env/proxyclip/activate.sh b/experimental/build_env/proxyclip/activate.sh new file mode 100644 index 0000000000000000000000000000000000000000..b75d327ddf9430a6dfdd4c389001251305b2d775 --- /dev/null +++ b/experimental/build_env/proxyclip/activate.sh @@ -0,0 +1,20 @@ +#!/bin/bash +# Convenience script to activate the ProxyCLIP environment +# Usage: source activate.sh + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BUILD_ENV_DIR="$(dirname "$SCRIPT_DIR")" +PROJECT_ROOT="$(dirname "$BUILD_ENV_DIR")" +VENV_DIR="$PROJECT_ROOT/.venv_proxyclip" + +if [ ! -d "$VENV_DIR" ]; then + echo "[ERROR] Virtual environment not found at $VENV_DIR" + echo "Please run setup_env.sh first:" + echo " bash $SCRIPT_DIR/setup_env.sh" + return 1 2>/dev/null || exit 1 +fi + +source "$VENV_DIR/bin/activate" +echo "ProxyCLIP environment activated!" +echo "Python: $(which python)" +echo "PyTorch: $(python -c 'import torch; print(torch.__version__)')" diff --git a/experimental/build_env/proxyclip/download_datasets.sh b/experimental/build_env/proxyclip/download_datasets.sh new file mode 100644 index 0000000000000000000000000000000000000000..2f1402bc99d0072b414268d12ef84dff4861db39 --- /dev/null +++ b/experimental/build_env/proxyclip/download_datasets.sh @@ -0,0 +1,312 @@ +#!/bin/bash +# Dataset Download Script for ProxyCLIP +# Downloads and prepares semantic segmentation datasets + +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BUILD_ENV_DIR="$(dirname "$SCRIPT_DIR")" +PROJECT_ROOT="$(dirname "$BUILD_ENV_DIR")" + +# Default data directory - can be customized +DATA_ROOT="${DATA_ROOT:-$PROJECT_ROOT/data}" + +echo "==============================================" +echo "ProxyCLIP Dataset Download Script" +echo "==============================================" +echo "Data will be downloaded to: $DATA_ROOT" +echo "" + +mkdir -p "$DATA_ROOT" +cd "$DATA_ROOT" + +# Function to download with resume support +download_file() { + local url=$1 + local filename=$2 + if [ -f "$filename" ]; then + echo " $filename already exists, skipping download." + else + echo " Downloading $filename..." + wget -c "$url" -O "$filename" + fi +} + +# ============================================ +# 1. Pascal VOC 2012 +# ============================================ +download_voc() { + echo "" + echo "[1/6] Pascal VOC 2012" + echo "----------------------------------------" + + VOC_DIR="$DATA_ROOT/VOCdevkit/VOC2012" + if [ -d "$VOC_DIR" ]; then + echo " Pascal VOC 2012 already exists at $VOC_DIR" + return + fi + + mkdir -p "$DATA_ROOT/VOCdevkit" + cd "$DATA_ROOT/VOCdevkit" + + # Download VOC 2012 trainval + download_file "http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar" "VOCtrainval_11-May-2012.tar" + + echo " Extracting..." + tar -xf VOCtrainval_11-May-2012.tar + + echo " Pascal VOC 2012 ready at: $VOC_DIR" +} + +# ============================================ +# 2. Pascal Context +# ============================================ +download_pascal_context() { + echo "" + echo "[2/6] Pascal Context" + echo "----------------------------------------" + + CONTEXT_DIR="$DATA_ROOT/VOCdevkit/VOC2010" + if [ -d "$CONTEXT_DIR/SegmentationClassContext" ]; then + echo " Pascal Context already exists at $CONTEXT_DIR" + return + fi + + # Pascal Context uses VOC2010 images + mkdir -p "$DATA_ROOT/VOCdevkit" + cd "$DATA_ROOT/VOCdevkit" + + # Download VOC 2010 + if [ ! -d "VOC2010" ]; then + download_file "http://host.robots.ox.ac.uk/pascal/VOC/voc2010/VOCtrainval_03-May-2010.tar" "VOCtrainval_03-May-2010.tar" + echo " Extracting VOC 2010..." + tar -xf VOCtrainval_03-May-2010.tar + fi + + # Download Pascal Context annotations + cd "$DATA_ROOT" + if [ ! -f "trainval_merged.json" ]; then + echo " Downloading Pascal Context annotations..." + download_file "https://cs.stanford.edu/~roozbeh/pascal-context/trainval_merged.json" "trainval_merged.json" + fi + + echo "" + echo " [NOTE] Pascal Context requires additional processing." + echo " Please run the conversion script after download:" + echo " python $SCRIPT_DIR/convert_pascal_context.py" + echo "" +} + +# ============================================ +# 3. ADE20K +# ============================================ +download_ade20k() { + echo "" + echo "[3/6] ADE20K" + echo "----------------------------------------" + + ADE_DIR="$DATA_ROOT/ADEChallengeData2016" + if [ -d "$ADE_DIR" ]; then + echo " ADE20K already exists at $ADE_DIR" + return + fi + + cd "$DATA_ROOT" + + # Download ADE20K + download_file "http://data.csail.mit.edu/places/ADEchallenge/ADEChallengeData2016.zip" "ADEChallengeData2016.zip" + + echo " Extracting..." + unzip -q ADEChallengeData2016.zip + + echo " ADE20K ready at: $ADE_DIR" +} + +# ============================================ +# 4. Cityscapes (Manual download required) +# ============================================ +download_cityscapes() { + echo "" + echo "[4/6] Cityscapes" + echo "----------------------------------------" + + CITY_DIR="$DATA_ROOT/cityscapes" + if [ -d "$CITY_DIR/leftImg8bit" ] && [ -d "$CITY_DIR/gtFine" ]; then + echo " Cityscapes already exists at $CITY_DIR" + return + fi + + echo " [MANUAL DOWNLOAD REQUIRED]" + echo "" + echo " Cityscapes requires registration. Please:" + echo " 1. Register at: https://www.cityscapes-dataset.com/register/" + echo " 2. Download the following files:" + echo " - leftImg8bit_trainvaltest.zip (11GB)" + echo " - gtFine_trainvaltest.zip (241MB)" + echo " 3. Extract to: $CITY_DIR" + echo "" + echo " Expected structure:" + echo " $CITY_DIR/" + echo " ├── leftImg8bit/" + echo " │ ├── train/" + echo " │ ├── val/" + echo " │ └── test/" + echo " └── gtFine/" + echo " ├── train/" + echo " ├── val/" + echo " └── test/" + echo "" + + mkdir -p "$CITY_DIR" +} + +# ============================================ +# 5. COCO-Stuff 164K +# ============================================ +download_coco_stuff() { + echo "" + echo "[5/6] COCO-Stuff 164K" + echo "----------------------------------------" + + COCO_DIR="$DATA_ROOT/coco_stuff164k" + if [ -d "$COCO_DIR/images" ] && [ -d "$COCO_DIR/annotations" ]; then + echo " COCO-Stuff 164K already exists at $COCO_DIR" + return + fi + + mkdir -p "$COCO_DIR" + cd "$COCO_DIR" + + # Download COCO images (train2017 and val2017) + echo " Downloading COCO images..." + mkdir -p images + cd images + + if [ ! -d "train2017" ]; then + download_file "http://images.cocodataset.org/zips/train2017.zip" "train2017.zip" + echo " Extracting train2017..." + unzip -q train2017.zip + fi + + if [ ! -d "val2017" ]; then + download_file "http://images.cocodataset.org/zips/val2017.zip" "val2017.zip" + echo " Extracting val2017..." + unzip -q val2017.zip + fi + + cd "$COCO_DIR" + + # Download COCO-Stuff annotations + echo " Downloading COCO-Stuff annotations..." + mkdir -p annotations + cd annotations + + if [ ! -d "train2017" ]; then + download_file "http://calvin.inf.ed.ac.uk/wp-content/uploads/data/cocostuffdataset/stuffthingmaps_trainval2017.zip" "stuffthingmaps_trainval2017.zip" + echo " Extracting annotations..." + unzip -q stuffthingmaps_trainval2017.zip + fi + + echo " COCO-Stuff 164K ready at: $COCO_DIR" +} + +# ============================================ +# 6. COCO-Object (Converted from COCO-Stuff) +# ============================================ +prepare_coco_object() { + echo "" + echo "[6/6] COCO-Object" + echo "----------------------------------------" + + COCO_OBJ_DIR="$DATA_ROOT/coco_object" + COCO_STUFF_DIR="$DATA_ROOT/coco_stuff164k" + + if [ -d "$COCO_OBJ_DIR" ]; then + echo " COCO-Object already exists at $COCO_OBJ_DIR" + return + fi + + if [ ! -d "$COCO_STUFF_DIR" ]; then + echo " [WARNING] COCO-Stuff 164K not found. Please download it first." + return + fi + + echo " Converting COCO-Stuff to COCO-Object..." + echo " Please run the conversion script:" + echo " python $PROJECT_ROOT/ProxyCLIP/datasets/cvt_coco_object.py $COCO_STUFF_DIR -o $COCO_OBJ_DIR" + echo "" +} + +# ============================================ +# Main execution +# ============================================ +echo "Select datasets to download (comma-separated, or 'all'):" +echo " 1. voc - Pascal VOC 2012 (~2GB)" +echo " 2. context - Pascal Context (~2GB + processing)" +echo " 3. ade20k - ADE20K (~1GB)" +echo " 4. cityscapes - Cityscapes (manual, ~12GB)" +echo " 5. cocostuff - COCO-Stuff 164K (~20GB)" +echo " 6. cocoobj - COCO-Object (converted from COCO-Stuff)" +echo "" + +# Check for command line argument +if [ -n "$1" ]; then + SELECTION="$1" +else + read -p "Enter selection (default: all): " SELECTION + SELECTION="${SELECTION:-all}" +fi + +download_selected() { + case "$1" in + voc|1) + download_voc + ;; + context|2) + download_pascal_context + ;; + ade20k|3) + download_ade20k + ;; + cityscapes|4) + download_cityscapes + ;; + cocostuff|5) + download_coco_stuff + ;; + cocoobj|6) + prepare_coco_object + ;; + all) + download_voc + download_pascal_context + download_ade20k + download_cityscapes + download_coco_stuff + prepare_coco_object + ;; + *) + echo "Unknown dataset: $1" + ;; + esac +} + +# Parse selection +IFS=',' read -ra DATASETS <<< "$SELECTION" +for dataset in "${DATASETS[@]}"; do + dataset=$(echo "$dataset" | tr -d ' ') + download_selected "$dataset" +done + +echo "" +echo "==============================================" +echo "Download complete!" +echo "==============================================" +echo "" +echo "Data location: $DATA_ROOT" +echo "" +echo "Next steps:" +echo " 1. Update data paths in ProxyCLIP/configs/*.py" +echo " 2. For Cityscapes, complete manual download" +echo " 3. For Pascal Context and COCO-Object, run conversion scripts" +echo "" diff --git a/experimental/build_env/proxyclip/requirements.txt b/experimental/build_env/proxyclip/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..b9910ee257093256b3f616c167d8dc77c8a67277 --- /dev/null +++ b/experimental/build_env/proxyclip/requirements.txt @@ -0,0 +1,32 @@ +# PyTorch with CUDA 12.4 +--extra-index-url https://download.pytorch.org/whl/cu124 +torch==2.6.0+cu124 +torchvision==0.21.0+cu124 +torchaudio==2.6.0+cu124 + +# OpenMMLab ecosystem +mmcv==2.1.0 +mmengine==0.10.4 +mmdet==3.3.0 + +# ProxyCLIP dependencies +einops>=0.3.0 +ftfy>=6.2.0 +huggingface_hub>=0.23.0 +matplotlib>=3.7.2 +nltk>=3.8.1 +numpy<2.0.0 +opencv-python>=4.6.0 +opencv-python-headless>=4.8.0 +openpyxl>=3.1.2 +Pillow>=10.4.0 +pycocotools>=2.0.7 +regex>=2023.8.8 +safetensors>=0.4.3 +scipy>=1.14.0 +scikit-image +timm>=0.4.12 +tqdm>=4.65.2 +transformers>=4.37.2 +prettytable +packaging diff --git a/experimental/build_env/proxyclip/setup_data_paths.py b/experimental/build_env/proxyclip/setup_data_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..618b0afab41e4a3ae43d56257795cb53d58e522b --- /dev/null +++ b/experimental/build_env/proxyclip/setup_data_paths.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +""" +Script to update data paths in ProxyCLIP config files. +Run this after downloading datasets to configure the correct paths. +""" + +import os +import sys +import argparse +from pathlib import Path + +# Default paths +SCRIPT_DIR = Path(__file__).parent +BUILD_ENV_DIR = SCRIPT_DIR.parent +PROJECT_ROOT = BUILD_ENV_DIR.parent +PROXYCLIP_DIR = PROJECT_ROOT / "ProxyCLIP_TPAMI" +CONFIGS_DIR = PROXYCLIP_DIR / "configs" + +# Server default data path +SERVER_DATA_ROOT = "/opt/tiger/xiaomoguhzz/dataset" + + +def update_config_paths(data_root: str, dry_run: bool = False): + """Update data paths in ProxyCLIP config files.""" + + data_root = Path(data_root).resolve() + + # Dataset path mappings + dataset_paths = { + "cfg_voc20.py": { + "data_prefix": { + "img_path": str(data_root / "VOCdevkit/VOC2012/JPEGImages"), + "seg_map_path": str(data_root / "VOCdevkit/VOC2012/SegmentationClass"), + }, + "ann_file": str(data_root / "VOCdevkit/VOC2012/ImageSets/Segmentation/val.txt"), + }, + "cfg_voc21.py": { + "data_prefix": { + "img_path": str(data_root / "VOCdevkit/VOC2012/JPEGImages"), + "seg_map_path": str(data_root / "VOCdevkit/VOC2012/SegmentationClass"), + }, + "ann_file": str(data_root / "VOCdevkit/VOC2012/ImageSets/Segmentation/val.txt"), + }, + "cfg_context59.py": { + "data_prefix": { + "img_path": str(data_root / "VOCdevkit/VOC2010/JPEGImages"), + "seg_map_path": str(data_root / "VOCdevkit/VOC2010/SegmentationClassContext"), + }, + "ann_file": str(data_root / "VOCdevkit/VOC2010/ImageSets/SegmentationContext/val.txt"), + }, + "cfg_context60.py": { + "data_prefix": { + "img_path": str(data_root / "VOCdevkit/VOC2010/JPEGImages"), + "seg_map_path": str(data_root / "VOCdevkit/VOC2010/SegmentationClassContext"), + }, + "ann_file": str(data_root / "VOCdevkit/VOC2010/ImageSets/SegmentationContext/val.txt"), + }, + "cfg_ade20k.py": { + "data_prefix": { + "img_path": str(data_root / "ADEChallengeData2016/images/validation"), + "seg_map_path": str(data_root / "ADEChallengeData2016/annotations/validation"), + }, + }, + "cfg_city_scapes.py": { + "data_prefix": { + "img_path": str(data_root / "cityscapes/leftImg8bit/val"), + "seg_map_path": str(data_root / "cityscapes/gtFine/val"), + }, + }, + "cfg_coco_stuff164k.py": { + "data_prefix": { + "img_path": str(data_root / "coco_stuff164k/images/val2017"), + "seg_map_path": str(data_root / "coco_stuff164k/annotations/val2017"), + }, + }, + "cfg_coco_object.py": { + "data_prefix": { + "img_path": str(data_root / "coco_object/images/val2017"), + "seg_map_path": str(data_root / "coco_object/annotations/val2017"), + }, + }, + } + + print("=" * 50) + print("Updating ProxyCLIP config files") + print("=" * 50) + print(f"Data root: {data_root}") + print(f"Config dir: {CONFIGS_DIR}") + print("") + + if not CONFIGS_DIR.exists(): + print(f"[ERROR] Config directory not found: {CONFIGS_DIR}") + return False + + for config_name, paths in dataset_paths.items(): + config_path = CONFIGS_DIR / config_name + if not config_path.exists(): + print(f"[SKIP] {config_name} - file not found") + continue + + print(f"[UPDATE] {config_name}") + + # Read config file + with open(config_path, 'r') as f: + content = f.read() + + # For now, just print what would be updated + if "data_prefix" in paths: + for key, value in paths["data_prefix"].items(): + print(f" {key}: {value}") + if "ann_file" in paths: + print(f" ann_file: {paths['ann_file']}") + + print("") + print("=" * 50) + print("") + print("To apply these changes, you need to manually update the config files.") + print("Each config file has a 'test_dataloader' section with 'data_prefix' settings.") + print("") + print("Example structure:") + print(" test_dataloader = dict(") + print(" dataset=dict(") + print(" data_prefix=dict(") + print(f" img_path='{data_root}/VOCdevkit/VOC2012/JPEGImages',") + print(f" seg_map_path='{data_root}/VOCdevkit/VOC2012/SegmentationClass',") + print(" ),") + print(" )") + print(" )") + print("") + + return True + + +def main(): + parser = argparse.ArgumentParser(description="Update data paths in ProxyCLIP configs") + parser.add_argument( + "--data-root", + type=str, + default=SERVER_DATA_ROOT, + help="Root directory containing all datasets (default: server path)", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Show what would be changed without modifying files", + ) + + args = parser.parse_args() + + success = update_config_paths(args.data_root, args.dry_run) + sys.exit(0 if success else 1) + + +if __name__ == "__main__": + main() diff --git a/experimental/build_env/proxyclip/setup_env.sh b/experimental/build_env/proxyclip/setup_env.sh new file mode 100644 index 0000000000000000000000000000000000000000..535649c6f762e54439c266ec914645f4307d46b4 --- /dev/null +++ b/experimental/build_env/proxyclip/setup_env.sh @@ -0,0 +1,85 @@ +#!/bin/bash +# ProxyCLIP Environment Setup Script +# Creates an isolated uv virtual environment with all dependencies + +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BUILD_ENV_DIR="$(dirname "$SCRIPT_DIR")" +PROJECT_ROOT="$(dirname "$BUILD_ENV_DIR")" +VENV_DIR="/opt/tiger/xiaomoguhzz/envs/proxyclip_venv" +MMSEG_DIR="$PROJECT_ROOT/mmsegmentation" + +echo "==============================================" +echo "ProxyCLIP Environment Setup" +echo "==============================================" +echo "Project root: $PROJECT_ROOT" +echo "Virtual env: $VENV_DIR" +echo "" + +# Check if uv is installed +if ! command -v uv &> /dev/null; then + echo "[ERROR] uv is not installed. Please install uv first:" + echo " curl -LsSf https://astral.sh/uv/install.sh | sh" + exit 1 +fi + +echo "[1/5] Creating virtual environment with Python 3.10..." +if [ -d "$VENV_DIR" ]; then + echo " Virtual environment already exists, removing..." + rm -rf "$VENV_DIR" +fi +uv venv "$VENV_DIR" --python 3.10 + +echo "" +echo "[2/5] Installing base dependencies from requirements.txt..." +uv pip install -r "$SCRIPT_DIR/requirements.txt" --python "$VENV_DIR/bin/python" + +echo "" +echo "[3/5] Installing mmsegmentation from PyPI..." + uv pip install mmsegmentation==1.2.2 --python "$VENV_DIR/bin/python" + +echo "" +echo "[4/5] Installing open_clip from ProxyCLIP..." +PROXYCLIP_DIR="$PROJECT_ROOT/ProxyCLIP" +if [ -d "$PROXYCLIP_DIR/open_clip" ]; then + echo " open_clip package is included in ProxyCLIP, no additional installation needed." +else + echo " Installing open_clip_torch..." + uv pip install open_clip_torch --python "$VENV_DIR/bin/python" +fi + +echo "" +echo "[5/5] Verifying installation..." +"$VENV_DIR/bin/python" -c " +import torch +import mmcv +import mmengine +import mmseg + +print('PyTorch version:', torch.__version__) +print('CUDA available:', torch.cuda.is_available()) +if torch.cuda.is_available(): + print('CUDA version:', torch.version.cuda) + print('GPU count:', torch.cuda.device_count()) +print('mmcv version:', mmcv.__version__) +print('mmengine version:', mmengine.__version__) +print('mmseg version:', mmseg.__version__) +" + +echo "" +echo "==============================================" +echo "Setup completed successfully!" +echo "==============================================" +echo "" +echo "To activate the environment, run:" +echo " source $VENV_DIR/bin/activate" +echo "" +echo "Or use the convenience script:" +echo " source $SCRIPT_DIR/activate.sh" +echo "" +echo "Next steps:" +echo " 1. Download datasets: bash $SCRIPT_DIR/download_datasets.sh" +echo " 2. Configure data paths in ProxyCLIP/configs/" +echo " 3. Run evaluation: cd $PROXYCLIP_DIR && python eval.py --config ./configs/cfg_voc20.py" +echo "" diff --git a/scripts/ablation_ijepa/debug_ijepa_gsc_eva_vitL14_336_coco.sh b/scripts/ablation_ijepa/debug_ijepa_gsc_eva_vitL14_336_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..43752d7e4705100eaf4024879053ba9331f607e3 --- /dev/null +++ b/scripts/ablation_ijepa/debug_ijepa_gsc_eva_vitL14_336_coco.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# JEPA-GSC 消融实验:EVA-CLIP-L/14-336 单卡调试 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt +exp_name=Debug_JEPA-GSC_EVA-L_DINOv2-B_csa_336 +vfm_type=dinov2-B +dataset_type=ablation_ijepa +version=ablation_ijepa +mode=csa_vfm_distill + +# 单卡调试 +CUDA_VISIBLE_DEVICES=0 python -m training.main \ + --batch-size=2 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=1 \ + --workers=2 \ + --model EVA02-CLIP-L-14-336 \ + --pretrained eva \ + --warmup 100 \ + --zeroshot-frequency 1 \ + --dataset-type ${dataset_type} \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --cache-dir ${pretrain_ckpt} \ + --log-every-n-steps 10 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 24 \ + --name ${exp_name} \ + --downsample-factor 14 \ + --det-image-size 336 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode ${mode} \ + --use_vfm ${vfm_type} \ + --loss_context_weight 0.25 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --skip-first-eval \ + --repa_layer_idx -1 \ + --sd-refine-weight 0.3 \ + --version ${version} \ + --train-ratio 0.01 diff --git a/scripts/ablation_ijepa/debug_ijepa_gsc_eva_vitb16_coco.sh b/scripts/ablation_ijepa/debug_ijepa_gsc_eva_vitb16_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..2529f6e0c1bc04dccc01e0c3121794f5492c3e51 --- /dev/null +++ b/scripts/ablation_ijepa/debug_ijepa_gsc_eva_vitb16_coco.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# JEPA-GSC 消融实验:EVA-CLIP-B/16 单卡调试 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt +exp_name=Debug_JEPA-GSC_EVA-B_DINOv2-B_csa_560 +vfm_type=dinov2-B +dataset_type=ablation_ijepa +version=ablation_ijepa +mode=csa_vfm_distill + +# 单卡调试 +CUDA_VISIBLE_DEVICES=0 python -m training.main \ + --batch-size=2 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=1 \ + --workers=2 \ + --model EVA02-CLIP-B-16 \ + --pretrained eva \ + --warmup 100 \ + --zeroshot-frequency 1 \ + --dataset-type ${dataset_type} \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --cache-dir ${pretrain_ckpt} \ + --log-every-n-steps 10 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 12 \ + --name ${exp_name} \ + --downsample-factor 16 \ + --det-image-size 560 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode ${mode} \ + --use_vfm ${vfm_type} \ + --loss_context_weight 0.25 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --skip-first-eval \ + --repa_layer_idx -1 \ + --sd-refine-weight 0.3 \ + --version ${version} \ + --train-ratio 0.01 diff --git a/scripts/ablation_ijepa/dist_ijepa_gsc_eva_vitL14_336_coco.sh b/scripts/ablation_ijepa/dist_ijepa_gsc_eva_vitL14_336_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..4dc638293e3787a5b09ecaa0d4e05012fa4403d8 --- /dev/null +++ b/scripts/ablation_ijepa/dist_ijepa_gsc_eva_vitL14_336_coco.sh @@ -0,0 +1,64 @@ +#!/bin/bash +# JEPA-GSC 消融实验:EVA-CLIP-L/14-336 多卡训练 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt +exp_name=Ablation_JEPA-GSC_EVA-L_DINOv2-B_csa_336 +vfm_type=dinov2-B +dataset_type=ablation_ijepa +version=ablation_ijepa +mode=csa_vfm_distill + +# Parse arguments for nohup +USE_NOHUP=true +if [[ "$1" == "--nohup" ]] || [[ "$1" == "true" ]]; then + USE_NOHUP=true +fi + +cmd="CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12349 \ + -m training.main \ + --batch-size=2 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=6 \ + --workers=4 \ + --model EVA02-CLIP-L-14-336 \ + --pretrained eva \ + --warmup 1000 \ + --zeroshot-frequency 6 \ + --dataset-type ${dataset_type} \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --cache-dir ${pretrain_ckpt} \ + --log-every-n-steps 100 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 24 \ + --name ${exp_name} \ + --downsample-factor 14 \ + --det-image-size 336 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode ${mode} \ + --use_vfm ${vfm_type} \ + --loss_context_weight 0.25 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --skip-first-eval \ + --repa_layer_idx -1 \ + --sd-refine-weight 0.3 \ + --version ${version}" \ + --resume /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/logs/Ablation_JEPA-GSC_EVA-L_DINOv2-B_csa_336/checkpoints/epoch_5.pt + +if [ "$USE_NOHUP" = true ]; then + LOG_DIR="logs/${exp_name}" + mkdir -p "$LOG_DIR" + echo "Running with nohup. Output will be saved to ${LOG_DIR}/nohup.log" + nohup sh -c "$cmd" > "${LOG_DIR}/nohup.log" 2>&1 & +else + eval $cmd +fi diff --git a/scripts/ablation_ijepa/dist_ijepa_gsc_eva_vitb16_coco.sh b/scripts/ablation_ijepa/dist_ijepa_gsc_eva_vitb16_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..f13acc22f3538a3505d365a491be13e2cb0a29f1 --- /dev/null +++ b/scripts/ablation_ijepa/dist_ijepa_gsc_eva_vitb16_coco.sh @@ -0,0 +1,65 @@ +#!/bin/bash +# JEPA-GSC 消融实验:EVA-CLIP-B/16 多卡训练 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt +exp_name=Ablation_JEPA-GSC_EVA-B_DINOv2-B_csa_560 +vfm_type=dinov2-B +dataset_type=ablation_ijepa +version=ablation_ijepa +mode=csa_vfm_distill + +# Parse arguments for nohup +USE_NOHUP=true +if [[ "$1" == "--nohup" ]] || [[ "$1" == "true" ]]; then + USE_NOHUP=true +fi + +# 多卡训练:总 batch_size=16 +# 请根据实际 GPU 数量调整 --nproc_per_node 和 --batch-size +cmd="CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12340 \ + -m training.main \ + --batch-size=2 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=6 \ + --workers=4 \ + --model EVA02-CLIP-B-16 \ + --pretrained eva \ + --warmup 1000 \ + --zeroshot-frequency 6 \ + --dataset-type ${dataset_type} \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --cache-dir ${pretrain_ckpt} \ + --log-every-n-steps 100 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 12 \ + --name ${exp_name} \ + --downsample-factor 16 \ + --det-image-size 560 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode ${mode} \ + --use_vfm ${vfm_type} \ + --loss_context_weight 0.25 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --skip-first-eval \ + --repa_layer_idx -1 \ + --sd-refine-weight 0.3 \ + --version ${version}" + +if [ "$USE_NOHUP" = true ]; then + LOG_DIR="logs/${exp_name}" + mkdir -p "$LOG_DIR" + echo "Running with nohup. Output will be saved to ${LOG_DIR}/nohup.log" + nohup sh -c "$cmd" > "${LOG_DIR}/nohup.log" 2>&1 & +else + eval $cmd +fi diff --git a/scripts/ablation_ijepa/resume_ijepa_gsc_eva_vitL14_336.sh b/scripts/ablation_ijepa/resume_ijepa_gsc_eva_vitL14_336.sh new file mode 100644 index 0000000000000000000000000000000000000000..41d6f7a533968792ef99ea3dbc943d87c07cd603 --- /dev/null +++ b/scripts/ablation_ijepa/resume_ijepa_gsc_eva_vitL14_336.sh @@ -0,0 +1,50 @@ +#!/bin/bash +# Resume Ablation_JEPA-GSC_EVA-L_DINOv2-B_csa_336 实验 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt +exp_name=Ablation_JEPA-GSC_EVA-L_DINOv2-B_csa_336 +resume_ckpt=logs/${exp_name}/checkpoints/epoch_5.pt + +cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private + +echo "Resuming: $exp_name" +echo "Checkpoint: $resume_ckpt" + +CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12342 \ + -m training.main \ + --batch-size=2 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=6 \ + --workers=4 \ + --model EVA02-CLIP-L-14-336 \ + --pretrained eva \ + --warmup 1000 \ + --zeroshot-frequency 6 \ + --dataset-type ablation_ijepa \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --cache-dir ${pretrain_ckpt} \ + --log-every-n-steps 100 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 24 \ + --name ${exp_name} \ + --downsample-factor 14 \ + --det-image-size 336 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode csa_vfm_distill \ + --use_vfm dinov2-B \ + --loss_context_weight 0.25 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --repa_layer_idx -1 \ + --sd-refine-weight 0.3 \ + --version ablation_ijepa \ + --resume ${resume_ckpt} diff --git a/scripts/ablation_sam/debug_sam_gsc_eva_vitL14_336_coco.sh b/scripts/ablation_sam/debug_sam_gsc_eva_vitL14_336_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..e02c501ef546a77c99e408f48c27fb830e151f7b --- /dev/null +++ b/scripts/ablation_sam/debug_sam_gsc_eva_vitL14_336_coco.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# SAM-GSC 消融实验:EVA-CLIP-L/14-336 单卡调试 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt +exp_name=Debug_SAM-GSC_EVA-L_DINOv2-B_csa_336 +vfm_type=dinov2-B +dataset_type=ablation_sam +version=ablation_sam +mode=csa_vfm_distill + +# 单卡调试 +CUDA_VISIBLE_DEVICES=0 python -m training.main \ + --batch-size=2 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=1 \ + --workers=2 \ + --model EVA02-CLIP-L-14-336 \ + --pretrained eva \ + --warmup 100 \ + --zeroshot-frequency 1 \ + --dataset-type ${dataset_type} \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --cache-dir ${pretrain_ckpt} \ + --log-every-n-steps 10 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 24 \ + --name ${exp_name} \ + --downsample-factor 14 \ + --det-image-size 336 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode ${mode} \ + --use_vfm ${vfm_type} \ + --loss_context_weight 0.25 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --skip-first-eval \ + --repa_layer_idx -1 \ + --sd-refine-weight 0.3 \ + --version ${version} \ + --train-ratio 0.01 diff --git a/scripts/ablation_sam/debug_sam_gsc_eva_vitb16_coco.sh b/scripts/ablation_sam/debug_sam_gsc_eva_vitb16_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..f47cc703e90600bf816785956d6ebc1aedbf9642 --- /dev/null +++ b/scripts/ablation_sam/debug_sam_gsc_eva_vitb16_coco.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# SAM-GSC 消融实验:EVA-CLIP-B/16 单卡调试 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt +exp_name=Debug_SAM-GSC_EVA-B_DINOv2-B_csa_560 +vfm_type=dinov2-B +dataset_type=ablation_sam +version=ablation_sam +mode=csa_vfm_distill + +# 单卡调试 +CUDA_VISIBLE_DEVICES=0 python -m training.main \ + --batch-size=2 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=1 \ + --workers=2 \ + --model EVA02-CLIP-B-16 \ + --pretrained eva \ + --warmup 100 \ + --zeroshot-frequency 1 \ + --dataset-type ${dataset_type} \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --cache-dir ${pretrain_ckpt} \ + --log-every-n-steps 10 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 12 \ + --name ${exp_name} \ + --downsample-factor 16 \ + --det-image-size 560 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode ${mode} \ + --use_vfm ${vfm_type} \ + --loss_context_weight 0.25 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --skip-first-eval \ + --repa_layer_idx -1 \ + --sd-refine-weight 0.3 \ + --version ${version} \ + --train-ratio 0.01 diff --git a/scripts/ablation_sam/dist_sam_gsc_eva_vitL14_336_coco.sh b/scripts/ablation_sam/dist_sam_gsc_eva_vitL14_336_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..65a4db28f2ab747420002b7141e1367febdeea05 --- /dev/null +++ b/scripts/ablation_sam/dist_sam_gsc_eva_vitL14_336_coco.sh @@ -0,0 +1,65 @@ +#!/bin/bash +# SAM-GSC 消融实验:EVA-CLIP-L/14-336 多卡训练 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt +exp_name=Ablation_SAM-GSC_EVA-L_DINOv2-B_csa_560 +vfm_type=dinov2-B +dataset_type=ablation_sam +version=ablation_sam +mode=csa_vfm_distill + +# Parse arguments for nohup +USE_NOHUP=false +if [[ "$1" == "--nohup" ]] || [[ "$1" == "true" ]]; then + USE_NOHUP=true +fi + +# 多卡训练:总 batch_size=16 +# EVA-CLIP-L 显存占用更大,可能需要减少每卡 batch_size +cmd="CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12347 \ + -m training.main \ + --batch-size=2 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=6 \ + --workers=4 \ + --model EVA02-CLIP-L-14-336 \ + --pretrained eva \ + --warmup 1000 \ + --zeroshot-frequency 6 \ + --dataset-type ${dataset_type} \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --cache-dir ${pretrain_ckpt} \ + --log-every-n-steps 100 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 24 \ + --name ${exp_name} \ + --downsample-factor 14 \ + --det-image-size 560 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode ${mode} \ + --use_vfm ${vfm_type} \ + --loss_context_weight 0.25 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --skip-first-eval \ + --repa_layer_idx -1 \ + --sd-refine-weight 0.3 \ + --version ${version}" + +if [ "$USE_NOHUP" = true ]; then + LOG_DIR="logs/${exp_name}" + mkdir -p "$LOG_DIR" + echo "Running with nohup. Output will be saved to ${LOG_DIR}/nohup.log" + nohup sh -c "$cmd" > "${LOG_DIR}/nohup.log" 2>&1 & +else + eval $cmd +fi diff --git a/scripts/ablation_sam/dist_sam_gsc_eva_vitb16_coco.sh b/scripts/ablation_sam/dist_sam_gsc_eva_vitb16_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..35fbf5524a5459b7c4f6d8338aeabf31ba610c6c --- /dev/null +++ b/scripts/ablation_sam/dist_sam_gsc_eva_vitb16_coco.sh @@ -0,0 +1,66 @@ +#!/bin/bash +# SAM-GSC 消融实验:EVA-CLIP-B/16 多卡训练 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt +exp_name=Ablation_SAM-GSC_EVA-B_DINOv2-B_csa_560 +vfm_type=dinov2-B +dataset_type=ablation_sam +version=ablation_sam +mode=csa_vfm_distill + +# Parse arguments for nohup +USE_NOHUP=true +if [[ "$1" == "--nohup" ]] || [[ "$1" == "true" ]]; then + USE_NOHUP=true +fi + +# 多卡训练:总 batch_size=16 +# 请根据实际 GPU 数量调整 --nproc_per_node 和 --batch-size +# 例如:4卡 x 4 = 16, 2卡 x 8 = 16, 8卡 x 2 = 16 +cmd="CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12348 \ + -m training.main \ + --batch-size=2 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=6 \ + --workers=4 \ + --model EVA02-CLIP-B-16 \ + --pretrained eva \ + --warmup 1000 \ + --zeroshot-frequency 6 \ + --dataset-type ${dataset_type} \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --cache-dir ${pretrain_ckpt} \ + --log-every-n-steps 100 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 12 \ + --name ${exp_name} \ + --downsample-factor 16 \ + --det-image-size 560 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode ${mode} \ + --use_vfm ${vfm_type} \ + --loss_context_weight 0.25 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --skip-first-eval \ + --repa_layer_idx -1 \ + --sd-refine-weight 0.3 \ + --version ${version}" + +if [ "$USE_NOHUP" = true ]; then + LOG_DIR="logs/${exp_name}" + mkdir -p "$LOG_DIR" + echo "Running with nohup. Output will be saved to ${LOG_DIR}/nohup.log" + nohup sh -c "$cmd" > "${LOG_DIR}/nohup.log" 2>&1 & +else + eval $cmd +fi diff --git a/scripts/declip+/DeCLIP+_eva_vitb16_coco.sh b/scripts/declip+/DeCLIP+_eva_vitb16_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..fe81b8a3cd20dd06e7e7ae69f641833db8d6e209 --- /dev/null +++ b/scripts/declip+/DeCLIP+_eva_vitb16_coco.sh @@ -0,0 +1,17 @@ +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt +exp_name=test +vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} +dataset_type=dift_proposals_distill # {proposals_distill,grid_distill,dift_grid_distill,dift_proposals_distill} +version=declip+ # {declip,declip2,declip+} +mode=csa_vfm_distill +# always keep total batchsize=16 , otherwise, Linear scaling the learning rate +CUDA_VISIBLE_DEVICES=0 torchrun --nproc_per_node 1 --master_port 29500 -m training.main --batch-size=2 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \ +--model EVA02-CLIP-B-16 --pretrained eva --warmup 1000 --zeroshot-frequency 6 --dataset-type ${dataset_type} \ +--test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy --train-image-root ${data_root}/train2017 \ +--val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \ +--name ${exp_name} --downsample-factor 16 --det-image-size 560 --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.7 --mode ${mode} --use_vfm ${vfm_type} --loss_context_weight 0.25 --loss_content_weight 1.0 --loss_region_weight 0.1 --skip-first-eval --repa_layer_idx -1 --sd-refine-weight 1.0 --cache-self-attn sd_self_attn_cache/sd_self_attn_coco.h5 --version ${version} --eval diff --git a/scripts/declip+/dist_DeCLIP+_eva_vitL14_336_coco.sh b/scripts/declip+/dist_DeCLIP+_eva_vitL14_336_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..22102527b5af1c49a6b909b3a4fe34811b6a7c7b --- /dev/null +++ b/scripts/declip+/dist_DeCLIP+_eva_vitL14_336_coco.sh @@ -0,0 +1,17 @@ +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt +exp_name=EVAL_dinov2B_csa_490_plus_exp95_sd0.2_0.1_1.0_0.2 +vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} +dataset_type=dift_grid_distill # {proposals_distill,grid_distill,dift_grid_distill} +version=declip+ # {declip,declip2,declip+} +mode=csa_vfm_distill +# always keep total batchsize=16 , otherwise, Linear scaling the learning rate +CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 29500 -m training.main --batch-size=1 --lr=5e-6 --wd=0.1 --epochs=6 --workers=4 \ +--model EVA02-CLIP-L-14-336 --pretrained eva --warmup 1000 --zeroshot-frequency 1 --dataset-type ${dataset_type} \ +--test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy --train-image-root ${data_root}/train2017 \ +--val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 24 \ +--name ${exp_name} --downsample-factor 14 --det-image-size 490 --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.95 --use_vfm ${vfm_type} --mode ${mode} --loss_context_weight 0.1 --loss_content_weight 1.0 --loss_region_weight 0.2 --skip-first-eval --version ${version} --grad-checkpointing --sd-refine-weight 0.2 --cache-self-attn sd_self_attn_cache/sd_self_attn_coco.h5 \ No newline at end of file diff --git a/scripts/declip+/dist_DeCLIP+_eva_vitL14_336_lvis.sh b/scripts/declip+/dist_DeCLIP+_eva_vitL14_336_lvis.sh new file mode 100644 index 0000000000000000000000000000000000000000..2be5904e42158832f5391a889d2819b797fdf780 --- /dev/null +++ b/scripts/declip+/dist_DeCLIP+_eva_vitL14_336_lvis.sh @@ -0,0 +1,17 @@ +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt +exp_name=EVAL_dinov2B_qq_896_plus_0.1_2.0_1.0_lvis +vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} +dataset_type=grid_distill # {proposals_distill,grid_distill,dift_grid_distill} +mode=qq_vfm_distill + +# always keep total batchsize=16 , otherwise, Linear scaling the learning rate +CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 29500 -m training.main --batch-size=1 --lr=5e-6 --wd=0.1 --epochs=6 --workers=4 \ +--model EVA02-CLIP-L-14-336 --pretrained eva --warmup 1000 --zeroshot-frequency 1 --dataset-type ${dataset_type} \ +--test-type coco_panoptic --train-data ${data_root}/annotations/lvis_v1_train.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy --train-image-root ${data_root} \ +--val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 24 \ +--name ${exp_name} --downsample-factor 14 --det-image-size 896 --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.95 --use_vfm ${vfm_type} --mode ${mode} --loss_context_weight 0.1 --loss_content_weight 2.0 --skip-first-eval --version declip2 --grad-checkpointing \ No newline at end of file diff --git a/scripts/declip+/dist_DeCLIP+_eva_vitb16_coco.sh b/scripts/declip+/dist_DeCLIP+_eva_vitb16_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..c58be497dd29a7d1c4396a176a3b9f651ad23d65 --- /dev/null +++ b/scripts/declip+/dist_DeCLIP+_eva_vitb16_coco.sh @@ -0,0 +1,17 @@ +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt +exp_name=EVA-B_DINOv2-B_csa_560_declip2_0.25_1.0_0.05 +vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} +dataset_type=grid_distill # {proposals_distill,grid_distill,dift_grid_distill,dift_proposals_distill} +version=declip2 # {declip,declip2,declip+} +mode=csa_vfm_distill +# always keep total batchsize=16 , otherwise, Linear scaling the learning rate +CUDA_VISIBLE_DEVICES=0,1,2,3 torchrun --nproc_per_node 4 --master_port 29500 -m training.main --batch-size=4 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \ +--model EVA02-CLIP-B-16 --pretrained eva --warmup 1000 --zeroshot-frequency 6 --dataset-type ${dataset_type} \ +--test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy --train-image-root ${data_root}/train2017 \ +--val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \ +--name ${exp_name} --downsample-factor 16 --det-image-size 560 --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.7 --mode ${mode} --use_vfm ${vfm_type} --loss_context_weight 0.25 --loss_content_weight 1.0 --loss_region_weight 0.05 --skip-first-eval --repa_layer_idx -1 --sd-refine-weight 1.0 --cache-self-attn sd_self_attn_cache/sd_self_attn_coco.h5 --version ${version} diff --git a/scripts/declip+/dist_DeCLIP+_eva_vitb16_coco_seg.sh b/scripts/declip+/dist_DeCLIP+_eva_vitb16_coco_seg.sh new file mode 100644 index 0000000000000000000000000000000000000000..99ecf4b4108ef7e381d8138e43c75a2bd54f8d57 --- /dev/null +++ b/scripts/declip+/dist_DeCLIP+_eva_vitb16_coco_seg.sh @@ -0,0 +1,17 @@ +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt +exp_name=EVA-B_DINOv2-B_csa_560_plus_sd1.0_0.9_1.0_0.3 +vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} +dataset_type=dift_grid_distill # {proposals_distill,grid_distill,dift_grid_distill} +version=declip+ # {declip,declip2,declip+} +mode=csa_vfm_distill +# always keep total batchsize=16 , otherwise, Linear scaling the learning rate +CUDA_VISIBLE_DEVICES=4,5,6,7 torchrun --nproc_per_node 4 --master_port 29501 -m training.main --batch-size=4 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \ +--model EVA02-CLIP-B-16 --pretrained eva --warmup 1000 --zeroshot-frequency 1 --dataset-type ${dataset_type} \ +--test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy --train-image-root ${data_root}/train2017 \ +--val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \ +--name ${exp_name} --downsample-factor 16 --det-image-size 560 --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.7 --mode ${mode} --use_vfm ${vfm_type} --loss_context_weight 0.9 --loss_content_weight 1.0 --loss_region_weight 0.3 --skip-first-eval --repa_layer_idx -1 --sd-refine-weight 1.0 --cache-self-attn sd_self_attn_cache/sd_self_attn_coco.h5 --version ${version} diff --git a/scripts/declip+/dist_DeCLIP+_eva_vitb16_lvis.sh b/scripts/declip+/dist_DeCLIP+_eva_vitb16_lvis.sh new file mode 100644 index 0000000000000000000000000000000000000000..57d16574d68fdc2fda1b307c03252732c0cf5d13 --- /dev/null +++ b/scripts/declip+/dist_DeCLIP+_eva_vitb16_lvis.sh @@ -0,0 +1,17 @@ +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt +exp_name=EVAB_dinov2B_csa_1024_plus_0.05_2.0_1.0_lvis +vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} +dataset_type=grid_distill # {proposals_distill,grid_distill,dift_grid_distill} +mode=csa_vfm_distill + +# always keep total batchsize=16 , otherwise, Linear scaling the learning rate +CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 29500 -m training.main --batch-size=2 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \ +--model EVA02-CLIP-B-16 --pretrained eva --warmup 1000 --zeroshot-frequency 1 --dataset-type ${dataset_type} \ +--test-type coco_panoptic --train-data ${data_root}/annotations/lvis_v1_train.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy --train-image-root ${data_root} \ +--val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \ +--name ${exp_name} --downsample-factor 16 --det-image-size 1024 --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.7 --mode ${mode} --use_vfm ${vfm_type} --loss_context_weight 0.05 --loss_content_weight 2.0 --skip-first-eval --repa_layer_idx -1 --cache-self-attn sd_self_attn_cache/sd_self_attn_coco.h5 --version declip2 diff --git a/scripts/declip/dist_eva_vitL14_336_coco.sh b/scripts/declip/dist_eva_vitL14_336_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..2e8262ae4f0bb3da60d442071c16df38a76661c2 --- /dev/null +++ b/scripts/declip/dist_eva_vitL14_336_coco.sh @@ -0,0 +1,21 @@ +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt +exp_name=mismatch_report +vfm_type=dinov2-L # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} +mode=csa_vfm_distill +GPU_IDS=${GPU_IDS:-4} # 手动指定可用 GPU,例如 "0,1,2,3" +IFS=',' read -r -a GPU_ARR <<< "${GPU_IDS}" +NUM_GPUS=${#GPU_ARR[@]} +[ "${NUM_GPUS}" -lt 1 ] && NUM_GPUS=1 +export CUDA_VISIBLE_DEVICES=${GPU_IDS} + +# always keep total batchsize=16 , otherwise, Linear scaling the learning rate +torchrun --nproc_per_node ${NUM_GPUS} --master_port 29500 -m training.main --batch-size=2 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \ +--model EVA02-CLIP-L-14-336 --pretrained eva --warmup 1000 --zeroshot-frequency 1 --dataset-type grid_distill \ +--test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy --train-image-root ${data_root}/train2017 \ +--val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 24 \ +--name ${exp_name} --downsample-factor 14 --det-image-size 560 --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.95 --use_vfm ${vfm_type} --mode ${mode} --loss_context_weight 0.05 --loss_content_weight 1.0 --repa_layer_idx -1 --eval \ No newline at end of file diff --git a/scripts/declip/dist_eva_vitb16_coco.sh b/scripts/declip/dist_eva_vitb16_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..7b44f84185609de4e674ad7aadfee6f5596223d4 --- /dev/null +++ b/scripts/declip/dist_eva_vitb16_coco.sh @@ -0,0 +1,65 @@ +#!/bin/bash +# DeCLIP 解耦蒸馏 baseline:EVA-CLIP-B/16 多卡训练 +# 用于与 Integrated 集成蒸馏对比,证明解耦蒸馏避免了优化冲突 +# 注意:不使用 SD Attention,与 Integrated 配置对齐 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt +exp_name=DeCLIP_EVA-B_DINOv2-B_560 +vfm_type=dinov2-B +dataset_type=grid_distill +version=declip +mode=csa_vfm_distill + +# Parse arguments for nohup +USE_NOHUP=true +if [[ "$1" == "--nohup" ]] || [[ "$1" == "true" ]]; then + USE_NOHUP=true +fi + +# 多卡训练:总 batch_size=16 +cmd="CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12350 \ + -m training.main \ + --batch-size=2 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=6 \ + --workers=4 \ + --model EVA02-CLIP-B-16 \ + --pretrained eva \ + --warmup 1000 \ + --zeroshot-frequency 6 \ + --dataset-type ${dataset_type} \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --cache-dir ${pretrain_ckpt} \ + --log-every-n-steps 100 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 12 \ + --name ${exp_name} \ + --downsample-factor 16 \ + --det-image-size 560 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode ${mode} \ + --use_vfm ${vfm_type} \ + --loss_context_weight 0.25 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --skip-first-eval \ + --repa_layer_idx -1 \ + --version ${version}" + +if [ "$USE_NOHUP" = true ]; then + LOG_DIR="logs/${exp_name}" + mkdir -p "$LOG_DIR" + echo "Running with nohup. Output will be saved to ${LOG_DIR}/nohup.log" + nohup sh -c "$cmd" > "${LOG_DIR}/nohup.log" 2>&1 & +else + eval $cmd +fi \ No newline at end of file diff --git a/scripts/declip/dist_tinyclip_vitb16_coco.sh b/scripts/declip/dist_tinyclip_vitb16_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..c71074e2086fe4b224488a99c9c9014bf8f1175d --- /dev/null +++ b/scripts/declip/dist_tinyclip_vitb16_coco.sh @@ -0,0 +1,15 @@ +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=checkpoints/tinyclip_autovit45m_32_text18m_laionyfcc400m.pt +exp_name=TinyCLIP_B_Dinov2_B_csa_560_0.25_1.0 +vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} + +# always keep total batchsize=16 , otherwise, Linear scaling the learning rate +python3 -m training.main -m training.main --batch-size=2 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \ +--model TinyCLIP-auto-ViT-45M-32-Text-18M --pretrained laionyfcc400m --warmup 1000 --zeroshot-frequency 1 --dataset-type grid_distill \ +--test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy --train-image-root ${data_root}/train2017 \ +--val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \ +--name ${exp_name} --downsample-factor 16 --det-image-size 560 --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.7 --mode csa_vfm_distill --use_vfm ${vfm_type} --loss_context_weight 0.25 --loss_content_weight 1.0 --version declip \ No newline at end of file diff --git a/scripts/declip/eva_vitb16_coco.sh b/scripts/declip/eva_vitb16_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..42402725074d6788f78cef6ceeea76b481b95e3b --- /dev/null +++ b/scripts/declip/eva_vitb16_coco.sh @@ -0,0 +1,18 @@ +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt +exp_name=EVA_B_DINOv2_B_csa_560_0.25_1.0_test +vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} +mode=csa_vfm_distill + +# Single GPU version for debugging +# Original: 8 GPUs with batch-size=2 each (total batchsize=16) +# Single GPU: batch-size=16 to keep total batchsize=16 +python -m training.main --batch-size=2 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \ +--model EVA02-CLIP-B-16 --pretrained eva --warmup 1000 --zeroshot-frequency 1 --dataset-type grid_distill \ +--test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy --train-image-root ${data_root}/train2017 \ +--val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \ +--name ${exp_name} --downsample-factor 16 --det-image-size 560 --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.7 --mode ${mode} --use_vfm ${vfm_type} --loss_context_weight 0.25 --loss_content_weight 1.0 --version declip diff --git a/scripts/declip/tinyclip_vitb16_coco.sh b/scripts/declip/tinyclip_vitb16_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba52b4cbef488bf11b0f96d0fb2c7cfb2f129d01 --- /dev/null +++ b/scripts/declip/tinyclip_vitb16_coco.sh @@ -0,0 +1,16 @@ +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt +exp_name=evab_dinov2B_csa_560_0.05_2.0 +vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} +dataset_type=grid_distill # {proposals_distill,grid_distill,dift_grid_distill} + +# always keep total batchsize=16 , otherwise, Linear scaling the learning rate +CUDA_VISIBLE_DEVICES=0,1,2,3 torchrun --nproc_per_node 4 --master_port 29500 -m training.main --batch-size=4 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \ +--model EVA02-CLIP-B-16 --pretrained eva --warmup 1000 --zeroshot-frequency 1 --dataset-type ${dataset_type} \ +--test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy --train-image-root ${data_root}/train2017 \ +--val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \ +--name ${exp_name} --downsample-factor 16 --det-image-size 560 --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.7 --mode csa_vfm_distill --use_vfm ${vfm_type} --loss_context_weight 0.05 --loss_content_weight 1.0 \ No newline at end of file diff --git a/scripts/decoupling_ablation/debug_integrated_eva_vitL14_336_coco.sh b/scripts/decoupling_ablation/debug_integrated_eva_vitL14_336_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..32e56a4a4e62bfca0eee3dd3ba522a02c83af642 --- /dev/null +++ b/scripts/decoupling_ablation/debug_integrated_eva_vitL14_336_coco.sh @@ -0,0 +1,46 @@ +#!/bin/bash +# Integrated Distillation 消融实验:EVA-CLIP-L/14-336 单卡调试 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt +exp_name=Debug_Integrated_EVA-L_DINOv2-L_336 +vfm_type=dinov2-L +dataset_type=grid_distill +version=integrated +mode=vanilla + +CUDA_VISIBLE_DEVICES=0 python -m training.main \ + --batch-size=2 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=1 \ + --workers=4 \ + --model EVA02-CLIP-L-14-336 \ + --pretrained eva \ + --warmup 100 \ + --zeroshot-frequency 1 \ + --dataset-type ${dataset_type} \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --cache-dir ${pretrain_ckpt} \ + --log-every-n-steps 10 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 24 \ + --name ${exp_name} \ + --downsample-factor 14 \ + --det-image-size 336 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode ${mode} \ + --use_vfm ${vfm_type} \ + --loss_context_weight 1.0 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --skip-first-eval \ + --repa_layer_idx -1 \ + --version ${version} diff --git a/scripts/decoupling_ablation/debug_integrated_eva_vitb16_coco.sh b/scripts/decoupling_ablation/debug_integrated_eva_vitb16_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..869bf2d4d05ebdb0af0df0dd424eb2f72c92d2d1 --- /dev/null +++ b/scripts/decoupling_ablation/debug_integrated_eva_vitb16_coco.sh @@ -0,0 +1,47 @@ +#!/bin/bash +# Integrated Distillation 消融实验:EVA-CLIP-B/16 单卡调试 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt +exp_name=Debug_Integrated_EVA-B_DINOv2-B_560 +vfm_type=dinov2-B +dataset_type=grid_distill +version=integrated +mode=vanilla + +# 单卡调试 +CUDA_VISIBLE_DEVICES=0 python -m training.main \ + --batch-size=4 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=1 \ + --workers=4 \ + --model EVA02-CLIP-B-16 \ + --pretrained eva \ + --warmup 100 \ + --zeroshot-frequency 1 \ + --dataset-type ${dataset_type} \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --cache-dir ${pretrain_ckpt} \ + --log-every-n-steps 10 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 12 \ + --name ${exp_name} \ + --downsample-factor 16 \ + --det-image-size 560 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode ${mode} \ + --use_vfm ${vfm_type} \ + --loss_context_weight 1.0 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --skip-first-eval \ + --repa_layer_idx -1 \ + --version ${version} diff --git a/scripts/decoupling_ablation/debug_integrated_openai_vitL14_coco.sh b/scripts/decoupling_ablation/debug_integrated_openai_vitL14_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..885a138014a61a5154c3ca6737a69d011ee1c917 --- /dev/null +++ b/scripts/decoupling_ablation/debug_integrated_openai_vitL14_coco.sh @@ -0,0 +1,44 @@ +#!/bin/bash +# Integrated Distillation 消融实验:OpenAI-CLIP-L/14 单卡调试 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +exp_name=Debug_Integrated_OpenAI-L_DINOv2-L_336 +vfm_type=dinov2-L +dataset_type=grid_distill +version=integrated +mode=vanilla + +CUDA_VISIBLE_DEVICES=0 python -m training.main \ + --batch-size=2 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=1 \ + --workers=4 \ + --model ViT-L-14 \ + --pretrained openai \ + --warmup 100 \ + --zeroshot-frequency 1 \ + --dataset-type ${dataset_type} \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_ViTL14.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --log-every-n-steps 10 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 24 \ + --name ${exp_name} \ + --downsample-factor 14 \ + --det-image-size 336 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode ${mode} \ + --use_vfm ${vfm_type} \ + --loss_context_weight 1.0 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --skip-first-eval \ + --repa_layer_idx -1 \ + --version ${version} diff --git a/scripts/decoupling_ablation/debug_integrated_openai_vitb16_coco.sh b/scripts/decoupling_ablation/debug_integrated_openai_vitb16_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..051cc4edb204586120443694f3f3e20cc3474eb7 --- /dev/null +++ b/scripts/decoupling_ablation/debug_integrated_openai_vitb16_coco.sh @@ -0,0 +1,44 @@ +#!/bin/bash +# Integrated Distillation 消融实验:OpenAI-CLIP-B/16 单卡调试 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +exp_name=Debug_Integrated_OpenAI-B_DINOv2-B_560 +vfm_type=dinov2-B +dataset_type=grid_distill +version=integrated +mode=vanilla + +CUDA_VISIBLE_DEVICES=0 python -m training.main \ + --batch-size=4 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=1 \ + --workers=4 \ + --model ViT-B-16 \ + --pretrained openai \ + --warmup 100 \ + --zeroshot-frequency 1 \ + --dataset-type ${dataset_type} \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_ViTB16.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --log-every-n-steps 10 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 12 \ + --name ${exp_name} \ + --downsample-factor 16 \ + --det-image-size 560 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode ${mode} \ + --use_vfm ${vfm_type} \ + --loss_context_weight 1.0 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --skip-first-eval \ + --repa_layer_idx -1 \ + --version ${version} diff --git a/scripts/decoupling_ablation/dist_integrated_eva_vitL14_336_coco.sh b/scripts/decoupling_ablation/dist_integrated_eva_vitL14_336_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..0d047ad4b982931ed9d3677fc4a517429e4cdc0c --- /dev/null +++ b/scripts/decoupling_ablation/dist_integrated_eva_vitL14_336_coco.sh @@ -0,0 +1,61 @@ +#!/bin/bash +# Integrated Distillation 消融实验:EVA-CLIP-L/14-336 多卡训练 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt +exp_name=Integrated_EVA-L_DINOv2-L_336 +vfm_type=dinov2-L +dataset_type=grid_distill +version=integrated +mode=vanilla + +USE_NOHUP=true +if [[ "$1" == "--nohup" ]] || [[ "$1" == "true" ]]; then + USE_NOHUP=true +fi + +cmd="CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12367 \ + -m training.main \ + --batch-size=2 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=6 \ + --workers=4 \ + --model EVA02-CLIP-L-14-336 \ + --pretrained eva \ + --warmup 1000 \ + --zeroshot-frequency 6 \ + --dataset-type ${dataset_type} \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --cache-dir ${pretrain_ckpt} \ + --log-every-n-steps 100 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 24 \ + --name ${exp_name} \ + --downsample-factor 14 \ + --det-image-size 560 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode ${mode} \ + --use_vfm ${vfm_type} \ + --loss_context_weight 1.0 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --skip-first-eval \ + --repa_layer_idx -1 \ + --version ${version}" + +if [ "$USE_NOHUP" = true ]; then + LOG_DIR="logs/${exp_name}" + mkdir -p "$LOG_DIR" + echo "Running with nohup. Output will be saved to ${LOG_DIR}/nohup.log" + nohup sh -c "$cmd" > "${LOG_DIR}/nohup.log" 2>&1 & +else + eval $cmd +fi diff --git a/scripts/decoupling_ablation/dist_integrated_eva_vitb16_coco.sh b/scripts/decoupling_ablation/dist_integrated_eva_vitb16_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..ce1fe8ddfe8505e8101e775064bfe0bf2402d238 --- /dev/null +++ b/scripts/decoupling_ablation/dist_integrated_eva_vitb16_coco.sh @@ -0,0 +1,69 @@ +#!/bin/bash +# Integrated Distillation 消融实验:EVA-CLIP-B/16 多卡训练 +# 对比 DeCLIP 解耦蒸馏,用于证明解耦蒸馏避免了优化冲突 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt +vfm_type=dinov2-B +dataset_type=grid_distill +version=integrated_grad_analysis +mode=vanilla + +# 根据 version 设置实验名称 +if [[ "$version" == "integrated_grad_analysis" ]]; then + exp_name=Integrated_EVA-B_DINOv2-B_560_grad_analysis_2loss +else + exp_name=Integrated_EVA-B_DINOv2-B_560_2loss +fi + +# Parse arguments for nohup +USE_NOHUP=true +if [[ "$1" == "--nohup" ]] || [[ "$1" == "true" ]]; then + USE_NOHUP=true +fi + +# 多卡训练:总 batch_size=16 +cmd="CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12348 \ + -m training.main \ + --batch-size=2 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=6 \ + --workers=4 \ + --model EVA02-CLIP-B-16 \ + --pretrained eva \ + --warmup 1000 \ + --zeroshot-frequency 6 \ + --dataset-type ${dataset_type} \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --cache-dir ${pretrain_ckpt} \ + --log-every-n-steps 100 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 12 \ + --name ${exp_name} \ + --downsample-factor 16 \ + --det-image-size 560 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode ${mode} \ + --use_vfm ${vfm_type} \ + --loss_context_weight 0.25 \ + --loss_content_weight 1.0 \ + --skip-first-eval \ + --repa_layer_idx -1 \ + --version ${version}" + +if [ "$USE_NOHUP" = true ]; then + LOG_DIR="logs/${exp_name}" + mkdir -p "$LOG_DIR" + echo "Running with nohup. Output will be saved to ${LOG_DIR}/nohup.log" + nohup sh -c "$cmd" > "${LOG_DIR}/nohup.log" 2>&1 & +else + eval $cmd +fi diff --git a/scripts/decoupling_ablation/dist_integrated_openai_vitL14_coco.sh b/scripts/decoupling_ablation/dist_integrated_openai_vitL14_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..f74fd4eb14152a435396911822efb402c902607c --- /dev/null +++ b/scripts/decoupling_ablation/dist_integrated_openai_vitL14_coco.sh @@ -0,0 +1,59 @@ +#!/bin/bash +# Integrated Distillation 消融实验:OpenAI-CLIP-L/14 多卡训练 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +exp_name=Integrated_OpenAI-L_DINOv2-L_336 +vfm_type=dinov2-L +dataset_type=grid_distill +version=integrated +mode=vanilla + +USE_NOHUP=true +if [[ "$1" == "--nohup" ]] || [[ "$1" == "true" ]]; then + USE_NOHUP=true +fi + +cmd="CUDA_VISIBLE_DEVICES=0,1,2,3 torchrun --nproc_per_node 4 --master_port 29505 \ + -m training.main \ + --batch-size=4 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=6 \ + --workers=4 \ + --model ViT-L-14 \ + --pretrained openai \ + --warmup 1000 \ + --zeroshot-frequency 6 \ + --dataset-type ${dataset_type} \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_ViTL14.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --log-every-n-steps 100 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 24 \ + --name ${exp_name} \ + --downsample-factor 14 \ + --det-image-size 336 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode ${mode} \ + --use_vfm ${vfm_type} \ + --loss_context_weight 1.0 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --skip-first-eval \ + --repa_layer_idx -1 \ + --version ${version}" + +if [ "$USE_NOHUP" = true ]; then + LOG_DIR="logs/${exp_name}" + mkdir -p "$LOG_DIR" + echo "Running with nohup. Output will be saved to ${LOG_DIR}/nohup.log" + nohup sh -c "$cmd" > "${LOG_DIR}/nohup.log" 2>&1 & +else + eval $cmd +fi diff --git a/scripts/decoupling_ablation/dist_integrated_openai_vitb16_coco.sh b/scripts/decoupling_ablation/dist_integrated_openai_vitb16_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..a46e6ccfa5bb39af686ff9d5f85e723c5b6cd9a7 --- /dev/null +++ b/scripts/decoupling_ablation/dist_integrated_openai_vitb16_coco.sh @@ -0,0 +1,60 @@ +#!/bin/bash +# Integrated Distillation 消融实验:OpenAI-CLIP-B/16 多卡训练 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +exp_name=Integrated_OpenAI-B_DINOv2-B_560 +vfm_type=dinov2-B +dataset_type=grid_distill +version=integrated +mode=vanilla + +USE_NOHUP=true +if [[ "$1" == "--nohup" ]] || [[ "$1" == "true" ]]; then + USE_NOHUP=true +fi + +# 多卡训练:总 batch_size=16 +cmd="CUDA_VISIBLE_DEVICES=0,1,2,3 torchrun --nproc_per_node 4 --master_port 29504 \ + -m training.main \ + --batch-size=4 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=6 \ + --workers=4 \ + --model ViT-B-16 \ + --pretrained openai \ + --warmup 1000 \ + --zeroshot-frequency 6 \ + --dataset-type ${dataset_type} \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_ViTB16.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --log-every-n-steps 100 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 12 \ + --name ${exp_name} \ + --downsample-factor 16 \ + --det-image-size 560 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode ${mode} \ + --use_vfm ${vfm_type} \ + --loss_context_weight 1.0 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --skip-first-eval \ + --repa_layer_idx -1 \ + --version ${version}" + +if [ "$USE_NOHUP" = true ]; then + LOG_DIR="logs/${exp_name}" + mkdir -p "$LOG_DIR" + echo "Running with nohup. Output will be saved to ${LOG_DIR}/nohup.log" + nohup sh -c "$cmd" > "${LOG_DIR}/nohup.log" 2>&1 & +else + eval $cmd +fi diff --git a/scripts/decoupling_ablation/resume_all_experiments.sh b/scripts/decoupling_ablation/resume_all_experiments.sh new file mode 100644 index 0000000000000000000000000000000000000000..72f7b3727cac7e0a4dbac671085a0e28dcc418cd --- /dev/null +++ b/scripts/decoupling_ablation/resume_all_experiments.sh @@ -0,0 +1,92 @@ +#!/bin/bash +# Resume 所有因 evaluation bug 中断的实验 +# Bug 已修复:src/training/data.py 第 715 行 np.asarray -> np.array + +set -e + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt + +# 选择要 resume 的实验 +# 1: Integrated_EVA-B_DINOv2-B_560 +# 2: Integrated_EVA-B_DINOv2-B_560_grad_analysis +# all: 两个都跑 +EXPERIMENT=${1:-"all"} + +resume_integrated() { + local exp_name=$1 + local version=$2 + local resume_ckpt="logs/${exp_name}/checkpoints/epoch_5.pt" + + if [ ! -f "$resume_ckpt" ]; then + echo "Checkpoint not found: $resume_ckpt" + return 1 + fi + + echo "==============================================" + echo "Resuming: $exp_name" + echo "Checkpoint: $resume_ckpt" + echo "==============================================" + + CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12349 \ + -m training.main \ + --batch-size=2 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=6 \ + --workers=4 \ + --model EVA02-CLIP-B-16 \ + --pretrained eva \ + --warmup 1000 \ + --zeroshot-frequency 6 \ + --dataset-type grid_distill \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --cache-dir ${pretrain_ckpt} \ + --log-every-n-steps 100 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 12 \ + --name ${exp_name} \ + --downsample-factor 16 \ + --det-image-size 560 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode vanilla \ + --use_vfm dinov2-B \ + --loss_context_weight 1.0 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --repa_layer_idx -1 \ + --version ${version} \ + --resume ${resume_ckpt} +} + +cd /opt/tiger/xiaomoguhzz/DeCLIP_private + +case $EXPERIMENT in + "1"|"integrated") + resume_integrated "Integrated_EVA-B_DINOv2-B_560" "integrated" + ;; + "2"|"grad_analysis") + resume_integrated "Integrated_EVA-B_DINOv2-B_560_grad_analysis" "integrated_grad_analysis" + ;; + "all") + echo "Resuming all experiments sequentially..." + resume_integrated "Integrated_EVA-B_DINOv2-B_560" "integrated" + resume_integrated "Integrated_EVA-B_DINOv2-B_560_grad_analysis" "integrated_grad_analysis" + ;; + *) + echo "Usage: $0 [1|integrated|2|grad_analysis|all]" + echo " 1/integrated - Resume Integrated_EVA-B_DINOv2-B_560" + echo " 2/grad_analysis - Resume Integrated_EVA-B_DINOv2-B_560_grad_analysis" + echo " all - Resume all experiments" + exit 1 + ;; +esac + +echo "Done!" diff --git a/scripts/decoupling_ablation/resume_integrated.sh b/scripts/decoupling_ablation/resume_integrated.sh new file mode 100644 index 0000000000000000000000000000000000000000..cbc8ed3f5c918b79027d6af781661697fe6fd1ec --- /dev/null +++ b/scripts/decoupling_ablation/resume_integrated.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# Resume Integrated_EVA-B_DINOv2-B_560 实验 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt +exp_name=Integrated_EVA-B_DINOv2-B_560 +resume_ckpt=logs/${exp_name}/checkpoints/epoch_5.pt + +cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private + +echo "Resuming: $exp_name" +echo "Checkpoint: $resume_ckpt" + +CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12349 \ + -m training.main \ + --batch-size=2 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=6 \ + --workers=4 \ + --model EVA02-CLIP-B-16 \ + --pretrained eva \ + --warmup 1000 \ + --zeroshot-frequency 6 \ + --dataset-type grid_distill \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --cache-dir ${pretrain_ckpt} \ + --log-every-n-steps 100 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 12 \ + --name ${exp_name} \ + --downsample-factor 16 \ + --det-image-size 560 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode vanilla \ + --use_vfm dinov2-B \ + --loss_context_weight 1.0 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --repa_layer_idx -1 \ + --version integrated \ + --resume ${resume_ckpt} diff --git a/scripts/decoupling_ablation/resume_integrated_grad_analysis.sh b/scripts/decoupling_ablation/resume_integrated_grad_analysis.sh new file mode 100644 index 0000000000000000000000000000000000000000..5eb1b4412487ed65d8cf612fcdc85ef43d77c9d5 --- /dev/null +++ b/scripts/decoupling_ablation/resume_integrated_grad_analysis.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# Resume Integrated_EVA-B_DINOv2-B_560_grad_analysis 实验 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt +exp_name=Integrated_EVA-B_DINOv2-B_560_grad_analysis +resume_ckpt=logs/${exp_name}/checkpoints/epoch_5.pt + +cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private + +echo "Resuming: $exp_name" +echo "Checkpoint: $resume_ckpt" + +CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12345 \ + -m training.main \ + --batch-size=2 \ + --lr=1e-5 \ + --wd=0.1 \ + --epochs=6 \ + --workers=4 \ + --model EVA02-CLIP-B-16 \ + --pretrained eva \ + --warmup 1000 \ + --zeroshot-frequency 6 \ + --dataset-type grid_distill \ + --test-type coco_panoptic \ + --train-data ${data_root}/annotations/instances_train2017.json \ + --val-data ${data_root}/annotations/panoptic_val2017.json \ + --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy \ + --train-image-root ${data_root}/train2017 \ + --val-image-root ${data_root}/val2017 \ + --cache-dir ${pretrain_ckpt} \ + --log-every-n-steps 100 \ + --lock-image \ + --save-frequency 1 \ + --lock-image-unlocked-groups 12 \ + --name ${exp_name} \ + --downsample-factor 16 \ + --det-image-size 560 \ + --val-segm-root ${data_root}/annotations/panoptic_val2017 \ + --alpha 0.7 \ + --mode vanilla \ + --use_vfm dinov2-B \ + --loss_context_weight 1.0 \ + --loss_content_weight 1.0 \ + --loss_region_weight 0.05 \ + --repa_layer_idx -1 \ + --version integrated_grad_analysis \ + --resume ${resume_ckpt} diff --git a/scripts/decoupling_ablation/train_integrated_L_ovcoco.sh b/scripts/decoupling_ablation/train_integrated_L_ovcoco.sh new file mode 100644 index 0000000000000000000000000000000000000000..720efc8e43f1d39b9e6539ff20f669f4c2149e4b --- /dev/null +++ b/scripts/decoupling_ablation/train_integrated_L_ovcoco.sh @@ -0,0 +1,45 @@ +#!/bin/bash +# Integrated EVA-L/14-336 OV-COCO 训练脚本 +# 使用 Integrated 蒸馏得到的 checkpoint 进行目标检测微调 + +set -e + +# 配置 +GPUS=${1:-8} +CONFIG="configs/declip/fvit_vitl14_upsample_fpn_bs64_3e_ovcoco_integrated.py" +WORK_DIR="work_dirs/integrated_L_ovcoco" + +# 切换到 F-ViT 目录 +cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT + +echo "==============================================" +echo "Integrated EVA-L/14-336 OV-COCO Training" +echo "==============================================" +echo "Config: ${CONFIG}" +echo "GPUs: ${GPUS}" +echo "Work Dir: ${WORK_DIR}" +echo "==============================================" + +# 检查 checkpoint 是否存在 +CKPT="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/logs/Integrated_EVA-L_DINOv2-L_336/checkpoints/epoch_6.pt" +if [ ! -f "$CKPT" ]; then + echo "Error: Integrated checkpoint not found: $CKPT" + exit 1 +fi +echo "Using Integrated checkpoint: $CKPT" + +# 检查 class_embed 是否存在 +CLASS_EMBED="datasets/embeddings/coco_with_background_evaclip_vitl14x336.pt" +if [ ! -f "$CLASS_EMBED" ]; then + echo "Error: Class embedding not found: $CLASS_EMBED" + exit 1 +fi +echo "Using class embedding: $CLASS_EMBED" + +# 运行训练 +bash dist_train.sh ${CONFIG} ${GPUS} --work-dir ${WORK_DIR} ${@:2} + +echo "==============================================" +echo "Training completed!" +echo "Results saved to: ${WORK_DIR}" +echo "==============================================" diff --git a/scripts/openai_declip+/DeCLIP+_openai_vitb16_coco.sh b/scripts/openai_declip+/DeCLIP+_openai_vitb16_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..78178e31d6d595abde79cf1572df1815256bda8a --- /dev/null +++ b/scripts/openai_declip+/DeCLIP+_openai_vitb16_coco.sh @@ -0,0 +1,16 @@ +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt +exp_name=test +vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} +dataset_type=dift_proposals_distill # {proposals_distill,grid_distill,dift_grid_distill,dift_proposals_distill} +version=declip+ # {declip,declip2,declip+} +# always keep total batchsize=16 , otherwise, Linear scaling the learning rate +CUDA_VISIBLE_DEVICES=7 torchrun --nproc_per_node 1 --master_port 29501 -m training.main --batch-size=2 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \ +--model ViT-B-16 --pretrained openai --warmup 1000 --zeroshot-frequency 6 --dataset-type ${dataset_type} \ +--test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy --train-image-root ${data_root}/train2017 \ +--val-image-root ${data_root}/val2017 --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \ +--name ${exp_name} --downsample-factor 16 --det-image-size 560 --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.7 --mode csa_vfm_distill --use_vfm ${vfm_type} --loss_context_weight 0.25 --loss_content_weight 1.0 --loss_region_weight 0.1 --skip-first-eval --repa_layer_idx -1 --sd-refine-weight 1.0 --cache-self-attn sd_self_attn_cache/sd_self_attn_coco.h5 --version ${version} --resume logs/OPENAI-B_DINOv2-B_csa_560_declip+_0.25_1.0_0.3/checkpoints/epoch_6.pt --eval diff --git a/scripts/openai_declip+/dist_DeCLIP+_openai_vitb16_coco.sh b/scripts/openai_declip+/dist_DeCLIP+_openai_vitb16_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..8eb569dd859d9b228732fe1fb18e0693dae0ca16 --- /dev/null +++ b/scripts/openai_declip+/dist_DeCLIP+_openai_vitb16_coco.sh @@ -0,0 +1,15 @@ +data_root=/opt/tiger/xiaomoguhzz/standard_coco +exp_name=OPENAI-B_DINOv2-B_csa_560_declip+_0.25_1.0_0.3 +vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} +dataset_type=proposals_distill # {proposals_distill,grid_distill,dift_grid_distill,dift_proposals_distill} +version=declip2 # {declip,declip2,declip+} +# always keep total batchsize=16 , otherwise, Linear scaling the learning rate +CUDA_VISIBLE_DEVICES=0,1,2,3 torchrun --nproc_per_node 4 --master_port 29500 -m training.main --batch-size=4 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \ +--model ViT-B-16 --pretrained openai --warmup 1000 --zeroshot-frequency 6 --dataset-type ${dataset_type} \ +--test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path metadata/coco_panoptic_clip_hand_craft_ViTB16.npy --train-image-root ${data_root}/train2017 \ +--val-image-root ${data_root}/val2017 --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \ +--name ${exp_name} --downsample-factor 16 --det-image-size 560 --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.7 --mode csa_vfm_distill --use_vfm ${vfm_type} --loss_context_weight 0.05 --loss_content_weight 2.0 --loss_region_weight 1.0 --skip-first-eval --repa_layer_idx -1 --sd-refine-weight 1.0 --cache-self-attn sd_self_attn_cache/sd_self_attn_coco.h5 --version ${version} --resume logs/OPENAI-B_DINOv2-B_csa_560_declip+_0.25_1.0_0.3/checkpoints/epoch_6.pt --eval diff --git a/scripts/tinyclip/dist_tinyclip_vit39m_coco.sh b/scripts/tinyclip/dist_tinyclip_vit39m_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..4d08e5554a1ca947742200e3b6345f0bdbadd678 --- /dev/null +++ b/scripts/tinyclip/dist_tinyclip_vit39m_coco.sh @@ -0,0 +1,32 @@ +# GPU selection for multi-GPU training (e.g., 0,1,2,3,4,5,6,7 for 8 GPUs) +# Note: For distributed training, torchrun will automatically use all available GPUs +# You can still use CUDA_VISIBLE_DEVICES to limit which GPUs are visible +gpu=2,4,5,6 + +# Training parameters +# Mode options: qq, kk, vv, csa, qq_vfm_distill, kk_vfm_distill, vv_vfm_distill, csa_vfm_distill, all_vfm_distill, maskclip, vanilla, sanity_check +mode=csa_vfm_distill +det_image_size=560 +loss_context_weight=0.25 +loss_content_weight=1.0 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt +vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} +model_name=TinyCLIP-ViT-39M-16-Text-19M +embed_path=metadata/coco_panoptic_clip_hand_craft_TinyCLIP-ViT-39M-16-Text-19M.npy +# Extract mode name for exp_name (remove _vfm_distill suffix if present) +mode_name=${mode%_vfm_distill} +exp_name=TinyCLIP_39M_dinov2B_${mode_name}_${det_image_size}_${loss_context_weight}_${loss_content_weight}_alpha0.5 + +# always keep total batchsize=16 , otherwise, Linear scaling the learning rate +CUDA_VISIBLE_DEVICES=${gpu} torchrun --nproc_per_node 4 --master_port 12345 -m training.main --batch-size=4 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \ +--model ${model_name} --pretrained ${pretrain_ckpt} --warmup 1000 --zeroshot-frequency 1 --dataset-type grid_distill \ +--test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path ${embed_path} --train-image-root ${data_root}/train2017 \ +--val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \ +--name ${exp_name} --downsample-factor 16 --det-image-size ${det_image_size} --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.5 --mode ${mode} --use_vfm ${vfm_type} --loss_context_weight ${loss_context_weight} --loss_content_weight ${loss_content_weight} --version declip --skip-first-eval + diff --git a/scripts/tinyclip/dist_tinyclip_vit63m_coco.sh b/scripts/tinyclip/dist_tinyclip_vit63m_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c02690385993367597298a9823d679a4e34f76a --- /dev/null +++ b/scripts/tinyclip/dist_tinyclip_vit63m_coco.sh @@ -0,0 +1,17 @@ +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=checkpoints/TinyCLIP-auto-ViT-63M-32-Text-31M-LAIONYFCC400M.pt +exp_name=TinyCLIP_63M_dinov2B_csa_560_0.25_1.0 +vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} +model_name=TinyCLIP-auto-ViT-63M-32-Text-31M +embed_path=metadata/coco_panoptic_clip_hand_craft_TinyCLIP-auto-ViT-63M-32-Text-31M.npy + +# always keep total batchsize=16 , otherwise, Linear scaling the learning rate +torchrun --nproc_per_node 8 --master_port 12345 -m training.main --batch-size=2 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \ +--model ${model_name} --pretrained ${pretrain_ckpt} --warmup 1000 --zeroshot-frequency 1 --dataset-type grid_distill \ +--test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path ${embed_path} --train-image-root ${data_root}/train2017 \ +--val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \ +--name ${exp_name} --downsample-factor 16 --det-image-size 560 --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.7 --mode csa_vfm_distill --use_vfm ${vfm_type} --loss_context_weight 0.25 --loss_content_weight 1.0 --version declip \ No newline at end of file diff --git a/scripts/tinyclip/tinyclip_vit39m_coco.sh b/scripts/tinyclip/tinyclip_vit39m_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..b4f5a6196d1b6700580596a02eb7004ab650be35 --- /dev/null +++ b/scripts/tinyclip/tinyclip_vit39m_coco.sh @@ -0,0 +1,30 @@ +# GPU selection (e.g., 0, 1, 2, 3 or 0,1 for multiple GPUs) +gpu=1 + +# Training parameters +# Mode options: qq, kk, vv, csa, qq_vfm_distill, kk_vfm_distill, vv_vfm_distill, csa_vfm_distill, all_vfm_distill, maskclip, vanilla, sanity_check +mode=csa_vfm_distill +det_image_size=560 +loss_context_weight=0.25 +loss_content_weight=1.0 + +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt +vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} +model_name=TinyCLIP-ViT-39M-16-Text-19M +embed_path=metadata/coco_panoptic_clip_hand_craft_TinyCLIP-ViT-39M-16-Text-19M.npy +# Extract mode name for exp_name (remove _vfm_distill suffix if present) +mode_name=${mode%_vfm_distill} +exp_name=TinyCLIP_39M_dinov2B_${mode_name}_${det_image_size}_${loss_context_weight}_${loss_content_weight} + +# Single GPU for debugging +CUDA_VISIBLE_DEVICES=${gpu} python -m training.main --batch-size=2 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \ +--model ${model_name} --pretrained ${pretrain_ckpt} --warmup 1000 --zeroshot-frequency 1 --dataset-type grid_distill \ +--test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path ${embed_path} --train-image-root ${data_root}/train2017 \ +--val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \ +--name ${exp_name} --downsample-factor 16 --det-image-size ${det_image_size} --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.7 --mode ${mode} --use_vfm ${vfm_type} --loss_context_weight ${loss_context_weight} --loss_content_weight ${loss_content_weight} --version declip + diff --git a/scripts/tinyclip/tinyclip_vit63m_coco.sh b/scripts/tinyclip/tinyclip_vit63m_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..eb7a225f312a9efff9faa0be9a77eeaaa8f950bf --- /dev/null +++ b/scripts/tinyclip/tinyclip_vit63m_coco.sh @@ -0,0 +1,17 @@ +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=checkpoints/TinyCLIP-auto-ViT-63M-32-Text-31M-LAIONYFCC400M.pt +exp_name=TinyCLIP_63M_dinov2B_csa_560_0.25_1.0 +vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} +model_name=TinyCLIP-auto-ViT-63M-32-Text-31M +embed_path=metadata/coco_panoptic_clip_hand_craft_TinyCLIP-auto-ViT-63M-32-Text-31M.npy + +# Single GPU for debugging +python -m training.main --batch-size=2 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \ +--model ${model_name} --pretrained ${pretrain_ckpt} --warmup 1000 --zeroshot-frequency 1 --dataset-type grid_distill \ +--test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path ${embed_path} --train-image-root ${data_root}/train2017 \ +--val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \ +--name ${exp_name} --downsample-factor 16 --det-image-size 560 --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.7 --mode csa_vfm_distill --use_vfm ${vfm_type} --loss_context_weight 0.25 --loss_content_weight 1.0 --version declip \ No newline at end of file diff --git a/scripts/tinyclip_declip_plus/dist_tinyclip_vit39m_coco.sh b/scripts/tinyclip_declip_plus/dist_tinyclip_vit39m_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cd84d044958e351d7d653343a14b88c4287972e --- /dev/null +++ b/scripts/tinyclip_declip_plus/dist_tinyclip_vit39m_coco.sh @@ -0,0 +1,45 @@ +# GPU selection for multi-GPU training (e.g., 0,1,2,3,4,5,6,7 for 8 GPUs) +# Note: For distributed training, torchrun will automatically use all available GPUs +# You can still use CUDA_VISIBLE_DEVICES to limit which GPUs are visible +gpu=4,5,6,7 + +# Training parameters +# Mode options: qq, kk, vv, csa, qq_vfm_distill, kk_vfm_distill, vv_vfm_distill, csa_vfm_distill, all_vfm_distill, maskclip, vanilla, sanity_check +mode=csa_vfm_distill +det_image_size=560 +loss_context_weight=0.25 +loss_content_weight=1.0 +loss_region_weight=0.05 + +# DeCLIP_PLUS specific parameters +sd_refine_weight=1.0 +repa_layer_idx=-1 # -1 means not using REPA, set to layer index if using REPA +cache_self_attn=/mnt/SSD8T/home/wjj/code/DeCLIP/sd_self_attn_cache/sd_self_attn_coco.h5 # Path to SD self-attention cache + +# Dataset and model paths +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt +vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} +model_name=TinyCLIP-ViT-39M-16-Text-19M +embed_path=metadata/coco_panoptic_clip_hand_craft_TinyCLIP-ViT-39M-16-Text-19M.npy + +# Dataset type: dift_grid_distill or dift_proposals_distill (both support sd_attn) +dataset_type=dift_grid_distill + +# Extract mode name for exp_name (remove _vfm_distill suffix if present) +mode_name=${mode%_vfm_distill} +exp_name=TinyCLIP_39M_DeCLIP+_dinov2B_${mode_name}_${det_image_size}_${loss_context_weight}_${loss_content_weight}_${loss_region_weight}_alpha0.4 + +# always keep total batchsize=16 , otherwise, Linear scaling the learning rate +CUDA_VISIBLE_DEVICES=${gpu} torchrun --nproc_per_node 4 --master_port 12345 -m training.main --batch-size=4 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \ +--model ${model_name} --pretrained ${pretrain_ckpt} --warmup 1000 --zeroshot-frequency 1 --dataset-type ${dataset_type} \ +--test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path ${embed_path} --train-image-root ${data_root}/train2017 \ +--val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \ +--name ${exp_name} --downsample-factor 16 --det-image-size ${det_image_size} --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.4 --mode ${mode} --use_vfm ${vfm_type} \ +--loss_context_weight ${loss_context_weight} --loss_content_weight ${loss_content_weight} --loss_region_weight ${loss_region_weight} \ +--version declip+ --cache-self-attn ${cache_self_attn} --sd-refine-weight ${sd_refine_weight} --repa_layer_idx ${repa_layer_idx} --skip-first-eval + diff --git a/scripts/tinyclip_declip_plus/tinyclip_vit39m_coco.sh b/scripts/tinyclip_declip_plus/tinyclip_vit39m_coco.sh new file mode 100644 index 0000000000000000000000000000000000000000..bada228d2dc2386a0bd8bd87476e4bf0c466a06c --- /dev/null +++ b/scripts/tinyclip_declip_plus/tinyclip_vit39m_coco.sh @@ -0,0 +1,43 @@ +# GPU selection (e.g., 0, 1, 2, 3 or 0,1 for multiple GPUs) +gpu=1 + +# Training parameters +# Mode options: qq, kk, vv, csa, qq_vfm_distill, kk_vfm_distill, vv_vfm_distill, csa_vfm_distill, all_vfm_distill, maskclip, vanilla, sanity_check +mode=csa_vfm_distill +det_image_size=560 +loss_context_weight=0.25 +loss_content_weight=1.0 +loss_region_weight=0.1 + +# DeCLIP_PLUS specific parameters +sd_refine_weight=1.0 +repa_layer_idx=-1 # -1 means not using REPA, set to layer index if using REPA +cache_self_attn=/mnt/SSD8T/home/wjj/code/DeCLIP/sd_self_attn_cache/sd_self_attn_coco.h5 # Path to SD self-attention cache + +# Dataset and model paths +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt +vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} +model_name=TinyCLIP-ViT-39M-16-Text-19M +embed_path=metadata/coco_panoptic_clip_hand_craft_TinyCLIP-ViT-39M-16-Text-19M.npy + +# Dataset type: dift_grid_distill or dift_proposals_distill (both support sd_attn) +dataset_type=dift_grid_distill + +# Extract mode name for exp_name (remove _vfm_distill suffix if present) +mode_name=${mode%_vfm_distill} +exp_name=TinyCLIP_39M_DeCLIP+_dinov2B_${mode_name}_${det_image_size}_${loss_context_weight}_${loss_content_weight}_${loss_region_weight} + +# Single GPU for debugging +CUDA_VISIBLE_DEVICES=${gpu} python -m training.main --batch-size=2 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \ +--model ${model_name} --pretrained ${pretrain_ckpt} --warmup 1000 --zeroshot-frequency 1 --dataset-type ${dataset_type} \ +--test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path ${embed_path} --train-image-root ${data_root}/train2017 \ +--val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \ +--name ${exp_name} --downsample-factor 16 --det-image-size ${det_image_size} --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.7 --mode ${mode} --use_vfm ${vfm_type} \ +--loss_context_weight ${loss_context_weight} --loss_content_weight ${loss_content_weight} --loss_region_weight ${loss_region_weight} \ +--version declip+ --cache-self-attn ${cache_self_attn} --sd-refine-weight ${sd_refine_weight} --repa_layer_idx ${repa_layer_idx} + diff --git a/scripts/tmp_script/dist_DeCLIP+_eva_vitb16_coco_1.sh b/scripts/tmp_script/dist_DeCLIP+_eva_vitb16_coco_1.sh new file mode 100644 index 0000000000000000000000000000000000000000..27ba1bf138c5509855f2e18d6d0cf2fec7d65409 --- /dev/null +++ b/scripts/tmp_script/dist_DeCLIP+_eva_vitb16_coco_1.sh @@ -0,0 +1,16 @@ +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt +exp_name=EVA-B_DINOv2-B_csa_1024_declip2_0.0_2.0_0.1 +vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} +dataset_type=proposals_distill # {proposals_distill,grid_distill,dift_grid_distill} +version=declip2 # {declip,declip2,declip+} +# always keep total batchsize=16 , otherwise, Linear scaling the learning rate +CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 29500 -m training.main --batch-size=2 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \ +--model EVA02-CLIP-B-16 --pretrained eva --warmup 1000 --zeroshot-frequency 6 --dataset-type ${dataset_type} \ +--test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy --train-image-root ${data_root}/train2017 \ +--val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \ +--name ${exp_name} --downsample-factor 16 --det-image-size 1024 --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.7 --mode csa_vfm_distill --use_vfm ${vfm_type} --loss_context_weight 0.0 --loss_content_weight 2.0 --loss_region_weight 0.1 --skip-first-eval --repa_layer_idx -1 --sd-refine-weight 1.0 --cache-self-attn sd_self_attn_cache/sd_self_attn_coco.h5 --version ${version} diff --git a/scripts/tmp_script/dist_DeCLIP+_eva_vitb16_coco_2.sh b/scripts/tmp_script/dist_DeCLIP+_eva_vitb16_coco_2.sh new file mode 100644 index 0000000000000000000000000000000000000000..a1e7b921f852157e221ff3d1feb30cc0d04b4d69 --- /dev/null +++ b/scripts/tmp_script/dist_DeCLIP+_eva_vitb16_coco_2.sh @@ -0,0 +1,16 @@ +data_root=/opt/tiger/xiaomoguhzz/standard_coco +pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt +exp_name=EVA-B_DINOv2-B_csa_1024_declip2_0.25_0.0_0.0 +vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16} +dataset_type=proposals_distill # {proposals_distill,grid_distill,dift_grid_distill} +version=declip2 # {declip,declip2,declip+} +# always keep total batchsize=16 , otherwise, Linear scaling the learning rate +CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 29500 -m training.main --batch-size=2 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \ +--model EVA02-CLIP-B-16 --pretrained eva --warmup 1000 --zeroshot-frequency 6 --dataset-type ${dataset_type} \ +--test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \ +--val-data ${data_root}/annotations/panoptic_val2017.json \ +--embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy --train-image-root ${data_root}/train2017 \ +--val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \ +--lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \ +--name ${exp_name} --downsample-factor 16 --det-image-size 1024 --val-segm-root ${data_root}/annotations/panoptic_val2017 \ +--alpha 0.7 --mode csa_vfm_distill --use_vfm ${vfm_type} --loss_context_weight 0.25 --loss_content_weight 0.0 --loss_region_weight 0.0 --skip-first-eval --repa_layer_idx -1 --sd-refine-weight 1.0 --cache-self-attn sd_self_attn_cache/sd_self_attn_coco.h5 --version ${version} diff --git a/src/diffusion_model/Processor.py b/src/diffusion_model/Processor.py new file mode 100644 index 0000000000000000000000000000000000000000..e0b4aee6891e072f383c2f04e4af0620edc0ca28 --- /dev/null +++ b/src/diffusion_model/Processor.py @@ -0,0 +1,120 @@ +import torch +import math +import torch.nn.functional as F +DIFFUSION_LAYERS = [ + 'down_blocks[0].attentions[0].transformer_blocks[0].attn1', # 0 + 'down_blocks[0].attentions[0].transformer_blocks[0].attn2', # 1 + 'down_blocks[0].attentions[1].transformer_blocks[0].attn1', # 2 + 'down_blocks[0].attentions[1].transformer_blocks[0].attn2', # 3 + 'down_blocks[1].attentions[0].transformer_blocks[0].attn1', # 4 + 'down_blocks[1].attentions[0].transformer_blocks[0].attn2', # 5 + 'down_blocks[1].attentions[1].transformer_blocks[0].attn1', # 6 + 'down_blocks[1].attentions[1].transformer_blocks[0].attn2', # 7 + 'down_blocks[2].attentions[0].transformer_blocks[0].attn1', # 8 + 'down_blocks[2].attentions[0].transformer_blocks[0].attn2', # 9 + 'down_blocks[2].attentions[1].transformer_blocks[0].attn1', # 10 + 'down_blocks[2].attentions[1].transformer_blocks[0].attn2', # 11 + + 'mid_block.attentions[0].transformer_blocks[0].attn1', + 'mid_block.attentions[0].transformer_blocks[0].attn2', + + 'up_blocks[1].attentions[0].transformer_blocks[0].attn1', # -18 + "up_blocks[1].attentions[0].transformer_blocks[0].attn2", # -17 + 'up_blocks[1].attentions[1].transformer_blocks[0].attn1', # -16 + "up_blocks[1].attentions[1].transformer_blocks[0].attn2", # -15 + 'up_blocks[1].attentions[2].transformer_blocks[0].attn1', # -14 + "up_blocks[1].attentions[2].transformer_blocks[0].attn2", # -13 + 'up_blocks[2].attentions[0].transformer_blocks[0].attn1', # -12 + "up_blocks[2].attentions[0].transformer_blocks[0].attn2", # -11 + 'up_blocks[2].attentions[1].transformer_blocks[0].attn1', # -10 + "up_blocks[2].attentions[1].transformer_blocks[0].attn2", # -9 + 'up_blocks[2].attentions[2].transformer_blocks[0].attn1', # -8 + 'up_blocks[2].attentions[2].transformer_blocks[0].attn2', # -7 + "up_blocks[3].attentions[0].transformer_blocks[0].attn1", # -6 + 'up_blocks[3].attentions[0].transformer_blocks[0].attn2', # -5 + "up_blocks[3].attentions[1].transformer_blocks[0].attn1", # -4 + 'up_blocks[3].attentions[1].transformer_blocks[0].attn2', # -3 + "up_blocks[3].attentions[2].transformer_blocks[0].attn1", # -2 + 'up_blocks[3].attentions[2].transformer_blocks[0].attn2', # -1 +] + + +class AttnProcessorForCallBack: + def __init__(self, model, layer): + self.model = model + self.layer = layer + + def __call__( + self, + attn, + hidden_states: torch.Tensor, + encoder_hidden_states=None, + attention_mask=None, + temb=None, + *args, + **kwargs, + ) -> torch.Tensor: + residual = hidden_states + + if attn.spatial_norm is not None: + hidden_states = attn.spatial_norm(hidden_states, temb) + input_ndim = hidden_states.ndim + + if input_ndim == 4: + batch_size, channel, height, width = hidden_states.shape + hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2) + + batch_size, sequence_length, _ = ( + hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape + ) + attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) + + if attn.group_norm is not None: + hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2) + query = attn.to_q(hidden_states) + if encoder_hidden_states is None: + encoder_hidden_states = hidden_states + elif attn.norm_cross: + encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states) + + key = attn.to_k(encoder_hidden_states) + value = attn.to_v(encoder_hidden_states) + + # ! add code + h=w=int(math.sqrt(query.shape[1])) + low_res_query=query.clone().transpose(-2,-1).view(batch_size, -1, h,w) + low_res_key=key.clone().transpose(-2,-1).view(batch_size, -1,h,w) + low_res_query_ds = F.interpolate(low_res_query, size=(35, 35), mode='bilinear', align_corners=False) + low_res_key_ds = F.interpolate(low_res_key, size=(35, 35), mode='bilinear', align_corners=False) + low_res_query_ds=low_res_query_ds.flatten(start_dim=-2).transpose(-2,-1) + low_res_key_ds=low_res_key_ds.flatten(start_dim=-2).transpose(-2,-1) + low_res_query_ds = attn.head_to_batch_dim(low_res_query_ds) + low_res_key_ds = attn.head_to_batch_dim(low_res_key_ds) + low_res_attention_probs = attn.get_attention_scores(low_res_query_ds, low_res_key_ds, attention_mask) + # ! add code + query = attn.head_to_batch_dim(query) + key = attn.head_to_batch_dim(key) + value = attn.head_to_batch_dim(value) + + attention_probs = attn.get_attention_scores(query, key, attention_mask) + hidden_states = torch.bmm(attention_probs, value) + hidden_states = attn.batch_to_head_dim(hidden_states) + + # linear proj + hidden_states = attn.to_out[0](hidden_states) + # dropout + hidden_states = attn.to_out[1](hidden_states) + + if input_ndim == 4: + hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width) + + if attn.residual_connection: + hidden_states = hidden_states + residual + + hidden_states = hidden_states / attn.rescale_output_factor + + head_size = attn.heads + batch_size, q_len, v_len = attention_probs.shape + attention_probs = attention_probs.reshape(batch_size // head_size, head_size, q_len, v_len) + self.model.attention_maps[self.layer] = low_res_attention_probs + return hidden_states diff --git a/src/diffusion_model/stable_diffusion.py b/src/diffusion_model/stable_diffusion.py new file mode 100644 index 0000000000000000000000000000000000000000..a8162010a3ad9571ff3d1639429da9cbddd5a13f --- /dev/null +++ b/src/diffusion_model/stable_diffusion.py @@ -0,0 +1,106 @@ +# make sure you're logged in with `huggingface-cli login` +import os +os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com' + +import torch +from diffusers.utils.torch_utils import randn_tensor +from diffusion_model.Processor import AttnProcessorForCallBack, DIFFUSION_LAYERS +from torch import autocast, nn +from diffusers import StableDiffusionPipeline + + +class diffusion(nn.Module): + + def __init__(self, + attention_layers_to_use=None, + model="v2.1", + time_step=45, + dtype=torch.float16, + device='cuda:0'): + super().__init__() + # stabilityai/stable-diffusion-2-1-base runwayml/stable-diffusion-v1-5 CompVis/stable-diffusion-v1-4 + if model == "v2.1": + model = "stabilityai/stable-diffusion-2-1-base" + elif model == "v1.5": + model = "runwayml/stable-diffusion-v1-5" + elif model == "v1.4": + model = "CompVis/stable-diffusion-v1-4" + else: + raise ValueError(f"Not supported model {model}") + self.model = StableDiffusionPipeline.from_pretrained(model, torch_dtype=dtype) + self.setup(device) + self.dtype = dtype + self.time_step = time_step + # 获取注意力图 + self.attention_maps = {} + if attention_layers_to_use is None: + attention_layers_to_use = [-1] + self.layers = attention_layers_to_use + for layer_idx in attention_layers_to_use: + attn = eval(f"self.model.unet.{DIFFUSION_LAYERS[layer_idx]}") + attn.processor = AttnProcessorForCallBack(self, layer_idx) + + def one_step(self, latents, prompts): + + self.model._guidance_scale = 1 + self.model._clip_skip = None + self.model._joint_attention_kwargs = None + self.model._interrupt = False + + self.model.scheduler.set_timesteps(50, device=self.device) + t = self.model.scheduler.timesteps[self.time_step] + + noise = randn_tensor(latents.shape, device=latents.device, dtype=latents.dtype) + # get latents + latents = self.model.scheduler.add_noise(latents, noise, t) + + prompt_embeds, _ = self.model.encode_prompt( + prompts, self.device, 1, do_classifier_free_guidance=False, + negative_prompt=None, + prompt_embeds=None, + negative_prompt_embeds=None, + lora_scale=None, + clip_skip=self.model.clip_skip, + ) + noise_pred = self.model.unet( + latents, + t, + encoder_hidden_states=prompt_embeds, + return_dict=False, + )[0] + + def generate_image(self, prompts): + with autocast("cuda"): + image = self.model(prompts)["images"][0] + return image + + @property + def device(self): + return self.model._execution_device + + def setup(self, device): + self.model.to(device) + + for param in self.model.vae.parameters(): + param.requires_grad = False + for param in self.model.unet.parameters(): + param.requires_grad = False + for param in self.model.text_encoder.parameters(): + param.requires_grad = False + + def forward(self, img, prompts=""): + latent = self.model.image_processor.preprocess(img, height=512, width=512).to(self.dtype) + latent = self.model.vae.encode(latent)[0].mean * self.model.vae.config.scaling_factor + self.one_step(latent, prompts=prompts) + + def forward_wo_preprocess(self, img, prompts=""): + latent = img.to(self.dtype) + latent = self.model.vae.encode(latent)[0].mean * self.model.vae.config.scaling_factor + self.one_step(latent, prompts=prompts) + +if __name__ == "__main__": + iseg = diffusion(attention_layers_to_use=[-2]) + prompt = "two dogs running under the sea. " + iseg.one_step(torch.randn((1, 4, 64, 64), dtype=torch.float16, device='cuda'), prompts='') + img = iseg.generate_image(prompt) + print(iseg.attention_maps[-2].shape) diff --git a/src/open_clip/__init__.py b/src/open_clip/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..685965160abf83cacb048abbcfc9bf9a79e64a7a --- /dev/null +++ b/src/open_clip/__init__.py @@ -0,0 +1,13 @@ +from .coca_model import CoCa +from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD +from .factory import create_model, create_model_and_transforms, create_model_from_pretrained, get_tokenizer,create_model_and_transforms_official +from .factory import list_models, add_model_config, get_model_config, load_checkpoint +from .loss import ClipLoss, DistillClipLoss, CoCaLoss +from .model import CLIP, CustomTextCLIP, CLIPTextCfg, CLIPVisionCfg, \ + convert_weights_to_lp, convert_weights_to_fp16, trace_model, get_cast_dtype +from .openai import load_openai_model, list_openai_models +from .pretrained import list_pretrained, list_pretrained_models_by_tag, list_pretrained_tags_by_model, \ + get_pretrained_url, download_pretrained_from_url, is_pretrained_cfg, get_pretrained_cfg, download_pretrained +from .push_to_hf_hub import push_pretrained_to_hf_hub, push_to_hf_hub +from .tokenizer import SimpleTokenizer, tokenize, decode +from .transform import image_transform, AugmentationCfg \ No newline at end of file diff --git a/src/open_clip/bpe_simple_vocab_16e6.txt.gz b/src/open_clip/bpe_simple_vocab_16e6.txt.gz new file mode 100644 index 0000000000000000000000000000000000000000..36a15856e00a06a9fbed8cdd34d2393fea4a3113 --- /dev/null +++ b/src/open_clip/bpe_simple_vocab_16e6.txt.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a +size 1356917 diff --git a/src/open_clip/coca_model.py b/src/open_clip/coca_model.py new file mode 100644 index 0000000000000000000000000000000000000000..039453af70d1c865dd7cc6016f732aff2f7dc3d2 --- /dev/null +++ b/src/open_clip/coca_model.py @@ -0,0 +1,458 @@ +from typing import Optional + +import torch +from torch import nn +from torch.nn import functional as F +import numpy as np +from dataclasses import dataclass + +from .transformer import ( + LayerNormFp32, + LayerNorm, + QuickGELU, + MultimodalTransformer, +) +from .model import CLIPTextCfg, CLIPVisionCfg, _build_vision_tower, _build_text_tower + +try: + from transformers import ( + BeamSearchScorer, + LogitsProcessorList, + TopPLogitsWarper, + TopKLogitsWarper, + RepetitionPenaltyLogitsProcessor, + MinLengthLogitsProcessor, + MaxLengthCriteria, + StoppingCriteriaList + ) + + GENERATION_TYPES = { + "top_k": TopKLogitsWarper, + "top_p": TopPLogitsWarper, + "beam_search": "beam_search" + } + _has_transformers = True +except ImportError as e: + GENERATION_TYPES = { + "top_k": None, + "top_p": None, + "beam_search": "beam_search" + } + _has_transformers = False + + +@dataclass +class MultimodalCfg(CLIPTextCfg): + mlp_ratio: int = 4 + dim_head: int = 64 + heads: int = 8 + n_queries: int = 256 + attn_pooler_heads: int = 8 + + +def _build_text_decoder_tower( + embed_dim, + multimodal_cfg, + quick_gelu: bool = False, + cast_dtype: Optional[torch.dtype] = None, +): + multimodal_cfg = MultimodalCfg(**multimodal_cfg) if isinstance(multimodal_cfg, dict) else multimodal_cfg + act_layer = QuickGELU if quick_gelu else nn.GELU + norm_layer = ( + LayerNormFp32 if cast_dtype in (torch.float16, torch.bfloat16) else LayerNorm + ) + + decoder = MultimodalTransformer( + context_length=multimodal_cfg.context_length, + width=multimodal_cfg.width, + heads=multimodal_cfg.heads, + layers=multimodal_cfg.layers, + ls_init_value=multimodal_cfg.ls_init_value, + output_dim=embed_dim, + act_layer=act_layer, + norm_layer=norm_layer, + ) + + return decoder + + +class CoCa(nn.Module): + def __init__( + self, + embed_dim, + multimodal_cfg: MultimodalCfg, + text_cfg: CLIPTextCfg, + vision_cfg: CLIPVisionCfg, + quick_gelu: bool = False, + cast_dtype: Optional[torch.dtype] = None, + pad_id: int = 0, + ): + super().__init__() + multimodal_cfg = MultimodalCfg(**multimodal_cfg) if isinstance(multimodal_cfg, dict) else multimodal_cfg + text_cfg = CLIPTextCfg(**text_cfg) if isinstance(text_cfg, dict) else text_cfg + vision_cfg = CLIPVisionCfg(**vision_cfg) if isinstance(vision_cfg, dict) else vision_cfg + + self.text = _build_text_tower( + embed_dim=embed_dim, + text_cfg=text_cfg, + quick_gelu=quick_gelu, + cast_dtype=cast_dtype, + ) + + vocab_size = ( + text_cfg.vocab_size # for hf models + if hasattr(text_cfg, "hf_model_name") and text_cfg.hf_model_name is not None + else text_cfg.vocab_size + ) + + self.visual = _build_vision_tower( + embed_dim=embed_dim, + vision_cfg=vision_cfg, + quick_gelu=quick_gelu, + cast_dtype=cast_dtype, + ) + + self.text_decoder = _build_text_decoder_tower( + vocab_size, + multimodal_cfg=multimodal_cfg, + quick_gelu=quick_gelu, + cast_dtype=cast_dtype, + ) + + self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) + self.pad_id = pad_id + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.visual.set_grad_checkpointing(enable) + self.text.set_grad_checkpointing(enable) + self.text_decoder.set_grad_checkpointing(enable) + + def _encode_image(self, images, normalize=True): + image_latent, tokens_embs = self.visual(images) + image_latent = F.normalize(image_latent, dim=-1) if normalize else image_latent + return image_latent, tokens_embs + + def _encode_text(self, text, normalize=True, embed_cls=True): + text = text[:, :-1] if embed_cls else text # make space for CLS token + text_latent, token_emb = self.text(text) + text_latent = F.normalize(text_latent, dim=-1) if normalize else text_latent + return text_latent, token_emb + + def encode_image(self, images, normalize=True): + image_latent, _ = self._encode_image(images, normalize=normalize) + return image_latent + + def encode_text(self, text, normalize=True, embed_cls=True): + text_latent, _ = self._encode_text(text, normalize=normalize, embed_cls=embed_cls) + return text_latent + + def forward(self, image, text, embed_cls=True, image_latent=None, image_embs=None): + text_latent, token_embs = self._encode_text(text, embed_cls=embed_cls) + if image_latent is None or image_embs is None: + image_latent, image_embs = self._encode_image(image) + + # TODO: add assertion to avoid bugs? + labels = text[:, -token_embs.shape[1]:] + + logits = self.text_decoder(image_embs, token_embs) + return { + "image_features": image_latent, + "text_features": text_latent, + "logits": logits, + "labels": labels, + "logit_scale": self.logit_scale.exp() + } + + def generate( + self, + image, + text=None, + seq_len=30, + max_seq_len=77, + temperature=1., + generation_type="beam_search", + top_p=0.1, # keep tokens in the 1 - top_p quantile + top_k=1, # keeps the top_k most probable tokens + pad_token_id=None, + eos_token_id=None, + sot_token_id=None, + num_beams=6, + num_beam_groups=3, + min_seq_len=5, + stopping_criteria=None, + repetition_penalty=1.0, + fixed_output_length=False # if True output.shape == (batch_size, seq_len) + ): + # taking many ideas and components from HuggingFace GenerationMixin + # https://huggingface.co/docs/transformers/main/en/main_classes/text_generation + assert _has_transformers, "Please install transformers for generate functionality. `pip install transformers`." + assert seq_len > min_seq_len, "seq_len must be larger than min_seq_len" + + with torch.no_grad(): + sot_token_id = 49406 if sot_token_id is None else sot_token_id + eos_token_id = 49407 if eos_token_id is None else eos_token_id + pad_token_id = self.pad_id if pad_token_id is None else pad_token_id + logit_processor = LogitsProcessorList( + [ + MinLengthLogitsProcessor(min_seq_len, eos_token_id), + RepetitionPenaltyLogitsProcessor(repetition_penalty), + ] + ) + + if stopping_criteria is None: + stopping_criteria = [MaxLengthCriteria(max_length=seq_len)] + + stopping_criteria = StoppingCriteriaList( + stopping_criteria + ) + + device = image.device + + if generation_type == "beam_search": + output = self._generate_beamsearch( + image_inputs = image, + pad_token_id=pad_token_id, + eos_token_id=eos_token_id, + sot_token_id=sot_token_id, + num_beams=num_beams, + num_beam_groups=num_beam_groups, + min_seq_len=min_seq_len, + stopping_criteria=stopping_criteria, + logit_processor=logit_processor, + ) + if fixed_output_length and output.shape[1] < seq_len: + return torch.cat( + (output, torch.ones(output.shape[0], seq_len-output.shape[1], device=device, dtype=output.dtype) * self.pad_id), + dim=1 + ) + return output + + elif generation_type == "top_p": + logit_warper = GENERATION_TYPES[generation_type](top_p) + elif generation_type == "top_k": + logit_warper = GENERATION_TYPES[generation_type](top_k) + else: + raise ValueError( + f"generation_type has to be one of " + f"{'| ' + ' | '.join(list(GENERATION_TYPES.keys())) + ' |'}." + ) + + image_latent, image_embs = self._encode_image(image) + + if text is None: + text = torch.ones((image.shape[0], 1), device=device, dtype=torch.long) * sot_token_id + + was_training = self.training + num_dims = len(text.shape) + + if num_dims == 1: + text = text[None, :] + + cur_len = text.shape[1] + self.eval() + out = text + + while True: + x = out[:, -max_seq_len:] + cur_len = x.shape[1] + logits = self(image, x, image_latent=image_latent, image_embs=image_embs, embed_cls=False)["logits"][:, -1] + mask = (out[:, -1] == eos_token_id) | (out[:, -1] == pad_token_id) + sample = torch.ones((out.shape[0], 1), device=device, dtype=torch.long) * pad_token_id + + if mask.all(): + if not fixed_output_length: + break + else: + logits = logits[~mask, :] + filtered_logits = logit_processor(x[~mask, :], logits) + filtered_logits = logit_warper(x[~mask, :], filtered_logits) + probs = F.softmax(filtered_logits / temperature, dim=-1) + + if (cur_len + 1 == seq_len): + sample[~mask, :] = torch.ones((sum(~mask), 1), device=device, dtype=torch.long) * eos_token_id + else: + sample[~mask, :] = torch.multinomial(probs, 1) + + out = torch.cat((out, sample), dim=-1) + + cur_len += 1 + + if stopping_criteria(out, None): + break + + if num_dims == 1: + out = out.squeeze(0) + + self.train(was_training) + return out + + def _generate_beamsearch( + self, + image_inputs, + pad_token_id=None, + eos_token_id=None, + sot_token_id=None, + num_beams=6, + num_beam_groups=3, + min_seq_len=5, + stopping_criteria=None, + logit_processor=None, + logit_warper=None, + ): + device = image_inputs.device + batch_size = image_inputs.shape[0] + image_inputs = torch.repeat_interleave(image_inputs, num_beams, dim=0) + image_latent, image_embs = self._encode_image(image_inputs) + + input_ids = torch.ones((batch_size * num_beams, 1), device=device, dtype=torch.long) + input_ids = input_ids * sot_token_id + beam_scorer = BeamSearchScorer( + batch_size=batch_size, + num_beams=num_beams, + device=device, + num_beam_groups=num_beam_groups, + ) + # instantiate logits processors + logits_processor = ( + LogitsProcessorList([MinLengthLogitsProcessor(min_seq_len, eos_token_id=eos_token_id)]) + if logit_processor is None + else logit_processor + ) + + batch_size = len(beam_scorer._beam_hyps) + num_beams = beam_scorer.num_beams + num_beam_groups = beam_scorer.num_beam_groups + num_sub_beams = num_beams // num_beam_groups + batch_beam_size, cur_len = input_ids.shape + beam_indices = None + + if num_beams * batch_size != batch_beam_size: + raise ValueError( + f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}." + ) + + beam_scores = torch.full((batch_size, num_beams), -1e9, dtype=torch.float, device=device) + # initialise score of first beam of each group with 0 and the rest with 1e-9. This ensures that the beams in + # the same group don't produce same tokens everytime. + beam_scores[:, ::num_sub_beams] = 0 + beam_scores = beam_scores.view((batch_size * num_beams,)) + + while True: + + # predicted tokens in cur_len step + current_tokens = torch.zeros(batch_size * num_beams, dtype=input_ids.dtype, device=device) + + # indices which will form the beams in the next time step + reordering_indices = torch.zeros(batch_size * num_beams, dtype=torch.long, device=device) + + # do one decoder step on all beams of all sentences in batch + model_inputs = prepare_inputs_for_generation(input_ids=input_ids, image_inputs=image_inputs) + outputs = self( + model_inputs['images'], + model_inputs['text'], + embed_cls=False, + image_latent=image_latent, + image_embs=image_embs + ) + + for beam_group_idx in range(num_beam_groups): + group_start_idx = beam_group_idx * num_sub_beams + group_end_idx = min(group_start_idx + num_sub_beams, num_beams) + group_size = group_end_idx - group_start_idx + + # indices of beams of current group among all sentences in batch + batch_group_indices = [] + + for batch_idx in range(batch_size): + batch_group_indices.extend( + [batch_idx * num_beams + idx for idx in range(group_start_idx, group_end_idx)] + ) + group_input_ids = input_ids[batch_group_indices] + + # select outputs of beams of currentg group only + next_token_logits = outputs['logits'][batch_group_indices, -1, :] + vocab_size = next_token_logits.shape[-1] + + next_token_scores_processed = logits_processor( + group_input_ids, next_token_logits, current_tokens=current_tokens, beam_group_idx=beam_group_idx + ) + next_token_scores = next_token_scores_processed + beam_scores[batch_group_indices].unsqueeze(-1) + next_token_scores = next_token_scores.expand_as(next_token_scores_processed) + + # reshape for beam search + next_token_scores = next_token_scores.view(batch_size, group_size * vocab_size) + + next_token_scores, next_tokens = torch.topk( + next_token_scores, 2 * group_size, dim=1, largest=True, sorted=True + ) + + next_indices = torch.div(next_tokens, vocab_size, rounding_mode="floor") + next_tokens = next_tokens % vocab_size + + # stateless + process_beam_indices = sum(beam_indices, ()) if beam_indices is not None else None + beam_outputs = beam_scorer.process( + group_input_ids, + next_token_scores, + next_tokens, + next_indices, + pad_token_id=pad_token_id, + eos_token_id=eos_token_id, + beam_indices=process_beam_indices, + ) + beam_scores[batch_group_indices] = beam_outputs["next_beam_scores"] + beam_next_tokens = beam_outputs["next_beam_tokens"] + beam_idx = beam_outputs["next_beam_indices"] + + input_ids[batch_group_indices] = group_input_ids[beam_idx] + group_input_ids = torch.cat([group_input_ids[beam_idx, :], beam_next_tokens.unsqueeze(-1)], dim=-1) + current_tokens[batch_group_indices] = group_input_ids[:, -1] + + # (beam_idx // group_size) -> batch_idx + # (beam_idx % group_size) -> offset of idx inside the group + reordering_indices[batch_group_indices] = ( + num_beams * torch.div(beam_idx, group_size, rounding_mode="floor") + group_start_idx + (beam_idx % group_size) + ) + + input_ids = torch.cat([input_ids, current_tokens.unsqueeze(-1)], dim=-1) + + # increase cur_len + cur_len = cur_len + 1 + if beam_scorer.is_done or stopping_criteria(input_ids, None): + break + + final_beam_indices = sum(beam_indices, ()) if beam_indices is not None else None + sequence_outputs = beam_scorer.finalize( + input_ids, + beam_scores, + next_tokens, + next_indices, + pad_token_id=pad_token_id, + eos_token_id=eos_token_id, + max_length=stopping_criteria.max_length, + beam_indices=final_beam_indices, + ) + return sequence_outputs['sequences'] + + +def prepare_inputs_for_generation(input_ids, image_inputs, past=None, **kwargs): + if past: + input_ids = input_ids[:, -1].unsqueeze(-1) + + attention_mask = kwargs.get("attention_mask", None) + position_ids = kwargs.get("position_ids", None) + + if attention_mask is not None and position_ids is None: + # create position_ids on the fly for batch generation + position_ids = attention_mask.long().cumsum(-1) - 1 + position_ids.masked_fill_(attention_mask == 0, 1) + else: + position_ids = None + return { + "text": input_ids, + "images": image_inputs, + "past_key_values": past, + "position_ids": position_ids, + "attention_mask": attention_mask, + } diff --git a/src/open_clip/constants.py b/src/open_clip/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..a670bb3fab442baeb9af53b91c312e6982af57ee --- /dev/null +++ b/src/open_clip/constants.py @@ -0,0 +1,2 @@ +OPENAI_DATASET_MEAN = (0.48145466, 0.4578275, 0.40821073) +OPENAI_DATASET_STD = (0.26862954, 0.26130258, 0.27577711) diff --git a/src/open_clip/customs.py b/src/open_clip/customs.py new file mode 100644 index 0000000000000000000000000000000000000000..eb11216b8632c4a4a2b964251c8a23ab77d07a72 --- /dev/null +++ b/src/open_clip/customs.py @@ -0,0 +1,35 @@ +from torch import Tensor +from torch.nn import MultiheadAttention +from torch.nn import functional as F +from typing import Optional, Tuple + + +class MultiheadSelfAttention(MultiheadAttention): + def forward(self, query: Tensor, key: Tensor, value: Tensor, key_padding_mask: Optional[Tensor] = None, + need_weights: bool = True, attn_mask: Optional[Tensor] = None, return_tokens: bool = False) \ + -> Tuple[Tensor, Tensor]: + assert query is value and value is key # self-attention + if return_tokens: + # in_projection + tokens = F.linear(value, self.in_proj_weight, bias=self.in_proj_bias)[..., -self.embed_dim:] + # out_projection + tokens = F.linear(tokens, self.out_proj.weight, bias=self.out_proj.bias) + else: + tokens = None + + attn_output, attn_output_weights = F.multi_head_attention_forward( + query=query, key=key, value=value, + embed_dim_to_check=self.embed_dim, + num_heads=self.num_heads, + in_proj_weight=self.in_proj_weight, + in_proj_bias=self.in_proj_bias, + bias_k=None, bias_v=None, + add_zero_attn=False, + dropout_p=0., + out_proj_weight=self.out_proj.weight, + out_proj_bias=self.out_proj.bias, + training=self.training, + key_padding_mask=key_padding_mask, need_weights=need_weights, + attn_mask=attn_mask) + + return attn_output, tokens # , attn_output_weights diff --git a/src/open_clip/eva_clip/__init__.py b/src/open_clip/eva_clip/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9e2c2f5790429ab3e94cf60fbbe66f43aaf17731 --- /dev/null +++ b/src/open_clip/eva_clip/__init__.py @@ -0,0 +1,11 @@ +from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD +from .factory import create_model, create_model_and_transforms, create_model_from_pretrained, get_tokenizer +from .factory import list_models, add_model_config, get_model_config, load_checkpoint +from .loss import ClipLoss +from .model import CLIP, CustomCLIP, CLIPTextCfg, CLIPVisionCfg,\ + convert_weights_to_lp, convert_weights_to_fp16, trace_model, get_cast_dtype +from .openai import load_openai_model, list_openai_models +from .pretrained import list_pretrained, list_pretrained_models_by_tag, list_pretrained_tags_by_model,\ + get_pretrained_url, download_pretrained_from_url, is_pretrained_cfg, get_pretrained_cfg, download_pretrained +from .tokenizer import SimpleTokenizer, tokenize +from .transform import image_transform \ No newline at end of file diff --git a/src/open_clip/eva_clip/bpe_simple_vocab_16e6.txt.gz b/src/open_clip/eva_clip/bpe_simple_vocab_16e6.txt.gz new file mode 100644 index 0000000000000000000000000000000000000000..36a15856e00a06a9fbed8cdd34d2393fea4a3113 --- /dev/null +++ b/src/open_clip/eva_clip/bpe_simple_vocab_16e6.txt.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a +size 1356917 diff --git a/src/open_clip/eva_clip/constants.py b/src/open_clip/eva_clip/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..a670bb3fab442baeb9af53b91c312e6982af57ee --- /dev/null +++ b/src/open_clip/eva_clip/constants.py @@ -0,0 +1,2 @@ +OPENAI_DATASET_MEAN = (0.48145466, 0.4578275, 0.40821073) +OPENAI_DATASET_STD = (0.26862954, 0.26130258, 0.27577711) diff --git a/src/open_clip/eva_clip/eva_vit_model.py b/src/open_clip/eva_clip/eva_vit_model.py new file mode 100644 index 0000000000000000000000000000000000000000..76c5487dacc696720a091a10c7d95196bfceb200 --- /dev/null +++ b/src/open_clip/eva_clip/eva_vit_model.py @@ -0,0 +1,1067 @@ +# -------------------------------------------------------- +# Adapted from https://github.com/microsoft/unilm/tree/master/beit +# -------------------------------------------------------- +import math +import os +from functools import partial +import torch +import torch.nn as nn +import torch.nn.functional as F +try: + from timm.models.layers import drop_path, to_2tuple, trunc_normal_ +except: + from timm.layers import drop_path, to_2tuple, trunc_normal_ + +from .transformer import PatchDropout +from .rope import VisionRotaryEmbedding, VisionRotaryEmbeddingFast +from torchvision.ops import roi_align +if os.getenv('ENV_TYPE') == 'deepspeed': + try: + from deepspeed.runtime.activation_checkpointing.checkpointing import checkpoint + except: + from torch.utils.checkpoint import checkpoint +else: + from torch.utils.checkpoint import checkpoint + +try: + import xformers.ops as xops +except ImportError: + xops = None + print("Please 'pip install xformers'") +from typing import Sequence + + +def _get_env_backend(env_name: str): + value = os.getenv(env_name, "").strip().lower() + if value in ("sdpa", "torch"): + return value + return None + + +def _build_attn_bias(attn_mask, rel_pos_bias, relative_position_bias, dtype, device): + attn_bias = None + if relative_position_bias is not None: + attn_bias = relative_position_bias + if rel_pos_bias is not None: + attn_bias = rel_pos_bias if attn_bias is None else attn_bias + rel_pos_bias + if attn_mask is not None: + mask = attn_mask.bool() + mask = (~mask).to(dtype=dtype, device=device) + mask = mask * torch.finfo(dtype).min + if mask.dim() == 2: + mask = mask[:, None, None, :] + elif mask.dim() == 3: + mask = mask[:, None, :, :] + attn_bias = mask if attn_bias is None else attn_bias + mask + return attn_bias + + +def _scaled_dot_product_attention(query, key, value, attn_bias, dropout_p, scale): + if not hasattr(F, "scaled_dot_product_attention"): + return None + try: + return F.scaled_dot_product_attention( + query, key, value, + attn_mask=attn_bias, + dropout_p=dropout_p, + is_causal=False, + scale=scale, + ) + except TypeError: + if scale is not None and scale != 1.0: + query = query * scale + return F.scaled_dot_product_attention( + query, key, value, + attn_mask=attn_bias, + dropout_p=dropout_p, + is_causal=False, + ) + + +class DropPath(nn.Module): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). + """ + def __init__(self, drop_prob=None): + super(DropPath, self).__init__() + self.drop_prob = drop_prob + + def forward(self, x): + return drop_path(x, self.drop_prob, self.training) + + def extra_repr(self) -> str: + return 'p={}'.format(self.drop_prob) + + +class Mlp(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + act_layer=nn.GELU, + norm_layer=nn.LayerNorm, + drop=0., + subln=False, + + ): + 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.ffn_ln = norm_layer(hidden_features) if subln else nn.Identity() + + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + # x = self.drop(x) + # commit this for the orignal BERT implement + x = self.ffn_ln(x) + + x = self.fc2(x) + x = self.drop(x) + return x + +class SwiGLU(nn.Module): + def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.SiLU, drop=0., + norm_layer=nn.LayerNorm, subln=False): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + + self.w1 = nn.Linear(in_features, hidden_features) + self.w2 = nn.Linear(in_features, hidden_features) + + self.act = act_layer() + self.ffn_ln = norm_layer(hidden_features) if subln else nn.Identity() + self.w3 = nn.Linear(hidden_features, out_features) + + self.drop = nn.Dropout(drop) + + def forward(self, x): + x1 = self.w1(x) + x2 = self.w2(x) + hidden = self.act(x1) * x2 + x = self.ffn_ln(hidden) + x = self.w3(x) + x = self.drop(x) + return x + +class Attention(nn.Module): + def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., + proj_drop=0., window_size=None, attn_head_dim=None, xattn=False, rope=None, subln=False, norm_layer=nn.LayerNorm): + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + if attn_head_dim is not None: + head_dim = attn_head_dim + all_head_dim = head_dim * self.num_heads + self.scale = qk_scale or head_dim ** -0.5 + + self.subln = subln + if self.subln: + self.q_proj = nn.Linear(dim, all_head_dim, bias=False) + self.k_proj = nn.Linear(dim, all_head_dim, bias=False) + self.v_proj = nn.Linear(dim, all_head_dim, bias=False) + else: + self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False) + + if qkv_bias: + self.q_bias = nn.Parameter(torch.zeros(all_head_dim)) + self.v_bias = nn.Parameter(torch.zeros(all_head_dim)) + else: + self.q_bias = None + self.v_bias = None + + if window_size: + self.window_size = window_size + self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3 + self.relative_position_bias_table = nn.Parameter( + torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH + # cls to token & token 2 cls & cls to cls + + # get pair-wise relative position index for each token inside the window + coords_h = torch.arange(window_size[0]) + coords_w = torch.arange(window_size[1]) + coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww + coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww + relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww + relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 + relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0 + relative_coords[:, :, 1] += window_size[1] - 1 + relative_coords[:, :, 0] *= 2 * window_size[1] - 1 + relative_position_index = \ + torch.zeros(size=(window_size[0] * window_size[1] + 1, ) * 2, dtype=relative_coords.dtype) + relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww + relative_position_index[0, 0:] = self.num_relative_distance - 3 + relative_position_index[0:, 0] = self.num_relative_distance - 2 + relative_position_index[0, 0] = self.num_relative_distance - 1 + + self.register_buffer("relative_position_index", relative_position_index) + else: + self.window_size = None + self.relative_position_bias_table = None + self.relative_position_index = None + + self.attn_drop = nn.Dropout(attn_drop) + self.inner_attn_ln = norm_layer(all_head_dim) if subln else nn.Identity() + # self.proj = nn.Linear(all_head_dim, all_head_dim) + self.proj = nn.Linear(all_head_dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + self.xattn = xattn + self.xattn_drop = attn_drop + + self.rope = rope + + def forward(self, x, rel_pos_bias=None, attn_mask=None): + B, N, C = x.shape + if self.subln: + q = F.linear(input=x, weight=self.q_proj.weight, bias=self.q_bias) + k = F.linear(input=x, weight=self.k_proj.weight, bias=None) + v = F.linear(input=x, weight=self.v_proj.weight, bias=self.v_bias) + + q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) # B, num_heads, N, C + k = k.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) + v = v.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) + else: + qkv_bias = None + if self.q_bias is not None: + qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias)) + + qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias) + qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # 3, B, num_heads, N, C + q, k, v = qkv[0], qkv[1], qkv[2] + + if self.rope: + if attn_mask is not None: + attn_mask = attn_mask.to(q) + # slightly fast impl + q_t = q[:, :, 1:, :] + ro_q_t = self.rope(q_t) + q = torch.cat((q[:, :, :1, :], ro_q_t), -2) + + k_t = k[:, :, 1:, :] + ro_k_t = self.rope(k_t) + k = torch.cat((k[:, :, :1, :], ro_k_t), -2) + + qk_backend = _get_env_backend("EVA_QK_ATTN_BACKEND") + use_xattn = self.xattn and qk_backend is None + + if use_xattn: + q = q.permute(0, 2, 1, 3) # B, num_heads, N, C -> B, N, num_heads, C + k = k.permute(0, 2, 1, 3) + v = v.permute(0, 2, 1, 3) + + x = xops.memory_efficient_attention( + q, k, v, + p=self.xattn_drop, + scale=self.scale, + attn_bias=attn_mask # to allow masked attention + ) + x = x.reshape(B, N, -1) + x = self.inner_attn_ln(x) + x = self.proj(x) + x = self.proj_drop(x) + else: + if qk_backend == "sdpa": + relative_position_bias = None + if self.relative_position_bias_table is not None: + relative_position_bias = \ + self.relative_position_bias_table[self.relative_position_index.view(-1)].view( + self.window_size[0] * self.window_size[1] + 1, + self.window_size[0] * self.window_size[1] + 1, -1) + relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() + + attn_bias = _build_attn_bias( + attn_mask, + rel_pos_bias, + relative_position_bias, + q.dtype, + q.device, + ) + dropout_p = self.attn_drop.p if self.training else 0.0 + sdpa_out = _scaled_dot_product_attention( + q, k, v, attn_bias, dropout_p, self.scale + ) + if sdpa_out is not None: + x = sdpa_out.transpose(1, 2).reshape(B, N, -1) + x = self.inner_attn_ln(x) + x = self.proj(x) + x = self.proj_drop(x) + return x + + q = q * self.scale + attn = (q @ k.transpose(-2, -1)) + + if self.relative_position_bias_table is not None: + relative_position_bias = \ + self.relative_position_bias_table[self.relative_position_index.view(-1)].view( + self.window_size[0] * self.window_size[1] + 1, + self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH + relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww + attn = attn + relative_position_bias.unsqueeze(0) + + if rel_pos_bias is not None: + attn = attn + rel_pos_bias + + if attn_mask is not None: + attn_mask = attn_mask.bool() + attn = attn.masked_fill(~attn_mask[:, None, None, :], float("-inf")) + + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B, N, -1) + x = self.inner_attn_ln(x) + x = self.proj(x) + x = self.proj_drop(x) + return x + + def proj_without_attn(self, x): + x = F.linear(input=x, weight=self.v_proj.weight, bias=self.v_bias) + # B, num_heads, C + x = self.inner_attn_ln(x) + x = self.proj(x) + x = self.proj_drop(x) + + return x + + def ss_attn(self, x, mode, attn_mask=None): + B, N, C = x.shape + use_qq_xformer = mode == "qq_xformer" + qq_backend = _get_env_backend("EVA_QQ_ATTN_BACKEND") + force_manual = qq_backend == "torch" + use_sdpa = qq_backend == "sdpa" + if self.subln: + q = F.linear(input=x, weight=self.q_proj.weight, bias=self.q_bias) + v = F.linear(input=x, weight=self.v_proj.weight, bias=self.v_bias) + if not use_qq_xformer: + k = F.linear(input=x, weight=self.k_proj.weight, bias=None) + q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) # B, num_heads, N, C + if not use_qq_xformer: + k = k.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) + v = v.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) + else: + q_bias = self.q_bias if self.q_bias is not None else None + v_bias = self.v_bias if self.v_bias is not None else None + all_head_dim = self.qkv.weight.shape[0] // 3 + if use_qq_xformer: + q_weight = self.qkv.weight[:all_head_dim] + v_weight = self.qkv.weight[2 * all_head_dim:] + q = F.linear(input=x, weight=q_weight, bias=q_bias) + v = F.linear(input=x, weight=v_weight, bias=v_bias) + else: + qkv_bias = None + if self.q_bias is not None: + qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias)) + + qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias) + qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # 3, B, num_heads, N, C + q, k, v = qkv[0], qkv[1], qkv[2] + q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) + if not use_qq_xformer: + k = k.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) + v = v.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) + + if self.rope: + if attn_mask is not None: + attn_mask = attn_mask.to(q) + # slightly fast impl + q_t = q[:, :, 1:, :] + ro_q_t = self.rope(q_t) + q = torch.cat((q[:, :, :1, :], ro_q_t), -2) + + if not use_qq_xformer: + k_t = k[:, :, 1:, :] + ro_k_t = self.rope(k_t) + k = torch.cat((k[:, :, :1, :], ro_k_t), -2) + + if use_qq_xformer and (not force_manual) and (not use_sdpa) and xops is not None and not torch.onnx.is_in_onnx_export(): + q_x = q.permute(0, 2, 1, 3).contiguous() + v_x = v.permute(0, 2, 1, 3).contiguous() + x = xops.memory_efficient_attention( + q_x, q_x, v_x, + p=0.0, + scale=1.0, + attn_bias=attn_mask + ) + x = x.reshape(B, N, -1) + x = self.inner_attn_ln(x) + x = self.proj(x) + x = self.proj_drop(x) + return x + if use_qq_xformer and use_sdpa: + attn_bias = _build_attn_bias(attn_mask, None, None, q.dtype, q.device) + sdpa_out = _scaled_dot_product_attention( + q, q, v, attn_bias, 0.0, 1.0 + ) + if sdpa_out is not None: + x = sdpa_out.transpose(1, 2).reshape(B, N, -1) + x = self.inner_attn_ln(x) + x = self.proj(x) + x = self.proj_drop(x) + return x + + q = q.contiguous().view(B*self.num_heads, N, -1) + if not use_qq_xformer: + k = k.contiguous().view(B*self.num_heads, N, -1) + v = v.contiguous().view(B*self.num_heads, N, -1) + + if 'qq' in mode: + q_attn = torch.bmm(q, q.transpose(1, 2)) # self.scale + attn_weights = F.softmax(q_attn, dim=-1) + elif 'csa' in mode: + q_attn = torch.bmm(q, q.transpose(1, 2)) # self.scale + k_attn = torch.bmm(k, k.transpose(1, 2)) # self.scale + attn_weights = F.softmax(q_attn, dim=-1) + F.softmax(k_attn, dim=-1) + elif 'vv' in mode: + v_attn = torch.bmm(v, v.transpose(1, 2)) # self.scale + attn_weights = F.softmax(v_attn, dim=-1) + elif 'kk' in mode: + k_attn = torch.bmm(k, k.transpose(1, 2)) # self.scale + attn_weights = F.softmax(k_attn, dim=-1) + elif 'all' in mode: + q_attn = torch.bmm(q, q.transpose(1, 2)) # self.scale + k_attn = torch.bmm(k, k.transpose(1, 2)) # self.scale + v_attn = torch.bmm(v, v.transpose(1, 2)) # self.scale + _attn = (q_attn+k_attn+v_attn)/3.0 + attn_weights = F.softmax(_attn, dim=-1) + else: + raise NotImplementedError(f"Mode '{mode}' is not implemented.") + + attn_output = torch.bmm(attn_weights, v) + attn_output = attn_output.transpose(0, 1).contiguous().view(N, B, C).transpose(0, 1) # B,N,C + attn_output = self.inner_attn_ln(attn_output) + attn_output = self.proj(attn_output) + attn_output = self.proj_drop(attn_output) + + if mode=="qq_vfm_distill": + return attn_output, q[:,1:] + elif mode=="kk_vfm_distill": + return attn_output, k[:,1:] + elif mode=="csa_vfm_distill": + return attn_output, (q[:,1:], k[:,1:]) + elif mode=="vv_vfm_distill": + return attn_output, v[:,1:] + elif mode=="all_vfm_distill": + return attn_output, (q[:,1:], k[:,1:], v[:,1:]) + else: + return attn_output + + +class Block(nn.Module): + + def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., + drop_path=0., init_values=None, act_layer=nn.GELU, norm_layer=nn.LayerNorm, + window_size=None, attn_head_dim=None, xattn=False, rope=None, postnorm=False, + subln=False, naiveswiglu=False): + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention( + dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, + attn_drop=attn_drop, proj_drop=drop, window_size=window_size, attn_head_dim=attn_head_dim, + xattn=xattn, rope=rope, subln=subln, norm_layer=norm_layer) + # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here + self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + + if naiveswiglu: + self.mlp = SwiGLU( + in_features=dim, + hidden_features=mlp_hidden_dim, + subln=subln, + norm_layer=norm_layer, + ) + else: + self.mlp = Mlp( + in_features=dim, + hidden_features=mlp_hidden_dim, + act_layer=act_layer, + subln=subln, + drop=drop + ) + + if init_values is not None and init_values > 0: + self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True) + self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True) + else: + self.gamma_1, self.gamma_2 = None, None + + self.postnorm = postnorm + + def forward(self, x, rel_pos_bias=None, attn_mask=None): + if self.gamma_1 is None: + if self.postnorm: + x = x + self.drop_path(self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias, attn_mask=attn_mask))) + x = x + self.drop_path(self.norm2(self.mlp(x))) + else: + x = x + self.drop_path(self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias, attn_mask=attn_mask)) + x = x + self.drop_path(self.mlp(self.norm2(x))) + else: + if self.postnorm: + x = x + self.drop_path(self.gamma_1 * self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias, attn_mask=attn_mask))) + x = x + self.drop_path(self.gamma_2 * self.norm2(self.mlp(x))) + else: + x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias, attn_mask=attn_mask)) + x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x))) + return x + + def forward_without_attn(self, x): + if self.gamma_1 is None: + if self.postnorm: + x = x + self.drop_path(self.norm1(self.attn.proj_without_attn(x))) + x = x + self.drop_path(self.norm2(self.mlp(x))) + else: + x = x + self.drop_path(self.attn.proj_without_attn(self.norm1(x))) + x = x + self.drop_path(self.mlp(self.norm2(x))) + else: + if self.postnorm: + x = x + self.drop_path(self.gamma_1 * self.norm1(self.attn.proj_without_attn(x))) + x = x + self.drop_path(self.gamma_2 * self.norm2(self.mlp(x))) + else: + x = x + self.drop_path(self.gamma_1 * self.attn.proj_without_attn(self.norm1(x))) + x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x))) + return x + + def forward_without_rcffn(self, x, mode): + if self.gamma_1 is None: + if self.postnorm: + x = self.drop_path(self.norm1(self.attn.ss_attn(x, mode))) + else: + x = self.drop_path(self.attn.ss_attn(self.norm1(x),mode)) + else: + if self.postnorm: + x = self.drop_path(self.gamma_1 * self.norm1(self.attn.ss_attn(x, mode))) + else: + x = self.drop_path(self.gamma_1 * self.attn.ss_attn(self.norm1(x),mode)) + return x + + def forward_dummy_csa(self, x, rel_pos_bias=None): + """ + 消融实验:使用标准 attention,但移除 residual 和 MLP + 用于验证 csa (Q@Q^T + K@K^T) 是否是导致性能下降的原因 + """ + if self.gamma_1 is None: + if self.postnorm: + x = self.drop_path(self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias))) + else: + x = self.drop_path(self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias)) + else: + if self.postnorm: + x = self.drop_path(self.gamma_1 * self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias))) + else: + x = self.drop_path(self.gamma_1 * self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias)) + return x + + def forward_declip(self, x, mode): + if self.gamma_1 is None: + if self.postnorm: + x = self.drop_path(self.norm1(self.attn.ss_attn(x, mode))) + if 'distill' in mode: + x, context = x[0], x[1] + x = x + self.drop_path(self.norm2(self.mlp(x))) + return x, context + else: + x = x + self.drop_path(self.norm2(self.mlp(x))) + else: + x = self.drop_path(self.attn.ss_attn(self.norm1(x),mode)) + if 'distill' in mode: + x, context = x[0], x[1] + x = x + self.drop_path(self.mlp(self.norm2(x))) + return x, context + else: + x = x + self.drop_path(self.mlp(self.norm2(x))) + else: + if self.postnorm: + x = self.drop_path(self.gamma_1 * self.norm1(self.attn.ss_attn(x, mode))) + if 'distill' in mode: + x, context = x[0], x[1] + x = x + self.drop_path(self.gamma_2 * self.norm2(self.mlp(x))) + return x, context + else: + x = x + self.drop_path(self.gamma_2 * self.norm2(self.mlp(x))) + else: + x = self.drop_path(self.gamma_1 * self.attn.ss_attn(self.norm1(x),mode)) + if 'distill' in mode: + x, context = x[0], x[1] + x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x))) + return x, context + else: + x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x))) + return x + + + +class PatchEmbed(nn.Module): + """ Image to Patch Embedding + """ + def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768): + super().__init__() + img_size = to_2tuple(img_size) + patch_size = to_2tuple(patch_size) + num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0]) + self.patch_shape = (img_size[0] // patch_size[0], img_size[1] // patch_size[1]) + self.img_size = img_size + self.patch_size = patch_size + self.num_patches = num_patches + + self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) + + def forward(self, x, **kwargs): + B, C, H, W = x.shape + # FIXME look at relaxing size constraints + # assert H == self.img_size[0] and W == self.img_size[1], \ + # f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." + x = self.proj(x).flatten(2).transpose(1, 2) + return x + + +class RelativePositionBias(nn.Module): + + def __init__(self, window_size, num_heads): + super().__init__() + self.window_size = window_size + self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3 + self.relative_position_bias_table = nn.Parameter( + torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH + # cls to token & token 2 cls & cls to cls + + # get pair-wise relative position index for each token inside the window + coords_h = torch.arange(window_size[0]) + coords_w = torch.arange(window_size[1]) + coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww + coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww + relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww + relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 + relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0 + relative_coords[:, :, 1] += window_size[1] - 1 + relative_coords[:, :, 0] *= 2 * window_size[1] - 1 + relative_position_index = \ + torch.zeros(size=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype) + relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww + relative_position_index[0, 0:] = self.num_relative_distance - 3 + relative_position_index[0:, 0] = self.num_relative_distance - 2 + relative_position_index[0, 0] = self.num_relative_distance - 1 + + self.register_buffer("relative_position_index", relative_position_index) + + def forward(self): + relative_position_bias = \ + self.relative_position_bias_table[self.relative_position_index.view(-1)].view( + self.window_size[0] * self.window_size[1] + 1, + self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH + return relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww + + +class EVAVisionTransformer(nn.Module): + """ Vision Transformer with support for patch or hybrid CNN input stage + """ + def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12, + num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0., + drop_path_rate=0., norm_layer=nn.LayerNorm, init_values=None, patch_dropout=0., + use_abs_pos_emb=True, use_rel_pos_bias=False, use_shared_rel_pos_bias=False, rope=False, + use_mean_pooling=True, init_scale=0.001, grad_checkpointing=False, xattn=False, postnorm=False, + pt_hw_seq_len=16, intp_freq=False, naiveswiglu=False, subln=False): + super().__init__() + self.image_size = img_size + self.num_heads = num_heads + self.num_classes = num_classes + self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models + + self.patch_embed = PatchEmbed( + img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) + num_patches = self.patch_embed.num_patches + + self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) + # self.mask_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) + if use_abs_pos_emb: + self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim)) + else: + self.pos_embed = None + + self.pos_drop = nn.Dropout(p=drop_rate) + + if use_shared_rel_pos_bias: + self.rel_pos_bias = RelativePositionBias(window_size=self.patch_embed.patch_shape, num_heads=num_heads) + else: + self.rel_pos_bias = None + + if rope: + half_head_dim = embed_dim // num_heads // 2 + hw_seq_len = img_size // patch_size + self.rope = VisionRotaryEmbeddingFast( + dim=half_head_dim, + pt_seq_len=pt_hw_seq_len, + ft_seq_len=hw_seq_len if intp_freq else None, + # patch_dropout=patch_dropout + ) + else: + self.rope = None + + self.naiveswiglu = naiveswiglu + + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule + self.use_rel_pos_bias = use_rel_pos_bias + self.blocks = nn.ModuleList([ + Block( + dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, + init_values=init_values, window_size=self.patch_embed.patch_shape if use_rel_pos_bias else None, + xattn=xattn, rope=self.rope, postnorm=postnorm, subln=subln, naiveswiglu=naiveswiglu) + for i in range(depth)]) + self.norm = nn.Identity() if use_mean_pooling else norm_layer(embed_dim) + self.fc_norm = norm_layer(embed_dim) if use_mean_pooling else None + self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity() + + if self.pos_embed is not None: + trunc_normal_(self.pos_embed, std=.02) + + trunc_normal_(self.cls_token, std=.02) + # trunc_normal_(self.mask_token, std=.02) + + self.apply(self._init_weights) + self.fix_init_weight() + + if isinstance(self.head, nn.Linear): + trunc_normal_(self.head.weight, std=.02) + self.head.weight.data.mul_(init_scale) + self.head.bias.data.mul_(init_scale) + + # setting a patch_dropout of 0. would mean it is disabled and this function would be the identity fn + self.patch_dropout = PatchDropout(patch_dropout) if patch_dropout > 0. else nn.Identity() + + self.grad_checkpointing = grad_checkpointing + + def fix_init_weight(self): + def rescale(param, layer_id): + param.div_(math.sqrt(2.0 * layer_id)) + + for layer_id, layer in enumerate(self.blocks): + rescale(layer.attn.proj.weight.data, layer_id + 1) + if self.naiveswiglu: + rescale(layer.mlp.w3.weight.data, layer_id + 1) + else: + rescale(layer.mlp.fc2.weight.data, layer_id + 1) + + def get_cast_dtype(self) -> torch.dtype: + return self.blocks[0].mlp.fc2.weight.dtype + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + def get_num_layers(self): + return len(self.blocks) + + def lock(self, unlocked_groups=0, freeze_bn_stats=False): + + for param in self.parameters(): + param.requires_grad = False + def _unlock(x): + if isinstance(x, list): + for g in x: + _unlock(g) + else: + if isinstance(x, torch.nn.Parameter): + x.requires_grad = True + else: + for p in x.parameters(): + p.requires_grad = True + + for blk in self.blocks[-unlocked_groups:]: + _unlock(blk) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.grad_checkpointing = enable + + @torch.jit.ignore + def no_weight_decay(self): + return {'pos_embed', 'cls_token'} + + def get_classifier(self): + return self.head + + def reset_classifier(self, num_classes, global_pool=''): + self.num_classes = num_classes + self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() + + def forward_features(self, x, return_all_features=False): + bs, _, h, w = x.shape + h = h // self.patch_embed.patch_size[0] + w = w // self.patch_embed.patch_size[1] + x = self.patch_embed(x) + batch_size, seq_len, _ = x.size() + + cls_tokens = self.cls_token.expand(batch_size, -1, -1) # stole cls_tokens impl from Phil Wang, thanks + x = torch.cat((cls_tokens, x), dim=1) + if self.pos_embed is not None: + x = x + self.rescale_positional_embedding(out_size=(h, w)) + x = self.pos_drop(x) + + # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in + if os.getenv('RoPE') == '1': + if self.training and not isinstance(self.patch_dropout, nn.Identity): + x, patch_indices_keep = self.patch_dropout(x) + self.rope.forward = partial(self.rope.forward, patch_indices_keep=patch_indices_keep) + else: + self.rope.forward = partial(self.rope.forward, patch_indices_keep=None) + x = self.patch_dropout(x) + else: + x = self.patch_dropout(x) + + rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None + for blk in self.blocks: + if self.grad_checkpointing: + x = checkpoint(blk, x, (rel_pos_bias,)) + else: + x = blk(x, rel_pos_bias=rel_pos_bias) + + if not return_all_features: + x = self.norm(x) + if self.fc_norm is not None: + return self.fc_norm(x.mean(1)) + else: + return x[:, 0] + return x + + def post_attention(self, x, return_all_features=False): + if not return_all_features: + x = self.norm(x) + if self.fc_norm is not None: + return self.fc_norm(x.mean(1)) + else: + return x[:, 0] + return x + + def forward(self, x, return_all_features=False): + if return_all_features: + return self.forward_features(x, return_all_features) + x = self.forward_features(x) + x = self.head(x) + return x + + def encode_dense(self,x,keep_shape=True,mode="qq",get_intermediate_layer=None): + + if get_intermediate_layer is None: + get_intermediate_layer = [] + get_intermediate_layer = set(get_intermediate_layer) + + bs, _, h, w = x.shape + h = h // self.patch_embed.patch_size[0] + w = w // self.patch_embed.patch_size[1] + x = self.patch_embed(x) + batch_size, seq_len, _ = x.size() + cls_tokens = self.cls_token.expand(batch_size, -1, -1) + x = torch.cat((cls_tokens, x), dim=1) + if self.pos_embed is not None: + x = x + self.rescale_positional_embedding(out_size=(h, w)) + x = self.pos_drop(x) + + if os.getenv('RoPE') == '1': + if self.training and not isinstance(self.patch_dropout, nn.Identity): + x, patch_indices_keep = self.patch_dropout(x) + self.rope.forward = partial(self.rope.forward, patch_indices_keep=patch_indices_keep) + else: + self.rope.forward = partial(self.rope.forward, patch_indices_keep=None) + x = self.patch_dropout(x) + else: + x = self.patch_dropout(x) + + rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None + + + intermediate_outputs = [] + + num_blocks = len(self.blocks) + for idx, blk in enumerate(self.blocks[:-1]): + x = blk(x, rel_pos_bias=rel_pos_bias) + if idx in get_intermediate_layer: + intermediate_outputs.append(x.clone()) + + last_idx = num_blocks - 1 + if "distill" in mode: + x, context = self.blocks[-1].forward_without_rcffn(x, mode) + # x, context = self.blocks[-1].forward_declip(x, mode) + else: + if mode == "maskclip": + x = self.blocks[-1].forward_without_attn(x) + elif mode == "vanilla" or mode == "sanity_check": + x = self.blocks[-1](x, rel_pos_bias=rel_pos_bias) + elif mode == "dummy_csa": + # 消融实验:标准 attention,但移除 residual 和 MLP + x = self.blocks[-1].forward_dummy_csa(x, rel_pos_bias=rel_pos_bias) + else: + x = self.blocks[-1].forward_without_rcffn(x, mode) + # x = self.blocks[-1].forward_declip(x, mode) + + x = x[:, 1:] + x = self.norm(x) + x = self.head(x) + assert self.fc_norm is None + if keep_shape: + x = x.view(bs, h, w, -1).permute(0, 3, 1, 2) + if last_idx in get_intermediate_layer: + intermediate_outputs.append(x.clone()) + if "distill" in mode: + if get_intermediate_layer: + return x, context, intermediate_outputs + else: + return x, context + elif mode == "sanity_check": + if get_intermediate_layer: + return x, x, intermediate_outputs + else: + return x, x + else: + if get_intermediate_layer: + return x, intermediate_outputs + else: + return x + + def extract_roi_features(self, x, normed_boxes, mode="qq", get_intermediate_layer=None,size=(1, 1)): + outputs = self.encode_dense( + x, + keep_shape=True, + mode=mode, + get_intermediate_layer=get_intermediate_layer + ) + boxes = self._denormalize_boxes(normed_boxes, outputs[0] if 'distill' in mode or mode == "sanity_check" else outputs) + if 'distill' in mode or mode == "sanity_check": + if get_intermediate_layer: + # features, extra_feats, intermediate_outputs + features, extra_feats, intermediate_outputs = outputs + else: + features, extra_feats = outputs + intermediate_outputs = None + + roi_feats = roi_align( + features, + boxes, + output_size=size, + spatial_scale=1.0, + sampling_ratio=-1, + aligned=True + ) + if size == (1, 1): + roi_feats = roi_feats[..., 0, 0] + else: + roi_feats=roi_feats.flatten(start_dim=-2).transpose(-2,-1).contiguous() + if get_intermediate_layer: + return roi_feats, extra_feats, intermediate_outputs + else: + return roi_feats, extra_feats + else: + if get_intermediate_layer: + features, intermediate_outputs = outputs + else: + features = outputs + intermediate_outputs = None + + roi_feats = roi_align( + features, + boxes, + output_size=size, + spatial_scale=1.0, + sampling_ratio=-1, + aligned=True + ) + if size == (1, 1): + roi_feats = roi_feats[..., 0, 0] + else: + roi_feats=roi_feats.flatten(start_dim=-2).transpose(-2,-1).contiguous() + if get_intermediate_layer: + return roi_feats, intermediate_outputs + else: + return roi_feats + + def rescale_positional_embedding(self, out_size): + h, w = out_size + if (h, w) == self.patch_embed.patch_shape: + return self.pos_embed + rescaled_positional_embedding = \ + self.pos_embed.new_zeros(1, 1 + h*w, self.pos_embed.shape[2]) + rescaled_positional_embedding[0, 0] = self.pos_embed[0, 0] + pe_2d = self.pos_embed[0, 1:].T.contiguous().view( + 1, -1, *self.patch_embed.patch_shape) + pe_2d = F.interpolate(pe_2d, out_size, mode='bicubic', align_corners=False).view(-1, h*w) + rescaled_positional_embedding[0, 1:] = pe_2d.T.contiguous() + + return rescaled_positional_embedding + + def mask_pool(self, x, masks,mode="qq"): + feature_map = self.encode_dense(x, keep_shape=False,mode=mode) + num_masks_per_image = [len(masks_per_image) for masks_per_image in masks] + masks = torch.cat(masks).float().flatten(-2, -1) # bs, h*w + feature_map = torch.repeat_interleave(feature_map, torch.tensor(num_masks_per_image, device=feature_map.device), dim=0) + features = (feature_map * masks.unsqueeze(-1)).sum(1) / (masks.sum(1, keepdim=True) + 1e-12) + + return features + + @staticmethod + def _denormalize_boxes(normed_boxes, x): + h, w = x.shape[-2:] + denormed_boxes = [] + for boxes in normed_boxes: + new_boxes = boxes.clone() # FIXME: do not change the value in normed_boxes! + new_boxes[:, [0, 2]] *= w + new_boxes[:, [1, 3]] *= h + denormed_boxes.append(new_boxes) + return denormed_boxes + + def encode_rois_and_image(self, x, normed_boxes): + bs, _, h, w = x.shape + h = h // self.patch_embed.patch_size[0] + w = w // self.patch_embed.patch_size[1] + x = self.patch_embed(x) + batch_size, seq_len, _ = x.size() + + cls_tokens = self.cls_token.expand(batch_size, -1, -1) # stole cls_tokens impl from Phil Wang, thanks + x = torch.cat((cls_tokens, x), dim=1) + if self.pos_embed is not None: + x = x + self.rescale_positional_embedding(out_size=(h, w)) + x = self.pos_drop(x) + + # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in + if os.getenv('RoPE') == '1': + if self.training and not isinstance(self.patch_dropout, nn.Identity): + x, patch_indices_keep = self.patch_dropout(x) + self.rope.forward = partial(self.rope.forward, patch_indices_keep=patch_indices_keep) + else: + self.rope.forward = partial(self.rope.forward, patch_indices_keep=None) + x = self.patch_dropout(x) + else: + x = self.patch_dropout(x) + + rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None + for blk in self.blocks[:-1]: + x = blk(x, rel_pos_bias=rel_pos_bias) + x_image = self.head( + self.post_attention( + self.blocks[-1]( + x, rel_pos_bias=rel_pos_bias) + ) + ) + x_image = F.normalize(x_image, dim=-1) + + x = self.blocks[-1].forward_without_attn(x)[:, 1:] + x = self.norm(x) + x = self.head(x) + assert self.fc_norm is None + x = F.normalize(x, dim=-1) # normalize along last dimension + x = x.view(bs, h, w, -1).permute(0, 3, 1, 2) + x_rois = roi_align(x, self._denormalize_boxes(normed_boxes, x), + (1, 1), 1.0, -1, True)[..., 0, 0] + x_rois = F.normalize(x_rois, dim=-1) + + return x_rois, x_image diff --git a/src/open_clip/eva_clip/factory.py b/src/open_clip/eva_clip/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..432f874feec85483fff706d2d315868715961559 --- /dev/null +++ b/src/open_clip/eva_clip/factory.py @@ -0,0 +1,455 @@ +import json +import logging +import os +import pathlib +import re +from copy import deepcopy +from pathlib import Path +from typing import Optional, Tuple, Union, Dict, Any +import torch + +from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD +from .model import CLIP, CustomCLIP, convert_weights_to_lp, convert_to_custom_text_state_dict,\ + get_cast_dtype +from .openai import load_openai_model +from .pretrained import is_pretrained_cfg, get_pretrained_cfg, download_pretrained, list_pretrained_tags_by_model +from .transform import image_transform +from .tokenizer import HFTokenizer, tokenize +from .utils import resize_clip_pos_embed, resize_evaclip_pos_embed, resize_visual_pos_embed, resize_eva_pos_embed + + +_MODEL_CONFIG_PATHS = [Path(__file__).parent / f"model_configs/"] +_MODEL_CONFIGS = {} # directory (model_name: config) of model architecture configs + + +def _natural_key(string_): + return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] + + +def _rescan_model_configs(): + global _MODEL_CONFIGS + + config_ext = ('.json',) + config_files = [] + for config_path in _MODEL_CONFIG_PATHS: + if config_path.is_file() and config_path.suffix in config_ext: + config_files.append(config_path) + elif config_path.is_dir(): + for ext in config_ext: + config_files.extend(config_path.glob(f'*{ext}')) + + for cf in config_files: + with open(cf, "r", encoding="utf8") as f: + model_cfg = json.load(f) + if all(a in model_cfg for a in ('embed_dim', 'vision_cfg', 'text_cfg')): + _MODEL_CONFIGS[cf.stem] = model_cfg + + _MODEL_CONFIGS = dict(sorted(_MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0]))) + + +_rescan_model_configs() # initial populate of model config registry + + +def list_models(): + """ enumerate available model architectures based on config files """ + return list(_MODEL_CONFIGS.keys()) + + +def add_model_config(path): + """ add model config path or file and update registry """ + if not isinstance(path, Path): + path = Path(path) + _MODEL_CONFIG_PATHS.append(path) + _rescan_model_configs() + + +def get_model_config(model_name): + if model_name in _MODEL_CONFIGS: + return deepcopy(_MODEL_CONFIGS[model_name]) + else: + return None + + +def get_tokenizer(model_name): + config = get_model_config(model_name) + tokenizer = HFTokenizer(config['text_cfg']['hf_tokenizer_name']) if 'hf_tokenizer_name' in config['text_cfg'] else tokenize + return tokenizer + + +# loading openai CLIP weights when is_openai=True for training +def load_state_dict(checkpoint_path: str, map_location: str='cpu', model_key: str='model|module|state_dict', is_openai: bool=False, skip_list: list=[]): + if is_openai: + model = torch.jit.load(checkpoint_path, map_location="cpu").eval() + state_dict = model.state_dict() + for key in ["input_resolution", "context_length", "vocab_size"]: + state_dict.pop(key, None) + else: + checkpoint = torch.load(checkpoint_path, map_location=map_location, weights_only=False) + for mk in model_key.split('|'): + if isinstance(checkpoint, dict) and mk in checkpoint: + state_dict = checkpoint[mk] + break + else: + state_dict = checkpoint + if next(iter(state_dict.items()))[0].startswith('module'): + state_dict = {k[7:]: v for k, v in state_dict.items()} + + for k in skip_list: + if k in list(state_dict.keys()): + logging.info(f"Removing key {k} from pretrained checkpoint") + del state_dict[k] + + if os.getenv('RoPE') == '1': + for k in list(state_dict.keys()): + if 'freqs_cos' in k or 'freqs_sin' in k: + del state_dict[k] + return state_dict + + + +def load_checkpoint(model, checkpoint_path, model_key="model|module|state_dict", strict=True): + state_dict = load_state_dict(checkpoint_path, model_key=model_key, is_openai=False) + # detect old format and make compatible with new format + if 'positional_embedding' in state_dict and not hasattr(model, 'positional_embedding'): + state_dict = convert_to_custom_text_state_dict(state_dict) + if 'text.logit_scale' in state_dict and hasattr(model, 'logit_scale'): + state_dict['logit_scale'] = state_dict['text.logit_scale'] + del state_dict['text.logit_scale'] + + # resize_clip_pos_embed for CLIP and open CLIP + if 'visual.positional_embedding' in state_dict: + resize_clip_pos_embed(state_dict, model) + # specified to eva_vit_model + elif 'visual.pos_embed' in state_dict: + resize_evaclip_pos_embed(state_dict, model) + + # resize_clip_pos_embed(state_dict, model) + incompatible_keys = model.load_state_dict(state_dict, strict=strict) + logging.info(f"incompatible_keys.missing_keys: {incompatible_keys.missing_keys}") + return incompatible_keys + +def load_clip_visual_state_dict(checkpoint_path: str, map_location: str='cpu', is_openai: bool=False, skip_list:list=[]): + state_dict = load_state_dict(checkpoint_path, map_location=map_location, is_openai=is_openai, skip_list=skip_list) + + for k in list(state_dict.keys()): + if not k.startswith('visual.'): + del state_dict[k] + for k in list(state_dict.keys()): + if k.startswith('visual.'): + new_k = k[7:] + state_dict[new_k] = state_dict[k] + del state_dict[k] + return state_dict + +def load_clip_text_state_dict(checkpoint_path: str, map_location: str='cpu', is_openai: bool=False, skip_list:list=[]): + state_dict = load_state_dict(checkpoint_path, map_location=map_location, is_openai=is_openai, skip_list=skip_list) + + for k in list(state_dict.keys()): + if k.startswith('visual.'): + del state_dict[k] + return state_dict + +def get_pretrained_tag(pretrained_model): + pretrained_model = pretrained_model.lower() + if "laion" in pretrained_model or "open_clip" in pretrained_model: + return "open_clip" + elif "openai" in pretrained_model: + return "clip" + elif "eva" in pretrained_model and "clip" in pretrained_model: + return "eva_clip" + else: + return "other" + +def load_pretrained_checkpoint( + model, + visual_checkpoint_path, + text_checkpoint_path, + strict=True, + visual_model=None, + text_model=None, + model_key="model|module|state_dict", + skip_list=[]): + visual_tag = get_pretrained_tag(visual_model) + text_tag = get_pretrained_tag(text_model) + + logging.info(f"num of model state_dict keys: {len(model.state_dict().keys())}") + visual_incompatible_keys, text_incompatible_keys = None, None + if visual_checkpoint_path: + if visual_tag == "eva_clip" or visual_tag == "open_clip": + visual_state_dict = load_clip_visual_state_dict(visual_checkpoint_path, is_openai=False, skip_list=skip_list) + elif visual_tag == "clip": + visual_state_dict = load_clip_visual_state_dict(visual_checkpoint_path, is_openai=True, skip_list=skip_list) + else: + visual_state_dict = load_state_dict(visual_checkpoint_path, model_key=model_key, is_openai=False, skip_list=skip_list) + + # resize_clip_pos_embed for CLIP and open CLIP + if 'positional_embedding' in visual_state_dict: + resize_visual_pos_embed(visual_state_dict, model) + # specified to EVA model + elif 'pos_embed' in visual_state_dict: + resize_eva_pos_embed(visual_state_dict, model) + + visual_incompatible_keys = model.visual.load_state_dict(visual_state_dict, strict=strict) + logging.info(f"num of loaded visual_state_dict keys: {len(visual_state_dict.keys())}") + logging.info(f"visual_incompatible_keys.missing_keys: {visual_incompatible_keys.missing_keys}") + + if text_checkpoint_path: + if text_tag == "eva_clip" or text_tag == "open_clip": + text_state_dict = load_clip_text_state_dict(text_checkpoint_path, is_openai=False, skip_list=skip_list) + elif text_tag == "clip": + text_state_dict = load_clip_text_state_dict(text_checkpoint_path, is_openai=True, skip_list=skip_list) + else: + text_state_dict = load_state_dict(visual_checkpoint_path, model_key=model_key, is_openai=False, skip_list=skip_list) + + text_incompatible_keys = model.text.load_state_dict(text_state_dict, strict=strict) + + logging.info(f"num of loaded text_state_dict keys: {len(text_state_dict.keys())}") + logging.info(f"text_incompatible_keys.missing_keys: {text_incompatible_keys.missing_keys}") + + return visual_incompatible_keys, text_incompatible_keys + +def create_model( + model_name: str, + pretrained: Optional[str] = None, + precision: str = 'fp32', + device: Union[str, torch.device] = 'cpu', + jit: bool = False, + force_quick_gelu: bool = False, + force_custom_clip: bool = False, + force_patch_dropout: Optional[float] = None, + pretrained_image: str = '', + pretrained_text: str = '', + pretrained_hf: bool = True, + pretrained_visual_model: str = None, + pretrained_text_model: str = None, + cache_dir: Optional[str] = None, + skip_list: list = [], +): + model_name = model_name.replace('/', '-') # for callers using old naming with / in ViT names + if isinstance(device, str): + device = torch.device(device) + + if pretrained and pretrained.lower() == 'openai': + logging.info(f'Loading pretrained {model_name} from OpenAI.') + model = load_openai_model( + model_name, + precision=precision, + device=device, + jit=jit, + cache_dir=cache_dir, + ) + else: + model_cfg = get_model_config(model_name) + if model_cfg is not None: + logging.info(f'Loaded {model_name} model config.') + else: + logging.error(f'Model config for {model_name} not found; available models {list_models()}.') + raise RuntimeError(f'Model config for {model_name} not found.') + if 'rope' in model_cfg.get('vision_cfg', {}): + if model_cfg['vision_cfg']['rope']: + os.environ['RoPE'] = "1" + else: + os.environ['RoPE'] = "0" + if force_quick_gelu: + # override for use of QuickGELU on non-OpenAI transformer models + model_cfg["quick_gelu"] = True + if force_patch_dropout is not None: + # override the default patch dropout value + model_cfg['vision_cfg']["patch_dropout"] = force_patch_dropout + + cast_dtype = get_cast_dtype(precision) + custom_clip = model_cfg.pop('custom_text', False) or force_custom_clip or ('hf_model_name' in model_cfg['text_cfg']) + if custom_clip: + if 'hf_model_name' in model_cfg.get('text_cfg', {}): + model_cfg['text_cfg']['hf_model_pretrained'] = pretrained_hf + model = CustomCLIP(**model_cfg, cast_dtype=cast_dtype) + else: + model = CLIP(**model_cfg, cast_dtype=cast_dtype) + pretrained_cfg = {} + + if pretrained: + checkpoint_path = '' + pretrained_cfg = get_pretrained_cfg(model_name, pretrained) + if pretrained_cfg: + checkpoint_path = download_pretrained(pretrained_cfg, cache_dir=cache_dir) + elif os.path.exists(pretrained): + checkpoint_path = pretrained + + if checkpoint_path: + logging.info(f'Loading pretrained {model_name} weights ({pretrained}).') + load_checkpoint(model, + checkpoint_path, + model_key="model|module|state_dict", + strict=False + ) + else: + error_str = ( + f'Pretrained weights ({pretrained}) not found for model {model_name}.' + f'Available pretrained tags ({list_pretrained_tags_by_model(model_name)}.') + logging.warning(error_str) + raise RuntimeError(error_str) + else: + visual_checkpoint_path = '' + text_checkpoint_path = '' + + if pretrained_image: + pretrained_visual_model = pretrained_visual_model.replace('/', '-') # for callers using old naming with / in ViT names + pretrained_image_cfg = get_pretrained_cfg(pretrained_visual_model, pretrained_image) + if 'timm_model_name' in model_cfg.get('vision_cfg', {}): + # pretrained weight loading for timm models set via vision_cfg + model_cfg['vision_cfg']['timm_model_pretrained'] = True + elif pretrained_image_cfg: + visual_checkpoint_path = download_pretrained(pretrained_image_cfg, cache_dir=cache_dir) + elif os.path.exists(pretrained_image): + visual_checkpoint_path = pretrained_image + else: + logging.warning(f'Pretrained weights ({visual_checkpoint_path}) not found for model {model_name}.visual.') + raise RuntimeError(f'Pretrained weights ({visual_checkpoint_path}) not found for model {model_name}.visual.') + + if pretrained_text: + pretrained_text_model = pretrained_text_model.replace('/', '-') # for callers using old naming with / in ViT names + pretrained_text_cfg = get_pretrained_cfg(pretrained_text_model, pretrained_text) + if pretrained_image_cfg: + text_checkpoint_path = download_pretrained(pretrained_text_cfg, cache_dir=cache_dir) + elif os.path.exists(pretrained_text): + text_checkpoint_path = pretrained_text + else: + logging.warning(f'Pretrained weights ({text_checkpoint_path}) not found for model {model_name}.text.') + raise RuntimeError(f'Pretrained weights ({text_checkpoint_path}) not found for model {model_name}.text.') + + if visual_checkpoint_path: + logging.info(f'Loading pretrained {model_name}.visual weights ({visual_checkpoint_path}).') + if text_checkpoint_path: + logging.info(f'Loading pretrained {model_name}.text weights ({text_checkpoint_path}).') + + if visual_checkpoint_path or text_checkpoint_path: + load_pretrained_checkpoint( + model, + visual_checkpoint_path, + text_checkpoint_path, + strict=False, + visual_model=pretrained_visual_model, + text_model=pretrained_text_model, + model_key="model|module|state_dict", + skip_list=skip_list + ) + + if "fp16" in precision or "bf16" in precision: + logging.info(f'convert precision to {precision}') + model = model.to(torch.bfloat16) if 'bf16' in precision else model.to(torch.float16) + + model.to(device=device) + + # set image / mean metadata from pretrained_cfg if available, or use default + model.visual.image_mean = pretrained_cfg.get('mean', None) or OPENAI_DATASET_MEAN + model.visual.image_std = pretrained_cfg.get('std', None) or OPENAI_DATASET_STD + + if jit: + model = torch.jit.script(model) + + return model + + +def create_model_and_transforms( + model_name: str, + pretrained: Optional[str] = None, + precision: str = 'fp32', + device: Union[str, torch.device] = 'cpu', + jit: bool = False, + force_quick_gelu: bool = False, + force_custom_clip: bool = False, + force_patch_dropout: Optional[float] = None, + pretrained_image: str = '', + pretrained_text: str = '', + pretrained_hf: bool = True, + pretrained_visual_model: str = None, + pretrained_text_model: str = None, + image_mean: Optional[Tuple[float, ...]] = None, + image_std: Optional[Tuple[float, ...]] = None, + cache_dir: Optional[str] = None, + skip_list: list = [], +): + model = create_model( + model_name, + pretrained, + precision=precision, + device=device, + jit=jit, + force_quick_gelu=force_quick_gelu, + force_custom_clip=force_custom_clip, + force_patch_dropout=force_patch_dropout, + pretrained_image=pretrained_image, + pretrained_text=pretrained_text, + pretrained_hf=pretrained_hf, + pretrained_visual_model=pretrained_visual_model, + pretrained_text_model=pretrained_text_model, + cache_dir=cache_dir, + skip_list=skip_list, + ) + + image_mean = image_mean or getattr(model.visual, 'image_mean', None) + image_std = image_std or getattr(model.visual, 'image_std', None) + preprocess_train = image_transform( + model.visual.image_size, + is_train=True, + mean=image_mean, + std=image_std + ) + preprocess_val = image_transform( + model.visual.image_size, + is_train=False, + mean=image_mean, + std=image_std + ) + + return model, preprocess_train, preprocess_val + +def create_model_from_pretrained( + model_name: str, + pretrained: str, + precision: str = 'fp32', + device: Union[str, torch.device] = 'cpu', + jit: bool = False, + force_quick_gelu: bool = False, + force_custom_clip: bool = False, + force_patch_dropout: Optional[float] = None, + return_transform: bool = True, + image_mean: Optional[Tuple[float, ...]] = None, + image_std: Optional[Tuple[float, ...]] = None, + cache_dir: Optional[str] = None, + is_frozen: bool = False, +): + if not is_pretrained_cfg(model_name, pretrained) and not os.path.exists(pretrained): + raise RuntimeError( + f'{pretrained} is not a valid pretrained cfg or checkpoint for {model_name}.' + f' Use open_clip.list_pretrained() to find one.') + + model = create_model( + model_name, + pretrained, + precision=precision, + device=device, + jit=jit, + force_quick_gelu=force_quick_gelu, + force_custom_clip=force_custom_clip, + force_patch_dropout=force_patch_dropout, + cache_dir=cache_dir, + ) + + if is_frozen: + for param in model.parameters(): + param.requires_grad = False + + if not return_transform: + return model + + image_mean = image_mean or getattr(model.visual, 'image_mean', None) + image_std = image_std or getattr(model.visual, 'image_std', None) + preprocess = image_transform( + model.visual.image_size, + is_train=False, + mean=image_mean, + std=image_std + ) + + return model, preprocess diff --git a/src/open_clip/eva_clip/hf_configs.py b/src/open_clip/eva_clip/hf_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..a8c9b704db1879676aed5cef26796303b65fe987 --- /dev/null +++ b/src/open_clip/eva_clip/hf_configs.py @@ -0,0 +1,57 @@ +# HF architecture dict: +arch_dict = { + # https://huggingface.co/docs/transformers/model_doc/roberta#roberta + "roberta": { + "config_names": { + "context_length": "max_position_embeddings", + "vocab_size": "vocab_size", + "width": "hidden_size", + "heads": "num_attention_heads", + "layers": "num_hidden_layers", + "layer_attr": "layer", + "token_embeddings_attr": "embeddings" + }, + "pooler": "mean_pooler", + }, + # https://huggingface.co/docs/transformers/model_doc/xlm-roberta#transformers.XLMRobertaConfig + "xlm-roberta": { + "config_names": { + "context_length": "max_position_embeddings", + "vocab_size": "vocab_size", + "width": "hidden_size", + "heads": "num_attention_heads", + "layers": "num_hidden_layers", + "layer_attr": "layer", + "token_embeddings_attr": "embeddings" + }, + "pooler": "mean_pooler", + }, + # https://huggingface.co/docs/transformers/model_doc/mt5#mt5 + "mt5": { + "config_names": { + # unlimited seqlen + # https://github.com/google-research/text-to-text-transfer-transformer/issues/273 + # https://github.com/huggingface/transformers/blob/v4.24.0/src/transformers/models/t5/modeling_t5.py#L374 + "context_length": "", + "vocab_size": "vocab_size", + "width": "d_model", + "heads": "num_heads", + "layers": "num_layers", + "layer_attr": "block", + "token_embeddings_attr": "embed_tokens" + }, + "pooler": "mean_pooler", + }, + "bert": { + "config_names": { + "context_length": "max_position_embeddings", + "vocab_size": "vocab_size", + "width": "hidden_size", + "heads": "num_attention_heads", + "layers": "num_hidden_layers", + "layer_attr": "layer", + "token_embeddings_attr": "embeddings" + }, + "pooler": "mean_pooler", + } +} diff --git a/src/open_clip/eva_clip/hf_model.py b/src/open_clip/eva_clip/hf_model.py new file mode 100644 index 0000000000000000000000000000000000000000..c4b9fd85b4066ba31db2bda5767ed1ce15de479d --- /dev/null +++ b/src/open_clip/eva_clip/hf_model.py @@ -0,0 +1,248 @@ +""" huggingface model adapter + +Wraps HuggingFace transformers (https://github.com/huggingface/transformers) models for use as a text tower in CLIP model. +""" + +import re + +import torch +import torch.nn as nn +from torch.nn import functional as F +from torch import TensorType +try: + import transformers + from transformers import AutoModel, AutoModelForMaskedLM, AutoTokenizer, AutoConfig, PretrainedConfig + from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, \ + BaseModelOutputWithPoolingAndCrossAttentions +except ImportError as e: + transformers = None + + + class BaseModelOutput: + pass + + + class PretrainedConfig: + pass + +from .hf_configs import arch_dict + +# utils +def _camel2snake(s): + return re.sub(r'(? TensorType: + # image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(x.device) + # attn_mask = (x != self.config.pad_token_id).long() + # out = self.transformer( + # input_ids=x, + # attention_mask=attn_mask, + # encoder_hidden_states = image_embeds, + # encoder_attention_mask = image_atts, + # ) + # pooled_out = self.pooler(out, attn_mask) + + # return self.itm_proj(pooled_out) + + def mask(self, input_ids, vocab_size, device, targets=None, masked_indices=None, probability_matrix=None): + if masked_indices is None: + masked_indices = torch.bernoulli(probability_matrix).bool() + + masked_indices[input_ids == self.tokenizer.pad_token_id] = False + masked_indices[input_ids == self.tokenizer.cls_token_id] = False + + if targets is not None: + targets[~masked_indices] = -100 # We only compute loss on masked tokens + + # 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK]) + indices_replaced = torch.bernoulli(torch.full(input_ids.shape, 0.8)).bool() & masked_indices + input_ids[indices_replaced] = self.tokenizer.mask_token_id + + # 10% of the time, we replace masked input tokens with random word + indices_random = torch.bernoulli(torch.full(input_ids.shape, 0.5)).bool() & masked_indices & ~indices_replaced + random_words = torch.randint(vocab_size, input_ids.shape, dtype=torch.long).to(device) + input_ids[indices_random] = random_words[indices_random] + # The rest of the time (10% of the time) we keep the masked input tokens unchanged + + if targets is not None: + return input_ids, targets + else: + return input_ids + + def forward_mlm(self, input_ids, image_embeds, mlm_probability=0.25): + labels = input_ids.clone() + attn_mask = (input_ids != self.config.pad_token_id).long() + image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(input_ids.device) + vocab_size = getattr(self.config, arch_dict[self.config.model_type]["config_names"]["vocab_size"]) + probability_matrix = torch.full(labels.shape, mlm_probability) + input_ids, labels = self.mask(input_ids, vocab_size, input_ids.device, targets=labels, + probability_matrix = probability_matrix) + mlm_output = self.transformer(input_ids, + attention_mask = attn_mask, + encoder_hidden_states = image_embeds, + encoder_attention_mask = image_atts, + return_dict = True, + labels = labels, + ) + return mlm_output.loss + # mlm_output = self.transformer(input_ids, + # attention_mask = attn_mask, + # encoder_hidden_states = image_embeds, + # encoder_attention_mask = image_atts, + # return_dict = True, + # ).last_hidden_state + # logits = self.mlm_proj(mlm_output) + + # # logits = logits[:, :-1, :].contiguous().view(-1, vocab_size) + # logits = logits[:, 1:, :].contiguous().view(-1, vocab_size) + # labels = labels[:, 1:].contiguous().view(-1) + + # mlm_loss = F.cross_entropy( + # logits, + # labels, + # # label_smoothing=0.1, + # ) + # return mlm_loss + + + def forward(self, x:TensorType) -> TensorType: + attn_mask = (x != self.config.pad_token_id).long() + out = self.transformer(input_ids=x, attention_mask=attn_mask) + pooled_out = self.pooler(out, attn_mask) + + return self.proj(pooled_out) + + def lock(self, unlocked_layers:int=0, freeze_layer_norm:bool=True): + if not unlocked_layers: # full freezing + for n, p in self.transformer.named_parameters(): + p.requires_grad = (not freeze_layer_norm) if "LayerNorm" in n.split(".") else False + return + + encoder = self.transformer.encoder if hasattr(self.transformer, 'encoder') else self.transformer + layer_list = getattr(encoder, arch_dict[self.config.model_type]["config_names"]["layer_attr"]) + print(f"Unlocking {unlocked_layers}/{len(layer_list) + 1} layers of hf model") + embeddings = getattr( + self.transformer, arch_dict[self.config.model_type]["config_names"]["token_embeddings_attr"]) + modules = [embeddings, *layer_list][:-unlocked_layers] + # freeze layers + for module in modules: + for n, p in module.named_parameters(): + p.requires_grad = (not freeze_layer_norm) if "LayerNorm" in n.split(".") else False + + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.transformer.gradient_checkpointing_enable() + + def get_num_layers(self): + encoder = self.transformer.encoder if hasattr(self.transformer, 'encoder') else self.transformer + layer_list = getattr(encoder, arch_dict[self.config.model_type]["config_names"]["layer_attr"]) + return len(layer_list) + + def init_parameters(self): + pass diff --git a/src/open_clip/eva_clip/loss.py b/src/open_clip/eva_clip/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..473f60d98d501067e85ace2dd089b00e249b6d17 --- /dev/null +++ b/src/open_clip/eva_clip/loss.py @@ -0,0 +1,138 @@ +import math +import torch +import torch.nn as nn +from torch.nn import functional as F + +try: + import torch.distributed.nn + from torch import distributed as dist + has_distributed = True +except ImportError: + has_distributed = False + +try: + import horovod.torch as hvd +except ImportError: + hvd = None + +from timm.loss import LabelSmoothingCrossEntropy + + +def gather_features( + image_features, + text_features, + local_loss=False, + gather_with_grad=False, + rank=0, + world_size=1, + use_horovod=False +): + assert has_distributed, 'torch.distributed did not import correctly, please use a PyTorch version with support.' + if use_horovod: + assert hvd is not None, 'Please install horovod' + if gather_with_grad: + all_image_features = hvd.allgather(image_features) + all_text_features = hvd.allgather(text_features) + else: + with torch.no_grad(): + all_image_features = hvd.allgather(image_features) + all_text_features = hvd.allgather(text_features) + if not local_loss: + # ensure grads for local rank when all_* features don't have a gradient + gathered_image_features = list(all_image_features.chunk(world_size, dim=0)) + gathered_text_features = list(all_text_features.chunk(world_size, dim=0)) + gathered_image_features[rank] = image_features + gathered_text_features[rank] = text_features + all_image_features = torch.cat(gathered_image_features, dim=0) + all_text_features = torch.cat(gathered_text_features, dim=0) + else: + # We gather tensors from all gpus + if gather_with_grad: + all_image_features = torch.cat(torch.distributed.nn.all_gather(image_features), dim=0) + all_text_features = torch.cat(torch.distributed.nn.all_gather(text_features), dim=0) + # all_image_features = torch.cat(torch.distributed.nn.all_gather(image_features, async_op=True), dim=0) + # all_text_features = torch.cat(torch.distributed.nn.all_gather(text_features, async_op=True), dim=0) + else: + gathered_image_features = [torch.zeros_like(image_features) for _ in range(world_size)] + gathered_text_features = [torch.zeros_like(text_features) for _ in range(world_size)] + dist.all_gather(gathered_image_features, image_features) + dist.all_gather(gathered_text_features, text_features) + if not local_loss: + # ensure grads for local rank when all_* features don't have a gradient + gathered_image_features[rank] = image_features + gathered_text_features[rank] = text_features + all_image_features = torch.cat(gathered_image_features, dim=0) + all_text_features = torch.cat(gathered_text_features, dim=0) + + return all_image_features, all_text_features + + +class ClipLoss(nn.Module): + + def __init__( + self, + local_loss=False, + gather_with_grad=False, + cache_labels=False, + rank=0, + world_size=1, + use_horovod=False, + smoothing=0., + ): + super().__init__() + self.local_loss = local_loss + self.gather_with_grad = gather_with_grad + self.cache_labels = cache_labels + self.rank = rank + self.world_size = world_size + self.use_horovod = use_horovod + self.label_smoothing_cross_entropy = LabelSmoothingCrossEntropy(smoothing=smoothing) if smoothing > 0 else None + + # cache state + self.prev_num_logits = 0 + self.labels = {} + + def forward(self, image_features, text_features, logit_scale=1.): + device = image_features.device + if self.world_size > 1: + all_image_features, all_text_features = gather_features( + image_features, text_features, + self.local_loss, self.gather_with_grad, self.rank, self.world_size, self.use_horovod) + + if self.local_loss: + logits_per_image = logit_scale * image_features @ all_text_features.T + logits_per_text = logit_scale * text_features @ all_image_features.T + else: + logits_per_image = logit_scale * all_image_features @ all_text_features.T + logits_per_text = logits_per_image.T + else: + logits_per_image = logit_scale * image_features @ text_features.T + logits_per_text = logit_scale * text_features @ image_features.T + # calculated ground-truth and cache if enabled + num_logits = logits_per_image.shape[0] + if self.prev_num_logits != num_logits or device not in self.labels: + labels = torch.arange(num_logits, device=device, dtype=torch.long) + if self.world_size > 1 and self.local_loss: + labels = labels + num_logits * self.rank + if self.cache_labels: + self.labels[device] = labels + self.prev_num_logits = num_logits + else: + labels = self.labels[device] + + if self.label_smoothing_cross_entropy: + total_loss = ( + self.label_smoothing_cross_entropy(logits_per_image, labels) + + self.label_smoothing_cross_entropy(logits_per_text, labels) + ) / 2 + else: + total_loss = ( + F.cross_entropy(logits_per_image, labels) + + F.cross_entropy(logits_per_text, labels) + ) / 2 + + acc = None + i2t_acc = (logits_per_image.argmax(-1) == labels).sum() / len(logits_per_image) + t2i_acc = (logits_per_text.argmax(-1) == labels).sum() / len(logits_per_text) + acc = {"i2t": i2t_acc, "t2i": t2i_acc} + return total_loss, acc \ No newline at end of file diff --git a/src/open_clip/eva_clip/model.py b/src/open_clip/eva_clip/model.py new file mode 100644 index 0000000000000000000000000000000000000000..df8ace7ddaceeec2b0c9792e7d85634506665272 --- /dev/null +++ b/src/open_clip/eva_clip/model.py @@ -0,0 +1,541 @@ +""" CLIP Model + +Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. +""" +import os +from dataclasses import dataclass +from typing import Optional, Tuple, Union +from functools import partial + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn + +try: + from .hf_model import HFTextEncoder +except: + HFTextEncoder = None +from .modified_resnet import ModifiedResNet +from .timm_model import TimmModel +from .eva_vit_model import EVAVisionTransformer +from .transformer import LayerNorm, QuickGELU, Attention, VisionTransformer, TextTransformer + +# 强制使用标准 LayerNorm,避免 apex 版本兼容性问题 +FusedLayerNorm = LayerNorm + +try: + import xformers.ops as xops +except ImportError: + xops = None + print("Please 'pip install xformers'") + +@dataclass +class CLIPVisionCfg: + layers: Union[Tuple[int, int, int, int], int] = 12 + width: int = 768 + head_width: int = 64 + mlp_ratio: float = 4.0 + patch_size: int = 16 + image_size: Union[Tuple[int, int], int] = 224 + ls_init_value: Optional[float] = None # layer scale initial value + patch_dropout: float = 0. # what fraction of patches to dropout during training (0 would mean disabled and no patches dropped) - 0.5 to 0.75 recommended in the paper for optimal results + global_average_pool: bool = False # whether to global average pool the last embedding layer, instead of using CLS token (https://arxiv.org/abs/2205.01580) + drop_path_rate: Optional[float] = None # drop path rate + timm_model_name: str = None # a valid model name overrides layers, width, patch_size + timm_model_pretrained: bool = False # use (imagenet) pretrained weights for named model + timm_pool: str = 'avg' # feature pooling for timm model ('abs_attn', 'rot_attn', 'avg', '') + timm_proj: str = 'linear' # linear projection for timm model output ('linear', 'mlp', '') + timm_proj_bias: bool = False # enable bias final projection + eva_model_name: str = None # a valid eva model name overrides layers, width, patch_size + qkv_bias: bool = True + fusedLN: bool = False + xattn: bool = False + postnorm: bool = False + rope: bool = False + pt_hw_seq_len: int = 16 # 224/14 + intp_freq: bool = False + naiveswiglu: bool = False + subln: bool = False + + +@dataclass +class CLIPTextCfg: + context_length: int = 77 + vocab_size: int = 49408 + width: int = 512 + heads: int = 8 + layers: int = 12 + ls_init_value: Optional[float] = None # layer scale initial value + hf_model_name: str = None + hf_tokenizer_name: str = None + hf_model_pretrained: bool = True + proj: str = 'mlp' + pooler_type: str = 'mean_pooler' + masked_language_modeling: bool = False + fusedLN: bool = False + xattn: bool = False + attn_mask: bool = True + +def get_cast_dtype(precision: str): + cast_dtype = None + if precision == 'bf16': + cast_dtype = torch.bfloat16 + elif precision == 'fp16': + cast_dtype = torch.float16 + return cast_dtype + + +def _build_vision_tower( + embed_dim: int, + vision_cfg: CLIPVisionCfg, + quick_gelu: bool = False, + cast_dtype: Optional[torch.dtype] = None +): + if isinstance(vision_cfg, dict): + vision_cfg = CLIPVisionCfg(**vision_cfg) + + # OpenAI models are pretrained w/ QuickGELU but native nn.GELU is both faster and more + # memory efficient in recent PyTorch releases (>= 1.10). + # NOTE: timm models always use native GELU regardless of quick_gelu flag. + act_layer = QuickGELU if quick_gelu else nn.GELU + + if vision_cfg.eva_model_name: + vision_heads = vision_cfg.width // vision_cfg.head_width + norm_layer = LayerNorm + + visual = EVAVisionTransformer( + img_size=vision_cfg.image_size, + patch_size=vision_cfg.patch_size, + num_classes=embed_dim, + use_mean_pooling=vision_cfg.global_average_pool, #False + init_values=vision_cfg.ls_init_value, + patch_dropout=vision_cfg.patch_dropout, + embed_dim=vision_cfg.width, + depth=vision_cfg.layers, + num_heads=vision_heads, + mlp_ratio=vision_cfg.mlp_ratio, + qkv_bias=vision_cfg.qkv_bias, + drop_path_rate=vision_cfg.drop_path_rate, + norm_layer= partial(FusedLayerNorm, eps=1e-6) if vision_cfg.fusedLN else partial(norm_layer, eps=1e-6), + xattn=vision_cfg.xattn, + rope=vision_cfg.rope, + postnorm=vision_cfg.postnorm, + pt_hw_seq_len= vision_cfg.pt_hw_seq_len, # 224/14 + intp_freq= vision_cfg.intp_freq, + naiveswiglu= vision_cfg.naiveswiglu, + subln= vision_cfg.subln + ) + elif vision_cfg.timm_model_name: + visual = TimmModel( + vision_cfg.timm_model_name, + pretrained=vision_cfg.timm_model_pretrained, + pool=vision_cfg.timm_pool, + proj=vision_cfg.timm_proj, + proj_bias=vision_cfg.timm_proj_bias, + embed_dim=embed_dim, + image_size=vision_cfg.image_size + ) + act_layer = nn.GELU # so that text transformer doesn't use QuickGELU w/ timm models + elif isinstance(vision_cfg.layers, (tuple, list)): + vision_heads = vision_cfg.width * 32 // vision_cfg.head_width + visual = ModifiedResNet( + layers=vision_cfg.layers, + output_dim=embed_dim, + heads=vision_heads, + image_size=vision_cfg.image_size, + width=vision_cfg.width + ) + else: + vision_heads = vision_cfg.width // vision_cfg.head_width + norm_layer = LayerNormFp32 if cast_dtype in (torch.float16, torch.bfloat16) else LayerNorm + visual = VisionTransformer( + image_size=vision_cfg.image_size, + patch_size=vision_cfg.patch_size, + width=vision_cfg.width, + layers=vision_cfg.layers, + heads=vision_heads, + mlp_ratio=vision_cfg.mlp_ratio, + ls_init_value=vision_cfg.ls_init_value, + patch_dropout=vision_cfg.patch_dropout, + global_average_pool=vision_cfg.global_average_pool, + output_dim=embed_dim, + act_layer=act_layer, + norm_layer=norm_layer, + ) + + return visual + + +def _build_text_tower( + embed_dim: int, + text_cfg: CLIPTextCfg, + quick_gelu: bool = False, + cast_dtype: Optional[torch.dtype] = None, +): + if isinstance(text_cfg, dict): + text_cfg = CLIPTextCfg(**text_cfg) + + if text_cfg.hf_model_name: + text = HFTextEncoder( + text_cfg.hf_model_name, + output_dim=embed_dim, + tokenizer_name=text_cfg.hf_tokenizer_name, + proj=text_cfg.proj, + pooler_type=text_cfg.pooler_type, + masked_language_modeling=text_cfg.masked_language_modeling + ) + else: + act_layer = QuickGELU if quick_gelu else nn.GELU + norm_layer = LayerNorm + + text = TextTransformer( + context_length=text_cfg.context_length, + vocab_size=text_cfg.vocab_size, + width=text_cfg.width, + heads=text_cfg.heads, + layers=text_cfg.layers, + ls_init_value=text_cfg.ls_init_value, + output_dim=embed_dim, + act_layer=act_layer, + norm_layer= FusedLayerNorm if text_cfg.fusedLN else norm_layer, + xattn=text_cfg.xattn, + attn_mask=text_cfg.attn_mask, + ) + return text + + +class CLIP(nn.Module): + def __init__( + self, + embed_dim: int, + vision_cfg: CLIPVisionCfg, + text_cfg: CLIPTextCfg, + quick_gelu: bool = False, + cast_dtype: Optional[torch.dtype] = None, + ): + super().__init__() + self.visual = _build_vision_tower(embed_dim, vision_cfg, quick_gelu, cast_dtype) + + text = _build_text_tower(embed_dim, text_cfg, quick_gelu, cast_dtype) + self.transformer = text.transformer + self.embed_dim = embed_dim + self.vocab_size = text.vocab_size + self.token_embedding = text.token_embedding + self.positional_embedding = text.positional_embedding + self.ln_final = text.ln_final + self.text_projection = text.text_projection + self.register_buffer('attn_mask', text.attn_mask, persistent=False) + + self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) + + def lock_image_tower(self, unlocked_groups=0, freeze_bn_stats=False): + # lock image tower as per LiT - https://arxiv.org/abs/2111.07991 + self.visual.lock(unlocked_groups=unlocked_groups, freeze_bn_stats=freeze_bn_stats) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.visual.set_grad_checkpointing(enable) + self.transformer.grad_checkpointing = enable + + @torch.jit.ignore + def no_weight_decay(self): + return {'logit_scale'} + + def encode_image(self, image, normalize: bool = False): + features = self.visual(image) + return F.normalize(features, dim=-1) if normalize else features + + def encode_text(self, text, normalize: bool = False): + cast_dtype = self.transformer.get_cast_dtype() + + x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model] + + x = x + self.positional_embedding.to(cast_dtype) + x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer(x, attn_mask=self.attn_mask) + x = x.permute(1, 0, 2) # LND -> NLD + x = self.ln_final(x) # [batch_size, n_ctx, transformer.width] + # take features from the eot embedding (eot_token is the highest number in each sequence) + x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection + return F.normalize(x, dim=-1) if normalize else x + + def forward(self, image, text): + image_features = self.encode_image(image, normalize=True) + text_features = self.encode_text(text, normalize=True) + return image_features, text_features, self.logit_scale.exp() + + +class CustomCLIP(nn.Module): + def __init__( + self, + embed_dim: int, + vision_cfg: CLIPVisionCfg, + text_cfg: CLIPTextCfg, + quick_gelu: bool = False, + cast_dtype: Optional[torch.dtype] = None, + itm_task: bool = False, + ): + super().__init__() + self.visual = _build_vision_tower(embed_dim, vision_cfg, quick_gelu, cast_dtype) + self.text = _build_text_tower(embed_dim, text_cfg, quick_gelu, cast_dtype) + self.embed_dim = embed_dim + print(f'Freeze text encoder parameters', flush=True) + for param in self.text.parameters(): + param.requires_grad = False + self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) + + def train(self, mode=True): + super().train(mode) + self.text.train(mode=False) + return self + + def lock_image_tower(self, unlocked_groups=0, freeze_bn_stats=False, **kwargs): + + # lock image tower as per LiT - https://arxiv.org/abs/2111.07991 + self.visual.lock(unlocked_groups=unlocked_groups, freeze_bn_stats=freeze_bn_stats) + + def lock_text_tower(self, unlocked_layers:int=0, freeze_layer_norm:bool=True): + self.text.lock(unlocked_layers, freeze_layer_norm) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.visual.set_grad_checkpointing(enable) + self.text.set_grad_checkpointing(enable) + + @torch.jit.ignore + def no_weight_decay(self): + return {'logit_scale'} + + def encode_image(self, image, normalize: bool = False): + features = self.visual(image) + return F.normalize(features, dim=-1) if normalize else features + + def encode_text(self, text, normalize: bool = False): + features = self.text(text) + return F.normalize(features, dim=-1) if normalize else features + + def forward(self, image, text): + image_features = self.encode_image(image, normalize=True) + text_features = self.encode_text(text, normalize=True) + return image_features, text_features, self.logit_scale.exp() + + def encode_dense( + self, + image, + normalize: bool = False, + keep_shape=False, + mode="qq", + get_intermediate_layer=None + ): + outputs = self.visual.encode_dense( + image, + keep_shape=keep_shape, + mode=mode, + get_intermediate_layer=get_intermediate_layer + ) + + # outputs 可能是 2个(features, extra_features)或者3个(features, extra_features, intermediate_outputs) + if 'distill' in mode or mode == "sanity_check": + if get_intermediate_layer: + features, extra_features, intermediate_outputs = outputs + else: + features, extra_features = outputs + intermediate_outputs = None + + if normalize: + if keep_shape: + features = F.normalize(features, dim=1) + else: + features = F.normalize(features, dim=-1) + + if get_intermediate_layer: + return features, extra_features, intermediate_outputs + else: + return features, extra_features + else: + if get_intermediate_layer: + features, intermediate_outputs = outputs + else: + features = outputs + intermediate_outputs = None + + if normalize: + if keep_shape: + features = F.normalize(features, dim=1) + else: + features = F.normalize(features, dim=-1) + + if get_intermediate_layer: + return features, intermediate_outputs + else: + return features + + def encode_pseudo_boxes(self, image, normed_boxes, normalize: bool = False, mode="qq", get_intermediate_layer=None, size=(1, 1)): + outputs = self.visual.extract_roi_features( + image, + normed_boxes, + mode=mode, + get_intermediate_layer=get_intermediate_layer, + size=size) + + if 'distill' in mode or mode == "sanity_check": + if get_intermediate_layer: + # box_features, clip_dense_feats, intermediate_outputs + box_features, context_feats, intermediate_outputs = outputs + else: + box_features, context_feats = outputs + intermediate_outputs = None + if normalize: + box_features = F.normalize(box_features, dim=-1) + if get_intermediate_layer: + return box_features, context_feats, intermediate_outputs + else: + return box_features, context_feats + else: + if get_intermediate_layer: + # box_features, intermediate_outputs + box_features, intermediate_outputs = outputs + else: + box_features = outputs + intermediate_outputs = None + + if normalize: + box_features = F.normalize(box_features, dim=-1) + + if get_intermediate_layer: + return box_features, intermediate_outputs + else: + return box_features + + def encode_masks(self, image, masks, normalize=True, mode="qq"): + mask_pooled = self.visual.mask_pool(image, masks, mode) + if normalize: + mask_pooled = F.normalize(mask_pooled, dim=-1) + return mask_pooled + + +def convert_weights_to_lp(model: nn.Module, dtype=torch.float16): + """Convert applicable model parameters to low-precision (bf16 or fp16)""" + + def _convert_weights(l): + if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): + l.weight.data = l.weight.data.to(dtype) + if l.bias is not None: + l.bias.data = l.bias.data.to(dtype) + + if isinstance(l, (nn.MultiheadAttention, Attention)): + for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]: + tensor = getattr(l, attr, None) + if tensor is not None: + tensor.data = tensor.data.to(dtype) + + if isinstance(l, nn.Parameter): + l.data = l.data.to(dtype) + + for name in ["text_projection", "proj"]: + if hasattr(l, name) and isinstance(l, nn.Parameter): + attr = getattr(l, name, None) + if attr is not None: + attr.data = attr.data.to(dtype) + + model.apply(_convert_weights) + + +convert_weights_to_fp16 = convert_weights_to_lp # backwards compat + + +# used to maintain checkpoint compatibility +def convert_to_custom_text_state_dict(state_dict: dict): + if 'text_projection' in state_dict: + # old format state_dict, move text tower -> .text + new_state_dict = {} + for k, v in state_dict.items(): + if any(k.startswith(p) for p in ( + 'text_projection', + 'positional_embedding', + 'token_embedding', + 'transformer', + 'ln_final', + 'logit_scale' + )): + k = 'text.' + k + new_state_dict[k] = v + return new_state_dict + return state_dict + + +def build_model_from_openai_state_dict( + state_dict: dict, + quick_gelu=True, + cast_dtype=torch.float16, +): + vit = "visual.proj" in state_dict + + if vit: + vision_width = state_dict["visual.conv1.weight"].shape[0] + vision_layers = len( + [k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")]) + vision_patch_size = state_dict["visual.conv1.weight"].shape[-1] + grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5) + image_size = vision_patch_size * grid_size + else: + counts: list = [ + len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]] + vision_layers = tuple(counts) + vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0] + output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5) + vision_patch_size = None + assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0] + image_size = output_width * 32 + + embed_dim = state_dict["text_projection"].shape[1] + context_length = state_dict["positional_embedding"].shape[0] + vocab_size = state_dict["token_embedding.weight"].shape[0] + transformer_width = state_dict["ln_final.weight"].shape[0] + transformer_heads = transformer_width // 64 + transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks"))) + + vision_cfg = CLIPVisionCfg( + layers=vision_layers, + width=vision_width, + patch_size=vision_patch_size, + image_size=image_size, + ) + text_cfg = CLIPTextCfg( + context_length=context_length, + vocab_size=vocab_size, + width=transformer_width, + heads=transformer_heads, + layers=transformer_layers + ) + model = CLIP( + embed_dim, + vision_cfg=vision_cfg, + text_cfg=text_cfg, + quick_gelu=quick_gelu, # OpenAI models were trained with QuickGELU + cast_dtype=cast_dtype, + ) + + for key in ["input_resolution", "context_length", "vocab_size"]: + state_dict.pop(key, None) + + convert_weights_to_fp16(model) # OpenAI state dicts are partially converted to float16 + model.load_state_dict(state_dict) + return model.eval() + + +def trace_model(model, batch_size=256, device=torch.device('cpu')): + model.eval() + image_size = model.visual.image_size + example_images = torch.ones((batch_size, 3, image_size, image_size), device=device) + example_text = torch.zeros((batch_size, model.context_length), dtype=torch.int, device=device) + model = torch.jit.trace_module( + model, + inputs=dict( + forward=(example_images, example_text), + encode_text=(example_text,), + encode_image=(example_images,) + )) + model.visual.image_size = image_size + return model diff --git a/src/open_clip/eva_clip/model_configs/EVA01-CLIP-B-16.json b/src/open_clip/eva_clip/model_configs/EVA01-CLIP-B-16.json new file mode 100644 index 0000000000000000000000000000000000000000..aad2058003962a4ab286bf4e1ae956288af34e62 --- /dev/null +++ b/src/open_clip/eva_clip/model_configs/EVA01-CLIP-B-16.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 16, + "eva_model_name": "eva-clip-b-16", + "ls_init_value": 0.1, + "drop_path_rate": 0.0 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/eva_clip/model_configs/EVA01-CLIP-g-14-plus.json b/src/open_clip/eva_clip/model_configs/EVA01-CLIP-g-14-plus.json new file mode 100644 index 0000000000000000000000000000000000000000..100279572ff6d1bcca601f0eb526b4d4ff174c7d --- /dev/null +++ b/src/open_clip/eva_clip/model_configs/EVA01-CLIP-g-14-plus.json @@ -0,0 +1,24 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 40, + "width": 1408, + "head_width": 88, + "mlp_ratio": 4.3637, + "patch_size": 14, + "eva_model_name": "eva-clip-g-14-x", + "drop_path_rate": 0, + "xattn": true, + "fusedLN": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24, + "xattn": false, + "fusedLN": true + } +} \ No newline at end of file diff --git a/src/open_clip/eva_clip/model_configs/EVA01-CLIP-g-14.json b/src/open_clip/eva_clip/model_configs/EVA01-CLIP-g-14.json new file mode 100644 index 0000000000000000000000000000000000000000..5d338b4e6104241d1f0304ee82400035d5385332 --- /dev/null +++ b/src/open_clip/eva_clip/model_configs/EVA01-CLIP-g-14.json @@ -0,0 +1,24 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 40, + "width": 1408, + "head_width": 88, + "mlp_ratio": 4.3637, + "patch_size": 14, + "eva_model_name": "eva-clip-g-14-x", + "drop_path_rate": 0.4, + "xattn": true, + "fusedLN": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12, + "xattn": false, + "fusedLN": true + } +} \ No newline at end of file diff --git a/src/open_clip/eva_clip/model_configs/EVA02-CLIP-B-16.json b/src/open_clip/eva_clip/model_configs/EVA02-CLIP-B-16.json new file mode 100644 index 0000000000000000000000000000000000000000..e4a6e723f77033caa341ddf9b5be1787d64ad42c --- /dev/null +++ b/src/open_clip/eva_clip/model_configs/EVA02-CLIP-B-16.json @@ -0,0 +1,29 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "head_width": 64, + "patch_size": 16, + "mlp_ratio": 2.6667, + "eva_model_name": "eva-clip-b-16-X", + "drop_path_rate": 0.0, + "xattn": true, + "fusedLN": true, + "rope": true, + "pt_hw_seq_len": 16, + "intp_freq": true, + "naiveswiglu": true, + "subln": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12, + "xattn": true, + "fusedLN": true + } +} \ No newline at end of file diff --git a/src/open_clip/eva_clip/model_configs/EVA02-CLIP-L-14-336.json b/src/open_clip/eva_clip/model_configs/EVA02-CLIP-L-14-336.json new file mode 100644 index 0000000000000000000000000000000000000000..3e1d124e1118911c5ad7b1ce85df195aca363ac4 --- /dev/null +++ b/src/open_clip/eva_clip/model_configs/EVA02-CLIP-L-14-336.json @@ -0,0 +1,29 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 336, + "layers": 24, + "width": 1024, + "drop_path_rate": 0, + "head_width": 64, + "mlp_ratio": 2.6667, + "patch_size": 14, + "eva_model_name": "eva-clip-l-14-336", + "xattn": true, + "fusedLN": true, + "rope": true, + "pt_hw_seq_len": 16, + "intp_freq": true, + "naiveswiglu": true, + "subln": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12, + "xattn": false, + "fusedLN": true + } +} \ No newline at end of file diff --git a/src/open_clip/eva_clip/model_configs/EVA02-CLIP-L-14.json b/src/open_clip/eva_clip/model_configs/EVA02-CLIP-L-14.json new file mode 100644 index 0000000000000000000000000000000000000000..03b22ad3cfb92f9c843b9ec8d672e57e7a9ba4a2 --- /dev/null +++ b/src/open_clip/eva_clip/model_configs/EVA02-CLIP-L-14.json @@ -0,0 +1,29 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 224, + "layers": 24, + "width": 1024, + "drop_path_rate": 0, + "head_width": 64, + "mlp_ratio": 2.6667, + "patch_size": 14, + "eva_model_name": "eva-clip-l-14", + "xattn": true, + "fusedLN": true, + "rope": true, + "pt_hw_seq_len": 16, + "intp_freq": true, + "naiveswiglu": true, + "subln": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12, + "xattn": false, + "fusedLN": true + } +} \ No newline at end of file diff --git a/src/open_clip/eva_clip/model_configs/EVA02-CLIP-bigE-14-plus.json b/src/open_clip/eva_clip/model_configs/EVA02-CLIP-bigE-14-plus.json new file mode 100644 index 0000000000000000000000000000000000000000..aa04e2545ac1e015daae2c10133956ce969524f7 --- /dev/null +++ b/src/open_clip/eva_clip/model_configs/EVA02-CLIP-bigE-14-plus.json @@ -0,0 +1,25 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 64, + "width": 1792, + "head_width": 112, + "mlp_ratio": 8.571428571428571, + "patch_size": 14, + "eva_model_name": "eva-clip-4b-14-x", + "drop_path_rate": 0, + "xattn": true, + "postnorm": true, + "fusedLN": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1280, + "heads": 20, + "layers": 32, + "xattn": false, + "fusedLN": true + } +} diff --git a/src/open_clip/eva_clip/model_configs/EVA02-CLIP-bigE-14.json b/src/open_clip/eva_clip/model_configs/EVA02-CLIP-bigE-14.json new file mode 100644 index 0000000000000000000000000000000000000000..747ffccc8bd49dbb6701b58e15843b7fe3754e64 --- /dev/null +++ b/src/open_clip/eva_clip/model_configs/EVA02-CLIP-bigE-14.json @@ -0,0 +1,25 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 64, + "width": 1792, + "head_width": 112, + "mlp_ratio": 8.571428571428571, + "patch_size": 14, + "eva_model_name": "eva-clip-4b-14-x", + "drop_path_rate": 0, + "xattn": true, + "postnorm": true, + "fusedLN": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24, + "xattn": false, + "fusedLN": true + } +} \ No newline at end of file diff --git a/src/open_clip/eva_clip/modified_resnet.py b/src/open_clip/eva_clip/modified_resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..883f8ac5c9dddbede82031855044eb454cddbadb --- /dev/null +++ b/src/open_clip/eva_clip/modified_resnet.py @@ -0,0 +1,181 @@ +from collections import OrderedDict + +import torch +from torch import nn +from torch.nn import functional as F + +from open_clip.eva_clip.utils import freeze_batch_norm_2d + + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__(self, inplanes, planes, stride=1): + super().__init__() + + # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1 + self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False) + self.bn1 = nn.BatchNorm2d(planes) + self.act1 = nn.ReLU(inplace=True) + + self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(planes) + self.act2 = nn.ReLU(inplace=True) + + self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity() + + self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False) + self.bn3 = nn.BatchNorm2d(planes * self.expansion) + self.act3 = nn.ReLU(inplace=True) + + self.downsample = None + self.stride = stride + + if stride > 1 or inplanes != planes * Bottleneck.expansion: + # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1 + self.downsample = nn.Sequential(OrderedDict([ + ("-1", nn.AvgPool2d(stride)), + ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)), + ("1", nn.BatchNorm2d(planes * self.expansion)) + ])) + + def forward(self, x: torch.Tensor): + identity = x + + out = self.act1(self.bn1(self.conv1(x))) + out = self.act2(self.bn2(self.conv2(out))) + out = self.avgpool(out) + out = self.bn3(self.conv3(out)) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + out = self.act3(out) + return out + + +class AttentionPool2d(nn.Module): + def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None): + super().__init__() + self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5) + self.k_proj = nn.Linear(embed_dim, embed_dim) + self.q_proj = nn.Linear(embed_dim, embed_dim) + self.v_proj = nn.Linear(embed_dim, embed_dim) + self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim) + self.num_heads = num_heads + + def forward(self, x): + x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC + x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC + x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC + x, _ = F.multi_head_attention_forward( + query=x, key=x, value=x, + embed_dim_to_check=x.shape[-1], + num_heads=self.num_heads, + q_proj_weight=self.q_proj.weight, + k_proj_weight=self.k_proj.weight, + v_proj_weight=self.v_proj.weight, + in_proj_weight=None, + in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]), + bias_k=None, + bias_v=None, + add_zero_attn=False, + dropout_p=0., + out_proj_weight=self.c_proj.weight, + out_proj_bias=self.c_proj.bias, + use_separate_proj_weight=True, + training=self.training, + need_weights=False + ) + + return x[0] + + +class ModifiedResNet(nn.Module): + """ + A ResNet class that is similar to torchvision's but contains the following changes: + - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool. + - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1 + - The final pooling layer is a QKV attention instead of an average pool + """ + + def __init__(self, layers, output_dim, heads, image_size=224, width=64): + super().__init__() + self.output_dim = output_dim + self.image_size = image_size + + # the 3-layer stem + self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False) + self.bn1 = nn.BatchNorm2d(width // 2) + self.act1 = nn.ReLU(inplace=True) + self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(width // 2) + self.act2 = nn.ReLU(inplace=True) + self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False) + self.bn3 = nn.BatchNorm2d(width) + self.act3 = nn.ReLU(inplace=True) + self.avgpool = nn.AvgPool2d(2) + + # residual layers + self._inplanes = width # this is a *mutable* variable used during construction + self.layer1 = self._make_layer(width, layers[0]) + self.layer2 = self._make_layer(width * 2, layers[1], stride=2) + self.layer3 = self._make_layer(width * 4, layers[2], stride=2) + self.layer4 = self._make_layer(width * 8, layers[3], stride=2) + + embed_dim = width * 32 # the ResNet feature dimension + self.attnpool = AttentionPool2d(image_size // 32, embed_dim, heads, output_dim) + + self.init_parameters() + + def _make_layer(self, planes, blocks, stride=1): + layers = [Bottleneck(self._inplanes, planes, stride)] + + self._inplanes = planes * Bottleneck.expansion + for _ in range(1, blocks): + layers.append(Bottleneck(self._inplanes, planes)) + + return nn.Sequential(*layers) + + def init_parameters(self): + if self.attnpool is not None: + std = self.attnpool.c_proj.in_features ** -0.5 + nn.init.normal_(self.attnpool.q_proj.weight, std=std) + nn.init.normal_(self.attnpool.k_proj.weight, std=std) + nn.init.normal_(self.attnpool.v_proj.weight, std=std) + nn.init.normal_(self.attnpool.c_proj.weight, std=std) + + for resnet_block in [self.layer1, self.layer2, self.layer3, self.layer4]: + for name, param in resnet_block.named_parameters(): + if name.endswith("bn3.weight"): + nn.init.zeros_(param) + + def lock(self, unlocked_groups=0, freeze_bn_stats=False): + assert unlocked_groups == 0, 'partial locking not currently supported for this model' + for param in self.parameters(): + param.requires_grad = False + if freeze_bn_stats: + freeze_batch_norm_2d(self) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + # FIXME support for non-transformer + pass + + def stem(self, x): + x = self.act1(self.bn1(self.conv1(x))) + x = self.act2(self.bn2(self.conv2(x))) + x = self.act3(self.bn3(self.conv3(x))) + x = self.avgpool(x) + return x + + def forward(self, x): + x = self.stem(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + x = self.attnpool(x) + + return x diff --git a/src/open_clip/eva_clip/openai.py b/src/open_clip/eva_clip/openai.py new file mode 100644 index 0000000000000000000000000000000000000000..cc4e13e876d6a7a3463b457e62c517cb063b1356 --- /dev/null +++ b/src/open_clip/eva_clip/openai.py @@ -0,0 +1,144 @@ +""" OpenAI pretrained model functions + +Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. +""" + +import os +import warnings +from typing import List, Optional, Union + +import torch + +from .model import build_model_from_openai_state_dict, convert_weights_to_lp, get_cast_dtype +from .pretrained import get_pretrained_url, list_pretrained_models_by_tag, download_pretrained_from_url + +__all__ = ["list_openai_models", "load_openai_model"] + + +def list_openai_models() -> List[str]: + """Returns the names of available CLIP models""" + return list_pretrained_models_by_tag('openai') + + +def load_openai_model( + name: str, + precision: Optional[str] = None, + device: Optional[Union[str, torch.device]] = None, + jit: bool = True, + cache_dir: Optional[str] = None, +): + """Load a CLIP model + + Parameters + ---------- + name : str + A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict + precision: str + Model precision, if None defaults to 'fp32' if device == 'cpu' else 'fp16'. + device : Union[str, torch.device] + The device to put the loaded model + jit : bool + Whether to load the optimized JIT model (default) or more hackable non-JIT model. + cache_dir : Optional[str] + The directory to cache the downloaded model weights + + Returns + ------- + model : torch.nn.Module + The CLIP model + preprocess : Callable[[PIL.Image], torch.Tensor] + A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input + """ + if device is None: + device = "cuda" if torch.cuda.is_available() else "cpu" + if precision is None: + precision = 'fp32' if device == 'cpu' else 'fp16' + + if get_pretrained_url(name, 'openai'): + model_path = download_pretrained_from_url(get_pretrained_url(name, 'openai'), cache_dir=cache_dir) + elif os.path.isfile(name): + model_path = name + else: + raise RuntimeError(f"Model {name} not found; available models = {list_openai_models()}") + + try: + # loading JIT archive + model = torch.jit.load(model_path, map_location=device if jit else "cpu").eval() + state_dict = None + except RuntimeError: + # loading saved state dict + if jit: + warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead") + jit = False + state_dict = torch.load(model_path, map_location="cpu") + + if not jit: + # Build a non-jit model from the OpenAI jitted model state dict + cast_dtype = get_cast_dtype(precision) + try: + model = build_model_from_openai_state_dict(state_dict or model.state_dict(), cast_dtype=cast_dtype) + except KeyError: + sd = {k[7:]: v for k, v in state_dict["state_dict"].items()} + model = build_model_from_openai_state_dict(sd, cast_dtype=cast_dtype) + + # model from OpenAI state dict is in manually cast fp16 mode, must be converted for AMP/fp32/bf16 use + model = model.to(device) + if precision.startswith('amp') or precision == 'fp32': + model.float() + elif precision == 'bf16': + convert_weights_to_lp(model, dtype=torch.bfloat16) + + return model + + # patch the device names + device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[]) + device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1] + + def patch_device(module): + try: + graphs = [module.graph] if hasattr(module, "graph") else [] + except RuntimeError: + graphs = [] + + if hasattr(module, "forward1"): + graphs.append(module.forward1.graph) + + for graph in graphs: + for node in graph.findAllNodes("prim::Constant"): + if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"): + node.copyAttributes(device_node) + + model.apply(patch_device) + patch_device(model.encode_image) + patch_device(model.encode_text) + + # patch dtype to float32 (typically for CPU) + if precision == 'fp32': + float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[]) + float_input = list(float_holder.graph.findNode("aten::to").inputs())[1] + float_node = float_input.node() + + def patch_float(module): + try: + graphs = [module.graph] if hasattr(module, "graph") else [] + except RuntimeError: + graphs = [] + + if hasattr(module, "forward1"): + graphs.append(module.forward1.graph) + + for graph in graphs: + for node in graph.findAllNodes("aten::to"): + inputs = list(node.inputs()) + for i in [1, 2]: # dtype can be the second or third argument to aten::to() + if inputs[i].node()["value"] == 5: + inputs[i].node().copyAttributes(float_node) + + model.apply(patch_float) + patch_float(model.encode_image) + patch_float(model.encode_text) + model.float() + + # ensure image_size attr available at consistent location for both jit and non-jit + model.visual.image_size = model.input_resolution.item() + return model diff --git a/src/open_clip/eva_clip/pretrained.py b/src/open_clip/eva_clip/pretrained.py new file mode 100644 index 0000000000000000000000000000000000000000..a1e55dcf36a0e7dbd4c13b4ca2d7cb460e4c3547 --- /dev/null +++ b/src/open_clip/eva_clip/pretrained.py @@ -0,0 +1,332 @@ +import hashlib +import os +import urllib +import warnings +from functools import partial +from typing import Dict, Union + +from tqdm import tqdm + +try: + from huggingface_hub import hf_hub_download + _has_hf_hub = True +except ImportError: + hf_hub_download = None + _has_hf_hub = False + + +def _pcfg(url='', hf_hub='', filename='', mean=None, std=None): + return dict( + url=url, + hf_hub=hf_hub, + mean=mean, + std=std, + ) + +_VITB32 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e31-d867053b.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e32-46683a32.pt"), + laion2b_e16=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-laion2b_e16-af8dbd0c.pth"), + laion2b_s34b_b79k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-laion2B-s34B-b79K/') +) + +_VITB32_quickgelu = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e31-d867053b.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e32-46683a32.pt"), +) + +_VITB16 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16-laion400m_e31-00efa78f.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16-laion400m_e32-55e67d44.pt"), + laion2b_s34b_b88k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-laion2B-s34B-b88K/'), +) + +_EVAB16 = dict( + eva=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_B_psz14to16.pt'), + eva02=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_B_psz14to16.pt'), + eva_clip=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_CLIP_B_psz16_s8B.pt'), + eva02_clip=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_CLIP_B_psz16_s8B.pt'), +) + +_VITB16_PLUS_240 = dict( + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16_plus_240-laion400m_e31-8fb26589.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16_plus_240-laion400m_e32-699c4b84.pt"), +) + +_VITL14 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_l_14-laion400m_e31-69988bb6.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_l_14-laion400m_e32-3d133497.pt"), + laion2b_s32b_b82k=_pcfg( + hf_hub='laion/CLIP-ViT-L-14-laion2B-s32B-b82K/', + mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), +) + +_EVAL14 = dict( + eva=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_L_psz14.pt'), + eva02=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_L_psz14.pt'), + eva_clip=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_CLIP_L_psz14_s4B.pt'), + eva02_clip=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_CLIP_L_psz14_s4B.pt'), +) + +_VITL14_336 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt"), +) + +_EVAL14_336 = dict( + eva_clip=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14_s6B.pt'), + eva02_clip=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14_s6B.pt'), + eva_clip_224to336=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_CLIP_L_psz14_224to336.pt'), + eva02_clip_224to336=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_CLIP_L_psz14_224to336.pt'), +) + +_VITH14 = dict( + laion2b_s32b_b79k=_pcfg(hf_hub='laion/CLIP-ViT-H-14-laion2B-s32B-b79K/'), +) + +_VITg14 = dict( + laion2b_s12b_b42k=_pcfg(hf_hub='laion/CLIP-ViT-g-14-laion2B-s12B-b42K/'), + laion2b_s34b_b88k=_pcfg(hf_hub='laion/CLIP-ViT-g-14-laion2B-s34B-b88K/'), +) + +_EVAg14 = dict( + eva=_pcfg(hf_hub='QuanSun/EVA-CLIP/'), + eva01=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA01_g_psz14.pt'), + eva_clip=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA01_CLIP_g_14_psz14_s11B.pt'), + eva01_clip=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA01_CLIP_g_14_psz14_s11B.pt'), +) + +_EVAg14_PLUS = dict( + eva=_pcfg(hf_hub='QuanSun/EVA-CLIP/'), + eva01=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA01_g_psz14.pt'), + eva_clip=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA01_CLIP_g_14_plus_psz14_s11B.pt'), + eva01_clip=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA01_CLIP_g_14_plus_psz14_s11B.pt'), +) + +_VITbigG14 = dict( + laion2b_s39b_b160k=_pcfg(hf_hub='laion/CLIP-ViT-bigG-14-laion2B-39B-b160k/'), +) + +_EVAbigE14 = dict( + eva=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_E_psz14.pt'), + eva02=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_E_psz14.pt'), + eva_clip=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_s4B.pt'), + eva02_clip=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_s4B.pt'), +) + +_EVAbigE14_PLUS = dict( + eva=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_E_psz14.pt'), + eva02=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_E_psz14.pt'), + eva_clip=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt'), + eva02_clip=_pcfg(hf_hub='QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt'), +) + + +_PRETRAINED = { + # "ViT-B-32": _VITB32, + "OpenaiCLIP-B-32": _VITB32, + "OpenCLIP-B-32": _VITB32, + + # "ViT-B-32-quickgelu": _VITB32_quickgelu, + "OpenaiCLIP-B-32-quickgelu": _VITB32_quickgelu, + "OpenCLIP-B-32-quickgelu": _VITB32_quickgelu, + + # "ViT-B-16": _VITB16, + "OpenaiCLIP-B-16": _VITB16, + "OpenCLIP-B-16": _VITB16, + + "EVA02-B-16": _EVAB16, + "EVA02-CLIP-B-16": _EVAB16, + + # "ViT-B-16-plus-240": _VITB16_PLUS_240, + "OpenCLIP-B-16-plus-240": _VITB16_PLUS_240, + + # "ViT-L-14": _VITL14, + "OpenaiCLIP-L-14": _VITL14, + "OpenCLIP-L-14": _VITL14, + + "EVA02-L-14": _EVAL14, + "EVA02-CLIP-L-14": _EVAL14, + + # "ViT-L-14-336": _VITL14_336, + "OpenaiCLIP-L-14-336": _VITL14_336, + + "EVA02-CLIP-L-14-336": _EVAL14_336, + + # "ViT-H-14": _VITH14, + # "ViT-g-14": _VITg14, + "OpenCLIP-H-14": _VITH14, + "OpenCLIP-g-14": _VITg14, + + "EVA01-CLIP-g-14": _EVAg14, + "EVA01-CLIP-g-14-plus": _EVAg14_PLUS, + + # "ViT-bigG-14": _VITbigG14, + "OpenCLIP-bigG-14": _VITbigG14, + + "EVA02-CLIP-bigE-14": _EVAbigE14, + "EVA02-CLIP-bigE-14-plus": _EVAbigE14_PLUS, +} + + +def _clean_tag(tag: str): + # normalize pretrained tags + return tag.lower().replace('-', '_') + + +def list_pretrained(as_str: bool = False): + """ returns list of pretrained models + Returns a tuple (model_name, pretrain_tag) by default or 'name:tag' if as_str == True + """ + return [':'.join([k, t]) if as_str else (k, t) for k in _PRETRAINED.keys() for t in _PRETRAINED[k].keys()] + + +def list_pretrained_models_by_tag(tag: str): + """ return all models having the specified pretrain tag """ + models = [] + tag = _clean_tag(tag) + for k in _PRETRAINED.keys(): + if tag in _PRETRAINED[k]: + models.append(k) + return models + + +def list_pretrained_tags_by_model(model: str): + """ return all pretrain tags for the specified model architecture """ + tags = [] + if model in _PRETRAINED: + tags.extend(_PRETRAINED[model].keys()) + return tags + + +def is_pretrained_cfg(model: str, tag: str): + if model not in _PRETRAINED: + return False + return _clean_tag(tag) in _PRETRAINED[model] + + +def get_pretrained_cfg(model: str, tag: str): + if model not in _PRETRAINED: + return {} + model_pretrained = _PRETRAINED[model] + return model_pretrained.get(_clean_tag(tag), {}) + + +def get_pretrained_url(model: str, tag: str): + cfg = get_pretrained_cfg(model, _clean_tag(tag)) + return cfg.get('url', '') + + +def download_pretrained_from_url( + url: str, + cache_dir: Union[str, None] = None, +): + if not cache_dir: + cache_dir = os.path.expanduser("~/.cache/clip") + os.makedirs(cache_dir, exist_ok=True) + filename = os.path.basename(url) + + if 'openaipublic' in url: + expected_sha256 = url.split("/")[-2] + elif 'mlfoundations' in url: + expected_sha256 = os.path.splitext(filename)[0].split("-")[-1] + else: + expected_sha256 = '' + + download_target = os.path.join(cache_dir, filename) + + if os.path.exists(download_target) and not os.path.isfile(download_target): + raise RuntimeError(f"{download_target} exists and is not a regular file") + + if os.path.isfile(download_target): + if expected_sha256: + if hashlib.sha256(open(download_target, "rb").read()).hexdigest().startswith(expected_sha256): + return download_target + else: + warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file") + else: + return download_target + + with urllib.request.urlopen(url) as source, open(download_target, "wb") as output: + with tqdm(total=int(source.headers.get("Content-Length")), ncols=80, unit='iB', unit_scale=True) as loop: + while True: + buffer = source.read(8192) + if not buffer: + break + + output.write(buffer) + loop.update(len(buffer)) + + if expected_sha256 and not hashlib.sha256(open(download_target, "rb").read()).hexdigest().startswith(expected_sha256): + raise RuntimeError(f"Model has been downloaded but the SHA256 checksum does not not match") + + return download_target + + +def has_hf_hub(necessary=False): + if not _has_hf_hub and necessary: + # if no HF Hub module installed, and it is necessary to continue, raise error + raise RuntimeError( + 'Hugging Face hub model specified but package not installed. Run `pip install huggingface_hub`.') + return _has_hf_hub + + +def download_pretrained_from_hf( + model_id: str, + filename: str = 'open_clip_pytorch_model.bin', + revision=None, + cache_dir: Union[str, None] = None, +): + has_hf_hub(True) + cached_file = hf_hub_download(model_id, filename, revision=revision, cache_dir=cache_dir) + return cached_file + + +def download_pretrained( + cfg: Dict, + force_hf_hub: bool = False, + cache_dir: Union[str, None] = None, +): + target = '' + if not cfg: + return target + + download_url = cfg.get('url', '') + download_hf_hub = cfg.get('hf_hub', '') + if download_hf_hub and force_hf_hub: + # use HF hub even if url exists + download_url = '' + + if download_url: + target = download_pretrained_from_url(download_url, cache_dir=cache_dir) + elif download_hf_hub: + has_hf_hub(True) + # we assume the hf_hub entries in pretrained config combine model_id + filename in + # 'org/model_name/filename.pt' form. To specify just the model id w/o filename and + # use 'open_clip_pytorch_model.bin' default, there must be a trailing slash 'org/model_name/'. + model_id, filename = os.path.split(download_hf_hub) + if filename: + target = download_pretrained_from_hf(model_id, filename=filename, cache_dir=cache_dir) + else: + target = download_pretrained_from_hf(model_id, cache_dir=cache_dir) + + return target diff --git a/src/open_clip/eva_clip/rope.py b/src/open_clip/eva_clip/rope.py new file mode 100644 index 0000000000000000000000000000000000000000..3a0b2ea0319d48a82313ee50b7c3c3a9d4a3f7d3 --- /dev/null +++ b/src/open_clip/eva_clip/rope.py @@ -0,0 +1,215 @@ +from math import pi +import torch +from torch import nn +from einops import rearrange, repeat +import logging +import torch.nn.functional as F + + +def broadcat(tensors, dim = -1): + num_tensors = len(tensors) + shape_lens = set(list(map(lambda t: len(t.shape), tensors))) + assert len(shape_lens) == 1, 'tensors must all have the same number of dimensions' + shape_len = list(shape_lens)[0] + dim = (dim + shape_len) if dim < 0 else dim + dims = list(zip(*map(lambda t: list(t.shape), tensors))) + expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim] + assert all([*map(lambda t: len(set(t[1])) <= 2, expandable_dims)]), 'invalid dimensions for broadcastable concatentation' + max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims)) + expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims)) + expanded_dims.insert(dim, (dim, dims[dim])) + expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims))) + tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes))) + return torch.cat(tensors, dim = dim) + +def rotate_half(x): + x = rearrange(x, '... (d r) -> ... d r', r = 2) + x1, x2 = x.unbind(dim = -1) + x = torch.stack((-x2, x1), dim = -1) + return rearrange(x, '... d r -> ... (d r)') + + +class VisionRotaryEmbedding(nn.Module): + def __init__( + self, + dim, + pt_seq_len, + ft_seq_len=None, + custom_freqs = None, + freqs_for = 'lang', + theta = 10000, + max_freq = 10, + num_freqs = 1, + ): + super().__init__() + self.ft_seq_len = ft_seq_len + if custom_freqs: + freqs = custom_freqs + elif freqs_for == 'lang': + freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim)) + elif freqs_for == 'pixel': + freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi + elif freqs_for == 'constant': + freqs = torch.ones(num_freqs).float() + else: + raise ValueError(f'unknown modality {freqs_for}') + + if ft_seq_len is None: ft_seq_len = pt_seq_len + t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len + + freqs_h = torch.einsum('..., f -> ... f', t, freqs) + freqs_h = repeat(freqs_h, '... n -> ... (n r)', r = 2) + + freqs_w = torch.einsum('..., f -> ... f', t, freqs) + freqs_w = repeat(freqs_w, '... n -> ... (n r)', r = 2) + + freqs = broadcat((freqs_h[:, None, :], freqs_w[None, :, :]), dim = -1) + + self.register_buffer("freqs_cos", freqs.cos()) + self.register_buffer("freqs_sin", freqs.sin()) + + logging.info(f'Shape of rope freq: {self.freqs_cos.shape}') + + def interpolate_freq(self, t_len, freq): + if t_len == self.ft_seq_len ** 2: + return freq + tar_size = int(t_len ** 0.5) + freq = freq.view(1, self.ft_seq_len, self.ft_seq_len, freq.shape[-1]).permute(0, 3, 1, 2) + freq = F.interpolate(freq, (tar_size, tar_size), mode='bicubic', + align_corners=False).view(-1, t_len).T + + return freq + + def forward(self, t, start_index = 0): + rot_dim = self.freqs_cos.shape[-1] + end_index = start_index + rot_dim + assert rot_dim <= t.shape[-1], f'feature dimension {t.shape[-1]} is not of sufficient size to rotate in all the positions {rot_dim}' + t_left, t, t_right = t[..., :start_index], t[..., start_index:end_index], t[..., end_index:] + # t = (t * self.freqs_cos) + (rotate_half(t) * self.freqs_sin) + + t = (t * self.interpolate_freq(t.shape[2], self.freqs_cos)) \ + + (rotate_half(t) * self.interpolate_freq(t.shape[2], self.freqs_sin)) + + return torch.cat((t_left, t, t_right), dim = -1) + + +class VisionRotaryEmbeddingFast(nn.Module): + def __init__( + self, + dim, + pt_seq_len, + ft_seq_len=None, + custom_freqs = None, + freqs_for = 'lang', + theta = 10000, + max_freq = 10, + num_freqs = 1, + patch_dropout = 0. + ): + super().__init__() + + self.custom_freqs = custom_freqs + self.pt_seq_len = pt_seq_len + self.ft_seq_len = ft_seq_len + self.freqs_for = freqs_for + self.dim = dim + self.theta = theta + self.max_freq = max_freq + self.num_freqs = num_freqs + if custom_freqs: + freqs = custom_freqs + elif freqs_for == 'lang': + freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim)) + elif freqs_for == 'pixel': + freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi + elif freqs_for == 'constant': + freqs = torch.ones(num_freqs).float() + else: + raise ValueError(f'unknown modality {freqs_for}') + + if ft_seq_len is None: ft_seq_len = pt_seq_len + t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len + + freqs = torch.einsum('..., f -> ... f', t, freqs) + freqs = repeat(freqs, '... n -> ... (n r)', r = 2) + freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim = -1) + + freqs_cos = freqs.cos().view(-1, freqs.shape[-1]) + freqs_sin = freqs.sin().view(-1, freqs.shape[-1]) + + self.patch_dropout = patch_dropout + + self.register_buffer("freqs_cos", freqs_cos) + self.register_buffer("freqs_sin", freqs_sin) + + logging.info(f'Shape of rope freq: {self.freqs_cos.shape}') + self.register_buffer("flag", torch.tensor(0, dtype=torch.long), + persistent=False) + + def forward(self, t, patch_indices_keep=None): + if patch_indices_keep is not None: + batch = t.size()[0] + batch_indices = torch.arange(batch) + batch_indices = batch_indices[..., None] + + freqs_cos = repeat(self.freqs_cos, 'i j -> n i m j', n=t.shape[0], m=t.shape[1]) + freqs_sin = repeat(self.freqs_sin, 'i j -> n i m j', n=t.shape[0], m=t.shape[1]) + + freqs_cos = freqs_cos[batch_indices, patch_indices_keep] + freqs_cos = rearrange(freqs_cos, 'n i m j -> n m i j') + freqs_sin = freqs_sin[batch_indices, patch_indices_keep] + freqs_sin = rearrange(freqs_sin, 'n i m j -> n m i j') + + return t * freqs_cos + rotate_half(t) * freqs_sin + freqs_cos, freqs_sin = self.recalculate(t) + return t * freqs_cos + rotate_half(t) * freqs_sin + # return t * self.freqs_cos + rotate_half(t) * self.freqs_sin + # return t * self.interpolate_freq(t.shape[2], self.freqs_cos) \ + # + rotate_half(t) * self.interpolate_freq(t.shape[2], self.freqs_sin) + + def interpolate_freq(self, t_len, freq): + if t_len == self.ft_seq_len ** 2: + return freq + tar_size = int(t_len ** 0.5) + freq = freq.view(1, self.ft_seq_len, self.ft_seq_len, freq.shape[-1]).permute(0, 3, 1, 2) + freq = F.interpolate(freq, (tar_size, tar_size), mode='bicubic', + align_corners=False).view(-1, t_len).T + + return freq + + def recalculate(self, x): + # TODO: fix it, do not calculate it every time + x_len = x.shape[2] + if x_len == self.ft_seq_len ** 2: + return self.freqs_cos, self.freqs_sin + elif hasattr(self, f"freqs_cos_{x_len}"): + return getattr(self, f"freqs_cos_{x_len}"), getattr(self, f"freqs_sin_{x_len}") + assert self.flag <= 4 + ft_seq_len = int(x_len ** 0.5) + if self.custom_freqs: + freqs = self.custom_freqs + elif self.freqs_for == 'lang': + freqs = 1. / (self.theta ** (torch.arange(0, self.dim, 2)[:(self.dim // 2)].float() / self.dim)) + elif self.freqs_for == 'pixel': + freqs = torch.linspace(1., self.max_freq / 2, self.dim // 2) * pi + elif self.freqs_for == 'constant': + freqs = torch.ones(self.num_freqs).float() + else: + raise ValueError(f'unknown modality {self.freqs_for}') + + t = torch.arange(ft_seq_len) / ft_seq_len * self.pt_seq_len + + freqs = torch.einsum('..., f -> ... f', t, freqs) + freqs = repeat(freqs, '... n -> ... (n r)', r = 2) + freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim = -1) + + freqs_cos = freqs.cos().view(-1, freqs.shape[-1]).to(x) + freqs_sin = freqs.sin().view(-1, freqs.shape[-1]).to(x) + # TODO this is just a workaround + self.register_buffer(f"freqs_cos_{x_len}", freqs_cos, persistent=False) + self.register_buffer(f"freqs_sin_{x_len}", freqs_sin, persistent=False) + self.flag.data += 1 + logging.info(f'Add a new rope freq of shape: {freqs_cos.shape}') + print(f'Add a new rope freq of shape: {freqs_cos.shape}', flush=True) + + return freqs_cos, freqs_sin diff --git a/src/open_clip/eva_clip/timm_model.py b/src/open_clip/eva_clip/timm_model.py new file mode 100644 index 0000000000000000000000000000000000000000..b58122c0b84fbda9e51867342823222234e17505 --- /dev/null +++ b/src/open_clip/eva_clip/timm_model.py @@ -0,0 +1,122 @@ +""" timm model adapter + +Wraps timm (https://github.com/rwightman/pytorch-image-models) models for use as a vision tower in CLIP model. +""" +import logging +from collections import OrderedDict + +import torch +import torch.nn as nn + +try: + import timm + from timm.models.layers import Mlp, to_2tuple + try: + # old timm imports < 0.8.1 + from timm.models.layers.attention_pool2d import RotAttentionPool2d + from timm.models.layers.attention_pool2d import AttentionPool2d as AbsAttentionPool2d + except ImportError: + # new timm imports >= 0.8.1 + from timm.layers import RotAttentionPool2d + from timm.layers import AttentionPool2d as AbsAttentionPool2d +except ImportError: + timm = None + +from .utils import freeze_batch_norm_2d + + +class TimmModel(nn.Module): + """ timm model adapter + # FIXME this adapter is a work in progress, may change in ways that break weight compat + """ + + def __init__( + self, + model_name, + embed_dim, + image_size=224, + pool='avg', + proj='linear', + proj_bias=False, + drop=0., + pretrained=False): + super().__init__() + if timm is None: + raise RuntimeError("Please `pip install timm` to use timm models.") + + self.image_size = to_2tuple(image_size) + self.trunk = timm.create_model(model_name, pretrained=pretrained) + feat_size = self.trunk.default_cfg.get('pool_size', None) + feature_ndim = 1 if not feat_size else 2 + if pool in ('abs_attn', 'rot_attn'): + assert feature_ndim == 2 + # if attn pooling used, remove both classifier and default pool + self.trunk.reset_classifier(0, global_pool='') + else: + # reset global pool if pool config set, otherwise leave as network default + reset_kwargs = dict(global_pool=pool) if pool else {} + self.trunk.reset_classifier(0, **reset_kwargs) + prev_chs = self.trunk.num_features + + head_layers = OrderedDict() + if pool == 'abs_attn': + head_layers['pool'] = AbsAttentionPool2d(prev_chs, feat_size=feat_size, out_features=embed_dim) + prev_chs = embed_dim + elif pool == 'rot_attn': + head_layers['pool'] = RotAttentionPool2d(prev_chs, out_features=embed_dim) + prev_chs = embed_dim + else: + assert proj, 'projection layer needed if non-attention pooling is used.' + + # NOTE attention pool ends with a projection layer, so proj should usually be set to '' if such pooling is used + if proj == 'linear': + head_layers['drop'] = nn.Dropout(drop) + head_layers['proj'] = nn.Linear(prev_chs, embed_dim, bias=proj_bias) + elif proj == 'mlp': + head_layers['mlp'] = Mlp(prev_chs, 2 * embed_dim, embed_dim, drop=drop, bias=(True, proj_bias)) + + self.head = nn.Sequential(head_layers) + + def lock(self, unlocked_groups=0, freeze_bn_stats=False): + """ lock modules + Args: + unlocked_groups (int): leave last n layer groups unlocked (default: 0) + """ + if not unlocked_groups: + # lock full model + for param in self.trunk.parameters(): + param.requires_grad = False + if freeze_bn_stats: + freeze_batch_norm_2d(self.trunk) + else: + # NOTE: partial freeze requires latest timm (master) branch and is subject to change + try: + # FIXME import here until API stable and in an official release + from timm.models.helpers import group_parameters, group_modules + except ImportError: + raise RuntimeError( + 'Please install latest timm `pip install git+https://github.com/rwightman/pytorch-image-models`') + matcher = self.trunk.group_matcher() + gparams = group_parameters(self.trunk, matcher) + max_layer_id = max(gparams.keys()) + max_layer_id = max_layer_id - unlocked_groups + for group_idx in range(max_layer_id + 1): + group = gparams[group_idx] + for param in group: + self.trunk.get_parameter(param).requires_grad = False + if freeze_bn_stats: + gmodules = group_modules(self.trunk, matcher, reverse=True) + gmodules = {k for k, v in gmodules.items() if v <= max_layer_id} + freeze_batch_norm_2d(self.trunk, gmodules) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + try: + self.trunk.set_grad_checkpointing(enable) + except Exception as e: + logging.warning('grad checkpointing not supported for this timm image tower, continuing without...') + + def forward(self, x): + x = self.trunk(x) + x = self.head(x) + return x diff --git a/src/open_clip/eva_clip/tokenizer.py b/src/open_clip/eva_clip/tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..41482f82aebbf197f4ee4e6c07c845a0d69dd7d6 --- /dev/null +++ b/src/open_clip/eva_clip/tokenizer.py @@ -0,0 +1,201 @@ +""" CLIP tokenizer + +Copied from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. +""" +import gzip +import html +import os +from functools import lru_cache +from typing import Union, List + +import ftfy +import regex as re +import torch + +# https://stackoverflow.com/q/62691279 +import os +os.environ["TOKENIZERS_PARALLELISM"] = "false" + + +@lru_cache() +def default_bpe(): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz") + + +@lru_cache() +def bytes_to_unicode(): + """ + Returns list of utf-8 byte and a corresponding list of unicode strings. + The reversible bpe codes work on unicode strings. + This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. + When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. + This is a signficant percentage of your normal, say, 32K bpe vocab. + To avoid that, we want lookup tables between utf-8 bytes and unicode strings. + And avoids mapping to whitespace/control characters the bpe code barfs on. + """ + bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1)) + cs = bs[:] + n = 0 + for b in range(2**8): + if b not in bs: + bs.append(b) + cs.append(2**8+n) + n += 1 + cs = [chr(n) for n in cs] + return dict(zip(bs, cs)) + + +def get_pairs(word): + """Return set of symbol pairs in a word. + Word is represented as tuple of symbols (symbols being variable-length strings). + """ + pairs = set() + prev_char = word[0] + for char in word[1:]: + pairs.add((prev_char, char)) + prev_char = char + return pairs + + +def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + +def whitespace_clean(text): + text = re.sub(r'\s+', ' ', text) + text = text.strip() + return text + + +class SimpleTokenizer(object): + def __init__(self, bpe_path: str = default_bpe(), special_tokens=None): + self.byte_encoder = bytes_to_unicode() + self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} + merges = gzip.open(bpe_path).read().decode("utf-8").split('\n') + merges = merges[1:49152-256-2+1] + merges = [tuple(merge.split()) for merge in merges] + vocab = list(bytes_to_unicode().values()) + vocab = vocab + [v+'' for v in vocab] + for merge in merges: + vocab.append(''.join(merge)) + if not special_tokens: + special_tokens = ['', ''] + else: + special_tokens = ['', ''] + special_tokens + vocab.extend(special_tokens) + self.encoder = dict(zip(vocab, range(len(vocab)))) + self.decoder = {v: k for k, v in self.encoder.items()} + self.bpe_ranks = dict(zip(merges, range(len(merges)))) + self.cache = {t:t for t in special_tokens} + special = "|".join(special_tokens) + self.pat = re.compile(special + r"""|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE) + + self.vocab_size = len(self.encoder) + self.all_special_ids = [self.encoder[t] for t in special_tokens] + + def bpe(self, token): + if token in self.cache: + return self.cache[token] + word = tuple(token[:-1]) + ( token[-1] + '',) + pairs = get_pairs(word) + + if not pairs: + return token+'' + + while True: + bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf'))) + if bigram not in self.bpe_ranks: + break + first, second = bigram + new_word = [] + i = 0 + while i < len(word): + try: + j = word.index(first, i) + new_word.extend(word[i:j]) + i = j + except: + new_word.extend(word[i:]) + break + + if word[i] == first and i < len(word)-1 and word[i+1] == second: + new_word.append(first+second) + i += 2 + else: + new_word.append(word[i]) + i += 1 + new_word = tuple(new_word) + word = new_word + if len(word) == 1: + break + else: + pairs = get_pairs(word) + word = ' '.join(word) + self.cache[token] = word + return word + + def encode(self, text): + bpe_tokens = [] + text = whitespace_clean(basic_clean(text)).lower() + for token in re.findall(self.pat, text): + token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8')) + bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' ')) + return bpe_tokens + + def decode(self, tokens): + text = ''.join([self.decoder[token] for token in tokens]) + text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('', ' ') + return text + + +_tokenizer = SimpleTokenizer() + + +def tokenize(texts: Union[str, List[str]], context_length: int = 77) -> torch.LongTensor: + """ + Returns the tokenized representation of given input string(s) + + Parameters + ---------- + texts : Union[str, List[str]] + An input string or a list of input strings to tokenize + context_length : int + The context length to use; all CLIP models use 77 as the context length + + Returns + ------- + A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length] + """ + if isinstance(texts, str): + texts = [texts] + + sot_token = _tokenizer.encoder[""] + eot_token = _tokenizer.encoder[""] + all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts] + result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) + + for i, tokens in enumerate(all_tokens): + if len(tokens) > context_length: + tokens = tokens[:context_length] # Truncate + tokens[-1] = eot_token + result[i, :len(tokens)] = torch.tensor(tokens) + + return result + + +class HFTokenizer: + "HuggingFace tokenizer wrapper" + def __init__(self, tokenizer_name:str): + from transformers import AutoTokenizer + self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name) + + def __call__(self, texts:Union[str, List[str]], context_length:int=77) -> torch.Tensor: + # same cleaning as for default tokenizer, except lowercasing + # adding lower (for case-sensitive tokenizers) will make it more robust but less sensitive to nuance + if isinstance(texts, str): + texts = [texts] + texts = [whitespace_clean(basic_clean(text)) for text in texts] + input_ids = self.tokenizer(texts, return_tensors='pt', max_length=context_length, padding='max_length', truncation=True).input_ids + return input_ids diff --git a/src/open_clip/eva_clip/transform.py b/src/open_clip/eva_clip/transform.py new file mode 100644 index 0000000000000000000000000000000000000000..39f3e4cf6cf9985131ae2ef254b59540904b02e7 --- /dev/null +++ b/src/open_clip/eva_clip/transform.py @@ -0,0 +1,103 @@ +from typing import Optional, Sequence, Tuple + +import torch +import torch.nn as nn +import torchvision.transforms.functional as F + +from torchvision.transforms import Normalize, Compose, RandomResizedCrop, InterpolationMode, ToTensor, Resize, \ + CenterCrop + +from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD + + +class ResizeMaxSize(nn.Module): + + def __init__(self, max_size, interpolation=InterpolationMode.BICUBIC, fn='max', fill=0): + super().__init__() + if not isinstance(max_size, int): + raise TypeError(f"Size should be int. Got {type(max_size)}") + self.max_size = max_size + self.interpolation = interpolation + self.fn = min if fn == 'min' else min + self.fill = fill + + def forward(self, img): + if isinstance(img, torch.Tensor): + height, width = img.shape[:2] + else: + width, height = img.size + scale = self.max_size / float(max(height, width)) + if scale != 1.0: + new_size = tuple(round(dim * scale) for dim in (height, width)) + img = F.resize(img, new_size, self.interpolation) + pad_h = self.max_size - new_size[0] + pad_w = self.max_size - new_size[1] + img = F.pad(img, padding=[pad_w//2, pad_h//2, pad_w - pad_w//2, pad_h - pad_h//2], fill=self.fill) + return img + + +def _convert_to_rgb(image): + return image.convert('RGB') + + +# class CatGen(nn.Module): +# def __init__(self, num=4): +# self.num = num +# def mixgen_batch(image, text): +# batch_size = image.shape[0] +# index = np.random.permutation(batch_size) + +# cat_images = [] +# for i in range(batch_size): +# # image mixup +# image[i,:] = lam * image[i,:] + (1 - lam) * image[index[i],:] +# # text concat +# text[i] = tokenizer((str(text[i]) + " " + str(text[index[i]])))[0] +# text = torch.stack(text) +# return image, text + + +def image_transform( + image_size: int, + is_train: bool, + mean: Optional[Tuple[float, ...]] = None, + std: Optional[Tuple[float, ...]] = None, + resize_longest_max: bool = False, + fill_color: int = 0, +): + mean = mean or OPENAI_DATASET_MEAN + if not isinstance(mean, (list, tuple)): + mean = (mean,) * 3 + + std = std or OPENAI_DATASET_STD + if not isinstance(std, (list, tuple)): + std = (std,) * 3 + + if isinstance(image_size, (list, tuple)) and image_size[0] == image_size[1]: + # for square size, pass size as int so that Resize() uses aspect preserving shortest edge + image_size = image_size[0] + + normalize = Normalize(mean=mean, std=std) + if is_train: + return Compose([ + RandomResizedCrop(image_size, scale=(0.9, 1.0), interpolation=InterpolationMode.BICUBIC), + _convert_to_rgb, + ToTensor(), + normalize, + ]) + else: + if resize_longest_max: + transforms = [ + ResizeMaxSize(image_size, fill=fill_color) + ] + else: + transforms = [ + Resize(image_size, interpolation=InterpolationMode.BICUBIC), + CenterCrop(image_size), + ] + transforms.extend([ + _convert_to_rgb, + ToTensor(), + normalize, + ]) + return Compose(transforms) diff --git a/src/open_clip/eva_clip/transformer.py b/src/open_clip/eva_clip/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..ecd64d95c3174130dc70fef7f48adca8af8becb7 --- /dev/null +++ b/src/open_clip/eva_clip/transformer.py @@ -0,0 +1,742 @@ +import os +import logging +from collections import OrderedDict +import math +from typing import Callable, Optional, Sequence +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F + +try: + from timm.models.layers import trunc_normal_ +except: + from timm.layers import trunc_normal_ + +from .rope import VisionRotaryEmbedding, VisionRotaryEmbeddingFast +from .utils import to_2tuple + +if os.getenv('ENV_TYPE') == 'deepspeed': + try: + import deepspeed + from deepspeed.runtime.activation_checkpointing.checkpointing import checkpoint + except: + print("Please 'pip install deepspeed'") + deepspeed = None + from torch.utils.checkpoint import checkpoint +else: + from torch.utils.checkpoint import checkpoint + +try: + import xformers.ops as xops +except ImportError: + xops = None + print("Please 'pip install xformers'") + +class LayerNormFp32(nn.LayerNorm): + """Subclass torch's LayerNorm to handle fp16 (by casting to float32 and back).""" + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def forward(self, x: torch.Tensor): + output = F.layer_norm( + x.float(), + self.normalized_shape, + self.weight.float() if self.weight is not None else None, + self.bias.float() if self.bias is not None else None, + self.eps, + ) + return output.type_as(x) + + +class LayerNorm(nn.LayerNorm): + """Subclass torch's LayerNorm (with cast back to input dtype).""" + + def forward(self, x: torch.Tensor): + orig_type = x.dtype + x = F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps) + return x.to(orig_type) + +class QuickGELU(nn.Module): + # NOTE This is slower than nn.GELU or nn.SiLU and uses more GPU memory + def forward(self, x: torch.Tensor): + return x * torch.sigmoid(1.702 * x) + + +class LayerScale(nn.Module): + def __init__(self, dim, init_values=1e-5, inplace=False): + super().__init__() + self.inplace = inplace + self.gamma = nn.Parameter(init_values * torch.ones(dim)) + + def forward(self, x): + return x.mul_(self.gamma) if self.inplace else x * self.gamma + +class PatchDropout(nn.Module): + """ + https://arxiv.org/abs/2212.00794 + """ + + def __init__(self, prob, exclude_first_token=True): + super().__init__() + assert 0 <= prob < 1. + self.prob = prob + self.exclude_first_token = exclude_first_token # exclude CLS token + logging.info(f"os.getenv('RoPE')={os.getenv('RoPE')}") + + def forward(self, x): + if not self.training or self.prob == 0.: + return x + + if self.exclude_first_token: + cls_tokens, x = x[:, :1], x[:, 1:] + else: + cls_tokens = torch.jit.annotate(torch.Tensor, x[:, :1]) + + batch = x.size()[0] + num_tokens = x.size()[1] + + batch_indices = torch.arange(batch) + batch_indices = batch_indices[..., None] + + keep_prob = 1 - self.prob + num_patches_keep = max(1, int(num_tokens * keep_prob)) + + rand = torch.randn(batch, num_tokens) + patch_indices_keep = rand.topk(num_patches_keep, dim=-1).indices + + x = x[batch_indices, patch_indices_keep] + + if self.exclude_first_token: + x = torch.cat((cls_tokens, x), dim=1) + + if self.training and os.getenv('RoPE') == '1': + return x, patch_indices_keep + + return x + + +def _in_projection_packed( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + w: torch.Tensor, + b: Optional[torch.Tensor] = None, + ): + """ + https://github.com/pytorch/pytorch/blob/db2a237763eb8693a20788be94f8c192e762baa8/torch/nn/functional.py#L4726 + """ + E = q.size(-1) + if k is v: + if q is k: + # self-attention + return F.linear(q, w, b).chunk(3, dim=-1) + else: + # encoder-decoder attention + w_q, w_kv = w.split([E, E * 2]) + if b is None: + b_q = b_kv = None + else: + b_q, b_kv = b.split([E, E * 2]) + return (F.linear(q, w_q, b_q),) + F.linear(k, w_kv, b_kv).chunk(2, dim=-1) + else: + w_q, w_k, w_v = w.chunk(3) + if b is None: + b_q = b_k = b_v = None + else: + b_q, b_k, b_v = b.chunk(3) + return F.linear(q, w_q, b_q), F.linear(k, w_k, b_k), F.linear(v, w_v, b_v) + +class Attention(nn.Module): + def __init__( + self, + dim, + num_heads=8, + qkv_bias=True, + scaled_cosine=False, + scale_heads=False, + logit_scale_max=math.log(1. / 0.01), + attn_drop=0., + proj_drop=0., + xattn=False, + rope=False + ): + super().__init__() + self.scaled_cosine = scaled_cosine + self.scale_heads = scale_heads + assert dim % num_heads == 0, 'dim should be divisible by num_heads' + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.scale = self.head_dim ** -0.5 + self.logit_scale_max = logit_scale_max + + # keeping in_proj in this form (instead of nn.Linear) to match weight scheme of original + self.in_proj_weight = nn.Parameter(torch.randn((dim * 3, dim)) * self.scale) + if qkv_bias: + self.in_proj_bias = nn.Parameter(torch.zeros(dim * 3)) + else: + self.in_proj_bias = None + + if self.scaled_cosine: + self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1)))) + else: + self.logit_scale = None + self.attn_drop = nn.Dropout(attn_drop) + if self.scale_heads: + self.head_scale = nn.Parameter(torch.ones((num_heads, 1, 1))) + else: + self.head_scale = None + self.out_proj = nn.Linear(dim, dim) + self.out_drop = nn.Dropout(proj_drop) + self.xattn = xattn + self.xattn_drop = attn_drop + self.rope = rope + + def forward(self, x, attn_mask: Optional[torch.Tensor] = None): + L, N, C = x.shape + q, k, v = F.linear(x, self.in_proj_weight, self.in_proj_bias).chunk(3, dim=-1) + if self.xattn: + q = q.contiguous().view(L, N, self.num_heads, -1).transpose(0, 1) + k = k.contiguous().view(L, N, self.num_heads, -1).transpose(0, 1) + v = v.contiguous().view(L, N, self.num_heads, -1).transpose(0, 1) + + x = xops.memory_efficient_attention( + q, k, v, + p=self.xattn_drop, + scale=self.scale if self.logit_scale is None else None, + attn_bias=xops.LowerTriangularMask() if attn_mask is not None else None, + ) + else: + q = q.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1) + k = k.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1) + v = v.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1) + + if self.logit_scale is not None: + attn = torch.bmm(F.normalize(q, dim=-1), F.normalize(k, dim=-1).transpose(-1, -2)) + logit_scale = torch.clamp(self.logit_scale, max=self.logit_scale_max).exp() + attn = attn.view(N, self.num_heads, L, L) * logit_scale + attn = attn.view(-1, L, L) + else: + q = q * self.scale + attn = torch.bmm(q, k.transpose(-1, -2)) + + if attn_mask is not None: + if attn_mask.dtype == torch.bool: + new_attn_mask = torch.zeros_like(attn_mask, dtype=q.dtype) + new_attn_mask.masked_fill_(attn_mask, float("-inf")) + attn_mask = new_attn_mask + attn += attn_mask + + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + + x = torch.bmm(attn, v) + + if self.head_scale is not None: + x = x.view(N, self.num_heads, L, C) * self.head_scale + x = x.view(-1, L, C) + x = x.transpose(0, 1).reshape(L, N, C) + x = self.out_proj(x) + x = self.out_drop(x) + return x + +class CustomAttention(nn.Module): + def __init__( + self, + dim, + num_heads=8, + qkv_bias=True, + scaled_cosine=True, + scale_heads=False, + logit_scale_max=math.log(1. / 0.01), + attn_drop=0., + proj_drop=0., + xattn=False + ): + super().__init__() + self.scaled_cosine = scaled_cosine + self.scale_heads = scale_heads + assert dim % num_heads == 0, 'dim should be divisible by num_heads' + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.scale = self.head_dim ** -0.5 + self.logit_scale_max = logit_scale_max + + # keeping in_proj in this form (instead of nn.Linear) to match weight scheme of original + self.in_proj_weight = nn.Parameter(torch.randn((dim * 3, dim)) * self.scale) + if qkv_bias: + self.in_proj_bias = nn.Parameter(torch.zeros(dim * 3)) + else: + self.in_proj_bias = None + + if self.scaled_cosine: + self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1)))) + else: + self.logit_scale = None + self.attn_drop = nn.Dropout(attn_drop) + if self.scale_heads: + self.head_scale = nn.Parameter(torch.ones((num_heads, 1, 1))) + else: + self.head_scale = None + self.out_proj = nn.Linear(dim, dim) + self.out_drop = nn.Dropout(proj_drop) + self.xattn = xattn + self.xattn_drop = attn_drop + + def forward(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attn_mask: Optional[torch.Tensor] = None): + q, k, v = _in_projection_packed(query, key, value, self.in_proj_weight, self.in_proj_bias) + N_q, B_q, C_q = q.shape + N_k, B_k, C_k = k.shape + N_v, B_v, C_v = v.shape + if self.xattn: + # B, N, C -> B, N, num_heads, C + q = q.permute(1, 0, 2).reshape(B_q, N_q, self.num_heads, -1) + k = k.permute(1, 0, 2).reshape(B_k, N_k, self.num_heads, -1) + v = v.permute(1, 0, 2).reshape(B_v, N_v, self.num_heads, -1) + + x = xops.memory_efficient_attention( + q, k, v, + p=self.xattn_drop, + scale=self.scale if self.logit_scale is None else None, + attn_bias=xops.LowerTriangularMask() if attn_mask is not None else None + ) + else: + # B*H, L, C + q = q.contiguous().view(N_q, B_q * self.num_heads, -1).transpose(0, 1) + k = k.contiguous().view(N_k, B_k * self.num_heads, -1).transpose(0, 1) + v = v.contiguous().view(N_v, B_v * self.num_heads, -1).transpose(0, 1) + + if self.logit_scale is not None: + # B*H, N_q, N_k + attn = torch.bmm(F.normalize(q, dim=-1), F.normalize(k, dim=-1).transpose(-1, -2)) + logit_scale = torch.clamp(self.logit_scale, max=self.logit_scale_max).exp() + attn = attn.view(B_q, self.num_heads, N_q, N_k) * logit_scale + attn = attn.view(-1, N_q, N_k) + else: + q = q * self.scale + attn = torch.bmm(q, k.transpose(-1, -2)) + + if attn_mask is not None: + if attn_mask.dtype == torch.bool: + new_attn_mask = torch.zeros_like(attn_mask, dtype=q.dtype) + new_attn_mask.masked_fill_(attn_mask, float("-inf")) + attn_mask = new_attn_mask + attn += attn_mask + + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + + x = torch.bmm(attn, v) + + if self.head_scale is not None: + x = x.view(B_q, self.num_heads, N_q, C_q) * self.head_scale + x = x.view(-1, N_q, C_q) + x = x.transpose(0, 1).reshape(N_q, B_q, C_q) + x = self.out_proj(x) + x = self.out_drop(x) + return x + +class CustomResidualAttentionBlock(nn.Module): + def __init__( + self, + d_model: int, + n_head: int, + mlp_ratio: float = 4.0, + ls_init_value: float = None, + act_layer: Callable = nn.GELU, + norm_layer: Callable = LayerNorm, + scale_cosine_attn: bool = False, + scale_heads: bool = False, + scale_attn: bool = False, + scale_fc: bool = False, + cross_attn: bool = False, + xattn: bool = False, + ): + super().__init__() + + self.ln_1 = norm_layer(d_model) + self.ln_1_k = norm_layer(d_model) if cross_attn else self.ln_1 + self.ln_1_v = norm_layer(d_model) if cross_attn else self.ln_1 + self.attn = CustomAttention( + d_model, n_head, + qkv_bias=True, + attn_drop=0., + proj_drop=0., + scaled_cosine=scale_cosine_attn, + scale_heads=scale_heads, + xattn=xattn + ) + + self.ln_attn = norm_layer(d_model) if scale_attn else nn.Identity() + self.ls_1 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity() + + self.ln_2 = norm_layer(d_model) + mlp_width = int(d_model * mlp_ratio) + self.mlp = nn.Sequential(OrderedDict([ + ("c_fc", nn.Linear(d_model, mlp_width)), + ('ln', norm_layer(mlp_width) if scale_fc else nn.Identity()), + ("gelu", act_layer()), + ("c_proj", nn.Linear(mlp_width, d_model)) + ])) + + self.ls_2 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity() + + def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, attn_mask: Optional[torch.Tensor] = None): + q = q + self.ls_1(self.ln_attn(self.attn(self.ln_1(q), self.ln_1_k(k), self.ln_1_v(v), attn_mask=attn_mask))) + q = q + self.ls_2(self.mlp(self.ln_2(q))) + return q + +class CustomTransformer(nn.Module): + def __init__( + self, + width: int, + layers: int, + heads: int, + mlp_ratio: float = 4.0, + ls_init_value: float = None, + act_layer: Callable = nn.GELU, + norm_layer: Callable = LayerNorm, + scale_cosine_attn: bool = True, + scale_heads: bool = False, + scale_attn: bool = False, + scale_fc: bool = False, + cross_attn: bool = False, + xattn: bool = False, + ): + super().__init__() + self.width = width + self.layers = layers + self.grad_checkpointing = False + self.xattn = xattn + + self.resblocks = nn.ModuleList([ + CustomResidualAttentionBlock( + width, + heads, + mlp_ratio, + ls_init_value=ls_init_value, + act_layer=act_layer, + norm_layer=norm_layer, + scale_cosine_attn=scale_cosine_attn, + scale_heads=scale_heads, + scale_attn=scale_attn, + scale_fc=scale_fc, + cross_attn=cross_attn, + xattn=xattn) + for _ in range(layers) + ]) + + def get_cast_dtype(self) -> torch.dtype: + return self.resblocks[0].mlp.c_fc.weight.dtype + + def forward(self, q: torch.Tensor, k: torch.Tensor = None, v: torch.Tensor = None, attn_mask: Optional[torch.Tensor] = None): + if k is None and v is None: + k = v = q + for r in self.resblocks: + if self.grad_checkpointing and not torch.jit.is_scripting(): + q = checkpoint(r, q, k, v, attn_mask) + else: + q = r(q, k, v, attn_mask=attn_mask) + return q + + +class ResidualAttentionBlock(nn.Module): + def __init__( + self, + d_model: int, + n_head: int, + mlp_ratio: float = 4.0, + ls_init_value: float = None, + act_layer: Callable = nn.GELU, + norm_layer: Callable = LayerNorm, + xattn: bool = False, + ): + super().__init__() + + self.ln_1 = norm_layer(d_model) + if xattn: + self.attn = Attention(d_model, n_head, xattn=True) + else: + self.attn = nn.MultiheadAttention(d_model, n_head) + self.ls_1 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity() + + self.ln_2 = norm_layer(d_model) + mlp_width = int(d_model * mlp_ratio) + self.mlp = nn.Sequential(OrderedDict([ + ("c_fc", nn.Linear(d_model, mlp_width)), + ("gelu", act_layer()), + ("c_proj", nn.Linear(mlp_width, d_model)) + ])) + + self.ls_2 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity() + self.xattn = xattn + + def attention(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None): + attn_mask = attn_mask.to(x.dtype) if attn_mask is not None else None + if self.xattn: + return self.attn(x, attn_mask=attn_mask) + return self.attn(x, x, x, need_weights=False, attn_mask=attn_mask)[0] + + def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None): + x = x + self.ls_1(self.attention(self.ln_1(x), attn_mask=attn_mask)) + x = x + self.ls_2(self.mlp(self.ln_2(x))) + return x + +class Transformer(nn.Module): + def __init__( + self, + width: int, + layers: int, + heads: int, + mlp_ratio: float = 4.0, + ls_init_value: float = None, + act_layer: Callable = nn.GELU, + norm_layer: Callable = LayerNorm, + xattn: bool = False, + ): + super().__init__() + self.width = width + self.layers = layers + self.grad_checkpointing = False + + self.resblocks = nn.ModuleList([ + ResidualAttentionBlock( + width, heads, mlp_ratio, ls_init_value=ls_init_value, act_layer=act_layer, norm_layer=norm_layer, xattn=xattn) + for _ in range(layers) + ]) + + def get_cast_dtype(self) -> torch.dtype: + return self.resblocks[0].mlp.c_fc.weight.dtype + + def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None): + for r in self.resblocks: + if self.grad_checkpointing and not torch.jit.is_scripting(): + x = checkpoint(r, x, attn_mask) + else: + x = r(x, attn_mask=attn_mask) + return x + + +class VisionTransformer(nn.Module): + def __init__( + self, + image_size: int, + patch_size: int, + width: int, + layers: int, + heads: int, + mlp_ratio: float, + ls_init_value: float = None, + patch_dropout: float = 0., + global_average_pool: bool = False, + output_dim: int = 512, + act_layer: Callable = nn.GELU, + norm_layer: Callable = LayerNorm, + xattn: bool = False, + ): + super().__init__() + self.image_size = to_2tuple(image_size) + self.patch_size = to_2tuple(patch_size) + self.grid_size = (self.image_size[0] // self.patch_size[0], self.image_size[1] // self.patch_size[1]) + self.output_dim = output_dim + self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False) + + scale = width ** -0.5 + self.class_embedding = nn.Parameter(scale * torch.randn(width)) + self.positional_embedding = nn.Parameter(scale * torch.randn(self.grid_size[0] * self.grid_size[1] + 1, width)) + + # setting a patch_dropout of 0. would mean it is disabled and this function would be the identity fn + self.patch_dropout = PatchDropout(patch_dropout) if patch_dropout > 0. else nn.Identity() + self.ln_pre = norm_layer(width) + + self.transformer = Transformer( + width, + layers, + heads, + mlp_ratio, + ls_init_value=ls_init_value, + act_layer=act_layer, + norm_layer=norm_layer, + xattn=xattn + ) + + self.global_average_pool = global_average_pool + self.ln_post = norm_layer(width) + self.proj = nn.Parameter(scale * torch.randn(width, output_dim)) + + def lock(self, unlocked_groups=0, freeze_bn_stats=False): + for param in self.parameters(): + param.requires_grad = False + + if unlocked_groups != 0: + groups = [ + [ + self.conv1, + self.class_embedding, + self.positional_embedding, + self.ln_pre, + ], + *self.transformer.resblocks[:-1], + [ + self.transformer.resblocks[-1], + self.ln_post, + ], + self.proj, + ] + + def _unlock(x): + if isinstance(x, Sequence): + for g in x: + _unlock(g) + else: + if isinstance(x, torch.nn.Parameter): + x.requires_grad = True + else: + for p in x.parameters(): + p.requires_grad = True + + _unlock(groups[-unlocked_groups:]) + + def get_num_layers(self): + return self.transformer.layers + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.transformer.grad_checkpointing = enable + + @torch.jit.ignore + def no_weight_decay(self): + return {'positional_embedding', 'class_embedding'} + + def forward(self, x: torch.Tensor, return_all_features: bool=False): + x = self.conv1(x) # shape = [*, width, grid, grid] + x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2] + x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] + x = torch.cat( + [self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), + x], dim=1) # shape = [*, grid ** 2 + 1, width] + x = x + self.positional_embedding.to(x.dtype) + + # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in + x = self.patch_dropout(x) + x = self.ln_pre(x) + + x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer(x) + x = x.permute(1, 0, 2) # LND -> NLD + + if not return_all_features: + if self.global_average_pool: + x = x.mean(dim=1) #x = x[:,1:,:].mean(dim=1) + else: + x = x[:, 0] + + x = self.ln_post(x) + + if self.proj is not None: + x = x @ self.proj + + return x + + +class TextTransformer(nn.Module): + def __init__( + self, + context_length: int = 77, + vocab_size: int = 49408, + width: int = 512, + heads: int = 8, + layers: int = 12, + ls_init_value: float = None, + output_dim: int = 512, + act_layer: Callable = nn.GELU, + norm_layer: Callable = LayerNorm, + xattn: bool= False, + attn_mask: bool = True + ): + super().__init__() + self.context_length = context_length + self.vocab_size = vocab_size + self.width = width + self.output_dim = output_dim + + self.token_embedding = nn.Embedding(vocab_size, width) + self.positional_embedding = nn.Parameter(torch.empty(self.context_length, width)) + self.transformer = Transformer( + width=width, + layers=layers, + heads=heads, + ls_init_value=ls_init_value, + act_layer=act_layer, + norm_layer=norm_layer, + xattn=xattn + ) + + self.xattn = xattn + self.ln_final = norm_layer(width) + self.text_projection = nn.Parameter(torch.empty(width, output_dim)) + + if attn_mask: + self.register_buffer('attn_mask', self.build_attention_mask(), persistent=False) + else: + self.attn_mask = None + + self.init_parameters() + + def init_parameters(self): + nn.init.normal_(self.token_embedding.weight, std=0.02) + nn.init.normal_(self.positional_embedding, std=0.01) + + proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5) + attn_std = self.transformer.width ** -0.5 + fc_std = (2 * self.transformer.width) ** -0.5 + for block in self.transformer.resblocks: + nn.init.normal_(block.attn.in_proj_weight, std=attn_std) + nn.init.normal_(block.attn.out_proj.weight, std=proj_std) + nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) + nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) + + if self.text_projection is not None: + nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.transformer.grad_checkpointing = enable + + @torch.jit.ignore + def no_weight_decay(self): + # return {'positional_embedding', 'token_embedding'} + return {'positional_embedding'} + + def get_num_layers(self): + return self.transformer.layers + + def build_attention_mask(self): + # lazily create causal attention mask, with full attention between the vision tokens + # pytorch uses additive attention mask; fill with -inf + mask = torch.empty(self.context_length, self.context_length) + mask.fill_(float("-inf")) + mask.triu_(1) # zero out the lower diagonal + return mask + + def forward(self, text, return_all_features: bool=False): + cast_dtype = self.transformer.get_cast_dtype() + x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model] + + x = x + self.positional_embedding.to(cast_dtype) + x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer(x, attn_mask=self.attn_mask) + # x = self.transformer(x) # no attention mask is applied + x = x.permute(1, 0, 2) # LND -> NLD + x = self.ln_final(x) + + if not return_all_features: + # x.shape = [batch_size, n_ctx, transformer.width] + # take features from the eot embedding (eot_token is the highest number in each sequence) + x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection + return x + + def lock(self, *args, **kwargs): + print(f'Freeze the text encoder', flush=True) + for p in self.parameters(): + p.requires_grad = False diff --git a/src/open_clip/eva_clip/utils.py b/src/open_clip/eva_clip/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bdc5a7a451fdf8911ebbc816afbd2664ff348836 --- /dev/null +++ b/src/open_clip/eva_clip/utils.py @@ -0,0 +1,326 @@ +from itertools import repeat +import collections.abc +import logging +import math +import numpy as np + +import torch +from torch import nn as nn +from torchvision.ops.misc import FrozenBatchNorm2d +import torch.nn.functional as F + +# open CLIP +def resize_clip_pos_embed(state_dict, model, interpolation: str = 'bicubic', seq_dim=1): + # Rescale the grid of position embeddings when loading from state_dict + old_pos_embed = state_dict.get('visual.positional_embedding', None) + if old_pos_embed is None or not hasattr(model.visual, 'grid_size'): + return + grid_size = to_2tuple(model.visual.grid_size) + extra_tokens = 1 # FIXME detect different token configs (ie no class token, or more) + new_seq_len = grid_size[0] * grid_size[1] + extra_tokens + if new_seq_len == old_pos_embed.shape[0]: + return + + if extra_tokens: + pos_emb_tok, pos_emb_img = old_pos_embed[:extra_tokens], old_pos_embed[extra_tokens:] + else: + pos_emb_tok, pos_emb_img = None, old_pos_embed + old_grid_size = to_2tuple(int(math.sqrt(len(pos_emb_img)))) + + logging.info('Resizing position embedding grid-size from %s to %s', old_grid_size, grid_size) + pos_emb_img = pos_emb_img.reshape(1, old_grid_size[0], old_grid_size[1], -1).permute(0, 3, 1, 2) + pos_emb_img = F.interpolate( + pos_emb_img, + size=grid_size, + mode=interpolation, + align_corners=True, + ) + pos_emb_img = pos_emb_img.permute(0, 2, 3, 1).reshape(1, grid_size[0] * grid_size[1], -1)[0] + if pos_emb_tok is not None: + new_pos_embed = torch.cat([pos_emb_tok, pos_emb_img], dim=0) + else: + new_pos_embed = pos_emb_img + state_dict['visual.positional_embedding'] = new_pos_embed + + +def resize_visual_pos_embed(state_dict, model, interpolation: str = 'bicubic', seq_dim=1): + # Rescale the grid of position embeddings when loading from state_dict + old_pos_embed = state_dict.get('positional_embedding', None) + if old_pos_embed is None or not hasattr(model.visual, 'grid_size'): + return + grid_size = to_2tuple(model.visual.grid_size) + extra_tokens = 1 # FIXME detect different token configs (ie no class token, or more) + new_seq_len = grid_size[0] * grid_size[1] + extra_tokens + if new_seq_len == old_pos_embed.shape[0]: + return + + if extra_tokens: + pos_emb_tok, pos_emb_img = old_pos_embed[:extra_tokens], old_pos_embed[extra_tokens:] + else: + pos_emb_tok, pos_emb_img = None, old_pos_embed + old_grid_size = to_2tuple(int(math.sqrt(len(pos_emb_img)))) + + logging.info('Resizing position embedding grid-size from %s to %s', old_grid_size, grid_size) + pos_emb_img = pos_emb_img.reshape(1, old_grid_size[0], old_grid_size[1], -1).permute(0, 3, 1, 2) + pos_emb_img = F.interpolate( + pos_emb_img, + size=grid_size, + mode=interpolation, + align_corners=True, + ) + pos_emb_img = pos_emb_img.permute(0, 2, 3, 1).reshape(1, grid_size[0] * grid_size[1], -1)[0] + if pos_emb_tok is not None: + new_pos_embed = torch.cat([pos_emb_tok, pos_emb_img], dim=0) + else: + new_pos_embed = pos_emb_img + state_dict['positional_embedding'] = new_pos_embed + +def resize_evaclip_pos_embed(state_dict, model, interpolation: str = 'bicubic', seq_dim=1): + all_keys = list(state_dict.keys()) + # interpolate position embedding + if 'visual.pos_embed' in state_dict: + pos_embed_checkpoint = state_dict['visual.pos_embed'] + embedding_size = pos_embed_checkpoint.shape[-1] + num_patches = model.visual.patch_embed.num_patches + num_extra_tokens = model.visual.pos_embed.shape[-2] - num_patches + # height (== width) for the checkpoint position embedding + orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5) + # height (== width) for the new position embedding + new_size = int(num_patches ** 0.5) + # class_token and dist_token are kept unchanged + if orig_size != new_size: + print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size)) + extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens] + # only the position tokens are interpolated + pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:] + pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2) + pos_tokens = torch.nn.functional.interpolate( + pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False) + pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2) + new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1) + state_dict['visual.pos_embed'] = new_pos_embed + + patch_embed_proj = state_dict['visual.patch_embed.proj.weight'] + patch_size = model.visual.patch_embed.patch_size + state_dict['visual.patch_embed.proj.weight'] = torch.nn.functional.interpolate( + patch_embed_proj.float(), size=patch_size, mode='bicubic', align_corners=False) + + +def resize_eva_pos_embed(state_dict, model, interpolation: str = 'bicubic', seq_dim=1): + all_keys = list(state_dict.keys()) + # interpolate position embedding + if 'pos_embed' in state_dict: + pos_embed_checkpoint = state_dict['pos_embed'] + embedding_size = pos_embed_checkpoint.shape[-1] + num_patches = model.visual.patch_embed.num_patches + num_extra_tokens = model.visual.pos_embed.shape[-2] - num_patches + # height (== width) for the checkpoint position embedding + orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5) + # height (== width) for the new position embedding + new_size = int(num_patches ** 0.5) + # class_token and dist_token are kept unchanged + if orig_size != new_size: + print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size)) + extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens] + # only the position tokens are interpolated + pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:] + pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2) + pos_tokens = torch.nn.functional.interpolate( + pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False) + pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2) + new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1) + state_dict['pos_embed'] = new_pos_embed + + patch_embed_proj = state_dict['patch_embed.proj.weight'] + patch_size = model.visual.patch_embed.patch_size + state_dict['patch_embed.proj.weight'] = torch.nn.functional.interpolate( + patch_embed_proj.float(), size=patch_size, mode='bicubic', align_corners=False) + + +def resize_rel_pos_embed(state_dict, model, interpolation: str = 'bicubic', seq_dim=1): + all_keys = list(state_dict.keys()) + for key in all_keys: + if "relative_position_index" in key: + state_dict.pop(key) + + if "relative_position_bias_table" in key: + rel_pos_bias = state_dict[key] + src_num_pos, num_attn_heads = rel_pos_bias.size() + dst_num_pos, _ = model.visual.state_dict()[key].size() + dst_patch_shape = model.visual.patch_embed.patch_shape + if dst_patch_shape[0] != dst_patch_shape[1]: + raise NotImplementedError() + num_extra_tokens = dst_num_pos - (dst_patch_shape[0] * 2 - 1) * (dst_patch_shape[1] * 2 - 1) + src_size = int((src_num_pos - num_extra_tokens) ** 0.5) + dst_size = int((dst_num_pos - num_extra_tokens) ** 0.5) + if src_size != dst_size: + print("Position interpolate for %s from %dx%d to %dx%d" % ( + key, src_size, src_size, dst_size, dst_size)) + extra_tokens = rel_pos_bias[-num_extra_tokens:, :] + rel_pos_bias = rel_pos_bias[:-num_extra_tokens, :] + + def geometric_progression(a, r, n): + return a * (1.0 - r ** n) / (1.0 - r) + + left, right = 1.01, 1.5 + while right - left > 1e-6: + q = (left + right) / 2.0 + gp = geometric_progression(1, q, src_size // 2) + if gp > dst_size // 2: + right = q + else: + left = q + + # if q > 1.090307: + # q = 1.090307 + + dis = [] + cur = 1 + for i in range(src_size // 2): + dis.append(cur) + cur += q ** (i + 1) + + r_ids = [-_ for _ in reversed(dis)] + + x = r_ids + [0] + dis + y = r_ids + [0] + dis + + t = dst_size // 2.0 + dx = np.arange(-t, t + 0.1, 1.0) + dy = np.arange(-t, t + 0.1, 1.0) + + print("Original positions = %s" % str(x)) + print("Target positions = %s" % str(dx)) + + all_rel_pos_bias = [] + + for i in range(num_attn_heads): + z = rel_pos_bias[:, i].view(src_size, src_size).float().numpy() + f = F.interpolate.interp2d(x, y, z, kind='cubic') + all_rel_pos_bias.append( + torch.Tensor(f(dx, dy)).contiguous().view(-1, 1).to(rel_pos_bias.device)) + + rel_pos_bias = torch.cat(all_rel_pos_bias, dim=-1) + + new_rel_pos_bias = torch.cat((rel_pos_bias, extra_tokens), dim=0) + state_dict[key] = new_rel_pos_bias + + # interpolate position embedding + if 'pos_embed' in state_dict: + pos_embed_checkpoint = state_dict['pos_embed'] + embedding_size = pos_embed_checkpoint.shape[-1] + num_patches = model.visual.patch_embed.num_patches + num_extra_tokens = model.visual.pos_embed.shape[-2] - num_patches + # height (== width) for the checkpoint position embedding + orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5) + # height (== width) for the new position embedding + new_size = int(num_patches ** 0.5) + # class_token and dist_token are kept unchanged + if orig_size != new_size: + print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size)) + extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens] + # only the position tokens are interpolated + pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:] + pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2) + pos_tokens = torch.nn.functional.interpolate( + pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False) + pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2) + new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1) + state_dict['pos_embed'] = new_pos_embed + + patch_embed_proj = state_dict['patch_embed.proj.weight'] + patch_size = model.visual.patch_embed.patch_size + state_dict['patch_embed.proj.weight'] = torch.nn.functional.interpolate( + patch_embed_proj.float(), size=patch_size, mode='bicubic', align_corners=False) + + +def freeze_batch_norm_2d(module, module_match={}, name=''): + """ + Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is + itself an instance of either `BatchNorm2d` or `SyncBatchNorm`, it is converted into `FrozenBatchNorm2d` and + returned. Otherwise, the module is walked recursively and submodules are converted in place. + + Args: + module (torch.nn.Module): Any PyTorch module. + module_match (dict): Dictionary of full module names to freeze (all if empty) + name (str): Full module name (prefix) + + Returns: + torch.nn.Module: Resulting module + + Inspired by https://github.com/pytorch/pytorch/blob/a5895f85be0f10212791145bfedc0261d364f103/torch/nn/modules/batchnorm.py#L762 + """ + res = module + is_match = True + if module_match: + is_match = name in module_match + if is_match and isinstance(module, (nn.modules.batchnorm.BatchNorm2d, nn.modules.batchnorm.SyncBatchNorm)): + res = FrozenBatchNorm2d(module.num_features) + res.num_features = module.num_features + res.affine = module.affine + if module.affine: + res.weight.data = module.weight.data.clone().detach() + res.bias.data = module.bias.data.clone().detach() + res.running_mean.data = module.running_mean.data + res.running_var.data = module.running_var.data + res.eps = module.eps + else: + for child_name, child in module.named_children(): + full_child_name = '.'.join([name, child_name]) if name else child_name + new_child = freeze_batch_norm_2d(child, module_match, full_child_name) + if new_child is not child: + res.add_module(child_name, new_child) + return res + + +# From PyTorch internals +def _ntuple(n): + def parse(x): + if isinstance(x, collections.abc.Iterable): + return x + return tuple(repeat(x, n)) + return parse + + +to_1tuple = _ntuple(1) +to_2tuple = _ntuple(2) +to_3tuple = _ntuple(3) +to_4tuple = _ntuple(4) +to_ntuple = lambda n, x: _ntuple(n)(x) + + +def is_logging(args): + def is_global_master(args): + return args.rank == 0 + + def is_local_master(args): + return args.local_rank == 0 + + def is_master(args, local=False): + return is_local_master(args) if local else is_global_master(args) + return is_master + + +class AllGather(torch.autograd.Function): + """An autograd function that performs allgather on a tensor. + Performs all_gather operation on the provided tensors. + *** Warning ***: torch.distributed.all_gather has no gradient. + """ + + @staticmethod + def forward(ctx, tensor, rank, world_size): + tensors_gather = [torch.empty_like(tensor) for _ in range(world_size)] + torch.distributed.all_gather(tensors_gather, tensor) + ctx.rank = rank + ctx.batch_size = tensor.shape[0] + return torch.cat(tensors_gather, 0) + + @staticmethod + def backward(ctx, grad_output): + return ( + grad_output[ctx.batch_size * ctx.rank: ctx.batch_size * (ctx.rank + 1)], + None, + None + ) + +allgather = AllGather.apply \ No newline at end of file diff --git a/src/open_clip/factory.py b/src/open_clip/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..bc8b867d693330c050773da5c04dcb43efd9213d --- /dev/null +++ b/src/open_clip/factory.py @@ -0,0 +1,424 @@ +import json +import logging +import os +import pathlib +import re +from copy import deepcopy +from pathlib import Path +from typing import Any, Dict, Optional, Tuple, Union +import torchvision.transforms as T +import torch +from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD +from .model import CLIP, CustomTextCLIP, convert_weights_to_lp, convert_to_custom_text_state_dict,\ + resize_pos_embed, get_cast_dtype +from .coca_model import CoCa +from .loss import ClipLoss, DistillClipLoss +from .openai import load_openai_model +from .pretrained import is_pretrained_cfg, get_pretrained_cfg, \ + download_pretrained, list_pretrained_tags_by_model, download_pretrained_from_hf +from .transform import image_transform, AugmentationCfg, det_image_transform +from .tokenizer import HFTokenizer, tokenize +from open_clip import eva_clip +HF_HUB_PREFIX = 'hf-hub:' +_MODEL_CONFIG_PATHS = [Path(__file__).parent / f"model_configs/"] +_MODEL_CONFIGS = {} # directory (model_name: config) of model architecture configs + + +def _natural_key(string_): + return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] + + +def _rescan_model_configs(): + global _MODEL_CONFIGS + + config_ext = ('.json',) + config_files = [] + for config_path in _MODEL_CONFIG_PATHS: + if config_path.is_file() and config_path.suffix in config_ext: + config_files.append(config_path) + elif config_path.is_dir(): + for ext in config_ext: + config_files.extend(config_path.glob(f'*{ext}')) + + for cf in config_files: + with open(cf, 'r') as f: + model_cfg = json.load(f) + if all(a in model_cfg for a in ('embed_dim', 'vision_cfg', 'text_cfg')): + _MODEL_CONFIGS[cf.stem] = model_cfg + + _MODEL_CONFIGS = {k: v for k, v in sorted(_MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0]))} + + +_rescan_model_configs() # initial populate of model config registry + + +def list_models(): + """ enumerate available model architectures based on config files """ + return list(_MODEL_CONFIGS.keys()) + + +def add_model_config(path): + """ add model config path or file and update registry """ + if not isinstance(path, Path): + path = Path(path) + _MODEL_CONFIG_PATHS.append(path) + _rescan_model_configs() + + +def get_model_config(model_name): + if model_name in _MODEL_CONFIGS: + return deepcopy(_MODEL_CONFIGS[model_name]) + else: + return None + + +def get_tokenizer(model_name): + if 'EVA' in model_name: + from open_clip import eva_clip + return eva_clip.get_tokenizer(model_name) + # 支持 TinyCLIP 模型 + if 'TinyCLIP' in model_name: + from open_clip import tiny_clip + return tiny_clip.get_tokenizer(model_name) + if model_name.startswith(HF_HUB_PREFIX): + tokenizer = HFTokenizer(model_name[len(HF_HUB_PREFIX):]) + elif 'maskclip' in model_name: + return None + else: + config = get_model_config(model_name) + tokenizer = HFTokenizer(config['text_cfg']['hf_tokenizer_name']) if 'hf_tokenizer_name' in config['text_cfg'] else tokenize + return tokenizer + + +def load_state_dict(checkpoint_path: str, map_location='cpu'): + checkpoint = torch.load(checkpoint_path, map_location=map_location) + if isinstance(checkpoint, dict) and 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + else: + state_dict = checkpoint + if next(iter(state_dict.items()))[0].startswith('module'): + state_dict = {k[7:]: v for k, v in state_dict.items()} + return state_dict + + +def load_checkpoint(model, checkpoint_path, strict=True): + state_dict = load_state_dict(checkpoint_path) + # detect old format and make compatible with new format + if 'positional_embedding' in state_dict and not hasattr(model, 'positional_embedding'): + state_dict = convert_to_custom_text_state_dict(state_dict) + resize_pos_embed(state_dict, model) + incompatible_keys = model.load_state_dict(state_dict, strict=strict) + return incompatible_keys + + +def create_model( + model_name: str, + pretrained: Optional[str] = None, + precision: str = 'fp32', + device: Union[str, torch.device] = 'cpu', + jit: bool = False, + force_quick_gelu: bool = False, + force_custom_text: bool = False, + force_patch_dropout: Optional[float] = None, + force_image_size: Optional[Union[int, Tuple[int, int]]] = None, + pretrained_image: bool = False, + pretrained_hf: bool = True, + cache_dir: Optional[str] = None, + output_dict: Optional[bool] = None, + require_pretrained: bool = False, +): + has_hf_hub_prefix = model_name.startswith(HF_HUB_PREFIX) + if has_hf_hub_prefix: + model_id = model_name[len(HF_HUB_PREFIX):] + checkpoint_path = download_pretrained_from_hf(model_id, cache_dir=cache_dir) + config_path = download_pretrained_from_hf(model_id, filename='open_clip_config.json', cache_dir=cache_dir) + + with open(config_path, 'r', encoding='utf-8') as f: + config = json.load(f) + pretrained_cfg = config['preprocess_cfg'] + model_cfg = config['model_cfg'] + else: + model_name = model_name.replace('/', '-') # for callers using old naming with / in ViT names + checkpoint_path = None + pretrained_cfg = {} + model_cfg = None + if isinstance(device, str): + device = torch.device(device) + + # 支持 TinyCLIP 模型(用于 create_model 单独调用的情况,如 teacher_model) + if 'TinyCLIP' in model_name: + from open_clip import tiny_clip + return tiny_clip.create_model( + model_name=model_name, + pretrained=pretrained, + precision=precision, + device=device, + jit=jit, + force_quick_gelu=force_quick_gelu, + pretrained_image=pretrained_image, + cache_dir=cache_dir, + args=None, # create_model 单独调用时没有 args + ) + + if pretrained == 'eva': + return eva_clip.create_model(model_name=model_name, + pretrained=cache_dir, force_custom_clip=True, + precision=precision, + device=device,) + + if pretrained and pretrained.lower() == 'openai': + logging.info(f'Loading pretrained {model_name} from OpenAI.') + model = load_openai_model( + model_name, + precision=precision, + device=device, + jit=jit, + cache_dir=cache_dir, + ) + # to always output dict even if it is clip + if output_dict and hasattr(model, "output_dict"): + model.output_dict = True + else: + model_cfg = model_cfg or get_model_config(model_name) + if model_cfg is not None: + logging.info(f'Loaded {model_name} model config.') + else: + logging.error(f'Model config for {model_name} not found; available models {list_models()}.') + raise RuntimeError(f'Model config for {model_name} not found.') + + if force_quick_gelu: + # override for use of QuickGELU on non-OpenAI transformer models + model_cfg["quick_gelu"] = True + + if force_patch_dropout is not None: + # override the default patch dropout value + model_cfg["vision_cfg"]["patch_dropout"] = force_patch_dropout + + if force_image_size is not None: + # override model config's image size + model_cfg["vision_cfg"]["image_size"] = force_image_size + + if pretrained_image: + if 'timm_model_name' in model_cfg.get('vision_cfg', {}): + # pretrained weight loading for timm models set via vision_cfg + model_cfg['vision_cfg']['timm_model_pretrained'] = True + else: + assert False, 'pretrained image towers currently only supported for timm models' + + cast_dtype = get_cast_dtype(precision) + is_hf_model = 'hf_model_name' in model_cfg.get('text_cfg', {}) + custom_text = model_cfg.pop('custom_text', False) or force_custom_text or is_hf_model + + if custom_text: + if is_hf_model: + model_cfg['text_cfg']['hf_model_pretrained'] = pretrained_hf + if "coca" in model_name: + model = CoCa(**model_cfg, cast_dtype=cast_dtype) + else: + model = CustomTextCLIP(**model_cfg, cast_dtype=cast_dtype) + else: + model = CLIP(**model_cfg, cast_dtype=cast_dtype) + + pretrained_loaded = False + if pretrained: + checkpoint_path = '' + pretrained_cfg = get_pretrained_cfg(model_name, pretrained) + if pretrained_cfg: + checkpoint_path = download_pretrained(pretrained_cfg, cache_dir=cache_dir) + elif os.path.exists(pretrained): + checkpoint_path = pretrained + if checkpoint_path: + print(f'Loading pretrained {model_name} weights ({pretrained}).', flush=True) + logging.info(f'Loading pretrained {model_name} weights ({pretrained}).') + load_checkpoint(model, checkpoint_path) + else: + error_str = ( + f'Pretrained weights ({pretrained}) not found for model {model_name}.' + f'Available pretrained tags ({list_pretrained_tags_by_model(model_name)}.') + logging.warning(error_str) + raise RuntimeError(error_str) + pretrained_loaded = True + elif has_hf_hub_prefix: + logging.info(f'Loading pretrained {model_name} weights ({pretrained}).') + load_checkpoint(model, checkpoint_path) + pretrained_loaded = True + + if require_pretrained and not pretrained_loaded: + # callers of create_model_from_pretrained always expect pretrained weights + raise RuntimeError( + f'Pretrained weights were required for (model: {model_name}, pretrained: {pretrained}) but not loaded.') + + model.to(device=device) + if precision in ("fp16", "bf16"): + convert_weights_to_lp(model, dtype=torch.bfloat16 if precision == 'bf16' else torch.float16) + + # set image / mean metadata from pretrained_cfg if available, or use default + model.visual.image_mean = pretrained_cfg.get('mean', None) or OPENAI_DATASET_MEAN + model.visual.image_std = pretrained_cfg.get('std', None) or OPENAI_DATASET_STD + + # to always output dict even if it is clip + if output_dict and hasattr(model, "output_dict"): + model.output_dict = True + + if jit: + model = torch.jit.script(model) + + return model + +def create_model_and_transforms( + model_name: str, + pretrained: Optional[str] = None, + precision: str = 'fp32', + device: Union[str, torch.device] = 'cpu', + jit: bool = False, + force_quick_gelu: bool = False, + force_custom_text: bool = False, + force_patch_dropout: Optional[float] = None, + force_image_size: Optional[Union[int, Tuple[int, int]]] = None, + pretrained_image: bool = False, + pretrained_hf: bool = True, + image_mean: Optional[Tuple[float, ...]] = None, + image_std: Optional[Tuple[float, ...]] = None, + aug_cfg: Optional[Union[Dict[str, Any], AugmentationCfg]] = None, + cache_dir: Optional[str] = None, + output_dict: Optional[bool] = None, + det_image_size=1024, + dataset_type=None, + args=None +): + + # 支持 TinyCLIP 模型 + if 'TinyCLIP' in model_name: + from open_clip import tiny_clip + model=tiny_clip.create_model( + model_name=model_name, + pretrained=pretrained, + precision=precision, + device=device, + jit=jit, + force_quick_gelu=force_quick_gelu, + pretrained_image=pretrained_image, + cache_dir=cache_dir, + args=None, + ) + else: + model = create_model( + model_name, + pretrained, + precision=precision, + device=device, + jit=jit, + force_quick_gelu=force_quick_gelu, + force_custom_text=force_custom_text, + force_patch_dropout=force_patch_dropout, + force_image_size=force_image_size, + pretrained_image=pretrained_image, + pretrained_hf=pretrained_hf, + cache_dir=cache_dir, + output_dict=output_dict, + ) + for attr in ['visual', 'vision_model']: + if hasattr(model, attr): + image_mean = getattr(getattr(model, attr), 'image_mean', None) + image_std = getattr(getattr(model, attr), 'image_std', None) + image_crop_size = getattr(getattr(model, attr), 'image_size', None) + break + if image_mean is None or image_std is None: + image_mean=OPENAI_DATASET_MEAN + image_std=OPENAI_DATASET_STD + if image_crop_size is None: + image_crop_size=(224, 224) + if args.image_crop_size>0: + image_crop_size=args.image_crop_size + + preprocess_train_det = det_image_transform(det_image_size, + is_train=False, + mean=image_mean, + std=image_std,) + + preprocess_train_img = image_transform(image_crop_size, + is_train=False, + mean=image_mean, + std=image_std, + resize_longest_max=True,) + preprocess_train = [preprocess_train_det, preprocess_train_img] + + + preprocess_val_det = det_image_transform(det_image_size, + is_train=False, + mean=image_mean, + std=image_std,) + + preprocess_val_img = image_transform(image_crop_size, + is_train=False, + mean=image_mean, + std=image_std, + resize_longest_max=True) + + return model, preprocess_train, [preprocess_val_det, preprocess_val_img] + +def create_model_and_transforms_official( + model_name: str, + pretrained: str = '', + precision: str = 'fp32', + device: torch.device = torch.device('cpu'), + jit: bool = False, + force_quick_gelu: bool = False, + pretrained_image: bool = False, + image_mean: Optional[Tuple[float, ...]] = None, + image_std: Optional[Tuple[float, ...]] = None, + cache_dir: Optional[str] = None, +): + model = create_model( + model_name, pretrained, precision, device, jit, + force_quick_gelu=force_quick_gelu, + pretrained_image=pretrained_image, + cache_dir=cache_dir) + + image_mean = image_mean or getattr(model.visual, 'image_mean', None) + image_std = image_std or getattr(model.visual, 'image_std', None) + preprocess_train = image_transform(model.visual.image_size, is_train=True, mean=image_mean, std=image_std) + preprocess_val = image_transform(model.visual.image_size, is_train=False, mean=image_mean, std=image_std) + + return model, preprocess_train, preprocess_val + +def create_model_from_pretrained( + model_name: str, + pretrained: Optional[str] = None, + precision: str = 'fp32', + device: Union[str, torch.device] = 'cpu', + jit: bool = False, + force_quick_gelu: bool = False, + force_custom_text: bool = False, + force_image_size: Optional[Union[int, Tuple[int, int]]] = None, + return_transform: bool = True, + image_mean: Optional[Tuple[float, ...]] = None, + image_std: Optional[Tuple[float, ...]] = None, + cache_dir: Optional[str] = None, +): + model = create_model( + model_name, + pretrained, + precision=precision, + device=device, + jit=jit, + force_quick_gelu=force_quick_gelu, + force_custom_text=force_custom_text, + force_image_size=force_image_size, + cache_dir=cache_dir, + require_pretrained=True, + ) + + if not return_transform: + return model + + image_mean = image_mean or getattr(model.visual, 'image_mean', None) + image_std = image_std or getattr(model.visual, 'image_std', None) + preprocess = image_transform( + model.visual.image_size, + is_train=False, + mean=image_mean, + std=image_std, + ) + + return model, preprocess diff --git a/src/open_clip/generation_utils.py b/src/open_clip/generation_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/open_clip/hf_configs.py b/src/open_clip/hf_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..e236222bafce0358445ea16953ca0b2d5a84758a --- /dev/null +++ b/src/open_clip/hf_configs.py @@ -0,0 +1,45 @@ +# HF architecture dict: +arch_dict = { + # https://huggingface.co/docs/transformers/model_doc/roberta#roberta + "roberta": { + "config_names": { + "context_length": "max_position_embeddings", + "vocab_size": "vocab_size", + "width": "hidden_size", + "heads": "num_attention_heads", + "layers": "num_hidden_layers", + "layer_attr": "layer", + "token_embeddings_attr": "embeddings" + }, + "pooler": "mean_pooler", + }, + # https://huggingface.co/docs/transformers/model_doc/xlm-roberta#transformers.XLMRobertaConfig + "xlm-roberta": { + "config_names": { + "context_length": "max_position_embeddings", + "vocab_size": "vocab_size", + "width": "hidden_size", + "heads": "num_attention_heads", + "layers": "num_hidden_layers", + "layer_attr": "layer", + "token_embeddings_attr": "embeddings" + }, + "pooler": "mean_pooler", + }, + # https://huggingface.co/docs/transformers/model_doc/mt5#mt5 + "mt5": { + "config_names": { + # unlimited seqlen + # https://github.com/google-research/text-to-text-transfer-transformer/issues/273 + # https://github.com/huggingface/transformers/blob/v4.24.0/src/transformers/models/t5/modeling_t5.py#L374 + "context_length": "", + "vocab_size": "vocab_size", + "width": "d_model", + "heads": "num_heads", + "layers": "num_layers", + "layer_attr": "block", + "token_embeddings_attr": "embed_tokens" + }, + "pooler": "mean_pooler", + }, +} diff --git a/src/open_clip/hf_model.py b/src/open_clip/hf_model.py new file mode 100644 index 0000000000000000000000000000000000000000..fbccc812757bf10b122ff14096980e0e38d1d221 --- /dev/null +++ b/src/open_clip/hf_model.py @@ -0,0 +1,176 @@ +""" huggingface model adapter + +Wraps HuggingFace transformers (https://github.com/huggingface/transformers) models for use as a text tower in CLIP model. +""" + +import re + +import torch +import torch.nn as nn +from torch import TensorType + +try: + import transformers + from transformers import AutoModel, AutoTokenizer, AutoConfig, PretrainedConfig + from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, \ + BaseModelOutputWithPoolingAndCrossAttentions +except ImportError as e: + transformers = None + + + class BaseModelOutput: + pass + + + class PretrainedConfig: + pass + +from .hf_configs import arch_dict + + +# utils +def _camel2snake(s): + return re.sub(r'(? torch.Tensor: + # calculated ground-truth and cache if enabled + if self.prev_num_logits != num_logits or device not in self.labels: + labels = torch.arange(num_logits, device=device, dtype=torch.long) + if self.world_size > 1 and self.local_loss: + labels = labels + num_logits * self.rank + if self.cache_labels: + self.labels[device] = labels + self.prev_num_logits = num_logits + else: + labels = self.labels[device] + return labels + + def get_logits(self, image_features, text_features, logit_scale): + if self.world_size > 1: + all_image_features, all_text_features = gather_features( + image_features, text_features, + self.local_loss, self.gather_with_grad, self.rank, self.world_size, self.use_horovod) + + if self.local_loss: + logits_per_image = logit_scale * image_features @ all_text_features.T + logits_per_text = logit_scale * text_features @ all_image_features.T + else: + logits_per_image = logit_scale * all_image_features @ all_text_features.T + logits_per_text = logits_per_image.T + else: + logits_per_image = logit_scale * image_features @ text_features.T + logits_per_text = logit_scale * text_features @ image_features.T + + return logits_per_image, logits_per_text + + def forward(self, image_features, text_features, logit_scale, output_dict=False): + device = image_features.device + logits_per_image, logits_per_text = self.get_logits(image_features, text_features, logit_scale) + + labels = self.get_ground_truth(device, logits_per_image.shape[0]) + + total_loss = ( + F.cross_entropy(logits_per_image, labels) + + F.cross_entropy(logits_per_text, labels) + ) / 2 + + return {"contrastive_loss": total_loss} if output_dict else total_loss + + +class CoCaLoss(ClipLoss): + def __init__( + self, + caption_loss_weight, + clip_loss_weight, + pad_id=0, # pad_token for open_clip custom tokenizer + local_loss=False, + gather_with_grad=False, + cache_labels=False, + rank=0, + world_size=1, + use_horovod=False, + ): + super().__init__( + local_loss=local_loss, + gather_with_grad=gather_with_grad, + cache_labels=cache_labels, + rank=rank, + world_size=world_size, + use_horovod=use_horovod + ) + + self.clip_loss_weight = clip_loss_weight + self.caption_loss_weight = caption_loss_weight + self.caption_loss = nn.CrossEntropyLoss(ignore_index=pad_id) + + def forward(self, image_features, text_features, logits, labels, logit_scale, output_dict=False): + clip_loss = super().forward(image_features, text_features, logit_scale) + clip_loss = self.clip_loss_weight * clip_loss + + caption_loss = self.caption_loss( + logits.permute(0, 2, 1), + labels, + ) + caption_loss = caption_loss * self.caption_loss_weight + + if output_dict: + return {"contrastive_loss": clip_loss, "caption_loss": caption_loss} + + return clip_loss, caption_loss + + +class DistillClipLoss(ClipLoss): + + def dist_loss(self, teacher_logits, student_logits): + loss = F.kl_div(student_logits.log_softmax(dim=1), + teacher_logits.softmax(dim=1), reduction='batchmean') + return loss + # return -(teacher_logits.softmax(dim=1) * student_logits.log_softmax(dim=1)).sum(dim=1).mean(dim=0) + + def forward( + self, + image_features, + text_features, + logit_scale, + dist_image_features, + dist_text_features, + dist_logit_scale, + output_dict=False, + ): + logits_per_image, logits_per_text = \ + self.get_logits(image_features, text_features, logit_scale) + + dist_logits_per_image, dist_logits_per_text = \ + self.get_logits(dist_image_features, dist_text_features, dist_logit_scale) + + labels = self.get_ground_truth(image_features.device, logits_per_image.shape[0]) + + contrastive_loss = ( + F.cross_entropy(logits_per_image, labels) + + F.cross_entropy(logits_per_text, labels) + ) / 2 + + distill_loss = ( + self.dist_loss(dist_logits_per_image, logits_per_image) + + self.dist_loss(dist_logits_per_text, logits_per_text) + ) / 2 + + if output_dict: + return {"contrastive_loss": contrastive_loss, "loss_kl": distill_loss} + + return contrastive_loss, distill_loss diff --git a/src/open_clip/model.py b/src/open_clip/model.py new file mode 100644 index 0000000000000000000000000000000000000000..9c5d28bf528ef8ba7ff3977633c3fe59fe0db560 --- /dev/null +++ b/src/open_clip/model.py @@ -0,0 +1,519 @@ +""" CLIP Model + +Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. +""" +from dataclasses import dataclass +import logging +import math +from typing import Optional, Tuple, Union + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn +from torch.utils.checkpoint import checkpoint + +from .hf_model import HFTextEncoder +from .modified_resnet import ModifiedResNet +from .timm_model import TimmModel +from .transformer import LayerNormFp32, LayerNorm, QuickGELU, Attention, VisionTransformer, TextTransformer +from .utils import to_2tuple + + +@dataclass +class CLIPVisionCfg: + layers: Union[Tuple[int, int, int, int], int] = 12 + width: int = 768 + head_width: int = 64 + mlp_ratio: float = 4.0 + patch_size: int = 16 + image_size: Union[Tuple[int, int], int] = 224 + ls_init_value: Optional[float] = None # layer scale initial value + patch_dropout: float = 0. # what fraction of patches to dropout during training (0 would mean disabled and no patches dropped) - 0.5 to 0.75 recommended in the paper for optimal results + input_patchnorm: bool = False # whether to use dual patchnorm - would only apply the input layernorm on each patch, as post-layernorm already exist in original clip vit design + global_average_pool: bool = False # whether to global average pool the last embedding layer, instead of using CLS token (https://arxiv.org/abs/2205.01580) + attentional_pool: bool = False # whether to use attentional pooler in the last embedding layer + n_queries: int = 256 # n_queries for attentional pooler + attn_pooler_heads: int = 8 # n heads for attentional_pooling + timm_model_name: str = None # a valid model name overrides layers, width, patch_size + timm_model_pretrained: bool = False # use (imagenet) pretrained weights for named model + timm_pool: str = 'avg' # feature pooling for timm model ('abs_attn', 'rot_attn', 'avg', '') + timm_proj: str = 'linear' # linear projection for timm model output ('linear', 'mlp', '') + timm_proj_bias: bool = False # enable bias final projection + timm_drop: float = 0. # head dropout + timm_drop_path: Optional[float] = None # backbone stochastic depth + output_tokens: bool = False + freeze_output = True + freeze_all_bns = True + + +@dataclass +class CLIPTextCfg: + context_length: int = 77 + vocab_size: int = 49408 + width: int = 512 + heads: int = 8 + layers: int = 12 + ls_init_value: Optional[float] = None # layer scale initial value + hf_model_name: str = None + hf_tokenizer_name: str = None + hf_model_pretrained: bool = True + proj: str = 'mlp' + pooler_type: str = 'mean_pooler' + embed_cls: bool = False + pad_id: int = 0 + output_tokens: bool = False + + +def get_cast_dtype(precision: str): + cast_dtype = None + if precision == 'bf16': + cast_dtype = torch.bfloat16 + elif precision == 'fp16': + cast_dtype = torch.float16 + return cast_dtype + + +def _build_vision_tower( + embed_dim: int, + vision_cfg: CLIPVisionCfg, + quick_gelu: bool = False, + cast_dtype: Optional[torch.dtype] = None +): + if isinstance(vision_cfg, dict): + vision_cfg = CLIPVisionCfg(**vision_cfg) + + # OpenAI models are pretrained w/ QuickGELU but native nn.GELU is both faster and more + # memory efficient in recent PyTorch releases (>= 1.10). + # NOTE: timm models always use native GELU regardless of quick_gelu flag. + act_layer = QuickGELU if quick_gelu else nn.GELU + + if vision_cfg.timm_model_name: + visual = TimmModel( + vision_cfg.timm_model_name, + pretrained=vision_cfg.timm_model_pretrained, + pool=vision_cfg.timm_pool, + proj=vision_cfg.timm_proj, + proj_bias=vision_cfg.timm_proj_bias, + drop=vision_cfg.timm_drop, + drop_path=vision_cfg.timm_drop_path, + patch_drop=vision_cfg.patch_dropout if vision_cfg.patch_dropout > 0 else None, + embed_dim=embed_dim, + image_size=vision_cfg.image_size, + ) + act_layer = nn.GELU # so that text transformer doesn't use QuickGELU w/ timm models + elif isinstance(vision_cfg.layers, (tuple, list)): + vision_heads = vision_cfg.width * 32 // vision_cfg.head_width + visual = ModifiedResNet( + layers=vision_cfg.layers, + output_dim=embed_dim, + heads=vision_heads, + image_size=vision_cfg.image_size, + width=vision_cfg.width, + freeze_output=vision_cfg.freeze_output, + freeze_all_bns=vision_cfg.freeze_all_bns + ) + else: + vision_heads = vision_cfg.width // vision_cfg.head_width + norm_layer = LayerNormFp32 if cast_dtype in (torch.float16, torch.bfloat16) else LayerNorm + visual = VisionTransformer( + image_size=vision_cfg.image_size, + patch_size=vision_cfg.patch_size, + width=vision_cfg.width, + layers=vision_cfg.layers, + heads=vision_heads, + mlp_ratio=vision_cfg.mlp_ratio, + ls_init_value=vision_cfg.ls_init_value, + patch_dropout=vision_cfg.patch_dropout, + input_patchnorm=vision_cfg.input_patchnorm, + global_average_pool=vision_cfg.global_average_pool, + attentional_pool=vision_cfg.attentional_pool, + n_queries=vision_cfg.n_queries, + attn_pooler_heads=vision_cfg.attn_pooler_heads, + output_tokens=vision_cfg.output_tokens, + output_dim=embed_dim, + act_layer=act_layer, + norm_layer=norm_layer, + ) + + return visual + + +def _build_text_tower( + embed_dim: int, + text_cfg: CLIPTextCfg, + quick_gelu: bool = False, + cast_dtype: Optional[torch.dtype] = None, +): + if isinstance(text_cfg, dict): + text_cfg = CLIPTextCfg(**text_cfg) + + if text_cfg.hf_model_name: + text = HFTextEncoder( + text_cfg.hf_model_name, + output_dim=embed_dim, + proj=text_cfg.proj, + pooler_type=text_cfg.pooler_type, + pretrained=text_cfg.hf_model_pretrained, + output_tokens=text_cfg.output_tokens, + ) + else: + act_layer = QuickGELU if quick_gelu else nn.GELU + norm_layer = LayerNormFp32 if cast_dtype in (torch.float16, torch.bfloat16) else LayerNorm + + text = TextTransformer( + context_length=text_cfg.context_length, + vocab_size=text_cfg.vocab_size, + width=text_cfg.width, + heads=text_cfg.heads, + layers=text_cfg.layers, + ls_init_value=text_cfg.ls_init_value, + output_dim=embed_dim, + embed_cls=text_cfg.embed_cls, + output_tokens=text_cfg.output_tokens, + pad_id=text_cfg.pad_id, + act_layer=act_layer, + norm_layer=norm_layer, + ) + return text + + +class CLIP(nn.Module): + output_dict: torch.jit.Final[bool] + + def __init__( + self, + embed_dim: int, + vision_cfg: CLIPVisionCfg, + text_cfg: CLIPTextCfg, + quick_gelu: bool = False, + cast_dtype: Optional[torch.dtype] = None, + output_dict: bool = False, + freeze_text=True, + ): + assert freeze_text, 'For now we must freeze text' + super().__init__() + self.output_dict = output_dict + self.visual = _build_vision_tower(embed_dim, vision_cfg, quick_gelu, cast_dtype) + + text = _build_text_tower(embed_dim, text_cfg, quick_gelu, cast_dtype) + if freeze_text: + print(f'Freeze text encoder parameters', flush=True) + for param in text.parameters(): + param.requires_grad = False + text.eval() + self.transformer = text.transformer + self.vocab_size = text.vocab_size + self.embed_dim = embed_dim + self.token_embedding = text.token_embedding + self.positional_embedding = text.positional_embedding + self.ln_final = text.ln_final + self.text_projection = text.text_projection + self.register_buffer('attn_mask', text.attn_mask, persistent=False) + self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) + + + def lock_image_tower(self, unlocked_groups=0, freeze_bn_stats=False, **kwargs): + self.visual.lock(unlocked_groups=unlocked_groups, freeze_bn_stats=freeze_bn_stats) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.visual.set_grad_checkpointing(enable) + self.transformer.grad_checkpointing = enable + + def encode_image(self, image, normalize: bool = False): + features = self.visual(image) + return F.normalize(features, dim=-1) if normalize else features + + def encode_dense(self, image, normalize = False, keep_shape=False, mode="qq_vfm_distill"): + if mode=="qq_vfm_distill" or mode=="kk_vfm_distill" or mode=="csa_vfm_distill": + features,extra_features = self.visual.encode_dense(image, keep_shape=keep_shape,mode=mode) + if normalize: + if keep_shape: + features = F.normalize(features, dim=1) + else: + features = F.normalize(features, dim=-1) + return features, extra_features + else: + features = self.visual.encode_dense(image, keep_shape=keep_shape,mode=mode) + if normalize: + if keep_shape: + features = F.normalize(features, dim=1) + else: + features = F.normalize(features, dim=-1) + return features + + def encode_pseudo_boxes(self, image, normed_boxes, normalize: bool = False, mode="qq_vfm_distill",size=(1, 1)): + if mode=="qq_vfm_distill" or mode=="kk_vfm_distill" or mode=="csa_vfm_distill": + box_features, clip_dense_feats = self.visual.extract_roi_features(image, normed_boxes, mode=mode, size=size) + if normalize: + box_features = F.normalize(box_features, dim=-1) + return box_features, clip_dense_feats + else: + box_features = self.visual.extract_roi_features(image, normed_boxes, mode=mode) + if normalize: + box_features = F.normalize(box_features, dim=-1) + return box_features + + def encode_masks(self, image, masks, normalize=True, mask_attn=False, mode="qq_vfm_distill"): + mask_pooled = self.visual.mask_pool(image, masks, mode) + if normalize: + mask_pooled = F.normalize(mask_pooled, dim=-1) + return mask_pooled + + def encode_text(self, text, normalize: bool = False): + cast_dtype = self.transformer.get_cast_dtype() + + x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model] + + x = x + self.positional_embedding.to(cast_dtype) + x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer(x, attn_mask=self.attn_mask) + x = x.permute(1, 0, 2) # LND -> NLD + x = self.ln_final(x) # [batch_size, n_ctx, transformer.width] + # take features from the eot embedding (eot_token is the highest number in each sequence) + x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection + return F.normalize(x, dim=-1) if normalize else x + + def forward(self, image, text=None): + image_features = self.encode_image(image, normalize=True) + if text is None: + text_features = None + else: + text_features = self.encode_text(text, normalize=True) + if self.output_dict: + return { + "image_features": image_features, + "text_features": text_features, + "logit_scale": self.logit_scale.exp() + } + return image_features, text_features, self.logit_scale.exp() + + def train(self, mode: bool = True): + if not isinstance(mode, bool): + raise ValueError("training mode is expected to be boolean") + self.training = mode + for name, module in self.named_children(): + if name == 'visual': + if mode: + logging.info(f'========Set module {name} as train mode========') + else: + logging.info(f'========Set module {name} as eval mode========') + module.train(mode) + else: + logging.info(f'========Set module {name} as eval mode========') + module.train(mode=False) + return self + + +class CustomTextCLIP(nn.Module): + output_dict: torch.jit.Final[bool] + + def __init__( + self, + embed_dim: int, + vision_cfg: CLIPVisionCfg, + text_cfg: CLIPTextCfg, + quick_gelu: bool = False, + cast_dtype: Optional[torch.dtype] = None, + output_dict: bool = False, + ): + super().__init__() + self.output_dict = output_dict + self.visual = _build_vision_tower(embed_dim, vision_cfg, quick_gelu, cast_dtype) + self.text = _build_text_tower(embed_dim, text_cfg, quick_gelu, cast_dtype) + self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) + + def lock_image_tower(self, unlocked_groups=0, freeze_bn_stats=False): + # lock image tower as per LiT - https://arxiv.org/abs/2111.07991 + self.visual.lock(unlocked_groups=unlocked_groups, freeze_bn_stats=freeze_bn_stats) + + def lock_text_tower(self, unlocked_layers: int = 0, freeze_layer_norm: bool = True): + self.text.lock(unlocked_layers, freeze_layer_norm) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.visual.set_grad_checkpointing(enable) + self.text.set_grad_checkpointing(enable) + + def encode_pseudo_boxes(self, image, normed_boxes, normalize: bool = False): + features = self.visual.extract_roi_features(image, normed_boxes) + return F.normalize(features, dim=-1) if normalize else features + + def encode_image(self, image, normalize: bool = False): + features = self.visual(image) + return F.normalize(features, dim=-1) if normalize else features + + def encode_text(self, text, normalize: bool = False): + features = self.text(text) + return F.normalize(features, dim=-1) if normalize else features + + def forward(self, image, text): + image_features = self.encode_image(image, normalize=True) + if text is None: + text_features = None + else: + text_features = self.encode_text(text, normalize=True) + if self.output_dict: + return { + "image_features": image_features, + "text_features": text_features, + "logit_scale": self.logit_scale.exp() + } + return image_features, text_features, self.logit_scale.exp() + + +def convert_weights_to_lp(model: nn.Module, dtype=torch.float16): + """Convert applicable model parameters to low-precision (bf16 or fp16)""" + + def _convert_weights(l): + if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): + l.weight.data = l.weight.data.to(dtype) + if l.bias is not None: + l.bias.data = l.bias.data.to(dtype) + + if isinstance(l, (nn.MultiheadAttention, Attention)): + for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]: + tensor = getattr(l, attr) + if tensor is not None: + tensor.data = tensor.data.to(dtype) + + for name in ["text_projection", "proj"]: + if hasattr(l, name): + attr = getattr(l, name) + if attr is not None: + attr.data = attr.data.to(dtype) + + model.apply(_convert_weights) + + +convert_weights_to_fp16 = convert_weights_to_lp # backwards compat + + +# used to maintain checkpoint compatibility +def convert_to_custom_text_state_dict(state_dict: dict): + if 'text_projection' in state_dict: + # old format state_dict, move text tower -> .text + new_state_dict = {} + for k, v in state_dict.items(): + if any(k.startswith(p) for p in ( + 'text_projection', + 'positional_embedding', + 'token_embedding', + 'transformer', + 'ln_final', + )): + k = 'text.' + k + new_state_dict[k] = v + return new_state_dict + return state_dict + + +def build_model_from_openai_state_dict( + state_dict: dict, + quick_gelu=True, + cast_dtype=torch.float16, +): + vit = "visual.proj" in state_dict + + if vit: + vision_width = state_dict["visual.conv1.weight"].shape[0] + vision_layers = len( + [k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")]) + vision_patch_size = state_dict["visual.conv1.weight"].shape[-1] + grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5) + image_size = vision_patch_size * grid_size + else: + counts: list = [ + len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]] + vision_layers = tuple(counts) + vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0] + output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5) + vision_patch_size = None + assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0] + image_size = output_width * 32 + + embed_dim = state_dict["text_projection"].shape[1] + context_length = state_dict["positional_embedding"].shape[0] + vocab_size = state_dict["token_embedding.weight"].shape[0] + transformer_width = state_dict["ln_final.weight"].shape[0] + transformer_heads = transformer_width // 64 + transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks"))) + + vision_cfg = CLIPVisionCfg( + layers=vision_layers, + width=vision_width, + patch_size=vision_patch_size, + image_size=image_size, + ) + text_cfg = CLIPTextCfg( + context_length=context_length, + vocab_size=vocab_size, + width=transformer_width, + heads=transformer_heads, + layers=transformer_layers, + ) + model = CLIP( + embed_dim, + vision_cfg=vision_cfg, + text_cfg=text_cfg, + quick_gelu=quick_gelu, # OpenAI models were trained with QuickGELU + cast_dtype=cast_dtype, + ) + + for key in ["input_resolution", "context_length", "vocab_size"]: + state_dict.pop(key, None) + + convert_weights_to_fp16(model) # OpenAI state dicts are partially converted to float16 + model.load_state_dict(state_dict) + return model.eval() + + +def trace_model(model, batch_size=256, device=torch.device('cpu')): + model.eval() + image_size = model.visual.image_size + example_images = torch.ones((batch_size, 3, image_size, image_size), device=device) + example_text = torch.zeros((batch_size, model.context_length), dtype=torch.int, device=device) + model = torch.jit.trace_module( + model, + inputs=dict( + forward=(example_images, example_text), + encode_text=(example_text,), + encode_image=(example_images,) + )) + model.visual.image_size = image_size + return model + + +def resize_pos_embed(state_dict, model, interpolation: str = 'bicubic', antialias: bool = True): + # Rescale the grid of position embeddings when loading from state_dict + old_pos_embed = state_dict.get('visual.positional_embedding', None) + if old_pos_embed is None or not hasattr(model.visual, 'grid_size'): + return + grid_size = to_2tuple(model.visual.grid_size) + extra_tokens = 1 # FIXME detect different token configs (ie no class token, or more) + new_seq_len = grid_size[0] * grid_size[1] + extra_tokens + if new_seq_len == old_pos_embed.shape[0]: + return + + if extra_tokens: + pos_emb_tok, pos_emb_img = old_pos_embed[:extra_tokens], old_pos_embed[extra_tokens:] + else: + pos_emb_tok, pos_emb_img = None, old_pos_embed + old_grid_size = to_2tuple(int(math.sqrt(len(pos_emb_img)))) + + logging.info('Resizing position embedding grid-size from %s to %s', old_grid_size, grid_size) + pos_emb_img = pos_emb_img.reshape(1, old_grid_size[0], old_grid_size[1], -1).permute(0, 3, 1, 2) + pos_emb_img = F.interpolate( + pos_emb_img, + size=grid_size, + mode=interpolation, + antialias=antialias, + align_corners=False, + ) + pos_emb_img = pos_emb_img.permute(0, 2, 3, 1).reshape(1, grid_size[0] * grid_size[1], -1)[0] + if pos_emb_tok is not None: + new_pos_embed = torch.cat([pos_emb_tok, pos_emb_img], dim=0) + else: + new_pos_embed = pos_emb_img + state_dict['visual.positional_embedding'] = new_pos_embed diff --git a/src/open_clip/model_configs/RN101-quickgelu.json b/src/open_clip/model_configs/RN101-quickgelu.json new file mode 100644 index 0000000000000000000000000000000000000000..d0db2c161d13138788c4609d373b023b8454d624 --- /dev/null +++ b/src/open_clip/model_configs/RN101-quickgelu.json @@ -0,0 +1,22 @@ +{ + "embed_dim": 512, + "quick_gelu": true, + "vision_cfg": { + "image_size": 224, + "layers": [ + 3, + 4, + 23, + 3 + ], + "width": 64, + "patch_size": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/RN101.json b/src/open_clip/model_configs/RN101.json new file mode 100644 index 0000000000000000000000000000000000000000..b88b4d3acbaa701c614ab0ea65fc88fcfe289c32 --- /dev/null +++ b/src/open_clip/model_configs/RN101.json @@ -0,0 +1,21 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": [ + 3, + 4, + 23, + 3 + ], + "width": 64, + "patch_size": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/RN50-quickgelu.json b/src/open_clip/model_configs/RN50-quickgelu.json new file mode 100644 index 0000000000000000000000000000000000000000..8c2f91260cdeb043434dc1e893cce81d4ce7f0d1 --- /dev/null +++ b/src/open_clip/model_configs/RN50-quickgelu.json @@ -0,0 +1,22 @@ +{ + "embed_dim": 1024, + "quick_gelu": true, + "vision_cfg": { + "image_size": 224, + "layers": [ + 3, + 4, + 6, + 3 + ], + "width": 64, + "patch_size": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} diff --git a/src/open_clip/model_configs/RN50.json b/src/open_clip/model_configs/RN50.json new file mode 100644 index 0000000000000000000000000000000000000000..33aa884d54fee0076c33676831e49d5e1ffcb8f2 --- /dev/null +++ b/src/open_clip/model_configs/RN50.json @@ -0,0 +1,21 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": [ + 3, + 4, + 6, + 3 + ], + "width": 64, + "patch_size": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/RN50x16.json b/src/open_clip/model_configs/RN50x16.json new file mode 100644 index 0000000000000000000000000000000000000000..3161e1a2c9a839161e652a4d729c2cdc971161db --- /dev/null +++ b/src/open_clip/model_configs/RN50x16.json @@ -0,0 +1,21 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 384, + "layers": [ + 6, + 8, + 18, + 8 + ], + "width": 96, + "patch_size": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/RN50x4.json b/src/open_clip/model_configs/RN50x4.json new file mode 100644 index 0000000000000000000000000000000000000000..e155237f8ce1026aaaeecc80751eabe6f329f0bb --- /dev/null +++ b/src/open_clip/model_configs/RN50x4.json @@ -0,0 +1,21 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "image_size": 288, + "layers": [ + 4, + 6, + 10, + 6 + ], + "width": 80, + "patch_size": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/RN50x64.json b/src/open_clip/model_configs/RN50x64.json new file mode 100644 index 0000000000000000000000000000000000000000..f5aaa2ee3de21ddb03cbd12766a3419bf34898c7 --- /dev/null +++ b/src/open_clip/model_configs/RN50x64.json @@ -0,0 +1,21 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 448, + "layers": [ + 3, + 15, + 36, + 10 + ], + "width": 128, + "patch_size": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-B-16-plus-240.json b/src/open_clip/model_configs/ViT-B-16-plus-240.json new file mode 100644 index 0000000000000000000000000000000000000000..5bbd12bcd01f64d6d0a0aa8316b129327a0d169a --- /dev/null +++ b/src/open_clip/model_configs/ViT-B-16-plus-240.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "image_size": 240, + "layers": 12, + "width": 896, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-B-16-plus.json b/src/open_clip/model_configs/ViT-B-16-plus.json new file mode 100644 index 0000000000000000000000000000000000000000..5dc1e09baccef2b15055c1bffeb9903e760101c6 --- /dev/null +++ b/src/open_clip/model_configs/ViT-B-16-plus.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 896, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-B-16.json b/src/open_clip/model_configs/ViT-B-16.json new file mode 100644 index 0000000000000000000000000000000000000000..395eea77ec3907c0611531aba63459b193e67b9c --- /dev/null +++ b/src/open_clip/model_configs/ViT-B-16.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-B-32-plus-256.json b/src/open_clip/model_configs/ViT-B-32-plus-256.json new file mode 100644 index 0000000000000000000000000000000000000000..2f09c857de9a4c01ae51297a7e2451984879f9de --- /dev/null +++ b/src/open_clip/model_configs/ViT-B-32-plus-256.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "image_size": 256, + "layers": 12, + "width": 896, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-B-32-quickgelu.json b/src/open_clip/model_configs/ViT-B-32-quickgelu.json new file mode 100644 index 0000000000000000000000000000000000000000..ce6bd923593293ed50dfcfb28b73ca7403bcf3c5 --- /dev/null +++ b/src/open_clip/model_configs/ViT-B-32-quickgelu.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 512, + "quick_gelu": true, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-B-32.json b/src/open_clip/model_configs/ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..07c8e28eb06fa1813ba932fe4eec668262d1c47f --- /dev/null +++ b/src/open_clip/model_configs/ViT-B-32.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-H-14.json b/src/open_clip/model_configs/ViT-H-14.json new file mode 100644 index 0000000000000000000000000000000000000000..3e3a7e934e7f02e41f4829996c4950e05f015a74 --- /dev/null +++ b/src/open_clip/model_configs/ViT-H-14.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 32, + "width": 1280, + "head_width": 80, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-H-16.json b/src/open_clip/model_configs/ViT-H-16.json new file mode 100644 index 0000000000000000000000000000000000000000..588485455fdf8193ec16474450b94e31c91ea93c --- /dev/null +++ b/src/open_clip/model_configs/ViT-H-16.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 32, + "width": 1280, + "head_width": 80, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-L-14-280.json b/src/open_clip/model_configs/ViT-L-14-280.json new file mode 100644 index 0000000000000000000000000000000000000000..2262deaefa82792d35d73c0d7c8e620525092581 --- /dev/null +++ b/src/open_clip/model_configs/ViT-L-14-280.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 280, + "layers": 24, + "width": 1024, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-L-14-336.json b/src/open_clip/model_configs/ViT-L-14-336.json new file mode 100644 index 0000000000000000000000000000000000000000..8d1f74c2639c3a3705df9865b9c08215675ddc97 --- /dev/null +++ b/src/open_clip/model_configs/ViT-L-14-336.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 336, + "layers": 24, + "width": 1024, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-L-14.json b/src/open_clip/model_configs/ViT-L-14.json new file mode 100644 index 0000000000000000000000000000000000000000..d4a4bbb1dd4ed4edb317d3ace4f3ad13b211c241 --- /dev/null +++ b/src/open_clip/model_configs/ViT-L-14.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 224, + "layers": 24, + "width": 1024, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-L-16-320.json b/src/open_clip/model_configs/ViT-L-16-320.json new file mode 100644 index 0000000000000000000000000000000000000000..fc2d13ca9ec7f0b56a886ddaf66c4a7ba7a442ba --- /dev/null +++ b/src/open_clip/model_configs/ViT-L-16-320.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 320, + "layers": 24, + "width": 1024, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-L-16.json b/src/open_clip/model_configs/ViT-L-16.json new file mode 100644 index 0000000000000000000000000000000000000000..82a1cedfa290adacbbdc02bc5d589734c22d41d3 --- /dev/null +++ b/src/open_clip/model_configs/ViT-L-16.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 224, + "layers": 24, + "width": 1024, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-M-16-alt.json b/src/open_clip/model_configs/ViT-M-16-alt.json new file mode 100644 index 0000000000000000000000000000000000000000..1a317aad8e02d9c26d2decc7cc49a18dfdf9e0d8 --- /dev/null +++ b/src/open_clip/model_configs/ViT-M-16-alt.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 384, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "patch_size": 16, + "ls_init_value": 1e-4 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 384, + "heads": 6, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-M-16.json b/src/open_clip/model_configs/ViT-M-16.json new file mode 100644 index 0000000000000000000000000000000000000000..f2f3225a46e09237730a151d161f70c86b985172 --- /dev/null +++ b/src/open_clip/model_configs/ViT-M-16.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-M-32-alt.json b/src/open_clip/model_configs/ViT-M-32-alt.json new file mode 100644 index 0000000000000000000000000000000000000000..fd222aeac0f582ef6a1a33f1b3fec70a5b386ac0 --- /dev/null +++ b/src/open_clip/model_configs/ViT-M-32-alt.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 384, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 384, + "heads": 6, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-M-32.json b/src/open_clip/model_configs/ViT-M-32.json new file mode 100644 index 0000000000000000000000000000000000000000..4f718642821035d9776d1e006817d65ede074366 --- /dev/null +++ b/src/open_clip/model_configs/ViT-M-32.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-S-16-alt.json b/src/open_clip/model_configs/ViT-S-16-alt.json new file mode 100644 index 0000000000000000000000000000000000000000..a8c056555e4da3ba0d1475a61fc316362ecce76f --- /dev/null +++ b/src/open_clip/model_configs/ViT-S-16-alt.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 256, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 384, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 256, + "heads": 4, + "layers": 10 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-S-16.json b/src/open_clip/model_configs/ViT-S-16.json new file mode 100644 index 0000000000000000000000000000000000000000..1d8504e59658803f3093e5b05de45f30a09b8185 --- /dev/null +++ b/src/open_clip/model_configs/ViT-S-16.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 384, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 384, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 384, + "heads": 6, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-S-32-alt.json b/src/open_clip/model_configs/ViT-S-32-alt.json new file mode 100644 index 0000000000000000000000000000000000000000..e1dfdec9824df09a2010e991ccfa1d9ee2f45807 --- /dev/null +++ b/src/open_clip/model_configs/ViT-S-32-alt.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 256, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 384, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 256, + "heads": 4, + "layers": 10 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-S-32.json b/src/open_clip/model_configs/ViT-S-32.json new file mode 100644 index 0000000000000000000000000000000000000000..9b8b4191b268de267268cfcb90fc01c6b9df07d8 --- /dev/null +++ b/src/open_clip/model_configs/ViT-S-32.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 384, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 384, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 384, + "heads": 6, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-bigG-14.json b/src/open_clip/model_configs/ViT-bigG-14.json new file mode 100644 index 0000000000000000000000000000000000000000..2cfba479a2e8f3737e71ce240732bf3bc743d8b7 --- /dev/null +++ b/src/open_clip/model_configs/ViT-bigG-14.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1280, + "vision_cfg": { + "image_size": 224, + "layers": 48, + "width": 1664, + "head_width": 104, + "mlp_ratio": 4.9231, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1280, + "heads": 20, + "layers": 32 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-e-14.json b/src/open_clip/model_configs/ViT-e-14.json new file mode 100644 index 0000000000000000000000000000000000000000..91a0fe14d25a107fb8ec48dd7faae313fd26ed7b --- /dev/null +++ b/src/open_clip/model_configs/ViT-e-14.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1280, + "vision_cfg": { + "image_size": 224, + "layers": 56, + "width": 1792, + "head_width": 112, + "mlp_ratio": 8.5715, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1280, + "heads": 20, + "layers": 36 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/ViT-g-14.json b/src/open_clip/model_configs/ViT-g-14.json new file mode 100644 index 0000000000000000000000000000000000000000..8c4b7325cc75b6112be7107d36ae2cb5762d9091 --- /dev/null +++ b/src/open_clip/model_configs/ViT-g-14.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 40, + "width": 1408, + "head_width": 88, + "mlp_ratio": 4.3637, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/coca_ViT-B-32.json b/src/open_clip/model_configs/coca_ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..7e7eb520a6a0096e5602d509ecd6186e278f4725 --- /dev/null +++ b/src/open_clip/model_configs/coca_ViT-B-32.json @@ -0,0 +1,30 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32, + "attentional_pool": true, + "attn_pooler_heads": 8, + "output_tokens": true + }, + "text_cfg": { + "context_length": 76, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12, + "embed_cls": true, + "output_tokens": true + }, + "multimodal_cfg": { + "context_length": 76, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12, + "attn_pooler_heads": 8 + }, + "custom_text": true +} \ No newline at end of file diff --git a/src/open_clip/model_configs/coca_ViT-L-14.json b/src/open_clip/model_configs/coca_ViT-L-14.json new file mode 100644 index 0000000000000000000000000000000000000000..3d5ca4ca2338540f06852df5ff35ea6277e64555 --- /dev/null +++ b/src/open_clip/model_configs/coca_ViT-L-14.json @@ -0,0 +1,30 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 224, + "layers": 24, + "width": 1024, + "patch_size": 14, + "attentional_pool": true, + "attn_pooler_heads": 8, + "output_tokens": true + }, + "text_cfg": { + "context_length": 76, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12, + "embed_cls": true, + "output_tokens": true + }, + "multimodal_cfg": { + "context_length": 76, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12, + "attn_pooler_heads": 12 + }, + "custom_text": true +} diff --git a/src/open_clip/model_configs/coca_base.json b/src/open_clip/model_configs/coca_base.json new file mode 100644 index 0000000000000000000000000000000000000000..cf8c6cecb78a49d7e7140145a0307cbd561077c2 --- /dev/null +++ b/src/open_clip/model_configs/coca_base.json @@ -0,0 +1,31 @@ +{ + "embed_dim": 512, + "multimodal_cfg": { + "width": 768, + "context_length": 76, + "vocab_size": 64000, + "mlp_ratio": 4, + "layers": 12, + "dim_head": 64, + "heads": 12, + "n_queries": 256, + "attn_pooler_heads": 8 + }, + "vision_cfg": { + "image_size": 288, + "layers": 12, + "width": 768, + "patch_size": 18, + "output_tokens": true + }, + "text_cfg": { + "context_length": 76, + "vocab_size": 64000, + "layers": 12, + "heads": 12, + "width": 768, + "embed_cls": true, + "output_tokens": true + }, + "custom_text": true +} \ No newline at end of file diff --git a/src/open_clip/model_configs/coca_roberta-ViT-B-32.json b/src/open_clip/model_configs/coca_roberta-ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..fb46354b95a17a46d7fcfd9d504e917ee6c1608c --- /dev/null +++ b/src/open_clip/model_configs/coca_roberta-ViT-B-32.json @@ -0,0 +1,24 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32, + "output_tokens": true + }, + "text_cfg": { + "hf_model_name": "roberta-base", + "hf_tokenizer_name": "roberta-base", + "proj": "linear", + "width": 768, + "output_tokens": true + }, + "multimodal_cfg": { + "context_length": 76, + "width": 768, + "heads": 8, + "layers": 12 + }, + "custom_text": true +} diff --git a/src/open_clip/model_configs/convnext_base.json b/src/open_clip/model_configs/convnext_base.json new file mode 100644 index 0000000000000000000000000000000000000000..bb6dba181d950ea5081155c90d47e72c94816b80 --- /dev/null +++ b/src/open_clip/model_configs/convnext_base.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "timm_model_name": "convnext_base", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 224 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/convnext_base_w.json b/src/open_clip/model_configs/convnext_base_w.json new file mode 100644 index 0000000000000000000000000000000000000000..82ea7ae3659e5514f37ff982f0ab1141dff4bd18 --- /dev/null +++ b/src/open_clip/model_configs/convnext_base_w.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "timm_model_name": "convnext_base", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 256 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/convnext_base_w_320.json b/src/open_clip/model_configs/convnext_base_w_320.json new file mode 100644 index 0000000000000000000000000000000000000000..0a07c4e16abaa4015ecc5f82ec845de16e1f9d88 --- /dev/null +++ b/src/open_clip/model_configs/convnext_base_w_320.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "timm_model_name": "convnext_base", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 320 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/convnext_large.json b/src/open_clip/model_configs/convnext_large.json new file mode 100644 index 0000000000000000000000000000000000000000..c4a1fea73dbead71c218a0e74b9b15f9b252e3ef --- /dev/null +++ b/src/open_clip/model_configs/convnext_large.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "timm_model_name": "convnext_large", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 224 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/convnext_large_d.json b/src/open_clip/model_configs/convnext_large_d.json new file mode 100644 index 0000000000000000000000000000000000000000..ae8fed21b58e1a6a411daf8b792ee50f0ab42346 --- /dev/null +++ b/src/open_clip/model_configs/convnext_large_d.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "timm_model_name": "convnext_large", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "mlp", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 256 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 16 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/convnext_large_d_320.json b/src/open_clip/model_configs/convnext_large_d_320.json new file mode 100644 index 0000000000000000000000000000000000000000..54c3df36a6f56ace0b12ada24c13058de96feed8 --- /dev/null +++ b/src/open_clip/model_configs/convnext_large_d_320.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "timm_model_name": "convnext_large", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "mlp", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 320 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 16 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/convnext_small.json b/src/open_clip/model_configs/convnext_small.json new file mode 100644 index 0000000000000000000000000000000000000000..3592c2a5cd21aae8d2544931773cf7603f67ea28 --- /dev/null +++ b/src/open_clip/model_configs/convnext_small.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "timm_model_name": "convnext_small", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 224 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/convnext_tiny.json b/src/open_clip/model_configs/convnext_tiny.json new file mode 100644 index 0000000000000000000000000000000000000000..ad11470f5ec40ffec771096971ce58d3d5b9249b --- /dev/null +++ b/src/open_clip/model_configs/convnext_tiny.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "timm_model_name": "convnext_tiny", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 224 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/convnext_xlarge.json b/src/open_clip/model_configs/convnext_xlarge.json new file mode 100644 index 0000000000000000000000000000000000000000..2a909965932eef994177c829fefc2bdc1c219b3f --- /dev/null +++ b/src/open_clip/model_configs/convnext_xlarge.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "timm_model_name": "convnext_xlarge", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 256 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 20 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/convnext_xxlarge.json b/src/open_clip/model_configs/convnext_xxlarge.json new file mode 100644 index 0000000000000000000000000000000000000000..23a55a681c346d1a315d8a163c1cb6ad495e6a91 --- /dev/null +++ b/src/open_clip/model_configs/convnext_xxlarge.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "timm_model_name": "convnext_xxlarge", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 256 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/convnext_xxlarge_320.json b/src/open_clip/model_configs/convnext_xxlarge_320.json new file mode 100644 index 0000000000000000000000000000000000000000..ac5134ca12cbaa97772cde059270d345386a74c7 --- /dev/null +++ b/src/open_clip/model_configs/convnext_xxlarge_320.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "timm_model_name": "convnext_xxlarge", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 320 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/mt5-base-ViT-B-32.json b/src/open_clip/model_configs/mt5-base-ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..58cad89cf0f446bbe15e4e25b1ac43424a828017 --- /dev/null +++ b/src/open_clip/model_configs/mt5-base-ViT-B-32.json @@ -0,0 +1,15 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "hf_model_name": "google/mt5-base", + "hf_tokenizer_name": "google/mt5-base", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/src/open_clip/model_configs/mt5-xl-ViT-H-14.json b/src/open_clip/model_configs/mt5-xl-ViT-H-14.json new file mode 100644 index 0000000000000000000000000000000000000000..b432810777ba7269dbb0e89edfe65cdd27e7d255 --- /dev/null +++ b/src/open_clip/model_configs/mt5-xl-ViT-H-14.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 32, + "width": 1280, + "head_width": 80, + "patch_size": 14 + }, + "text_cfg": { + "hf_model_name": "google/mt5-xl", + "hf_tokenizer_name": "google/mt5-xl", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/src/open_clip/model_configs/roberta-ViT-B-32.json b/src/open_clip/model_configs/roberta-ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..ed687d472a73bb2ac96025f355f80437ab14c260 --- /dev/null +++ b/src/open_clip/model_configs/roberta-ViT-B-32.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "quick_gelu": true, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "hf_model_name": "roberta-base", + "hf_tokenizer_name": "roberta-base", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/src/open_clip/model_configs/swin_base_patch4_window7_224.json b/src/open_clip/model_configs/swin_base_patch4_window7_224.json new file mode 100644 index 0000000000000000000000000000000000000000..bd6820f0cf2aa655e0a2723287f4b78895a58e6a --- /dev/null +++ b/src/open_clip/model_configs/swin_base_patch4_window7_224.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "timm_model_name": "swin_base_patch4_window7_224", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "image_size": 224 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/vit_medium_patch16_gap_256.json b/src/open_clip/model_configs/vit_medium_patch16_gap_256.json new file mode 100644 index 0000000000000000000000000000000000000000..8843eaf08cad16c3e7b5f496fd650715c9573f65 --- /dev/null +++ b/src/open_clip/model_configs/vit_medium_patch16_gap_256.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "timm_model_name": "vit_medium_patch16_gap_256", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "image_size": 256 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/vit_relpos_medium_patch16_cls_224.json b/src/open_clip/model_configs/vit_relpos_medium_patch16_cls_224.json new file mode 100644 index 0000000000000000000000000000000000000000..ed217b202d5e6071c5307f4547c97ff4cfe2abd1 --- /dev/null +++ b/src/open_clip/model_configs/vit_relpos_medium_patch16_cls_224.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "timm_model_name": "vit_relpos_medium_patch16_cls_224", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "image_size": 224 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/model_configs/xlm-roberta-base-ViT-B-32.json b/src/open_clip/model_configs/xlm-roberta-base-ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..751bccc2c6fc41bc4ff20182de88d86739d518d9 --- /dev/null +++ b/src/open_clip/model_configs/xlm-roberta-base-ViT-B-32.json @@ -0,0 +1,15 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "hf_model_name": "xlm-roberta-base", + "hf_tokenizer_name": "xlm-roberta-base", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/src/open_clip/model_configs/xlm-roberta-large-ViT-H-14.json b/src/open_clip/model_configs/xlm-roberta-large-ViT-H-14.json new file mode 100644 index 0000000000000000000000000000000000000000..31f271faa9bbb7a9da53900b483a4c00a16f3c4a --- /dev/null +++ b/src/open_clip/model_configs/xlm-roberta-large-ViT-H-14.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 32, + "width": 1280, + "head_width": 80, + "patch_size": 14 + }, + "text_cfg": { + "hf_model_name": "xlm-roberta-large", + "hf_tokenizer_name": "xlm-roberta-large", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/src/open_clip/modified_resnet.py b/src/open_clip/modified_resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..19c0527593c85083a69e74573ce0c66dfcddb4dd --- /dev/null +++ b/src/open_clip/modified_resnet.py @@ -0,0 +1,402 @@ +from collections import OrderedDict + +import torch +from torch import nn +from torch.nn import functional as F + +from open_clip.utils import freeze_batch_norm_2d +from torchvision.ops import roi_align + + +class FrozenBatchNorm2d(nn.Module): + _version = 3 + def __init__(self, num_features, eps=1e-5): + super().__init__() + self.num_features = num_features + self.eps = eps + self.register_buffer("weight", torch.ones(num_features)) + self.register_buffer("bias", torch.zeros(num_features)) + self.register_buffer("running_mean", torch.zeros(num_features)) + self.register_buffer("running_var", torch.ones(num_features) - eps) + + def forward(self, x): + if x.requires_grad: + scale = self.weight * (self.running_var + self.eps).rsqrt() + bias = self.bias - self.running_mean * scale + scale = scale.reshape(1, -1, 1, 1) + bias = bias.reshape(1, -1, 1, 1) + out_dtype = x.dtype # may be half + return x * scale.to(out_dtype) + bias.to(out_dtype) + else: + return F.batch_norm( + x, + self.running_mean, + self.running_var, + self.weight, + self.bias, + training=False, + eps=self.eps, + ) + + def _load_from_state_dict( + self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs + ): + version = local_metadata.get("version", None) + + if version is None or version < 2: + if prefix + "running_mean" not in state_dict: + state_dict[prefix + "running_mean"] = torch.zeros_like(self.running_mean) + if prefix + "running_var" not in state_dict: + state_dict[prefix + "running_var"] = torch.ones_like(self.running_var) + + super()._load_from_state_dict( + state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs + ) + + def __repr__(self): + return "FrozenBatchNorm2d(num_features={}, eps={})".format(self.num_features, self.eps) + + @classmethod + def convert_frozen_batchnorm(cls, module): + bn_module = nn.modules.batchnorm + bn_module = (bn_module.BatchNorm2d, bn_module.SyncBatchNorm) + res = module + if isinstance(module, bn_module): + res = cls(module.num_features) + if module.affine: + res.weight.data = module.weight.data.clone().detach() + res.bias.data = module.bias.data.clone().detach() + res.running_mean.data = module.running_mean.data + res.running_var.data = module.running_var.data + res.eps = module.eps + else: + for name, child in module.named_children(): + new_child = cls.convert_frozen_batchnorm(child) + if new_child is not child: + res.add_module(name, new_child) + return res + + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__(self, inplanes, planes, stride=1): + super().__init__() + + # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1 + self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False) + self.bn1 = nn.BatchNorm2d(planes) + self.act1 = nn.ReLU(inplace=True) + + self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(planes) + self.act2 = nn.ReLU(inplace=True) + + self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity() + + self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False) + self.bn3 = nn.BatchNorm2d(planes * self.expansion) + self.act3 = nn.ReLU(inplace=True) + + self.downsample = None + self.stride = stride + + if stride > 1 or inplanes != planes * Bottleneck.expansion: + # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1 + self.downsample = nn.Sequential(OrderedDict([ + ("-1", nn.AvgPool2d(stride)), + ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)), + ("1", nn.BatchNorm2d(planes * self.expansion)) + ])) + + def forward(self, x: torch.Tensor): + identity = x + + out = self.act1(self.bn1(self.conv1(x))) + out = self.act2(self.bn2(self.conv2(out))) + out = self.avgpool(out) + out = self.bn3(self.conv3(out)) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + out = self.act3(out) + return out + + +class AttentionPool2d(nn.Module): + def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None, + freeze_output=True): + super().__init__() + self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5) + self.k_proj = nn.Linear(embed_dim, embed_dim) + self.q_proj = nn.Linear(embed_dim, embed_dim) + self.v_proj = nn.Linear(embed_dim, embed_dim) + self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim) + self.num_heads = num_heads + self.spacial_dim = spacial_dim + + if freeze_output: + print(f'Freeze the V2L layer', flush=True) + for p in self.c_proj.parameters(): + p.requires_grad = False + for p in self.v_proj.parameters(): + p.requires_grad = False + + def forward(self, x): + x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC + x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC + x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC + x, _ = F.multi_head_attention_forward( + query=x, key=x, value=x, + embed_dim_to_check=x.shape[-1], + num_heads=self.num_heads, + q_proj_weight=self.q_proj.weight, + k_proj_weight=self.k_proj.weight, + v_proj_weight=self.v_proj.weight, + in_proj_weight=None, + in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]), + bias_k=None, + bias_v=None, + add_zero_attn=False, + dropout_p=0., + out_proj_weight=self.c_proj.weight, + out_proj_bias=self.c_proj.bias, + use_separate_proj_weight=True, + training=self.training, + need_weights=False + ) + + return x[0] + + def rescale_positional_embedding(self, out_size, dtype): + h, w = out_size + rescaled_positional_embedding = \ + self.positional_embedding.new_zeros(1 + h*w, self.positional_embedding.shape[1]) + rescaled_positional_embedding[0] = self.positional_embedding[0] + pe_2d = self.positional_embedding[1:].T.contiguous().view( + 1, -1, self.spacial_dim, self.spacial_dim) + pe_2d = F.interpolate(pe_2d, out_size, mode='bicubic', align_corners=False).view(-1, h*w) + rescaled_positional_embedding[1:] = pe_2d.T.contiguous() + + return rescaled_positional_embedding.to(dtype=dtype) + + def proj_without_attn(self, value): + value = F.linear(value, self.v_proj.weight, bias=self.v_proj.bias) + value = F.linear(value, self.c_proj.weight, bias=self.c_proj.bias) + + return value + + def forward_dense(self, x): + bs, _, h, w = x.shape + x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC + x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC + if h == self.spacial_dim and w == self.spacial_dim: + pe = self.positional_embedding[:, None, :].to(x.dtype) + else: + pe = self.rescale_positional_embedding(out_size=(h, w), dtype=x.dtype)[:, None, :] + + x = x + pe # (HW+1)NC + + x = self.proj_without_attn(x) + + return x[1:].permute(1, 2, 0).view(bs, -1, h, w) + + +class ModifiedResNet(nn.Module): + """ + A ResNet class that is similar to torchvision's but contains the following changes: + - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool. + - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1 + - The final pooling layer is a QKV attention instead of an average pool + """ + + def __init__(self, layers, output_dim, heads, image_size=224, width=64, + freeze_output=True, + freeze_all_bns=True): + super().__init__() + self.output_dim = output_dim + self.image_size = image_size + self.freeze_output = freeze_output + self.freeze_all_bns = freeze_all_bns + # the 3-layer stem + self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False) + self.bn1 = nn.BatchNorm2d(width // 2) + self.act1 = nn.ReLU(inplace=True) + self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(width // 2) + self.act2 = nn.ReLU(inplace=True) + self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False) + self.bn3 = nn.BatchNorm2d(width) + self.act3 = nn.ReLU(inplace=True) + self.avgpool = nn.AvgPool2d(2) + + # residual layers + self._inplanes = width # this is a *mutable* variable used during construction + self.layer1 = self._make_layer(width, layers[0]) + self.layer2 = self._make_layer(width * 2, layers[1], stride=2) + self.layer3 = self._make_layer(width * 4, layers[2], stride=2) + self.layer4 = self._make_layer(width * 8, layers[3], stride=2) + + embed_dim = width * 32 # the ResNet feature dimension + self.attnpool = AttentionPool2d(image_size // 32, embed_dim, heads, output_dim, freeze_output) + self.attnpool_input_size = image_size // 32 + + def _make_layer(self, planes, blocks, stride=1): + layers = [Bottleneck(self._inplanes, planes, stride)] + + self._inplanes = planes * Bottleneck.expansion + for _ in range(1, blocks): + layers.append(Bottleneck(self._inplanes, planes)) + + return nn.Sequential(*layers) + + def lock(self, unlocked_groups=0, freeze_bn_stats=True): + assert freeze_bn_stats + def _lock(module): + for param in module.parameters(): + param.requires_grad = False + if freeze_bn_stats: + freeze_batch_norm_2d(module) + module.eval() + + freeze_at = 5 - unlocked_groups + print(f'Freeze the resnet at {freeze_at}', flush=True) + + if freeze_at >= 1: # stem + _lock(self.conv1) + _lock(self.bn1) + _lock(self.conv2) + _lock(self.bn2) + _lock(self.conv3) + _lock(self.bn3) + # each stage is a torch.nn.modules.container.Sequential + for idx, stage in enumerate([self.layer1, self.layer2, self.layer3, self.layer4], start=2): + if freeze_at >= idx: + for block in stage.children(): # each block is a Bottleneck + _lock(block) + if self.freeze_all_bns: + print(f'Freeze all bn layers', flush=True) # TODO: study if this is necessary + freeze_batch_norm_2d(self) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + # FIXME support for non-transformer + pass + + def stem(self, x): + x = self.act1(self.bn1(self.conv1(x))) + x = self.act2(self.bn2(self.conv2(x))) + x = self.act3(self.bn3(self.conv3(x))) + x = self.avgpool(x) + return x + + def forward(self, x): + with torch.no_grad(): + x = self.stem(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + x = self.attnpool(x) + + return x + + @staticmethod + def _denormalize_boxes(normed_boxes, x): + h, w = x.shape[-2:] + denormed_boxes = [] + for boxes in normed_boxes: + new_boxes = boxes.clone() # FIXME: do not change the value in normed_boxes! + new_boxes[:, [0, 2]] *= w + new_boxes[:, [1, 3]] *= h + denormed_boxes.append(new_boxes) + return denormed_boxes + + def _extract_roi_features_v1(self, x, normed_boxes, **kwargs): + with torch.no_grad(): # TODO: speed up trick + x = self.stem(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + + tar_size = self.attnpool_input_size + # TODO: debug + roi_feats = roi_align(x, self._denormalize_boxes(normed_boxes, x), + (tar_size, tar_size), 1.0, -1, True) + + roi_feats = self.attnpool(roi_feats) + + return roi_feats + + def extract_roi_features(self, x, normed_boxes, extract_type='v1'): + if extract_type == 'v1': + return self._extract_roi_features_v1(x, normed_boxes) + else: + assert extract_type == 'v2' + return self._extract_roi_features_v2(x, normed_boxes) + + def mask_attn_pool(self, image, masks): + return self.mask_pool(image, masks) + + def mask_pool(self, image, masks): + x = self.stem(image) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + + feature_map = self.attnpool.forward_dense(x) + feature_map = F.normalize(feature_map, dim=1) # remember to normalize! + + feature_map = feature_map.flatten(-2, -1) # bs, c, h*w + num_masks_per_image = [len(masks_per_image) for masks_per_image in masks] + masks = torch.cat(masks).float().flatten(-2, -1) # bs, h*w + feature_map = torch.repeat_interleave( + feature_map, torch.tensor(num_masks_per_image, device=feature_map.device), dim=0) + features = (feature_map * masks[:, None]).sum(-1) / (masks.sum(1, keepdim=True) + 1e-12) + + return features + + def _extract_roi_features_v2(self, x, normed_boxes, **kwargs): + x = self.stem(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + + x = self.attnpool.forward_dense(x) + x = F.normalize(x, dim=1) # remember to normalize! + # TODO: debug + roi_feats = roi_align(x, self._denormalize_boxes(normed_boxes, x), + (1, 1), 1.0, -1, True)[:, :, 0, 0] + return roi_feats + # def _extract_roi_features_v2(self, x, normed_boxes, **kwargs): + # with torch.no_grad(): # TODO speed up trick + # x = self.stem(x) + # x = self.layer1(x) + # x = self.layer2(x) + # x = self.layer3(x) + # tar_size = self.attnpool_input_size * 2 + # # TODO: debug + # roi_feats = roi_align(x, self._denormalize_boxes(normed_boxes, x), + # (tar_size, tar_size), 1.0, -1, True) + # + # roi_feats = self.layer4(roi_feats) + # roi_feats = self.attnpool(roi_feats) + # + # return roi_feats + + def encode_dense(self, x, keep_shape=True): + x = self.stem(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + + feature_map = self.attnpool.forward_dense(x) + feature_map = F.normalize(feature_map, dim=1) # remember to normalize! + + return feature_map diff --git a/src/open_clip/openai.py b/src/open_clip/openai.py new file mode 100644 index 0000000000000000000000000000000000000000..b02d4ad1b70839e5fd4afae035bbc11ac305ed7a --- /dev/null +++ b/src/open_clip/openai.py @@ -0,0 +1,143 @@ +""" OpenAI pretrained model functions + +Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. +""" + +import os +import warnings +from typing import List, Optional, Union + +import torch + +from .model import build_model_from_openai_state_dict, convert_weights_to_lp, get_cast_dtype +from .pretrained import get_pretrained_url, list_pretrained_models_by_tag, download_pretrained_from_url + +__all__ = ["list_openai_models", "load_openai_model"] + + +def list_openai_models() -> List[str]: + """Returns the names of available CLIP models""" + return list_pretrained_models_by_tag('openai') + + +def load_openai_model( + name: str, + precision: Optional[str] = None, + device: Optional[Union[str, torch.device]] = None, + jit: bool = True, + cache_dir: Optional[str] = None, +): + """Load a CLIP model + + Parameters + ---------- + name : str + A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict + precision: str + Model precision, if None defaults to 'fp32' if device == 'cpu' else 'fp16'. + device : Union[str, torch.device] + The device to put the loaded model + jit : bool + Whether to load the optimized JIT model (default) or more hackable non-JIT model. + cache_dir : Optional[str] + The directory to cache the downloaded model weights + + Returns + ------- + model : torch.nn.Module + The CLIP model + preprocess : Callable[[PIL.Image], torch.Tensor] + A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input + """ + if device is None: + device = "cuda" if torch.cuda.is_available() else "cpu" + if precision is None: + precision = 'fp32' if device == 'cpu' else 'fp16' + + if get_pretrained_url(name, 'openai'): + model_path = download_pretrained_from_url(get_pretrained_url(name, 'openai'), cache_dir=cache_dir) + elif os.path.isfile(name): + model_path = name + else: + raise RuntimeError(f"Model {name} not found; available models = {list_openai_models()}") + + try: + # loading JIT archive + model = torch.jit.load(model_path, map_location=device if jit else "cpu").eval() + state_dict = None + except RuntimeError: + # loading saved state dict + if jit: + warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead") + jit = False + state_dict = torch.load(model_path, map_location="cpu") + if not jit: + # Build a non-jit model from the OpenAI jitted model state dict + cast_dtype = get_cast_dtype(precision) + try: + model = build_model_from_openai_state_dict(state_dict or model.state_dict(), cast_dtype=cast_dtype) + except KeyError: + sd = {k[7:]: v for k, v in state_dict["state_dict"].items()} + model = build_model_from_openai_state_dict(sd, cast_dtype=cast_dtype) + + # model from OpenAI state dict is in manually cast fp16 mode, must be converted for AMP/fp32/bf16 use + model = model.to(device) + if precision.startswith('amp') or precision == 'fp32': + model.float() + elif precision == 'bf16': + convert_weights_to_lp(model, dtype=torch.bfloat16) + + return model + + # patch the device names + device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[]) + device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1] + + def patch_device(module): + try: + graphs = [module.graph] if hasattr(module, "graph") else [] + except RuntimeError: + graphs = [] + + if hasattr(module, "forward1"): + graphs.append(module.forward1.graph) + + for graph in graphs: + for node in graph.findAllNodes("prim::Constant"): + if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"): + node.copyAttributes(device_node) + + model.apply(patch_device) + patch_device(model.encode_image) + patch_device(model.encode_text) + + # patch dtype to float32 (typically for CPU) + if precision == 'fp32': + float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[]) + float_input = list(float_holder.graph.findNode("aten::to").inputs())[1] + float_node = float_input.node() + + def patch_float(module): + try: + graphs = [module.graph] if hasattr(module, "graph") else [] + except RuntimeError: + graphs = [] + + if hasattr(module, "forward1"): + graphs.append(module.forward1.graph) + + for graph in graphs: + for node in graph.findAllNodes("aten::to"): + inputs = list(node.inputs()) + for i in [1, 2]: # dtype can be the second or third argument to aten::to() + if inputs[i].node()["value"] == 5: + inputs[i].node().copyAttributes(float_node) + + model.apply(patch_float) + patch_float(model.encode_image) + patch_float(model.encode_text) + model.float() + + # ensure image_size attr available at consistent location for both jit and non-jit + model.visual.image_size = model.input_resolution.item() + return model diff --git a/src/open_clip/pretrained.py b/src/open_clip/pretrained.py new file mode 100644 index 0000000000000000000000000000000000000000..87e7e527497d643fdf6ac931ac73b6e887a90d0d --- /dev/null +++ b/src/open_clip/pretrained.py @@ -0,0 +1,376 @@ +import hashlib +import os +import urllib +import warnings +from functools import partial +from typing import Dict, Union + +from tqdm import tqdm + +from .version import __version__ + +try: + from huggingface_hub import hf_hub_download + hf_hub_download = partial(hf_hub_download, library_name="open_clip", library_version=__version__) + _has_hf_hub = True +except ImportError: + hf_hub_download = None + _has_hf_hub = False + + +def _pcfg(url='', hf_hub='', mean=None, std=None): + return dict( + url=url, + hf_hub=hf_hub, + mean=mean, + std=std, + ) + + +_RN50 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-yfcc15m-455df137.pt"), + cc12m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-cc12m-f000538c.pt"), +) + +_RN50_quickgelu = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-yfcc15m-455df137.pt"), + cc12m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-cc12m-f000538c.pt"), +) + +_RN101 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn101-quickgelu-yfcc15m-3e04b30e.pt"), +) + +_RN101_quickgelu = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn101-quickgelu-yfcc15m-3e04b30e.pt"), +) + +_RN50x4 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt"), +) + +_RN50x16 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt"), +) + +_RN50x64 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt"), +) + +_VITB32 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e31-d867053b.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e32-46683a32.pt"), + laion2b_e16=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-laion2b_e16-af8dbd0c.pth"), + laion2b_s34b_b79k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-laion2B-s34B-b79K/') +) + +_VITB32_quickgelu = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e31-d867053b.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e32-46683a32.pt"), +) + +_VITB16 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16-laion400m_e31-00efa78f.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16-laion400m_e32-55e67d44.pt"), + # laion400m_32k=_pcfg( + # url="", + # mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), + # laion400m_64k=_pcfg( + # url="", + # mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), + laion2b_s34b_b88k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-laion2B-s34B-b88K/'), +) + +_VITB16_PLUS_240 = dict( + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16_plus_240-laion400m_e31-8fb26589.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16_plus_240-laion400m_e32-699c4b84.pt"), +) + +_VITL14 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_l_14-laion400m_e31-69988bb6.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_l_14-laion400m_e32-3d133497.pt"), + laion2b_s32b_b82k=_pcfg( + hf_hub='laion/CLIP-ViT-L-14-laion2B-s32B-b82K/', + mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), +) + +_VITL14_336 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt"), +) + +_VITH14 = dict( + laion2b_s32b_b79k=_pcfg(hf_hub='laion/CLIP-ViT-H-14-laion2B-s32B-b79K/'), +) + +_VITg14 = dict( + laion2b_s12b_b42k=_pcfg(hf_hub='laion/CLIP-ViT-g-14-laion2B-s12B-b42K/'), + laion2b_s34b_b88k=_pcfg(hf_hub='laion/CLIP-ViT-g-14-laion2B-s34B-b88K/'), +) + +_VITbigG14 = dict( + laion2b_s39b_b160k=_pcfg(hf_hub='laion/CLIP-ViT-bigG-14-laion2B-39B-b160k/'), +) + +_robertaViTB32 = dict( + laion2b_s12b_b32k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-roberta-base-laion2B-s12B-b32k/'), +) + +_xlmRobertaBaseViTB32 = dict( + laion5b_s13b_b90k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-xlm-roberta-base-laion5B-s13B-b90k/'), +) + +_xlmRobertaLargeFrozenViTH14 = dict( + frozen_laion5b_s13b_b90k=_pcfg(hf_hub='laion/CLIP-ViT-H-14-frozen-xlm-roberta-large-laion5B-s13B-b90k/'), +) + +_convnext_base = dict( + laion400m_s13b_b51k=_pcfg(hf_hub='laion/CLIP-convnext_base-laion400M-s13B-b51K/'), +) + +_convnext_base_w = dict( + laion2b_s13b_b82k=_pcfg(hf_hub='laion/CLIP-convnext_base_w-laion2B-s13B-b82K/'), + laion2b_s13b_b82k_augreg=_pcfg(hf_hub='laion/CLIP-convnext_base_w-laion2B-s13B-b82K-augreg/'), + laion_aesthetic_s13b_b82k=_pcfg(hf_hub='laion/CLIP-convnext_base_w-laion_aesthetic-s13B-b82K/'), +) + +_convnext_base_w_320 = dict( + laion_aesthetic_s13b_b82k=_pcfg(hf_hub='laion/CLIP-convnext_base_w_320-laion_aesthetic-s13B-b82K/'), + laion_aesthetic_s13b_b82k_augreg=_pcfg(hf_hub='laion/CLIP-convnext_base_w_320-laion_aesthetic-s13B-b82K-augreg/'), +) + +_convnext_large_d = dict( + laion2b_s26b_b102k_augreg=_pcfg(hf_hub='laion/CLIP-convnext_large_d.laion2B-s26B-b102K-augreg/'), +) + +_convnext_large_d_320 = dict( + laion2b_s29b_b131k_ft=_pcfg(hf_hub='laion/CLIP-convnext_large_d_320.laion2B-s29B-b131K-ft/'), + laion2b_s29b_b131k_ft_soup=_pcfg(hf_hub='laion/CLIP-convnext_large_d_320.laion2B-s29B-b131K-ft-soup/'), +) + +_convnext_xxlarge = dict( + laion2b_s34b_b82k_augreg=_pcfg(hf_hub='laion/CLIP-convnext_xxlarge-laion2B-s34B-b82K-augreg/'), + laion2b_s34b_b82k_augreg_rewind=_pcfg(hf_hub='laion/CLIP-convnext_xxlarge-laion2B-s34B-b82K-augreg-rewind/'), + laion2b_s34b_b82k_augreg_soup=_pcfg(hf_hub='laion/CLIP-convnext_xxlarge-laion2B-s34B-b82K-augreg-soup/'), +) + +_coca_VITB32 = dict( + laion2b_s13b_b90k=_pcfg(hf_hub='laion/CoCa-ViT-B-32-laion2B-s13B-b90k/'), + mscoco_finetuned_laion2b_s13b_b90k=_pcfg(hf_hub='laion/mscoco_finetuned_CoCa-ViT-B-32-laion2B-s13B-b90k/') +) + +_coca_VITL14 = dict( + laion2b_s13b_b90k=_pcfg(hf_hub='laion/CoCa-ViT-L-14-laion2B-s13B-b90k/'), + mscoco_finetuned_laion2b_s13b_b90k=_pcfg(hf_hub='laion/mscoco_finetuned_CoCa-ViT-L-14-laion2B-s13B-b90k/') +) + + +_PRETRAINED = { + "RN50": _RN50, + "RN50-quickgelu": _RN50_quickgelu, + "RN101": _RN101, + "RN101-quickgelu": _RN101_quickgelu, + "RN50x4": _RN50x4, + "RN50x16": _RN50x16, + "RN50x64": _RN50x64, + "ViT-B-32": _VITB32, + "ViT-B-32-quickgelu": _VITB32_quickgelu, + "ViT-B-16": _VITB16, + "ViT-B-16-plus-240": _VITB16_PLUS_240, + "ViT-L-14": _VITL14, + "ViT-L-14-336": _VITL14_336, + "ViT-H-14": _VITH14, + "ViT-g-14": _VITg14, + "ViT-bigG-14": _VITbigG14, + "roberta-ViT-B-32": _robertaViTB32, + "xlm-roberta-base-ViT-B-32": _xlmRobertaBaseViTB32, + "xlm-roberta-large-ViT-H-14": _xlmRobertaLargeFrozenViTH14, + "convnext_base": _convnext_base, + "convnext_base_w": _convnext_base_w, + "convnext_base_w_320": _convnext_base_w_320, + "convnext_large_d": _convnext_large_d, + "convnext_large_d_320": _convnext_large_d_320, + "convnext_xxlarge": _convnext_xxlarge, + "coca_ViT-B-32": _coca_VITB32, + "coca_ViT-L-14": _coca_VITL14, +} + + +def _clean_tag(tag: str): + # normalize pretrained tags + return tag.lower().replace('-', '_') + + +def list_pretrained(as_str: bool = False): + """ returns list of pretrained models + Returns a tuple (model_name, pretrain_tag) by default or 'name:tag' if as_str == True + """ + return [':'.join([k, t]) if as_str else (k, t) for k in _PRETRAINED.keys() for t in _PRETRAINED[k].keys()] + + +def list_pretrained_models_by_tag(tag: str): + """ return all models having the specified pretrain tag """ + models = [] + tag = _clean_tag(tag) + for k in _PRETRAINED.keys(): + if tag in _PRETRAINED[k]: + models.append(k) + return models + + +def list_pretrained_tags_by_model(model: str): + """ return all pretrain tags for the specified model architecture """ + tags = [] + if model in _PRETRAINED: + tags.extend(_PRETRAINED[model].keys()) + return tags + + +def is_pretrained_cfg(model: str, tag: str): + if model not in _PRETRAINED: + return False + return _clean_tag(tag) in _PRETRAINED[model] + + +def get_pretrained_cfg(model: str, tag: str): + if model not in _PRETRAINED: + return {} + model_pretrained = _PRETRAINED[model] + return model_pretrained.get(_clean_tag(tag), {}) + + +def get_pretrained_url(model: str, tag: str): + cfg = get_pretrained_cfg(model, _clean_tag(tag)) + return cfg.get('url', '') + + +def download_pretrained_from_url( + url: str, + cache_dir: Union[str, None] = None, +): + if not cache_dir: + cache_dir = os.path.expanduser("~/.cache/clip") + os.makedirs(cache_dir, exist_ok=True) + filename = os.path.basename(url) + + if 'openaipublic' in url: + expected_sha256 = url.split("/")[-2] + elif 'mlfoundations' in url: + expected_sha256 = os.path.splitext(filename)[0].split("-")[-1] + else: + expected_sha256 = '' + + download_target = os.path.join(cache_dir, filename) + + if os.path.exists(download_target) and not os.path.isfile(download_target): + raise RuntimeError(f"{download_target} exists and is not a regular file") + + if os.path.isfile(download_target): + if expected_sha256: + if hashlib.sha256(open(download_target, "rb").read()).hexdigest().startswith(expected_sha256): + return download_target + else: + warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file") + else: + return download_target + + with urllib.request.urlopen(url) as source, open(download_target, "wb") as output: + with tqdm(total=int(source.headers.get("Content-Length")), ncols=80, unit='iB', unit_scale=True) as loop: + while True: + buffer = source.read(8192) + if not buffer: + break + + output.write(buffer) + loop.update(len(buffer)) + + if expected_sha256 and not hashlib.sha256(open(download_target, "rb").read()).hexdigest().startswith(expected_sha256): + raise RuntimeError(f"Model has been downloaded but the SHA256 checksum does not not match") + + return download_target + + +def has_hf_hub(necessary=False): + if not _has_hf_hub and necessary: + # if no HF Hub module installed, and it is necessary to continue, raise error + raise RuntimeError( + 'Hugging Face hub model specified but package not installed. Run `pip install huggingface_hub`.') + return _has_hf_hub + + +def download_pretrained_from_hf( + model_id: str, + filename: str = 'open_clip_pytorch_model.bin', + revision=None, + cache_dir: Union[str, None] = None, +): + has_hf_hub(True) + cached_file = hf_hub_download(model_id, filename, revision=revision, cache_dir=cache_dir) + return cached_file + + +def download_pretrained( + cfg: Dict, + force_hf_hub: bool = False, + cache_dir: Union[str, None] = None, +): + target = '' + if not cfg: + return target + + download_url = cfg.get('url', '') + download_hf_hub = cfg.get('hf_hub', '') + if download_hf_hub and force_hf_hub: + # use HF hub even if url exists + download_url = '' + + if download_url: + target = download_pretrained_from_url(download_url, cache_dir=cache_dir) + elif download_hf_hub: + has_hf_hub(True) + # we assume the hf_hub entries in pretrained config combine model_id + filename in + # 'org/model_name/filename.pt' form. To specify just the model id w/o filename and + # use 'open_clip_pytorch_model.bin' default, there must be a trailing slash 'org/model_name/'. + model_id, filename = os.path.split(download_hf_hub) + if filename: + target = download_pretrained_from_hf(model_id, filename=filename, cache_dir=cache_dir) + else: + target = download_pretrained_from_hf(model_id, cache_dir=cache_dir) + + return target diff --git a/src/open_clip/push_to_hf_hub.py b/src/open_clip/push_to_hf_hub.py new file mode 100644 index 0000000000000000000000000000000000000000..23c0631c81dcb43829b7374fac09406ecefcb436 --- /dev/null +++ b/src/open_clip/push_to_hf_hub.py @@ -0,0 +1,243 @@ +import argparse +import json +from pathlib import Path +from tempfile import TemporaryDirectory +from typing import Optional, Tuple + +import torch + +try: + from huggingface_hub import ( + create_repo, + get_hf_file_metadata, + hf_hub_download, + hf_hub_url, + repo_type_and_id_from_hf_id, + upload_folder, + ) + from huggingface_hub.utils import EntryNotFoundError + _has_hf_hub = True +except ImportError: + _has_hf_hub = False + +from .factory import create_model_from_pretrained, get_model_config, get_tokenizer +from .tokenizer import HFTokenizer + + +def save_config_for_hf( + model, + config_path: str, + model_config: Optional[dict] +): + preprocess_cfg = { + 'mean': model.visual.image_mean, + 'std': model.visual.image_std, + } + hf_config = { + 'model_cfg': model_config, + 'preprocess_cfg': preprocess_cfg, + } + + with config_path.open('w') as f: + json.dump(hf_config, f, indent=2) + + +def save_for_hf( + model, + tokenizer: HFTokenizer, + model_config: dict, + save_directory: str, + weights_filename='open_clip_pytorch_model.bin', + config_filename='open_clip_config.json', +): + save_directory = Path(save_directory) + save_directory.mkdir(exist_ok=True, parents=True) + + weights_path = save_directory / weights_filename + torch.save(model.state_dict(), weights_path) + + tokenizer.save_pretrained(save_directory) + + config_path = save_directory / config_filename + save_config_for_hf(model, config_path, model_config=model_config) + + +def push_to_hf_hub( + model, + tokenizer, + model_config: Optional[dict], + repo_id: str, + commit_message: str = 'Add model', + token: Optional[str] = None, + revision: Optional[str] = None, + private: bool = False, + create_pr: bool = False, + model_card: Optional[dict] = None, +): + if not isinstance(tokenizer, HFTokenizer): + # default CLIP tokenizers use https://huggingface.co/openai/clip-vit-large-patch14 + tokenizer = HFTokenizer('openai/clip-vit-large-patch14') + + # Create repo if it doesn't exist yet + repo_url = create_repo(repo_id, token=token, private=private, exist_ok=True) + + # Infer complete repo_id from repo_url + # Can be different from the input `repo_id` if repo_owner was implicit + _, repo_owner, repo_name = repo_type_and_id_from_hf_id(repo_url) + repo_id = f"{repo_owner}/{repo_name}" + + # Check if README file already exist in repo + try: + get_hf_file_metadata(hf_hub_url(repo_id=repo_id, filename="README.md", revision=revision)) + has_readme = True + except EntryNotFoundError: + has_readme = False + + # Dump model and push to Hub + with TemporaryDirectory() as tmpdir: + # Save model weights and config. + save_for_hf( + model, + tokenizer=tokenizer, + model_config=model_config, + save_directory=tmpdir, + ) + + # Add readme if it does not exist + if not has_readme: + model_card = model_card or {} + model_name = repo_id.split('/')[-1] + readme_path = Path(tmpdir) / "README.md" + readme_text = generate_readme(model_card, model_name) + readme_path.write_text(readme_text) + + # Upload model and return + return upload_folder( + repo_id=repo_id, + folder_path=tmpdir, + revision=revision, + create_pr=create_pr, + commit_message=commit_message, + ) + + +def push_pretrained_to_hf_hub( + model_name, + pretrained: str, + repo_id: str, + image_mean: Optional[Tuple[float, ...]] = None, + image_std: Optional[Tuple[float, ...]] = None, + commit_message: str = 'Add model', + token: Optional[str] = None, + revision: Optional[str] = None, + private: bool = False, + create_pr: bool = False, + model_card: Optional[dict] = None, +): + model, preprocess_eval = create_model_from_pretrained( + model_name, + pretrained=pretrained, + image_mean=image_mean, + image_std=image_std, + ) + + model_config = get_model_config(model_name) + assert model_config + + tokenizer = get_tokenizer(model_name) + + push_to_hf_hub( + model=model, + tokenizer=tokenizer, + model_config=model_config, + repo_id=repo_id, + commit_message=commit_message, + token=token, + revision=revision, + private=private, + create_pr=create_pr, + model_card=model_card, + ) + + +def generate_readme(model_card: dict, model_name: str): + readme_text = "---\n" + readme_text += "tags:\n- zero-shot-image-classification\n- clip\n" + readme_text += "library_tag: open_clip\n" + readme_text += f"license: {model_card.get('license', 'mit')}\n" + if 'details' in model_card and 'Dataset' in model_card['details']: + readme_text += 'datasets:\n' + readme_text += f"- {model_card['details']['Dataset'].lower()}\n" + readme_text += "---\n" + readme_text += f"# Model card for {model_name}\n" + if 'description' in model_card: + readme_text += f"\n{model_card['description']}\n" + if 'details' in model_card: + readme_text += f"\n## Model Details\n" + for k, v in model_card['details'].items(): + if isinstance(v, (list, tuple)): + readme_text += f"- **{k}:**\n" + for vi in v: + readme_text += f" - {vi}\n" + elif isinstance(v, dict): + readme_text += f"- **{k}:**\n" + for ki, vi in v.items(): + readme_text += f" - {ki}: {vi}\n" + else: + readme_text += f"- **{k}:** {v}\n" + if 'usage' in model_card: + readme_text += f"\n## Model Usage\n" + readme_text += model_card['usage'] + readme_text += '\n' + + if 'comparison' in model_card: + readme_text += f"\n## Model Comparison\n" + readme_text += model_card['comparison'] + readme_text += '\n' + + if 'citation' in model_card: + readme_text += f"\n## Citation\n" + if not isinstance(model_card['citation'], (list, tuple)): + citations = [model_card['citation']] + else: + citations = model_card['citation'] + for c in citations: + readme_text += f"```bibtex\n{c}\n```\n" + + return readme_text + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Push to Hugging Face Hub") + parser.add_argument( + "--model", type=str, help="Name of the model to use.", + ) + parser.add_argument( + "--pretrained", type=str, + help="Use a pretrained CLIP model weights with the specified tag or file path.", + ) + parser.add_argument( + "--repo-id", type=str, + help="Destination HF Hub repo-id ie 'organization/model_id'.", + ) + parser.add_argument( + '--image-mean', type=float, nargs='+', default=None, metavar='MEAN', + help='Override default image mean value of dataset') + parser.add_argument( + '--image-std', type=float, nargs='+', default=None, metavar='STD', + help='Override default image std deviation of of dataset') + args = parser.parse_args() + + print(f'Saving model {args.model} with pretrained weights {args.pretrained} to Hugging Face Hub at {args.repo_id}') + + # FIXME add support to pass model_card json / template from file via cmd line + + push_pretrained_to_hf_hub( + args.model, + args.pretrained, + args.repo_id, + image_mean=args.image_mean, # override image mean/std if trained w/ non defaults + image_std=args.image_std, + ) + + print(f'{args.model} saved.') diff --git a/src/open_clip/timm_model.py b/src/open_clip/timm_model.py new file mode 100644 index 0000000000000000000000000000000000000000..cf9e79f20ddcbc9877e8eb3f8b4dc87ba947561f --- /dev/null +++ b/src/open_clip/timm_model.py @@ -0,0 +1,239 @@ +""" timm model adapter + +Wraps timm (https://github.com/rwightman/pytorch-image-models) models for use as a vision tower in CLIP model. +""" +import logging +from collections import OrderedDict + +import torch +import torch.nn as nn +from torchvision.ops import roi_align +import torch.nn.functional as F +try: + import timm + from timm.models.layers import Mlp, to_2tuple + try: + # old timm imports < 0.8.1 + from timm.models.layers.attention_pool2d import RotAttentionPool2d + from timm.models.layers.attention_pool2d import AttentionPool2d as AbsAttentionPool2d + except ImportError: + # new timm imports >= 0.8.1 + from timm.layers import RotAttentionPool2d + from timm.layers import AttentionPool2d as AbsAttentionPool2d +except ImportError: + timm = None + +from .utils import freeze_batch_norm_2d + + +class TimmModel(nn.Module): + """ timm model adapter + """ + + def __init__( + self, + model_name, + embed_dim, + image_size=224, + pool='avg', + proj='linear', + proj_bias=False, + drop=0., + drop_path=None, + patch_drop=None, + pretrained=False, + ): + super().__init__() + if timm is None: + raise RuntimeError("Please `pip install timm` to use timm models.") + self.image_size = to_2tuple(image_size) + + # setup kwargs that may not be common across all models + timm_kwargs = {} + if drop_path is not None: + timm_kwargs['drop_path_rate'] = drop_path + if patch_drop is not None: + timm_kwargs['patch_drop_rate'] = patch_drop + + custom_pool = pool in ('abs_attn', 'rot_attn') + if not proj and not custom_pool: + # use network classifier head as projection if no proj specified and no custom pooling used + self.trunk = timm.create_model( + model_name, + num_classes=embed_dim, + global_pool=pool, + pretrained=pretrained, + **timm_kwargs, + ) + prev_chs = embed_dim + else: + self.trunk = timm.create_model( + model_name, + pretrained=pretrained, + **timm_kwargs, + ) + feat_size = self.trunk.default_cfg.get('pool_size', None) + feature_ndim = 1 if not feat_size else 2 + if custom_pool: + assert feature_ndim == 2 + # if attn pooling used, remove both classifier and default pool + self.trunk.reset_classifier(0, global_pool='') + else: + # reset global pool if pool config set, otherwise leave as network default + reset_kwargs = dict(global_pool=pool) if pool else {} + self.trunk.reset_classifier(0, **reset_kwargs) + prev_chs = self.trunk.num_features + + head_layers = OrderedDict() + + # Add custom pooling to head + if pool == 'abs_attn': + head_layers['pool'] = AbsAttentionPool2d(prev_chs, feat_size=feat_size, out_features=embed_dim) + prev_chs = embed_dim + elif pool == 'rot_attn': + head_layers['pool'] = RotAttentionPool2d(prev_chs, out_features=embed_dim) + prev_chs = embed_dim + + # NOTE attention pool ends with a projection layer, so proj should usually be set to '' if such pooling is used + if proj == 'linear': + head_layers['drop'] = nn.Dropout(drop) + head_layers['proj'] = nn.Linear(prev_chs, embed_dim, bias=proj_bias) + elif proj == 'mlp': + head_layers['mlp'] = Mlp(prev_chs, 2 * embed_dim, embed_dim, drop=(drop, 0), bias=(True, proj_bias)) + else: + assert not proj, f'Unknown projection type {proj}.' + + self.head = nn.Sequential(head_layers) + + def lock(self, unlocked_groups=0, freeze_bn_stats=False): + """ lock modules + Args: + unlocked_groups (int): leave last n layer groups unlocked (default: 0) + """ + if not unlocked_groups: + # lock full model + for param in self.trunk.parameters(): + param.requires_grad = False + if freeze_bn_stats: + freeze_batch_norm_2d(self.trunk) + else: + # NOTE: partial freeze requires latest timm (master) branch and is subject to change + try: + # FIXME import here until API stable and in an official release + from timm.models.helpers import group_parameters, group_modules + except ImportError: + raise RuntimeError( + 'Please install latest timm `pip install git+https://github.com/rwightman/pytorch-image-models`') + matcher = self.trunk.group_matcher() + gparams = group_parameters(self.trunk, matcher) + max_layer_id = max(gparams.keys()) + max_layer_id = max_layer_id - unlocked_groups + for group_idx in range(max_layer_id + 1): + group = gparams[group_idx] + for param in group: + self.trunk.get_parameter(param).requires_grad = False + if freeze_bn_stats: + gmodules = group_modules(self.trunk, matcher, reverse=True) + gmodules = {k for k, v in gmodules.items() if v <= max_layer_id} + freeze_batch_norm_2d(self.trunk, gmodules) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + try: + self.trunk.set_grad_checkpointing(enable) + except Exception as e: + logging.warning('grad checkpointing not supported for this timm image tower, continuing without...') + + def forward(self, x): + x = self.trunk(x) + x = self.head(x) + return x + + @staticmethod + def _denormalize_boxes(normed_boxes, x): + h, w = x.shape[-2:] + denormed_boxes = [] + for boxes in normed_boxes: + new_boxes = boxes.clone() # FIXME: do not change the value in normed_boxes! + new_boxes[:, [0, 2]] *= w + new_boxes[:, [1, 3]] *= h + denormed_boxes.append(new_boxes) + return denormed_boxes + + def _extract_roi_features_v1(self, x, normed_boxes, **kwargs): + h, w = x.shape[-2:] + x = self.trunk.forward_features(x) + h_f, w_f = x.shape[-2:] + tar_h = (self.image_size[0] * h_f) // h + tar_w = (self.image_size[1] * w_f) // w + x = roi_align(x, self._denormalize_boxes(normed_boxes, x), (tar_h, tar_w), + 1.0, -1, True) + + x = self.trunk.forward_head(x) + x = self.head(x) + + return x + + def encode_dense(self, x, **kwargs): + x = self.trunk.forward_features(x) + x = self.dense_trunk_head(x) + x = self.head(x) + x = x.permute(0, 3, 1, 2) + + return x + + def dense_trunk_head(self, x): + x = self.trunk.head.norm(x) + x = x.permute(0, 2, 3, 1) + x = self.trunk.head.drop(x) + # x = x.permute(0, 3, 1, 2) + + return x + + def mask_pool(self, image, masks): + feature_map = self.encode_dense(image) + feature_map = F.normalize(feature_map, dim=1) # remember to normalize! + feature_map = feature_map.flatten(-2, -1) # bs, c, h*w + num_masks_per_image = [len(masks_per_image) for masks_per_image in masks] + masks = torch.cat(masks).float().flatten(-2, -1) # bs, h*w + feature_map = torch.repeat_interleave( + feature_map, torch.tensor(num_masks_per_image, device=feature_map.device), dim=0) + features = (feature_map * masks[:, None]).sum(-1) / (masks.sum(1, keepdim=True) + 1e-12) + + return features + + def extract_roi_features(self, x, normed_boxes, extract_type='v1'): + assert extract_type == "v1" + if extract_type == 'v1': + return self._extract_roi_features_v1(x, normed_boxes) + else: + assert extract_type == 'v2' + return self._extract_roi_features_v2(x, normed_boxes) + + def _extract_roi_features_v2(self, x, normed_boxes, **kwargs): + x = self.encode_dense(x) + x = F.normalize(x, dim=1) # remember to normalize! + + roi_feats = roi_align(x, self._denormalize_boxes(normed_boxes, x), (1, 1), + 1.0, -1, True)[..., 0, 0] + return roi_feats + + def encode_rois_and_image(self, x, normed_boxes, **kwargs): + h, w = x.shape[-2:] + x = self.trunk.forward_features(x) + h_f, w_f = x.shape[-2:] + tar_h = (self.image_size[0] * h_f) // h + tar_w = (self.image_size[1] * w_f) // w + x_image = x + x_rois = roi_align(x, self._denormalize_boxes(normed_boxes, x), (tar_h, tar_w), + 1.0, -1, True) + + x_rois = self.trunk.forward_head(x_rois) + x_rois = self.head(x_rois) + x_rois = F.normalize(x_rois, dim=-1) + + x_image = self.trunk.forward_head(x_image) + x_image = self.head(x_image) + x_image = F.normalize(x_image, dim=-1) + + return x_rois, x_image diff --git a/src/open_clip/tiny_clip/__init__.py b/src/open_clip/tiny_clip/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..310ee0047ad9767ba8d3ce1928f9c1a695fbf807 --- /dev/null +++ b/src/open_clip/tiny_clip/__init__.py @@ -0,0 +1,11 @@ +from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD +from .factory import list_models, create_model, create_model_and_transforms, get_tokenizer, add_model_config, \ + load_model, load_exp +from .loss import ClipLoss +from .model import CLIP, CLIPTextCfg, CLIPVisionCfg, convert_weights_to_fp16, trace_model +from .openai import load_openai_model, list_openai_models +from .pretrained import list_pretrained, list_pretrained_tag_models, list_pretrained_model_tags,\ + get_pretrained_url, download_pretrained_from_url, is_pretrained_cfg, get_pretrained_cfg, download_pretrained +from .tokenizer import SimpleTokenizer, tokenize +from .transform import image_transform +from .l0module import L0Module diff --git a/src/open_clip/tiny_clip/bpe_simple_vocab_16e6.txt.gz b/src/open_clip/tiny_clip/bpe_simple_vocab_16e6.txt.gz new file mode 100644 index 0000000000000000000000000000000000000000..36a15856e00a06a9fbed8cdd34d2393fea4a3113 --- /dev/null +++ b/src/open_clip/tiny_clip/bpe_simple_vocab_16e6.txt.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a +size 1356917 diff --git a/src/open_clip/tiny_clip/clip_soft_loss.py b/src/open_clip/tiny_clip/clip_soft_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..dc036027ec98bebe18e1a2f84940c373b3bc863f --- /dev/null +++ b/src/open_clip/tiny_clip/clip_soft_loss.py @@ -0,0 +1,88 @@ +import torch +import torch.distributed.nn +from torch import distributed as dist, nn as nn +from torch.nn import functional as F +from open_clip.loss import gather_features, gather_feature +from contextlib import nullcontext +import numpy as np + + +class ClipSoftLoss(nn.Module): + def __init__( + self, + local_loss=False, + gather_with_grad=False, + cache_labels=False, + rank=None, + world_size=None, + use_horovod=False, + ): + super().__init__() + self.local_loss = local_loss + self.gather_with_grad = gather_with_grad + if rank is None: + assert world_size is None + rank, world_size = dist.get_rank(), dist.get_world_size() + self.rank = rank + self.world_size = world_size + self.use_horovod = use_horovod + assert self.local_loss + + # cache state + self.feat_buffer = dict() + + def compute_sim(self, image_features, text_features): + all_image_features = self.gather_feature(image_features) + all_text_features = self.gather_feature(text_features) + + # calculate logits + # with torch.cuda.amp.autocast(enabled=False): + with nullcontext(): + logits_per_image = image_features @ all_text_features.T + logits_per_text = text_features @ all_image_features.T + return logits_per_image, logits_per_text + + def gather_feature(self, feat): + feat_id = id(feat) + if feat_id not in self.feat_buffer: + args = (self.local_loss, self.gather_with_grad, + self.rank, self.world_size, self.use_horovod) + all_feat = gather_feature(feat, *args) + self.feat_buffer[feat_id] = all_feat + return self.feat_buffer[feat_id] + + def forward(self, + image_features, text_features, logit_scale, + teacher_image_features, teacher_text_features, teacher_logit_scale, + average_two_losses=True, + labels=None, + ): + # calculated ground-truth and cache if enabled + logits_per_image, logits_per_text = self.compute_sim( + image_features, text_features) + teacher_logits_per_image, teacher_logits_per_text = self.compute_sim( + teacher_image_features, teacher_text_features) + + self.feat_buffer.clear() + + # with torch.cuda.amp.autocast(enabled=False): + with nullcontext(): + logits_per_image = logit_scale * logits_per_image + logits_per_text = logit_scale * logits_per_text + teacher_logits_per_image = teacher_logit_scale * teacher_logits_per_image + teacher_logits_per_text = teacher_logit_scale * teacher_logits_per_text + + def single_loss_fn(logits, teacher_logits): + teacher_probs = F.softmax(teacher_logits, -1) + return F.cross_entropy(logits, teacher_probs) + + if average_two_losses: + total_loss = (single_loss_fn(logits_per_image, teacher_logits_per_image) + + single_loss_fn(logits_per_text, teacher_logits_per_text)) / 2 + return total_loss + else: + img2text_loss = single_loss_fn( + logits_per_image, teacher_logits_per_image) + text2img_loss = single_loss_fn( + logits_per_text, teacher_logits_per_text) + return img2text_loss, text2img_loss diff --git a/src/open_clip/tiny_clip/constants.py b/src/open_clip/tiny_clip/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..a670bb3fab442baeb9af53b91c312e6982af57ee --- /dev/null +++ b/src/open_clip/tiny_clip/constants.py @@ -0,0 +1,2 @@ +OPENAI_DATASET_MEAN = (0.48145466, 0.4578275, 0.40821073) +OPENAI_DATASET_STD = (0.26862954, 0.26130258, 0.27577711) diff --git a/src/open_clip/tiny_clip/factory.py b/src/open_clip/tiny_clip/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..f08fba9594f02f4c0e94a0e704b1c44b6562e3df --- /dev/null +++ b/src/open_clip/tiny_clip/factory.py @@ -0,0 +1,286 @@ +import json +import logging +import os +import pathlib +import re +from copy import deepcopy +from pathlib import Path +from typing import Optional, Tuple + +import torch + +from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD +from .model import CLIP, convert_weights_to_fp16, resize_pos_embed +from .model import load_pruned_model, prune_model +from .pretrained import get_pretrained_cfg, download_pretrained + +# Optional imports - these may not be available in all environments +try: + from .openai import load_openai_model +except ImportError: + load_openai_model = None + +try: + from .transform import image_transform +except ImportError: + # Simple placeholder for image_transform + def image_transform(image_size, is_train=True, mean=None, std=None, val_keep_ratio=True): + from torchvision import transforms + if mean is None: + mean = OPENAI_DATASET_MEAN + if std is None: + std = OPENAI_DATASET_STD + if is_train: + return transforms.Compose([ + transforms.RandomResizedCrop(image_size), + transforms.RandomHorizontalFlip(), + transforms.ToTensor(), + transforms.Normalize(mean=mean, std=std) + ]) + else: + return transforms.Compose([ + transforms.Resize(image_size), + transforms.CenterCrop(image_size), + transforms.ToTensor(), + transforms.Normalize(mean=mean, std=std) + ]) + +try: + from .tokenizer import HFTokenizer, tokenize +except ImportError: + # Placeholder tokenizers + class HFTokenizer: + def __init__(self, *args, **kwargs): + raise NotImplementedError("HFTokenizer requires additional dependencies") + + def tokenize(*args, **kwargs): + raise NotImplementedError("tokenize requires additional dependencies") + +HF_HUB_PREFIX = 'hf-hub:' +_MODEL_CONFIG_PATHS = [Path(__file__).parent / f"model_configs/"] +# directory (model_name: config) of model architecture configs +_MODEL_CONFIGS = {} + + +def _natural_key(string_): + return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] + + +def _rescan_model_configs(): + global _MODEL_CONFIGS + + config_ext = ('.json',) + config_files = [] + for config_path in _MODEL_CONFIG_PATHS: + if config_path.is_file() and config_path.suffix in config_ext: + config_files.append(config_path) + elif config_path.is_dir(): + for ext in config_ext: + config_files.extend(config_path.glob(f'*{ext}')) + + for cf in config_files: + with open(cf, 'r') as f: + model_cfg = json.load(f) + if all(a in model_cfg for a in ('embed_dim', 'vision_cfg', 'text_cfg')): + _MODEL_CONFIGS[cf.stem] = model_cfg + + _MODEL_CONFIGS = {k: v for k, v in sorted( + _MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0]))} + + +_rescan_model_configs() # initial populate of model config registry + + +def get_model_config(model_name): + if model_name in _MODEL_CONFIGS: + return deepcopy(_MODEL_CONFIGS[model_name]) + else: + return None + + +def get_tokenizer(model_name): + if model_name.startswith(HF_HUB_PREFIX): + tokenizer = HFTokenizer(model_name[len(HF_HUB_PREFIX):]) + else: + config = get_model_config(model_name) + tokenizer = HFTokenizer( + config['text_cfg']['hf_tokenizer_name']) if 'hf_tokenizer_name' in config['text_cfg'] else tokenize + return tokenizer + + +def load_state_dict(checkpoint_path: str, map_location='cpu'): + checkpoint = torch.load(checkpoint_path, map_location=map_location) + if isinstance(checkpoint, dict) and 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + else: + state_dict = checkpoint + if next(iter(state_dict.items()))[0].startswith('module'): + state_dict = {k[7:]: v for k, v in state_dict.items()} + return state_dict + + +def load_checkpoint(model, checkpoint_path, strict=True): + state_dict = load_state_dict(checkpoint_path) + resize_pos_embed(state_dict, model) + incompatible_keys = model.load_state_dict(state_dict, strict=strict) + return incompatible_keys + + +def load_pruned_checkpoint(model, checkpoint_path, strict=True): + state_dict = load_state_dict(checkpoint_path) + resize_pos_embed(state_dict, model) + incompatible_keys = load_pruned_model(model, state_dict, strict=strict) + return incompatible_keys + + +def create_model( + model_name: str, + pretrained: str = '', + precision: str = 'fp32', + device: torch.device = torch.device('cpu'), + jit: bool = False, + force_quick_gelu: bool = False, + pretrained_image: bool = False, + cache_dir: Optional[str] = None, + args=None, +): + # for callers using old naming with / in ViT names + model_name = model_name.replace('/', '-') + if pretrained.lower() == 'openai': + if load_openai_model is None: + raise RuntimeError("load_openai_model is not available. Please install required dependencies.") + logging.info(f'Loading pretrained {model_name} from OpenAI.') + model = load_openai_model( + model_name, device=device, jit=jit, cache_dir=cache_dir) + # See https://discuss.pytorch.org/t/valueerror-attemting-to-unscale-fp16-gradients/81372 + if precision == "amp" or precision == "fp32": + model = model.float() + else: + if model_name in _MODEL_CONFIGS: + logging.info(f'Loading {model_name} model config.') + model_cfg = deepcopy(_MODEL_CONFIGS[model_name]) + else: + logging.error( + f'Model config for {model_name} not found; available models {list_models()}.') + raise RuntimeError(f'Model config for {model_name} not found.') + + if force_quick_gelu: + # override for use of QuickGELU on non-OpenAI transformer models + model_cfg["quick_gelu"] = True + + if pretrained_image: + if 'timm_model_name' in model_cfg.get('vision_cfg', {}): + # pretrained weight loading for timm models set via vision_cfg + model_cfg['vision_cfg']['timm_model_pretrained'] = True + else: + assert False, 'pretrained image towers currently only supported for timm models' + if args is not None: + model_cfg['mask_image'] = getattr(args, 'prune_image', False) + model_cfg['mask_text'] = getattr(args, 'prune_text', False) + model_cfg['sparsity_warmup'] = getattr( + args, 'sparsity_warmup', 1000) + model_cfg['start_sparsity'] = getattr(args, 'start_sparsity', 0.0) + model_cfg['sparsity'] = getattr(args, 'target_sparsity', 0.25) + logging.info( + f'model sparsity varies from {model_cfg["start_sparsity"]} to {model_cfg["sparsity"]}, sparsity warmup steps: {model_cfg["sparsity_warmup"]}') + + logging.info(str(model_cfg)) + auto_weight_inheritance = model_cfg.get('mask_image', False) or \ + model_cfg.get('mask_text', False) + + model = CLIP(**model_cfg) + pretrained_cfg = {} + if pretrained: + checkpoint_path = '' + pretrained_cfg = get_pretrained_cfg(model_name, pretrained) + if pretrained_cfg: + checkpoint_path = download_pretrained( + pretrained_cfg, cache_dir=cache_dir) + elif os.path.exists(pretrained): + checkpoint_path = pretrained + + if checkpoint_path: + logging.info( + f'Loading pretrained {model_name} weights ({pretrained}).') + if not auto_weight_inheritance: + load_checkpoint(model, checkpoint_path) + else: + load_pruned_checkpoint(model, checkpoint_path) + model = prune_model(model) + else: + logging.warning( + f'Pretrained weights ({pretrained}) not found for model {model_name}.') + raise RuntimeError( + f'Pretrained weights ({pretrained}) not found for model {model_name}.') + + model.to(device=device) + if precision == "fp16": + assert device.type != 'cpu' + convert_weights_to_fp16(model) + + # set image / mean metadata from pretrained_cfg if available, or use default + if 'davit' in model_name.lower(): + pretrained_cfg['mean'] = [0.485, 0.456, 0.406] + pretrained_cfg['std'] = [0.229, 0.224, 0.225] + model.visual.image_mean = pretrained_cfg.get( + 'mean', None) or OPENAI_DATASET_MEAN + model.visual.image_std = pretrained_cfg.get( + 'std', None) or OPENAI_DATASET_STD + + if jit: + model = torch.jit.script(model) + + return model + + +def create_model_and_transforms( + model_name: str, + pretrained: str = '', + precision: str = 'fp32', + device: torch.device = torch.device('cpu'), + jit: bool = False, + force_quick_gelu: bool = False, + pretrained_image: bool = False, + image_mean: Optional[Tuple[float, ...]] = None, + image_std: Optional[Tuple[float, ...]] = None, + cache_dir: Optional[str] = None, + args=None, +): + model = create_model( + model_name, pretrained, precision, device, jit, + force_quick_gelu=force_quick_gelu, + pretrained_image=pretrained_image, + cache_dir=cache_dir, + args=args) + + image_mean = image_mean or getattr(model.visual, 'image_mean', None) + image_std = image_std or getattr(model.visual, 'image_std', None) + val_keep_ratio = 'davit' not in model_name.lower() + preprocess_train = image_transform( + model.visual.image_size, is_train=True, mean=image_mean, std=image_std) + preprocess_val = image_transform(model.visual.image_size, is_train=False, + mean=image_mean, std=image_std, val_keep_ratio=val_keep_ratio) + return model, preprocess_train, preprocess_val + + +def list_models(): + """ enumerate available model architectures based on config files """ + return list(_MODEL_CONFIGS.keys()) + + +def add_model_config(path): + """ add model config path or file and update registry """ + if not isinstance(path, Path): + path = Path(path) + _MODEL_CONFIG_PATHS.append(path) + _rescan_model_configs() + + +def load_exp(name, device='cpu'): + assert '@' in name + teacher_model_name, teacher_pretrained = name.split('@') + return create_model_and_transforms(teacher_model_name, pretrained=teacher_pretrained) + + +def load_model(name, device='cpu'): + return load_exp(name, device)[0] diff --git a/src/open_clip/tiny_clip/imagenet_zeroshot_data.py b/src/open_clip/tiny_clip/imagenet_zeroshot_data.py new file mode 100644 index 0000000000000000000000000000000000000000..2ffa6af96150bdd146ac3e395e60f90fbed8eed7 --- /dev/null +++ b/src/open_clip/tiny_clip/imagenet_zeroshot_data.py @@ -0,0 +1,251 @@ + + +imagenet_classnames = ["tench", "goldfish", "great white shark", "tiger shark", "hammerhead shark", "electric ray", + "stingray", "rooster", "hen", "ostrich", "brambling", "goldfinch", "house finch", "junco", + "indigo bunting", "American robin", "bulbul", "jay", "magpie", "chickadee", "American dipper", + "kite (bird of prey)", "bald eagle", "vulture", "great grey owl", "fire salamander", + "smooth newt", "newt", "spotted salamander", "axolotl", "American bullfrog", "tree frog", + "tailed frog", "loggerhead sea turtle", "leatherback sea turtle", "mud turtle", "terrapin", + "box turtle", "banded gecko", "green iguana", "Carolina anole", + "desert grassland whiptail lizard", "agama", "frilled-necked lizard", "alligator lizard", + "Gila monster", "European green lizard", "chameleon", "Komodo dragon", "Nile crocodile", + "American alligator", "triceratops", "worm snake", "ring-necked snake", + "eastern hog-nosed snake", "smooth green snake", "kingsnake", "garter snake", "water snake", + "vine snake", "night snake", "boa constrictor", "African rock python", "Indian cobra", + "green mamba", "sea snake", "Saharan horned viper", "eastern diamondback rattlesnake", + "sidewinder rattlesnake", "trilobite", "harvestman", "scorpion", "yellow garden spider", + "barn spider", "European garden spider", "southern black widow", "tarantula", "wolf spider", + "tick", "centipede", "black grouse", "ptarmigan", "ruffed grouse", "prairie grouse", "peafowl", + "quail", "partridge", "african grey parrot", "macaw", "sulphur-crested cockatoo", "lorikeet", + "coucal", "bee eater", "hornbill", "hummingbird", "jacamar", "toucan", "duck", + "red-breasted merganser", "goose", "black swan", "tusker", "echidna", "platypus", "wallaby", + "koala", "wombat", "jellyfish", "sea anemone", "brain coral", "flatworm", "nematode", "conch", + "snail", "slug", "sea slug", "chiton", "chambered nautilus", "Dungeness crab", "rock crab", + "fiddler crab", "red king crab", "American lobster", "spiny lobster", "crayfish", "hermit crab", + "isopod", "white stork", "black stork", "spoonbill", "flamingo", "little blue heron", + "great egret", "bittern bird", "crane bird", "limpkin", "common gallinule", "American coot", + "bustard", "ruddy turnstone", "dunlin", "common redshank", "dowitcher", "oystercatcher", + "pelican", "king penguin", "albatross", "grey whale", "killer whale", "dugong", "sea lion", + "Chihuahua", "Japanese Chin", "Maltese", "Pekingese", "Shih Tzu", "King Charles Spaniel", + "Papillon", "toy terrier", "Rhodesian Ridgeback", "Afghan Hound", "Basset Hound", "Beagle", + "Bloodhound", "Bluetick Coonhound", "Black and Tan Coonhound", "Treeing Walker Coonhound", + "English foxhound", "Redbone Coonhound", "borzoi", "Irish Wolfhound", "Italian Greyhound", + "Whippet", "Ibizan Hound", "Norwegian Elkhound", "Otterhound", "Saluki", "Scottish Deerhound", + "Weimaraner", "Staffordshire Bull Terrier", "American Staffordshire Terrier", + "Bedlington Terrier", "Border Terrier", "Kerry Blue Terrier", "Irish Terrier", + "Norfolk Terrier", "Norwich Terrier", "Yorkshire Terrier", "Wire Fox Terrier", + "Lakeland Terrier", "Sealyham Terrier", "Airedale Terrier", "Cairn Terrier", + "Australian Terrier", "Dandie Dinmont Terrier", "Boston Terrier", "Miniature Schnauzer", + "Giant Schnauzer", "Standard Schnauzer", "Scottish Terrier", "Tibetan Terrier", + "Australian Silky Terrier", "Soft-coated Wheaten Terrier", "West Highland White Terrier", + "Lhasa Apso", "Flat-Coated Retriever", "Curly-coated Retriever", "Golden Retriever", + "Labrador Retriever", "Chesapeake Bay Retriever", "German Shorthaired Pointer", "Vizsla", + "English Setter", "Irish Setter", "Gordon Setter", "Brittany dog", "Clumber Spaniel", + "English Springer Spaniel", "Welsh Springer Spaniel", "Cocker Spaniel", "Sussex Spaniel", + "Irish Water Spaniel", "Kuvasz", "Schipperke", "Groenendael dog", "Malinois", "Briard", + "Australian Kelpie", "Komondor", "Old English Sheepdog", "Shetland Sheepdog", "collie", + "Border Collie", "Bouvier des Flandres dog", "Rottweiler", "German Shepherd Dog", "Dobermann", + "Miniature Pinscher", "Greater Swiss Mountain Dog", "Bernese Mountain Dog", + "Appenzeller Sennenhund", "Entlebucher Sennenhund", "Boxer", "Bullmastiff", "Tibetan Mastiff", + "French Bulldog", "Great Dane", "St. Bernard", "husky", "Alaskan Malamute", "Siberian Husky", + "Dalmatian", "Affenpinscher", "Basenji", "pug", "Leonberger", "Newfoundland dog", + "Great Pyrenees dog", "Samoyed", "Pomeranian", "Chow Chow", "Keeshond", "brussels griffon", + "Pembroke Welsh Corgi", "Cardigan Welsh Corgi", "Toy Poodle", "Miniature Poodle", + "Standard Poodle", "Mexican hairless dog (xoloitzcuintli)", "grey wolf", "Alaskan tundra wolf", + "red wolf or maned wolf", "coyote", "dingo", "dhole", "African wild dog", "hyena", "red fox", + "kit fox", "Arctic fox", "grey fox", "tabby cat", "tiger cat", "Persian cat", "Siamese cat", + "Egyptian Mau", "cougar", "lynx", "leopard", "snow leopard", "jaguar", "lion", "tiger", + "cheetah", "brown bear", "American black bear", "polar bear", "sloth bear", "mongoose", + "meerkat", "tiger beetle", "ladybug", "ground beetle", "longhorn beetle", "leaf beetle", + "dung beetle", "rhinoceros beetle", "weevil", "fly", "bee", "ant", "grasshopper", + "cricket insect", "stick insect", "cockroach", "praying mantis", "cicada", "leafhopper", + "lacewing", "dragonfly", "damselfly", "red admiral butterfly", "ringlet butterfly", + "monarch butterfly", "small white butterfly", "sulphur butterfly", "gossamer-winged butterfly", + "starfish", "sea urchin", "sea cucumber", "cottontail rabbit", "hare", "Angora rabbit", + "hamster", "porcupine", "fox squirrel", "marmot", "beaver", "guinea pig", "common sorrel horse", + "zebra", "pig", "wild boar", "warthog", "hippopotamus", "ox", "water buffalo", "bison", + "ram (adult male sheep)", "bighorn sheep", "Alpine ibex", "hartebeest", "impala (antelope)", + "gazelle", "arabian camel", "llama", "weasel", "mink", "European polecat", + "black-footed ferret", "otter", "skunk", "badger", "armadillo", "three-toed sloth", "orangutan", + "gorilla", "chimpanzee", "gibbon", "siamang", "guenon", "patas monkey", "baboon", "macaque", + "langur", "black-and-white colobus", "proboscis monkey", "marmoset", "white-headed capuchin", + "howler monkey", "titi monkey", "Geoffroy's spider monkey", "common squirrel monkey", + "ring-tailed lemur", "indri", "Asian elephant", "African bush elephant", "red panda", + "giant panda", "snoek fish", "eel", "silver salmon", "rock beauty fish", "clownfish", + "sturgeon", "gar fish", "lionfish", "pufferfish", "abacus", "abaya", "academic gown", + "accordion", "acoustic guitar", "aircraft carrier", "airliner", "airship", "altar", "ambulance", + "amphibious vehicle", "analog clock", "apiary", "apron", "trash can", "assault rifle", + "backpack", "bakery", "balance beam", "balloon", "ballpoint pen", "Band-Aid", "banjo", + "baluster / handrail", "barbell", "barber chair", "barbershop", "barn", "barometer", "barrel", + "wheelbarrow", "baseball", "basketball", "bassinet", "bassoon", "swimming cap", "bath towel", + "bathtub", "station wagon", "lighthouse", "beaker", "military hat (bearskin or shako)", + "beer bottle", "beer glass", "bell tower", "baby bib", "tandem bicycle", "bikini", + "ring binder", "binoculars", "birdhouse", "boathouse", "bobsleigh", "bolo tie", "poke bonnet", + "bookcase", "bookstore", "bottle cap", "hunting bow", "bow tie", "brass memorial plaque", "bra", + "breakwater", "breastplate", "broom", "bucket", "buckle", "bulletproof vest", + "high-speed train", "butcher shop", "taxicab", "cauldron", "candle", "cannon", "canoe", + "can opener", "cardigan", "car mirror", "carousel", "tool kit", "cardboard box / carton", + "car wheel", "automated teller machine", "cassette", "cassette player", "castle", "catamaran", + "CD player", "cello", "mobile phone", "chain", "chain-link fence", "chain mail", "chainsaw", + "storage chest", "chiffonier", "bell or wind chime", "china cabinet", "Christmas stocking", + "church", "movie theater", "cleaver", "cliff dwelling", "cloak", "clogs", "cocktail shaker", + "coffee mug", "coffeemaker", "spiral or coil", "combination lock", "computer keyboard", + "candy store", "container ship", "convertible", "corkscrew", "cornet", "cowboy boot", + "cowboy hat", "cradle", "construction crane", "crash helmet", "crate", "infant bed", + "Crock Pot", "croquet ball", "crutch", "cuirass", "dam", "desk", "desktop computer", + "rotary dial telephone", "diaper", "digital clock", "digital watch", "dining table", + "dishcloth", "dishwasher", "disc brake", "dock", "dog sled", "dome", "doormat", "drilling rig", + "drum", "drumstick", "dumbbell", "Dutch oven", "electric fan", "electric guitar", + "electric locomotive", "entertainment center", "envelope", "espresso machine", "face powder", + "feather boa", "filing cabinet", "fireboat", "fire truck", "fire screen", "flagpole", "flute", + "folding chair", "football helmet", "forklift", "fountain", "fountain pen", "four-poster bed", + "freight car", "French horn", "frying pan", "fur coat", "garbage truck", + "gas mask or respirator", "gas pump", "goblet", "go-kart", "golf ball", "golf cart", "gondola", + "gong", "gown", "grand piano", "greenhouse", "radiator grille", "grocery store", "guillotine", + "hair clip", "hair spray", "half-track", "hammer", "hamper", "hair dryer", "hand-held computer", + "handkerchief", "hard disk drive", "harmonica", "harp", "combine harvester", "hatchet", + "holster", "home theater", "honeycomb", "hook", "hoop skirt", "gymnastic horizontal bar", + "horse-drawn vehicle", "hourglass", "iPod", "clothes iron", "carved pumpkin", "jeans", "jeep", + "T-shirt", "jigsaw puzzle", "rickshaw", "joystick", "kimono", "knee pad", "knot", "lab coat", + "ladle", "lampshade", "laptop computer", "lawn mower", "lens cap", "letter opener", "library", + "lifeboat", "lighter", "limousine", "ocean liner", "lipstick", "slip-on shoe", "lotion", + "music speaker", "loupe magnifying glass", "sawmill", "magnetic compass", "messenger bag", + "mailbox", "tights", "one-piece bathing suit", "manhole cover", "maraca", "marimba", "mask", + "matchstick", "maypole", "maze", "measuring cup", "medicine cabinet", "megalith", "microphone", + "microwave oven", "military uniform", "milk can", "minibus", "miniskirt", "minivan", "missile", + "mitten", "mixing bowl", "mobile home", "ford model t", "modem", "monastery", "monitor", + "moped", "mortar and pestle", "graduation cap", "mosque", "mosquito net", "vespa", + "mountain bike", "tent", "computer mouse", "mousetrap", "moving van", "muzzle", "metal nail", + "neck brace", "necklace", "baby pacifier", "notebook computer", "obelisk", "oboe", "ocarina", + "odometer", "oil filter", "pipe organ", "oscilloscope", "overskirt", "bullock cart", + "oxygen mask", "product packet / packaging", "paddle", "paddle wheel", "padlock", "paintbrush", + "pajamas", "palace", "pan flute", "paper towel", "parachute", "parallel bars", "park bench", + "parking meter", "railroad car", "patio", "payphone", "pedestal", "pencil case", + "pencil sharpener", "perfume", "Petri dish", "photocopier", "plectrum", "Pickelhaube", + "picket fence", "pickup truck", "pier", "piggy bank", "pill bottle", "pillow", "ping-pong ball", + "pinwheel", "pirate ship", "drink pitcher", "block plane", "planetarium", "plastic bag", + "plate rack", "farm plow", "plunger", "Polaroid camera", "pole", "police van", "poncho", + "pool table", "soda bottle", "plant pot", "potter's wheel", "power drill", "prayer rug", + "printer", "prison", "missile", "projector", "hockey puck", "punching bag", "purse", "quill", + "quilt", "race car", "racket", "radiator", "radio", "radio telescope", "rain barrel", + "recreational vehicle", "fishing casting reel", "reflex camera", "refrigerator", + "remote control", "restaurant", "revolver", "rifle", "rocking chair", "rotisserie", "eraser", + "rugby ball", "ruler measuring stick", "sneaker", "safe", "safety pin", "salt shaker", "sandal", + "sarong", "saxophone", "scabbard", "weighing scale", "school bus", "schooner", "scoreboard", + "CRT monitor", "screw", "screwdriver", "seat belt", "sewing machine", "shield", "shoe store", + "shoji screen / room divider", "shopping basket", "shopping cart", "shovel", "shower cap", + "shower curtain", "ski", "balaclava ski mask", "sleeping bag", "slide rule", "sliding door", + "slot machine", "snorkel", "snowmobile", "snowplow", "soap dispenser", "soccer ball", "sock", + "solar thermal collector", "sombrero", "soup bowl", "keyboard space bar", "space heater", + "space shuttle", "spatula", "motorboat", "spider web", "spindle", "sports car", "spotlight", + "stage", "steam locomotive", "through arch bridge", "steel drum", "stethoscope", "scarf", + "stone wall", "stopwatch", "stove", "strainer", "tram", "stretcher", "couch", "stupa", + "submarine", "suit", "sundial", "sunglasses", "sunglasses", "sunscreen", "suspension bridge", + "mop", "sweatshirt", "swim trunks / shorts", "swing", "electrical switch", "syringe", + "table lamp", "tank", "tape player", "teapot", "teddy bear", "television", "tennis ball", + "thatched roof", "front curtain", "thimble", "threshing machine", "throne", "tile roof", + "toaster", "tobacco shop", "toilet seat", "torch", "totem pole", "tow truck", "toy store", + "tractor", "semi-trailer truck", "tray", "trench coat", "tricycle", "trimaran", "tripod", + "triumphal arch", "trolleybus", "trombone", "hot tub", "turnstile", "typewriter keyboard", + "umbrella", "unicycle", "upright piano", "vacuum cleaner", "vase", "vaulted or arched ceiling", + "velvet fabric", "vending machine", "vestment", "viaduct", "violin", "volleyball", + "waffle iron", "wall clock", "wallet", "wardrobe", "military aircraft", "sink", + "washing machine", "water bottle", "water jug", "water tower", "whiskey jug", "whistle", + "hair wig", "window screen", "window shade", "Windsor tie", "wine bottle", "airplane wing", + "wok", "wooden spoon", "wool", "split-rail fence", "shipwreck", "sailboat", "yurt", "website", + "comic book", "crossword", "traffic or street sign", "traffic light", "dust jacket", "menu", + "plate", "guacamole", "consomme", "hot pot", "trifle", "ice cream", "popsicle", "baguette", + "bagel", "pretzel", "cheeseburger", "hot dog", "mashed potatoes", "cabbage", "broccoli", + "cauliflower", "zucchini", "spaghetti squash", "acorn squash", "butternut squash", "cucumber", + "artichoke", "bell pepper", "cardoon", "mushroom", "Granny Smith apple", "strawberry", "orange", + "lemon", "fig", "pineapple", "banana", "jackfruit", "cherimoya (custard apple)", "pomegranate", + "hay", "carbonara", "chocolate syrup", "dough", "meatloaf", "pizza", "pot pie", "burrito", + "red wine", "espresso", "tea cup", "eggnog", "mountain", "bubble", "cliff", "coral reef", + "geyser", "lakeshore", "promontory", "sandbar", "beach", "valley", "volcano", "baseball player", + "bridegroom", "scuba diver", "rapeseed", "daisy", "yellow lady's slipper", "corn", "acorn", + "rose hip", "horse chestnut seed", "coral fungus", "agaric", "gyromitra", "stinkhorn mushroom", + "earth star fungus", "hen of the woods mushroom", "bolete", "corn cob", "toilet paper"] + + +openai_imagenet_template = [ + lambda c: f'a bad photo of a {c}.', + lambda c: f'a photo of many {c}.', + lambda c: f'a sculpture of a {c}.', + lambda c: f'a photo of the hard to see {c}.', + lambda c: f'a low resolution photo of the {c}.', + lambda c: f'a rendering of a {c}.', + lambda c: f'graffiti of a {c}.', + lambda c: f'a bad photo of the {c}.', + lambda c: f'a cropped photo of the {c}.', + lambda c: f'a tattoo of a {c}.', + lambda c: f'the embroidered {c}.', + lambda c: f'a photo of a hard to see {c}.', + lambda c: f'a bright photo of a {c}.', + lambda c: f'a photo of a clean {c}.', + lambda c: f'a photo of a dirty {c}.', + lambda c: f'a dark photo of the {c}.', + lambda c: f'a drawing of a {c}.', + lambda c: f'a photo of my {c}.', + lambda c: f'the plastic {c}.', + lambda c: f'a photo of the cool {c}.', + lambda c: f'a close-up photo of a {c}.', + lambda c: f'a black and white photo of the {c}.', + lambda c: f'a painting of the {c}.', + lambda c: f'a painting of a {c}.', + lambda c: f'a pixelated photo of the {c}.', + lambda c: f'a sculpture of the {c}.', + lambda c: f'a bright photo of the {c}.', + lambda c: f'a cropped photo of a {c}.', + lambda c: f'a plastic {c}.', + lambda c: f'a photo of the dirty {c}.', + lambda c: f'a jpeg corrupted photo of a {c}.', + lambda c: f'a blurry photo of the {c}.', + lambda c: f'a photo of the {c}.', + lambda c: f'a good photo of the {c}.', + lambda c: f'a rendering of the {c}.', + lambda c: f'a {c} in a video game.', + lambda c: f'a photo of one {c}.', + lambda c: f'a doodle of a {c}.', + lambda c: f'a close-up photo of the {c}.', + lambda c: f'a photo of a {c}.', + lambda c: f'the origami {c}.', + lambda c: f'the {c} in a video game.', + lambda c: f'a sketch of a {c}.', + lambda c: f'a doodle of the {c}.', + lambda c: f'a origami {c}.', + lambda c: f'a low resolution photo of a {c}.', + lambda c: f'the toy {c}.', + lambda c: f'a rendition of the {c}.', + lambda c: f'a photo of the clean {c}.', + lambda c: f'a photo of a large {c}.', + lambda c: f'a rendition of a {c}.', + lambda c: f'a photo of a nice {c}.', + lambda c: f'a photo of a weird {c}.', + lambda c: f'a blurry photo of a {c}.', + lambda c: f'a cartoon {c}.', + lambda c: f'art of a {c}.', + lambda c: f'a sketch of the {c}.', + lambda c: f'a embroidered {c}.', + lambda c: f'a pixelated photo of a {c}.', + lambda c: f'itap of the {c}.', + lambda c: f'a jpeg corrupted photo of the {c}.', + lambda c: f'a good photo of a {c}.', + lambda c: f'a plushie {c}.', + lambda c: f'a photo of the nice {c}.', + lambda c: f'a photo of the small {c}.', + lambda c: f'a photo of the weird {c}.', + lambda c: f'the cartoon {c}.', + lambda c: f'art of the {c}.', + lambda c: f'a drawing of the {c}.', + lambda c: f'a photo of the large {c}.', + lambda c: f'a black and white photo of a {c}.', + lambda c: f'the plushie {c}.', + lambda c: f'a dark photo of a {c}.', + lambda c: f'itap of a {c}.', + lambda c: f'graffiti of the {c}.', + lambda c: f'a toy {c}.', + lambda c: f'itap of my {c}.', + lambda c: f'a photo of a cool {c}.', + lambda c: f'a photo of a small {c}.', + lambda c: f'a tattoo of the {c}.', +] diff --git a/src/open_clip/tiny_clip/l0module.py b/src/open_clip/tiny_clip/l0module.py new file mode 100644 index 0000000000000000000000000000000000000000..db391563b04810b058e958d1e3093ab8b06f8adb --- /dev/null +++ b/src/open_clip/tiny_clip/l0module.py @@ -0,0 +1,368 @@ +# Adapted from https://github.com/princeton-nlp/CoFiPruning/blob/main/models/l0_module.py +# MIT license +import math +import numpy as np + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class L0Module(nn.Module): + limit_a, limit_b, epsilon = -.1, 1.1, 1e-6 + all_types = ["hidden_z", "heads_z", "mha_z", "intermediate_z", "ffn_z"] + + def __init__(self, config, + start_sparsity=0.0, + target_sparsity=0.0, + lagrangian_warmup=0, + init_loga=0.5, + temperature=2. / 3., + pruning_type=["hidden", "heads", "intermediate", "layer"], + magical_number=0.8, # from Wang et al. 2020 + ): + super(L0Module, self).__init__() + + self.magical_number = magical_number + self.lagrangian_warmup = lagrangian_warmup + + self.pruning_type = pruning_type + self.start_sparsity = start_sparsity + self.target_sparsity = target_sparsity + self.temperature = temperature + + self.hidden_size = config.hidden_size + self.intermediate_size = config.intermediate_size + self.num_attention_heads = config.num_attention_heads + self.dim_per_head = self.hidden_size // self.num_attention_heads + self.num_hidden_layers = config.num_hidden_layers + + self.params_per_head_layer = self.hidden_size * \ + self.hidden_size * 4 + self.hidden_size * 4 + self.params_per_head = self.params_per_head_layer // self.num_attention_heads + + self.params_per_mlp_layer = self.hidden_size * self.intermediate_size * \ + 2 + self.hidden_size + self.intermediate_size + self.params_per_intermediate_dim = self.params_per_mlp_layer // self.intermediate_size + + # we ignore the parameters in normalization layers (it takes a very small amount) + self.full_model_size = ( + self.params_per_head_layer + self.params_per_mlp_layer) * self.num_hidden_layers + self.prunable_model_size = 0 + + init_loga = init_loga if isinstance(init_loga, float) else 0.5 + self.loga_mean = math.log( + 1.0 - self.epsilon - init_loga) - math.log(init_loga + self.epsilon) + + self.types = [] + self.z_logas = {} + self.parameters_per_dim = {} + self.sizes = {} + self.shapes = {} + + self.hidden_loga = None + self.hidden_type = None + + for t in pruning_type: + self.initialize_one_module(t) + + self.lambda_1 = nn.Parameter(torch.tensor(10.00)) + self.lambda_2 = nn.Parameter(torch.tensor(10.00)) + + def initialize_parameters(self, size, num_layer=None, mean=None): + if num_layer is not None: + loga = nn.Parameter(torch.Tensor(num_layer, size)) + else: + loga = nn.Parameter(torch.Tensor(size)) + mean = mean or self.loga_mean + # loga.data.normal_(mean, 1e-2) + loga.data.normal_(mean, 0) + return loga + + def initialize_one_module(self, module_name): + default_mean = 10 + if module_name == "intermediate": + self.intermediate_loga = self.initialize_parameters( + self.intermediate_size, self.num_hidden_layers, mean=default_mean) + self.add_one_module( + self.intermediate_loga, type_name="intermediate", + parameter_per_dim=self.params_per_intermediate_dim, size=self.intermediate_size, + shape=[self.num_hidden_layers, 1, 1, self.intermediate_size] + ) + self.prunable_model_size += self.params_per_mlp_layer * self.num_hidden_layers + elif module_name == "heads": + self.heads_loga = self.initialize_parameters( + self.num_attention_heads, self.num_hidden_layers, mean=default_mean) + self.add_one_module( + self.heads_loga, type_name="heads", + parameter_per_dim=self.params_per_head, size=self.num_attention_heads, + shape=[self.num_hidden_layers, 1, + self.num_attention_heads, 1, 1] + ) + self.prunable_model_size += self.params_per_head * \ + self.num_hidden_layers * self.num_attention_heads + elif module_name == "hidden": + self.hidden_loga = self.initialize_parameters( + self.hidden_size, mean=default_mean) + self.add_one_module( + self.hidden_loga, type_name="hidden", + parameter_per_dim=self.hidden_size * 4 + self.hidden_size * 4 * 2, + size=self.hidden_size, shape=[self.hidden_size] + ) + elif module_name == "layer": + self.ffn_loga = self.initialize_parameters( + self.num_hidden_layers, mean=default_mean) + self.add_one_module( + self.ffn_loga, type_name="ffn", + parameter_per_dim=self.params_per_mlp_layer, size=1, + shape=[self.num_hidden_layers] + ) + self.mha_loga = self.initialize_parameters( + self.num_hidden_layers, mean=default_mean) + self.add_one_module( + self.mha_loga, type_name="mha", + parameter_per_dim=self.params_per_head * self.num_attention_heads, size=1, + shape=[self.num_hidden_layers] + ) + + # ! init the z_logas + def add_one_module(self, z_loga, type_name, parameter_per_dim, size, shape): + self.types.append(type_name) + self.z_logas[type_name] = z_loga + self.parameters_per_dim[type_name] = parameter_per_dim + self.sizes[type_name] = size + self.shapes[type_name] = shape + + def constrain_parameters(self): + for key in self.z_logas: + self.z_logas[key].data.clamp_( + min=math.log(1e-2), max=math.log(1e2)) + + def cdf_qz(self, x, loga): + """Implements the CDF of the 'stretched' concrete distribution""" + xn = (x - self.limit_a) / (self.limit_b - self.limit_a) + logits = math.log(xn) - math.log(1.0 - xn) + return torch.sigmoid(logits * self.temperature - loga).clamp(min=self.epsilon, max=1 - self.epsilon) + + def score_loga(self, loga): + return 1.0 - self.cdf_qz(0.0, loga) + + def get_num_parameters_and_constraint(self, hidden=False): + num_parameters = 0 + + layers = self.num_hidden_layers + hidden_size = self.hidden_size + heads = self.num_attention_heads + device = self.z_logas[self.types[0]].device + # 12 * 1 * 1 + mha_score = self.score_loga(self.mha_loga).view( + -1, 1, 1) if "mha" in self.types else torch.ones([layers, 1, 1]).to(device) + # 12 * 12 * 1 + heads_score = self.score_loga(self.heads_loga).unsqueeze( + dim=-1) if "heads" in self.types else torch.ones([layers, heads, 1]).to(device) + + if "heads" not in self.parameters_per_dim: + self.parameters_per_dim["heads"] = self.params_per_head + if "intermediate" not in self.parameters_per_dim: + self.parameters_per_dim["intermediate"] = self.params_per_intermediate_dim + + if hidden: + hidden_score = self.score_loga( + self.hidden_loga) if "hidden" in self.types else torch.ones([hidden_size]).to(device) + heads_score = ( + heads_score * mha_score) if mha_score is not None else heads_score # 38+106 + heads_score = heads_score.reshape(-1) + num_parameters += torch.outer(hidden_score, heads_score).sum( + ) * self.parameters_per_dim["heads"] / self.hidden_size + else: + heads_score = heads_score * mha_score + num_parameters += heads_score.sum() * \ + self.parameters_per_dim["heads"] + + # 12 * 1 + if 'ffn' in self.types: + ffn_score = self.score_loga(self.ffn_loga).unsqueeze( + dim=-1) if "ffn" in self.types else torch.ones([layers, 1]).to(device) + else: + ffn_score = 1 + # 12 * 3072 + intermediate_score = self.score_loga(self.intermediate_loga) if "intermediate" in self.types else torch.ones([ + layers, hidden_size * 4]).to(device) + + intermediate_score = intermediate_score * ffn_score + + if hidden: + intermediate_score = intermediate_score.reshape(-1) # 13893+22971 + num_parameters += torch.sum(torch.outer(hidden_score, + intermediate_score)) * 2 + else: + num_parameters += intermediate_score.sum() * \ + self.parameters_per_dim["intermediate"] + + return num_parameters + + def get_target_sparsity(self, pruned_steps): + target_sparsity = (self.target_sparsity - self.start_sparsity) * \ + min(1, pruned_steps / self.lagrangian_warmup) + self.start_sparsity + return target_sparsity + + def lagrangian_regularization(self, pruned_steps): + target_sparsity = self.get_target_sparsity( + pruned_steps) if self.lagrangian_warmup > 0 else self.target_sparsity + expect_sparsity = 1 - self.get_num_parameters_and_constraint( + "hidden" in self.types) / self.prunable_model_size + + # lagrangian_loss = ( + # self.lambda_1 * (expect_sparsity - target_sparsity).abs() + + # self.lambda_2 * (expect_sparsity - target_sparsity).square() + # ) + + zero = torch.tensor(0.0, device=expect_sparsity.device) + lagrangian_loss = ( + self.lambda_1 * torch.maximum(target_sparsity - expect_sparsity, zero) + + self.lambda_2 * + torch.maximum(target_sparsity - expect_sparsity, zero).square() + ) + + return lagrangian_loss, expect_sparsity.detach().item(), target_sparsity + + # during training + def _sample_z(self, loga): + # Uniform random numbers for the concrete distribution + u = torch.zeros_like(loga).uniform_(self.epsilon, 1.0 - self.epsilon) + # quantile concrete + z = torch.sigmoid( + (torch.log(u) - torch.log(1 - u) + loga) / self.temperature) + z = z * (self.limit_b - self.limit_a) + self.limit_a + z = F.hardtanh(z, min_val=0.0, max_val=1.0) + return z + + # during inference + def _deterministic_z(self, size, loga, soft=True): + soft_mask = torch.sigmoid( + loga / self.temperature * self.magical_number) + if not soft: + return soft_mask + expected_num_zeros = size - self.score_loga(loga).sum().item() + num_zeros = round(expected_num_zeros) + if num_zeros > 0: + if soft_mask.ndim == 0: + soft_mask = torch.tensor(0).to(loga.device) + else: + _, indices = torch.topk(soft_mask, k=num_zeros, largest=False) + soft_mask[indices] = 0. + return soft_mask + + def get_z_from_zs(self, zs): + numpified_zs = {} + # for t in self.all_types: + # name = t[:-2] + for t in self.types: + name = t + numpified_zs[name] = (zs[t].squeeze().detach().cpu( + ).numpy() > 0) if t in zs else np.ones(self.shapes[name]) + return numpified_zs + + def calculate_model_size(self, zs): + if zs is None: + return {"pruned_sparsity": 0.0} + + layers = self.num_hidden_layers + hidden_size = self.hidden_size + heads = self.num_attention_heads + device = self.z_logas[self.types[0]].device + + numpified_zs = self.get_z_from_zs(zs) + hidden_z = numpified_zs["hidden"] if "hidden" in numpified_zs.keys() else np.ones([ + hidden_size]) + heads_z = numpified_zs["heads"] if "heads" in numpified_zs.keys() else np.ones([ + layers, 1, heads, 1, 1]) + mha_z = numpified_zs["mha"].reshape(-1, 1, 1, 1, 1) if "mha" in numpified_zs.keys( + ) else np.ones([heads_z.shape[0], 1, 1, 1, 1]) + intermediate_z = numpified_zs["intermediate"] if "intermediate" in numpified_zs.keys( + ) else np.ones([layers, 1, 1, hidden_size * 4]) + ffn_z = numpified_zs["ffn"].reshape(-1, 1, 1, 1) if "ffn" in numpified_zs.keys( + ) else np.ones([heads_z.shape[0], 1, 1, 1]) + + remain_hidden = hidden_z.sum().item() + remain_intermediate = intermediate_z.reshape( + self.num_hidden_layers, self.intermediate_size).sum(-1).tolist() + remain_heads = heads_z.reshape( + self.num_hidden_layers, self.num_attention_heads).sum(-1).tolist() + + heads = np.outer((heads_z * mha_z).reshape(-1), hidden_z).sum().item() + intermediate = np.outer( + (intermediate_z * ffn_z).reshape(-1), hidden_z).sum().item() + + remain_model_size = heads * self.dim_per_head * 4 + intermediate * 2 + + pruned_model_size = self.prunable_model_size - remain_model_size + + results = { + 'mha': mha_z.reshape(-1).astype(int).tolist(), + 'ffn': ffn_z.reshape(-1).astype(int).tolist(), + 'remain_hidden': remain_hidden, + 'remain_intermediate': remain_intermediate, + 'remain_heads': remain_heads, + 'pruned_params': pruned_model_size, + 'remain_params': remain_model_size, + 'pruned_sparsity': pruned_model_size / self.prunable_model_size + } + return results + + def forward(self, soft=True): + zs = {f"{t}_z": [] for t in self.types} + + if self.training: + for i, t in enumerate(self.types): + loga = self.z_logas[t] + z = self._sample_z(loga) + zs[f"{t}_z"] = z.reshape(self.shapes[t]) + else: + for i, t in enumerate(self.types): + if t != "hidden": # hidden is not a per layer sample + tmp = [] + for loga in self.z_logas[t]: + z = self._deterministic_z( + self.sizes[t], loga.detach(), soft=soft) + tmp.append(z.reshape(self.shapes[t][1:])) + zs[f"{t}_z"] = torch.stack(tmp) + else: + zs[f"{t}_z"] = self._deterministic_z( + self.sizes[t], self.hidden_loga.detach(), soft=soft) + return zs + + @torch.no_grad() + def l0_mask(self): + zs = {f"{t}_z": [] for t in self.types} + # self.magical_number = 1.0 + + def get_mask(loga): return torch.sigmoid( + loga / self.temperature * self.magical_number) + for t in self.types: + if t == "hidden": + zs[f"{t}_z"] = get_mask(self.hidden_loga) + else: + tmp = [] + loga_all_layers = self.z_logas[t] + for layer in range(len(loga_all_layers)): + loga = loga_all_layers[layer] + z = get_mask(loga) + tmp.append(z.reshape(self.shapes[t][1:])) + zs[f"{t}_z"] = torch.stack(tmp) + return zs + + +if __name__ == '__main__': + from collections import namedtuple + Config = namedtuple('Config', [ + 'hidden_size', 'intermediate_size', 'num_attention_heads', 'num_hidden_layers']) + config = Config(hidden_size=768, intermediate_size=4 * 768, + num_attention_heads=12, num_hidden_layers=12) + l0_module = L0Module(config, lagrangian_warmup=200, target_sparsity=0.5) + l0_module.train() + zs = l0_module() + l0_module.eval() + zs = l0_module() + result = l0_module.calculate_model_size(zs) + print(result) diff --git a/src/open_clip/tiny_clip/loss.py b/src/open_clip/tiny_clip/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..05655cf984d4c5d327fb7719951f12646171527d --- /dev/null +++ b/src/open_clip/tiny_clip/loss.py @@ -0,0 +1,165 @@ +import torch +import torch.nn as nn +from torch.nn import functional as F + +try: + import torch.distributed.nn + from torch import distributed as dist + has_distributed = True +except ImportError: + has_distributed = False + +try: + import horovod.torch as hvd +except ImportError: + hvd = None + + +def gather_features( + image_features, + text_features, + local_loss=False, + gather_with_grad=False, + rank=0, + world_size=1, + use_horovod=False +): + assert has_distributed, 'torch.distributed did not import correctly, please use a PyTorch version with support.' + if use_horovod: + assert hvd is not None, 'Please install horovod' + if gather_with_grad: + all_image_features = hvd.allgather(image_features) + all_text_features = hvd.allgather(text_features) + else: + with torch.no_grad(): + all_image_features = hvd.allgather(image_features) + all_text_features = hvd.allgather(text_features) + if not local_loss: + # ensure grads for local rank when all_* features don't have a gradient + gathered_image_features = list( + all_image_features.chunk(world_size, dim=0)) + gathered_text_features = list( + all_text_features.chunk(world_size, dim=0)) + gathered_image_features[rank] = image_features + gathered_text_features[rank] = text_features + all_image_features = torch.cat(gathered_image_features, dim=0) + all_text_features = torch.cat(gathered_text_features, dim=0) + else: + # We gather tensors from all gpus + if gather_with_grad: + all_image_features = torch.cat( + torch.distributed.nn.all_gather(image_features), dim=0) + all_text_features = torch.cat( + torch.distributed.nn.all_gather(text_features), dim=0) + else: + gathered_image_features = [torch.zeros_like( + image_features) for _ in range(world_size)] + gathered_text_features = [torch.zeros_like( + text_features) for _ in range(world_size)] + dist.all_gather(gathered_image_features, image_features) + dist.all_gather(gathered_text_features, text_features) + if not local_loss: + # ensure grads for local rank when all_* features don't have a gradient + gathered_image_features[rank] = image_features + gathered_text_features[rank] = text_features + all_image_features = torch.cat(gathered_image_features, dim=0) + all_text_features = torch.cat(gathered_text_features, dim=0) + + return all_image_features, all_text_features + + +def gather_feature( + image_features, + local_loss=False, + gather_with_grad=False, + rank=0, + world_size=1, + use_horovod=False +): + if use_horovod: + assert hvd is not None, 'Please install horovod' + if gather_with_grad: + all_image_features = hvd.allgather(image_features) + else: + with torch.no_grad(): + all_image_features = hvd.allgather(image_features) + if not local_loss: + # ensure grads for local rank when all_* features don't have a gradient + gathered_image_features = list( + all_image_features.chunk(world_size, dim=0)) + gathered_image_features[rank] = image_features + all_image_features = torch.cat(gathered_image_features, dim=0) + else: + # We gather tensors from all gpus + if gather_with_grad: + all_image_features = torch.cat( + torch.distributed.nn.all_gather(image_features), dim=0) + else: + gathered_image_features = [torch.zeros_like( + image_features) for _ in range(world_size)] + dist.all_gather(gathered_image_features, image_features) + if not local_loss: + # ensure grads for local rank when all_* features don't have a gradient + gathered_image_features[rank] = image_features + all_image_features = torch.cat(gathered_image_features, dim=0) + + return all_image_features + + +class ClipLoss(nn.Module): + + def __init__( + self, + local_loss=False, + gather_with_grad=False, + cache_labels=False, + rank=0, + world_size=1, + use_horovod=False, + ): + super().__init__() + self.local_loss = local_loss + self.gather_with_grad = gather_with_grad + self.cache_labels = cache_labels + self.rank = rank + self.world_size = world_size + self.use_horovod = use_horovod + + # cache state + self.prev_num_logits = 0 + self.labels = {} + + def forward(self, image_features, text_features, logit_scale): + device = image_features.device + if self.world_size > 1: + all_image_features, all_text_features = gather_features( + image_features, text_features, + self.local_loss, self.gather_with_grad, self.rank, self.world_size, self.use_horovod) + + if self.local_loss: + logits_per_image = logit_scale * image_features @ all_text_features.T + logits_per_text = logit_scale * text_features @ all_image_features.T + else: + logits_per_image = logit_scale * all_image_features @ all_text_features.T + logits_per_text = logits_per_image.T + else: + logits_per_image = logit_scale * image_features @ text_features.T + logits_per_text = logit_scale * text_features @ image_features.T + + # calculated ground-truth and cache if enabled + num_logits = logits_per_image.shape[0] + if self.prev_num_logits != num_logits or device not in self.labels: + labels = torch.arange(num_logits, device=device, dtype=torch.long) + if self.world_size > 1 and self.local_loss: + labels = labels + num_logits * self.rank + if self.cache_labels: + self.labels[device] = labels + self.prev_num_logits = num_logits + else: + labels = self.labels[device] + + total_loss = ( + F.cross_entropy(logits_per_image, labels) + + F.cross_entropy(logits_per_text, labels) + ) / 2 + return total_loss diff --git a/src/open_clip/tiny_clip/model.py b/src/open_clip/tiny_clip/model.py new file mode 100644 index 0000000000000000000000000000000000000000..0a489e1ee9d3064ac2be7ff8e2e21260a50a200f --- /dev/null +++ b/src/open_clip/tiny_clip/model.py @@ -0,0 +1,1936 @@ +""" CLIP Model + +Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. +""" + +import functools +import inspect +from copy import deepcopy +import os +import random +import copy +from contextlib import nullcontext +from argparse import Namespace + +from dataclasses import dataclass +import functools +import logging +import math +from typing import Tuple, Union, Callable, Optional +from torchvision.ops import roi_align +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn +from torch.utils.checkpoint import checkpoint +# apply the non-reentrant variant of checkpoint +if 'use_reentrant' in inspect.signature(checkpoint).parameters: + checkpoint = functools.partial(checkpoint, use_reentrant=False) + +from .timm_model import TimmModel +from .utils import freeze_batch_norm_2d, to_2tuple +from .resnet import ModifiedResNet +from .l0module import L0Module + + +def load_state_dict(model, state_dict): + model.load_state_dict(state_dict, strict=True) + + +class LayerNorm(nn.LayerNorm): + """Subclass torch's LayerNorm to handle fp16.""" + + def forward(self, x: torch.Tensor, hidden_z=None): + ''' + x: (N, L, C) + hidden_z: (C,) + ''' + self.hidden_z = hidden_z + orig_type = x.dtype + + if hidden_z is None: + x = F.layer_norm(x, self.normalized_shape, + self.weight, self.bias, self.eps) + else: + assert len(self.normalized_shape) == 1 + # [TODO] weighted layer norm + remaining_index = torch.where(hidden_z != 0)[0] + compressed_input = torch.index_select( + x, dim=-1, index=remaining_index) + compressed_weight = self.weight[remaining_index] + compressed_bias = self.bias[remaining_index] + normalized_shape = len(remaining_index) + normed_input = F.layer_norm( + compressed_input, [normalized_shape], compressed_weight, compressed_bias, self.eps) + x = x.new_zeros(x.shape) + x[..., remaining_index] = normed_input.to(orig_type) + + return x.to(orig_type) + + def prune(self): + if self.hidden_z is None: + return self + hidden_z = self.hidden_z + assert len(self.normalized_shape) == 1 + remaining_index = torch.where(hidden_z != 0)[0] + compressed_weight = self.weight[remaining_index] + compressed_bias = self.bias[remaining_index] + # m = self + m = LayerNorm(remaining_index.shape[0]).to(self.weight.device) + m.normalized_shape = (len(remaining_index),) + m.weight.data = compressed_weight.contiguous() + m.bias.data = compressed_bias.contiguous() + return m + + def prune_mul_hidden(self): + if self.hidden_z is None: + return self + hidden_z = self.hidden_z + assert len(self.normalized_shape) == 1 + remaining_index = torch.where(hidden_z != 0)[0] + compressed_weight = self.weight[remaining_index] * \ + hidden_z[remaining_index] + compressed_bias = self.bias[remaining_index] * \ + hidden_z[remaining_index] + m = self + m.normalized_shape = (len(remaining_index),) + m.weight.data = compressed_weight.contiguous() + m.bias.data = compressed_bias.contiguous() + return m + + +class QuickGELU(nn.Module): + # NOTE This is slower than nn.GELU or nn.SiLU and uses more GPU memory + def forward(self, x: torch.Tensor): + return x * torch.sigmoid(1.702 * x) + + +class Mlp(nn.Module): + def __init__(self, d_model, mlp_width, act_layer=nn.GELU, scale_fc=False): + super().__init__() + self.d_model = d_model + self.mlp_width = mlp_width + self.c_fc = nn.Linear(d_model, mlp_width) + assert not scale_fc + # self.ln = LayerNorm(mlp_width) if scale_fc else nn.Identity() + self.act_layer = act_layer + self.scale_fc = scale_fc + self.gelu = act_layer() + self.c_proj = nn.Linear(mlp_width, d_model) + + def forward(self, x, hidden_z=None, intermediate_z=None): + ''' + x: (N, L, C) + intermediate_z: (mlp_width,) or (1, 1, mlp_width) + hidden_z: (embed_dim,) or (1, 1, embed_dim) + ''' + self.hidden_z = hidden_z + self.intermediate_z = intermediate_z + + x = self.c_fc(x) + x = self.gelu(x) + if intermediate_z is not None: + x = torch.mul(x, intermediate_z) + x = self.c_proj(x) + if hidden_z is not None: + x = torch.mul(x, hidden_z) + return x + + def prune(self): + device = self.c_fc.weight.device + if self.hidden_z is None: + self.hidden_z = torch.ones( + (self.d_model,), dtype=torch.bool, device=device) + if self.intermediate_z is None: + self.intermediate_z = torch.ones( + (self.mlp_width,), dtype=torch.bool, device=device) + hidden_r = torch.where(self.hidden_z != 0)[0] + intermediate_r = torch.where(self.intermediate_z != 0)[0] + d_model = len(hidden_r) + mlp_width = len(intermediate_r) + # m = self + m = copy.deepcopy(self) + m.c_fc = nn.Linear(hidden_r.shape[0], intermediate_r.shape[0]) + m.c_proj = nn.Linear(intermediate_r.shape[0], hidden_r.shape[0]) + m.d_model = d_model + m.mlp_width = mlp_width + m.c_fc.weight = nn.Parameter( + (self.c_fc.weight[intermediate_r][:, hidden_r]).contiguous()) + m.c_fc.bias = nn.Parameter( + (self.c_fc.bias[intermediate_r]).contiguous()) + + m.c_proj.weight = nn.Parameter(((self.c_proj.weight * + self.intermediate_z.view(1, -1) * self.hidden_z.view(-1, 1))[hidden_r][:, intermediate_r]).contiguous()) + m.c_proj.bias = nn.Parameter( + ((self.c_proj.bias * self.hidden_z)[hidden_r]).contiguous()) + return m + + +class MultiheadAttention(nn.MultiheadAttention): + def prune(self): + device = self.in_proj_weight.device + if self.hidden_z is None: + self.hidden_z = torch.ones( + (self.embed_dim,), dtype=torch.bool, device=device) + if self.head_z is None: + self.head_z = torch.ones( + (self.num_heads,), dtype=torch.bool, device=device) + hidden_r = torch.where(self.hidden_z != 0)[0] + head_r = torch.where(self.head_z != 0)[0] + d_model = len(hidden_r) + d_head = len(head_r) + org_num_heads = self.num_heads + org_head_dim = self.head_dim + org_embed_dim = self.embed_dim + mod = self + mod.use_naive_compute = True + mod.embed_dim = d_model + mod.head_dim = self.head_dim + mod.num_heads = d_head + inter_dim = d_head * self.head_dim + mod.in_proj_weight = nn.Parameter(self.in_proj_weight.view( + 3, org_num_heads, org_head_dim, org_embed_dim)[:, head_r][..., hidden_r].reshape(-1, d_model)) + if self.in_proj_bias is not None: + mod.in_proj_bias = nn.Parameter(self.in_proj_bias.view( + 3, org_num_heads, org_head_dim)[:, head_r].reshape(-1)) + mod.out_proj.weight = nn.Parameter( + ((self.out_proj.weight * self.hidden_z.view(-1, 1)). + view(org_embed_dim, org_num_heads, org_head_dim) * self.head_z.view(1, org_num_heads, 1))[hidden_r][:, head_r].reshape(d_model, -1) + ) + if self.out_proj.bias is not None: + mod.out_proj.bias = nn.Parameter( + (self.out_proj.bias * self.hidden_z.view(-1,)). + view(org_embed_dim)[hidden_r].reshape(-1) + ) + return mod + + +class ResidualAttentionBlock(nn.Module): + def __init__( + self, + d_model: int, + n_head: int, + mlp_ratio: float = 4.0, + act_layer: Callable = nn.GELU, + scale_cosine_attn: bool = False, + scale_heads: bool = False, + scale_attn: bool = False, + scale_fc: bool = False, + ): + super().__init__() + + self.ln_1 = LayerNorm(d_model) + # FIXME torchscript issues need to be resolved for custom attention + # if scale_cosine_attn or scale_heads: + # self.attn = Attention( + # d_model, n_head, + # scaled_cosine=scale_cosine_attn, + # scale_heads=scale_heads, + # ) + self.attn = MultiheadAttention(d_model, n_head) + assert not scale_attn + self.ln_attn = LayerNorm(d_model) if scale_attn else nn.Identity() + + self.ln_2 = LayerNorm(d_model) + mlp_width = int(d_model * mlp_ratio) + self.mlp = Mlp(d_model, mlp_width, act_layer, scale_fc) + def attention(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None, + *, + head_z: Optional[torch.Tensor] = None, + hidden_z: Optional[torch.Tensor] = None, + ): + + self.attn.head_z = head_z + self.attn.hidden_z = hidden_z + + if (head_z is None and hidden_z is None and + not getattr(self.attn, 'use_naive_compute', False)): + return self.attn(x, x, x, need_weights=False, attn_mask=attn_mask)[0] + else: + # the following code does not support `attn_mask` + # x: (length, batch_size, embed_dim) + n_head = self.attn.num_heads + length, batch_size, d_model = x.shape + ws = self.attn.in_proj_weight.chunk(3) + bs = self.attn.in_proj_bias.chunk(3) + dim_per_head = len(ws[0]) // n_head + # (length, batch_size, n_head * dim_per_head) + q, k, v = [F.linear(x, w, b) for w, b in zip(ws, bs)] + # (batch_size * n_head, length, d_head) + q = q.reshape(length, batch_size * n_head, -1).transpose(0, 1) + k = k.reshape(length, batch_size * n_head, -1).transpose(0, 1) + v = v.reshape(length, batch_size * n_head, -1).transpose(0, 1) + scale = dim_per_head ** -0.5 + q *= scale + # (batch_size * n_head, length, length) + sim = q @ k.transpose(1, 2) + if attn_mask is not None: + sim += attn_mask + sim = torch.softmax(sim, -1) + # (batch_size * n_head, length, head_dim) + out = sim @ v + if head_z is not None: + out = out.view(batch_size, n_head, length, dim_per_head) + # head_z: (1, n_head, 1, 1) + out *= head_z.view(1, -1, 1, 1) + out = out.view(batch_size * n_head, length, dim_per_head) + out = out.transpose(0, 1).reshape(length, batch_size, -1) + out = F.linear(out, self.attn.out_proj.weight, + self.attn.out_proj.bias) + if hidden_z is not None: + out = torch.mul(out, hidden_z) + return out + + def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None, + hidden_z: Optional[torch.Tensor] = None, + heads_z: Optional[torch.Tensor] = None, + mha_z: Optional[torch.Tensor] = None, + intermediate_z: Optional[torch.Tensor] = None, + ffn_z: Optional[torch.Tensor] = None): + + self.hidden_z = hidden_z + self.heads_z = heads_z + self.mha_z = mha_z + self.intermediate_z = intermediate_z + self.ffn_z = ffn_z + + # x: (length, batch_size, embed_dim) e.g. 50, 128, 768 for vision + if self.attention is not None: + attn_out = self.attention(self.ln_1(x, hidden_z=hidden_z), + attn_mask=attn_mask, + head_z=heads_z, hidden_z=hidden_z) + if mha_z is not None: # a number + attn_out = attn_out.mul(mha_z) + x = x + attn_out + if self.mlp is not None: + ln_2_out = self.ln_2(x, hidden_z=hidden_z) + + mlp_out = self.mlp(ln_2_out, + intermediate_z=intermediate_z, + hidden_z=hidden_z) + if ffn_z is not None: # a number + mlp_out = mlp_out.mul(ffn_z) + x = x + mlp_out + return x + + def prune(self): + mod = self + if (self.mha_z is not None and self.mha_z.item() == 0) or (self.heads_z).sum() == 0: + mod.ln_1 = None + mod.attn = None + mod.attention = None + else: + mod.ln_1 = mod.ln_1.prune() + mod.attn = mod.attn.prune() + if self.mha_z is not None: + mod.attn.out_proj.weight.data *= self.mha_z + mod.attn.out_proj.bias.data *= self.mha_z + + if self.ffn_z is not None and self.ffn_z.item() == 0: + mod.ln_2 = None + mod.mlp = None + else: + mod.ln_2 = mod.ln_2.prune() + mod.mlp = mod.mlp.prune() + if self.ffn_z is not None: + mod.mlp.c_proj.weight.data *= self.ffn_z + mod.mlp.c_proj.bias.data *= self.ffn_z + return mod + + def csa_attn(self, x, mode, hidden_z=None, heads_z=None, mha_z=None): + """ + Cross-Self Attention: uses both q@q and k@k attention. + """ + x = self.ln_1(x, hidden_z=hidden_z) + attn_layer = self.attn + + # Set attention masks + attn_layer.head_z = heads_z + attn_layer.hidden_z = hidden_z + + num_heads = attn_layer.num_heads + length, bsz, embed_dim = x.size() + head_dim = embed_dim // num_heads + scale = head_dim ** -0.5 + + # Get q, k, v + ws = attn_layer.in_proj_weight.chunk(3) + bs = attn_layer.in_proj_bias.chunk(3) if attn_layer.in_proj_bias is not None else (None, None, None) + q, k, v = [F.linear(x, w, b) for w, b in zip(ws, bs)] + + # Reshape for multi-head attention + q = q.reshape(length, bsz * num_heads, head_dim).transpose(0, 1) # (bsz*num_heads, length, head_dim) + k = k.reshape(length, bsz * num_heads, head_dim).transpose(0, 1) + v = v.reshape(length, bsz * num_heads, head_dim).transpose(0, 1) + + # Compute q@q and k@k attention + q_attn = torch.bmm(q, q.transpose(1, 2))# scale + k_attn = torch.bmm(k, k.transpose(1, 2))# scale + attn_weights = F.softmax(q_attn, dim=-1) + F.softmax(k_attn, dim=-1) + + # Apply attention to values + attn_output = torch.bmm(attn_weights, v) + # Apply head mask if needed + if heads_z is not None: + attn_output = attn_output.view(bsz, num_heads, length, head_dim) + attn_output = attn_output * heads_z.view(1, -1, 1, 1) + attn_output = attn_output.view(bsz * num_heads, length, head_dim) + # Reshape back + attn_output = attn_output.transpose(0, 1).reshape(length, bsz, embed_dim) + + # Apply output projection + attn_output = F.linear(attn_output, attn_layer.out_proj.weight, attn_layer.out_proj.bias) + + # Apply hidden mask and mha_z if needed + if hidden_z is not None: + attn_output = torch.mul(attn_output, hidden_z) + if mha_z is not None: + attn_output = attn_output.mul(mha_z) + + if "distill" in mode: + # Return attention output and extra features (q, k excluding class token) + return attn_output, (q[:, 1:], k[:, 1:]) + else: + return attn_output + + def ss_attn(self, x, mode, hidden_z=None, heads_z=None, mha_z=None): + """ + Self-Self Attention: uses either q@q or k@k attention based on mode. + """ + x = self.ln_1(x, hidden_z=hidden_z) + attn_layer = self.attn + + # Set attention masks + attn_layer.head_z = heads_z + attn_layer.hidden_z = hidden_z + + num_heads = attn_layer.num_heads + length, bsz, embed_dim = x.size() + head_dim = embed_dim // num_heads + scale = head_dim ** -0.5 + + # Get q, k, v + ws = attn_layer.in_proj_weight.chunk(3) + bs = attn_layer.in_proj_bias.chunk(3) if attn_layer.in_proj_bias is not None else (None, None, None) + q, k, v = [F.linear(x, w, b) for w, b in zip(ws, bs)] + + # Reshape for multi-head attention + q = q.reshape(length, bsz * num_heads, head_dim).transpose(0, 1) # (bsz*num_heads, length, head_dim) + k = k.reshape(length, bsz * num_heads, head_dim).transpose(0, 1) + v = v.reshape(length, bsz * num_heads, head_dim).transpose(0, 1) + + # Compute attention based on mode + if mode == "qq" or mode == "qq_vfm_distill": + q_attn = torch.bmm(q, q.transpose(1, 2)) # scale + attn_weights = F.softmax(q_attn, dim=-1) + extra_feats = q[:, 1:] if "distill" in mode else None + elif mode == "kk" or mode == "kk_vfm_distill": + k_attn = torch.bmm(k, k.transpose(1, 2)) # scale + attn_weights = F.softmax(k_attn, dim=-1) + extra_feats = k[:, 1:] if "distill" in mode else None + else: + raise NotImplementedError(f"The mode '{mode}' is not implemented for ss_attn.") + + # Apply attention to values + attn_output = torch.bmm(attn_weights, v) + + # Apply head mask if needed + if heads_z is not None: + attn_output = attn_output.view(bsz, num_heads, length, head_dim) + attn_output = attn_output * heads_z.view(1, -1, 1, 1) + attn_output = attn_output.view(bsz * num_heads, length, head_dim) + + # Reshape back + attn_output = attn_output.transpose(0, 1).reshape(length, bsz, embed_dim) + + # Apply output projection + attn_output = F.linear(attn_output, attn_layer.out_proj.weight, attn_layer.out_proj.bias) + + # Apply hidden mask and mha_z if needed + if hidden_z is not None: + attn_output = torch.mul(attn_output, hidden_z) + if mha_z is not None: + attn_output = attn_output.mul(mha_z) + + if "distill" in mode: + return attn_output, extra_feats + else: + return attn_output + + +class Transformer(nn.Module): + def __init__(self, width: int, layers: int, heads: int, mlp_ratio: float = 4.0, + act_layer: Callable = nn.GELU): + super().__init__() + self.width = width + self.layers = layers + self.grad_checkpointing = False + + assert width % heads == 0 + self.head_dim = width // heads + self.num_heads = heads + self.mlp_ratio = mlp_ratio + + self.resblocks = nn.ModuleList([ + ResidualAttentionBlock( + width, heads, mlp_ratio, act_layer=act_layer) + for _ in range(layers) + ]) + + def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None, + hidden_z: Optional[torch.Tensor] = None, + heads_z: Optional[torch.Tensor] = None, + mha_z: Optional[torch.Tensor] = None, + intermediate_z: Optional[torch.Tensor] = None, + ffn_z: Optional[torch.Tensor] = None): + + return self.infer_blocks(x, attn_mask, + hidden_z=hidden_z, + heads_z=heads_z, + mha_z=mha_z, + intermediate_z=intermediate_z, + ffn_z=ffn_z) + + def infer_blocks(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None, block_idxs=None, + hidden_z: Optional[torch.Tensor] = None, + heads_z: Optional[torch.Tensor] = None, + mha_z: Optional[torch.Tensor] = None, + intermediate_z: Optional[torch.Tensor] = None, + ffn_z: Optional[torch.Tensor] = None): + + num_layers = self.layers + if hidden_z is not None: + assert hidden_z.shape == (self.width,) + if heads_z is not None: + if heads_z.ndim == 5: + heads_z = heads_z.view(num_layers, self.num_heads) + assert heads_z.shape in [(num_layers, self.num_heads), (self.num_heads,)], ( + heads_z.shape, (num_layers, self.num_heads)) + if mha_z is not None: + assert mha_z.shape == (num_layers,), mha_z.shape + if intermediate_z is not None: + if intermediate_z.ndim == 4: + intermediate_z = intermediate_z.view(num_layers, -1) + assert intermediate_z.shape in [ + (num_layers, self.mlp_ratio * self.width), (self.mlp_ratio * self.width,)], intermediate_z.shape + if ffn_z is not None: + assert ffn_z.shape == (num_layers,), ffn_z.shape + + def _get_zi(z, i, ndim=2): + if z is None: + return None + if z.ndim == ndim: + return z[i] + return z + + block_idxs = block_idxs or list(range(self.layers)) + for i in block_idxs: + r = self.resblocks[i] + + if self.grad_checkpointing and not torch.jit.is_scripting(): + x = checkpoint(r, x, attn_mask, + hidden_z, + _get_zi(heads_z, i), + _get_zi(mha_z, i, ndim=1), + _get_zi(intermediate_z, i), + _get_zi(ffn_z, i, ndim=1)) + else: + x = r(x, attn_mask=attn_mask, + hidden_z=hidden_z, + heads_z=_get_zi(heads_z, i), + mha_z=_get_zi(mha_z, i, ndim=1), + intermediate_z=_get_zi(intermediate_z, i), + ffn_z=_get_zi(ffn_z, i, ndim=1)) + + return x + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.grad_checkpointing = enable + + def extra_repr(self): + return f'grad_checkpointing={self.grad_checkpointing}' + + def prune(self): + mod = self + for i in range(len(self.resblocks)): + self.resblocks[i] = self.resblocks[i].prune() + return mod + + def extract_feature_map(self, x, mode='vanilla', hidden_z=None, heads_z=None, + mha_z=None, intermediate_z=None, ffn_z=None): + """ + Extract feature map from transformer, supporting different modes. + Supports vanilla, qq, kk, csa, and their distill variants. + """ + def _get_zi(z, i, ndim=2): + """Helper function to get z value for layer i""" + if z is None: + return None + if z.ndim == ndim: + return z[i] + return z + + # Process all layers except the last one + for i in range(self.layers - 1): + r = self.resblocks[i] + x = r(x, attn_mask=None, + hidden_z=hidden_z, + heads_z=_get_zi(heads_z, i) if heads_z is not None else None, + mha_z=_get_zi(mha_z, i, ndim=1) if mha_z is not None else None, + intermediate_z=_get_zi(intermediate_z, i) if intermediate_z is not None else None, + ffn_z=_get_zi(ffn_z, i, ndim=1) if ffn_z is not None else None) + + # Process the last layer based on mode + r = self.resblocks[-1] + last_heads_z = _get_zi(heads_z, self.layers - 1) if heads_z is not None else None + last_mha_z = _get_zi(mha_z, self.layers - 1, ndim=1) if mha_z is not None else None + last_intermediate_z = _get_zi(intermediate_z, self.layers - 1) if intermediate_z is not None else None + last_ffn_z = _get_zi(ffn_z, self.layers - 1, ndim=1) if ffn_z is not None else None + + if mode == 'vanilla': + x = r(x, attn_mask=None, + hidden_z=hidden_z, + heads_z=last_heads_z, + mha_z=last_mha_z, + intermediate_z=last_intermediate_z, + ffn_z=last_ffn_z) + return x + elif mode in ['csa', 'csa_vfm_distill']: + # For csa mode, only return attention output without residual connection and MLP + # This matches EVA CLIP's forward_without_rcffn behavior + result = r.csa_attn(x, mode, + hidden_z=hidden_z, + heads_z=last_heads_z, + mha_z=last_mha_z) + if 'distill' in mode: + return result[0], result[1] # attn_out, extra_feats + else: + return result # attn_out only + elif mode in ['qq', 'kk', 'qq_vfm_distill', 'kk_vfm_distill']: + # For qq/kk mode, only return attention output without residual connection and MLP + # This matches EVA CLIP's forward_without_rcffn behavior + result = r.ss_attn(x, mode, + hidden_z=hidden_z, + heads_z=last_heads_z, + mha_z=last_mha_z) + if 'distill' in mode: + return result[0], result[1] # attn_out, extra_feats + else: + return result # attn_out only + else: + raise NotImplementedError(f"The mode '{mode}' is not implemented.") + + +class VisualTransformer(nn.Module): + def __init__( + self, + image_size: int, + patch_size: int, + width: int, + layers: int, + heads: int, + mlp_ratio: float, + output_dim: int, + act_layer: Callable = nn.GELU, + teacher_width: int = -1, + ): + super().__init__() + self.image_size = to_2tuple(image_size) + self.patch_size = to_2tuple(patch_size) + self.grid_size = ( + self.image_size[0] // self.patch_size[0], self.image_size[1] // self.patch_size[1]) + self.output_dim = output_dim + self.embed_dim = width + self.layers = layers + self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, + kernel_size=patch_size, stride=patch_size, bias=False) + + scale = width ** -0.5 + self.class_embedding = nn.Parameter(scale * torch.randn(width)) + self.positional_embedding = nn.Parameter( + scale * torch.randn(self.grid_size[0] * self.grid_size[1] + 1, width)) + self.ln_pre = LayerNorm(width) + + self.transformer = Transformer( + width, layers, heads, mlp_ratio, act_layer=act_layer) + self.head_dim = width // heads + + self.ln_post = LayerNorm(width) + # image proj + if teacher_width > 0: + self.proj = nn.Parameter(torch.empty( + teacher_width, output_dim), requires_grad=False) + else: + self.proj = nn.Parameter(scale * torch.randn(width, output_dim)) + + def lock(self, unlocked_groups=0, freeze_bn_stats=False): + for param in self.parameters(): + param.requires_grad = False + + def _unlock(x): + if isinstance(x, list): + for g in x: + _unlock(g) + else: + if isinstance(x, torch.nn.Parameter): + x.requires_grad = True + else: + for p in x.parameters(): + p.requires_grad = True + + for blk in self.transformer.resblocks[-unlocked_groups:]: + _unlock(blk) + + if freeze_bn_stats: + freeze_batch_norm_2d(self) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.transformer.set_grad_checkpointing(enable) + + + + def get_proj_feature(self, x): + if self.proj is not None: + x = x @ self.proj + return x + + def extra_repr(self): + return 'image_size={}, output_dim={}'.format(self.image_size, self.output_dim) + + def prune(self): + hidden_r = torch.where(self.hidden_z != 0)[0] + self.conv1.weight = nn.Parameter( + (self.conv1.weight.data * self.hidden_z.view(-1, 1, 1, 1))[hidden_r]) + if self.conv1.bias is not None: + self.conv1.bias = nn.Parameter( + (self.conv1.bias * self.hidden_z.view(-1,))[hidden_r]) + self.class_embedding = nn.Parameter( + (self.class_embedding * self.hidden_z.view(-1,))[hidden_r]) + self.positional_embedding = nn.Parameter( + (self.positional_embedding * self.hidden_z.view(1, -1))[:, hidden_r]) + self.ln_pre = self.ln_pre.prune() + self.transformer = self.transformer.prune() + self.ln_post = self.ln_post.prune() + if self.embed_dim_z is not None: + embed_dim_r = self.embed_dim_z > 0 + self.proj = nn.Parameter((self.proj * self.hidden_z.view(-1, 1) + * self.embed_dim_z.view(1, -1))[hidden_r][:, embed_dim_r]) + else: + self.proj = nn.Parameter( + (self.proj * self.hidden_z.view(-1, 1))[hidden_r]) + return self + + def forward(self, x: torch.Tensor, + hidden_z: Optional[torch.Tensor] = None, + heads_z: Optional[torch.Tensor] = None, + mha_z: Optional[torch.Tensor] = None, + intermediate_z: Optional[torch.Tensor] = None, + ffn_z: Optional[torch.Tensor] = None, + embed_dim_z: Optional[torch.Tensor] = None): + + self.hidden_z = hidden_z + self.embed_dim_z = embed_dim_z + + x = x.to(self.conv1.weight.device) + x = self.conv1(x) # shape = [*, width, grid, grid] + # shape = [*, width, grid ** 2] + x = x.reshape(x.shape[0], x.shape[1], -1) + x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] + # the first token is the class token. + x = torch.cat( + [self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), + x], dim=1) # shape = [*, 1 + grid ** 2, width] + x = x + self.positional_embedding.to(x.dtype) # 128, 50, 768 + + if hidden_z is not None: + x = torch.mul(x, hidden_z) + x = self.ln_pre(x, hidden_z=hidden_z) + + x = x.permute(1, 0, 2) # NLD -> LND 50, 128, 768 + x = self.transformer(x, + hidden_z=hidden_z, + heads_z=heads_z, + mha_z=mha_z, + intermediate_z=intermediate_z, + ffn_z=ffn_z) + + x = x.permute(1, 0, 2) # LND -> NLD + + # select class token + x = self.ln_post(x[:, 0, :], hidden_z=hidden_z) + + if self.proj is not None: + x = self.get_proj_feature(x) + + return x + def _global_pool(self, x: torch.Tensor): + """Separate class token and patch tokens.""" + return x[:, 0], x[:, 1:] + + def encode_dense(self, x, keep_shape=False, mode='vanilla', + hidden_z=None, heads_z=None, mha_z=None, + intermediate_z=None, ffn_z=None, embed_dim_z=None): + """ + Encode dense feature map from images. + Similar to OpenAI CLIP's encode_dense but adapted for TinyCLIP. + """ + self.hidden_z = hidden_z + self.embed_dim_z = embed_dim_z + + x = x.to(self.conv1.weight.device) + x = self.conv1(x) # shape = [*, width, grid, grid] + bs, _, h, w = x.shape + # shape = [*, width, grid ** 2] + x = x.reshape(x.shape[0], x.shape[1], -1) + x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] + # the first token is the class token. + x = torch.cat( + [self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), + x], dim=1) # shape = [*, 1 + grid ** 2, width] + + # Handle positional embedding + if (h, w) == self.grid_size: + pe = self.positional_embedding.to(x.dtype) + else: + pe = self.rescale_positional_embedding(out_size=(h, w), dtype=x.dtype) + + x = x + pe + + if hidden_z is not None: + x = torch.mul(x, hidden_z) + x = self.ln_pre(x, hidden_z=hidden_z) + + x = x.permute(1, 0, 2) # NLD -> LND + # For TinyCLIP, we support vanilla mode and distill modes + if 'distill' in mode: + x, extra_feats = self.transformer.extract_feature_map( + x, mode=mode, hidden_z=hidden_z, heads_z=heads_z, + mha_z=mha_z, intermediate_z=intermediate_z, ffn_z=ffn_z) + else: + x = self.transformer.extract_feature_map( + x, mode=mode, hidden_z=hidden_z, heads_z=heads_z, + mha_z=mha_z, intermediate_z=intermediate_z, ffn_z=ffn_z) + + x = x.permute(1, 0, 2) # LND -> NLD + # Use _global_pool to separate class token and patch tokens + _, tokens = self._global_pool(x) + tokens = self.ln_post(tokens, hidden_z=hidden_z) + + if self.proj is not None: + tokens = tokens @ self.proj + + feature_map = tokens.view(bs, h * w, -1) + feature_map = F.normalize(feature_map, dim=-1) + + if keep_shape: + feature_map = feature_map.view(bs, h, w, -1).permute(0, 3, 1, 2) + + if 'distill' in mode: + return feature_map, extra_feats + else: + return feature_map + + def extract_roi_features(self, x, normed_boxes, mode="vanilla", size=(1, 1), + hidden_z=None, heads_z=None, mha_z=None, + intermediate_z=None, ffn_z=None, embed_dim_z=None): + """ + Extract ROI features from images using normalized boxes. + """ + if mode in ["qq_vfm_distill", "kk_vfm_distill", "csa_vfm_distill"]: + x, extra_feats = self.encode_dense( + x, keep_shape=True, mode=mode, + hidden_z=hidden_z, heads_z=heads_z, mha_z=mha_z, + intermediate_z=intermediate_z, ffn_z=ffn_z, embed_dim_z=embed_dim_z) + boxes = self._denormalize_boxes(normed_boxes, x) + + roi_feats = roi_align( + x, + boxes, + output_size=size, + spatial_scale=1.0, + sampling_ratio=-1, + aligned=True + ) + if size == (1, 1): + roi_feats = roi_feats[..., 0, 0] + else: + roi_feats = roi_feats.flatten(start_dim=-2).transpose(-2, -1).contiguous() + return roi_feats, extra_feats + else: + x = self.encode_dense( + x, keep_shape=True, mode=mode, + hidden_z=hidden_z, heads_z=heads_z, mha_z=mha_z, + intermediate_z=intermediate_z, ffn_z=ffn_z, embed_dim_z=embed_dim_z) + boxes = self._denormalize_boxes(normed_boxes, x) + roi_feats = roi_align( + x, + boxes, + output_size=size, + spatial_scale=1.0, + sampling_ratio=-1, + aligned=True + ) + if size == (1, 1): + roi_feats = roi_feats[..., 0, 0] + else: + roi_feats = roi_feats.flatten(start_dim=-2).transpose(-2, -1).contiguous() + return roi_feats + + def mask_pool(self, x, masks, mode="vanilla", + hidden_z=None, heads_z=None, mha_z=None, + intermediate_z=None, ffn_z=None, embed_dim_z=None): + """ + Pool features using masks. + """ + feature_map = self.encode_dense( + x, keep_shape=False, mode=mode, + hidden_z=hidden_z, heads_z=heads_z, mha_z=mha_z, + intermediate_z=intermediate_z, ffn_z=ffn_z, embed_dim_z=embed_dim_z) + num_masks_per_image = [len(masks_per_image) for masks_per_image in masks] + masks = torch.cat(masks).float().flatten(-2, -1) # bs, h*w + feature_map = torch.repeat_interleave( + feature_map, torch.tensor(num_masks_per_image, device=feature_map.device), dim=0) + features = (feature_map * masks.unsqueeze(-1)).sum(1) / (masks.sum(1, keepdim=True) + 1e-12) + return features + + @staticmethod + def _denormalize_boxes(normed_boxes, x): + """ + Denormalize boxes from [0, 1] to pixel coordinates. + """ + h, w = x.shape[-2:] + denormed_boxes = [] + for boxes in normed_boxes: + new_boxes = boxes.clone() # FIXME: do not change the value in normed_boxes! + new_boxes[:, [0, 2]] *= w + new_boxes[:, [1, 3]] *= h + denormed_boxes.append(new_boxes) + return denormed_boxes + + def rescale_positional_embedding(self, out_size, dtype): + """ + Rescale positional embedding to match output size. + """ + h, w = out_size + rescaled_positional_embedding = \ + self.positional_embedding.new_zeros(1 + h*w, self.positional_embedding.shape[1]) + rescaled_positional_embedding[0] = self.positional_embedding[0] + pe_2d = self.positional_embedding[1:].T.contiguous().view( + 1, -1, *self.grid_size) + pe_2d = F.interpolate(pe_2d, out_size, mode='bicubic', align_corners=False).view(-1, h*w) + rescaled_positional_embedding[1:] = pe_2d.T.contiguous() + return rescaled_positional_embedding.to(dtype=dtype) + + +@dataclass +class CLIPVisionCfg: + layers: Union[Tuple[int, int, int, int], int] = 12 + width: int = 768 + teacher_width: int = -1 + head_width: int = 64 + mlp_ratio: float = 4.0 + patch_size: int = 16 + image_size: Union[Tuple[int, int], int] = 224 + timm_model_name: str = None # a valid model name overrides layers, width, patch_size + # use (imagenet) pretrained weights for named model + timm_model_pretrained: bool = False + # feature pooling for timm model ('abs_attn', 'rot_attn', 'avg', '') + timm_pool: str = 'avg' + # linear projection for timm model output ('linear', 'mlp', '') + timm_proj: str = 'linear' + + +@dataclass +class CLIPTextCfg: + context_length: int = 77 + vocab_size: int = 49408 + width: int = 512 + teacher_width: int = -1 + heads: int = 8 + layers: int = 12 + + +class ImageEncoder(nn.Module): + def __init__(self, embed_dim, vision_cfg, quick_gelu, + l0_module_image=False, + mask_cfg=None): + super().__init__() + act_layer = QuickGELU if quick_gelu else nn.GELU + + if vision_cfg.timm_model_name: + self.visual = TimmModel( + vision_cfg.timm_model_name, + pretrained=vision_cfg.timm_model_pretrained, + pool=vision_cfg.timm_pool, + proj=vision_cfg.timm_proj, + embed_dim=embed_dim, + image_size=vision_cfg.image_size + ) + act_layer = nn.GELU # so that text transformer doesn't use QuickGELU w/ timm models + elif isinstance(vision_cfg.layers, (tuple, list)): + vision_heads = vision_cfg.width * 32 // vision_cfg.head_width + self.visual = ModifiedResNet( + layers=vision_cfg.layers, + output_dim=embed_dim, + heads=vision_heads, + image_size=vision_cfg.image_size, + width=vision_cfg.width + ) + else: + vision_heads = vision_cfg.width // vision_cfg.head_width + self.visual = VisualTransformer( + image_size=vision_cfg.image_size, + patch_size=vision_cfg.patch_size, + width=vision_cfg.width, + layers=vision_cfg.layers, + heads=vision_heads, + mlp_ratio=vision_cfg.mlp_ratio, + output_dim=embed_dim, + act_layer=act_layer, + teacher_width=vision_cfg.teacher_width, + ) + self.init_parameters() + + if l0_module_image: + logging.info('use l0_module_vision') + config_mask = Namespace() + config_mask.hidden_size = vision_cfg.width + config_mask.intermediate_size = 4 * vision_cfg.width + config_mask.num_attention_heads = vision_heads + config_mask.num_hidden_layers = vision_cfg.layers + config_mask.sparsity_warmup = mask_cfg.sparsity_warmup + config_mask.sparsity = mask_cfg.sparsity + config_mask.start_sparsity = mask_cfg.start_sparsity + self.l0_module = L0Module(config_mask, lagrangian_warmup=config_mask.sparsity_warmup, start_sparsity=config_mask.start_sparsity, + target_sparsity=config_mask.sparsity, pruning_type=["hidden", "heads", "intermediate"]) + else: + self.l0_module = None + + self.mask = None + + def init_parameters(self): + if hasattr(self.visual, 'init_parameters'): + self.visual.init_parameters() + + def forward(self, image, normalized=False, + **mask): + + if self.l0_module is not None: + mask = self.l0_module.forward() + + self.mask = mask + + image_features = self.visual(image, **mask) + + embed_dim_z = mask.get('embed_dim_z', None) + if embed_dim_z is not None: + image_features = image_features.mul(embed_dim_z) + + if normalized: + image_features = F.normalize(image_features, dim=-1) + return image_features + + def prune(self): + self.visual = self.visual.prune() + return self + + +class TextEncoder(nn.Module): + def __init__(self, embed_dim, text_cfg, quick_gelu, + l0_module_text, mask_cfg=None): + super().__init__() + + act_layer = QuickGELU if quick_gelu else nn.GELU + self.context_length = text_cfg.context_length + + if text_cfg.layers > 0: + self.transformer = Transformer( + width=text_cfg.width, + layers=text_cfg.layers, + heads=text_cfg.heads, + act_layer=act_layer, + ) + else: + self.transformer = None + + self.text_projection = None + if text_cfg.layers > 0: + self.vocab_size = text_cfg.vocab_size + self.token_embedding = nn.Embedding( + text_cfg.vocab_size, text_cfg.width) + self.positional_embedding = nn.Parameter( + torch.empty(self.context_length, text_cfg.width)) + self.ln_final = LayerNorm(text_cfg.width) + if text_cfg.teacher_width > 0: + self.text_projection = nn.Parameter(torch.empty( + text_cfg.width, embed_dim), requires_grad=False) + else: + self.text_projection = nn.Parameter( + torch.empty(text_cfg.width, embed_dim)) + self.register_buffer( + 'attn_mask', self.build_attention_mask(), persistent=False) + else: + self.token_embedding = None + self.init_parameters() + + if l0_module_text: + logging.info('use l0_module_text') + config_mask = Namespace() + config_mask.hidden_size = text_cfg.width + config_mask.intermediate_size = 4 * text_cfg.width + config_mask.num_attention_heads = text_cfg.heads + config_mask.num_hidden_layers = text_cfg.layers + config_mask.sparsity_warmup = mask_cfg.sparsity_warmup + config_mask.sparsity = mask_cfg.sparsity + config_mask.start_sparsity = mask_cfg.start_sparsity + self.l0_module = L0Module(config_mask, lagrangian_warmup=config_mask.sparsity_warmup, start_sparsity=config_mask.start_sparsity, + target_sparsity=config_mask.sparsity, pruning_type=["hidden", "heads", "intermediate"]) + else: + self.l0_module = None + + self.mask = None + + def init_parameters(self): + if self.transformer is not None: + nn.init.normal_(self.token_embedding.weight, std=0.02) + nn.init.normal_(self.positional_embedding, std=0.01) + + proj_std = (self.transformer.width ** -0.5) * \ + ((2 * self.transformer.layers) ** -0.5) + attn_std = self.transformer.width ** -0.5 + fc_std = (2 * self.transformer.width) ** -0.5 + for block in self.transformer.resblocks: + nn.init.normal_(block.attn.in_proj_weight, std=attn_std) + nn.init.normal_(block.attn.out_proj.weight, std=proj_std) + nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) + nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) + + if self.text_projection is not None: + nn.init.normal_(self.text_projection, + std=self.transformer.width ** -0.5) + + def build_attention_mask(self): + # lazily create causal attention mask, with full attention between the vision tokens + # pytorch uses additive attention mask; fill with -inf + mask = torch.empty(self.context_length, self.context_length) + mask.fill_(float("-inf")) + mask.triu_(1) # zero out the lower diagonal + return mask + + def encode_text(self, text, normalized=False, + hidden_z: Optional[torch.Tensor] = None, + heads_z: Optional[torch.Tensor] = None, + mha_z: Optional[torch.Tensor] = None, + intermediate_z: Optional[torch.Tensor] = None, + ffn_z: Optional[torch.Tensor] = None, + embed_dim_z: Optional[torch.Tensor] = None, + ): + self.hidden_z = hidden_z + self.embed_dim_z = embed_dim_z + + text = text.to(self.token_embedding.weight.device) + x = self.token_embedding(text) # [batch_size, n_ctx, d_model] + + x = x + self.positional_embedding + if hidden_z is not None: + x = torch.mul(x, hidden_z) + + x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer(x, attn_mask=self.attn_mask, + hidden_z=hidden_z, + heads_z=heads_z, + mha_z=mha_z, + intermediate_z=intermediate_z, + ffn_z=ffn_z) + x = x.permute(1, 0, 2) # LND -> NLD + x = self.ln_final(x, hidden_z) + + # if hidden_z is not None: + # x = torch.mul(x, hidden_z) + + x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] + + # x.shape = [batch_size, n_ctx, transformer.width] + # take features from the eot embedding (eot_token is the highest number in each sequence) + x = self.get_proj_feature(x) + if embed_dim_z is not None: + x = x.mul(embed_dim_z) + if normalized: + x = F.normalize(x, dim=-1) + + return x + + def get_proj_feature(self, x): + return x @ self.text_projection + + def forward(self, text, normalized=False): + mask = dict() + + if self.l0_module is not None: + mask = self.l0_module.forward() + + self.mask = mask + + return self.encode_text(text, normalized=normalized, **mask) + + def prune(self): + device = self.token_embedding.weight.device + if self.hidden_z is None: + self.hidden_z = torch.ones( + self.text_projection.size(0), device=device) + if self.embed_dim_z is None: + self.embed_dim_z = torch.ones( + self.text_projection.size(1), device=device) + mod = self + self_copy = copy.deepcopy(self) + hidden_r = self.hidden_z > 0 + mod.token_embedding = nn.Embedding( + self_copy.token_embedding.weight.shape[0], hidden_r.sum()) + mod.positional_embedding = nn.Parameter( + torch.empty(self_copy.context_length, hidden_r.sum())) + mod.token_embedding.weight = nn.Parameter( + (self_copy.token_embedding.weight * self_copy.hidden_z.view(1, -1))[:, hidden_r]) + mod.positional_embedding = nn.Parameter( + (self_copy.positional_embedding * self_copy.hidden_z.view(1, -1))[:, hidden_r]) + mod.transformer = self.transformer.prune() + mod.ln_final = self.ln_final.prune() + embed_dim_r = self.embed_dim_z > 0 + mod.text_projection = nn.Parameter( + (self.text_projection * self.hidden_z.view(-1, 1) * self.embed_dim_z.view(1, -1))[hidden_r][:, embed_dim_r]) + return mod + + +class LogitScale(nn.Module): + def __init__(self): + super().__init__() + self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) + + def forward(self, dummy): + return self.logit_scale + + +class FNBlock(nn.Module): + def __init__(self, fn): + super().__init__() + self.fn = fn + + def forward(self, *args, **kwargs): + return self.fn(*args, **kwargs) + + +class FakeDDP(nn.Module): + def __init__(self, module): + super().__init__() + self.module = module + + def forward(self, *args, **kwargs): + return self.module(*args, **kwargs) + + +class CLIPBase(nn.Module): + def __init__(self, image_encoder, text_encoder): + super().__init__() + self._image_encoder = image_encoder + self._text_encoder = text_encoder + + self._logit_scale = LogitScale() + + # autocast context + self.image_autocast = nullcontext + self.text_autocast = nullcontext + self.logit_autocast = nullcontext + + # copy the module without ddp + self._without_ddp = [self._image_encoder, + self._text_encoder, self._logit_scale] + + self.used_ddp = False + + def set_autocast(self, image_autocast, text_autocast, logit_autocast): + self.image_autocast = image_autocast + self.text_autocast = text_autocast + self.logit_autocast = logit_autocast + + @property + def image_encoder_without_ddp(self): + return self._without_ddp[0] + + @image_encoder_without_ddp.setter + def image_encoder_without_ddp(self, encoder): + assert self.used_ddp is False + self._image_encoder = encoder + self._without_ddp[0] = self._image_encoder + + @property + def text_encoder_without_ddp(self): + return self._without_ddp[1] + + @text_encoder_without_ddp.setter + def text_encoder_without_ddp(self, encoder): + assert self.used_ddp is False + self._text_encoder = encoder + self._without_ddp[1] = self._text_encoder + + @property + def logit_scale_without_ddp(self): + return self._without_ddp[2] + + @logit_scale_without_ddp.setter + def logit_scale_without_ddp(self, logit_scale): + assert self.used_ddp is False + self._logit_scale = logit_scale + self._without_ddp[2] = self._logit_scale + + @property + def visual(self): + return self.image_encoder_without_ddp.visual + + @property + def transformer(self): + return self.text_encoder_without_ddp.transformer + + @property + def text_encoder_without_ddp(self): + return self._without_ddp[1] + + @property + def logit_scale_without_ddp(self): + return self._without_ddp[2] + + def get_teacher(self): + return self.teacher[0] + + def use_teacher_image(self): + def teacher_image_encoder_fn(image, normalized=False): + teacher = self.get_teacher() + with torch.no_grad(): + return teacher.encode_image(image, normalized=normalized) + + self._image_encoder = FNBlock(teacher_image_encoder_fn) + + class EmptyVisual(nn.Module): + def __init__(self): + super().__init__() + self.layers = 0 + self._image_encoder.visual = EmptyVisual() + self._without_ddp[0] = self._image_encoder + + def use_teacher_text(self): + def teacher_text_encoder_fn(text, normalized=False): + teacher = self.get_teacher() + with torch.no_grad(): + return teacher.encode_text(text, normalized=normalized) + self._text_encoder = FNBlock(teacher_text_encoder_fn) + + class EmptyTransformer(nn.Module): + def __init__(self): + super().__init__() + self.layers = 0 + self._text_encoder.transformer = EmptyTransformer() + self._text_encoder.token_embedding = None + self._without_ddp[1] = self._text_encoder + + def ddpify(self, ddp_fn): + def _ddp_fn(module): + cnt = sum([p.numel() + for p in module.parameters() if p.requires_grad]) + if cnt > 0: + return ddp_fn(module) + return FakeDDP(module) + self._image_encoder = _ddp_fn(self.image_encoder_without_ddp) + self._text_encoder = _ddp_fn(self.text_encoder_without_ddp) + self._logit_scale = _ddp_fn(self.logit_scale_without_ddp) + + self.used_ddp = True + + def forward(self, image, text, normalized=True): + image_features = text_features = None + if image is not None: + with self.image_autocast(): + image_features = self._image_encoder( + image, normalized=normalized) + if text is not None: + with self.text_autocast(): + text_features = self._text_encoder(text, normalized=normalized) + with self.logit_autocast(): + logit_scale = self._logit_scale(torch.tensor(0)) + return image_features, text_features, logit_scale.exp() + + def encode_image(self, image, normalize=False): + """ + Encode image to features. + Compatible with OpenAI CLIP's encode_image interface. + """ + with self.image_autocast(): + return self._image_encoder(image, normalized=normalize) + + def encode_text(self, text, normalized=False): + with self.text_autocast(): + return self._text_encoder(text, normalized=normalized) + + @property + def logit_scale(self): + return self.logit_scale_without_ddp.logit_scale + + def lock_image_tower(self, unlocked_groups=0, freeze_bn_stats=False): + # lock image tower as per LiT - https://arxiv.org/abs/2111.07991 + self.visual.lock(unlocked_groups=unlocked_groups, freeze_bn_stats=freeze_bn_stats) + + def lock_text_tower(self, unlocked_groups=0, freeze_bn_stats=False): + assert unlocked_groups == 0, 'partial locking not currently supported for this model' + tower = self.text_encoder_without_ddp + for param in tower.parameters(): + param.requires_grad = False + if freeze_bn_stats: + freeze_batch_norm_2d(tower) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + visual = self.image_encoder_without_ddp.visual + transformer = self.text_encoder_without_ddp.transformer + if hasattr(visual, 'set_grad_checkpointing'): + visual.set_grad_checkpointing(enable) + if transformer is not None and hasattr(transformer, 'set_grad_checkpointing'): + transformer.set_grad_checkpointing(enable) + + def image_named_params(self): + return self._image_encoder.named_parameters() + + def text_named_params(self): + return self._text_encoder.named_parameters() + + def joint_named_params(self): + return self._logit_scale.named_parameters() + + def load_state_dict(self, state_dict, strict=True): + state_dict = convert_to_new_checkpoint(state_dict, self.used_ddp) + if not any(k.startswith('_image_encoder') for k in state_dict.keys()): + self.use_teacher_image() + + for m in ['module.', '']: + flag = f'_image_encoder.{m}visual.model.head.0.weight' + if flag in state_dict: + # LN + state_dict[f'_image_encoder.{m}visual.ln_post.weight'] = state_dict.pop( + f'_image_encoder.{m}visual.model.head.0.weight') + state_dict[f'_image_encoder.{m}visual.ln_post.bias'] = state_dict.pop( + f'_image_encoder.{m}visual.model.head.0.bias') + # FC + state_dict[f'_image_encoder.{m}visual.proj'] = state_dict.pop( + f'_image_encoder.{m}visual.model.head.1.weight').T + new_state_dict = state_dict.copy() + for k, v in new_state_dict.items(): + if '.module' in k: + state_dict[k.replace('.module', '')] = v + state_dict.pop(k) + return super().load_state_dict(state_dict, strict=strict) + + +class CLIP(CLIPBase): + def __init__( + self, + embed_dim: int, + vision_cfg: CLIPVisionCfg, + text_cfg: CLIPTextCfg, + quick_gelu: bool = False, + mask_image: bool = False, + mask_text: bool = False, + sparsity_warmup: int = 1000, + sparsity: float = 0.25, + start_sparsity: float = 0.0, + freeze_text: bool = True, + ): + vision_ocfg = None + text_ocfg = None + + if isinstance(vision_cfg, dict): + vision_ocfg = vision_cfg.pop('configs', None) + vision_cfg = CLIPVisionCfg(**vision_cfg) + + if isinstance(text_cfg, dict): + text_ocfg = text_cfg.pop('configs', None) + text_cfg = CLIPTextCfg(**text_cfg) + + mask_cfg = Namespace() + mask_cfg.sparsity_warmup = sparsity_warmup + mask_cfg.sparsity = sparsity + mask_cfg.start_sparsity = start_sparsity + + if vision_ocfg is None: + image_encoder = ImageEncoder(embed_dim, vision_cfg, quick_gelu, + l0_module_image=mask_image, + mask_cfg=mask_cfg) + + if text_ocfg is None: + text_encoder = TextEncoder(embed_dim, text_cfg, quick_gelu, + l0_module_text=mask_text, mask_cfg=mask_cfg) + + super().__init__(image_encoder, text_encoder) + # Freeze text encoder at initialization + if freeze_text: + print(f'Freeze text encoder parameters', flush=True) + self.lock_text_tower() + self.text_encoder_without_ddp.eval() + + def train(self, mode: bool = True): + """Override train() to ensure text encoder stays frozen even in training mode.""" + if not isinstance(mode, bool): + raise ValueError("training mode is expected to be boolean") + self.training = mode + + # Set image encoder to training/eval mode based on mode + if mode: + logging.info(f'========Set image encoder as train mode========') + else: + logging.info(f'========Set image encoder as eval mode========') + self.image_encoder_without_ddp.train(mode) + + # Always keep text encoder in eval mode (frozen) + logging.info(f'========Set text encoder as eval mode (frozen)========') + self.text_encoder_without_ddp.train(False) + + # Ensure text encoder parameters remain frozen + for param in self.text_encoder_without_ddp.parameters(): + param.requires_grad = False + + return self + + def encode_dense(self, image, normalize=False, keep_shape=False, mode="vanilla"): + """ + Encode dense feature map from images. + Compatible with OpenAI CLIP's encode_dense interface. + """ + visual = self.visual + if not isinstance(visual, VisualTransformer): + raise NotImplementedError("encode_dense is only supported for VisualTransformer") + + # Get mask parameters if available + mask = getattr(self.image_encoder_without_ddp, 'mask', None) + if mask is None or not isinstance(mask, dict): + mask = {} + hidden_z = mask.get('hidden_z', None) + heads_z = mask.get('heads_z', None) + mha_z = mask.get('mha_z', None) + intermediate_z = mask.get('intermediate_z', None) + ffn_z = mask.get('ffn_z', None) + embed_dim_z = mask.get('embed_dim_z', None) + + with self.image_autocast(): + if mode in ["qq_vfm_distill", "kk_vfm_distill", "csa_vfm_distill"]: + features, extra_features = visual.encode_dense( + image, keep_shape=keep_shape, mode=mode, + hidden_z=hidden_z, heads_z=heads_z, mha_z=mha_z, + intermediate_z=intermediate_z, ffn_z=ffn_z, embed_dim_z=embed_dim_z) + if normalize: + if keep_shape: + features = F.normalize(features, dim=1) + else: + features = F.normalize(features, dim=-1) + return features, extra_features + else: + features = visual.encode_dense( + image, keep_shape=keep_shape, mode=mode, + hidden_z=hidden_z, heads_z=heads_z, mha_z=mha_z, + intermediate_z=intermediate_z, ffn_z=ffn_z, embed_dim_z=embed_dim_z) + if normalize: + if keep_shape: + features = F.normalize(features, dim=1) + else: + features = F.normalize(features, dim=-1) + return features + + def encode_pseudo_boxes(self, image, normed_boxes, normalize=False, mode="vanilla", size=(1, 1)): + """ + Encode ROI features from images using normalized boxes. + Compatible with OpenAI CLIP's encode_pseudo_boxes interface. + """ + visual = self.visual + if not isinstance(visual, VisualTransformer): + raise NotImplementedError("encode_pseudo_boxes is only supported for VisualTransformer") + + # Get mask parameters if available + mask = getattr(self.image_encoder_without_ddp, 'mask', None) + if mask is None or not isinstance(mask, dict): + mask = {} + hidden_z = mask.get('hidden_z', None) + heads_z = mask.get('heads_z', None) + mha_z = mask.get('mha_z', None) + intermediate_z = mask.get('intermediate_z', None) + ffn_z = mask.get('ffn_z', None) + embed_dim_z = mask.get('embed_dim_z', None) + + with self.image_autocast(): + if mode in ["qq_vfm_distill", "kk_vfm_distill", "csa_vfm_distill"]: + box_features, clip_dense_feats = visual.extract_roi_features( + image, normed_boxes, mode=mode, size=size, + hidden_z=hidden_z, heads_z=heads_z, mha_z=mha_z, + intermediate_z=intermediate_z, ffn_z=ffn_z, embed_dim_z=embed_dim_z) + if normalize: + box_features = F.normalize(box_features, dim=-1) + return box_features, clip_dense_feats + else: + box_features = visual.extract_roi_features( + image, normed_boxes, mode=mode, size=size, + hidden_z=hidden_z, heads_z=heads_z, mha_z=mha_z, + intermediate_z=intermediate_z, ffn_z=ffn_z, embed_dim_z=embed_dim_z) + + if normalize: + box_features = F.normalize(box_features, dim=-1) + return box_features + + def encode_masks(self, image, masks, normalize=True, mask_attn=False, mode="vanilla"): + """ + Encode mask-pooled features from images. + Compatible with OpenAI CLIP's encode_masks interface. + """ + visual = self.visual + if not isinstance(visual, VisualTransformer): + raise NotImplementedError("encode_masks is only supported for VisualTransformer") + + # Get mask parameters if available + mask = getattr(self.image_encoder_without_ddp, 'mask', None) + if mask is None or not isinstance(mask, dict): + mask = {} + hidden_z = mask.get('hidden_z', None) + heads_z = mask.get('heads_z', None) + mha_z = mask.get('mha_z', None) + intermediate_z = mask.get('intermediate_z', None) + ffn_z = mask.get('ffn_z', None) + embed_dim_z = mask.get('embed_dim_z', None) + + with self.image_autocast(): + mask_pooled = visual.mask_pool( + image, masks, mode=mode, + hidden_z=hidden_z, heads_z=heads_z, mha_z=mha_z, + intermediate_z=intermediate_z, ffn_z=ffn_z, embed_dim_z=embed_dim_z) + if normalize: + mask_pooled = F.normalize(mask_pooled, dim=-1) + return mask_pooled + + +def convert_to_new_checkpoint(state_dict, used_ddp=False): + if '_logit_scale.module.logit_scale' in state_dict: + if not used_ddp: + new_checkpoint = dict() + for k, v in state_dict.items(): + sp = k.split('.') + assert sp[1] == 'module', (sp, state_dict.keys()) + k = '.'.join(sp[:1] + sp[2:]) + new_checkpoint[k] = v + state_dict = new_checkpoint + return state_dict + if '_logit_scale.logit_scale' in state_dict: + if used_ddp: + new_checkpoint = dict() + for k, v in state_dict.items(): + sp = k.split('.') + k = '.'.join(sp[:1] + ['module'] + sp[1:]) + new_checkpoint[k] = v + state_dict = new_checkpoint + return state_dict + image_prefix = '_image_encoder.' + text_prefix = '_text_encoder.' + logit_scale_prefix = '_logit_scale.' + if used_ddp: + image_prefix += 'module.' + text_prefix += 'module.' + logit_scale_prefix += 'module.' + new_checkpoint = dict() + if 'module.logit_scale' in state_dict: + # remove the prefix module + state_dict = {k[len('module.'):]: v for k, v in state_dict.items()} + if 'logit_scale' in state_dict: + # old CLIP checkpoint + for k, v in state_dict.items(): + if k.startswith('visual.'): + new_checkpoint[image_prefix + k] = v + elif k == 'logit_scale': + new_checkpoint[logit_scale_prefix + 'logit_scale'] = v + else: + new_checkpoint[text_prefix + k] = v + else: + new_checkpoint = state_dict + return new_checkpoint + + +def convert_weights_to_fp16(model: nn.Module): + """Convert applicable model parameters to fp16""" + + def _convert_weights_to_fp16(l): + if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): + l.weight.data = l.weight.data.half() + if l.bias is not None: + l.bias.data = l.bias.data.half() + + if isinstance(l, (nn.MultiheadAttention, )): + for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]: + tensor = getattr(l, attr) + if tensor is not None: + tensor.data = tensor.data.half() + + for name in ["text_projection", "proj"]: + if hasattr(l, name): + attr = getattr(l, name) + if attr is not None: + attr.data = attr.data.half() + + model.apply(_convert_weights_to_fp16) + + +def build_model_from_openai_state_dict(state_dict: dict): + vit = "visual.proj" in state_dict + + if vit: + vision_width = state_dict["visual.conv1.weight"].shape[0] + vision_layers = len( + [k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")]) + vision_patch_size = state_dict["visual.conv1.weight"].shape[-1] + grid_size = round( + (state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5) + image_size = vision_patch_size * grid_size + else: + counts: list = [ + len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]] + vision_layers = tuple(counts) + vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0] + output_width = round( + (state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5) + vision_patch_size = None + assert output_width ** 2 + \ + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0] + image_size = output_width * 32 + + embed_dim = state_dict["text_projection"].shape[1] + context_length = state_dict["positional_embedding"].shape[0] + vocab_size = state_dict["token_embedding.weight"].shape[0] + transformer_width = state_dict["ln_final.weight"].shape[0] + transformer_heads = transformer_width // 64 + transformer_layers = len(set( + k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks"))) + + vision_cfg = CLIPVisionCfg( + layers=vision_layers, + width=vision_width, + patch_size=vision_patch_size, + image_size=image_size, + ) + text_cfg = CLIPTextCfg( + context_length=context_length, + vocab_size=vocab_size, + width=transformer_width, + heads=transformer_heads, + layers=transformer_layers + ) + model = CLIP( + embed_dim, + vision_cfg=vision_cfg, + text_cfg=text_cfg, + quick_gelu=True, # OpenAI models were trained with QuickGELU + ) + + for key in ["input_resolution", "context_length", "vocab_size"]: + state_dict.pop(key, None) + + convert_weights_to_fp16(model) + model.load_state_dict(state_dict) + return model.eval() + + +def trace_model(model, batch_size=256, device=torch.device('cpu')): + model.eval() + image_size = model.visual.image_size + example_images = torch.ones( + (batch_size, 3, image_size, image_size), device=device) + example_text = torch.zeros( + (batch_size, model.context_length), dtype=torch.int, device=device) + model = torch.jit.trace_module( + model, + inputs=dict( + forward=(example_images, example_text), + encode_text=(example_text,), + encode_image=(example_images,) + )) + model.visual.image_size = image_size + return model + + +def resize_pos_embed(state_dict, model, interpolation: str = 'bicubic', seq_dim=1): + # Rescale the grid of position embeddings when loading from state_dict + old_pos_embed = state_dict.get('visual.positional_embedding', None) + if old_pos_embed is None or not hasattr(model.visual, 'grid_size'): + return + grid_size = to_2tuple(model.visual.grid_size) + # FIXME detect different token configs (ie no class token, or more) + extra_tokens = 1 + new_seq_len = grid_size[0] * grid_size[1] + extra_tokens + if new_seq_len == old_pos_embed.shape[0]: + return + + if extra_tokens: + pos_emb_tok, pos_emb_img = old_pos_embed[: + extra_tokens], old_pos_embed[extra_tokens:] + else: + pos_emb_tok, pos_emb_img = None, old_pos_embed + old_grid_size = to_2tuple(int(math.sqrt(len(pos_emb_img)))) + + logging.info('Resizing position embedding grid-size from %s to %s', + old_grid_size, grid_size) + pos_emb_img = pos_emb_img.reshape( + 1, old_grid_size[0], old_grid_size[1], -1).permute(0, 3, 1, 2) + pos_emb_img = F.interpolate( + pos_emb_img, + size=grid_size, + mode=interpolation, + align_corners=True, + ) + pos_emb_img = pos_emb_img.permute(0, 2, 3, 1).reshape( + 1, grid_size[0] * grid_size[1], -1)[0] + if pos_emb_tok is not None: + new_pos_embed = torch.cat([pos_emb_tok, pos_emb_img], dim=0) + else: + new_pos_embed = pos_emb_img + state_dict['visual.positional_embedding'] = new_pos_embed + + +@torch.no_grad() +def load_pruned_model(model, pruned_state_dict, strict=True): + ''' + A full model loads the pruned state dict. + + Inputs: + model_state_dict: the full model weights + pruned_state_dict: the pruned model weights + ''' + def _copy_to_full_weight(dst, src): + assert dst.ndim == src.ndim, (dst.ndim, src.ndim) + dst.zero_() + dims = src.shape + if len(dims) == 0: + dst.copy_(src) + else: + slices = [slice(0, d) for d in dims] + dst[slices].copy_(src) + + for _ in range(2): + pruned_state_dict = { + k.replace('module.', ''): v for k, v in pruned_state_dict.items()} + + lambda_init_value = 10.0 + model_state_dict = model.state_dict() + head_dim = model.transformer.head_dim + + pruned_state_dict = {k.replace('image_encoder_without_ddp', '_image_encoder'). + replace('text_encoder_without_ddp', '_text_encoder'): v for k, v in pruned_state_dict.items()} + + for name, dst in model_state_dict.items(): + # auto weight inheritance model weight prefix + dst_shape = dst.shape + + # copy weights + if name in pruned_state_dict: + src = pruned_state_dict[name] + if 'attn.in_proj_weight' in name: + # reshape: (3 * num_heads * head_dim, embed_dim) -> (3, num_heads, head_dim, embed_dim) + assert len(src.shape) == 2 + _copy_to_full_weight(dst.view(3, -1, head_dim, dst_shape[-1]), + src.view(3, -1, head_dim, src.shape[-1])) + elif 'attn.in_proj_bias' in name: + # reshape: (3 * num_heads * head_dim,) -> (3, num_heads, head_dim) + assert len(src.shape) == 1 + _copy_to_full_weight(dst.view(3, -1, head_dim), + src.view(3, -1, head_dim)) + else: + _copy_to_full_weight(dst, src) + else: + if '.resblocks.' in name: + # the layer has been pruned. + dst.zero_() + + model_state_dict['_logit_scale.logit_scale'] = pruned_state_dict['_logit_scale.logit_scale'] + + # prune hidden dimensions + encoder_names = ['_image_encoder', '_text_encoder'] + hidden_size_img = pruned_state_dict['_image_encoder.visual.ln_pre.weight'].shape[0] + hidden_size_txt = pruned_state_dict['_text_encoder.positional_embedding'].shape[1] + hidden_sizes = [hidden_size_img, hidden_size_txt] + + for ename, hidden_size in zip(encoder_names, hidden_sizes): + # reset lambda in l0 module + model_state_dict[f'{ename}.l0_module.lambda_1'].fill_( + lambda_init_value) + model_state_dict[f'{ename}.l0_module.lambda_2'].fill_( + lambda_init_value) + # prune the last dimensions + model_state_dict[f'{ename}.l0_module.hidden_loga'][hidden_size:].fill_( + -lambda_init_value) + + def _get_layer_id(name): + return int(name.split('resblocks.')[1].split('.')[0]) + + for ename in encoder_names: + # get the depth of the encoder + encoder_keys = list(k for k in model_state_dict.keys() if ename in k) + encoder_depth = max(_get_layer_id(k) + for k in encoder_keys if 'resblocks' in k) + 1 + pruned_encoder_keys = list( + k for k in pruned_state_dict.keys() if ename in k) + in_proj_weight_shapes = [None for _ in range(encoder_depth)] + mlp_c_fc_shapes = [None for _ in range(encoder_depth)] + for k in pruned_encoder_keys: + if 'in_proj_weight' in k: + d = _get_layer_id(k) + in_proj_weight_shapes[d] = pruned_state_dict[k].shape + elif 'mlp.c_fc.weight' in k: + d = _get_layer_id(k) + mlp_c_fc_shapes[d] = pruned_state_dict[k].shape + + for d in range(encoder_depth): + # set heads_loga + if in_proj_weight_shapes[d] is not None: + num_heads = in_proj_weight_shapes[d][0] // head_dim // 3 + model_state_dict[f'{ename}.l0_module.heads_loga'][d, + num_heads:].fill_(-lambda_init_value) + else: + # all heads have been pruned + model_state_dict[f'{ename}.l0_module.heads_loga'][d, + :].fill_(-lambda_init_value) + + # set intermediate_loga + if mlp_c_fc_shapes[d] is not None: + inter_size = mlp_c_fc_shapes[d][0] + model_state_dict[f'{ename}.l0_module.intermediate_loga'][d, + inter_size:].fill_(-lambda_init_value) + else: + # all intermediate dimensions have been pruned + model_state_dict[f'{ename}.l0_module.intermediate_loga'][d, + :].fill_(-lambda_init_value) + + return model.load_state_dict(model_state_dict, strict=strict) + + +def prune_model(model): + device = next(model.parameters()).device + + with torch.no_grad(): + model.image_encoder_without_ddp.eval() + image_size = (1, 3) + model.image_encoder_without_ddp.visual.image_size + image = torch.randn(image_size, device=device) + model.image_encoder_without_ddp(image) + model.image_encoder_without_ddp = model.image_encoder_without_ddp.prune() + + assert hasattr(model.image_encoder_without_ddp, 'l0_module') + model.image_encoder_without_ddp.l0_module = None + + with torch.no_grad(): + model.text_encoder_without_ddp.eval() + context_length = model.text_encoder_without_ddp.context_length + text = torch.zeros((1, context_length), dtype=torch.long, device=device) + model.text_encoder_without_ddp(text) + model.text_encoder_without_ddp = model.text_encoder_without_ddp.prune() + + assert hasattr(model.text_encoder_without_ddp, 'l0_module') + model.text_encoder_without_ddp.l0_module = None + + return model diff --git a/src/open_clip/tiny_clip/model_configs/RN50.json b/src/open_clip/tiny_clip/model_configs/RN50.json new file mode 100644 index 0000000000000000000000000000000000000000..33aa884d54fee0076c33676831e49d5e1ffcb8f2 --- /dev/null +++ b/src/open_clip/tiny_clip/model_configs/RN50.json @@ -0,0 +1,21 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": [ + 3, + 4, + 6, + 3 + ], + "width": 64, + "patch_size": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/tiny_clip/model_configs/TinyCLIP-ResNet-19M-Text-19M.json b/src/open_clip/tiny_clip/model_configs/TinyCLIP-ResNet-19M-Text-19M.json new file mode 100644 index 0000000000000000000000000000000000000000..0c51ad8bfb5ed23f7ecc2b39c2ffa83140aa1620 --- /dev/null +++ b/src/open_clip/tiny_clip/model_configs/TinyCLIP-ResNet-19M-Text-19M.json @@ -0,0 +1,21 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": [ + 3, + 4, + 6, + 3 + ], + "width": 44, + "patch_size": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 6 + } +} \ No newline at end of file diff --git a/src/open_clip/tiny_clip/model_configs/TinyCLIP-ResNet-30M-Text-29M.json b/src/open_clip/tiny_clip/model_configs/TinyCLIP-ResNet-30M-Text-29M.json new file mode 100644 index 0000000000000000000000000000000000000000..ee1c8e675d083721900ed4be16aab28134a4364b --- /dev/null +++ b/src/open_clip/tiny_clip/model_configs/TinyCLIP-ResNet-30M-Text-29M.json @@ -0,0 +1,21 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": [ + 3, + 4, + 6, + 3 + ], + "width": 56, + "patch_size": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 9 + } +} \ No newline at end of file diff --git a/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-39M-16-Text-19M.json b/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-39M-16-Text-19M.json new file mode 100644 index 0000000000000000000000000000000000000000..cda162a5daab7ff56ea9c158ce4d28f0fcc3d84e --- /dev/null +++ b/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-39M-16-Text-19M.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 6 + } +} diff --git a/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-40M-32-Text-19M.json b/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-40M-32-Text-19M.json new file mode 100644 index 0000000000000000000000000000000000000000..6c61930a2e78c952a6cd4269c6ecc4f0359eeb04 --- /dev/null +++ b/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-40M-32-Text-19M.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 6 + } +} diff --git a/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-61M-32-Text-29M.json b/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-61M-32-Text-29M.json new file mode 100644 index 0000000000000000000000000000000000000000..f58211a2d4ae61c2cd51e6cade812dfedd77af45 --- /dev/null +++ b/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-61M-32-Text-29M.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 640, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 9 + } +} diff --git a/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-8M-16-Text-3M.json b/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-8M-16-Text-3M.json new file mode 100644 index 0000000000000000000000000000000000000000..f73483282a3447901775351a5eed728a8a905fef --- /dev/null +++ b/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-8M-16-Text-3M.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 10, + "width": 256, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 256, + "heads": 4, + "layers": 3 + } +} diff --git a/src/open_clip/tiny_clip/model_configs/TinyCLIP-auto-ViT-22M-32-Text-10M.json b/src/open_clip/tiny_clip/model_configs/TinyCLIP-auto-ViT-22M-32-Text-10M.json new file mode 100644 index 0000000000000000000000000000000000000000..bb568bb9e046b411b60a2ce601dd6de3aa1ca54b --- /dev/null +++ b/src/open_clip/tiny_clip/model_configs/TinyCLIP-auto-ViT-22M-32-Text-10M.json @@ -0,0 +1,19 @@ +{ + "mask_image": true, + "mask_text": true, + + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} diff --git a/src/open_clip/tiny_clip/model_configs/TinyCLIP-auto-ViT-45M-32-Text-18M.json b/src/open_clip/tiny_clip/model_configs/TinyCLIP-auto-ViT-45M-32-Text-18M.json new file mode 100644 index 0000000000000000000000000000000000000000..bb568bb9e046b411b60a2ce601dd6de3aa1ca54b --- /dev/null +++ b/src/open_clip/tiny_clip/model_configs/TinyCLIP-auto-ViT-45M-32-Text-18M.json @@ -0,0 +1,19 @@ +{ + "mask_image": true, + "mask_text": true, + + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} diff --git a/src/open_clip/tiny_clip/model_configs/TinyCLIP-auto-ViT-63M-32-Text-31M.json b/src/open_clip/tiny_clip/model_configs/TinyCLIP-auto-ViT-63M-32-Text-31M.json new file mode 100644 index 0000000000000000000000000000000000000000..bb568bb9e046b411b60a2ce601dd6de3aa1ca54b --- /dev/null +++ b/src/open_clip/tiny_clip/model_configs/TinyCLIP-auto-ViT-63M-32-Text-31M.json @@ -0,0 +1,19 @@ +{ + "mask_image": true, + "mask_text": true, + + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} diff --git a/src/open_clip/tiny_clip/model_configs/ViT-B-16.json b/src/open_clip/tiny_clip/model_configs/ViT-B-16.json new file mode 100644 index 0000000000000000000000000000000000000000..9afeef0fbc807f130f2b2bc65c1dd85abc9eba72 --- /dev/null +++ b/src/open_clip/tiny_clip/model_configs/ViT-B-16.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} diff --git a/src/open_clip/tiny_clip/model_configs/ViT-B-32.json b/src/open_clip/tiny_clip/model_configs/ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..07c8e28eb06fa1813ba932fe4eec668262d1c47f --- /dev/null +++ b/src/open_clip/tiny_clip/model_configs/ViT-B-32.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/src/open_clip/tiny_clip/openai.py b/src/open_clip/tiny_clip/openai.py new file mode 100644 index 0000000000000000000000000000000000000000..23a44e004d7d69148a886d7ddc9a1d298bd332d8 --- /dev/null +++ b/src/open_clip/tiny_clip/openai.py @@ -0,0 +1,138 @@ +""" OpenAI pretrained model functions + +Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. +""" + +import os +import warnings +from typing import Union, List + +import torch + +from .model import build_model_from_openai_state_dict +from .pretrained import get_pretrained_url, list_pretrained_tag_models, download_pretrained_from_url + +__all__ = ["list_openai_models", "load_openai_model"] + + +def list_openai_models() -> List[str]: + """Returns the names of available CLIP models""" + return list_pretrained_tag_models('openai') + + +def load_openai_model( + name: str, + device: Union[str, torch.device] = "cuda" if torch.cuda.is_available( + ) else "cpu", + jit=True, + cache_dir=None, +): + """Load a CLIP model + + Parameters + ---------- + name : str + A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict + device : Union[str, torch.device] + The device to put the loaded model + jit : bool + Whether to load the optimized JIT model (default) or more hackable non-JIT model. + cache_dir : Optional[str] + The directory to cache the downloaded model weights + + Returns + ------- + model : torch.nn.Module + The CLIP model + preprocess : Callable[[PIL.Image], torch.Tensor] + A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input + """ + if get_pretrained_url(name, 'openai'): + model_path = download_pretrained_from_url( + get_pretrained_url(name, 'openai'), cache_dir=cache_dir) + elif os.path.isfile(name): + model_path = name + else: + raise RuntimeError( + f"Model {name} not found; available models = {list_openai_models()}") + + try: + # loading JIT archive + model = torch.jit.load( + model_path, map_location=device if jit else "cpu").eval() + state_dict = None + except RuntimeError: + # loading saved state dict + if jit: + warnings.warn( + f"File {model_path} is not a JIT archive. Loading as a state dict instead") + jit = False + state_dict = torch.load(model_path, map_location="cpu") + + if not jit: + try: + model = build_model_from_openai_state_dict( + state_dict or model.state_dict()).to(device) + except KeyError: + sd = {k[7:]: v for k, v in state_dict["state_dict"].items()} + model = build_model_from_openai_state_dict(sd).to(device) + + if str(device) == "cpu": + model.float() + return model + + # patch the device names + device_holder = torch.jit.trace(lambda: torch.ones( + []).to(torch.device(device)), example_inputs=[]) + device_node = [n for n in device_holder.graph.findAllNodes( + "prim::Constant") if "Device" in repr(n)][-1] + + def patch_device(module): + try: + graphs = [module.graph] if hasattr(module, "graph") else [] + except RuntimeError: + graphs = [] + + if hasattr(module, "forward1"): + graphs.append(module.forward1.graph) + + for graph in graphs: + for node in graph.findAllNodes("prim::Constant"): + if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"): + node.copyAttributes(device_node) + + model.apply(patch_device) + patch_device(model.encode_image) + patch_device(model.encode_text) + + # patch dtype to float32 on CPU + if str(device) == "cpu": + float_holder = torch.jit.trace( + lambda: torch.ones([]).float(), example_inputs=[]) + float_input = list(float_holder.graph.findNode("aten::to").inputs())[1] + float_node = float_input.node() + + def patch_float(module): + try: + graphs = [module.graph] if hasattr(module, "graph") else [] + except RuntimeError: + graphs = [] + + if hasattr(module, "forward1"): + graphs.append(module.forward1.graph) + + for graph in graphs: + for node in graph.findAllNodes("aten::to"): + inputs = list(node.inputs()) + for i in [1, 2]: # dtype can be the second or third argument to aten::to() + if inputs[i].node()["value"] == 5: + inputs[i].node().copyAttributes(float_node) + + model.apply(patch_float) + patch_float(model.encode_image) + patch_float(model.encode_text) + model.float() + + # ensure image_size attr available at consistent location for both jit and non-jit + model.visual.image_size = model.input_resolution.item() + return model diff --git a/src/open_clip/tiny_clip/pretrained.py b/src/open_clip/tiny_clip/pretrained.py new file mode 100644 index 0000000000000000000000000000000000000000..4a89069557b1e1ae32dd5bfc09b9ab8a2062d827 --- /dev/null +++ b/src/open_clip/tiny_clip/pretrained.py @@ -0,0 +1,411 @@ +import hashlib +import os +import time +import urllib +import warnings +from functools import partial +from typing import Dict, Union + +from tqdm import tqdm + +from .version import __version__ + +try: + from huggingface_hub import hf_hub_download + hf_hub_download = partial( + hf_hub_download, library_name="open_clip", library_version=__version__) + _has_hf_hub = True +except ImportError: + hf_hub_download = None + _has_hf_hub = False + + +def _pcfg(url='', hf_hub='', mean=None, std=None): + return dict( + url=url, + hf_hub=hf_hub, + mean=mean, + std=std, + ) + + +_RN50 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-yfcc15m-455df137.pt"), + cc12m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-cc12m-f000538c.pt"), +) + +_RN50_quickgelu = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-yfcc15m-455df137.pt"), + cc12m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-cc12m-f000538c.pt"), +) + +_RN101 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn101-quickgelu-yfcc15m-3e04b30e.pt"), +) + +_RN101_quickgelu = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn101-quickgelu-yfcc15m-3e04b30e.pt"), +) + +_RN50x4 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt"), +) + +_RN50x16 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt"), +) + +_RN50x64 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt"), +) + +_VITB32 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e31-d867053b.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e32-46683a32.pt"), + laion2b_e16=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-laion2b_e16-af8dbd0c.pth"), + laion2b_s34b_b79k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-laion2B-s34B-b79K/') +) + +_VITB32_quickgelu = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e31-d867053b.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e32-46683a32.pt"), +) + +_VITB16 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16-laion400m_e31-00efa78f.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16-laion400m_e32-55e67d44.pt"), + # laion400m_32k=_pcfg( + # url="", + # mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), + # laion400m_64k=_pcfg( + # url="", + # mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), + laion2b_s34b_b88k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-laion2B-s34B-b88K/'), +) + +_VITB16_PLUS_240 = dict( + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16_plus_240-laion400m_e31-8fb26589.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16_plus_240-laion400m_e32-699c4b84.pt"), +) + +_VITL14 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_l_14-laion400m_e31-69988bb6.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_l_14-laion400m_e32-3d133497.pt"), + laion2b_s32b_b82k=_pcfg( + hf_hub='laion/CLIP-ViT-L-14-laion2B-s32B-b82K/', + mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), +) + +_VITL14_336 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt"), +) + +_VITH14 = dict( + laion2b_s32b_b79k=_pcfg(hf_hub='laion/CLIP-ViT-H-14-laion2B-s32B-b79K/'), +) + +_VITg14 = dict( + laion2b_s12b_b42k=_pcfg(hf_hub='laion/CLIP-ViT-g-14-laion2B-s12B-b42K/'), +) + +# TinyCLIP + +# manual weight inheritance + +_TINYCLIP_VIT_39M_16_TEXT_19M = { + "YFCC15M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + ), +} + +_TINYCLIP_VIT_8M_16_TEXT_3M = { + "YFCC15M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-ViT-8M-16-Text-3M-YFCC15M.pt", + ), +} + +_TINYCLIP_RESNET_30M_TEXT_29M = { + "LAION400M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-ResNet-30M-Text-29M-LAION400M.pt", + ), +} + +_TINYCLIP_RESNET_19M_TEXT_19M = { + "LAION400M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-ResNet-19M-Text-19M-LAION400M.pt", + ), +} + +_TINYCLIP_VIT_61M_32_TEXT_29M = { + "LAION400M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-ViT-61M-32-Text-29M-LAION400M.pt", + ), +} + +_TINYCLIP_VIT_40M_32_TEXT_19M = { + "LAION400M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-ViT-40M-32-Text-19M-LAION400M.pt", + ), +} + +# auto weight inheritance + +_TINYCLIP_AUTO_VIT_63M_32_TEXT_31M = { + "LAION400M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-auto-ViT-63M-32-Text-31M-LAION400M.pt", + ), + "LAIONYFCC400M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-auto-ViT-63M-32-Text-31M-LAIONYFCC400M.pt", + ), +} + +_TINYCLIP_AUTO_VIT_45M_32_TEXT_18M = { + "LAION400M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-auto-ViT-45M-32-Text-18M-LAION400M.pt", + ), + "LAIONYFCC400M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-auto-ViT-45M-32-Text-18M-LAIONYFCC400M.pt", + ), +} + +_TINYCLIP_AUTO_VIT_22M_32_TEXT_10M = { + "LAION400M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-auto-ViT-22M-32-Text-10M-LAION400M.pt", + ), +} + +_PRETRAINED = { + "RN50": _RN50, + "RN50-quickgelu": _RN50_quickgelu, + "RN101": _RN101, + "RN101-quickgelu": _RN101_quickgelu, + "RN50x4": _RN50x4, + "RN50x16": _RN50x16, + "RN50x64": _RN50x64, + "ViT-B-32": _VITB32, + "ViT-B-32-quickgelu": _VITB32_quickgelu, + "ViT-B-16": _VITB16, + "ViT-B-16-plus-240": _VITB16_PLUS_240, + "ViT-L-14": _VITL14, + "ViT-L-14-336": _VITL14_336, + "ViT-H-14": _VITH14, + "ViT-g-14": _VITg14, + + "TinyCLIP-ViT-39M-16-Text-19M": _TINYCLIP_VIT_39M_16_TEXT_19M, + "TinyCLIP-ViT-8M-16-Text-3M": _TINYCLIP_VIT_8M_16_TEXT_3M, + "TinyCLIP-ResNet-30M-Text-29M": _TINYCLIP_RESNET_30M_TEXT_29M, + "TinyCLIP-ResNet-19M-Text-19M": _TINYCLIP_RESNET_19M_TEXT_19M, + "TinyCLIP-ViT-61M-32-Text-29M": _TINYCLIP_VIT_61M_32_TEXT_29M, + "TinyCLIP-ViT-40M-32-Text-19M": _TINYCLIP_VIT_40M_32_TEXT_19M, + + "TinyCLIP-auto-ViT-63M-32-Text-31M": _TINYCLIP_AUTO_VIT_63M_32_TEXT_31M, + "TinyCLIP-auto-ViT-45M-32-Text-18M": _TINYCLIP_AUTO_VIT_45M_32_TEXT_18M, + "TinyCLIP-auto-ViT-22M-32-Text-10M": _TINYCLIP_AUTO_VIT_22M_32_TEXT_10M, +} + + +def list_pretrained(as_str: bool = False): + """ returns list of pretrained models + Returns a tuple (model_name, pretrain_tag) by default or 'name:tag' if as_str == True + """ + return [':'.join([k, t]) if as_str else (k, t) for k in _PRETRAINED.keys() for t in _PRETRAINED[k].keys()] + + +def list_pretrained_tag_models(tag: str): + """ return all models having the specified pretrain tag """ + models = [] + for k in _PRETRAINED.keys(): + if tag in _PRETRAINED[k]: + models.append(k) + return models + + +def list_pretrained_model_tags(model: str): + """ return all pretrain tags for the specified model architecture """ + tags = [] + if model in _PRETRAINED: + tags.extend(_PRETRAINED[model].keys()) + return tags + + +def is_pretrained_cfg(model: str, tag: str): + if model not in _PRETRAINED: + return False + return tag.lower() in _PRETRAINED[model] + + +def get_pretrained_cfg(model: str, tag: str): + if model not in _PRETRAINED: + return {} + model_pretrained = _PRETRAINED[model] + if tag in model_pretrained: + return model_pretrained[tag] + return model_pretrained.get(tag.lower(), {}) + + +def get_pretrained_url(model: str, tag: str): + cfg = get_pretrained_cfg(model, tag) + return cfg.get('url', '') + + +def is_local_master(): + return int(os.getenv('LOCAL_RANK', 0)) == 0 + + +def download_pretrained_from_url( + url: str = os.path.expanduser("~/.cache/clip"), + cache_dir: Union[str, None] = None, +): + + if not cache_dir: + cache_dir = os.path.expanduser("~/.cache/clip") + os.makedirs(cache_dir, exist_ok=True) + + filename = os.path.basename(url) + download_target = os.path.join(cache_dir, filename) + if is_local_master(): + for _ in range(20): + try: + return _download_pretrained(url, cache_dir) + except Exception as e: + print(f'Download pretrained: {url}, {cache_dir}, {e}') + time.sleep(10) + else: + while not os.path.exists(download_target): + time.sleep(1) + return download_target + + +def _download_pretrained(url: str, root: str = os.path.expanduser("~/.cache/clip")): + os.makedirs(root, exist_ok=True) + filename = os.path.basename(url) + + if 'openaipublic' in url: + expected_sha256 = url.split("/")[-2] + else: + expected_sha256 = '' + + download_target = os.path.join(root, filename) + + if os.path.exists(download_target) and not os.path.isfile(download_target): + raise RuntimeError( + f"{download_target} exists and is not a regular file") + + if os.path.isfile(download_target): + if expected_sha256: + if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256: + return download_target + else: + warnings.warn( + f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file") + else: + return download_target + + download_target_tmp = download_target + ".tmp" + with urllib.request.urlopen(url) as source, open(download_target_tmp, "wb") as output: + with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True) as loop: + while True: + buffer = source.read(8192) + if not buffer: + break + + output.write(buffer) + loop.update(len(buffer)) + + if expected_sha256 and hashlib.sha256(open(download_target_tmp, "rb").read()).hexdigest() != expected_sha256: + os.remove(download_target_tmp) + raise RuntimeError( + f"Model has been downloaded but the SHA256 checksum does not not match") + + os.rename(download_target_tmp, download_target) + return download_target + + +def has_hf_hub(necessary=False): + if not _has_hf_hub and necessary: + # if no HF Hub module installed, and it is necessary to continue, raise error + raise RuntimeError( + 'Hugging Face hub model specified but package not installed. Run `pip install huggingface_hub`.') + return _has_hf_hub + + +def download_pretrained_from_hf( + model_id: str, + filename: str = 'open_clip_pytorch_model.bin', + revision=None, + cache_dir: Union[str, None] = None, +): + has_hf_hub(True) + cached_file = hf_hub_download( + model_id, filename, revision=revision, cache_dir=cache_dir) + return cached_file + + +def download_pretrained( + cfg: Dict, + force_hf_hub: bool = False, + cache_dir: Union[str, None] = None, +): + target = '' + if not cfg: + return target + + download_url = cfg.get('url', '') + download_hf_hub = cfg.get('hf_hub', '') + if download_hf_hub and force_hf_hub: + # use HF hub even if url exists + download_url = '' + + if download_url: + target = download_pretrained_from_url( + download_url, cache_dir=cache_dir) + elif download_hf_hub: + has_hf_hub(True) + # we assume the hf_hub entries in pretrained config combine model_id + filename in + # 'org/model_name/filename.pt' form. To specify just the model id w/o filename and + # use 'open_clip_pytorch_model.bin' default, there must be a trailing slash 'org/model_name/'. + model_id, filename = os.path.split(download_hf_hub) + if filename: + target = download_pretrained_from_hf( + model_id, filename=filename, cache_dir=cache_dir) + else: + target = download_pretrained_from_hf(model_id, cache_dir=cache_dir) + + return target diff --git a/src/open_clip/tiny_clip/resnet.py b/src/open_clip/tiny_clip/resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..081a794c49da8b0ab61a7dbf88436adb3b9d0c49 --- /dev/null +++ b/src/open_clip/tiny_clip/resnet.py @@ -0,0 +1,187 @@ +import torch +from torch import nn +import torch.nn.functional as F +from collections import OrderedDict + + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__(self, inplanes, planes, stride=1): + super().__init__() + + # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1 + self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False) + self.bn1 = nn.BatchNorm2d(planes) + self.act1 = nn.ReLU(inplace=True) + + self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(planes) + self.act2 = nn.ReLU(inplace=True) + + self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity() + + self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False) + self.bn3 = nn.BatchNorm2d(planes * self.expansion) + self.act3 = nn.ReLU(inplace=True) + + self.downsample = None + self.stride = stride + + if stride > 1 or inplanes != planes * Bottleneck.expansion: + # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1 + self.downsample = nn.Sequential(OrderedDict([ + ("-1", nn.AvgPool2d(stride)), + ("0", nn.Conv2d(inplanes, planes * + self.expansion, 1, stride=1, bias=False)), + ("1", nn.BatchNorm2d(planes * self.expansion)) + ])) + + def forward(self, x: torch.Tensor): + identity = x + + out = self.act1(self.bn1(self.conv1(x))) + out = self.act2(self.bn2(self.conv2(out))) + out = self.avgpool(out) + out = self.bn3(self.conv3(out)) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + out = self.act3(out) + return out + + +class AttentionPool2d(nn.Module): + def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None): + super().__init__() + self.positional_embedding = nn.Parameter(torch.randn( + spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5) + self.k_proj = nn.Linear(embed_dim, embed_dim) + self.q_proj = nn.Linear(embed_dim, embed_dim) + self.v_proj = nn.Linear(embed_dim, embed_dim) + self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim) + self.num_heads = num_heads + + def forward(self, x): + x = x.reshape(x.shape[0], x.shape[1], x.shape[2] + * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC + x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC + x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC + x, _ = F.multi_head_attention_forward( + query=x, key=x, value=x, + embed_dim_to_check=x.shape[-1], + num_heads=self.num_heads, + q_proj_weight=self.q_proj.weight, + k_proj_weight=self.k_proj.weight, + v_proj_weight=self.v_proj.weight, + in_proj_weight=None, + in_proj_bias=torch.cat( + [self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]), + bias_k=None, + bias_v=None, + add_zero_attn=False, + dropout_p=0, + out_proj_weight=self.c_proj.weight, + out_proj_bias=self.c_proj.bias, + use_separate_proj_weight=True, + training=self.training, + need_weights=False + ) + + return x[0] + + +class ModifiedResNet(nn.Module): + """ + A ResNet class that is similar to torchvision's but contains the following changes: + - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool. + - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1 + - The final pooling layer is a QKV attention instead of an average pool + """ + + def __init__(self, layers, output_dim, heads, image_size=224, width=64): + super().__init__() + self.output_dim = output_dim + self.image_size = image_size + + # the 3-layer stem + self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, + stride=2, padding=1, bias=False) + self.bn1 = nn.BatchNorm2d(width // 2) + self.act1 = nn.ReLU(inplace=True) + self.conv2 = nn.Conv2d(width // 2, width // 2, + kernel_size=3, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(width // 2) + self.act2 = nn.ReLU(inplace=True) + self.conv3 = nn.Conv2d( + width // 2, width, kernel_size=3, padding=1, bias=False) + self.bn3 = nn.BatchNorm2d(width) + self.act3 = nn.ReLU(inplace=True) + self.avgpool = nn.AvgPool2d(2) + + # residual layers + self._inplanes = width # this is a *mutable* variable used during construction + self.layer1 = self._make_layer(width, layers[0]) + self.layer2 = self._make_layer(width * 2, layers[1], stride=2) + self.layer3 = self._make_layer(width * 4, layers[2], stride=2) + self.layer4 = self._make_layer(width * 8, layers[3], stride=2) + + embed_dim = width * 32 # the ResNet feature dimension + self.head_dim = embed_dim // heads + self.attnpool = AttentionPool2d( + image_size // 32, embed_dim, heads, output_dim) + + self.init_parameters() + + def _make_layer(self, planes, blocks, stride=1): + layers = [Bottleneck(self._inplanes, planes, stride)] + + self._inplanes = planes * Bottleneck.expansion + for _ in range(1, blocks): + layers.append(Bottleneck(self._inplanes, planes)) + + return nn.Sequential(*layers) + + def init_parameters(self): + if self.attnpool is not None: + std = self.attnpool.c_proj.in_features ** -0.5 + nn.init.normal_(self.attnpool.q_proj.weight, std=std) + nn.init.normal_(self.attnpool.k_proj.weight, std=std) + nn.init.normal_(self.attnpool.v_proj.weight, std=std) + nn.init.normal_(self.attnpool.c_proj.weight, std=std) + + for resnet_block in [self.layer1, self.layer2, self.layer3, self.layer4]: + for name, param in resnet_block.named_parameters(): + if name.endswith("bn3.weight"): + nn.init.zeros_(param) + + def lock(self, unlocked_groups=0, freeze_bn_stats=False): + assert unlocked_groups == 0, 'partial locking not currently supported for this model' + for param in self.parameters(): + param.requires_grad = False + if freeze_bn_stats: + freeze_batch_norm_2d(self) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + # FIXME support for non-transformer + pass + + def stem(self, x): + x = self.act1(self.bn1(self.conv1(x))) + x = self.act2(self.bn2(self.conv2(x))) + x = self.act3(self.bn3(self.conv3(x))) + x = self.avgpool(x) + return x + + def forward(self, x): + x = self.stem(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + x = self.attnpool(x) + + return x diff --git a/src/open_clip/tiny_clip/timm_model.py b/src/open_clip/tiny_clip/timm_model.py new file mode 100644 index 0000000000000000000000000000000000000000..068acfd254e898655719d5e1a09f3a4e1c612ddf --- /dev/null +++ b/src/open_clip/tiny_clip/timm_model.py @@ -0,0 +1,122 @@ +""" timm model adapter + +Wraps timm (https://github.com/rwightman/pytorch-image-models) models for use as a vision tower in CLIP model. +""" +from collections import OrderedDict + +import torch.nn as nn + +try: + import timm + from timm.models.layers import Mlp, to_2tuple +except: + timm = None +try: + from timm.models.layers.attention_pool2d import RotAttentionPool2d + from timm.models.layers.attention_pool2d import AttentionPool2d as AbsAttentionPool2d +except: + pass + +try: + from .utils import freeze_batch_norm_2d +except: + from utils import freeze_batch_norm_2d + + +class TimmModel(nn.Module): + """ timm model adapter + # FIXME this adapter is a work in progress, may change in ways that break weight compat + """ + + def __init__( + self, + model_name, + embed_dim, + image_size=224, + pool='avg', + proj='linear', + drop=0., + pretrained=False): + super().__init__() + if timm is None: + raise RuntimeError("Please `pip install timm` to use timm models.") + + self.image_size = to_2tuple(image_size) + self.trunk = timm.create_model(model_name, pretrained=pretrained) + feat_size = self.trunk.default_cfg.get('pool_size', None) + feature_ndim = 1 if not feat_size else 2 + if pool in ('abs_attn', 'rot_attn'): + assert feature_ndim == 2 + # if attn pooling used, remove both classifier and default pool + self.trunk.reset_classifier(0, global_pool='') + else: + # reset global pool if pool config set, otherwise leave as network default + reset_kwargs = dict(global_pool=pool) if pool else {} + self.trunk.reset_classifier(0, **reset_kwargs) + prev_chs = self.trunk.num_features + + head_layers = OrderedDict() + if pool == 'abs_attn': + head_layers['pool'] = AbsAttentionPool2d( + prev_chs, feat_size=feat_size, out_features=embed_dim) + prev_chs = embed_dim + elif pool == 'rot_attn': + head_layers['pool'] = RotAttentionPool2d( + prev_chs, out_features=embed_dim) + prev_chs = embed_dim + else: + assert proj, 'projection layer needed if non-attention pooling is used.' + + # NOTE attention pool ends with a projection layer, so proj should usually be set to '' if such pooling is used + if proj == 'linear': + head_layers['drop'] = nn.Dropout(drop) + head_layers['proj'] = nn.Linear(prev_chs, embed_dim) + elif proj == 'mlp': + head_layers['mlp'] = Mlp( + prev_chs, 2 * embed_dim, embed_dim, drop=drop) + + self.head = nn.Sequential(head_layers) + + def lock(self, unlocked_groups=0, freeze_bn_stats=False): + """ lock modules + Args: + unlocked_groups (int): leave last n layer groups unlocked (default: 0) + """ + if not unlocked_groups: + # lock full model + for param in self.trunk.parameters(): + param.requires_grad = False + if freeze_bn_stats: + freeze_batch_norm_2d(self.trunk) + else: + # NOTE: partial freeze requires latest timm (master) branch and is subject to change + try: + # FIXME import here until API stable and in an official release + from timm.models.helpers import group_parameters, group_modules + except ImportError: + raise RuntimeError( + 'Please install latest timm `pip install git+https://github.com/rwightman/pytorch-image-models`') + matcher = self.trunk.group_matcher() + gparams = group_parameters(self.trunk, matcher) + max_layer_id = max(gparams.keys()) + max_layer_id = max_layer_id - unlocked_groups + for group_idx in range(max_layer_id + 1): + group = gparams[group_idx] + for param in group: + self.trunk.get_parameter(param).requires_grad = False + if freeze_bn_stats: + gmodules = group_modules(self.trunk, matcher, reverse=True) + gmodules = {k for k, v in gmodules.items() if v <= + max_layer_id} + freeze_batch_norm_2d(self.trunk, gmodules) + + def forward(self, x): + x = self.trunk(x) + x = self.head(x) + return x + + +if __name__ == '__main__': + model = TimmModel('vit_base_patch32_224_in21k', + 512, pool='', pretrained=False) + print(model) diff --git a/src/open_clip/tiny_clip/tokenizer.py b/src/open_clip/tiny_clip/tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..59ad0dce4ba1b86001205e650c38857ed7468cdf --- /dev/null +++ b/src/open_clip/tiny_clip/tokenizer.py @@ -0,0 +1,215 @@ +""" CLIP tokenizer + +Copied from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. +""" +import gzip +import html +import os +from functools import lru_cache +from typing import Union, List + +import ftfy +import regex as re +import torch + + +@lru_cache() +def default_bpe(): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz") + + +@lru_cache() +def bytes_to_unicode(): + """ + Returns list of utf-8 byte and a corresponding list of unicode strings. + The reversible bpe codes work on unicode strings. + This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. + When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. + This is a signficant percentage of your normal, say, 32K bpe vocab. + To avoid that, we want lookup tables between utf-8 bytes and unicode strings. + And avoids mapping to whitespace/control characters the bpe code barfs on. + """ + bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), + ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1)) + cs = bs[:] + n = 0 + for b in range(2**8): + if b not in bs: + bs.append(b) + cs.append(2**8 + n) + n += 1 + cs = [chr(n) for n in cs] + return dict(zip(bs, cs)) + + +def get_pairs(word): + """Return set of symbol pairs in a word. + Word is represented as tuple of symbols (symbols being variable-length strings). + """ + pairs = set() + prev_char = word[0] + for char in word[1:]: + pairs.add((prev_char, char)) + prev_char = char + return pairs + + +def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + +def whitespace_clean(text): + text = re.sub(r'\s+', ' ', text) + text = text.strip() + return text + + +class SimpleTokenizer(object): + def __init__(self, bpe_path: str = default_bpe(), special_tokens=None): + self.byte_encoder = bytes_to_unicode() + self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} + merges = gzip.open(bpe_path).read().decode("utf-8").split('\n') + merges = merges[1:49152 - 256 - 2 + 1] + merges = [tuple(merge.split()) for merge in merges] + vocab = list(bytes_to_unicode().values()) + vocab = vocab + [v + '' for v in vocab] + for merge in merges: + vocab.append(''.join(merge)) + if not special_tokens: + special_tokens = ['', ''] + else: + special_tokens = ['', + ''] + special_tokens + vocab.extend(special_tokens) + self.encoder = dict(zip(vocab, range(len(vocab)))) + self.decoder = {v: k for k, v in self.encoder.items()} + self.bpe_ranks = dict(zip(merges, range(len(merges)))) + self.cache = {t: t for t in special_tokens} + special = "|".join(special_tokens) + self.pat = re.compile( + special + r"""|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE) + + self.vocab_size = len(self.encoder) + self.all_special_ids = [self.encoder[t] for t in special_tokens] + + def bpe(self, token): + if token in self.cache: + return self.cache[token] + word = tuple(token[:-1]) + (token[-1] + '',) + pairs = get_pairs(word) + + if not pairs: + return token + '' + + while True: + bigram = min(pairs, key=lambda pair: self.bpe_ranks.get( + pair, float('inf'))) + if bigram not in self.bpe_ranks: + break + first, second = bigram + new_word = [] + i = 0 + while i < len(word): + try: + j = word.index(first, i) + new_word.extend(word[i:j]) + i = j + except: + new_word.extend(word[i:]) + break + + if word[i] == first and i < len(word) - 1 and word[i + 1] == second: + new_word.append(first + second) + i += 2 + else: + new_word.append(word[i]) + i += 1 + new_word = tuple(new_word) + word = new_word + if len(word) == 1: + break + else: + pairs = get_pairs(word) + word = ' '.join(word) + self.cache[token] = word + return word + + def encode(self, text): + bpe_tokens = [] + text = whitespace_clean(basic_clean(text)).lower() + for token in re.findall(self.pat, text): + token = ''.join(self.byte_encoder[b] + for b in token.encode('utf-8')) + bpe_tokens.extend(self.encoder[bpe_token] + for bpe_token in self.bpe(token).split(' ')) + return bpe_tokens + + def decode(self, tokens): + text = ''.join([self.decoder[token] for token in tokens]) + text = bytearray([self.byte_decoder[c] for c in text]).decode( + 'utf-8', errors="replace").replace('', ' ') + return text + + +_tokenizer = SimpleTokenizer() + + +def tokenize(texts: Union[str, List[str]], context_length: int = 77) -> torch.LongTensor: + """ + Returns the tokenized representation of given input string(s) + + Parameters + ---------- + texts : Union[str, List[str]] + An input string or a list of input strings to tokenize + context_length : int + The context length to use; all CLIP models use 77 as the context length + + Returns + ------- + A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length] + """ + if isinstance(texts, str): + texts = [texts] + + sot_token = _tokenizer.encoder[""] + eot_token = _tokenizer.encoder[""] + all_tokens = [[sot_token] + + _tokenizer.encode(text) + [eot_token] for text in texts] + result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) + + for i, tokens in enumerate(all_tokens): + if len(tokens) > context_length: + tokens = tokens[:context_length] # Truncate + tokens[-1] = eot_token + result[i, :len(tokens)] = torch.tensor(tokens) + + return result + + +class HFTokenizer: + """HuggingFace tokenizer wrapper""" + + def __init__(self, tokenizer_name: str): + from transformers import AutoTokenizer + self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name) + + def save_pretrained(self, dest): + self.tokenizer.save_pretrained(dest) + + def __call__(self, texts: Union[str, List[str]], context_length: int = 77) -> torch.Tensor: + # same cleaning as for default tokenizer, except lowercasing + # adding lower (for case-sensitive tokenizers) will make it more robust but less sensitive to nuance + if isinstance(texts, str): + texts = [texts] + texts = [whitespace_clean(basic_clean(text)) for text in texts] + input_ids = self.tokenizer( + texts, + return_tensors='pt', + max_length=context_length, + padding='max_length', + truncation=True, + ).input_ids + return input_ids diff --git a/src/open_clip/tiny_clip/transform.py b/src/open_clip/tiny_clip/transform.py new file mode 100644 index 0000000000000000000000000000000000000000..f6780eed3cd3ab84cfb1221c567f20a758e88c79 --- /dev/null +++ b/src/open_clip/tiny_clip/transform.py @@ -0,0 +1,123 @@ +from typing import Optional, Sequence, Tuple + +import torch +import torch.nn as nn +import torchvision.transforms.functional as F + +from torchvision.transforms import Normalize, Compose, RandomResizedCrop, InterpolationMode, ToTensor, Resize, \ + CenterCrop + +from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD + + +class ResizeMaxSize(nn.Module): + + def __init__(self, max_size, interpolation=InterpolationMode.BICUBIC, fn='max', fill=0): + super().__init__() + if not isinstance(max_size, int): + raise TypeError(f"Size should be int. Got {type(max_size)}") + self.max_size = max_size + self.interpolation = interpolation + self.fn = min if fn == 'min' else min + self.fill = fill + + def forward(self, img): + if isinstance(img, torch.Tensor): + height, width = img.shape[:2] + else: + width, height = img.size + scale = self.max_size / float(max(height, width)) + if scale != 1.0: + new_size = tuple(round(dim * scale) for dim in (height, width)) + img = F.resize(img, new_size, self.interpolation) + pad_h = self.max_size - new_size[0] + pad_w = self.max_size - new_size[1] + img = F.pad(img, padding=[ + pad_w // 2, pad_h // 2, pad_w - pad_w // 2, pad_h - pad_h // 2], fill=self.fill) + return img + + +class ResizeMaxSize(nn.Module): + + def __init__(self, max_size, interpolation=InterpolationMode.BICUBIC, fn='max', fill=0): + super().__init__() + if not isinstance(max_size, int): + raise TypeError(f"Size should be int. Got {type(max_size)}") + self.max_size = max_size + self.interpolation = interpolation + self.fn = min if fn == 'min' else min + self.fill = fill + + def forward(self, img): + if isinstance(img, torch.Tensor): + height, width = img.shape[:2] + else: + width, height = img.size + scale = self.max_size / float(max(height, width)) + if scale != 1.0: + new_size = tuple(round(dim * scale) for dim in (height, width)) + img = F.resize(img, new_size, self.interpolation) + pad_h = self.max_size - new_size[0] + pad_w = self.max_size - new_size[1] + img = F.pad(img, padding=[ + pad_w // 2, pad_h // 2, pad_w - pad_w // 2, pad_h - pad_h // 2], fill=self.fill) + return img + + +def _convert_to_rgb(image): + return image.convert('RGB') + + +def image_transform( + image_size: int, + is_train: bool, + mean: Optional[Tuple[float, ...]] = None, + std: Optional[Tuple[float, ...]] = None, + resize_longest_max: bool = False, + fill_color: int = 0, + val_keep_ratio: bool = True, +): + + mean = mean or OPENAI_DATASET_MEAN + if not isinstance(mean, (list, tuple)): + mean = (mean,) * 3 + + std = std or OPENAI_DATASET_STD + if not isinstance(std, (list, tuple)): + std = (std,) * 3 + + if isinstance(image_size, (list, tuple)) and image_size[0] == image_size[1]: + # for square size, pass size as int so that Resize() uses aspect preserving shortest edge + image_size = image_size[0] + + normalize = Normalize(mean=mean, std=std) + if is_train: + return Compose([ + RandomResizedCrop(image_size, scale=(0.9, 1.0), + interpolation=InterpolationMode.BICUBIC), + _convert_to_rgb, + ToTensor(), + normalize, + ]) + else: + if resize_longest_max: + transforms = [ + ResizeMaxSize(image_size, fill=fill_color) + ] + else: + if val_keep_ratio: + transforms = [ + Resize(image_size, interpolation=InterpolationMode.BICUBIC), + CenterCrop(image_size), + ] + else: + transforms = [ + Resize((image_size, image_size), + interpolation=InterpolationMode.BICUBIC), + ] + transforms.extend([ + _convert_to_rgb, + ToTensor(), + normalize, + ]) + return Compose(transforms) diff --git a/src/open_clip/tiny_clip/utils.py b/src/open_clip/tiny_clip/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e2ff1fdada90142a35dede8788034b2d9f739b4e --- /dev/null +++ b/src/open_clip/tiny_clip/utils.py @@ -0,0 +1,62 @@ +from itertools import repeat +import collections.abc + +from torch import nn as nn +from torchvision.ops.misc import FrozenBatchNorm2d + + +def freeze_batch_norm_2d(module, module_match={}, name=''): + """ + Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is + itself an instance of either `BatchNorm2d` or `SyncBatchNorm`, it is converted into `FrozenBatchNorm2d` and + returned. Otherwise, the module is walked recursively and submodules are converted in place. + + Args: + module (torch.nn.Module): Any PyTorch module. + module_match (dict): Dictionary of full module names to freeze (all if empty) + name (str): Full module name (prefix) + + Returns: + torch.nn.Module: Resulting module + + Inspired by https://github.com/pytorch/pytorch/blob/a5895f85be0f10212791145bfedc0261d364f103/torch/nn/modules/batchnorm.py#L762 + """ + res = module + is_match = True + if module_match: + is_match = name in module_match + if is_match and isinstance(module, (nn.modules.batchnorm.BatchNorm2d, nn.modules.batchnorm.SyncBatchNorm)): + res = FrozenBatchNorm2d(module.num_features) + res.num_features = module.num_features + res.affine = module.affine + if module.affine: + res.weight.data = module.weight.data.clone().detach() + res.bias.data = module.bias.data.clone().detach() + res.running_mean.data = module.running_mean.data + res.running_var.data = module.running_var.data + res.eps = module.eps + else: + for child_name, child in module.named_children(): + full_child_name = '.'.join( + [name, child_name]) if name else child_name + new_child = freeze_batch_norm_2d( + child, module_match, full_child_name) + if new_child is not child: + res.add_module(child_name, new_child) + return res + + +# From PyTorch internals +def _ntuple(n): + def parse(x): + if isinstance(x, collections.abc.Iterable): + return x + return tuple(repeat(x, n)) + return parse + + +to_1tuple = _ntuple(1) +to_2tuple = _ntuple(2) +to_3tuple = _ntuple(3) +to_4tuple = _ntuple(4) +def to_ntuple(n, x): return _ntuple(n)(x) diff --git a/src/open_clip/tiny_clip/version.py b/src/open_clip/tiny_clip/version.py new file mode 100644 index 0000000000000000000000000000000000000000..668c3446ee12c61dc54e5f9cacdd3b778505118c --- /dev/null +++ b/src/open_clip/tiny_clip/version.py @@ -0,0 +1 @@ +__version__ = '2.0.2' diff --git a/src/open_clip/tiny_clip/weight_inherit.py b/src/open_clip/tiny_clip/weight_inherit.py new file mode 100644 index 0000000000000000000000000000000000000000..b10c968a9922db089df144ea33eb34b204cf3dfb --- /dev/null +++ b/src/open_clip/tiny_clip/weight_inherit.py @@ -0,0 +1,203 @@ +import torch +import re +from collections import defaultdict + + +BLOCKS_PATTERNS = [ + # blocks... + (re.compile(r"visual.blocks\.(\d+)\.(\d+)\.(.*?)$"), 'visual.blocks.{}.{}.{}'), + # TinyViT + (re.compile(r"layers.(\d+)\.blocks\.(\d+)\.(.*?)$"), 'layers.{}.blocks.{}.{}'), + # ResNet + (re.compile(r'visual.layer(\d+).(\d+).(.*?)$'), 'visual.layer{}.{}.{}'), +] + +TRANS_PATTENS = [ + (re.compile(r"resblocks\.(\d+)\.(.*?)$"), 'resblocks.{}.{}'), +] + + +def get_depth_state(state_dict): + state = defaultdict(list) + tstr = None + for k, v in state_dict.items(): + # k is the name of the parameter `v` + for pts in [BLOCKS_PATTERNS, TRANS_PATTENS]: + for pt, s in pts: + match = pt.search(k) + if match is not None: + if tstr is not None: + assert tstr == s, (tstr, s) + else: + tstr = s + groups = match.groups() + if len(groups) == 3: + stage_id, block_id = map(int, groups[:2]) + postname = groups[2] + new_name = tstr.format(stage_id, block_id, postname) + else: + stage_id = 0 + block_id = int(groups[0]) + postname = groups[1] + new_name = tstr.format(block_id, postname) + assert k.endswith(new_name) + prename = k[:-len(new_name)] + stage = state[stage_id] + if block_id >= len(stage): + stage.extend([list()] * (block_id - len(stage) + 1)) + + stage[block_id].append((v, (prename, postname))) + assert tstr is not None + return state, tstr + + +def prune_param(param, shape): + if param.numel() == 1: + return param + # select the front param + sl = [slice(0, s) for s in shape] + param = param[sl] + assert param.shape == shape, (param.shape, shape) + return param + + +def compute_dict_params(state_dict): + params = 0 + for v in state_dict.values(): + params += v.numel() + return params + + +def weight_inherit(student_state_dict, teacher_state_dict, head_dim): + # the function will overwrite student_state_dict + student_depth_state, tstr = get_depth_state(student_state_dict) + teacher_depth_state, tstr2 = get_depth_state(teacher_state_dict) + assert tstr == tstr2 + assert len(student_depth_state) == len(teacher_depth_state) + # remap depth + vised = set() + for si in sorted(student_depth_state.keys()): + student_depth = len(student_depth_state[si]) + teacher_depth = len(teacher_depth_state[si]) + # interval_front + encoder_type = 'interval_front' + step = teacher_depth // max(student_depth, 1) + idx = list(range(0, student_depth * step, step)) + print( + f'sample_method for {encoder_type}: stage: {si} depth: {teacher_depth} -> {student_depth}, idx: {idx}') + + for i, j in enumerate(idx): + for v, (prename, postname) in teacher_depth_state[si][j]: + try: + new_name = prename + tstr.format(si, i, postname) + except: + new_name = '' + if new_name not in student_state_dict: + # transformer + assert si == 0 + new_name = prename + tstr.format(i, postname) + + assert new_name in student_state_dict, new_name + if '.qkv.' in new_name or '.attn.in_proj_' in new_name: + # qkv shape: (out_dim[q, k, v], in_dim) + # out - q - n_heads * head_dim + student_v = student_state_dict[new_name] + student_head = student_v.size(0) // (3 * head_dim) + teacher_head = v.size(0) // (3 * head_dim) + if new_name.endswith('.qkv.weight') or new_name.endswith('.attn.in_proj_weight'): + # (3 * H * head_dim, in_dim) + student_dim = student_v.size(1) + teacher_dim = v.size(1) + student_state_dict[new_name] = v.view(3, teacher_head, head_dim, teacher_dim)[ + :, :student_head, :, :student_dim].reshape(3 * student_head * head_dim, student_dim) + else: + assert new_name.endswith( + '.qkv.bias') or new_name.endswith('.attn.in_proj_bias') + student_state_dict[new_name] = v.view(3, teacher_head, head_dim)[ + :, :student_head].reshape(-1,) + else: + try: + student_state_dict[new_name] = prune_param( + v, student_state_dict[new_name].shape) + except: + print(new_name, v.shape) + raise + vised.add(new_name) + other_param_names = set(student_state_dict.keys()) - vised + print('OTHER Pruned Params:', other_param_names) + for k in other_param_names: + student_state_dict[k] = prune_param( + teacher_state_dict[k], student_state_dict[k].shape) + vised.add(k) + assert vised == set(student_state_dict.keys()), set( + student_state_dict.keys()) - vised + student_num_params = compute_dict_params(student_state_dict) + teacher_num_params = compute_dict_params(teacher_state_dict) + print( + f'Weight Inherit: {teacher_num_params} -> {student_num_params}, {student_num_params / teacher_num_params * 100:.2f}%') + return student_state_dict + + +if __name__ == '__main__': + def weight_inherit_for_tinyvit(): + from tiny_vit import tiny_vit_5m_224, tiny_vit_21m_224 + student_model = tiny_vit_5m_224() + teacher_model = tiny_vit_21m_224() + + student_state_dict = student_model.state_dict() + teacher_state_dict = teacher_model.state_dict() + + weight_inherit(student_state_dict, teacher_state_dict) + + # load inherited weights + student_model.load_state_dict(student_state_dict) + + def weight_inherit_for_open_clip_transformer(): + from open_clip.model import Transformer + student_model = Transformer(width=256, layers=3, heads=256 // 64) + teacher_model = Transformer(width=512, layers=12, heads=512 // 64) + + student_state_dict = student_model.state_dict() + teacher_state_dict = teacher_model.state_dict() + + weight_inherit(student_state_dict, teacher_state_dict, head_dim=64) + + # load inherited weights + student_model.load_state_dict(student_state_dict) + + def weight_inherit_for_open_clip_vision(): + from open_clip.model import ImageEncoder, CLIPVisionCfg + student_cfg = CLIPVisionCfg(layers=3, width=256) + teacher_cfg = CLIPVisionCfg(layers=6, width=512) + student_model = ImageEncoder(256, student_cfg, quick_gelu=False) + teacher_model = ImageEncoder(512, teacher_cfg, quick_gelu=False) + + student_state_dict = student_model.state_dict() + teacher_state_dict = teacher_model.state_dict() + + weight_inherit(student_state_dict, teacher_state_dict, head_dim=64) + + # load inherited weights + student_model.load_state_dict(student_state_dict) + + def weight_inherit_for_open_clip_resnet(): + from open_clip.model import ImageEncoder, CLIPVisionCfg + # layers to identify ResNet + student_cfg = CLIPVisionCfg(image_size=224, layers=[ + 1, 1, 1, 1], width=64, patch_size=None) + teacher_cfg = CLIPVisionCfg(image_size=224, layers=[ + 2, 2, 6, 2], width=64, patch_size=None) + student_model = ImageEncoder(64, student_cfg, quick_gelu=False) + teacher_model = ImageEncoder(64, teacher_cfg, quick_gelu=False) + + student_state_dict = student_model.state_dict() + teacher_state_dict = teacher_model.state_dict() + + weight_inherit(student_state_dict, teacher_state_dict, head_dim=64) + + # weight_inherit_for_tinyvit() + weight_inherit_for_open_clip_transformer() + weight_inherit_for_open_clip_vision() + weight_inherit_for_open_clip_resnet() + + print("OVER") diff --git a/src/open_clip/tokenizer.py b/src/open_clip/tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..23fcfcbcb4ca051ba5bba7520918693001999282 --- /dev/null +++ b/src/open_clip/tokenizer.py @@ -0,0 +1,214 @@ +""" CLIP tokenizer + +Copied from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. +""" +import gzip +import html +import os +from functools import lru_cache +from typing import Union, List + +import ftfy +import regex as re +import torch + +# https://stackoverflow.com/q/62691279 +import os +os.environ["TOKENIZERS_PARALLELISM"] = "false" + + +@lru_cache() +def default_bpe(): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz") + + +@lru_cache() +def bytes_to_unicode(): + """ + Returns list of utf-8 byte and a corresponding list of unicode strings. + The reversible bpe codes work on unicode strings. + This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. + When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. + This is a significant percentage of your normal, say, 32K bpe vocab. + To avoid that, we want lookup tables between utf-8 bytes and unicode strings. + And avoids mapping to whitespace/control characters the bpe code barfs on. + """ + bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1)) + cs = bs[:] + n = 0 + for b in range(2**8): + if b not in bs: + bs.append(b) + cs.append(2**8+n) + n += 1 + cs = [chr(n) for n in cs] + return dict(zip(bs, cs)) + + +def get_pairs(word): + """Return set of symbol pairs in a word. + Word is represented as tuple of symbols (symbols being variable-length strings). + """ + pairs = set() + prev_char = word[0] + for char in word[1:]: + pairs.add((prev_char, char)) + prev_char = char + return pairs + + +def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + +def whitespace_clean(text): + text = re.sub(r'\s+', ' ', text) + text = text.strip() + return text + + +class SimpleTokenizer(object): + def __init__(self, bpe_path: str = default_bpe(), special_tokens=None): + self.byte_encoder = bytes_to_unicode() + self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} + merges = gzip.open(bpe_path).read().decode("utf-8").split('\n') + merges = merges[1:49152-256-2+1] + merges = [tuple(merge.split()) for merge in merges] + vocab = list(bytes_to_unicode().values()) + vocab = vocab + [v+'' for v in vocab] + for merge in merges: + vocab.append(''.join(merge)) + if not special_tokens: + special_tokens = ['', ''] + else: + special_tokens = ['', ''] + special_tokens + vocab.extend(special_tokens) + self.encoder = dict(zip(vocab, range(len(vocab)))) + self.decoder = {v: k for k, v in self.encoder.items()} + self.bpe_ranks = dict(zip(merges, range(len(merges)))) + self.cache = {t:t for t in special_tokens} + special = "|".join(special_tokens) + self.pat = re.compile(special + r"""|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE) + + self.vocab_size = len(self.encoder) + self.all_special_ids = [self.encoder[t] for t in special_tokens] + + def bpe(self, token): + if token in self.cache: + return self.cache[token] + word = tuple(token[:-1]) + ( token[-1] + '',) + pairs = get_pairs(word) + + if not pairs: + return token+'' + + while True: + bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf'))) + if bigram not in self.bpe_ranks: + break + first, second = bigram + new_word = [] + i = 0 + while i < len(word): + try: + j = word.index(first, i) + new_word.extend(word[i:j]) + i = j + except: + new_word.extend(word[i:]) + break + + if word[i] == first and i < len(word)-1 and word[i+1] == second: + new_word.append(first+second) + i += 2 + else: + new_word.append(word[i]) + i += 1 + new_word = tuple(new_word) + word = new_word + if len(word) == 1: + break + else: + pairs = get_pairs(word) + word = ' '.join(word) + self.cache[token] = word + return word + + def encode(self, text): + bpe_tokens = [] + text = whitespace_clean(basic_clean(text)).lower() + for token in re.findall(self.pat, text): + token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8')) + bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' ')) + return bpe_tokens + + def decode(self, tokens): + text = ''.join([self.decoder[token] for token in tokens]) + text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('', ' ') + return text + + +_tokenizer = SimpleTokenizer() + +def decode(output_ids: torch.Tensor): + output_ids = output_ids.cpu().numpy() + return _tokenizer.decode(output_ids) + +def tokenize(texts: Union[str, List[str]], context_length: int = 77) -> torch.LongTensor: + """ + Returns the tokenized representation of given input string(s) + + Parameters + ---------- + texts : Union[str, List[str]] + An input string or a list of input strings to tokenize + context_length : int + The context length to use; all CLIP models use 77 as the context length + + Returns + ------- + A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length] + """ + if isinstance(texts, str): + texts = [texts] + + sot_token = _tokenizer.encoder[""] + eot_token = _tokenizer.encoder[""] + all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts] + result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) + + for i, tokens in enumerate(all_tokens): + if len(tokens) > context_length: + tokens = tokens[:context_length] # Truncate + tokens[-1] = eot_token + result[i, :len(tokens)] = torch.tensor(tokens) + + return result + + +class HFTokenizer: + """HuggingFace tokenizer wrapper""" + + def __init__(self, tokenizer_name: str): + from transformers import AutoTokenizer + self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name) + + def save_pretrained(self, dest): + self.tokenizer.save_pretrained(dest) + + def __call__(self, texts: Union[str, List[str]], context_length: int = 77) -> torch.Tensor: + # same cleaning as for default tokenizer, except lowercasing + # adding lower (for case-sensitive tokenizers) will make it more robust but less sensitive to nuance + if isinstance(texts, str): + texts = [texts] + texts = [whitespace_clean(basic_clean(text)) for text in texts] + input_ids = self.tokenizer( + texts, + return_tensors='pt', + max_length=context_length, + padding='max_length', + truncation=True, + ).input_ids + return input_ids diff --git a/src/open_clip/transform.py b/src/open_clip/transform.py new file mode 100644 index 0000000000000000000000000000000000000000..887e37328e6b24b1137a05ae337bb9a0796f1358 --- /dev/null +++ b/src/open_clip/transform.py @@ -0,0 +1,321 @@ +import warnings +from dataclasses import dataclass, asdict +from typing import Any, Dict, Optional, Sequence, Tuple, Union + +import torch +import torch.nn as nn +import torchvision.transforms.functional as F +from torchvision.transforms.v2 import ScaleJitter +from torchvision.transforms import Normalize, Compose, RandomResizedCrop, InterpolationMode, ToTensor, Resize, \ + CenterCrop +from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD +import numpy as np +@dataclass +class AugmentationCfg: + scale: Tuple[float, float] = (0.9, 1.0) + ratio: Optional[Tuple[float, float]] = None + color_jitter: Optional[Union[float, Tuple[float, float, float]]] = None + interpolation: Optional[str] = None + re_prob: Optional[float] = None + re_count: Optional[int] = None + use_timm: bool = False + + +class ResizeMaxSize(nn.Module): + + def __init__(self, max_size, interpolation=InterpolationMode.BICUBIC, fn='max', fill=0): + super().__init__() + if not isinstance(max_size, int): + raise TypeError(f"Size should be int. Got {type(max_size)}") + self.max_size = max_size + self.interpolation = interpolation + self.fn = min if fn == 'min' else min + self.fill = fill + + def forward(self, img): + if isinstance(img, torch.Tensor): + height, width = img.shape[:2] + else: + width, height = img.size + scale = self.max_size / float(max(height, width)) + new_size = tuple(round(dim * scale) for dim in (height, width)) + img = F.resize(img, new_size, self.interpolation) + pad_h = self.max_size - new_size[0] + pad_w = self.max_size - new_size[1] + img = F.pad(img, padding=[pad_w // 2, pad_h // 2, pad_w - pad_w // 2, pad_h - pad_h // 2], fill=self.fill) + + return img + + +def _convert_to_rgb(image): + return image.convert('RGB') + + +def image_transform( + image_size: int, + is_train: bool, + mean: Optional[Tuple[float, ...]] = None, + std: Optional[Tuple[float, ...]] = None, + resize_longest_max: bool = False, + fill_color: int = 0, + aug_cfg: Optional[Union[Dict[str, Any], AugmentationCfg]] = None, +): + mean = mean or OPENAI_DATASET_MEAN + if not isinstance(mean, (list, tuple)): + mean = (mean,) * 3 + + std = std or OPENAI_DATASET_STD + if not isinstance(std, (list, tuple)): + std = (std,) * 3 + + if isinstance(image_size, (list, tuple)) and image_size[0] == image_size[1]: + # for square size, pass size as int so that Resize() uses aspect preserving shortest edge + image_size = image_size[0] + + if isinstance(aug_cfg, dict): + aug_cfg = AugmentationCfg(**aug_cfg) + else: + aug_cfg = aug_cfg or AugmentationCfg() + normalize = Normalize(mean=mean, std=std) + if is_train: + aug_cfg_dict = {k: v for k, v in asdict(aug_cfg).items() if v is not None} + use_timm = aug_cfg_dict.pop('use_timm', False) + if use_timm: + from timm.data import create_transform # timm can still be optional + if isinstance(image_size, (tuple, list)): + assert len(image_size) >= 2 + input_size = (3,) + image_size[-2:] + else: + input_size = (3, image_size, image_size) + # by default, timm aug randomly alternates bicubic & bilinear for better robustness at inference time + aug_cfg_dict.setdefault('interpolation', 'random') + aug_cfg_dict.setdefault('color_jitter', None) # disable by default + train_transform = create_transform( + input_size=input_size, + is_training=True, + hflip=0., + mean=mean, + std=std, + re_mode='pixel', + **aug_cfg_dict, + ) + else: + train_transform = Compose([ + RandomResizedCrop( + image_size, + scale=aug_cfg_dict.pop('scale'), + interpolation=InterpolationMode.BICUBIC, + ), + _convert_to_rgb, + ToTensor(), + normalize, + ]) + if aug_cfg_dict: + warnings.warn(f'Unused augmentation cfg items, specify `use_timm` to use ({list(aug_cfg_dict.keys())}).') + return train_transform + else: + if resize_longest_max: + transforms = [ + ResizeMaxSize(image_size, fill=fill_color) + ] + else: + transforms = [ + Resize(image_size, interpolation=InterpolationMode.BICUBIC), + CenterCrop(image_size), + ] + transforms.extend([ + _convert_to_rgb, + ToTensor(), + normalize, + ]) + return Compose(transforms) + + +def det_image_transform( + image_size: int, + is_train: bool, + mean: Optional[Tuple[float, ...]] = None, + std: Optional[Tuple[float, ...]] = None, + fill_color: int = 0, +): + mean = mean or OPENAI_DATASET_MEAN + if not isinstance(mean, (list, tuple)): + mean = (mean,) * 3 + + std = std or OPENAI_DATASET_STD + if not isinstance(std, (list, tuple)): + std = (std,) * 3 + + if isinstance(image_size, (list, tuple)) and image_size[0] == image_size[1]: + # for square size, pass size as int so that Resize() uses aspect preserving shortest edge + image_size = image_size[0] + + normalize = Normalize(mean=mean, std=std) + if is_train: + # ! new add feature + transforms = [ + Resize(image_size, interpolation=InterpolationMode.BICUBIC), + CenterCrop(image_size), + _convert_to_rgb, + ToTensor(), + normalize, + ] + return Compose(transforms) + # ! new add feature + else: + transforms = [ + ResizeLongest(image_size, fill=fill_color), + _convert_to_rgb, + ToTensor(), + normalize, + ] + return Compose(transforms) + + +class ResizeLongest(nn.Module): + def __init__(self, max_size, interpolation=InterpolationMode.BICUBIC, fill=0): + super().__init__() + if not isinstance(max_size, int): + raise TypeError(f"Size should be int. Got {type(max_size)}") + self.max_size = max_size + self.interpolation = interpolation + self.fill = fill + + def forward(self, img): + if isinstance(img, torch.Tensor): + height, width = img.shape[1:] + else: + width, height = img.size + scale = self.max_size / float(max(height, width)) + new_height, new_width = round(height * scale), round(width * scale) + img = F.resize(img, [new_height, new_width], self.interpolation, antialias=None) + pad_h = self.max_size - new_height + pad_w = self.max_size - new_width + img = F.pad(img, padding=[0, 0, pad_w, pad_h], fill=self.fill) + return img + + +def get_scale(img, new_image): + if isinstance(img, torch.Tensor): + height, width = new_image.shape[-2:] + else: + width, height = img.size + + if isinstance(new_image, torch.Tensor): + new_height, new_width = new_image.shape[-2:] + else: + new_width, new_height = new_image.size + + scale = min(new_height/height, new_width/width) + + return scale + + + +class FixedSizeCrop: + """ + If `crop_size` is smaller than the input image size, then it uses a random crop of + the crop size. If `crop_size` is larger than the input image size, then it pads + the right and the bottom of the image to the crop size if `pad` is True, otherwise + it returns the smaller image. + """ + def __init__(self, crop_size, pad=True, pad_value=128.0, seg_pad_value=255,return_param=False): + """ + Args: + crop_size: target image (height, width). + pad: if True, will pad images smaller than `crop_size` up to `crop_size` + pad_value: the padding value to the image. + seg_pad_value: the padding value to the segmentation mask. + """ + self.crop_size = crop_size # (height, width) + self.pad = pad + self.pad_value = pad_value + self.seg_pad_value = seg_pad_value + self.return_param=return_param + + def _get_random_crop_params(self, img, output_size): + """ Get parameters for a random crop. """ + w, h = img.size # PIL image size is (width, height) + crop_h, crop_w = output_size + # If image is larger than the crop size, calculate the random crop parameters + if h > crop_h and w > crop_w: + top = np.random.randint(0, h - crop_h + 1) + left = np.random.randint(0, w - crop_w + 1) + else: + # If the image is smaller, no crop is needed (padding will be applied later if required) + top = 0 + left = 0 + return top, left, crop_h, crop_w + + def _pad_if_needed(self, img): + """ Pad the image on the right and bottom if its size is smaller than `crop_size`. """ + w, h = img.size # PIL image size is (width, height) + crop_h, crop_w = self.crop_size + # Calculate required padding for height and width + pad_h = max(crop_h - h, 0) + pad_w = max(crop_w - w, 0) + # Only pad if necessary + if pad_h > 0 or pad_w > 0: + # Padding order: [left, top, right, bottom] + img = F.pad(img, padding=[0, 0, pad_w, pad_h], fill=self.pad_value) + return img + + def __call__(self, img, param=None): + """ Apply the crop or padding to the image. """ + # First, apply padding if needed (if the image is smaller than the crop size) + img = self._pad_if_needed(img) + # Now, the image size is guaranteed to be at least as large as the target crop size + w, h = img.size + if param: + h_scale, w_scale = param + crop_h, crop_w = self.crop_size + top, left=int(h_scale*h),int(w_scale*w) + + else: + top, left, crop_h, crop_w = self._get_random_crop_params(img, self.crop_size) + # Apply random crop + img = F.crop(img, top=top, left=left, height=crop_h, width=crop_w) + if self.return_param: + return img, (top/h,left/w) + else: + return img + +class ImgRescale: + def __init__(self, + max_size: Optional[Union[int, Tuple[int, int]]] = (1024, 1024), + interpolation=InterpolationMode.BICUBIC): + """ + Args: + max_size (Union[int, Tuple[int, int]]): 最大宽度和高度。如果是整数,则表示正方形的最大尺寸。 + interpolation (str): 插值方式,默认为 'bicubic'。 + """ + if isinstance(max_size, int): + self.max_size = (max_size, max_size) # 如果提供的是单个整数,则假定宽高相同 + else: + self.max_size = max_size # 否则使用提供的 (height, width) + self.interpolation = interpolation + + def __call__(self, img): + """ + Args: + img (PIL.Image or torch.Tensor): 输入的图像。 + + Returns: + img: 调整大小后的图像。 + """ + # 获取图像的宽高 + if isinstance(img, torch.Tensor): + height, width = img.shape[-2:] # 如果是 Tensor,形状为 (C, H, W) + else: + width, height = img.size # 如果是 PIL.Image,获取图像的宽高 + max_long_edge = max(self.max_size) + max_short_edge = min(self.max_size) + scale_factor = min(max_long_edge / max(height, width), + max_short_edge / min(height, width)) + # 计算新的尺寸 + new_size = (round(height * scale_factor), round(width * scale_factor)) + + # 调整图像大小 + img = F.resize(img, new_size, self.interpolation) + + return img diff --git a/src/open_clip/transformer.py b/src/open_clip/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..0d37d7b0db88ed54f1f300133e7ba0a497b94fdb --- /dev/null +++ b/src/open_clip/transformer.py @@ -0,0 +1,881 @@ +import logging +from collections import OrderedDict +import math +from typing import Callable, Optional, Sequence, Tuple +import torch +from torch import nn +from torch.nn import functional as F +from torch.utils.checkpoint import checkpoint +from torchvision.ops import roi_align +from .utils import to_2tuple + + +class LayerNormFp32(nn.LayerNorm): + """Subclass torch's LayerNorm to handle fp16 (by casting to float32 and back).""" + + def forward(self, x: torch.Tensor): + orig_type = x.dtype + x = F.layer_norm(x.to(torch.float32), self.normalized_shape, self.weight, self.bias, self.eps) + return x.to(orig_type) + + +class LayerNorm(nn.LayerNorm): + """Subclass torch's LayerNorm (with cast back to input dtype).""" + + def forward(self, x: torch.Tensor): + orig_type = x.dtype + x = F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps) + return x.to(orig_type) + + +class QuickGELU(nn.Module): + # NOTE This is slower than nn.GELU or nn.SiLU and uses more GPU memory + def forward(self, x: torch.Tensor): + return x * torch.sigmoid(1.702 * x) + + +class LayerScale(nn.Module): + def __init__(self, dim, init_values=1e-5, inplace=False): + super().__init__() + self.inplace = inplace + self.gamma = nn.Parameter(init_values * torch.ones(dim)) + + def forward(self, x): + return x.mul_(self.gamma) if self.inplace else x * self.gamma + + +class PatchDropout(nn.Module): + """ + https://arxiv.org/abs/2212.00794 + """ + + def __init__(self, prob, exclude_first_token=True): + super().__init__() + assert 0 <= prob < 1. + self.prob = prob + self.exclude_first_token = exclude_first_token # exclude CLS token + + def forward(self, x): + if not self.training or self.prob == 0.: + return x + + if self.exclude_first_token: + cls_tokens, x = x[:, :1], x[:, 1:] + else: + cls_tokens = torch.jit.annotate(torch.Tensor, x[:, :1]) + + batch = x.size()[0] + num_tokens = x.size()[1] + + batch_indices = torch.arange(batch) + batch_indices = batch_indices[..., None] + + keep_prob = 1 - self.prob + num_patches_keep = max(1, int(num_tokens * keep_prob)) + + rand = torch.randn(batch, num_tokens) + patch_indices_keep = rand.topk(num_patches_keep, dim=-1).indices + + x = x[batch_indices, patch_indices_keep] + + if self.exclude_first_token: + x = torch.cat((cls_tokens, x), dim=1) + + return x + + +class Attention(nn.Module): + def __init__( + self, + dim, + num_heads=8, + qkv_bias=True, + scaled_cosine=False, + scale_heads=False, + logit_scale_max=math.log(1. / 0.01), + attn_drop=0., + proj_drop=0. + ): + super().__init__() + self.scaled_cosine = scaled_cosine + self.scale_heads = scale_heads + assert dim % num_heads == 0, 'dim should be divisible by num_heads' + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.scale = self.head_dim ** -0.5 + self.logit_scale_max = logit_scale_max + + # keeping in_proj in this form (instead of nn.Linear) to match weight scheme of original + self.in_proj_weight = nn.Parameter(torch.randn((dim * 3, dim)) * self.scale) + if qkv_bias: + self.in_proj_bias = nn.Parameter(torch.zeros(dim * 3)) + else: + self.in_proj_bias = None + + if self.scaled_cosine: + self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1)))) + else: + self.logit_scale = None + self.attn_drop = nn.Dropout(attn_drop) + if self.scale_heads: + self.head_scale = nn.Parameter(torch.ones((num_heads, 1, 1))) + else: + self.head_scale = None + self.out_proj = nn.Linear(dim, dim) + self.out_drop = nn.Dropout(proj_drop) + + def forward(self, x, attn_mask: Optional[torch.Tensor] = None): + L, N, C = x.shape + q, k, v = F.linear(x, self.in_proj_weight, self.in_proj_bias).chunk(3, dim=-1) + q = q.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1) + k = k.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1) + v = v.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1) + + if self.logit_scale is not None: + attn = torch.bmm(F.normalize(q, dim=-1), F.normalize(k, dim=-1).transpose(-1, -2)) + logit_scale = torch.clamp(self.logit_scale, max=self.logit_scale_max).exp() + attn = attn.view(N, self.num_heads, L, L) * logit_scale + attn = attn.view(-1, L, L) + else: + q = q * self.scale + attn = torch.bmm(q, k.transpose(-1, -2)) + + if attn_mask is not None: + if attn_mask.dtype == torch.bool: + new_attn_mask = torch.zeros_like(attn_mask, dtype=q.dtype) + new_attn_mask.masked_fill_(attn_mask, float("-inf")) + attn_mask = new_attn_mask + attn += attn_mask + + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + + x = torch.bmm(attn, v) + if self.head_scale is not None: + x = x.view(N, self.num_heads, L, C) * self.head_scale + x = x.view(-1, L, C) + x = x.transpose(0, 1).reshape(L, N, C) + x = self.out_proj(x) + x = self.out_drop(x) + return x + + +class AttentionalPooler(nn.Module): + def __init__( + self, + d_model: int, + context_dim: int, + n_head: int = 8, + n_queries: int = 256, + norm_layer: Callable = LayerNorm + ): + super().__init__() + self.query = nn.Parameter(torch.randn(n_queries, d_model)) + self.attn = nn.MultiheadAttention(d_model, n_head, kdim=context_dim, vdim=context_dim) + self.ln_q = norm_layer(d_model) + self.ln_k = norm_layer(context_dim) + + def forward(self, x: torch.Tensor): + x = self.ln_k(x).permute(1, 0, 2) # NLD -> LND + N = x.shape[1] + q = self.ln_q(self.query) + out = self.attn(self._repeat(q, N), x, x, need_weights=False)[0] + return out.permute(1, 0, 2) # LND -> NLD + + def _repeat(self, query, N: int): + return query.unsqueeze(1).repeat(1, N, 1) + + +class ResidualAttentionBlock(nn.Module): + def __init__( + self, + d_model: int, + n_head: int, + mlp_ratio: float = 4.0, + ls_init_value: float = None, + act_layer: Callable = nn.GELU, + norm_layer: Callable = LayerNorm, + is_cross_attention: bool = False, + ): + super().__init__() + + self.ln_1 = norm_layer(d_model) + self.attn = nn.MultiheadAttention(d_model, n_head) + self.ls_1 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity() + if is_cross_attention: + self.ln_1_kv = norm_layer(d_model) + + self.ln_2 = norm_layer(d_model) + mlp_width = int(d_model * mlp_ratio) + self.mlp = nn.Sequential(OrderedDict([ + ("c_fc", nn.Linear(d_model, mlp_width)), + ("gelu", act_layer()), + ("c_proj", nn.Linear(mlp_width, d_model)) + ])) + self.ls_2 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity() + + def attention( + self, + q_x: torch.Tensor, + k_x: Optional[torch.Tensor] = None, + v_x: Optional[torch.Tensor] = None, + attn_mask: Optional[torch.Tensor] = None, + ): + k_x = k_x if k_x is not None else q_x + v_x = v_x if v_x is not None else q_x + + # attn_mask = attn_mask.to(q_x.dtype) if attn_mask is not None else None + return self.attn( + q_x, k_x, v_x, need_weights=False, attn_mask=attn_mask + )[0] + + def forward( + self, + q_x: torch.Tensor, + k_x: Optional[torch.Tensor] = None, + v_x: Optional[torch.Tensor] = None, + attn_mask: Optional[torch.Tensor] = None, + ): + k_x = self.ln_1_kv(k_x) if hasattr(self, "ln_1_kv") and k_x is not None else None + v_x = self.ln_1_kv(v_x) if hasattr(self, "ln_1_kv") and v_x is not None else None + + x = q_x + self.ls_1(self.attention(q_x=self.ln_1(q_x), k_x=k_x, v_x=v_x, attn_mask=attn_mask)) + x = x + self.ls_2(self.mlp(self.ln_2(x))) + return x + + +class ResidualAttentionBlockV2(ResidualAttentionBlock): + def proj_without_attn(self, value): + attn_module = self.attn + value = F.linear(value, attn_module.in_proj_weight, + bias=attn_module.in_proj_bias)[..., -attn_module.embed_dim:] + value = F.linear(value, attn_module.out_proj.weight, + bias=attn_module.out_proj.bias) + + return value + + def forward_without_attn(self, q_x): + x = q_x + self.ls_1(self.proj_without_attn(value=self.ln_1(q_x))) # use the maskclip-zhou style + x = x + self.ls_2(self.mlp(self.ln_2(x))) + return x + + def csa_attn(self, x, mode): + x = self.ln_1(x) + attn_layer = self.attn + num_heads = attn_layer.num_heads + _, bsz, embed_dim = x.size() + head_dim = embed_dim // num_heads + scale = head_dim ** -0.5 + q, k, v = F.linear(x, attn_layer.in_proj_weight, attn_layer.in_proj_bias).chunk(3, dim=-1) + q = q.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) + k = k.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) + v = v.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) + q_attn = torch.bmm(q, q.transpose(1, 2)) * scale + k_attn = torch.bmm(k, k.transpose(1, 2)) * scale + attn_weights = F.softmax(q_attn, dim=-1) + F.softmax(k_attn, dim=-1) + attn_output = torch.bmm(attn_weights, v) + attn_output = attn_output.transpose(0, 1).contiguous().view(-1, bsz, embed_dim) + attn_output = attn_layer.out_proj(attn_output) + attn_output=self.ls_1(attn_output) + if "distill" in mode: + return attn_output, (q[:, 1:], k[:, 1:]) + else: + return attn_output + + def ss_attn(self, x, mode): + x = self.ln_1(x) + attn_layer = self.attn + num_heads = attn_layer.num_heads + _, bsz, embed_dim = x.size() + head_dim = embed_dim // num_heads + scale = head_dim ** -0.5 + q, k, v = F.linear(x, attn_layer.in_proj_weight, attn_layer.in_proj_bias).chunk(3, dim=-1) + q = q.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) + k = k.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) + v = v.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) + if mode=="qq" or mode=="qq_vfm_distill": + q_attn = torch.bmm(q, q.transpose(1, 2)) * scale + attn_weights = F.softmax(q_attn, dim=-1) + elif mode=="kk" or mode=="kk_vfm_distill": + k_attn = torch.bmm(k, k.transpose(1, 2)) * scale + attn_weights = F.softmax(k_attn, dim=-1) + else: + raise NotImplementedError(f"The mode '{mode}' is not implemented.") + attn_output = torch.bmm(attn_weights, v) + attn_output = attn_output.transpose(0, 1).contiguous().view(-1, bsz, embed_dim) + attn_output = attn_layer.out_proj(attn_output) + attn_output=self.ls_1(attn_output) + if mode=='qq_vfm_distill': + return attn_output, q[:, 1:] + elif mode == 'kk_vfm_distill': + return attn_output, k[:, 1:] + else: + return attn_output + +class Transformer(nn.Module): + def __init__( + self, + width: int, + layers: int, + heads: int, + mlp_ratio: float = 4.0, + ls_init_value: float = None, + act_layer: Callable = nn.GELU, + norm_layer: Callable = LayerNorm, + ): + super().__init__() + self.width = width + self.layers = layers + self.grad_checkpointing = False + + self.resblocks = nn.ModuleList([ + ResidualAttentionBlockV2( + width, heads, mlp_ratio, ls_init_value=ls_init_value, act_layer=act_layer, norm_layer=norm_layer) + for _ in range(layers) + ]) + + def get_cast_dtype(self) -> torch.dtype: + return self.resblocks[0].mlp.c_fc.weight.dtype + + def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None): + for r in self.resblocks: + if self.grad_checkpointing and not torch.jit.is_scripting(): + # TODO: handle kwargs https://github.com/pytorch/pytorch/issues/79887#issuecomment-1161758372 + x = checkpoint(r, x, None, None, attn_mask) + else: + x = r(x, attn_mask=attn_mask) + return x + + def extract_feature_map(self, x, return_forward=False,mode='maskclip'): + for i in range(self.layers - 1): + x = self.resblocks[i](x) + if mode=='maskclip': + x = self.resblocks[-1].forward_without_attn(x) + elif mode in ['csa','csa_vfm_distill']: + x = self.resblocks[-1].csa_attn(x,mode) + elif mode in ['qq','kk','qq_vfm_distill','kk_vfm_distill']: + x = self.resblocks[-1].ss_attn(x, mode) + elif mode=='vanilla': + x = self.resblocks[-1](x) + else: + raise NotImplementedError(f"The mode '{mode}' is not implemented.") + return x + + def forward_image_dense(self, x, attn_mask): + for i in range(self.layers - 1): + x = self.resblocks[i](x, attn_mask=attn_mask) + dense = self.resblocks[-1].forward_without_attn(x) + image = self.resblocks[-1](x, attn_mask=attn_mask) + + return image, dense + + +class VisionTransformer(nn.Module): + output_tokens: torch.jit.Final[bool] + + def __init__( + self, + image_size: int, + patch_size: int, + width: int, + layers: int, + heads: int, + mlp_ratio: float, + ls_init_value: float = None, + global_average_pool: bool = False, + attentional_pool: bool = False, + n_queries: int = 256, + attn_pooler_heads: int = 8, + output_dim: int = 512, + patch_dropout: float = 0., + input_patchnorm: bool = False, + act_layer: Callable = nn.GELU, + norm_layer: Callable = LayerNorm, + output_tokens: bool = False + ): + super().__init__() + self.output_tokens = output_tokens + image_height, image_width = self.image_size = to_2tuple(image_size) + patch_height, patch_width = self.patch_size = to_2tuple(patch_size) + self.grid_size = (image_height // patch_height, image_width // patch_width) + self.output_dim = output_dim + + # whether to layernorm each patch, as done in dual patchnorm paper - https://arxiv.org/abs/2302.01327v1 + self.input_patchnorm = input_patchnorm + assert not input_patchnorm + if input_patchnorm: + patch_input_dim = patch_height * patch_width * 3 + self.patchnorm_pre_ln = LayerNorm(patch_input_dim) + self.conv1 = nn.Linear(patch_input_dim, width) + else: + self.patchnorm_pre_ln = nn.Identity() + self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False) + + # class embeddings and positional embeddings + scale = width ** -0.5 + self.class_embedding = nn.Parameter(scale * torch.randn(width)) + self.positional_embedding = nn.Parameter(scale * torch.randn(self.grid_size[0] * self.grid_size[1] + 1, width)) + + # setting a patch_dropout of 0. would mean it is disabled and this function would be the identity fn + self.patch_dropout = PatchDropout(patch_dropout) if patch_dropout > 0. else nn.Identity() + + self.ln_pre = norm_layer(width) + self.transformer = Transformer( + width, + layers, + heads, + mlp_ratio, + ls_init_value=ls_init_value, + act_layer=act_layer, + norm_layer=norm_layer, + ) + self.num_heads = heads + + self.global_average_pool = global_average_pool + if attentional_pool: + self.attn_pool = AttentionalPooler(output_dim, width, n_head=attn_pooler_heads, n_queries=n_queries) + self.ln_post = norm_layer(output_dim) + self.proj = nn.Parameter(scale * torch.randn(output_dim, output_dim)) + else: + self.attn_pool = None + self.ln_post = norm_layer(width) + self.proj = nn.Parameter(scale * torch.randn(width, output_dim)) + + self.init_parameters() + + def lock(self, unlocked_groups=0, freeze_bn_stats=False): + for param in self.parameters(): + param.requires_grad = False + + if unlocked_groups != 0: + groups = [ + [ + self.conv1, + self.class_embedding, + self.ln_pre, + ], + self.positional_embedding, + *self.transformer.resblocks[:-1], + [ + self.transformer.resblocks[-1], + # self.ln_post, # fix layer norm + ], + # self.proj, # fix output layers + ] + + def _unlock(x): + if isinstance(x, Sequence): + for g in x: + _unlock(g) + else: + if isinstance(x, torch.nn.Parameter): + x.requires_grad = True + else: + for p in x.parameters(): + p.requires_grad = True + + _unlock(groups[-unlocked_groups:]) + + def attention_lock(self, **kwargs): + for name, params in self.named_parameters(): + params.requires_grad = True if "attn" in name or "position" in name else False + + def init_parameters(self): + # FIXME OpenAI CLIP did not define an init for the VisualTransformer + # TODO experiment if default PyTorch init, below, or alternate init is best. + pass + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.transformer.grad_checkpointing = enable + + def _global_pool(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: + if self.global_average_pool: # false + return x.mean(dim=1), x + else: + return x[:, 0], x[:, 1:] + + def forward(self, x: torch.Tensor): + + x = self.conv1(x) # shape = [*, width, grid, grid] + bs, _, h, w = x.shape + x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2] + x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] + + # class embeddings and positional embeddings + x = torch.cat( + [self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), + x], dim=1) # shape = [*, grid ** 2 + 1, width] + # TODO: Allow interpolating the positional embeddings + + if (h, w) == self.grid_size: + pe = self.positional_embedding.to(x.dtype) + else: + pe = self.rescale_positional_embedding(out_size=(h, w), dtype=x.dtype) + + x = x + pe + + # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in + x = self.patch_dropout(x) + x = self.ln_pre(x) + + x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer(x) + x = x.permute(1, 0, 2) # LND -> NLD + + if self.attn_pool is not None: + x = self.attn_pool(x) + x = self.ln_post(x) + pooled, tokens = self._global_pool(x) + else: + pooled, tokens = self._global_pool(x) + pooled = self.ln_post(pooled) + + if self.proj is not None: + pooled = pooled @ self.proj + + if self.output_tokens: + return pooled, tokens + + return pooled + + def extract_roi_features(self, x, normed_boxes, mode="qq_vfm_distill", size=(1, 1)): + + if mode in ["qq_vfm_distill", "kk_vfm_distill", "csa_vfm_distill"]: + x, extra_feats = self.encode_dense(x, keep_shape=True, mode=mode) + boxes = self._denormalize_boxes(normed_boxes, x) + roi_feats = roi_align( + x, + boxes, + output_size=size, + spatial_scale=1.0, + sampling_ratio=-1, + aligned=True + ) + if size == (1, 1): + roi_feats = roi_feats[..., 0, 0] + else: + roi_feats = roi_feats.flatten(start_dim=-2).transpose(-2, -1).contiguous() + return roi_feats, extra_feats + else: + x = self.encode_dense(x, keep_shape=True, mode=mode) + boxes = self._denormalize_boxes(normed_boxes, x) + roi_feats = roi_align( + x, + boxes, + output_size=size, + spatial_scale=1.0, + sampling_ratio=-1, + aligned=True + ) + if size == (1, 1): + roi_feats = roi_feats[..., 0, 0] + else: + roi_feats = roi_feats.flatten(start_dim=-2).transpose(-2, -1).contiguous() + return roi_feats + + def mask_pool(self, x, masks, mode="qq_vfm_distill"): + feature_map = self.encode_dense(x, keep_shape=False,mode=mode) + num_masks_per_image = [len(masks_per_image) for masks_per_image in masks] + masks = torch.cat(masks).float().flatten(-2, -1) # bs, h*w + feature_map = torch.repeat_interleave(feature_map, torch.tensor(num_masks_per_image, device=feature_map.device), dim=0) + features = (feature_map * masks.unsqueeze(-1)).sum(1) / (masks.sum(1, keepdim=True) + 1e-12) + return features + + def encode_dense(self, x, keep_shape=False, mode='maskclip'): + x = self.conv1(x) # shape = [*, width, grid, grid] + bs, _, h, w = x.shape + # assert h == w # TODO: support input of any shape, need to change the normed boxes to real boxes + x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2] + x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] + x = torch.cat( + [self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), + x], dim=1) # shape = [*, grid ** 2 + 1, width] + if (h, w) == self.grid_size: + pe = self.positional_embedding.to(x.dtype) + else: + pe = self.rescale_positional_embedding(out_size=(h, w), dtype=x.dtype) + + x = x + pe + + # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in + x = self.patch_dropout(x) + x = self.ln_pre(x) + x = x.permute(1, 0, 2) # NLD -> LND + if 'distill' in mode: + x, extra_feats = self.transformer.extract_feature_map(x, mode=mode) + else: + x = self.transformer.extract_feature_map(x, mode=mode) + x = x.permute(1, 0, 2) # LND -> NLD + if self.attn_pool is not None: + x = self.attn_pool(x) + x = self.ln_post(x) + _, tokens = self._global_pool(x) + else: + _, tokens = self._global_pool(x) + tokens = self.ln_post(tokens) + if self.proj is not None: + tokens = tokens @ self.proj + feature_map = tokens.view(bs, h * w, -1) # .permute(0, 3, 1, 2) + feature_map = F.normalize(feature_map, dim=-1) # FIXME code from clipself, will slightly affect performance + if keep_shape: + feature_map = feature_map.view(bs, h, w, -1).permute(0, 3, 1, 2) + if 'distill' in mode: + return feature_map, extra_feats + else: + return feature_map + + @staticmethod + def _denormalize_boxes(normed_boxes, x): + h, w = x.shape[-2:] + denormed_boxes = [] + for boxes in normed_boxes: + new_boxes = boxes.clone() # FIXME: do not change the value in normed_boxes! + new_boxes[:, [0, 2]] *= w + new_boxes[:, [1, 3]] *= h + denormed_boxes.append(new_boxes) + return denormed_boxes + + def rescale_positional_embedding(self, out_size, dtype): + h, w = out_size + rescaled_positional_embedding = \ + self.positional_embedding.new_zeros(1 + h*w, self.positional_embedding.shape[1]) + rescaled_positional_embedding[0] = self.positional_embedding[0] + pe_2d = self.positional_embedding[1:].T.contiguous().view( + 1, -1, *self.grid_size) + pe_2d = F.interpolate(pe_2d, out_size, mode='bicubic', align_corners=False).view(-1, h*w) + rescaled_positional_embedding[1:] = pe_2d.T.contiguous() + + return rescaled_positional_embedding.to(dtype=dtype) + + + + + +class TextTransformer(nn.Module): + output_tokens: torch.jit.Final[bool] + + def __init__( + self, + context_length: int = 77, + vocab_size: int = 49408, + width: int = 512, + heads: int = 8, + layers: int = 12, + ls_init_value: float = None, + output_dim: int = 512, + act_layer: Callable = nn.GELU, + norm_layer: Callable = LayerNorm, + embed_cls: bool = False, + pad_id: int = 0, + output_tokens: bool = False, + ): + super().__init__() + self.output_tokens = output_tokens + self.num_pos = self.context_length = context_length + self.vocab_size = vocab_size + self.width = width + self.output_dim = output_dim + self.heads = heads + self.pad_id = pad_id + + self.text_projection = nn.Parameter(torch.empty(width, output_dim)) + + if embed_cls: + self.cls_emb = nn.Parameter(torch.empty(width)) + self.num_pos += 1 + else: + self.cls_emb = None + + self.token_embedding = nn.Embedding(vocab_size, width) + self.positional_embedding = nn.Parameter(torch.empty(self.num_pos, width)) + self.transformer = Transformer( + width=width, + layers=layers, + heads=heads, + ls_init_value=ls_init_value, + act_layer=act_layer, + norm_layer=norm_layer, + ) + self.ln_final = norm_layer(width) + + self.register_buffer('attn_mask', self.build_attention_mask(), persistent=False) + + self.init_parameters() + + def init_parameters(self): + nn.init.normal_(self.token_embedding.weight, std=0.02) + nn.init.normal_(self.positional_embedding, std=0.01) + if self.cls_emb is not None: + nn.init.normal_(self.cls_emb, std=0.01) + + proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5) + attn_std = self.transformer.width ** -0.5 + fc_std = (2 * self.transformer.width) ** -0.5 + for block in self.transformer.resblocks: + nn.init.normal_(block.attn.in_proj_weight, std=attn_std) + nn.init.normal_(block.attn.out_proj.weight, std=proj_std) + nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) + nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) + + if self.text_projection is not None: + nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5) + + def lock(self, unlocked_layers: int = 0, freeze_layer_norm: bool = True): + assert unlocked_layers == 0 and freeze_layer_norm + print(f'Freeze the text encoder', flush=True) + for p in self.parameters(): + p.requires_grad = False + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.transformer.grad_checkpointing = enable + + def build_attention_mask(self): + # lazily create causal attention mask, with full attention between the tokens + # pytorch uses additive attention mask; fill with -inf + mask = torch.empty(self.num_pos, self.num_pos) + mask.fill_(float("-inf")) + mask.triu_(1) # zero out the lower diagonal + return mask + + def build_cls_mask(self, text, cast_dtype: torch.dtype): + cls_mask = (text != self.pad_id).unsqueeze(1) + cls_mask = F.pad(cls_mask, (1, 0, cls_mask.shape[2], 0), value=1.0) + additive_mask = torch.empty(cls_mask.shape, dtype=cast_dtype, device=cls_mask.device) + additive_mask.fill_(0) + additive_mask.masked_fill_(~cls_mask, float("-inf")) + additive_mask = torch.repeat_interleave(additive_mask, self.heads, 0) + return additive_mask + + def _repeat(self, t, N: int): + return t.reshape(1, 1, -1).repeat(N, 1, 1) + + def forward(self, text): + cast_dtype = self.transformer.get_cast_dtype() + seq_len = text.shape[1] + + x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model] + attn_mask = self.attn_mask + if self.cls_emb is not None: + seq_len += 1 + x = torch.cat([x, self._repeat(self.cls_emb, x.shape[0])], dim=1) + cls_mask = self.build_cls_mask(text, cast_dtype) + attn_mask = attn_mask[None, :seq_len, :seq_len] + cls_mask[:, :seq_len, :seq_len] + + x = x + self.positional_embedding[:seq_len].to(cast_dtype) + x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer(x, attn_mask=attn_mask) + x = x.permute(1, 0, 2) # LND -> NLD + + # x.shape = [batch_size, n_ctx, transformer.width] + # take features from the eot embedding (eot_token is the highest number in each sequence) + if self.cls_emb is not None: + pooled, tokens = x[:, -1], x[:, :-1] + pooled = self.ln_final(pooled) + else: + x = self.ln_final(x) + pooled, tokens = x[torch.arange(x.shape[0]), text.argmax(dim=-1)], x + + if self.text_projection is not None: + pooled = pooled @ self.text_projection + + if self.output_tokens: + return pooled, tokens + + return pooled + + +class MultimodalTransformer(Transformer): + def __init__( + self, + width: int, + layers: int, + heads: int, + context_length: int = 77, + mlp_ratio: float = 4.0, + ls_init_value: float = None, + act_layer: Callable = nn.GELU, + norm_layer: Callable = LayerNorm, + output_dim: int = 512, + ): + + super().__init__( + width=width, + layers=layers, + heads=heads, + mlp_ratio=mlp_ratio, + ls_init_value=ls_init_value, + act_layer=act_layer, + norm_layer=norm_layer, + ) + self.context_length = context_length + self.cross_attn = nn.ModuleList([ + ResidualAttentionBlock( + width, + heads, + mlp_ratio, + ls_init_value=ls_init_value, + act_layer=act_layer, + norm_layer=norm_layer, + is_cross_attention=True, + ) + for _ in range(layers) + ]) + + self.register_buffer('attn_mask', self.build_attention_mask(), persistent=False) + + self.ln_final = norm_layer(width) + self.text_projection = nn.Parameter(torch.empty(width, output_dim)) + + def init_parameters(self): + proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5) + attn_std = self.transformer.width ** -0.5 + fc_std = (2 * self.transformer.width) ** -0.5 + for block in self.transformer.resblocks: + nn.init.normal_(block.attn.in_proj_weight, std=attn_std) + nn.init.normal_(block.attn.out_proj.weight, std=proj_std) + nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) + nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) + for block in self.transformer.cross_attn: + nn.init.normal_(block.attn.in_proj_weight, std=attn_std) + nn.init.normal_(block.attn.out_proj.weight, std=proj_std) + nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) + nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) + + if self.text_projection is not None: + nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5) + + def build_attention_mask(self): + # lazily create causal attention mask, with full attention between the tokens + # pytorch uses additive attention mask; fill with -inf + mask = torch.empty(self.context_length, self.context_length) + mask.fill_(float("-inf")) + mask.triu_(1) # zero out the lower diagonal + return mask + + def forward(self, image_embs, text_embs): + text_embs = text_embs.permute(1, 0, 2) # NLD -> LNDsq + image_embs = image_embs.permute(1, 0, 2) # NLD -> LND + seq_len = text_embs.shape[0] + + for resblock, cross_attn in zip(self.resblocks, self.cross_attn): + if self.grad_checkpointing and not torch.jit.is_scripting(): + # TODO: handle kwargs https://github.com/pytorch/pytorch/issues/79887#issuecomment-1161758372 + text_embs = checkpoint(resblock, text_embs, None, None, self.attn_mask[:seq_len, :seq_len]) + text_embs = checkpoint(cross_attn, text_embs, image_embs, image_embs, None) + else: + text_embs = resblock(text_embs, attn_mask=self.attn_mask[:seq_len, :seq_len]) + text_embs = cross_attn(text_embs, k_x=image_embs, v_x=image_embs) + + x = text_embs.permute(1, 0, 2) # LND -> NLD + x = self.ln_final(x) + + if self.text_projection is not None: + x = x @ self.text_projection + + return x + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.grad_checkpointing = enable diff --git a/src/open_clip/utils.py b/src/open_clip/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..51e80c5e296b24cae130ab0459baf268e0db7673 --- /dev/null +++ b/src/open_clip/utils.py @@ -0,0 +1,60 @@ +from itertools import repeat +import collections.abc + +from torch import nn as nn +from torchvision.ops.misc import FrozenBatchNorm2d + + +def freeze_batch_norm_2d(module, module_match={}, name=''): + """ + Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is + itself an instance of either `BatchNorm2d` or `SyncBatchNorm`, it is converted into `FrozenBatchNorm2d` and + returned. Otherwise, the module is walked recursively and submodules are converted in place. + + Args: + module (torch.nn.Module): Any PyTorch module. + module_match (dict): Dictionary of full module names to freeze (all if empty) + name (str): Full module name (prefix) + + Returns: + torch.nn.Module: Resulting module + + Inspired by https://github.com/pytorch/pytorch/blob/a5895f85be0f10212791145bfedc0261d364f103/torch/nn/modules/batchnorm.py#L762 + """ + res = module + is_match = True + if module_match: + is_match = name in module_match + if is_match and isinstance(module, (nn.modules.batchnorm.BatchNorm2d, nn.modules.batchnorm.SyncBatchNorm)): + res = FrozenBatchNorm2d(module.num_features) + res.num_features = module.num_features + res.affine = module.affine + if module.affine: + res.weight.data = module.weight.data.clone().detach() + res.bias.data = module.bias.data.clone().detach() + res.running_mean.data = module.running_mean.data + res.running_var.data = module.running_var.data + res.eps = module.eps + else: + for child_name, child in module.named_children(): + full_child_name = '.'.join([name, child_name]) if name else child_name + new_child = freeze_batch_norm_2d(child, module_match, full_child_name) + if new_child is not child: + res.add_module(child_name, new_child) + return res + + +# From PyTorch internals +def _ntuple(n): + def parse(x): + if isinstance(x, collections.abc.Iterable): + return x + return tuple(repeat(x, n)) + return parse + + +to_1tuple = _ntuple(1) +to_2tuple = _ntuple(2) +to_3tuple = _ntuple(3) +to_4tuple = _ntuple(4) +to_ntuple = lambda n, x: _ntuple(n)(x) diff --git a/src/open_clip/version.py b/src/open_clip/version.py new file mode 100644 index 0000000000000000000000000000000000000000..48aa744fb053599044caf0253b889b5cfe5b78e7 --- /dev/null +++ b/src/open_clip/version.py @@ -0,0 +1 @@ +__version__ = '2.16.0' diff --git a/src/segment_anything/__init__.py b/src/segment_anything/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..34383d83f5e76bc801f31b20e5651e383be348b6 --- /dev/null +++ b/src/segment_anything/__init__.py @@ -0,0 +1,15 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from .build_sam import ( + build_sam, + build_sam_vit_h, + build_sam_vit_l, + build_sam_vit_b, + sam_model_registry, +) +from .predictor import SamPredictor +from .automatic_mask_generator import SamAutomaticMaskGenerator diff --git a/src/segment_anything/automatic_mask_generator.py b/src/segment_anything/automatic_mask_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..d5a8c969207f119feff7087f94e044403acdff00 --- /dev/null +++ b/src/segment_anything/automatic_mask_generator.py @@ -0,0 +1,372 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch +from torchvision.ops.boxes import batched_nms, box_area # type: ignore + +from typing import Any, Dict, List, Optional, Tuple + +from .modeling import Sam +from .predictor import SamPredictor +from .utils.amg import ( + MaskData, + area_from_rle, + batch_iterator, + batched_mask_to_box, + box_xyxy_to_xywh, + build_all_layer_point_grids, + calculate_stability_score, + coco_encode_rle, + generate_crop_boxes, + is_box_near_crop_edge, + mask_to_rle_pytorch, + remove_small_regions, + rle_to_mask, + uncrop_boxes_xyxy, + uncrop_masks, + uncrop_points, +) + + +class SamAutomaticMaskGenerator: + def __init__( + self, + model: Sam, + points_per_side: Optional[int] = 32, + points_per_batch: int = 64, + pred_iou_thresh: float = 0.88, + stability_score_thresh: float = 0.95, + stability_score_offset: float = 1.0, + box_nms_thresh: float = 0.7, + crop_n_layers: int = 0, + crop_nms_thresh: float = 0.7, + crop_overlap_ratio: float = 512 / 1500, + crop_n_points_downscale_factor: int = 1, + point_grids: Optional[List[np.ndarray]] = None, + min_mask_region_area: int = 0, + output_mode: str = "binary_mask", + ) -> None: + """ + Using a SAM model, generates masks for the entire image. + Generates a grid of point prompts over the image, then filters + low quality and duplicate masks. The default settings are chosen + for SAM with a ViT-H backbone. + + Arguments: + model (Sam): The SAM model to use for mask prediction. + points_per_side (int or None): The number of points to be sampled + along one side of the image. The total number of points is + points_per_side**2. If None, 'point_grids' must provide explicit + point sampling. + points_per_batch (int): Sets the number of points run simultaneously + by the model. Higher numbers may be faster but use more GPU memory. + pred_iou_thresh (float): A filtering threshold in [0,1], using the + model's predicted mask quality. + stability_score_thresh (float): A filtering threshold in [0,1], using + the stability of the mask under changes to the cutoff used to binarize + the model's mask predictions. + stability_score_offset (float): The amount to shift the cutoff when + calculated the stability score. + box_nms_thresh (float): The box IoU cutoff used by non-maximal + suppression to filter duplicate masks. + crop_n_layers (int): If >0, mask prediction will be run again on + crops of the image. Sets the number of layers to run, where each + layer has 2**i_layer number of image crops. + crop_nms_thresh (float): The box IoU cutoff used by non-maximal + suppression to filter duplicate masks between different crops. + crop_overlap_ratio (float): Sets the degree to which crops overlap. + In the first crop layer, crops will overlap by this fraction of + the image length. Later layers with more crops scale down this overlap. + crop_n_points_downscale_factor (int): The number of points-per-side + sampled in layer n is scaled down by crop_n_points_downscale_factor**n. + point_grids (list(np.ndarray) or None): A list over explicit grids + of points used for sampling, normalized to [0,1]. The nth grid in the + list is used in the nth crop layer. Exclusive with points_per_side. + min_mask_region_area (int): If >0, postprocessing will be applied + to remove disconnected regions and holes in masks with area smaller + than min_mask_region_area. Requires opencv. + output_mode (str): The form masks are returned in. Can be 'binary_mask', + 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools. + For large resolutions, 'binary_mask' may consume large amounts of + memory. + """ + + assert (points_per_side is None) != ( + point_grids is None + ), "Exactly one of points_per_side or point_grid must be provided." + if points_per_side is not None: + self.point_grids = build_all_layer_point_grids( + points_per_side, + crop_n_layers, + crop_n_points_downscale_factor, + ) + elif point_grids is not None: + self.point_grids = point_grids + else: + raise ValueError("Can't have both points_per_side and point_grid be None.") + + assert output_mode in [ + "binary_mask", + "uncompressed_rle", + "coco_rle", + ], f"Unknown output_mode {output_mode}." + if output_mode == "coco_rle": + from pycocotools import mask as mask_utils # type: ignore # noqa: F401 + + if min_mask_region_area > 0: + import cv2 # type: ignore # noqa: F401 + + self.predictor = SamPredictor(model) + self.points_per_batch = points_per_batch + self.pred_iou_thresh = pred_iou_thresh + self.stability_score_thresh = stability_score_thresh + self.stability_score_offset = stability_score_offset + self.box_nms_thresh = box_nms_thresh + self.crop_n_layers = crop_n_layers + self.crop_nms_thresh = crop_nms_thresh + self.crop_overlap_ratio = crop_overlap_ratio + self.crop_n_points_downscale_factor = crop_n_points_downscale_factor + self.min_mask_region_area = min_mask_region_area + self.output_mode = output_mode + + @torch.no_grad() + def generate(self, image: np.ndarray) -> List[Dict[str, Any]]: + """ + Generates masks for the given image. + + Arguments: + image (np.ndarray): The image to generate masks for, in HWC uint8 format. + + Returns: + list(dict(str, any)): A list over records for masks. Each record is + a dict containing the following keys: + segmentation (dict(str, any) or np.ndarray): The mask. If + output_mode='binary_mask', is an array of shape HW. Otherwise, + is a dictionary containing the RLE. + bbox (list(float)): The box around the mask, in XYWH format. + area (int): The area in pixels of the mask. + predicted_iou (float): The model's own prediction of the mask's + quality. This is filtered by the pred_iou_thresh parameter. + point_coords (list(list(float))): The point coordinates input + to the model to generate this mask. + stability_score (float): A measure of the mask's quality. This + is filtered on using the stability_score_thresh parameter. + crop_box (list(float)): The crop of the image used to generate + the mask, given in XYWH format. + """ + + # Generate masks + mask_data = self._generate_masks(image) + + # Filter small disconnected regions and holes in masks + if self.min_mask_region_area > 0: + mask_data = self.postprocess_small_regions( + mask_data, + self.min_mask_region_area, + max(self.box_nms_thresh, self.crop_nms_thresh), + ) + + # Encode masks + if self.output_mode == "coco_rle": + mask_data["segmentations"] = [coco_encode_rle(rle) for rle in mask_data["rles"]] + elif self.output_mode == "binary_mask": + mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]] + else: + mask_data["segmentations"] = mask_data["rles"] + + # Write mask records + curr_anns = [] + for idx in range(len(mask_data["segmentations"])): + ann = { + "segmentation": mask_data["segmentations"][idx], + "area": area_from_rle(mask_data["rles"][idx]), + "bbox": box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(), + "predicted_iou": mask_data["iou_preds"][idx].item(), + "point_coords": [mask_data["points"][idx].tolist()], + "stability_score": mask_data["stability_score"][idx].item(), + "crop_box": box_xyxy_to_xywh(mask_data["crop_boxes"][idx]).tolist(), + } + curr_anns.append(ann) + + return curr_anns + + def _generate_masks(self, image: np.ndarray) -> MaskData: + orig_size = image.shape[:2] + crop_boxes, layer_idxs = generate_crop_boxes( + orig_size, self.crop_n_layers, self.crop_overlap_ratio + ) + + # Iterate over image crops + data = MaskData() + for crop_box, layer_idx in zip(crop_boxes, layer_idxs): + crop_data = self._process_crop(image, crop_box, layer_idx, orig_size) + data.cat(crop_data) + + # Remove duplicate masks between crops + if len(crop_boxes) > 1: + # Prefer masks from smaller crops + scores = 1 / box_area(data["crop_boxes"]) + scores = scores.to(data["boxes"].device) + keep_by_nms = batched_nms( + data["boxes"].float(), + scores, + torch.zeros_like(data["boxes"][:, 0]), # categories + iou_threshold=self.crop_nms_thresh, + ) + data.filter(keep_by_nms) + + data.to_numpy() + return data + + def _process_crop( + self, + image: np.ndarray, + crop_box: List[int], + crop_layer_idx: int, + orig_size: Tuple[int, ...], + ) -> MaskData: + # Crop the image and calculate embeddings + x0, y0, x1, y1 = crop_box + cropped_im = image[y0:y1, x0:x1, :] + cropped_im_size = cropped_im.shape[:2] + self.predictor.set_image(cropped_im) + + # Get points for this crop + points_scale = np.array(cropped_im_size)[None, ::-1] + points_for_image = self.point_grids[crop_layer_idx] * points_scale + + # Generate masks for this crop in batches + data = MaskData() + for (points,) in batch_iterator(self.points_per_batch, points_for_image): + batch_data = self._process_batch(points, cropped_im_size, crop_box, orig_size) + data.cat(batch_data) + del batch_data + self.predictor.reset_image() + + # Remove duplicates within this crop. + keep_by_nms = batched_nms( + data["boxes"].float(), + data["iou_preds"], + torch.zeros_like(data["boxes"][:, 0]), # categories + iou_threshold=self.box_nms_thresh, + ) + data.filter(keep_by_nms) + + # Return to the original image frame + data["boxes"] = uncrop_boxes_xyxy(data["boxes"], crop_box) + data["points"] = uncrop_points(data["points"], crop_box) + data["crop_boxes"] = torch.tensor([crop_box for _ in range(len(data["rles"]))]) + + return data + + def _process_batch( + self, + points: np.ndarray, + im_size: Tuple[int, ...], + crop_box: List[int], + orig_size: Tuple[int, ...], + ) -> MaskData: + orig_h, orig_w = orig_size + + # Run model on this batch + transformed_points = self.predictor.transform.apply_coords(points, im_size) + in_points = torch.as_tensor(transformed_points, device=self.predictor.device) + in_labels = torch.ones(in_points.shape[0], dtype=torch.int, device=in_points.device) + masks, iou_preds, _ = self.predictor.predict_torch( + in_points[:, None, :], + in_labels[:, None], + multimask_output=True, + return_logits=True, + ) + + # Serialize predictions and store in MaskData + data = MaskData( + masks=masks.flatten(0, 1), + iou_preds=iou_preds.flatten(0, 1), + points=torch.as_tensor(points.repeat(masks.shape[1], axis=0)), + ) + del masks + + # Filter by predicted IoU + if self.pred_iou_thresh > 0.0: + keep_mask = data["iou_preds"] > self.pred_iou_thresh + data.filter(keep_mask) + + # Calculate stability score + data["stability_score"] = calculate_stability_score( + data["masks"], self.predictor.model.mask_threshold, self.stability_score_offset + ) + if self.stability_score_thresh > 0.0: + keep_mask = data["stability_score"] >= self.stability_score_thresh + data.filter(keep_mask) + + # Threshold masks and calculate boxes + data["masks"] = data["masks"] > self.predictor.model.mask_threshold + data["boxes"] = batched_mask_to_box(data["masks"]) + + # Filter boxes that touch crop boundaries + keep_mask = ~is_box_near_crop_edge(data["boxes"], crop_box, [0, 0, orig_w, orig_h]) + if not torch.all(keep_mask): + data.filter(keep_mask) + + # Compress to RLE + data["masks"] = uncrop_masks(data["masks"], crop_box, orig_h, orig_w) + data["rles"] = mask_to_rle_pytorch(data["masks"]) + del data["masks"] + + return data + + @staticmethod + def postprocess_small_regions( + mask_data: MaskData, min_area: int, nms_thresh: float + ) -> MaskData: + """ + Removes small disconnected regions and holes in masks, then reruns + box NMS to remove any new duplicates. + + Edits mask_data in place. + + Requires open-cv as a dependency. + """ + if len(mask_data["rles"]) == 0: + return mask_data + + # Filter small disconnected regions and holes + new_masks = [] + scores = [] + for rle in mask_data["rles"]: + mask = rle_to_mask(rle) + + mask, changed = remove_small_regions(mask, min_area, mode="holes") + unchanged = not changed + mask, changed = remove_small_regions(mask, min_area, mode="islands") + unchanged = unchanged and not changed + + new_masks.append(torch.as_tensor(mask).unsqueeze(0)) + # Give score=0 to changed masks and score=1 to unchanged masks + # so NMS will prefer ones that didn't need postprocessing + scores.append(float(unchanged)) + + # Recalculate boxes and remove any new duplicates + masks = torch.cat(new_masks, dim=0) + boxes = batched_mask_to_box(masks) + keep_by_nms = batched_nms( + boxes.float(), + torch.as_tensor(scores), + torch.zeros_like(boxes[:, 0]), # categories + iou_threshold=nms_thresh, + ) + + # Only recalculate RLEs for masks that have changed + for i_mask in keep_by_nms: + if scores[i_mask] == 0.0: + mask_torch = masks[i_mask].unsqueeze(0) + mask_data["rles"][i_mask] = mask_to_rle_pytorch(mask_torch)[0] + mask_data["boxes"][i_mask] = boxes[i_mask] # update res directly + mask_data.filter(keep_by_nms) + + return mask_data diff --git a/src/segment_anything/build_sam.py b/src/segment_anything/build_sam.py new file mode 100644 index 0000000000000000000000000000000000000000..37cd245124079e7cdd0d047ef9dde077db99efcc --- /dev/null +++ b/src/segment_anything/build_sam.py @@ -0,0 +1,107 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch + +from functools import partial + +from .modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWayTransformer + + +def build_sam_vit_h(checkpoint=None): + return _build_sam( + encoder_embed_dim=1280, + encoder_depth=32, + encoder_num_heads=16, + encoder_global_attn_indexes=[7, 15, 23, 31], + checkpoint=checkpoint, + ) + + +build_sam = build_sam_vit_h + + +def build_sam_vit_l(checkpoint=None): + return _build_sam( + encoder_embed_dim=1024, + encoder_depth=24, + encoder_num_heads=16, + encoder_global_attn_indexes=[5, 11, 17, 23], + checkpoint=checkpoint, + ) + + +def build_sam_vit_b(checkpoint=None): + return _build_sam( + encoder_embed_dim=768, + encoder_depth=12, + encoder_num_heads=12, + encoder_global_attn_indexes=[2, 5, 8, 11], + checkpoint=checkpoint, + ) + + +sam_model_registry = { + "default": build_sam_vit_h, + "vit_h": build_sam_vit_h, + "vit_l": build_sam_vit_l, + "vit_b": build_sam_vit_b, +} + + +def _build_sam( + encoder_embed_dim, + encoder_depth, + encoder_num_heads, + encoder_global_attn_indexes, + checkpoint=None, +): + prompt_embed_dim = 256 + image_size = 1024 + vit_patch_size = 16 + image_embedding_size = image_size // vit_patch_size + sam = Sam( + image_encoder=ImageEncoderViT( + depth=encoder_depth, + embed_dim=encoder_embed_dim, + img_size=image_size, + mlp_ratio=4, + norm_layer=partial(torch.nn.LayerNorm, eps=1e-6), + num_heads=encoder_num_heads, + patch_size=vit_patch_size, + qkv_bias=True, + use_rel_pos=True, + global_attn_indexes=encoder_global_attn_indexes, + window_size=14, + out_chans=prompt_embed_dim, + ), + prompt_encoder=PromptEncoder( + embed_dim=prompt_embed_dim, + image_embedding_size=(image_embedding_size, image_embedding_size), + input_image_size=(image_size, image_size), + mask_in_chans=16, + ), + mask_decoder=MaskDecoder( + num_multimask_outputs=3, + transformer=TwoWayTransformer( + depth=2, + embedding_dim=prompt_embed_dim, + mlp_dim=2048, + num_heads=8, + ), + transformer_dim=prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + ), + pixel_mean=[123.675, 116.28, 103.53], + pixel_std=[58.395, 57.12, 57.375], + ) + sam.eval() + if checkpoint is not None: + with open(checkpoint, "rb") as f: + state_dict = torch.load(f) + sam.load_state_dict(state_dict) + return sam diff --git a/src/segment_anything/modeling/__init__.py b/src/segment_anything/modeling/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..38e906243d898d7fc071c0fe218338c5cace3ea1 --- /dev/null +++ b/src/segment_anything/modeling/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from .sam import Sam +from .image_encoder import ImageEncoderViT +from .mask_decoder import MaskDecoder +from .prompt_encoder import PromptEncoder +from .transformer import TwoWayTransformer diff --git a/src/segment_anything/modeling/common.py b/src/segment_anything/modeling/common.py new file mode 100644 index 0000000000000000000000000000000000000000..2bf15236a3eb24d8526073bc4fa2b274cccb3f96 --- /dev/null +++ b/src/segment_anything/modeling/common.py @@ -0,0 +1,43 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn + +from typing import Type + + +class MLPBlock(nn.Module): + def __init__( + self, + embedding_dim: int, + mlp_dim: int, + act: Type[nn.Module] = nn.GELU, + ) -> None: + super().__init__() + self.lin1 = nn.Linear(embedding_dim, mlp_dim) + self.lin2 = nn.Linear(mlp_dim, embedding_dim) + self.act = act() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.lin2(self.act(self.lin1(x))) + + +# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa +# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa +class LayerNorm2d(nn.Module): + def __init__(self, num_channels: int, eps: float = 1e-6) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(num_channels)) + self.bias = nn.Parameter(torch.zeros(num_channels)) + self.eps = eps + + def forward(self, x: torch.Tensor) -> torch.Tensor: + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x diff --git a/src/segment_anything/modeling/image_encoder.py b/src/segment_anything/modeling/image_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..c4065270b53bad5797b0864773e1721451141cb8 --- /dev/null +++ b/src/segment_anything/modeling/image_encoder.py @@ -0,0 +1,412 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from typing import Optional, Tuple, Type + +from .common import LayerNorm2d, MLPBlock + + +# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa +class ImageEncoderViT(nn.Module): + def __init__( + self, + img_size: int = 1024, + patch_size: int = 16, + in_chans: int = 3, + embed_dim: int = 768, + depth: int = 12, + num_heads: int = 12, + mlp_ratio: float = 4.0, + out_chans: int = 256, + qkv_bias: bool = True, + norm_layer: Type[nn.Module] = nn.LayerNorm, + act_layer: Type[nn.Module] = nn.GELU, + use_abs_pos: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + global_attn_indexes: Tuple[int, ...] = (), + ) -> None: + """ + Args: + img_size (int): Input image size. + patch_size (int): Patch size. + in_chans (int): Number of input image channels. + embed_dim (int): Patch embedding dimension. + depth (int): Depth of ViT. + num_heads (int): Number of attention heads in each ViT block. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + norm_layer (nn.Module): Normalization layer. + act_layer (nn.Module): Activation layer. + use_abs_pos (bool): If True, use absolute positional embeddings. + use_rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + window_size (int): Window size for window attention blocks. + global_attn_indexes (list): Indexes for blocks using global attention. + """ + super().__init__() + self.img_size = img_size + + self.patch_embed = PatchEmbed( + kernel_size=(patch_size, patch_size), + stride=(patch_size, patch_size), + in_chans=in_chans, + embed_dim=embed_dim, + ) + image_height, image_width = self.image_size = (img_size,img_size) + patch_height, patch_width = self.patch_size = (patch_size,patch_size) + self.grid_size = (image_height // patch_height, image_width // patch_width) + self.pos_embed: Optional[nn.Parameter] = None + if use_abs_pos: + # Initialize absolute positional embedding with pretrain image size. + self.pos_embed = nn.Parameter( + torch.zeros(1, img_size // patch_size, img_size // patch_size, embed_dim) + ) + + self.blocks = nn.ModuleList() + for i in range(depth): + block = Block( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + norm_layer=norm_layer, + act_layer=act_layer, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + window_size=window_size if i not in global_attn_indexes else 0, + input_size=(img_size // patch_size, img_size // patch_size), + ) + self.blocks.append(block) + + self.neck = nn.Sequential( + nn.Conv2d( + embed_dim, + out_chans, + kernel_size=1, + bias=False, + ), + LayerNorm2d(out_chans), + nn.Conv2d( + out_chans, + out_chans, + kernel_size=3, + padding=1, + bias=False, + ), + LayerNorm2d(out_chans), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.patch_embed(x) + # + _, h,w, _ = x.shape + # ## + if self.pos_embed is not None: + ### + if (h, w) == self.grid_size: + x = x + self.pos_embed + else: + x = x + self.rescale_positional_embedding(out_size=(h, w), dtype=x.dtype) + ### + # x = x + self.pos_embed + + for blk in self.blocks: + x = blk(x) + + x = self.neck(x.permute(0, 3, 1, 2)) + + return x + + def rescale_positional_embedding(self, out_size, dtype): + h, w = out_size + pos_embed = self.pos_embed.permute(0, 3, 1, 2) # [b, c, h, w] + pos_embed = F.interpolate(pos_embed, (h, w), mode='bicubic', align_corners=False) + pos_embed = pos_embed.permute(0, 2, 3, 1) # [b, h, w, c] + return pos_embed.to(dtype=dtype) + +class Block(nn.Module): + """Transformer blocks with support of window attention and residual propagation blocks""" + + def __init__( + self, + dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + norm_layer: Type[nn.Module] = nn.LayerNorm, + act_layer: Type[nn.Module] = nn.GELU, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + input_size: Optional[Tuple[int, int]] = None, + ) -> None: + """ + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads in each ViT block. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + norm_layer (nn.Module): Normalization layer. + act_layer (nn.Module): Activation layer. + use_rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + window_size (int): Window size for window attention blocks. If it equals 0, then + use global attention. + input_size (tuple(int, int) or None): Input resolution for calculating the relative + positional parameter size. + """ + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + input_size=input_size if window_size == 0 else (window_size, window_size), + ) + + self.norm2 = norm_layer(dim) + self.mlp = MLPBlock(embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer) + + self.window_size = window_size + + def forward(self, x: torch.Tensor) -> torch.Tensor: + shortcut = x + x = self.norm1(x) + # Window partition + if self.window_size > 0: + H, W = x.shape[1], x.shape[2] + x, pad_hw = window_partition(x, self.window_size) + + x = self.attn(x) + # Reverse window partition + if self.window_size > 0: + x = window_unpartition(x, self.window_size, pad_hw, (H, W)) + + x = shortcut + x + x = x + self.mlp(self.norm2(x)) + + return x + + +class Attention(nn.Module): + """Multi-head Attention block with relative position embeddings.""" + + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + input_size: Optional[Tuple[int, int]] = None, + ) -> None: + """ + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + input_size (tuple(int, int) or None): Input resolution for calculating the relative + positional parameter size. + """ + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim**-0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.proj = nn.Linear(dim, dim) + + self.use_rel_pos = use_rel_pos + if self.use_rel_pos: + assert ( + input_size is not None + ), "Input size must be provided if using relative positional encoding." + # initialize relative positional embeddings + self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim)) + self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + B, H, W, _ = x.shape + # qkv with shape (3, B, nHead, H * W, C) + qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) + # q, k, v with shape (B * nHead, H * W, C) + q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) + + attn = (q * self.scale) @ k.transpose(-2, -1) + + if self.use_rel_pos: + attn = add_decomposed_rel_pos(attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W)) + + attn = attn.softmax(dim=-1) + x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1) + x = self.proj(x) + + return x + + +def window_partition(x: torch.Tensor, window_size: int) -> Tuple[torch.Tensor, Tuple[int, int]]: + """ + Partition into non-overlapping windows with padding if needed. + Args: + x (tensor): input tokens with [B, H, W, C]. + window_size (int): window size. + + Returns: + windows: windows after partition with [B * num_windows, window_size, window_size, C]. + (Hp, Wp): padded height and width before partition + """ + B, H, W, C = x.shape + + pad_h = (window_size - H % window_size) % window_size + pad_w = (window_size - W % window_size) % window_size + if pad_h > 0 or pad_w > 0: + x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h)) + Hp, Wp = H + pad_h, W + pad_w + + x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C) + windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + return windows, (Hp, Wp) + + +def window_unpartition( + windows: torch.Tensor, window_size: int, pad_hw: Tuple[int, int], hw: Tuple[int, int] +) -> torch.Tensor: + """ + Window unpartition into original sequences and removing padding. + Args: + windows (tensor): input tokens with [B * num_windows, window_size, window_size, C]. + window_size (int): window size. + pad_hw (Tuple): padded height and width (Hp, Wp). + hw (Tuple): original height and width (H, W) before padding. + + Returns: + x: unpartitioned sequences with [B, H, W, C]. + """ + Hp, Wp = pad_hw + H, W = hw + B = windows.shape[0] // (Hp * Wp // window_size // window_size) + x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1) + + if Hp > H or Wp > W: + x = x[:, :H, :W, :].contiguous() + return x + + +def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor: + """ + Get relative positional embeddings according to the relative positions of + query and key sizes. + Args: + q_size (int): size of query q. + k_size (int): size of key k. + rel_pos (Tensor): relative position embeddings (L, C). + + Returns: + Extracted positional embeddings according to relative positions. + """ + max_rel_dist = int(2 * max(q_size, k_size) - 1) + # Interpolate rel pos if needed. + if rel_pos.shape[0] != max_rel_dist: + # Interpolate rel pos. + rel_pos_resized = F.interpolate( + rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1), + size=max_rel_dist, + mode="linear", + ) + rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0) + else: + rel_pos_resized = rel_pos + + # Scale the coords with short length if shapes for q and k are different. + q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0) + k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0) + relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0) + + return rel_pos_resized[relative_coords.long()] + + +def add_decomposed_rel_pos( + attn: torch.Tensor, + q: torch.Tensor, + rel_pos_h: torch.Tensor, + rel_pos_w: torch.Tensor, + q_size: Tuple[int, int], + k_size: Tuple[int, int], +) -> torch.Tensor: + """ + Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`. + https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950 + Args: + attn (Tensor): attention map. + q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C). + rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis. + rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis. + q_size (Tuple): spatial sequence size of query q with (q_h, q_w). + k_size (Tuple): spatial sequence size of key k with (k_h, k_w). + + Returns: + attn (Tensor): attention map with added relative positional embeddings. + """ + q_h, q_w = q_size + k_h, k_w = k_size + Rh = get_rel_pos(q_h, k_h, rel_pos_h) + Rw = get_rel_pos(q_w, k_w, rel_pos_w) + + B, _, dim = q.shape + r_q = q.reshape(B, q_h, q_w, dim) + rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh) + rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw) + + attn = ( + attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :] + ).view(B, q_h * q_w, k_h * k_w) + + return attn + + +class PatchEmbed(nn.Module): + """ + Image to Patch Embedding. + """ + + def __init__( + self, + kernel_size: Tuple[int, int] = (16, 16), + stride: Tuple[int, int] = (16, 16), + padding: Tuple[int, int] = (0, 0), + in_chans: int = 3, + embed_dim: int = 768, + ) -> None: + """ + Args: + kernel_size (Tuple): kernel size of the projection layer. + stride (Tuple): stride of the projection layer. + padding (Tuple): padding size of the projection layer. + in_chans (int): Number of input image channels. + embed_dim (int): Patch embedding dimension. + """ + super().__init__() + + self.proj = nn.Conv2d( + in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.proj(x) + # B C H W -> B H W C + x = x.permute(0, 2, 3, 1) + return x \ No newline at end of file diff --git a/src/segment_anything/modeling/mask_decoder.py b/src/segment_anything/modeling/mask_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..5d2fdb03d535a91fa725d1ec4e92a7a1f217dfe0 --- /dev/null +++ b/src/segment_anything/modeling/mask_decoder.py @@ -0,0 +1,176 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from torch import nn +from torch.nn import functional as F + +from typing import List, Tuple, Type + +from .common import LayerNorm2d + + +class MaskDecoder(nn.Module): + def __init__( + self, + *, + transformer_dim: int, + transformer: nn.Module, + num_multimask_outputs: int = 3, + activation: Type[nn.Module] = nn.GELU, + iou_head_depth: int = 3, + iou_head_hidden_dim: int = 256, + ) -> None: + """ + Predicts masks given an image and prompt embeddings, using a + transformer architecture. + + Arguments: + transformer_dim (int): the channel dimension of the transformer + transformer (nn.Module): the transformer used to predict masks + num_multimask_outputs (int): the number of masks to predict + when disambiguating masks + activation (nn.Module): the type of activation to use when + upscaling masks + iou_head_depth (int): the depth of the MLP used to predict + mask quality + iou_head_hidden_dim (int): the hidden dimension of the MLP + used to predict mask quality + """ + super().__init__() + self.transformer_dim = transformer_dim + self.transformer = transformer + + self.num_multimask_outputs = num_multimask_outputs + + self.iou_token = nn.Embedding(1, transformer_dim) + self.num_mask_tokens = num_multimask_outputs + 1 + self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim) + + self.output_upscaling = nn.Sequential( + nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2), + LayerNorm2d(transformer_dim // 4), + activation(), + nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2), + activation(), + ) + self.output_hypernetworks_mlps = nn.ModuleList( + [ + MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) + for i in range(self.num_mask_tokens) + ] + ) + + self.iou_prediction_head = MLP( + transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth + ) + + def forward( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + multimask_output: bool, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Predict masks given image and prompt embeddings. + + Arguments: + image_embeddings (torch.Tensor): the embeddings from the image encoder + image_pe (torch.Tensor): positional encoding with the shape of image_embeddings + sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes + dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs + multimask_output (bool): Whether to return multiple masks or a single + mask. + + Returns: + torch.Tensor: batched predicted masks + torch.Tensor: batched predictions of mask quality + """ + masks, iou_pred = self.predict_masks( + image_embeddings=image_embeddings, + image_pe=image_pe, + sparse_prompt_embeddings=sparse_prompt_embeddings, + dense_prompt_embeddings=dense_prompt_embeddings, + ) + + # Select the correct mask or masks for output + if multimask_output: + mask_slice = slice(1, None) + else: + mask_slice = slice(0, 1) + masks = masks[:, mask_slice, :, :] + iou_pred = iou_pred[:, mask_slice] + + # Prepare output + return masks, iou_pred + + def predict_masks( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Predicts masks. See 'forward' for more details.""" + # Concatenate output tokens + output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0) + output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.size(0), -1, -1) + tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1) + + # Expand per-image data in batch direction to be per-mask + src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0) + src = src + dense_prompt_embeddings + pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0) + b, c, h, w = src.shape + + # Run the transformer + hs, src = self.transformer(src, pos_src, tokens) + iou_token_out = hs[:, 0, :] + mask_tokens_out = hs[:, 1 : (1 + self.num_mask_tokens), :] + + # Upscale mask embeddings and predict masks using the mask tokens + src = src.transpose(1, 2).view(b, c, h, w) + upscaled_embedding = self.output_upscaling(src) + hyper_in_list: List[torch.Tensor] = [] + for i in range(self.num_mask_tokens): + hyper_in_list.append(self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :])) + hyper_in = torch.stack(hyper_in_list, dim=1) + b, c, h, w = upscaled_embedding.shape + masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w) + + # Generate mask quality predictions + iou_pred = self.iou_prediction_head(iou_token_out) + + return masks, iou_pred + + +# Lightly adapted from +# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa +class MLP(nn.Module): + def __init__( + self, + input_dim: int, + hidden_dim: int, + output_dim: int, + num_layers: int, + sigmoid_output: bool = False, + ) -> None: + super().__init__() + self.num_layers = num_layers + h = [hidden_dim] * (num_layers - 1) + self.layers = nn.ModuleList( + nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]) + ) + self.sigmoid_output = sigmoid_output + + def forward(self, x): + for i, layer in enumerate(self.layers): + x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) + if self.sigmoid_output: + x = F.sigmoid(x) + return x diff --git a/src/segment_anything/modeling/prompt_encoder.py b/src/segment_anything/modeling/prompt_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..c3143f4f8e02ddd7ca8587b40ff5d47c3a6b7ef3 --- /dev/null +++ b/src/segment_anything/modeling/prompt_encoder.py @@ -0,0 +1,214 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch +from torch import nn + +from typing import Any, Optional, Tuple, Type + +from .common import LayerNorm2d + + +class PromptEncoder(nn.Module): + def __init__( + self, + embed_dim: int, + image_embedding_size: Tuple[int, int], + input_image_size: Tuple[int, int], + mask_in_chans: int, + activation: Type[nn.Module] = nn.GELU, + ) -> None: + """ + Encodes prompts for input to SAM's mask decoder. + + Arguments: + embed_dim (int): The prompts' embedding dimension + image_embedding_size (tuple(int, int)): The spatial size of the + image embedding, as (H, W). + input_image_size (int): The padded size of the image as input + to the image encoder, as (H, W). + mask_in_chans (int): The number of hidden channels used for + encoding input masks. + activation (nn.Module): The activation to use when encoding + input masks. + """ + super().__init__() + self.embed_dim = embed_dim + self.input_image_size = input_image_size + self.image_embedding_size = image_embedding_size + self.pe_layer = PositionEmbeddingRandom(embed_dim // 2) + + self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners + point_embeddings = [nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings)] + self.point_embeddings = nn.ModuleList(point_embeddings) + self.not_a_point_embed = nn.Embedding(1, embed_dim) + + self.mask_input_size = (4 * image_embedding_size[0], 4 * image_embedding_size[1]) + self.mask_downscaling = nn.Sequential( + nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans // 4), + activation(), + nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans), + activation(), + nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1), + ) + self.no_mask_embed = nn.Embedding(1, embed_dim) + + def get_dense_pe(self) -> torch.Tensor: + """ + Returns the positional encoding used to encode point prompts, + applied to a dense set of points the shape of the image encoding. + + Returns: + torch.Tensor: Positional encoding with shape + 1x(embed_dim)x(embedding_h)x(embedding_w) + """ + return self.pe_layer(self.image_embedding_size).unsqueeze(0) + + def _embed_points( + self, + points: torch.Tensor, + labels: torch.Tensor, + pad: bool, + ) -> torch.Tensor: + """Embeds point prompts.""" + points = points + 0.5 # Shift to center of pixel + if pad: + padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device) + padding_label = -torch.ones((labels.shape[0], 1), device=labels.device) + points = torch.cat([points, padding_point], dim=1) + labels = torch.cat([labels, padding_label], dim=1) + point_embedding = self.pe_layer.forward_with_coords(points, self.input_image_size) + point_embedding[labels == -1] = 0.0 + point_embedding[labels == -1] += self.not_a_point_embed.weight + point_embedding[labels == 0] += self.point_embeddings[0].weight + point_embedding[labels == 1] += self.point_embeddings[1].weight + return point_embedding + + def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor: + """Embeds box prompts.""" + boxes = boxes + 0.5 # Shift to center of pixel + coords = boxes.reshape(-1, 2, 2) + corner_embedding = self.pe_layer.forward_with_coords(coords, self.input_image_size) + corner_embedding[:, 0, :] += self.point_embeddings[2].weight + corner_embedding[:, 1, :] += self.point_embeddings[3].weight + return corner_embedding + + def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor: + """Embeds mask inputs.""" + mask_embedding = self.mask_downscaling(masks) + return mask_embedding + + def _get_batch_size( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + ) -> int: + """ + Gets the batch size of the output given the batch size of the input prompts. + """ + if points is not None: + return points[0].shape[0] + elif boxes is not None: + return boxes.shape[0] + elif masks is not None: + return masks.shape[0] + else: + return 1 + + def _get_device(self) -> torch.device: + return self.point_embeddings[0].weight.device + + def forward( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Embeds different types of prompts, returning both sparse and dense + embeddings. + + Arguments: + points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates + and labels to embed. + boxes (torch.Tensor or none): boxes to embed + masks (torch.Tensor or none): masks to embed + + Returns: + torch.Tensor: sparse embeddings for the points and boxes, with shape + BxNx(embed_dim), where N is determined by the number of input points + and boxes. + torch.Tensor: dense embeddings for the masks, in the shape + Bx(embed_dim)x(embed_H)x(embed_W) + """ + bs = self._get_batch_size(points, boxes, masks) + sparse_embeddings = torch.empty((bs, 0, self.embed_dim), device=self._get_device()) + if points is not None: + coords, labels = points + point_embeddings = self._embed_points(coords, labels, pad=(boxes is None)) + sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1) + if boxes is not None: + box_embeddings = self._embed_boxes(boxes) + sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1) + + if masks is not None: + dense_embeddings = self._embed_masks(masks) + else: + dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand( + bs, -1, self.image_embedding_size[0], self.image_embedding_size[1] + ) + + return sparse_embeddings, dense_embeddings + + +class PositionEmbeddingRandom(nn.Module): + """ + Positional encoding using random spatial frequencies. + """ + + def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: + super().__init__() + if scale is None or scale <= 0.0: + scale = 1.0 + self.register_buffer( + "positional_encoding_gaussian_matrix", + scale * torch.randn((2, num_pos_feats)), + ) + + def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor: + """Positionally encode points that are normalized to [0,1].""" + # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape + coords = 2 * coords - 1 + coords = coords @ self.positional_encoding_gaussian_matrix + coords = 2 * np.pi * coords + # outputs d_1 x ... x d_n x C shape + return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1) + + def forward(self, size: Tuple[int, int]) -> torch.Tensor: + """Generate positional encoding for a grid of the specified size.""" + h, w = size + device: Any = self.positional_encoding_gaussian_matrix.device + grid = torch.ones((h, w), device=device, dtype=torch.float32) + y_embed = grid.cumsum(dim=0) - 0.5 + x_embed = grid.cumsum(dim=1) - 0.5 + y_embed = y_embed / h + x_embed = x_embed / w + + pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1)) + return pe.permute(2, 0, 1) # C x H x W + + def forward_with_coords( + self, coords_input: torch.Tensor, image_size: Tuple[int, int] + ) -> torch.Tensor: + """Positionally encode points that are not normalized to [0,1].""" + coords = coords_input.clone() + coords[:, :, 0] = coords[:, :, 0] / image_size[1] + coords[:, :, 1] = coords[:, :, 1] / image_size[0] + return self._pe_encoding(coords.to(torch.float)) # B x N x C diff --git a/src/segment_anything/modeling/sam.py b/src/segment_anything/modeling/sam.py new file mode 100644 index 0000000000000000000000000000000000000000..8074cff6b40addc6b66f7ab4962218eef20da13c --- /dev/null +++ b/src/segment_anything/modeling/sam.py @@ -0,0 +1,174 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from torch import nn +from torch.nn import functional as F + +from typing import Any, Dict, List, Tuple + +from .image_encoder import ImageEncoderViT +from .mask_decoder import MaskDecoder +from .prompt_encoder import PromptEncoder + + +class Sam(nn.Module): + mask_threshold: float = 0.0 + image_format: str = "RGB" + + def __init__( + self, + image_encoder: ImageEncoderViT, + prompt_encoder: PromptEncoder, + mask_decoder: MaskDecoder, + pixel_mean: List[float] = [123.675, 116.28, 103.53], + pixel_std: List[float] = [58.395, 57.12, 57.375], + ) -> None: + """ + SAM predicts object masks from an image and input prompts. + + Arguments: + image_encoder (ImageEncoderViT): The backbone used to encode the + image into image embeddings that allow for efficient mask prediction. + prompt_encoder (PromptEncoder): Encodes various types of input prompts. + mask_decoder (MaskDecoder): Predicts masks from the image embeddings + and encoded prompts. + pixel_mean (list(float)): Mean values for normalizing pixels in the input image. + pixel_std (list(float)): Std values for normalizing pixels in the input image. + """ + super().__init__() + self.image_encoder = image_encoder + self.prompt_encoder = prompt_encoder + self.mask_decoder = mask_decoder + self.register_buffer("pixel_mean", torch.Tensor(pixel_mean).view(-1, 1, 1), False) + self.register_buffer("pixel_std", torch.Tensor(pixel_std).view(-1, 1, 1), False) + + @property + def device(self) -> Any: + return self.pixel_mean.device + + @torch.no_grad() + def forward( + self, + batched_input: List[Dict[str, Any]], + multimask_output: bool, + ) -> List[Dict[str, torch.Tensor]]: + """ + Predicts masks end-to-end from provided images and prompts. + If prompts are not known in advance, using SamPredictor is + recommended over calling the model directly. + + Arguments: + batched_input (list(dict)): A list over input images, each a + dictionary with the following keys. A prompt key can be + excluded if it is not present. + 'image': The image as a torch tensor in 3xHxW format, + already transformed for input to the model. + 'original_size': (tuple(int, int)) The original size of + the image before transformation, as (H, W). + 'point_coords': (torch.Tensor) Batched point prompts for + this image, with shape BxNx2. Already transformed to the + input frame of the model. + 'point_labels': (torch.Tensor) Batched labels for point prompts, + with shape BxN. + 'boxes': (torch.Tensor) Batched box inputs, with shape Bx4. + Already transformed to the input frame of the model. + 'mask_inputs': (torch.Tensor) Batched mask inputs to the model, + in the form Bx1xHxW. + multimask_output (bool): Whether the model should predict multiple + disambiguating masks, or return a single mask. + + Returns: + (list(dict)): A list over input images, where each element is + as dictionary with the following keys. + 'masks': (torch.Tensor) Batched binary mask predictions, + with shape BxCxHxW, where B is the number of input prompts, + C is determined by multimask_output, and (H, W) is the + original size of the image. + 'iou_predictions': (torch.Tensor) The model's predictions + of mask quality, in shape BxC. + 'low_res_logits': (torch.Tensor) Low resolution logits with + shape BxCxHxW, where H=W=256. Can be passed as mask input + to subsequent iterations of prediction. + """ + input_images = torch.stack([self.preprocess(x["image"]) for x in batched_input], dim=0) + image_embeddings = self.image_encoder(input_images) + + outputs = [] + for image_record, curr_embedding in zip(batched_input, image_embeddings): + if "point_coords" in image_record: + points = (image_record["point_coords"], image_record["point_labels"]) + else: + points = None + sparse_embeddings, dense_embeddings = self.prompt_encoder( + points=points, + boxes=image_record.get("boxes", None), + masks=image_record.get("mask_inputs", None), + ) + low_res_masks, iou_predictions = self.mask_decoder( + image_embeddings=curr_embedding.unsqueeze(0), + image_pe=self.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + ) + masks = self.postprocess_masks( + low_res_masks, + input_size=image_record["image"].shape[-2:], + original_size=image_record["original_size"], + ) + masks = masks > self.mask_threshold + outputs.append( + { + "masks": masks, + "iou_predictions": iou_predictions, + "low_res_logits": low_res_masks, + } + ) + return outputs + + def postprocess_masks( + self, + masks: torch.Tensor, + input_size: Tuple[int, ...], + original_size: Tuple[int, ...], + ) -> torch.Tensor: + """ + Remove padding and upscale masks to the original image size. + + Arguments: + masks (torch.Tensor): Batched masks from the mask_decoder, + in BxCxHxW format. + input_size (tuple(int, int)): The size of the image input to the + model, in (H, W) format. Used to remove padding. + original_size (tuple(int, int)): The original size of the image + before resizing for input to the model, in (H, W) format. + + Returns: + (torch.Tensor): Batched masks in BxCxHxW format, where (H, W) + is given by original_size. + """ + masks = F.interpolate( + masks, + (self.image_encoder.img_size, self.image_encoder.img_size), + mode="bilinear", + align_corners=False, + ) + masks = masks[..., : input_size[0], : input_size[1]] + masks = F.interpolate(masks, original_size, mode="bilinear", align_corners=False) + return masks + + def preprocess(self, x: torch.Tensor) -> torch.Tensor: + """Normalize pixel values and pad to a square input.""" + # Normalize colors + x = (x - self.pixel_mean) / self.pixel_std + + # Pad + h, w = x.shape[-2:] + padh = self.image_encoder.img_size - h + padw = self.image_encoder.img_size - w + x = F.pad(x, (0, padw, 0, padh)) + return x diff --git a/src/segment_anything/modeling/transformer.py b/src/segment_anything/modeling/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..33b8070d3c18d11a43fcca3e1b3d7d33dc9a1147 --- /dev/null +++ b/src/segment_anything/modeling/transformer.py @@ -0,0 +1,240 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from torch import Tensor, nn + +import math +from typing import Tuple, Type + +from .common import MLPBlock + + +class TwoWayTransformer(nn.Module): + def __init__( + self, + depth: int, + embedding_dim: int, + num_heads: int, + mlp_dim: int, + activation: Type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + ) -> None: + """ + A transformer decoder that attends to an input image using + queries whose positional embedding is supplied. + + Args: + depth (int): number of layers in the transformer + embedding_dim (int): the channel dimension for the input embeddings + num_heads (int): the number of heads for multihead attention. Must + divide embedding_dim + mlp_dim (int): the channel dimension internal to the MLP block + activation (nn.Module): the activation to use in the MLP block + """ + super().__init__() + self.depth = depth + self.embedding_dim = embedding_dim + self.num_heads = num_heads + self.mlp_dim = mlp_dim + self.layers = nn.ModuleList() + + for i in range(depth): + self.layers.append( + TwoWayAttentionBlock( + embedding_dim=embedding_dim, + num_heads=num_heads, + mlp_dim=mlp_dim, + activation=activation, + attention_downsample_rate=attention_downsample_rate, + skip_first_layer_pe=(i == 0), + ) + ) + + self.final_attn_token_to_image = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + self.norm_final_attn = nn.LayerNorm(embedding_dim) + + def forward( + self, + image_embedding: Tensor, + image_pe: Tensor, + point_embedding: Tensor, + ) -> Tuple[Tensor, Tensor]: + """ + Args: + image_embedding (torch.Tensor): image to attend to. Should be shape + B x embedding_dim x h x w for any h and w. + image_pe (torch.Tensor): the positional encoding to add to the image. Must + have the same shape as image_embedding. + point_embedding (torch.Tensor): the embedding to add to the query points. + Must have shape B x N_points x embedding_dim for any N_points. + + Returns: + torch.Tensor: the processed point_embedding + torch.Tensor: the processed image_embedding + """ + # BxCxHxW -> BxHWxC == B x N_image_tokens x C + bs, c, h, w = image_embedding.shape + image_embedding = image_embedding.flatten(2).permute(0, 2, 1) + image_pe = image_pe.flatten(2).permute(0, 2, 1) + + # Prepare queries + queries = point_embedding + keys = image_embedding + + # Apply transformer blocks and final layernorm + for layer in self.layers: + queries, keys = layer( + queries=queries, + keys=keys, + query_pe=point_embedding, + key_pe=image_pe, + ) + + # Apply the final attention layer from the points to the image + q = queries + point_embedding + k = keys + image_pe + attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm_final_attn(queries) + + return queries, keys + + +class TwoWayAttentionBlock(nn.Module): + def __init__( + self, + embedding_dim: int, + num_heads: int, + mlp_dim: int = 2048, + activation: Type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + skip_first_layer_pe: bool = False, + ) -> None: + """ + A transformer block with four layers: (1) self-attention of sparse + inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp + block on sparse inputs, and (4) cross attention of dense inputs to sparse + inputs. + + Arguments: + embedding_dim (int): the channel dimension of the embeddings + num_heads (int): the number of heads in the attention layers + mlp_dim (int): the hidden dimension of the mlp block + activation (nn.Module): the activation of the mlp block + skip_first_layer_pe (bool): skip the PE on the first layer + """ + super().__init__() + self.self_attn = Attention(embedding_dim, num_heads) + self.norm1 = nn.LayerNorm(embedding_dim) + + self.cross_attn_token_to_image = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + self.norm2 = nn.LayerNorm(embedding_dim) + + self.mlp = MLPBlock(embedding_dim, mlp_dim, activation) + self.norm3 = nn.LayerNorm(embedding_dim) + + self.norm4 = nn.LayerNorm(embedding_dim) + self.cross_attn_image_to_token = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + + self.skip_first_layer_pe = skip_first_layer_pe + + def forward( + self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor + ) -> Tuple[Tensor, Tensor]: + # Self attention block + if self.skip_first_layer_pe: + queries = self.self_attn(q=queries, k=queries, v=queries) + else: + q = queries + query_pe + attn_out = self.self_attn(q=q, k=q, v=queries) + queries = queries + attn_out + queries = self.norm1(queries) + + # Cross attention block, tokens attending to image embedding + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm2(queries) + + # MLP block + mlp_out = self.mlp(queries) + queries = queries + mlp_out + queries = self.norm3(queries) + + # Cross attention block, image embedding attending to tokens + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries) + keys = keys + attn_out + keys = self.norm4(keys) + + return queries, keys + + +class Attention(nn.Module): + """ + An attention layer that allows for downscaling the size of the embedding + after projection to queries, keys, and values. + """ + + def __init__( + self, + embedding_dim: int, + num_heads: int, + downsample_rate: int = 1, + ) -> None: + super().__init__() + self.embedding_dim = embedding_dim + self.internal_dim = embedding_dim // downsample_rate + self.num_heads = num_heads + assert self.internal_dim % num_heads == 0, "num_heads must divide embedding_dim." + + self.q_proj = nn.Linear(embedding_dim, self.internal_dim) + self.k_proj = nn.Linear(embedding_dim, self.internal_dim) + self.v_proj = nn.Linear(embedding_dim, self.internal_dim) + self.out_proj = nn.Linear(self.internal_dim, embedding_dim) + + def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor: + b, n, c = x.shape + x = x.reshape(b, n, num_heads, c // num_heads) + return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head + + def _recombine_heads(self, x: Tensor) -> Tensor: + b, n_heads, n_tokens, c_per_head = x.shape + x = x.transpose(1, 2) + return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C + + def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor: + # Input projections + q = self.q_proj(q) + k = self.k_proj(k) + v = self.v_proj(v) + + # Separate into heads + q = self._separate_heads(q, self.num_heads) + k = self._separate_heads(k, self.num_heads) + v = self._separate_heads(v, self.num_heads) + + # Attention + _, _, _, c_per_head = q.shape + attn = q @ k.permute(0, 1, 3, 2) # B x N_heads x N_tokens x N_tokens + attn = attn / math.sqrt(c_per_head) + attn = torch.softmax(attn, dim=-1) + + # Get output + out = attn @ v + out = self._recombine_heads(out) + out = self.out_proj(out) + + return out \ No newline at end of file diff --git a/src/segment_anything/predictor.py b/src/segment_anything/predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..8a6e6d816955b4c6097e1de6ce6e4ed3bafe327c --- /dev/null +++ b/src/segment_anything/predictor.py @@ -0,0 +1,269 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch + +from segment_anything.modeling import Sam + +from typing import Optional, Tuple + +from .utils.transforms import ResizeLongestSide + + +class SamPredictor: + def __init__( + self, + sam_model: Sam, + ) -> None: + """ + Uses SAM to calculate the image embedding for an image, and then + allow repeated, efficient mask prediction given prompts. + + Arguments: + sam_model (Sam): The model to use for mask prediction. + """ + super().__init__() + self.model = sam_model + self.transform = ResizeLongestSide(sam_model.image_encoder.img_size) + self.reset_image() + + def set_image( + self, + image: np.ndarray, + image_format: str = "RGB", + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. + + Arguments: + image (np.ndarray): The image for calculating masks. Expects an + image in HWC uint8 format, with pixel values in [0, 255]. + image_format (str): The color format of the image, in ['RGB', 'BGR']. + """ + assert image_format in [ + "RGB", + "BGR", + ], f"image_format must be in ['RGB', 'BGR'], is {image_format}." + if image_format != self.model.image_format: + image = image[..., ::-1] + + # Transform the image to the form expected by the model + input_image = self.transform.apply_image(image) + input_image_torch = torch.as_tensor(input_image, device=self.device) + input_image_torch = input_image_torch.permute(2, 0, 1).contiguous()[None, :, :, :] + + self.set_torch_image(input_image_torch, image.shape[:2]) + + @torch.no_grad() + def set_torch_image( + self, + transformed_image: torch.Tensor, + original_image_size: Tuple[int, ...], + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. Expects the input + image to be already transformed to the format expected by the model. + + Arguments: + transformed_image (torch.Tensor): The input image, with shape + 1x3xHxW, which has been transformed with ResizeLongestSide. + original_image_size (tuple(int, int)): The size of the image + before transformation, in (H, W) format. + """ + assert ( + len(transformed_image.shape) == 4 + and transformed_image.shape[1] == 3 + and max(*transformed_image.shape[2:]) == self.model.image_encoder.img_size + ), f"set_torch_image input must be BCHW with long side {self.model.image_encoder.img_size}." + self.reset_image() + + self.original_size = original_image_size + self.input_size = tuple(transformed_image.shape[-2:]) + input_image = self.model.preprocess(transformed_image) + self.features = self.model.image_encoder(input_image) + self.is_image_set = True + + def predict( + self, + point_coords: Optional[np.ndarray] = None, + point_labels: Optional[np.ndarray] = None, + box: Optional[np.ndarray] = None, + mask_input: Optional[np.ndarray] = None, + multimask_output: bool = True, + return_logits: bool = False, + ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + Predict masks for the given input prompts, using the currently set image. + + Arguments: + point_coords (np.ndarray or None): A Nx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (np.ndarray or None): A length N array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + box (np.ndarray or None): A length 4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form 1xHxW, where + for SAM, H=W=256. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (np.ndarray): The output masks in CxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (np.ndarray): An array of length C containing the model's + predictions for the quality of each mask. + (np.ndarray): An array of shape CxHxW, where C is the number + of masks and H=W=256. These low resolution logits can be passed to + a subsequent iteration as mask input. + """ + if not self.is_image_set: + raise RuntimeError("An image must be set with .set_image(...) before mask prediction.") + + # Transform input prompts + coords_torch, labels_torch, box_torch, mask_input_torch = None, None, None, None + if point_coords is not None: + assert ( + point_labels is not None + ), "point_labels must be supplied if point_coords is supplied." + point_coords = self.transform.apply_coords(point_coords, self.original_size) + coords_torch = torch.as_tensor(point_coords, dtype=torch.float, device=self.device) + labels_torch = torch.as_tensor(point_labels, dtype=torch.int, device=self.device) + coords_torch, labels_torch = coords_torch[None, :, :], labels_torch[None, :] + if box is not None: + box = self.transform.apply_boxes(box, self.original_size) + box_torch = torch.as_tensor(box, dtype=torch.float, device=self.device) + box_torch = box_torch[None, :] + if mask_input is not None: + mask_input_torch = torch.as_tensor(mask_input, dtype=torch.float, device=self.device) + mask_input_torch = mask_input_torch[None, :, :, :] + + masks, iou_predictions, low_res_masks = self.predict_torch( + coords_torch, + labels_torch, + box_torch, + mask_input_torch, + multimask_output, + return_logits=return_logits, + ) + + masks_np = masks[0].detach().cpu().numpy() + iou_predictions_np = iou_predictions[0].detach().cpu().numpy() + low_res_masks_np = low_res_masks[0].detach().cpu().numpy() + return masks_np, iou_predictions_np, low_res_masks_np + + @torch.no_grad() + def predict_torch( + self, + point_coords: Optional[torch.Tensor], + point_labels: Optional[torch.Tensor], + boxes: Optional[torch.Tensor] = None, + mask_input: Optional[torch.Tensor] = None, + multimask_output: bool = True, + return_logits: bool = False, + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Predict masks for the given input prompts, using the currently set image. + Input prompts are batched torch tensors and are expected to already be + transformed to the input frame using ResizeLongestSide. + + Arguments: + point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (torch.Tensor or None): A BxN array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + boxes (np.ndarray or None): A Bx4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form Bx1xHxW, where + for SAM, H=W=256. Masks returned by a previous iteration of the + predict method do not need further transformation. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (torch.Tensor): The output masks in BxCxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (torch.Tensor): An array of shape BxC containing the model's + predictions for the quality of each mask. + (torch.Tensor): An array of shape BxCxHxW, where C is the number + of masks and H=W=256. These low res logits can be passed to + a subsequent iteration as mask input. + """ + if not self.is_image_set: + raise RuntimeError("An image must be set with .set_image(...) before mask prediction.") + + if point_coords is not None: + points = (point_coords, point_labels) + else: + points = None + + # Embed prompts + sparse_embeddings, dense_embeddings = self.model.prompt_encoder( + points=points, + boxes=boxes, + masks=mask_input, + ) + + # Predict masks + low_res_masks, iou_predictions = self.model.mask_decoder( + image_embeddings=self.features, + image_pe=self.model.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + ) + + # Upscale the masks to the original image resolution + masks = self.model.postprocess_masks(low_res_masks, self.input_size, self.original_size) + + if not return_logits: + masks = masks > self.model.mask_threshold + + return masks, iou_predictions, low_res_masks + + def get_image_embedding(self) -> torch.Tensor: + """ + Returns the image embeddings for the currently set image, with + shape 1xCxHxW, where C is the embedding dimension and (H,W) are + the embedding spatial dimension of SAM (typically C=256, H=W=64). + """ + if not self.is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) to generate an embedding." + ) + assert self.features is not None, "Features must exist if an image has been set." + return self.features + + @property + def device(self) -> torch.device: + return self.model.device + + def reset_image(self) -> None: + """Resets the currently set image.""" + self.is_image_set = False + self.features = None + self.orig_h = None + self.orig_w = None + self.input_h = None + self.input_w = None diff --git a/src/segment_anything/utils/__init__.py b/src/segment_anything/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5277f46157403e47fd830fc519144b97ef69d4ae --- /dev/null +++ b/src/segment_anything/utils/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/src/segment_anything/utils/amg.py b/src/segment_anything/utils/amg.py new file mode 100644 index 0000000000000000000000000000000000000000..be064071ef399fea96c673ad173689656c23534a --- /dev/null +++ b/src/segment_anything/utils/amg.py @@ -0,0 +1,346 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch + +import math +from copy import deepcopy +from itertools import product +from typing import Any, Dict, Generator, ItemsView, List, Tuple + + +class MaskData: + """ + A structure for storing masks and their related data in batched format. + Implements basic filtering and concatenation. + """ + + def __init__(self, **kwargs) -> None: + for v in kwargs.values(): + assert isinstance( + v, (list, np.ndarray, torch.Tensor) + ), "MaskData only supports list, numpy arrays, and torch tensors." + self._stats = dict(**kwargs) + + def __setitem__(self, key: str, item: Any) -> None: + assert isinstance( + item, (list, np.ndarray, torch.Tensor) + ), "MaskData only supports list, numpy arrays, and torch tensors." + self._stats[key] = item + + def __delitem__(self, key: str) -> None: + del self._stats[key] + + def __getitem__(self, key: str) -> Any: + return self._stats[key] + + def items(self) -> ItemsView[str, Any]: + return self._stats.items() + + def filter(self, keep: torch.Tensor) -> None: + for k, v in self._stats.items(): + if v is None: + self._stats[k] = None + elif isinstance(v, torch.Tensor): + self._stats[k] = v[torch.as_tensor(keep, device=v.device)] + elif isinstance(v, np.ndarray): + self._stats[k] = v[keep.detach().cpu().numpy()] + elif isinstance(v, list) and keep.dtype == torch.bool: + self._stats[k] = [a for i, a in enumerate(v) if keep[i]] + elif isinstance(v, list): + self._stats[k] = [v[i] for i in keep] + else: + raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.") + + def cat(self, new_stats: "MaskData") -> None: + for k, v in new_stats.items(): + if k not in self._stats or self._stats[k] is None: + self._stats[k] = deepcopy(v) + elif isinstance(v, torch.Tensor): + self._stats[k] = torch.cat([self._stats[k], v], dim=0) + elif isinstance(v, np.ndarray): + self._stats[k] = np.concatenate([self._stats[k], v], axis=0) + elif isinstance(v, list): + self._stats[k] = self._stats[k] + deepcopy(v) + else: + raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.") + + def to_numpy(self) -> None: + for k, v in self._stats.items(): + if isinstance(v, torch.Tensor): + self._stats[k] = v.detach().cpu().numpy() + + +def is_box_near_crop_edge( + boxes: torch.Tensor, crop_box: List[int], orig_box: List[int], atol: float = 20.0 +) -> torch.Tensor: + """Filter masks at the edge of a crop, but not at the edge of the original image.""" + crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device) + orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device) + boxes = uncrop_boxes_xyxy(boxes, crop_box).float() + near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0) + near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0) + near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge) + return torch.any(near_crop_edge, dim=1) + + +def box_xyxy_to_xywh(box_xyxy: torch.Tensor) -> torch.Tensor: + box_xywh = deepcopy(box_xyxy) + box_xywh[2] = box_xywh[2] - box_xywh[0] + box_xywh[3] = box_xywh[3] - box_xywh[1] + return box_xywh + + +def batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]: + assert len(args) > 0 and all( + len(a) == len(args[0]) for a in args + ), "Batched iteration must have inputs of all the same size." + n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0) + for b in range(n_batches): + yield [arg[b * batch_size : (b + 1) * batch_size] for arg in args] + + +def mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]: + """ + Encodes masks to an uncompressed RLE, in the format expected by + pycoco tools. + """ + # Put in fortran order and flatten h,w + b, h, w = tensor.shape + tensor = tensor.permute(0, 2, 1).flatten(1) + + # Compute change indices + diff = tensor[:, 1:] ^ tensor[:, :-1] + change_indices = diff.nonzero() + + # Encode run length + out = [] + for i in range(b): + cur_idxs = change_indices[change_indices[:, 0] == i, 1] + cur_idxs = torch.cat( + [ + torch.tensor([0], dtype=cur_idxs.dtype, device=cur_idxs.device), + cur_idxs + 1, + torch.tensor([h * w], dtype=cur_idxs.dtype, device=cur_idxs.device), + ] + ) + btw_idxs = cur_idxs[1:] - cur_idxs[:-1] + counts = [] if tensor[i, 0] == 0 else [0] + counts.extend(btw_idxs.detach().cpu().tolist()) + out.append({"size": [h, w], "counts": counts}) + return out + + +def rle_to_mask(rle: Dict[str, Any]) -> np.ndarray: + """Compute a binary mask from an uncompressed RLE.""" + h, w = rle["size"] + mask = np.empty(h * w, dtype=bool) + idx = 0 + parity = False + for count in rle["counts"]: + mask[idx : idx + count] = parity + idx += count + parity ^= True + mask = mask.reshape(w, h) + return mask.transpose() # Put in C order + + +def area_from_rle(rle: Dict[str, Any]) -> int: + return sum(rle["counts"][1::2]) + + +def calculate_stability_score( + masks: torch.Tensor, mask_threshold: float, threshold_offset: float +) -> torch.Tensor: + """ + Computes the stability score for a batch of masks. The stability + score is the IoU between the binary masks obtained by thresholding + the predicted mask logits at high and low values. + """ + # One mask is always contained inside the other. + # Save memory by preventing unnecessary cast to torch.int64 + intersections = ( + (masks > (mask_threshold + threshold_offset)) + .sum(-1, dtype=torch.int16) + .sum(-1, dtype=torch.int32) + ) + unions = ( + (masks > (mask_threshold - threshold_offset)) + .sum(-1, dtype=torch.int16) + .sum(-1, dtype=torch.int32) + ) + return intersections / unions + + +def build_point_grid(n_per_side: int) -> np.ndarray: + """Generates a 2D grid of points evenly spaced in [0,1]x[0,1].""" + offset = 1 / (2 * n_per_side) + points_one_side = np.linspace(offset, 1 - offset, n_per_side) + points_x = np.tile(points_one_side[None, :], (n_per_side, 1)) + points_y = np.tile(points_one_side[:, None], (1, n_per_side)) + points = np.stack([points_x, points_y], axis=-1).reshape(-1, 2) + return points + + +def build_all_layer_point_grids( + n_per_side: int, n_layers: int, scale_per_layer: int +) -> List[np.ndarray]: + """Generates point grids for all crop layers.""" + points_by_layer = [] + for i in range(n_layers + 1): + n_points = int(n_per_side / (scale_per_layer**i)) + points_by_layer.append(build_point_grid(n_points)) + return points_by_layer + + +def generate_crop_boxes( + im_size: Tuple[int, ...], n_layers: int, overlap_ratio: float +) -> Tuple[List[List[int]], List[int]]: + """ + Generates a list of crop boxes of different sizes. Each layer + has (2**i)**2 boxes for the ith layer. + """ + crop_boxes, layer_idxs = [], [] + im_h, im_w = im_size + short_side = min(im_h, im_w) + + # Original image + crop_boxes.append([0, 0, im_w, im_h]) + layer_idxs.append(0) + + def crop_len(orig_len, n_crops, overlap): + return int(math.ceil((overlap * (n_crops - 1) + orig_len) / n_crops)) + + for i_layer in range(n_layers): + n_crops_per_side = 2 ** (i_layer + 1) + overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side)) + + crop_w = crop_len(im_w, n_crops_per_side, overlap) + crop_h = crop_len(im_h, n_crops_per_side, overlap) + + crop_box_x0 = [int((crop_w - overlap) * i) for i in range(n_crops_per_side)] + crop_box_y0 = [int((crop_h - overlap) * i) for i in range(n_crops_per_side)] + + # Crops in XYWH format + for x0, y0 in product(crop_box_x0, crop_box_y0): + box = [x0, y0, min(x0 + crop_w, im_w), min(y0 + crop_h, im_h)] + crop_boxes.append(box) + layer_idxs.append(i_layer + 1) + + return crop_boxes, layer_idxs + + +def uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: List[int]) -> torch.Tensor: + x0, y0, _, _ = crop_box + offset = torch.tensor([[x0, y0, x0, y0]], device=boxes.device) + # Check if boxes has a channel dimension + if len(boxes.shape) == 3: + offset = offset.unsqueeze(1) + return boxes + offset + + +def uncrop_points(points: torch.Tensor, crop_box: List[int]) -> torch.Tensor: + x0, y0, _, _ = crop_box + offset = torch.tensor([[x0, y0]], device=points.device) + # Check if points has a channel dimension + if len(points.shape) == 3: + offset = offset.unsqueeze(1) + return points + offset + + +def uncrop_masks( + masks: torch.Tensor, crop_box: List[int], orig_h: int, orig_w: int +) -> torch.Tensor: + x0, y0, x1, y1 = crop_box + if x0 == 0 and y0 == 0 and x1 == orig_w and y1 == orig_h: + return masks + # Coordinate transform masks + pad_x, pad_y = orig_w - (x1 - x0), orig_h - (y1 - y0) + pad = (x0, pad_x - x0, y0, pad_y - y0) + return torch.nn.functional.pad(masks, pad, value=0) + + +def remove_small_regions( + mask: np.ndarray, area_thresh: float, mode: str +) -> Tuple[np.ndarray, bool]: + """ + Removes small disconnected regions and holes in a mask. Returns the + mask and an indicator of if the mask has been modified. + """ + import cv2 # type: ignore + + assert mode in ["holes", "islands"] + correct_holes = mode == "holes" + working_mask = (correct_holes ^ mask).astype(np.uint8) + n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8) + sizes = stats[:, -1][1:] # Row 0 is background label + small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh] + if len(small_regions) == 0: + return mask, False + fill_labels = [0] + small_regions + if not correct_holes: + fill_labels = [i for i in range(n_labels) if i not in fill_labels] + # If every region is below threshold, keep largest + if len(fill_labels) == 0: + fill_labels = [int(np.argmax(sizes)) + 1] + mask = np.isin(regions, fill_labels) + return mask, True + + +def coco_encode_rle(uncompressed_rle: Dict[str, Any]) -> Dict[str, Any]: + from pycocotools import mask as mask_utils # type: ignore + + h, w = uncompressed_rle["size"] + rle = mask_utils.frPyObjects(uncompressed_rle, h, w) + rle["counts"] = rle["counts"].decode("utf-8") # Necessary to serialize with json + return rle + + +def batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor: + """ + Calculates boxes in XYXY format around masks. Return [0,0,0,0] for + an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4. + """ + # torch.max below raises an error on empty inputs, just skip in this case + if torch.numel(masks) == 0: + return torch.zeros(*masks.shape[:-2], 4, device=masks.device) + + # Normalize shape to CxHxW + shape = masks.shape + h, w = shape[-2:] + if len(shape) > 2: + masks = masks.flatten(0, -3) + else: + masks = masks.unsqueeze(0) + + # Get top and bottom edges + in_height, _ = torch.max(masks, dim=-1) + in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :] + bottom_edges, _ = torch.max(in_height_coords, dim=-1) + in_height_coords = in_height_coords + h * (~in_height) + top_edges, _ = torch.min(in_height_coords, dim=-1) + + # Get left and right edges + in_width, _ = torch.max(masks, dim=-2) + in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :] + right_edges, _ = torch.max(in_width_coords, dim=-1) + in_width_coords = in_width_coords + w * (~in_width) + left_edges, _ = torch.min(in_width_coords, dim=-1) + + # If the mask is empty the right edge will be to the left of the left edge. + # Replace these boxes with [0, 0, 0, 0] + empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges) + out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1) + out = out * (~empty_filter).unsqueeze(-1) + + # Return to original shape + if len(shape) > 2: + out = out.reshape(*shape[:-2], 4) + else: + out = out[0] + + return out diff --git a/src/segment_anything/utils/onnx.py b/src/segment_anything/utils/onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..3196bdf4b782e6eeb3da4ad66ef3c7b1741535fe --- /dev/null +++ b/src/segment_anything/utils/onnx.py @@ -0,0 +1,144 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn +from torch.nn import functional as F + +from typing import Tuple + +from ..modeling import Sam +from .amg import calculate_stability_score + + +class SamOnnxModel(nn.Module): + """ + This model should not be called directly, but is used in ONNX export. + It combines the prompt encoder, mask decoder, and mask postprocessing of Sam, + with some functions modified to enable model tracing. Also supports extra + options controlling what information. See the ONNX export script for details. + """ + + def __init__( + self, + model: Sam, + return_single_mask: bool, + use_stability_score: bool = False, + return_extra_metrics: bool = False, + ) -> None: + super().__init__() + self.mask_decoder = model.mask_decoder + self.model = model + self.img_size = model.image_encoder.img_size + self.return_single_mask = return_single_mask + self.use_stability_score = use_stability_score + self.stability_score_offset = 1.0 + self.return_extra_metrics = return_extra_metrics + + @staticmethod + def resize_longest_image_size( + input_image_size: torch.Tensor, longest_side: int + ) -> torch.Tensor: + input_image_size = input_image_size.to(torch.float32) + scale = longest_side / torch.max(input_image_size) + transformed_size = scale * input_image_size + transformed_size = torch.floor(transformed_size + 0.5).to(torch.int64) + return transformed_size + + def _embed_points(self, point_coords: torch.Tensor, point_labels: torch.Tensor) -> torch.Tensor: + point_coords = point_coords + 0.5 + point_coords = point_coords / self.img_size + point_embedding = self.model.prompt_encoder.pe_layer._pe_encoding(point_coords) + point_labels = point_labels.unsqueeze(-1).expand_as(point_embedding) + + point_embedding = point_embedding * (point_labels != -1) + point_embedding = point_embedding + self.model.prompt_encoder.not_a_point_embed.weight * ( + point_labels == -1 + ) + + for i in range(self.model.prompt_encoder.num_point_embeddings): + point_embedding = point_embedding + self.model.prompt_encoder.point_embeddings[ + i + ].weight * (point_labels == i) + + return point_embedding + + def _embed_masks(self, input_mask: torch.Tensor, has_mask_input: torch.Tensor) -> torch.Tensor: + mask_embedding = has_mask_input * self.model.prompt_encoder.mask_downscaling(input_mask) + mask_embedding = mask_embedding + ( + 1 - has_mask_input + ) * self.model.prompt_encoder.no_mask_embed.weight.reshape(1, -1, 1, 1) + return mask_embedding + + def mask_postprocessing(self, masks: torch.Tensor, orig_im_size: torch.Tensor) -> torch.Tensor: + masks = F.interpolate( + masks, + size=(self.img_size, self.img_size), + mode="bilinear", + align_corners=False, + ) + + prepadded_size = self.resize_longest_image_size(orig_im_size, self.img_size).to(torch.int64) + masks = masks[..., : prepadded_size[0], : prepadded_size[1]] # type: ignore + + orig_im_size = orig_im_size.to(torch.int64) + h, w = orig_im_size[0], orig_im_size[1] + masks = F.interpolate(masks, size=(h, w), mode="bilinear", align_corners=False) + return masks + + def select_masks( + self, masks: torch.Tensor, iou_preds: torch.Tensor, num_points: int + ) -> Tuple[torch.Tensor, torch.Tensor]: + # Determine if we should return the multiclick mask or not from the number of points. + # The reweighting is used to avoid control flow. + score_reweight = torch.tensor( + [[1000] + [0] * (self.model.mask_decoder.num_mask_tokens - 1)] + ).to(iou_preds.device) + score = iou_preds + (num_points - 2.5) * score_reweight + best_idx = torch.argmax(score, dim=1) + masks = masks[torch.arange(masks.shape[0]), best_idx, :, :].unsqueeze(1) + iou_preds = iou_preds[torch.arange(masks.shape[0]), best_idx].unsqueeze(1) + + return masks, iou_preds + + @torch.no_grad() + def forward( + self, + image_embeddings: torch.Tensor, + point_coords: torch.Tensor, + point_labels: torch.Tensor, + mask_input: torch.Tensor, + has_mask_input: torch.Tensor, + orig_im_size: torch.Tensor, + ): + sparse_embedding = self._embed_points(point_coords, point_labels) + dense_embedding = self._embed_masks(mask_input, has_mask_input) + + masks, scores = self.model.mask_decoder.predict_masks( + image_embeddings=image_embeddings, + image_pe=self.model.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embedding, + dense_prompt_embeddings=dense_embedding, + ) + + if self.use_stability_score: + scores = calculate_stability_score( + masks, self.model.mask_threshold, self.stability_score_offset + ) + + if self.return_single_mask: + masks, scores = self.select_masks(masks, scores, point_coords.shape[1]) + + upscaled_masks = self.mask_postprocessing(masks, orig_im_size) + + if self.return_extra_metrics: + stability_scores = calculate_stability_score( + upscaled_masks, self.model.mask_threshold, self.stability_score_offset + ) + areas = (upscaled_masks > self.model.mask_threshold).sum(-1).sum(-1) + return upscaled_masks, scores, stability_scores, areas, masks + + return upscaled_masks, scores, masks diff --git a/src/segment_anything/utils/transforms.py b/src/segment_anything/utils/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..c08ba1e3db751f3a5483a003be38c69c2cf2df85 --- /dev/null +++ b/src/segment_anything/utils/transforms.py @@ -0,0 +1,102 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch +from torch.nn import functional as F +from torchvision.transforms.functional import resize, to_pil_image # type: ignore + +from copy import deepcopy +from typing import Tuple + + +class ResizeLongestSide: + """ + Resizes images to the longest side 'target_length', as well as provides + methods for resizing coordinates and boxes. Provides methods for + transforming both numpy array and batched torch tensors. + """ + + def __init__(self, target_length: int) -> None: + self.target_length = target_length + + def apply_image(self, image: np.ndarray) -> np.ndarray: + """ + Expects a numpy array with shape HxWxC in uint8 format. + """ + target_size = self.get_preprocess_shape(image.shape[0], image.shape[1], self.target_length) + return np.array(resize(to_pil_image(image), target_size)) + + def apply_coords(self, coords: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray: + """ + Expects a numpy array of length 2 in the final dimension. Requires the + original image size in (H, W) format. + """ + old_h, old_w = original_size + new_h, new_w = self.get_preprocess_shape( + original_size[0], original_size[1], self.target_length + ) + coords = deepcopy(coords).astype(float) + coords[..., 0] = coords[..., 0] * (new_w / old_w) + coords[..., 1] = coords[..., 1] * (new_h / old_h) + return coords + + def apply_boxes(self, boxes: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray: + """ + Expects a numpy array shape Bx4. Requires the original image size + in (H, W) format. + """ + boxes = self.apply_coords(boxes.reshape(-1, 2, 2), original_size) + return boxes.reshape(-1, 4) + + def apply_image_torch(self, image: torch.Tensor) -> torch.Tensor: + """ + Expects batched images with shape BxCxHxW and float format. This + transformation may not exactly match apply_image. apply_image is + the transformation expected by the model. + """ + # Expects an image in BCHW format. May not exactly match apply_image. + target_size = self.get_preprocess_shape(image.shape[2], image.shape[3], self.target_length) + return F.interpolate( + image, target_size, mode="bilinear", align_corners=False, antialias=True + ) + + def apply_coords_torch( + self, coords: torch.Tensor, original_size: Tuple[int, ...] + ) -> torch.Tensor: + """ + Expects a torch tensor with length 2 in the last dimension. Requires the + original image size in (H, W) format. + """ + old_h, old_w = original_size + new_h, new_w = self.get_preprocess_shape( + original_size[0], original_size[1], self.target_length + ) + coords = deepcopy(coords).to(torch.float) + coords[..., 0] = coords[..., 0] * (new_w / old_w) + coords[..., 1] = coords[..., 1] * (new_h / old_h) + return coords + + def apply_boxes_torch( + self, boxes: torch.Tensor, original_size: Tuple[int, ...] + ) -> torch.Tensor: + """ + Expects a torch tensor with shape Bx4. Requires the original image + size in (H, W) format. + """ + boxes = self.apply_coords_torch(boxes.reshape(-1, 2, 2), original_size) + return boxes.reshape(-1, 4) + + @staticmethod + def get_preprocess_shape(oldh: int, oldw: int, long_side_length: int) -> Tuple[int, int]: + """ + Compute the output size given input size and target long side length. + """ + scale = long_side_length * 1.0 / max(oldh, oldw) + newh, neww = oldh * scale, oldw * scale + neww = int(neww + 0.5) + newh = int(newh + 0.5) + return (newh, neww) diff --git a/src/training/.gitignore b/src/training/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..333c1e910a3e2bef1b9d0d4587392627d8388974 --- /dev/null +++ b/src/training/.gitignore @@ -0,0 +1 @@ +logs/ diff --git a/src/training/__init__.py b/src/training/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/training/ablation_ijepa.py b/src/training/ablation_ijepa.py new file mode 100644 index 0000000000000000000000000000000000000000..0b7673397a52e2bfd9ed25d74c191dfa6825122d --- /dev/null +++ b/src/training/ablation_ijepa.py @@ -0,0 +1,551 @@ +""" +JEPA-GSC 消融实验训练代码 + +使用 I-JEPA encoder 的 self-attention 代替 SD attention 来 refine DINO 相似度矩阵。 +实时计算 I-JEPA attention(不预提取)。 +""" + +import os +import sys +from typing import List +import torch +import torch.nn.functional as F +import torch.nn as nn +from torchvision.ops import roi_align + +# 添加 I-JEPA 路径 +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "third_party", "ijepa")) + + +# ============ I-JEPA Attention 提取模块 ============ + +class IJEPAAttentionExtractor(nn.Module): + """ + 从 I-JEPA encoder 提取 self-attention map + + 参考 ProxyCLIP 的处理方式:在加载权重时预先插值 pos_embed 到目标分辨率, + 而不是在每次 forward 时动态插值,减少运行时开销。 + + 参考: https://github.com/mc-lan/ProxyCLIP/blob/main/proxyclip_segmentor.py + """ + def __init__(self, checkpoint_path: str, model_name: str = "vit_huge", + patch_size: int = 14, target_img_size: int = 224, + attention_layer_indices: List[int] = None, device: str = "cuda"): + super().__init__() + + self.patch_size = patch_size + self.target_img_size = target_img_size + + # 动态导入 I-JEPA 模型 + from third_party.ijepa.src.models.vision_transformer import ( + vit_huge, vit_large, vit_base + ) + + model_fn = { + "vit_huge": vit_huge, + "vit_large": vit_large, + "vit_base": vit_base, + }[model_name] + + # 创建模型时使用目标分辨率(CLIP 需要的分辨率) + self.model = model_fn(patch_size=patch_size, img_size=[target_img_size]) + self.num_layers = len(self.model.blocks) + + # 加载权重,在加载前先插值 pos_embed(参考 ProxyCLIP 的 MAE 处理方式) + if checkpoint_path and os.path.exists(checkpoint_path): + checkpoint = torch.load(checkpoint_path, map_location="cpu") + + if "encoder" in checkpoint: + state_dict = checkpoint["encoder"] + elif "target_encoder" in checkpoint: + state_dict = checkpoint["target_encoder"] + else: + state_dict = checkpoint + + # 处理 key 前缀 + new_state_dict = {} + for k, v in state_dict.items(): + if k.startswith("module."): + k = k[7:] + new_state_dict[k] = v + + # 在加载前先插值 pos_embed(关键步骤,参考 ProxyCLIP) + self._interpolate_pos_embed(new_state_dict, target_img_size, patch_size) + + # 加载权重 + msg = self.model.load_state_dict(new_state_dict, strict=False) + print(f"Loaded I-JEPA checkpoint from {checkpoint_path}") + print(f" Target resolution: {target_img_size}x{target_img_size}") + print(f" Position embedding interpolated at load time") + if msg.missing_keys: + print(f" Missing keys: {msg.missing_keys}") + else: + print(f"Warning: I-JEPA checkpoint not found at {checkpoint_path}, using random init") + + self.model = self.model.to(device).half().eval() + + # 冻结所有参数 + for p in self.model.parameters(): + p.requires_grad = False + + # 默认使用倒数第 4 和倒数第 2 层(类比 SD 的 [-4, -6]) + if attention_layer_indices is None: + attention_layer_indices = [-4, -2] + + self.attention_layers = [ + idx if idx >= 0 else self.num_layers + idx + for idx in attention_layer_indices + ] + + def _interpolate_pos_embed(self, state_dict: dict, target_img_size: int, patch_size: int): + """ + 在加载权重前插值 pos_embed(参考 ProxyCLIP/MAE 的处理方式) + + 这样可以避免在每次 forward 时进行插值计算。 + """ + if 'pos_embed' not in state_dict: + return + + pos_embed_checkpoint = state_dict['pos_embed'] + embedding_dim = pos_embed_checkpoint.shape[-1] + num_patches_checkpoint = pos_embed_checkpoint.shape[1] + + # 目标 patch 数量 + num_patches_target = (target_img_size // patch_size) ** 2 + + if num_patches_checkpoint == num_patches_target: + print(f" pos_embed size matches, no interpolation needed") + return + + # 计算源和目标的 grid size + src_grid_size = int(num_patches_checkpoint ** 0.5) + tgt_grid_size = int(num_patches_target ** 0.5) + + print(f" Interpolating pos_embed from {src_grid_size}x{src_grid_size} to {tgt_grid_size}x{tgt_grid_size}") + + # 2D bicubic 插值 + pos_embed_2d = pos_embed_checkpoint.reshape(1, src_grid_size, src_grid_size, embedding_dim) + pos_embed_2d = pos_embed_2d.permute(0, 3, 1, 2) # [1, C, H, W] + pos_embed_2d = F.interpolate( + pos_embed_2d, + size=(tgt_grid_size, tgt_grid_size), + mode='bicubic', + align_corners=False + ) + pos_embed_new = pos_embed_2d.permute(0, 2, 3, 1).reshape(1, -1, embedding_dim) + + state_dict['pos_embed'] = pos_embed_new + + @torch.no_grad() + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + 提取 I-JEPA attention map + + 由于 pos_embed 已在加载时预插值到目标分辨率,这里直接使用。 + + Args: + x: 输入图像 (B, 3, H, W),已经过预处理,尺寸应与 target_img_size 一致 + + Returns: + attention: 聚合的 attention map (B, N, N) + """ + # Patch embedding + x = self.model.patch_embed(x) + B, N, D = x.shape + + # Add positional embedding(已在加载时预插值,直接使用) + # 如果输入尺寸与预期不符,interpolate_pos_encoding 会处理 + if N == self.model.pos_embed.shape[1]: + x = x + self.model.pos_embed + else: + # Fallback: 运行时插值(不应该发生,因为我们已经对齐了分辨率) + pos_embed = self.model.interpolate_pos_encoding(x, self.model.pos_embed) + x = x + pos_embed + + # 收集 attention + attentions = [] + + for i, blk in enumerate(self.model.blocks): + if i in self.attention_layers: + # I-JEPA Block 支持 return_attention + attn = blk(x, return_attention=True) # (B, nHead, N, N) + attentions.append(attn) + x = blk(x) + + # 聚合多层 attention + if len(attentions) > 0: + attn_stack = torch.stack(attentions, dim=0) # (L, B, nHead, N, N) + attn_aggregated = attn_stack.mean(dim=(0, 2)) # (B, N, N) + else: + attn_aggregated = torch.eye(N, device=x.device, dtype=x.dtype).unsqueeze(0).expand(B, -1, -1) + + return attn_aggregated + + +# ============ JEPA-GSC 训练模块 ============ + +class DeCLIPWithREPAProjector(nn.Module): + """与 declip_plus.py 保持一致的模型包装器""" + + def __init__(self, declip_model, clip_dim=768, hidden_dim=1024, vfm_dim=768, args=None): + super().__init__() + self.model = declip_model + self.repa_layer_idx = args.repa_layer_idx + self.projector = nn.Sequential( + nn.Linear(clip_dim, hidden_dim), + nn.SiLU(), + nn.Linear(hidden_dim, hidden_dim), + nn.SiLU(), + nn.Linear(hidden_dim, vfm_dim) + ) + self.initialize_projector_weights() + self.logit_scale = self.model.logit_scale + + def initialize_projector_weights(self): + for module in self.projector.modules(): + if isinstance(module, nn.Linear): + nn.init.xavier_uniform_(module.weight) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + + def encode_image(self, *args, **kwargs): + return self.model.encode_image(*args, **kwargs) + + def encode_text(self, *args, **kwargs): + return self.model.encode_text(*args, **kwargs) + + def encode_dense(self, *args, **kwargs): + return self.model.encode_dense(*args, **kwargs) + + def encode_pseudo_boxes(self, images, rois_list, normalize=False, mode="qq", size=(1, 1)): + student_roi_features, context, intermediate_layer_output = self.model.encode_pseudo_boxes( + images, rois_list, normalize=normalize, mode=mode, size=size, + get_intermediate_layer=[self.repa_layer_idx] + ) + alpha = 0.3 + residual = intermediate_layer_output[0] + intermediate_layer_output = self.projector(intermediate_layer_output[0]) + intermediate_layer_output = alpha * residual + intermediate_layer_output + return student_roi_features, context, intermediate_layer_output + + def encode_masks(self, *args, **kwargs): + return self.model.encode_masks(*args, **kwargs) + + def train(self, mode=True): + self.model.train(mode) + self.training = self.model.training + return self + + def lock_image_tower(self, *args, **kwargs): + return self.model.lock_image_tower(*args, **kwargs) + + def lock_text_tower(self, *args, **kwargs): + return self.model.lock_text_tower(*args, **kwargs) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.model.set_grad_checkpointing(enable) + + @torch.jit.ignore + def no_weight_decay(self): + return self.model.no_weight_decay() + + +class DeCLIP_IJEPA_GSC: + """ + JEPA-GSC 消融实验:使用 I-JEPA attention 代替 SD attention + """ + + def __init__(self, ijepa_extractor: IJEPAAttentionExtractor): + self.ijepa_extractor = ijepa_extractor + + def __call__(self, batch, student, teacher, vfm_model, args): + losses = {} + context_weight = args.loss_context_weight + content_weight = args.loss_content_weight + region_weight = args.loss_region_weight + need_repa = args.repa_layer_idx != -1 + + if args.distributed: + student = student.module + + dtype_map = {"bf16": torch.bfloat16, "amp": torch.float16} + input_dtype = dtype_map.get(args.precision, torch.float32) + + # I-JEPA 版本的数据有 5 个元素(包含 I-JEPA 专用图像) + images, normed_boxes, image_crops, vfm_image, ijepa_image = prepare_inputs_ijepa(batch, args.device, input_dtype) + + # 实时计算 I-JEPA attention + with torch.no_grad(): + ijepa_attn = self.ijepa_extractor(ijepa_image) + + loss_ensemble = self.intra_image_distill( + student, teacher, vfm_model, images, normed_boxes, image_crops, vfm_image, ijepa_attn, args + ) + + loss_context, loss_content, loss_region = loss_ensemble[0], loss_ensemble[1], loss_ensemble[2] + losses.update({"loss_context": loss_context * context_weight}) + losses.update({"loss_content": loss_content * content_weight}) + losses.update({"loss_region": loss_region * region_weight}) + + if need_repa: + loss_repa = loss_ensemble[2] + losses.update({"loss_repa": loss_repa}) + + return losses, len(images) + + def intra_image_distill(self, student, teacher, vfm_model, images, normed_boxes, image_crops, vfm_image, ijepa_attn, args): + need_repa = args.repa_layer_idx != -1 + roi_size = (3, 3) + B = images.shape[0] + rois_list = [] + crops_list = [] + + for bboxes_per_image, crops_per_image in zip(normed_boxes, image_crops): + valid = bboxes_per_image[:, -1] > 0.5 + rois_list.append(bboxes_per_image[valid, :4]) + crops_list.append(crops_per_image[valid]) + + image_crops = torch.cat(crops_list) + + if need_repa: + student_roi_features, context, intermediate_layer_output = student.encode_pseudo_boxes( + images, rois_list, normalize=True, mode=args.mode, size=roi_size + ) + else: + student_roi_features, context = student.encode_pseudo_boxes( + images, rois_list, normalize=True, mode=args.mode, size=roi_size + ) + + with torch.no_grad(): + teacher_crop_features = teacher.encode_image(image_crops, normalize=True) + intra_vfm_feats = extract_vfm_features(vfm_model, vfm_image, args) + vfm_roi_features = extract_roi_features(intra_vfm_feats, rois_list, normalize=True) + intra_vfm_feats = F.normalize(intra_vfm_feats, dim=1).flatten(start_dim=-2) + intra_vfm_corr = torch.einsum('bci,bcj->bij', intra_vfm_feats, intra_vfm_feats) + + # 使用 I-JEPA attention refine DINO 相似度 + refined_intra_vfm_corr = refine_dino_with_ijepa(intra_vfm_corr, ijepa_attn, args.sd_refine_weight) + + student_intra_corr = compute_student_intra_image_similarity(images.shape[0], context, args) + loss_context = context_loss(student_intra_corr, refined_intra_vfm_corr, teacher_temp=0.8) + loss_content = soft_content_distill_loss(student_roi_features, teacher_crop_features) + loss_region = region_scd_loss(student_roi_features, vfm_roi_features) + + if need_repa: + loss_repa = repa_loss(intermediate_layer_output, intra_vfm_feats) + return loss_context, loss_content, loss_repa + else: + return loss_context, loss_content, loss_region + + +# ============ 辅助函数 ============ + +def refine_dino_with_ijepa(dino_corr: torch.Tensor, ijepa_attn: torch.Tensor, refine_weight: float) -> torch.Tensor: + """使用 I-JEPA attention refine DINO 相似度矩阵""" + # 调整 I-JEPA attention 尺寸以匹配 DINO + B_dino, HW_dino, _ = dino_corr.shape + B_ijepa, HW_ijepa, _ = ijepa_attn.shape + + if HW_dino != HW_ijepa: + ijepa_attn = resize_attention(ijepa_attn, int(HW_dino ** 0.5)) + + residual = dino_corr + dino_corr_propagated = torch.bmm(ijepa_attn, dino_corr) + dino_corr_refined = dino_corr_propagated * refine_weight + residual * (1 - refine_weight) + + # 强制对角线为 1 + bs, hw, _ = dino_corr_refined.shape + device = dino_corr_refined.device + eye = torch.eye(hw, dtype=dino_corr_refined.dtype, device=device).unsqueeze(0).expand(bs, -1, -1) + dino_corr_refined = dino_corr_refined * (1 - eye) + eye + + return dino_corr_refined + + +def resize_attention(attn: torch.Tensor, target_size: int) -> torch.Tensor: + """调整 attention 矩阵尺寸""" + B, N, _ = attn.shape + current_size = int(N ** 0.5) + + if current_size == target_size: + return attn + + # (B, N, N) -> (B, h, w, h, w) -> interpolate + attn = attn.view(B, current_size, current_size, current_size, current_size) + attn = attn.permute(0, 1, 3, 2, 4).contiguous() # (B, h, h, w, w) + attn = attn.view(B, current_size * current_size, current_size, current_size) + attn = F.interpolate(attn, size=(target_size, target_size), mode='bilinear', align_corners=False) + attn = attn.view(B, current_size, current_size, target_size * target_size) + attn = attn.permute(0, 3, 1, 2).contiguous() + attn = F.interpolate(attn, size=(target_size, target_size), mode='bilinear', align_corners=False) + attn = attn.view(B, target_size * target_size, target_size * target_size) + attn = F.softmax(attn, dim=-1) + + return attn + + +def prepare_inputs_ijepa(batch, device, dtype): + """准备 JEPA-GSC 的输入(包含 I-JEPA 图像)""" + images, normed_boxes, image_crops, vfm_image, ijepa_image = batch + images = images.to(device=device, dtype=dtype, non_blocking=True) + normed_boxes = normed_boxes.to(device=device, dtype=dtype, non_blocking=True) + image_crops = image_crops.to(device=device, dtype=dtype, non_blocking=True) + vfm_image = vfm_image.to(device=device, dtype=dtype, non_blocking=True) + ijepa_image = ijepa_image.to(device=device, dtype=dtype, non_blocking=True) + return images, normed_boxes, image_crops, vfm_image, ijepa_image + + +def extract_vfm_features(vfm_model, image, args): + """从 VFM 模型提取特征""" + if "dinov2" in args.use_vfm or "sd_dino" in args.use_vfm or "sam_dino" in args.use_vfm: + vfm_feats = vfm_model.get_intermediate_layers(image, reshape=True)[0] + elif 'sam' in args.use_vfm: + vfm_feats = vfm_model.image_encoder(image) + elif 'dino' in args.use_vfm: + feat = vfm_model.get_intermediate_layers(image)[0] + nb_im = feat.shape[0] + patch_size = vfm_model.patch_embed.patch_size + I, J = image[0].shape[-2] // patch_size, image[0].shape[-2] // patch_size + vfm_feats = feat[:, 1:, :].reshape(nb_im, I, J, -1).permute(0, 3, 1, 2) + else: + raise NotImplementedError(f"VFM mode {args.use_vfm} is not implemented.") + return vfm_feats + + +def extract_roi_features(x, normed_boxes, size=(3, 3), normalize=False): + """提取 ROI 特征""" + def _denormalize_boxes(normed_boxes, x): + h, w = x.shape[-2:] + denormed_boxes = [] + for boxes in normed_boxes: + new_boxes = boxes.clone() + new_boxes[:, [0, 2]] *= w + new_boxes[:, [1, 3]] *= h + denormed_boxes.append(new_boxes) + return denormed_boxes + + if size == (1, 1): + roi_feats = roi_align(x, _denormalize_boxes(normed_boxes, x), size, 1.0, -1, True)[..., 0, 0] + else: + roi_feats = roi_align(x, _denormalize_boxes(normed_boxes, x), size, 1.0, -1, True).flatten(start_dim=-2) + + if normalize: + roi_feats = F.normalize(roi_feats, dim=1) + return roi_feats + + +def compute_student_intra_image_similarity(B, context, args): + """计算学生模型的图像内相似度""" + N, _ = context[0].shape[1:] if isinstance(context, tuple) else context.shape[1:] + + if args.mode in ["qq_vfm_distill", "kk_vfm_distill", "vv_vfm_distill", "sanity_check"]: + context = context.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + context = F.normalize(context, dim=-1).transpose(-2, -1) + student_context_similarity = torch.einsum("b c m, b c n -> b m n", context, context) + elif args.mode == "csa_vfm_distill": + q_feature, k_feature = context + q_feature = q_feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + k_feature = k_feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + q_feature = F.normalize(q_feature, dim=-1).transpose(-2, -1) + k_feature = F.normalize(k_feature, dim=-1).transpose(-2, -1) + student_context_similarity = ( + torch.einsum("b c m, b c n -> b m n", q_feature, q_feature) + + torch.einsum("b c m, b c n -> b m n", k_feature, k_feature) + ) / 2.0 + elif args.mode == "all_vfm_distill": + q_feature, k_feature, v_feature = context + features = [q_feature, k_feature, v_feature] + similarities = [] + for feature in features: + feature = feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + feature = F.normalize(feature, dim=-1).transpose(-2, -1) + similarities.append(torch.einsum("b c m, b c n -> b m n", feature, feature)) + student_context_similarity = sum(similarities) / len(features) + else: + raise NotImplementedError(f"Mode '{args.mode}' is not implemented.") + + return student_context_similarity + + +def context_loss(student_corr, teacher_corr, teacher_temp=1.0, student_temp=1.0): + """Context distillation loss""" + student_log_prob = F.log_softmax(student_corr / student_temp, dim=-1) + with torch.no_grad(): + teacher_prob = F.softmax(teacher_corr / teacher_temp, dim=-1) + kl_loss = F.kl_div(student_log_prob, teacher_prob, reduction='batchmean') * (teacher_temp * student_temp) + return kl_loss + + +def soft_content_distill_loss(student_roi_features, teacher_crop_features, T=1.0): + """Content distillation loss""" + sim = torch.einsum('bpc,bc->bp', student_roi_features, teacher_crop_features) + weights = F.softmax(sim / T, dim=1) + weighted_student = (student_roi_features * weights.unsqueeze(-1)).sum(dim=1) + weighted_student = F.normalize(weighted_student, dim=-1) + cosine_similarity = (weighted_student * teacher_crop_features).sum(dim=-1) + loss = 1.0 - cosine_similarity.mean() + return loss + + +def region_scd_loss(student_roi_features, intra_vfm_roi_feats, T_teacher=1.0, T_student=1.0): + """Region correlation loss""" + with torch.no_grad(): + intra_vfm_roi_feats = intra_vfm_roi_feats.transpose(-2, -1).contiguous() + teacher_corr = torch.einsum('bic,bjc->bij', intra_vfm_roi_feats, intra_vfm_roi_feats) / T_teacher + teacher_prob = F.softmax(teacher_corr, dim=-1) + student_corr = torch.einsum('bic,bjc->bij', student_roi_features, student_roi_features) / T_student + student_log_prob = F.log_softmax(student_corr, dim=-1) + loss = F.kl_div(student_log_prob, teacher_prob, reduction='batchmean') * (T_teacher * T_student) + return loss + + +def repa_loss(clip_intermediate_out, vfm_out): + """REPA loss""" + vfm_out = vfm_out.transpose(1, 2) + clip_intermediate_out = clip_intermediate_out[:, 1:] + clip_intermediate_out = F.normalize(clip_intermediate_out, dim=-1) + similarity = (clip_intermediate_out * vfm_out).sum(dim=-1) + loss = -similarity.mean() + return loss + + +# ============ 构建函数 ============ + +def build_ijepa_attention_extractor(args): + """ + 构建 I-JEPA attention 提取器 + + 参考 ProxyCLIP 的处理方式: + 1. 计算 CLIP 需要的目标分辨率(与 DINO patch 数对齐) + 2. 在加载权重时预先插值 pos_embed 到目标分辨率 + 3. 运行时直接使用,无需额外插值开销 + """ + ijepa_ckpts = { + "vit_huge_14": "/opt/tiger/xiaomoguhzz/ijepa/IN1K-vit.h.14-300e.pth.tar", + "vit_huge_16": "/opt/tiger/xiaomoguhzz/ijepa/IN1K-vit.h.16-448px-300e.pth.tar", + } + + # 根据 CLIP 的配置选择 I-JEPA 配置 + ijepa_type = getattr(args, 'ijepa_type', 'vit_huge_14') + checkpoint = ijepa_ckpts.get(ijepa_type, ijepa_ckpts['vit_huge_14']) + + # 计算目标分辨率(与 DINO/CLIP 对齐) + # L = det_image_size // downsample_factor 是 DINO 的 patch 数 + # I-JEPA patch_size=14,所以 I-JEPA 的分辨率 = L * 14 + L = args.det_image_size // args.downsample_factor + target_img_size = L * 14 # I-JEPA patch_size = 14 + + print(f"Building I-JEPA attention extractor:") + print(f" CLIP det_image_size={args.det_image_size}, downsample_factor={args.downsample_factor}") + print(f" Target patch count: {L}x{L} = {L*L}") + print(f" I-JEPA target resolution: {target_img_size}x{target_img_size}") + + extractor = IJEPAAttentionExtractor( + checkpoint_path=checkpoint, + model_name="vit_huge", + patch_size=14, + target_img_size=target_img_size, # 目标分辨率,加载时预插值 pos_embed + device=args.device + ) + return extractor diff --git a/src/training/ablation_sam.py b/src/training/ablation_sam.py new file mode 100644 index 0000000000000000000000000000000000000000..5c8777601781795bf1386eee6a88b3806aaebb3f --- /dev/null +++ b/src/training/ablation_sam.py @@ -0,0 +1,491 @@ +""" +SAM-GSC 消融实验训练代码 + +使用 SAM image encoder 的 self-attention 代替 SD attention 来 refine DINO 相似度矩阵。 +实时计算 SAM attention(不预提取)。 +""" + +from typing import List, Tuple +import torch +import torch.nn.functional as F +import torch.nn as nn +from torchvision.ops import roi_align + +from src.segment_anything import sam_model_registry +from src.segment_anything.modeling.image_encoder import Attention as SAMAttention + + +# ============ SAM Attention 提取模块 ============ + +class SAMAttentionExtractor(nn.Module): + """ + 从 SAM image encoder 提取 global attention layers 的 attention map + """ + def __init__(self, sam_checkpoint: str, model_type: str = "vit_l", + attention_layer_indices: List[int] = None, device: str = "cuda"): + super().__init__() + + # 加载 SAM 模型 + sam = sam_model_registry[model_type](checkpoint=sam_checkpoint) + self.image_encoder = sam.image_encoder.to(device).half().eval() + + # 冻结所有参数 + for p in self.image_encoder.parameters(): + p.requires_grad = False + + # 找出 global attention 层(window_size == 0 的层) + self.global_attn_layer_indices = [] + for i, blk in enumerate(self.image_encoder.blocks): + if blk.window_size == 0: + self.global_attn_layer_indices.append(i) + + # 默认使用最后两个 global attention 层 + if attention_layer_indices is None: + self.attention_layers = self.global_attn_layer_indices[-2:] + else: + self.attention_layers = [self.global_attn_layer_indices[i] for i in attention_layer_indices] + + # 修改需要提取 attention 的层 + self._patch_attention_modules() + + def _patch_attention_modules(self): + """Patch attention modules to return attention weights""" + for layer_idx in self.attention_layers: + block = self.image_encoder.blocks[layer_idx] + original_attn = block.attn + block.attn = SAMAttentionWithOutput(original_attn) + + @torch.no_grad() + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + 提取 SAM attention map + + Args: + x: 输入图像 (B, 3, H, W),已经过预处理 + + Returns: + attention: 聚合的 attention map (B, HW, HW) + """ + # Patch embedding + x = self.image_encoder.patch_embed(x) + _, h, w, _ = x.shape + + # Position embedding + if self.image_encoder.pos_embed is not None: + if (h, w) == self.image_encoder.grid_size: + x = x + self.image_encoder.pos_embed + else: + x = x + self.image_encoder.rescale_positional_embedding(out_size=(h, w), dtype=x.dtype) + + # 收集 attention + attentions = [] + + for i, blk in enumerate(self.image_encoder.blocks): + if i in self.attention_layers: + # 这些层返回 attention + shortcut = x + x_normed = blk.norm1(x) + x_attn, attn = blk.attn(x_normed, return_attention=True) + x = shortcut + x_attn + x = x + blk.mlp(blk.norm2(x)) + attentions.append(attn) + else: + x = blk(x) + + # 聚合多层 attention: (L, B, nHead, HW, HW) -> (B, HW, HW) + if len(attentions) > 0: + attn_stack = torch.stack(attentions, dim=0) + attn_aggregated = attn_stack.mean(dim=(0, 2)) # 平均所有层和所有 head + else: + B = x.shape[0] + HW = h * w + attn_aggregated = torch.eye(HW, device=x.device, dtype=x.dtype).unsqueeze(0).expand(B, -1, -1) + + return attn_aggregated + + +class SAMAttentionWithOutput(nn.Module): + """修改 SAM Attention 模块以返回 attention weights""" + + def __init__(self, original_attn: SAMAttention): + super().__init__() + self.num_heads = original_attn.num_heads + self.scale = original_attn.scale + self.qkv = original_attn.qkv + self.proj = original_attn.proj + self.use_rel_pos = original_attn.use_rel_pos + if self.use_rel_pos: + self.rel_pos_h = original_attn.rel_pos_h + self.rel_pos_w = original_attn.rel_pos_w + + def forward(self, x: torch.Tensor, return_attention: bool = False): + B, H, W, _ = x.shape + qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) + q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) + + attn = (q * self.scale) @ k.transpose(-2, -1) + + if self.use_rel_pos: + from src.segment_anything.modeling.image_encoder import add_decomposed_rel_pos + attn = add_decomposed_rel_pos(attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W)) + + attn = attn.softmax(dim=-1) + + x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1) + x = self.proj(x) + + if return_attention: + # (B*nHead, HW, HW) -> (B, nHead, HW, HW) + attn_output = attn.view(B, self.num_heads, H * W, H * W) + return x, attn_output + return x + + +# ============ SAM-GSC 训练模块 ============ + +class DeCLIPWithREPAProjector(nn.Module): + """与 declip_plus.py 保持一致的模型包装器""" + + def __init__(self, declip_model, clip_dim=768, hidden_dim=1024, vfm_dim=768, args=None): + super().__init__() + self.model = declip_model + self.repa_layer_idx = args.repa_layer_idx + self.projector = nn.Sequential( + nn.Linear(clip_dim, hidden_dim), + nn.SiLU(), + nn.Linear(hidden_dim, hidden_dim), + nn.SiLU(), + nn.Linear(hidden_dim, vfm_dim) + ) + self.initialize_projector_weights() + self.logit_scale = self.model.logit_scale + + def initialize_projector_weights(self): + for module in self.projector.modules(): + if isinstance(module, nn.Linear): + nn.init.xavier_uniform_(module.weight) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + + def encode_image(self, *args, **kwargs): + return self.model.encode_image(*args, **kwargs) + + def encode_text(self, *args, **kwargs): + return self.model.encode_text(*args, **kwargs) + + def encode_dense(self, *args, **kwargs): + return self.model.encode_dense(*args, **kwargs) + + def encode_pseudo_boxes(self, images, rois_list, normalize=False, mode="qq", size=(1, 1)): + student_roi_features, context, intermediate_layer_output = self.model.encode_pseudo_boxes( + images, rois_list, normalize=normalize, mode=mode, size=size, + get_intermediate_layer=[self.repa_layer_idx] + ) + alpha = 0.3 + residual = intermediate_layer_output[0] + intermediate_layer_output = self.projector(intermediate_layer_output[0]) + intermediate_layer_output = alpha * residual + intermediate_layer_output + return student_roi_features, context, intermediate_layer_output + + def encode_masks(self, *args, **kwargs): + return self.model.encode_masks(*args, **kwargs) + + def train(self, mode=True): + self.model.train(mode) + self.training = self.model.training + return self + + def lock_image_tower(self, *args, **kwargs): + return self.model.lock_image_tower(*args, **kwargs) + + def lock_text_tower(self, *args, **kwargs): + return self.model.lock_text_tower(*args, **kwargs) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.model.set_grad_checkpointing(enable) + + @torch.jit.ignore + def no_weight_decay(self): + return self.model.no_weight_decay() + + +class DeCLIP_SAM_GSC: + """ + SAM-GSC 消融实验:使用 SAM attention 代替 SD attention + """ + + def __init__(self, sam_extractor: SAMAttentionExtractor): + self.sam_extractor = sam_extractor + + def __call__(self, batch, student, teacher, vfm_model, args): + losses = {} + context_weight = args.loss_context_weight + content_weight = args.loss_content_weight + region_weight = args.loss_region_weight + need_repa = args.repa_layer_idx != -1 + + if args.distributed: + student = student.module + + dtype_map = {"bf16": torch.bfloat16, "amp": torch.float16} + input_dtype = dtype_map.get(args.precision, torch.float32) + + # SAM 版本的数据只有 4 个元素(没有预缓存的 attention) + images, normed_boxes, image_crops, vfm_image, sam_image = prepare_inputs_sam(batch, args.device, input_dtype) + + # 实时计算 SAM attention + with torch.no_grad(): + sam_attn = self.sam_extractor(sam_image) + + loss_ensemble = self.intra_image_distill( + student, teacher, vfm_model, images, normed_boxes, image_crops, vfm_image, sam_attn, args + ) + + loss_context, loss_content, loss_region = loss_ensemble[0], loss_ensemble[1], loss_ensemble[2] + losses.update({"loss_context": loss_context * context_weight}) + losses.update({"loss_content": loss_content * content_weight}) + losses.update({"loss_region": loss_region * region_weight}) + + if need_repa: + loss_repa = loss_ensemble[2] + losses.update({"loss_repa": loss_repa}) + + return losses, len(images) + + def intra_image_distill(self, student, teacher, vfm_model, images, normed_boxes, image_crops, vfm_image, sam_attn, args): + need_repa = args.repa_layer_idx != -1 + roi_size = (3, 3) + B = images.shape[0] + rois_list = [] + crops_list = [] + + for bboxes_per_image, crops_per_image in zip(normed_boxes, image_crops): + valid = bboxes_per_image[:, -1] > 0.5 + rois_list.append(bboxes_per_image[valid, :4]) + crops_list.append(crops_per_image[valid]) + + image_crops = torch.cat(crops_list) + + if need_repa: + student_roi_features, context, intermediate_layer_output = student.encode_pseudo_boxes( + images, rois_list, normalize=True, mode=args.mode, size=roi_size + ) + else: + student_roi_features, context = student.encode_pseudo_boxes( + images, rois_list, normalize=True, mode=args.mode, size=roi_size + ) + + with torch.no_grad(): + teacher_crop_features = teacher.encode_image(image_crops, normalize=True) + intra_vfm_feats = extract_vfm_features(vfm_model, vfm_image, args) + vfm_roi_features = extract_roi_features(intra_vfm_feats, rois_list, normalize=True) + intra_vfm_feats = F.normalize(intra_vfm_feats, dim=1).flatten(start_dim=-2) + intra_vfm_corr = torch.einsum('bci,bcj->bij', intra_vfm_feats, intra_vfm_feats) + + # 使用 SAM attention refine DINO 相似度 + refined_intra_vfm_corr = refine_dino_with_sam(intra_vfm_corr, sam_attn, args.sd_refine_weight) + + student_intra_corr = compute_student_intra_image_similarity(images.shape[0], context, args) + loss_context = context_loss(student_intra_corr, refined_intra_vfm_corr, teacher_temp=0.8) + loss_content = soft_content_distill_loss(student_roi_features, teacher_crop_features) + loss_region = region_scd_loss(student_roi_features, vfm_roi_features) + + if need_repa: + loss_repa = repa_loss(intermediate_layer_output, intra_vfm_feats) + return loss_context, loss_content, loss_repa + else: + return loss_context, loss_content, loss_region + + +# ============ 辅助函数 ============ + +def refine_dino_with_sam(dino_corr: torch.Tensor, sam_attn: torch.Tensor, refine_weight: float) -> torch.Tensor: + """使用 SAM attention refine DINO 相似度矩阵""" + # 调整 SAM attention 尺寸以匹配 DINO + B_dino, HW_dino, _ = dino_corr.shape + B_sam, HW_sam, _ = sam_attn.shape + + if HW_dino != HW_sam: + sam_attn = resize_attention(sam_attn, int(HW_dino ** 0.5)) + + residual = dino_corr + dino_corr_propagated = torch.bmm(sam_attn, dino_corr) + dino_corr_refined = dino_corr_propagated * refine_weight + residual * (1 - refine_weight) + + # 强制对角线为 1 + bs, hw, _ = dino_corr_refined.shape + device = dino_corr_refined.device + eye = torch.eye(hw, dtype=dino_corr_refined.dtype, device=device).unsqueeze(0).expand(bs, -1, -1) + dino_corr_refined = dino_corr_refined * (1 - eye) + eye + + return dino_corr_refined + + +def resize_attention(attn: torch.Tensor, target_size: int) -> torch.Tensor: + """调整 attention 矩阵尺寸""" + B, N, _ = attn.shape + current_size = int(N ** 0.5) + + if current_size == target_size: + return attn + + # (B, N, N) -> (B, 1, h, w, h, w) -> interpolate + attn = attn.view(B, current_size, current_size, current_size, current_size) + attn = attn.permute(0, 1, 3, 2, 4).contiguous() # (B, h, h, w, w) + attn = attn.view(B, current_size * current_size, current_size, current_size) + attn = F.interpolate(attn, size=(target_size, target_size), mode='bilinear', align_corners=False) + attn = attn.view(B, current_size, current_size, target_size * target_size) + attn = attn.permute(0, 3, 1, 2).contiguous() + attn = F.interpolate(attn, size=(target_size, target_size), mode='bilinear', align_corners=False) + attn = attn.view(B, target_size * target_size, target_size * target_size) + attn = F.softmax(attn, dim=-1) + + return attn + + +def prepare_inputs_sam(batch, device, dtype): + """准备 SAM-GSC 的输入(包含 SAM 图像)""" + images, normed_boxes, image_crops, vfm_image, sam_image = batch + images = images.to(device=device, dtype=dtype, non_blocking=True) + normed_boxes = normed_boxes.to(device=device, dtype=dtype, non_blocking=True) + image_crops = image_crops.to(device=device, dtype=dtype, non_blocking=True) + vfm_image = vfm_image.to(device=device, dtype=dtype, non_blocking=True) + sam_image = sam_image.to(device=device, dtype=dtype, non_blocking=True) + return images, normed_boxes, image_crops, vfm_image, sam_image + + +def extract_vfm_features(vfm_model, image, args): + """从 VFM 模型提取特征""" + if "dinov2" in args.use_vfm or "sd_dino" in args.use_vfm or "sam_dino" in args.use_vfm: + vfm_feats = vfm_model.get_intermediate_layers(image, reshape=True)[0] + elif 'sam' in args.use_vfm: + vfm_feats = vfm_model.image_encoder(image) + elif 'dino' in args.use_vfm: + feat = vfm_model.get_intermediate_layers(image)[0] + nb_im = feat.shape[0] + patch_size = vfm_model.patch_embed.patch_size + I, J = image[0].shape[-2] // patch_size, image[0].shape[-2] // patch_size + vfm_feats = feat[:, 1:, :].reshape(nb_im, I, J, -1).permute(0, 3, 1, 2) + else: + raise NotImplementedError(f"VFM mode {args.use_vfm} is not implemented.") + return vfm_feats + + +def extract_roi_features(x, normed_boxes, size=(3, 3), normalize=False): + """提取 ROI 特征""" + def _denormalize_boxes(normed_boxes, x): + h, w = x.shape[-2:] + denormed_boxes = [] + for boxes in normed_boxes: + new_boxes = boxes.clone() + new_boxes[:, [0, 2]] *= w + new_boxes[:, [1, 3]] *= h + denormed_boxes.append(new_boxes) + return denormed_boxes + + if size == (1, 1): + roi_feats = roi_align(x, _denormalize_boxes(normed_boxes, x), size, 1.0, -1, True)[..., 0, 0] + else: + roi_feats = roi_align(x, _denormalize_boxes(normed_boxes, x), size, 1.0, -1, True).flatten(start_dim=-2) + + if normalize: + roi_feats = F.normalize(roi_feats, dim=1) + return roi_feats + + +def compute_student_intra_image_similarity(B, context, args): + """计算学生模型的图像内相似度""" + N, _ = context[0].shape[1:] if isinstance(context, tuple) else context.shape[1:] + + if args.mode in ["qq_vfm_distill", "kk_vfm_distill", "vv_vfm_distill", "sanity_check"]: + context = context.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + context = F.normalize(context, dim=-1).transpose(-2, -1) + student_context_similarity = torch.einsum("b c m, b c n -> b m n", context, context) + elif args.mode == "csa_vfm_distill": + q_feature, k_feature = context + q_feature = q_feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + k_feature = k_feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + q_feature = F.normalize(q_feature, dim=-1).transpose(-2, -1) + k_feature = F.normalize(k_feature, dim=-1).transpose(-2, -1) + student_context_similarity = ( + torch.einsum("b c m, b c n -> b m n", q_feature, q_feature) + + torch.einsum("b c m, b c n -> b m n", k_feature, k_feature) + ) / 2.0 + elif args.mode == "all_vfm_distill": + q_feature, k_feature, v_feature = context + features = [q_feature, k_feature, v_feature] + similarities = [] + for feature in features: + feature = feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + feature = F.normalize(feature, dim=-1).transpose(-2, -1) + similarities.append(torch.einsum("b c m, b c n -> b m n", feature, feature)) + student_context_similarity = sum(similarities) / len(features) + else: + raise NotImplementedError(f"Mode '{args.mode}' is not implemented.") + + return student_context_similarity + + +def context_loss(student_corr, teacher_corr, teacher_temp=1.0, student_temp=1.0): + """Context distillation loss""" + student_log_prob = F.log_softmax(student_corr / student_temp, dim=-1) + with torch.no_grad(): + teacher_prob = F.softmax(teacher_corr / teacher_temp, dim=-1) + kl_loss = F.kl_div(student_log_prob, teacher_prob, reduction='batchmean') * (teacher_temp * student_temp) + return kl_loss + + +def soft_content_distill_loss(student_roi_features, teacher_crop_features, T=1.0): + """Content distillation loss""" + sim = torch.einsum('bpc,bc->bp', student_roi_features, teacher_crop_features) + weights = F.softmax(sim / T, dim=1) + weighted_student = (student_roi_features * weights.unsqueeze(-1)).sum(dim=1) + weighted_student = F.normalize(weighted_student, dim=-1) + cosine_similarity = (weighted_student * teacher_crop_features).sum(dim=-1) + loss = 1.0 - cosine_similarity.mean() + return loss + + +def region_scd_loss(student_roi_features, intra_vfm_roi_feats, T_teacher=1.0, T_student=1.0): + """Region correlation loss""" + with torch.no_grad(): + intra_vfm_roi_feats = intra_vfm_roi_feats.transpose(-2, -1).contiguous() + teacher_corr = torch.einsum('bic,bjc->bij', intra_vfm_roi_feats, intra_vfm_roi_feats) / T_teacher + teacher_prob = F.softmax(teacher_corr, dim=-1) + student_corr = torch.einsum('bic,bjc->bij', student_roi_features, student_roi_features) / T_student + student_log_prob = F.log_softmax(student_corr, dim=-1) + loss = F.kl_div(student_log_prob, teacher_prob, reduction='batchmean') * (T_teacher * T_student) + return loss + + +def repa_loss(clip_intermediate_out, vfm_out): + """REPA loss""" + vfm_out = vfm_out.transpose(1, 2) + clip_intermediate_out = clip_intermediate_out[:, 1:] + clip_intermediate_out = F.normalize(clip_intermediate_out, dim=-1) + similarity = (clip_intermediate_out * vfm_out).sum(dim=-1) + loss = -similarity.mean() + return loss + + +# ============ 构建函数 ============ + +def build_sam_attention_extractor(args): + """构建 SAM attention 提取器""" + sam_ckpts = { + "sam-B": "/opt/tiger/xiaomoguhzz/sam_vit_b_01ec64.pth", + "sam-L": "/opt/tiger/xiaomoguhzz/sam_vit_l_0b3195.pth", + } + + # 默认使用 SAM-L + sam_type = getattr(args, 'sam_type', 'sam-L') + checkpoint = sam_ckpts.get(sam_type, sam_ckpts['sam-L']) + model_type = "vit_l" if "L" in sam_type else "vit_b" + + extractor = SAMAttentionExtractor( + sam_checkpoint=checkpoint, + model_type=model_type, + device=args.device + ) + return extractor diff --git a/src/training/coco_api.py b/src/training/coco_api.py new file mode 100644 index 0000000000000000000000000000000000000000..40f7f2c9b930de3dadd967db9d131913fc9bf54c --- /dev/null +++ b/src/training/coco_api.py @@ -0,0 +1,137 @@ +# Copyright (c) OpenMMLab. All rights reserved. +# This file add snake case alias for coco api + +import warnings +from collections import defaultdict +from typing import List, Optional, Union + +import pycocotools +from pycocotools.coco import COCO as _COCO +from pycocotools.cocoeval import COCOeval as _COCOeval + + +class COCO(_COCO): + """This class is almost the same as official pycocotools package. + + It implements some snake case function aliases. So that the COCO class has + the same interface as LVIS class. + """ + + def __init__(self, annotation_file=None): + if getattr(pycocotools, '__version__', '0') >= '12.0.2': + warnings.warn( + 'mmpycocotools is deprecated. Please install official pycocotools by "pip install pycocotools"', # noqa: E501 + UserWarning) + super().__init__(annotation_file=annotation_file) + self.img_ann_map = self.imgToAnns + self.cat_img_map = self.catToImgs + + def get_ann_ids(self, img_ids=[], cat_ids=[], area_rng=[], iscrowd=None): + return self.getAnnIds(img_ids, cat_ids, area_rng, iscrowd) + + def get_cat_ids(self, cat_names=[], sup_names=[], cat_ids=[]): + return self.getCatIds(cat_names, sup_names, cat_ids) + + def get_img_ids(self, img_ids=[], cat_ids=[]): + return self.getImgIds(img_ids, cat_ids) + + def load_anns(self, ids): + return self.loadAnns(ids) + + def load_cats(self, ids): + return self.loadCats(ids) + + def load_imgs(self, ids): + return self.loadImgs(ids) + + +# just for the ease of import +COCOeval = _COCOeval + + +class COCOPanoptic(COCO): + """This wrapper is for loading the panoptic style annotation file. + + The format is shown in the CocoPanopticDataset class. + + Args: + annotation_file (str, optional): Path of annotation file. + Defaults to None. + """ + + def __init__(self, annotation_file: Optional[str] = None) -> None: + super(COCOPanoptic, self).__init__(annotation_file) + + def createIndex(self) -> None: + """Create index.""" + # create index + print('creating index...') + # anns stores 'segment_id -> annotation' + anns, cats, imgs = {}, {}, {} + img_to_anns, cat_to_imgs = defaultdict(list), defaultdict(list) + if 'annotations' in self.dataset: + for ann in self.dataset['annotations']: + for seg_ann in ann['segments_info']: + # to match with instance.json + seg_ann['image_id'] = ann['image_id'] + img_to_anns[ann['image_id']].append(seg_ann) + # segment_id is not unique in coco dataset orz... + # annotations from different images but + # may have same segment_id + if seg_ann['id'] in anns.keys(): + anns[seg_ann['id']].append(seg_ann) + else: + anns[seg_ann['id']] = [seg_ann] + + # filter out annotations from other images + img_to_anns_ = defaultdict(list) + for k, v in img_to_anns.items(): + img_to_anns_[k] = [x for x in v if x['image_id'] == k] + img_to_anns = img_to_anns_ + + if 'images' in self.dataset: + for img_info in self.dataset['images']: + img_info['segm_file'] = img_info['file_name'].replace( + 'jpg', 'png') + imgs[img_info['id']] = img_info + + if 'categories' in self.dataset: + for cat in self.dataset['categories']: + cats[cat['id']] = cat + + if 'annotations' in self.dataset and 'categories' in self.dataset: + for ann in self.dataset['annotations']: + for seg_ann in ann['segments_info']: + cat_to_imgs[seg_ann['category_id']].append(ann['image_id']) + + print('index created!') + + self.anns = anns + self.imgToAnns = img_to_anns + self.catToImgs = cat_to_imgs + self.imgs = imgs + self.cats = cats + + def load_anns(self, + ids: Union[List[int], int] = []) -> Optional[List[dict]]: + """Load anns with the specified ids. + + ``self.anns`` is a list of annotation lists instead of a + list of annotations. + + Args: + ids (Union[List[int], int]): Integer ids specifying anns. + + Returns: + anns (List[dict], optional): Loaded ann objects. + """ + anns = [] + + if hasattr(ids, '__iter__') and hasattr(ids, '__len__'): + # self.anns is a list of annotation lists instead of + # a list of annotations + for id in ids: + anns += self.anns[id] + return anns + elif type(ids) == int: + return self.anns[ids] diff --git a/src/training/custom_transforms.py b/src/training/custom_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..9c828dc0af5935132c2e8b4a7b065d0b78e1fe2e --- /dev/null +++ b/src/training/custom_transforms.py @@ -0,0 +1,44 @@ +import random +import torch +import torch.nn as nn +import torchvision.transforms.functional as F +from torchvision.transforms import RandomCrop, InterpolationMode + + +class CustomRandomResize(nn.Module): + + def __init__(self, scale=(0.5, 2.0), interpolation=InterpolationMode.BILINEAR): + super().__init__() + self.min_scale, self.max_scale = min(scale), max(scale) + self.interpolation = interpolation + + def forward(self, img): + if isinstance(img, torch.Tensor): + height, width = img.shape[:2] + else: + width, height = img.size + scale = random.uniform(self.min_scale, self.max_scale) + new_size = [int(height * scale), int(width * scale)] + img = F.resize(img, new_size, self.interpolation) + + return img + + +class CustomRandomCrop(RandomCrop): + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be cropped. + + Returns: + PIL Image or Tensor: Cropped image. + """ + + width, height = F.get_image_size(img) + tar_h, tar_w = self.size + + tar_h = min(tar_h, height) + tar_w = min(tar_w, width) + i, j, h, w = self.get_params(img, (tar_h, tar_w)) + + return F.crop(img, i, j, h, w) diff --git a/src/training/data.py b/src/training/data.py new file mode 100644 index 0000000000000000000000000000000000000000..0b58ea1e0551765e3c7e43071d2ba6ad18a5b6c0 --- /dev/null +++ b/src/training/data.py @@ -0,0 +1,1163 @@ +import json +import logging +import os +import random +from dataclasses import dataclass +from multiprocessing import Value +from typing import List +import numpy as np +from training.misc import get_tokenizer +from training.utils import mask2box +import torch +from PIL import Image +from torch.utils.data import Dataset, DataLoader +from torch.utils.data.distributed import DistributedSampler +from open_clip.transform import FixedSizeCrop, _convert_to_rgb, det_image_transform, get_scale +from pycocotools.coco import COCO +from training.coco_api import COCOPanoptic +from panopticapi import utils +from torchvision.transforms import ToTensor, Resize, CenterCrop, Compose +from pycocotools.coco import COCO as COCOAPI +import h5py +# import mmcv +import io +# from mmengine.fileio import get +try: + from petrel_client.client import Client +except: + Client = None +from open_clip.transform import ResizeLongest + +class ProposalDistillDataset(Dataset): + def __init__(self, input_filename, transforms, image_root, + crop_size=224, + tokenizer=None, args=None): + logging.debug(f'Loading coco style data from {input_filename}.') + self.coco = COCO(input_filename) + logging.debug('Done loading data.') + self.transforms = transforms + self.tokenize = tokenizer + self.image_root = image_root + self.image_ids = list(self.coco.imgs.keys()) + self.max_anns = 20 + if not isinstance(crop_size, (tuple, list)): + crop_size = [crop_size, crop_size] + self.crop_size = crop_size + self.args = args + self.min_size = args.min_size + self.max_size = args.max_size + self.ceph_root = args.train_ceph_root + self.use_ceph = (self.ceph_root != "") + self.FILE_CLIENT = None + L = args.det_image_size//args.downsample_factor + if args.use_vfm: + if args.use_vfm == "dino-B-8": # patch 8 + vfm_resolution = L * 8 + elif args.use_vfm in ["dinov2-L","dinov2-B","sd_dino"]: # patch 14 + vfm_resolution = L* 14 + elif args.use_vfm in ["sam-B","sam-L","dino-B-16"]: # patch 16 + vfm_resolution = L* 16 + else: + raise NotImplementedError(f"vfm type '{args.use_vfm}' is not implemented.") + self.vfm_transform = det_image_transform( + vfm_resolution, + is_train=False, + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]) + else: + self.vfm_transform=None + + def read_image(self, image_name): + if self.use_ceph: + image_path = os.path.join(self.ceph_root, image_name) + if self.FILE_CLIENT is None: + self.FILE_CLIENT = Client() + try: + img_bytes = self.FILE_CLIENT.get(image_path) + buff = io.BytesIO(img_bytes) + image = Image.open(buff) + except: + print(f"Cannot load {image_path}", flush=True) + return None + else: + image_path = os.path.join(self.image_root, image_name) + try: + image = Image.open(image_path) + except: + print(f"Cannot load {image_path}", flush=True) + return None + width, height = image.size + if width < 10 or height < 10: + print(f"Invalid image, size {image.size}", flush=True) + return None + + return image + + def __len__(self): + return len(self.image_ids) + + def __getitem__(self, idx): + image_id = self.image_ids[idx] + image_info = self.coco.imgs[image_id] + if 'file_name' in image_info: + image_name = image_info['file_name'] + else: + assert 'coco_url' in image_info + coco_url = image_info['coco_url'].split('/') + image_name = os.path.join(coco_url[-2], coco_url[-1]) + + old_image = self.read_image(image_name) + vfm_image=self.vfm_transform(old_image) + if old_image is None: + next_id = random.choice(range(self.__len__())) + return self.__getitem__(next_id) + img_w, img_h = old_image.width, old_image.height + new_image = self.transforms[0](old_image) + scale = get_scale(old_image, new_image) + anns = self.coco.imgToAnns[image_id] + boxes_template = torch.zeros(self.max_anns, 4 + 1) # xyxy s + texts=[] + image_crops = torch.zeros(self.max_anns, 3, *self.crop_size) + indices = list(range(len(anns))) + random.shuffle(indices) + num_valid_boxes = 0 + for i, ann_id in enumerate(indices[:self.max_anns]): + ann = anns[ann_id] + x, y, w, h = ann['bbox'] + if w*h < (self.min_size ** 2) or w*h > (self.max_size ** 2): + continue + num_valid_boxes += 1 + cx, cy = x + w*0.5, y + h*0.5 + x0, y0, x1, y1 = \ + max(cx - w*0.75, 0), max(cy - h*0.75, 0), min(cx + w*0.75, img_w), min(cy + h*0.75, img_h) + image_crops[i] = self.transforms[1](old_image.crop((x0, y0, x1, y1))) # image crops + box_info = torch.tensor([x, y, x + w, y + h, 1.0]) # x, y, x + w, y + h + boxes_template[i] = box_info + + if num_valid_boxes == 0: + boxes_template[0] = torch.tensor([0, 0, img_w / 4, img_h / 4, 1.0]) # avoid empty + image_crops[0] = self.transforms[1](old_image.crop((0, 0, img_w // 4, img_h // 4))) + + _, h, w = new_image.shape + + boxes_template[:, :4] *= scale + boxes_template[:, [0, 2]] /= w + boxes_template[:, [1, 3]] /= h + return new_image, boxes_template, image_crops, vfm_image + + +class GridDistillDataset(Dataset): + def __init__(self, + input_filename, + transforms, + image_root, + max_split=16, + crop_size=224, + pre_transforms=False, + ceph_root="", + args=None): + if os.path.basename(input_filename) in ['lvis_v1_train.json', 'instances_train2017.json']: + # coco style distillation + logging.debug(f'Loading coco style data from {input_filename}.') + self.coco = COCO(input_filename) + logging.debug('Done loading data.') + image_ids = list(self.coco.imgs.keys()) + self.style="coco" + if args.use_knn: + with open(args.use_knn, "r") as f: + self.knn = json.load(f) + else: + self.knn=False + elif os.path.basename(input_filename) in ['chat.json','mixed_data.json','llava_v1_5_mix624k.json']: + # llava style distillation + with open(input_filename, 'r') as file: + data = json.load(file) + image_ids = [item["image"] for item in data] + self.style="llava" + else: + raise ValueError(f"Unsupported file format or style for {input_filename}.") + self._init_choices(max_split) + self.transforms = transforms + self.image_root = image_root + self.args = args + train_ratio = args.train_ratio + if train_ratio < 1.0: + num_images = int(len(image_ids) * train_ratio) + random.shuffle(image_ids) + image_ids = image_ids[:num_images] + self.image_ids = image_ids + self.max_anns = args.max_boxes + if not isinstance(crop_size, (tuple, list)): + crop_size = [crop_size, crop_size] + self.crop_size = crop_size + self._init_boxes() + self.ceph_root = ceph_root + self.use_ceph = (ceph_root != "") + self.FILE_CLIENT = None + L = args.det_image_size//args.downsample_factor + if args.use_vfm: + if args.use_vfm == "dino-B-8": # patch 8 + vfm_resolution = L * 8 + elif args.use_vfm in ["dinov2-L","dinov2-B","sd_dino"]: # patch 14 + vfm_resolution = L* 14 + elif args.use_vfm in ["sam-B","sam-L","dino-B-16"]: # patch 16 + vfm_resolution = L* 16 + else: + raise NotImplementedError(f"vfm type '{args.use_vfm}' is not implemented.") + self.vfm_transform = det_image_transform( + vfm_resolution, + is_train=False, + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]) + else: + self.vfm_transform=None + if args.use_vfm in ["sd_dino"]: + self.sd_transform = Compose([ResizeLongest(args.det_image_size), + _convert_to_rgb, + ToTensor(),]) + else: + self.sd_transform=None + + def read_image(self, image_name): + if self.use_ceph: + image_path = os.path.join(self.ceph_root, image_name) + if self.FILE_CLIENT is None: + self.FILE_CLIENT = Client() + try: + img_bytes = self.FILE_CLIENT.get(image_path) + buff = io.BytesIO(img_bytes) + image = Image.open(buff) + except: + print(f"Cannot load {image_path}", flush=True) + return None + else: + image_path = os.path.join(self.image_root, image_name) + try: + image = Image.open(image_path) + except: + print(f"Cannot load {image_path}", flush=True) + return None + + width, height = image.size + if width < 10 or height < 10: + print(f"Invalid image, size {image.size}", flush=True) + return None + return image + + def _init_choices(self, M=16): + choices = [] + for m in range(1, M+1): + for n in range((m + 1)//2, min(m*2 + 1, M+1)): + choices.append((m, n)) + self.choices = choices + + def __len__(self): + return len(self.image_ids) + + def _init_boxes(self, ): + box_templates = {} + for choice in self.choices: + M, N = choice + grid_x, grid_y = torch.meshgrid(torch.linspace(0, 1, N + 1), torch.linspace(0, 1, M + 1), + indexing='xy') + x0y0s = torch.stack([grid_x[:M, :N], grid_y[:M, :N]], dim=-1) + x1y1s = torch.stack([grid_x[1:, 1:], grid_y[1:, 1:]], dim=-1) + pseudo_boxes = torch.cat([x0y0s, x1y1s],dim=-1).view(-1, 4) + + assert pseudo_boxes.shape[0] == M*N + box_templates[choice] = pseudo_boxes + + self.box_templates = box_templates + + def _obtain_image_crops(self, image, choice): + image_crops = [] + img_w, img_h = image.size + normed_boxes = self.box_templates[choice] + indices = list(range(len(normed_boxes))) + random.shuffle(indices) + indices = indices[:self.max_anns] + boxes = normed_boxes * torch.tensor([img_w, img_h, img_w, img_h]) + for idx in indices: + box = boxes[idx] + x0, y0, x1, y1 = box.tolist() # todo expand + if self.args.crop_scale > 1.0: + box_w, box_h = x1 - x0, y1 - y0 + cx, cy = (x1 + x0)/2, (y1 + y0)/2 + delta_factor = 0.5 * self.args.crop_scale + x0, y0, x1, y1 = max(cx - box_w * delta_factor, 0), max(cy - box_h * delta_factor, 0), \ + min(cx + box_w * delta_factor, img_w), min(cy + box_h * delta_factor, img_h) + vanilla_view=self.transforms[1](image.crop((x0, y0, x1, y1))) + image_crops.append(vanilla_view) + return torch.stack(image_crops), boxes[indices] + + def _load_target(self, id: int): + return self.coco.loadAnns(self.coco.getAnnIds(id)) + + def precess_knn_images(self,image_id): + knn_image_ids = self.knn[str(image_id)] + selected_knn_image_id = random.choice(knn_image_ids) + image_info = self.coco.imgs[selected_knn_image_id] + if 'file_name' in image_info: + image_name = image_info['file_name'] + else: + assert 'coco_url' in image_info + coco_url = image_info['coco_url'].split('/') + image_name = os.path.join(coco_url[-2], coco_url[-1]) + knn_image=self.read_image(image_name) + knn_image_vfm =self.vfm_transform(knn_image) + knn_image_clip = self.transforms[0](knn_image) + return knn_image_vfm, knn_image_clip + + def __getitem__(self, idx): + image_id = self.image_ids[idx] + if self.style=="coco": + image_info = self.coco.imgs[image_id] + if 'file_name' in image_info: + image_name = image_info['file_name'] + else: + assert 'coco_url' in image_info + coco_url = image_info['coco_url'].split('/') + image_name = os.path.join(coco_url[-2], coco_url[-1]) + else: + image_name=image_id + old_image = self.read_image(image_name) + if self.vfm_transform: + vfm_image=self.vfm_transform(old_image) + else: + vfm_image = torch.empty(0) + if self.sd_transform: + sd_image = self.sd_transform(old_image) + else: + sd_image = torch.empty(0) + if old_image is None: + next_id = random.choice(range(self.__len__())) + return self.__getitem__(next_id) + new_image = self.transforms[0](old_image) + scale = get_scale(old_image, new_image) + boxes_template = torch.zeros(self.max_anns, 4 + 1) + image_crops_template = torch.zeros(self.max_anns, 3, *self.crop_size) + image_crops, boxes = self._obtain_image_crops(old_image,random.choice(self.choices)) + assert image_crops.shape[0] == boxes.shape[0] + _, h, w = new_image.shape + boxes[:, :4] *= scale + boxes[:, [0, 2]] /= w + boxes[:, [1, 3]] /= h + boxes_template[:boxes.shape[0], :4] = boxes + boxes_template[:boxes.shape[0], 4] = 1.0 + image_crops_template[:boxes.shape[0]] = image_crops + if self.knn: + knn_image_vfm, knn_image_clip=self.precess_knn_images(image_id) + if self.sd_transform is not None: + return new_image, boxes_template, image_crops_template, vfm_image, sd_image, knn_image_vfm, knn_image_clip + else: + return new_image, boxes_template, image_crops_template, vfm_image, knn_image_vfm, knn_image_clip + if self.args.precompute_knn: + return new_image, boxes_template, image_crops_template, vfm_image, image_id + if self.sd_transform is not None: + return new_image, boxes_template, image_crops_template, vfm_image, sd_image + else: + return new_image, boxes_template, image_crops_template, vfm_image + + +class DiFTProposalDistillDataset(Dataset): + def __init__(self, input_filename, transforms, image_root, + crop_size=224, + tokenizer=None, args=None): + logging.debug(f'Loading coco style data from {input_filename}.') + self.coco = COCO(input_filename) + logging.debug('Done loading data.') + self.transforms = transforms + self.tokenize = tokenizer + self.image_root = image_root + self.image_ids = list(self.coco.imgs.keys()) + self.max_anns = 20 + self.cache_path = args.cache_self_attn + self.cache = None + if not isinstance(crop_size, (tuple, list)): + crop_size = [crop_size, crop_size] + self.crop_size = crop_size + self.args = args + self.min_size = args.min_size + self.max_size = args.max_size + self.ceph_root = args.train_ceph_root + self.use_ceph = (self.ceph_root != "") + self.FILE_CLIENT = None + L = args.det_image_size//args.downsample_factor + if args.use_vfm: + if args.use_vfm == "dino-B-8": # patch 8 + vfm_resolution = L * 8 + elif args.use_vfm in ["dinov2-L","dinov2-B","sd_dino"]: # patch 14 + vfm_resolution = L* 14 + elif args.use_vfm in ["sam-B","sam-L","dino-B-16"]: # patch 16 + vfm_resolution = L* 16 + else: + raise NotImplementedError(f"vfm type '{args.use_vfm}' is not implemented.") + self.vfm_transform = det_image_transform( + vfm_resolution, + is_train=False, + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]) + else: + self.vfm_transform=None + + def read_image(self, image_name): + if self.use_ceph: + image_path = os.path.join(self.ceph_root, image_name) + if self.FILE_CLIENT is None: + self.FILE_CLIENT = Client() + try: + img_bytes = self.FILE_CLIENT.get(image_path) + buff = io.BytesIO(img_bytes) + image = Image.open(buff) + except: + print(f"Cannot load {image_path}", flush=True) + return None + else: + image_path = os.path.join(self.image_root, image_name) + try: + image = Image.open(image_path) + except: + print(f"Cannot load {image_path}", flush=True) + return None + width, height = image.size + if width < 10 or height < 10: + print(f"Invalid image, size {image.size}", flush=True) + return None + + return image + + def __len__(self): + return len(self.image_ids) + + def _lazy_open_cache(self): + if self.cache is None: + self.cache = h5py.File(self.cache_path, 'r', swmr=True) + + def __getitem__(self, idx): + image_id = self.image_ids[idx] + image_info = self.coco.imgs[image_id] + if 'file_name' in image_info: + image_name = image_info['file_name'] + else: + assert 'coco_url' in image_info + coco_url = image_info['coco_url'].split('/') + image_name = os.path.join(coco_url[-2], coco_url[-1]) + + old_image = self.read_image(image_name) + vfm_image=self.vfm_transform(old_image) + if old_image is None: + next_id = random.choice(range(self.__len__())) + return self.__getitem__(next_id) + img_w, img_h = old_image.width, old_image.height + new_image = self.transforms[0](old_image) + scale = get_scale(old_image, new_image) + anns = self.coco.imgToAnns[image_id] + boxes_template = torch.zeros(self.max_anns, 4 + 1) # xyxy s + texts=[] + image_crops = torch.zeros(self.max_anns, 3, *self.crop_size) + indices = list(range(len(anns))) + random.shuffle(indices) + num_valid_boxes = 0 + for i, ann_id in enumerate(indices[:self.max_anns]): + ann = anns[ann_id] + x, y, w, h = ann['bbox'] + if w*h < (self.min_size ** 2) or w*h > (self.max_size ** 2): + continue + num_valid_boxes += 1 + cx, cy = x + w*0.5, y + h*0.5 + x0, y0, x1, y1 = \ + max(cx - w*0.75, 0), max(cy - h*0.75, 0), min(cx + w*0.75, img_w), min(cy + h*0.75, img_h) + image_crops[i] = self.transforms[1](old_image.crop((x0, y0, x1, y1))) # image crops + box_info = torch.tensor([x, y, x + w, y + h, 1.0]) # x, y, x + w, y + h + boxes_template[i] = box_info + + if num_valid_boxes == 0: + boxes_template[0] = torch.tensor([0, 0, img_w / 4, img_h / 4, 1.0]) # avoid empty + image_crops[0] = self.transforms[1](old_image.crop((0, 0, img_w // 4, img_h // 4))) + + _, h, w = new_image.shape + + boxes_template[:, :4] *= scale + boxes_template[:, [0, 2]] /= w + boxes_template[:, [1, 3]] /= h + self._lazy_open_cache() + key = os.path.basename(image_name) + sd_self_attn = torch.from_numpy(self.cache[key][()]) + return new_image, boxes_template, image_crops, vfm_image,sd_self_attn + +class DiFTGridDistillDataset(Dataset): + def __init__(self, + input_filename, + transforms, + image_root, + max_split=16, + crop_size=224, + args=None): + self.coco = COCO(input_filename) + logging.info('Done loading data.') + self._init_choices(max_split) + self.transforms = transforms + self.image_root = image_root + self.args = args + self.image_ids = list(self.coco.imgs.keys()) + self.max_anns = args.max_boxes + self.cache_path = args.cache_self_attn + self.cache = None + if not isinstance(crop_size, (tuple, list)): + crop_size = [crop_size, crop_size] + self.crop_size = crop_size + self._init_boxes() + L = args.det_image_size//args.downsample_factor + if args.use_vfm: + if args.use_vfm == "dino-B-8": # patch 8 + vfm_resolution = L * 8 + elif args.use_vfm in ["dinov2-L","dinov2-B","sd_dino"]: # patch 14 + vfm_resolution = L* 14 + elif args.use_vfm in ["sam-B","sam-L","dino-B-16"]: # patch 16 + vfm_resolution = L* 16 + else: + raise NotImplementedError(f"vfm type '{args.use_vfm}' is not implemented.") + self.vfm_transform = det_image_transform( + vfm_resolution, + is_train=False, + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]) + else: + self.vfm_transform=None + + def read_image(self, image_name): + image_path = os.path.join(self.image_root, image_name) + try: + image = Image.open(image_path) + except: + print(f"Cannot load {image_path}", flush=True) + return None + width, height = image.size + if width < 10 or height < 10: + print(f"Invalid image, size {image.size}", flush=True) + return None + return image + + def _lazy_open_cache(self): + if self.cache is None: + self.cache = h5py.File(self.cache_path, 'r', swmr=True) + + def _init_choices(self, M=16): + choices = [] + for m in range(1, M+1): + for n in range((m + 1)//2, min(m*2 + 1, M+1)): + choices.append((m, n)) + self.choices = choices + + def __len__(self): + return len(self.image_ids) + + def _init_boxes(self, ): + box_templates = {} + for choice in self.choices: + M, N = choice + grid_x, grid_y = torch.meshgrid(torch.linspace(0, 1, N + 1), torch.linspace(0, 1, M + 1), + indexing='xy') + x0y0s = torch.stack([grid_x[:M, :N], grid_y[:M, :N]], dim=-1) + x1y1s = torch.stack([grid_x[1:, 1:], grid_y[1:, 1:]], dim=-1) + pseudo_boxes = torch.cat([x0y0s, x1y1s],dim=-1).view(-1, 4) + + assert pseudo_boxes.shape[0] == M*N + box_templates[choice] = pseudo_boxes + self.box_templates = box_templates + + def _obtain_image_crops(self, image, choice): + image_crops = [] + img_w, img_h = image.size + normed_boxes = self.box_templates[choice] + indices = list(range(len(normed_boxes))) + random.shuffle(indices) + indices = indices[:self.max_anns] + boxes = normed_boxes * torch.tensor([img_w, img_h, img_w, img_h]) + for idx in indices: + box = boxes[idx] + x0, y0, x1, y1 = box.tolist() # todo expand + if self.args.crop_scale > 1.0: + box_w, box_h = x1 - x0, y1 - y0 + cx, cy = (x1 + x0)/2, (y1 + y0)/2 + delta_factor = 0.5 * self.args.crop_scale + x0, y0, x1, y1 = max(cx - box_w * delta_factor, 0), max(cy - box_h * delta_factor, 0), \ + min(cx + box_w * delta_factor, img_w), min(cy + box_h * delta_factor, img_h) + vanilla_view=self.transforms[1](image.crop((x0, y0, x1, y1))) + image_crops.append(vanilla_view) + return torch.stack(image_crops), boxes[indices] + + def _load_target(self, id: int): + return self.coco.loadAnns(self.coco.getAnnIds(id)) + + def __getitem__(self, idx): + + image_id = self.image_ids[idx] + image_info = self.coco.imgs[image_id] + if 'file_name' in image_info: + image_name = image_info['file_name'] + else: + assert 'coco_url' in image_info + coco_url = image_info['coco_url'].split('/') + image_name = os.path.join(coco_url[-2], coco_url[-1]) + old_image = self.read_image(image_name) + if self.vfm_transform: + vfm_image=self.vfm_transform(old_image) + else: + vfm_image = torch.empty(0) + if old_image is None: + next_id = random.choice(range(self.__len__())) + return self.__getitem__(next_id) + + new_image = self.transforms[0](old_image) + scale = get_scale(old_image, new_image) + boxes_template = torch.zeros(self.max_anns, 4 + 1) + image_crops_template = torch.zeros(self.max_anns, 3, *self.crop_size) + image_crops, boxes = self._obtain_image_crops(old_image,random.choice(self.choices)) + assert image_crops.shape[0] == boxes.shape[0] + _, h, w = new_image.shape + boxes[:, :4] *= scale + boxes[:, [0, 2]] /= w + boxes[:, [1, 3]] /= h + boxes_template[:boxes.shape[0], :4] = boxes + boxes_template[:boxes.shape[0], 4] = 1.0 + image_crops_template[:boxes.shape[0]] = image_crops + + self._lazy_open_cache() + key = os.path.basename(image_name) + sd_self_attn = torch.from_numpy(self.cache[key][()]) + return new_image, boxes_template, image_crops_template, vfm_image,sd_self_attn + + + +class COCOPanopticDataset(Dataset): + def __init__(self, input_filename, transforms, image_root, embed_path, + segm_root, + crop_size=224, + tokenizer=None, + downsample_factor=16, + min_size=8, + max_size=1024, + args=None): + logging.debug(f'Loading coco caption style data from {input_filename}.') + self.coco = COCOPanoptic(input_filename) + logging.debug('Done loading data.') + self.transforms = transforms + self.tokenize = tokenizer + self.image_root = image_root + self.embeddings = np.load(embed_path) + self.image_ids = list(self.coco.imgs.keys()) + num_annos = [len(anns) for anns in self.coco.imgToAnns.values()] + self.max_anns = min(max(num_annos), 100) + if not isinstance(crop_size, (tuple, list)): + crop_size = [crop_size, crop_size] + self.crop_size = crop_size + self.min_size = 8 # fix for val + self.max_size = 1024 + self.segm_root = segm_root + self.downsample_factor = downsample_factor + self.segm_transform = ResizeLongest(max_size=self.transforms[0].transforms[0].max_size // downsample_factor, + fill=0) # downsample to the output size of image encoder + self.args=args + cat_ids = sorted([cat['id'] for cat in self.coco.cats.values()]) + self.cat_id2label = {cat_id: label for label, cat_id in enumerate(cat_ids)} + self.label2cat_id = {label: cat_id for cat_id, label in self.cat_id2label.items()} + def __len__(self): + return len(self.image_ids) + + @staticmethod + def _load_segm(segm_path): + segmentation = np.array( + Image.open(segm_path), + dtype=np.uint8 + ) + # img_bytes = get(segm_path) + # pan_png = mmcv.imfrombytes( + # img_bytes, flag='color', channel_order='rgb').squeeze() + segm_map = utils.rgb2id(segmentation) + + return segm_map + + def __getitem__(self, idx): + image_id = self.image_ids[idx] + image_info = self.coco.imgs[image_id] + image_name = image_info['file_name'] + segm_file = image_info['segm_file'] + image_path = os.path.join(self.image_root, image_name) + segm_path = os.path.join(self.segm_root, segm_file) + segm_map = self._load_segm(segm_path) + old_image = Image.open(image_path) + img_w, img_h = old_image.width, old_image.height + new_image = self.transforms[0](old_image) + scale = get_scale(old_image, new_image) + anns = self.coco.imgToAnns[image_id] + boxes_template = torch.zeros(self.max_anns, 4 + 2 + 1 + 1) # xyxy c valid size, isthing + image_crops = torch.zeros(self.max_anns, 3, *self.crop_size) + gt_masks = torch.zeros(self.max_anns, self.segm_transform.max_size,self.segm_transform.max_size) + masked_image_crops = torch.zeros(self.max_anns, 3, *self.crop_size) + for i, ann in enumerate(anns): + if i == self.max_anns: + break + cat_id = ann['category_id'] + is_thing = self.coco.cats[cat_id]['isthing'] + if is_thing > 0: + x, y, w, h = ann['bbox'] + cx, cy = x + w*0.5, y + h*0.5 + x0, y0, x1, y1 = \ + max(cx - w*0.75, 0), max(cy - h*0.75, 0), min(cx + w*0.75, img_w), min(cy + h*0.75, img_h) + else: + x0, y0, x1, y1 = mask2box(segm_map == ann['id']) + x, y, w, h = x0, y0, x1 - x0, y1 - y0 + if w * h < (self.min_size ** 2) or w * h > (self.max_size ** 2): + continue + image_crops[i] = self.transforms[1](old_image.crop((x0, y0, x1, y1))) # image crops + # masked image crop + np_old_image = np.array(old_image) + np_old_image[segm_map != ann['id']] = 114 + masked_old_image = Image.fromarray(np_old_image) + masked_image_crops[i] = self.transforms[1](masked_old_image.crop((x0, y0, x1, y1))) # image crops + + gt_mask = torch.from_numpy(segm_map == ann['id']).float() + gt_mask = self.segm_transform(gt_mask[None]) > 0.0 + cls_label = self.cat_id2label[cat_id] + box_info = torch.tensor([x, y, x + w, y + h, cls_label, 1.0, w * h, is_thing]) # x, y, x + w, y + h + boxes_template[i] = box_info + gt_masks[i] = gt_mask[0] + _, h, w = new_image.shape + + boxes_template[:, :4] *= scale + boxes_template[:, [0, 2]] /= w + boxes_template[:, [1, 3]] /= h + return image_name, new_image, boxes_template, image_crops, gt_masks, masked_image_crops + + +class COCORegionCLIPDataset(Dataset): + def __init__(self, input_filename, transforms, image_root, args): + logging.debug(f'Loading coco caption style data from {input_filename}.') + self.coco = COCO(input_filename) + logging.debug('Done loading data.') + self.transforms = transforms + self.image_root = image_root + image_ids = list(self.coco.imgToAnns.keys()) # only use images that have anns + train_ratio = args.train_ratio + if train_ratio < 1.0: + num_images = int(len(image_ids) * train_ratio) + random.shuffle(image_ids) + image_ids = image_ids[:num_images] + self.image_ids = image_ids + + num_annos = [len(anns) for anns in self.coco.imgToAnns.values()] + self.max_anns = min(max(num_annos), 20) + self.args = args + self.ceph_root = args.train_ceph_root + self.use_ceph = (self.ceph_root != "") + self.FILE_CLIENT = None + cat_ids = sorted([cat['id'] for cat in self.coco.cats.values()]) + + self.cat_id2label = {cat_id: label for label, cat_id in enumerate(cat_ids)} + + def __len__(self): + return len(self.image_ids) + + def read_image(self, image_name): + if self.use_ceph: + image_path = os.path.join(self.ceph_root, image_name) + if self.FILE_CLIENT is None: + self.FILE_CLIENT = Client() + img_bytes = self.FILE_CLIENT.get(image_path) + buff = io.BytesIO(img_bytes) + image = Image.open(buff) + else: + image_path = os.path.join(self.image_root, image_name) + image = Image.open(image_path) + return image + + def __getitem__(self, idx): + image_id = self.image_ids[idx] + image_info = self.coco.imgs[image_id] + image_name = image_info['file_name'] + # image_path = os.path.join(self.image_root, image_name) + # old_image = Image.open(image_path) + old_image = self.read_image(image_name) + new_image = self.transforms[0](old_image) + + scale = get_scale(old_image, new_image) + anns = self.coco.imgToAnns[image_id] + boxes_template = torch.zeros(self.max_anns, 4 + 2) # xyxy cls valid + + for i, ann in enumerate(anns): + if i == self.max_anns: + break + cat_id = ann['category_id'] + x, y, w, h = ann['bbox'] + cls_label = self.cat_id2label[cat_id] + box_info = torch.tensor([x, y, x + w, y + h, cls_label, 1.0]) # x, y, x + w, y + h + boxes_template[i] = box_info + + _, h, w = new_image.shape + + boxes_template[:, :4] *= scale + boxes_template[:, [0, 2]] /= w + boxes_template[:, [1, 3]] /= h + + return new_image, boxes_template + + +class COCOCaptionDataset(Dataset): + def __init__(self, input_filename, transforms, image_root, + tokenizer=None, args=None): + logging.debug(f'Loading coco caption style data from {input_filename}.') + with open(input_filename, 'r') as f: + self.images = json.load(f)['images'] + logging.debug('Done loading data.') + self.transforms = transforms + self.tokenize = get_tokenizer(args.model) + self.image_root = image_root + self.ceph_root = args.train_ceph_root + self.use_ceph = (self.ceph_root != "") + self.FILE_CLIENT = None + + def read_image(self, image_name): + if self.use_ceph: + image_path = os.path.join(self.ceph_root, image_name) + if self.FILE_CLIENT is None: + self.FILE_CLIENT = Client() + try: + img_bytes = self.FILE_CLIENT.get(image_path) + buff = io.BytesIO(img_bytes) + image = Image.open(buff) + except: + print(f"Cannot load {image_path}", flush=True) + return None + else: + image_path = os.path.join(self.image_root, image_name) + try: + image = Image.open(image_path) + except: + print(f"Cannot load {image_path}", flush=True) + return None + + width, height = image.size + if width < 10 or height < 10: + print(f"Invalid image, size {image.size}", flush=True) + return None + + return image + + def __len__(self): + return len(self.images) + + def __getitem__(self, idx): + image_info = self.images[idx] + text = random.choice(image_info['captions']) + image_name = image_info['file_name'] + image = self.read_image(image_name) + if image is None: + next_id = random.choice(range(self.__len__())) + return self.__getitem__(next_id) + image = self.transforms(image) + text = self.tokenize([text])[0] + return image, text + + +def get_coco_panoptic_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None): + input_filename = args.train_data if is_train else args.val_data + + if args.image_crop_size>0 : + image_crop_size=args.image_crop_size + else: + if args.model=="EVA02-CLIP-B-16" or args.model=="ViT-B-16" or args.model=="ViT-L-14" or "Tiny" in args.model: + image_crop_size=224 + elif args.model=="siglip-so400m-patch14-384": + image_crop_size=384 + else: + image_crop_size=336 # ViT-L-14-336 & EVA02-CLIP-L-14-336 + assert input_filename + + dataset = COCOPanopticDataset( + input_filename, + preprocess_fn, + segm_root=args.val_segm_root, + image_root=args.val_image_root, + embed_path=args.embed_path, + tokenizer=tokenizer, + crop_size=image_crop_size, + min_size=args.min_size, + max_size=args.max_size, + downsample_factor=args.downsample_factor, + args=args, + ) + num_samples = len(dataset) + # TODO: distributed for test + sampler = DistributedSampler(dataset) if args.distributed else None # and is_train else None + shuffle = is_train and sampler is None + if is_train: + batch_size = args.batch_size + else: + batch_size = min(args.batch_size, 1) # only support bs = 1 for inference + dataloader = DataLoader( + dataset, + batch_size=batch_size, + shuffle=shuffle, + num_workers=args.workers, + pin_memory=True, + sampler=sampler, + drop_last=is_train, + ) + dataloader.num_samples = num_samples + dataloader.num_batches = len(dataloader) + + return DataInfo(dataloader, sampler) + + +def get_proposal_distill_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None): + assert is_train + input_filename = args.train_data # if is_train else args.val_data + assert input_filename + dataset = ProposalDistillDataset( + input_filename, + preprocess_fn, + image_root=args.train_image_root, + tokenizer=tokenizer, + crop_size=args.input_size, + args=args + ) + num_samples = len(dataset) + # TODO: distributed for test + sampler = DistributedSampler(dataset) if args.distributed else None # and is_train else None + shuffle = is_train and sampler is None + batch_size = args.batch_size + dataloader = DataLoader( + dataset, + batch_size=batch_size, + shuffle=shuffle, + num_workers=args.workers, + pin_memory=True, + sampler=sampler, + drop_last=is_train, + ) + dataloader.num_samples = num_samples + dataloader.num_batches = len(dataloader) + + return DataInfo(dataloader, sampler) + + +def get_grid_distill_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None): + assert is_train + input_filename = args.train_data + assert input_filename + dataset = GridDistillDataset( + input_filename=input_filename, + transforms=preprocess_fn, + image_root=args.train_image_root, + crop_size=args.input_size, + max_split=args.max_split, + ceph_root=args.train_ceph_root, + pre_transforms=args.pre_transforms, + args=args + ) + num_samples = len(dataset) + # TODO: distributed for test + sampler = DistributedSampler(dataset) if args.distributed else None # and is_train else None + shuffle = is_train and sampler is None + batch_size = args.batch_size + dataloader = DataLoader( + dataset, + batch_size=batch_size, + shuffle=shuffle, + num_workers=args.workers, + pin_memory=True, + sampler=sampler, + drop_last=is_train, + ) + dataloader.num_samples = num_samples + dataloader.num_batches = len(dataloader) + + return DataInfo(dataloader, sampler) + +def get_dift_grid_distill_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None): + assert is_train + input_filename = args.train_data + assert input_filename + dataset = DiFTGridDistillDataset( + input_filename=input_filename, + transforms=preprocess_fn, + image_root=args.train_image_root, + crop_size=args.input_size, + max_split=args.max_split, + args=args + ) + num_samples = len(dataset) + # TODO: distributed for test + sampler = DistributedSampler(dataset) if args.distributed else None # and is_train else None + shuffle = is_train and sampler is None + batch_size = args.batch_size + dataloader = DataLoader( + dataset, + batch_size=batch_size, + shuffle=shuffle, + num_workers=args.workers, + pin_memory=True, + sampler=sampler, + drop_last=is_train, + ) + dataloader.num_samples = num_samples + dataloader.num_batches = len(dataloader) + + return DataInfo(dataloader, sampler) + +def get_region_clip_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None): + assert is_train + input_filename = args.train_data + assert input_filename + dataset = COCORegionCLIPDataset( + input_filename=input_filename, + transforms=preprocess_fn, + image_root=args.train_image_root, + args=args, + ) + num_samples = len(dataset) + # TODO: distributed for test + sampler = DistributedSampler(dataset) if args.distributed else None # and is_train else None + shuffle = is_train and sampler is None + batch_size = args.batch_size + dataloader = DataLoader( + dataset, + batch_size=batch_size, + shuffle=shuffle, + num_workers=args.workers, + pin_memory=True, + sampler=sampler, + drop_last=is_train, + ) + dataloader.num_samples = num_samples + dataloader.num_batches = len(dataloader) + + return DataInfo(dataloader, sampler) + + +def get_coco_caption_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None): + assert is_train + input_filename = args.train_data + assert input_filename + dataset = COCOCaptionDataset( + input_filename, + preprocess_fn, + image_root=args.train_image_root, + tokenizer=tokenizer, + args=args + ) + num_samples = len(dataset) + sampler = DistributedSampler(dataset) if args.distributed and is_train else None + shuffle = is_train and sampler is None + + dataloader = DataLoader( + dataset, + batch_size=args.batch_size, + shuffle=shuffle, + num_workers=args.workers, + pin_memory=True, + sampler=sampler, + drop_last=is_train, + ) + dataloader.num_samples = num_samples + dataloader.num_batches = len(dataloader) + + return DataInfo(dataloader, sampler) + +def get_dift_proposal_distill_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None): + assert is_train + input_filename = args.train_data # if is_train else args.val_data + assert input_filename + dataset = DiFTProposalDistillDataset( + input_filename, + preprocess_fn, + image_root=args.train_image_root, + tokenizer=tokenizer, + crop_size=args.input_size, + args=args + ) + num_samples = len(dataset) + # TODO: distributed for test + sampler = DistributedSampler(dataset) if args.distributed else None # and is_train else None + shuffle = is_train and sampler is None + batch_size = args.batch_size + dataloader = DataLoader( + dataset, + batch_size=batch_size, + shuffle=shuffle, + num_workers=args.workers, + pin_memory=True, + sampler=sampler, + drop_last=is_train, + ) + dataloader.num_samples = num_samples + dataloader.num_batches = len(dataloader) + + return DataInfo(dataloader, sampler) + +class SharedEpoch: + def __init__(self, epoch: int = 0): + self.shared_epoch = Value('i', epoch) + + def set_value(self, epoch): + self.shared_epoch.value = epoch + + def get_value(self): + return self.shared_epoch.value + + +@dataclass +class DataInfo: + dataloader: DataLoader + sampler: DistributedSampler = None + shared_epoch: SharedEpoch = None + + def set_epoch(self, epoch): + if self.shared_epoch is not None: + self.shared_epoch.set_value(epoch) + if self.sampler is not None and isinstance(self.sampler, DistributedSampler): + self.sampler.set_epoch(epoch) + + +def get_dataset_fn(data_path, dataset_type): + if dataset_type == 'coco_panoptic': + return get_coco_panoptic_dataset + elif dataset_type == 'proposals_distill': + return get_proposal_distill_dataset + elif dataset_type == 'grid_distill': + return get_grid_distill_dataset + elif dataset_type == 'dift_grid_distill': + return get_dift_grid_distill_dataset + elif dataset_type == 'dift_proposals_distill': + return get_dift_proposal_distill_dataset + elif dataset_type == 'region_clip': + return get_region_clip_dataset + elif dataset_type == 'coco_caption': + return get_coco_caption_dataset + elif dataset_type == 'ablation_sam': + from training.data_ablation import get_ablation_sam_dataset + return get_ablation_sam_dataset + elif dataset_type == 'ablation_ijepa': + from training.data_ablation import get_ablation_ijepa_dataset + return get_ablation_ijepa_dataset + else: + raise ValueError(f"Unsupported dataset type: {dataset_type}") + + +def get_data(args, preprocess_fns, epoch=0, tokenizer=None): + preprocess_train, preprocess_val = preprocess_fns + data = {} + if args.train_data: + data["train"] = get_dataset_fn(args.train_data, args.dataset_type)( + args, preprocess_train, is_train=True, epoch=epoch, tokenizer=tokenizer) + + if args.val_data: + data["val"] = get_dataset_fn(args.val_data, dataset_type=args.test_type)( + args, preprocess_val, is_train=False, tokenizer=tokenizer) + + return data + +class SDNormalize(object): + def __call__(self, img): + return 2.0 * img - 1.0 \ No newline at end of file diff --git a/src/training/data_ablation.py b/src/training/data_ablation.py new file mode 100644 index 0000000000000000000000000000000000000000..345ef8a881df5772f3ea506b4dcaad57cb838497 --- /dev/null +++ b/src/training/data_ablation.py @@ -0,0 +1,298 @@ +""" +消融实验专用数据集 + +支持 SAM-GSC 和 JEPA-GSC 的数据加载,提供额外的图像预处理用于实时计算 attention。 +""" + +import json +import logging +import os +import random +from dataclasses import dataclass +import numpy as np +import torch +from PIL import Image +from torch.utils.data import Dataset, DataLoader +from torch.utils.data.distributed import DistributedSampler +from open_clip.transform import det_image_transform, get_scale +from pycocotools.coco import COCO + + +class AblationGridDistillDataset(Dataset): + """ + 消融实验专用数据集 + + 在 GridDistillDataset 基础上,额外返回用于 SAM 或 I-JEPA 的预处理图像。 + """ + + def __init__(self, + input_filename, + transforms, + image_root, + max_split=16, + crop_size=224, + args=None, + ablation_type="sam"): # "sam" or "ijepa" + + self.coco = COCO(input_filename) + logging.info('Done loading data.') + self._init_choices(max_split) + self.transforms = transforms + self.image_root = image_root + self.args = args + self.ablation_type = ablation_type + + image_ids = list(self.coco.imgs.keys()) + train_ratio = args.train_ratio + if train_ratio < 1.0: + num_images = int(len(image_ids) * train_ratio) + random.shuffle(image_ids) + image_ids = image_ids[:num_images] + self.image_ids = image_ids + + self.max_anns = args.max_boxes + if not isinstance(crop_size, (tuple, list)): + crop_size = [crop_size, crop_size] + self.crop_size = crop_size + self._init_boxes() + + # 计算各模型需要的分辨率 + L = args.det_image_size // args.downsample_factor + + # VFM (DINOv2) 分辨率 + if args.use_vfm: + if args.use_vfm == "dino-B-8": + vfm_resolution = L * 8 + elif args.use_vfm in ["dinov2-L", "dinov2-B", "sd_dino"]: + vfm_resolution = L * 14 + elif args.use_vfm in ["sam-B", "sam-L", "dino-B-16"]: + vfm_resolution = L * 16 + else: + raise NotImplementedError(f"vfm type '{args.use_vfm}' is not implemented.") + + self.vfm_transform = det_image_transform( + vfm_resolution, + is_train=False, + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225] + ) + else: + self.vfm_transform = None + + # 消融模型分辨率 + if ablation_type == "sam": + # SAM patch_size=16 + ablation_resolution = L * 16 + self.ablation_transform = det_image_transform( + ablation_resolution, + is_train=False, + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225] + ) + elif ablation_type == "ijepa": + # I-JEPA patch_size=14 + ablation_resolution = L * 14 + self.ablation_transform = det_image_transform( + ablation_resolution, + is_train=False, + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225] + ) + else: + raise ValueError(f"Unknown ablation type: {ablation_type}") + + logging.info(f"Ablation Dataset: VFM resolution={vfm_resolution if args.use_vfm else 'None'}, " + f"{ablation_type.upper()} resolution={ablation_resolution}") + + def read_image(self, image_name): + image_path = os.path.join(self.image_root, image_name) + try: + image = Image.open(image_path) + except: + print(f"Cannot load {image_path}", flush=True) + return None + width, height = image.size + if width < 10 or height < 10: + print(f"Invalid image, size {image.size}", flush=True) + return None + return image + + def _init_choices(self, M=16): + choices = [] + for m in range(1, M + 1): + for n in range((m + 1) // 2, min(m * 2 + 1, M + 1)): + choices.append((m, n)) + self.choices = choices + + def __len__(self): + return len(self.image_ids) + + def _init_boxes(self): + box_templates = {} + for choice in self.choices: + M, N = choice + grid_x, grid_y = torch.meshgrid( + torch.linspace(0, 1, N + 1), + torch.linspace(0, 1, M + 1), + indexing='xy' + ) + x0y0s = torch.stack([grid_x[:M, :N], grid_y[:M, :N]], dim=-1) + x1y1s = torch.stack([grid_x[1:, 1:], grid_y[1:, 1:]], dim=-1) + pseudo_boxes = torch.cat([x0y0s, x1y1s], dim=-1).view(-1, 4) + assert pseudo_boxes.shape[0] == M * N + box_templates[choice] = pseudo_boxes + self.box_templates = box_templates + + def _obtain_image_crops(self, image, choice): + image_crops = [] + img_w, img_h = image.size + normed_boxes = self.box_templates[choice] + indices = list(range(len(normed_boxes))) + random.shuffle(indices) + indices = indices[:self.max_anns] + boxes = normed_boxes * torch.tensor([img_w, img_h, img_w, img_h]) + + for idx in indices: + box = boxes[idx] + x0, y0, x1, y1 = box.tolist() + if self.args.crop_scale > 1.0: + box_w, box_h = x1 - x0, y1 - y0 + cx, cy = (x1 + x0) / 2, (y1 + y0) / 2 + delta_factor = 0.5 * self.args.crop_scale + x0 = max(cx - box_w * delta_factor, 0) + y0 = max(cy - box_h * delta_factor, 0) + x1 = min(cx + box_w * delta_factor, img_w) + y1 = min(cy + box_h * delta_factor, img_h) + vanilla_view = self.transforms[1](image.crop((x0, y0, x1, y1))) + image_crops.append(vanilla_view) + + return torch.stack(image_crops), boxes[indices] + + def __getitem__(self, idx): + image_id = self.image_ids[idx] + image_info = self.coco.imgs[image_id] + + if 'file_name' in image_info: + image_name = image_info['file_name'] + else: + assert 'coco_url' in image_info + coco_url = image_info['coco_url'].split('/') + image_name = os.path.join(coco_url[-2], coco_url[-1]) + + old_image = self.read_image(image_name) + if old_image is None: + next_id = random.choice(range(self.__len__())) + return self.__getitem__(next_id) + + # VFM 图像 + if self.vfm_transform: + vfm_image = self.vfm_transform(old_image) + else: + vfm_image = torch.empty(0) + + # 消融模型图像 (SAM 或 I-JEPA) + ablation_image = self.ablation_transform(old_image) + + # CLIP 图像 + new_image = self.transforms[0](old_image) + scale = get_scale(old_image, new_image) + + # Boxes 和 crops + boxes_template = torch.zeros(self.max_anns, 4 + 1) + image_crops_template = torch.zeros(self.max_anns, 3, *self.crop_size) + image_crops, boxes = self._obtain_image_crops(old_image, random.choice(self.choices)) + + assert image_crops.shape[0] == boxes.shape[0] + _, h, w = new_image.shape + boxes[:, :4] *= scale + boxes[:, [0, 2]] /= w + boxes[:, [1, 3]] /= h + boxes_template[:boxes.shape[0], :4] = boxes + boxes_template[:boxes.shape[0], 4] = 1.0 + image_crops_template[:boxes.shape[0]] = image_crops + + return new_image, boxes_template, image_crops_template, vfm_image, ablation_image + + +# ============ 数据加载函数 ============ + +@dataclass +class DataInfo: + dataloader: DataLoader + sampler: DistributedSampler = None + + def set_epoch(self, epoch): + if self.sampler is not None and isinstance(self.sampler, DistributedSampler): + self.sampler.set_epoch(epoch) + + +def get_ablation_sam_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None): + """获取 SAM 消融实验数据集""" + assert is_train + input_filename = args.train_data + assert input_filename + + dataset = AblationGridDistillDataset( + input_filename=input_filename, + transforms=preprocess_fn, + image_root=args.train_image_root, + crop_size=args.input_size, + max_split=args.max_split, + args=args, + ablation_type="sam" + ) + + num_samples = len(dataset) + sampler = DistributedSampler(dataset) if args.distributed else None + shuffle = is_train and sampler is None + batch_size = args.batch_size + + dataloader = DataLoader( + dataset, + batch_size=batch_size, + shuffle=shuffle, + num_workers=args.workers, + pin_memory=True, + sampler=sampler, + drop_last=is_train, + ) + dataloader.num_samples = num_samples + dataloader.num_batches = len(dataloader) + + return DataInfo(dataloader, sampler) + + +def get_ablation_ijepa_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None): + """获取 I-JEPA 消融实验数据集""" + assert is_train + input_filename = args.train_data + assert input_filename + + dataset = AblationGridDistillDataset( + input_filename=input_filename, + transforms=preprocess_fn, + image_root=args.train_image_root, + crop_size=args.input_size, + max_split=args.max_split, + args=args, + ablation_type="ijepa" + ) + + num_samples = len(dataset) + sampler = DistributedSampler(dataset) if args.distributed else None + shuffle = is_train and sampler is None + batch_size = args.batch_size + + dataloader = DataLoader( + dataset, + batch_size=batch_size, + shuffle=shuffle, + num_workers=args.workers, + pin_memory=True, + sampler=sampler, + drop_last=is_train, + ) + dataloader.num_samples = num_samples + dataloader.num_batches = len(dataloader) + + return DataInfo(dataloader, sampler) diff --git a/src/training/declip.py b/src/training/declip.py new file mode 100644 index 0000000000000000000000000000000000000000..951f659818968ca5c2a88ba2da11a4f83f917e6c --- /dev/null +++ b/src/training/declip.py @@ -0,0 +1,97 @@ +import torch +import torch.nn.functional as F +from training.misc import is_main_process +import torch + + +class DeCLIP: + def __call__(self, batch, student, teacher, vfm_model, args): + losses={} + context_weight = args.loss_context_weight + content_weight = args.loss_content_weight + if args.distributed: + student = student.module + dtype_map = {"bf16": torch.bfloat16, "amp": torch.float16} + input_dtype = dtype_map.get(args.precision, torch.float32) + images, normed_boxes, image_crops, proxy_image = batch + images = images.to(device=args.device, dtype=input_dtype, non_blocking=True) + normed_boxes = normed_boxes.to(device=args.device, dtype=input_dtype,non_blocking=True) + image_crops = image_crops.to(device=args.device, dtype=input_dtype,non_blocking=True) + proxy_image=proxy_image.to(device=args.device, dtype=input_dtype, non_blocking=True) + + rois_list = [] + crops_list = [] + for bboxes_per_image, crops_per_image in zip(normed_boxes, image_crops): + valid = bboxes_per_image[:, -1] > 0.5 + rois_list.append(bboxes_per_image[valid, :4]) + crops_list.append(crops_per_image[valid]) + image_crops = torch.cat(crops_list) + student_roi_features, context = student.encode_pseudo_boxes(images, rois_list, normalize=True, mode = args.mode) + + with torch.no_grad(): + teacher_crop_features = teacher.encode_image(image_crops, normalize=True) + if args.use_vfm: + teacher_context_similarity, teacher_h, teacher_w = self.get_teacher_context_similarity(vfm_model,proxy_image,args) + else: + teacher_context_similarity=teacher_h = teacher_w=None + + if args.use_vfm: + student_context_similarity=self.get_student_context_similarity(images, context,teacher_h,teacher_w, args) + _loss_context=(teacher_context_similarity - student_context_similarity).norm(p=2,dim=-1).mean() + losses.update({"loss_context":_loss_context*context_weight}) + + _loss_content = 1.0 - (student_roi_features * teacher_crop_features).sum(-1).mean() + losses.update({"loss_content":_loss_content * content_weight}) + return losses, len(images) + + def get_teacher_context_similarity(self,vfm_model,proxy_image,args): + if 'sam' in args.use_vfm: + vfm_feats=vfm_model.image_encoder(proxy_image) + elif "dinov2" in args.use_vfm: + vfm_feats = vfm_model.get_intermediate_layers(proxy_image, reshape=True)[0] + elif 'dino' in args.use_vfm: + feat = vfm_model.get_intermediate_layers(proxy_image)[0] + nb_im = feat.shape[0] + patch_size = vfm_model.patch_embed.patch_size + I, J = proxy_image[0].shape[-2] // patch_size, proxy_image[0].shape[-2] // patch_size + vfm_feats = feat[:, 1:, :].reshape(nb_im, I, J, -1).permute(0, 3, 1, 2) + else: + raise NotImplementedError(f"mode {args.use_vfm} is not implemented yet.") + teacher_h,teacher_w=vfm_feats.shape[-2:] + vfm_feats= F.normalize(vfm_feats.flatten(-2,-1), dim=1) + vfm_similarity = torch.einsum("b c m, b c n -> b m n", vfm_feats, vfm_feats) + return vfm_similarity,teacher_h,teacher_w + + def get_student_context_similarity(self,images,context,teacher_h,teacher_w,args): + B = images.shape[0] + if args.mode in ["qq_vfm_distill","kk_vfm_distill","vv_vfm_distill","sanity_check"]: + N, _ = context.shape[1:] + context=context.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + bs, N, C = context.shape + n_sqrt = int(N ** 0.5) + if n_sqrt != teacher_h or n_sqrt != teacher_w: + context_reshaped = context.transpose(-2,-1).contiguous().view(bs, C, n_sqrt, n_sqrt) + context_resized = F.interpolate(context_reshaped, size=(teacher_h, teacher_w), mode='bilinear', align_corners=False) + context = context_resized.transpose(-2,-1).contiguous().view(bs, teacher_h * teacher_w, C) + context = F.normalize(context, dim=-1).transpose(-2,-1) + student_context_similarity=torch.einsum("b c m, b c n -> b m n", context, context) + elif args.mode == "csa_vfm_distill": + q_feature, k_feature = context + N, _ = q_feature.shape[1:] + q_feature = q_feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + k_feature = k_feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + q_feature = F.normalize(q_feature, dim=-1).transpose(-2,-1) + k_feature = F.normalize(k_feature, dim=-1).transpose(-2,-1) + student_context_similarity=(torch.einsum("b c m, b c n -> b m n", q_feature, q_feature)+torch.einsum("b c m, b c n -> b m n", k_feature, k_feature))/2.0 + elif args.mode == "all_vfm_distill": + q_feature, k_feature, v_feature = context + q_feature = F.normalize(q_feature, dim=-1).transpose(-2,-1) + k_feature = F.normalize(k_feature, dim=-1).transpose(-2,-1) + v_feature = F.normalize(v_feature, dim=-1).transpose(-2,-1) + student_context_similarity=(torch.einsum("b c m, b c n -> b m n", q_feature, q_feature)+ + torch.einsum("b c m, b c n -> b m n", k_feature, k_feature)+ + torch.einsum("b c m, b c n -> b m n", v_feature, v_feature))/3.0 + + else: + raise NotImplementedError(f"Mode '{args.mode}' is not implemented.") + return student_context_similarity \ No newline at end of file diff --git a/src/training/declip2.py b/src/training/declip2.py new file mode 100644 index 0000000000000000000000000000000000000000..160b13fccb44286cf6dd4a126d51fa6d9cb983d1 --- /dev/null +++ b/src/training/declip2.py @@ -0,0 +1,161 @@ +from typing import List +import torch +import torch.nn.functional as F +import torch +from torch.cuda.amp import autocast +from torchvision.ops import roi_align +# ! declip2只加入了region loss,没有加入sd smoothing +class DeCLIP2: + def __call__(self, batch, student, teacher, vfm_model, args): + losses = {} + context_weight = args.loss_context_weight + content_weight = args.loss_content_weight + region_weight= args.loss_region_weight + if args.distributed: + student = student.module + dtype_map = {"bf16": torch.bfloat16, "amp": torch.float16} + input_dtype = dtype_map.get(args.precision, torch.float32) + images, normed_boxes, image_crops, vfm_image = prepare_inputs(batch, args.device, input_dtype) + loss_ensemble = self.intra_image_distill(student, teacher, vfm_model, images, normed_boxes, image_crops, vfm_image, args) + loss_context, loss_content ,loss_region= loss_ensemble[0], loss_ensemble[1], loss_ensemble[2] + losses.update({"loss_context":loss_context * context_weight}) + losses.update({"loss_content":loss_content * content_weight}) + losses.update({"loss_region":loss_region * region_weight}) + return losses, len(images) + + def intra_image_distill(self, student, teacher, vfm_model, images, normed_boxes, image_crops, vfm_image,args): + roi_size=(3, 3) + B = images.shape[0] + rois_list = [] + crops_list = [] + for bboxes_per_image, crops_per_image in zip(normed_boxes, image_crops): + valid = bboxes_per_image[:, -1] > 0.5 + rois_list.append(bboxes_per_image[valid, :4]) + crops_list.append(crops_per_image[valid]) + image_crops = torch.cat(crops_list) + student_roi_features, context = student.encode_pseudo_boxes(images, rois_list, normalize=True, mode = args.mode, size=roi_size) + + with torch.no_grad(): + teacher_crop_features = teacher.encode_image(image_crops, normalize=True) + intra_vfm_feats = extract_vfm_features(vfm_model, vfm_image,args) # bs,768, h,w + vfm_roi_features= extract_roi_features(intra_vfm_feats,rois_list,normalize=True) + intra_vfm_feats = F.normalize(intra_vfm_feats,dim=1).flatten(start_dim=-2) + intra_vfm_corr = torch.einsum('bci,bcj->bij', intra_vfm_feats, intra_vfm_feats) + + student_intra_corr = compute_student_intra_image_similarity(images.shape[0], context, args) + loss_context = context_loss(student_intra_corr, intra_vfm_corr) + # loss_content = 1.0 - (student_roi_features * teacher_crop_features).sum(-1).mean() + loss_content = soft_content_distill_loss(student_roi_features,teacher_crop_features) + loss_region= region_scd_loss(student_roi_features,vfm_roi_features) + return loss_context, loss_content,loss_region + +def context_loss(student_corr, teacher_corr, teacher_temp=1.0, student_temp=1.0): + student_log_prob = F.log_softmax(student_corr / student_temp, dim=-1) + with torch.no_grad(): + teacher_prob = F.softmax(teacher_corr / teacher_temp, dim=-1) + kl_loss=F.kl_div(student_log_prob, teacher_prob, reduction='batchmean')* (teacher_temp*student_temp) + return kl_loss + + +def soft_content_distill_loss(student_roi_features, teacher_crop_features, T=1.0): + sim = torch.einsum('bpc,bc->bp', student_roi_features, teacher_crop_features) + weights = F.softmax(sim / T, dim=1) + weighted_student = (student_roi_features * weights.unsqueeze(-1)).sum(dim=1) + weighted_student = F.normalize(weighted_student, dim=-1) + cosine_similarity = (weighted_student * teacher_crop_features).sum(dim=-1) + loss = 1.0 - cosine_similarity.mean() + return loss + +def region_scd_loss(student_roi_features, intra_vfm_roi_feats, T_teacher=1.0, T_student=1.0): + with torch.no_grad(): + intra_vfm_roi_feats=intra_vfm_roi_feats.transpose(-2,-1).contiguous() # bs, L, C + teacher_corr=torch.einsum('bic,bjc->bij', intra_vfm_roi_feats, intra_vfm_roi_feats) / T_teacher + teacher_prob = F.softmax(teacher_corr, dim=-1) + student_corr=torch.einsum('bic,bjc->bij', student_roi_features, student_roi_features) / T_student + student_log_prob = F.log_softmax(student_corr, dim=-1) + loss = F.kl_div(student_log_prob, teacher_prob, reduction='batchmean') * (T_teacher * T_student) + return loss + + +def extract_roi_features(x, normed_boxes, size=(3,3), normalize=False): + """ + x:(bs,c,h,w) + """ + def _denormalize_boxes(normed_boxes, x): + h, w = x.shape[-2:] + denormed_boxes = [] + for boxes in normed_boxes: + new_boxes = boxes.clone() # FIXME: do not change the value in normed_boxes! + new_boxes[:, [0, 2]] *= w + new_boxes[:, [1, 3]] *= h + denormed_boxes.append(new_boxes) + return denormed_boxes + if size==(1, 1): + roi_feats=roi_align(x, _denormalize_boxes(normed_boxes, x), size, 1.0, -1, True)[..., 0, 0] + else: + roi_feats=roi_align(x, _denormalize_boxes(normed_boxes, x), size, 1.0, -1, True).flatten(start_dim=-2) + if normalize: + roi_feats=F.normalize(roi_feats,dim=1) + return roi_feats + + +def prepare_inputs(batch, device, dtype): + """ + 将输入批次中的数据加载到设备,并转换为指定数据类型。 + """ + images, normed_boxes, image_crops, vfm_image = batch + images = images.to(device=device, dtype=dtype, non_blocking=True) + normed_boxes = normed_boxes.to(device=device, dtype=dtype, non_blocking=True) + image_crops = image_crops.to(device=device, dtype=dtype, non_blocking=True) + vfm_image = vfm_image.to(device=device, dtype=dtype, non_blocking=True) + return images, normed_boxes, image_crops, vfm_image + + +def extract_vfm_features(vfm_model, image, args): + """ + 从 VFM 模型中提取特征,并对其进行归一化。 + """ + if "dinov2" in args.use_vfm or "sd_dino" in args.use_vfm or "sam_dino" in args.use_vfm: + vfm_feats = vfm_model.get_intermediate_layers(image, reshape=True)[0] + elif 'sam' in args.use_vfm: + vfm_feats = vfm_model.image_encoder(image) + elif 'dino' in args.use_vfm: + feat = vfm_model.get_intermediate_layers(image)[0] + nb_im = feat.shape[0] + patch_size = vfm_model.patch_embed.patch_size + I, J = image[0].shape[-2] // patch_size, image[0].shape[-2] // patch_size + vfm_feats = feat[:, 1:, :].reshape(nb_im, I, J, -1).permute(0, 3, 1, 2) + else: + raise NotImplementedError(f"VFM mode {args.use_vfm} is not implemented.") + return vfm_feats + +def compute_student_intra_image_similarity(B, context, args): + + N, _ = context[0].shape[1:] if isinstance(context, tuple) else context.shape[1:] + if args.mode in ["qq_vfm_distill", "kk_vfm_distill", "vv_vfm_distill", "sanity_check"]: + context = context.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + context = F.normalize(context, dim=-1).transpose(-2, -1) + student_context_similarity = torch.einsum("b c m, b c n -> b m n", context, context) + + elif args.mode == "csa_vfm_distill": + q_feature, k_feature = context + q_feature = q_feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + k_feature = k_feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + q_feature = F.normalize(q_feature, dim=-1).transpose(-2, -1) + k_feature = F.normalize(k_feature, dim=-1).transpose(-2, -1) + student_context_similarity = (torch.einsum("b c m, b c n -> b m n", q_feature, q_feature) + + torch.einsum("b c m, b c n -> b m n", k_feature, k_feature)) / 2.0 + elif args.mode == "all_vfm_distill": + q_feature, k_feature, v_feature = context + features = [q_feature, k_feature, v_feature] + similarities = [] + for feature in features: + feature = feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + feature = F.normalize(feature, dim=-1).transpose(-2, -1) + similarities.append(torch.einsum("b c m, b c n -> b m n", feature, feature)) + student_context_similarity = sum(similarities) / len(features) + + else: + raise NotImplementedError(f"Mode '{args.mode}' is not implemented.") + + return student_context_similarity \ No newline at end of file diff --git a/src/training/declip_plus.py b/src/training/declip_plus.py new file mode 100644 index 0000000000000000000000000000000000000000..065c2304f7af1ffc0ad29a3155a2316bfa0c6241 --- /dev/null +++ b/src/training/declip_plus.py @@ -0,0 +1,304 @@ +from typing import List +import torch +import torch.nn.functional as F +import torch +from torch.cuda.amp import autocast +from torchvision.ops import roi_align +import torch.nn as nn + +# ! declip_plus 同时支持region loss,以及sd smoothing +class DeCLIPWithREPAProjector(nn.Module): + def __init__(self, declip_model, clip_dim=768, hidden_dim=1024, vfm_dim=768,args=None): + super().__init__() + self.model = declip_model + self.repa_layer_idx = args.repa_layer_idx + self.projector = nn.Sequential( + nn.Linear(clip_dim, hidden_dim), + nn.SiLU(), + nn.Linear(hidden_dim, hidden_dim), + nn.SiLU(), + nn.Linear(hidden_dim, vfm_dim)) + # self.projector = nn.Sequential(nn.Linear(clip_dim, hidden_dim, bias=False), + # nn.GELU(), + # nn.Linear(hidden_dim,vfm_dim, bias=False)) + self.initialize_projector_weights() + self.logit_scale=self.model.logit_scale + + def initialize_projector_weights(self): + for module in self.projector.modules(): + if isinstance(module, nn.Linear): + nn.init.xavier_uniform_(module.weight) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + + def encode_image(self, *args, **kwargs): + return self.model.encode_image(*args, **kwargs) + + def encode_text(self, *args, **kwargs): + return self.model.encode_text(*args, **kwargs) + + def encode_dense(self, *args, **kwargs): + return self.model.encode_dense(*args, **kwargs) + + def encode_pseudo_boxes(self, images, rois_list, normalize = False, mode="qq", size=(1, 1)): + student_roi_features, context, intermediate_layer_output = self.model.encode_pseudo_boxes(images, + rois_list, + normalize=normalize, + mode = mode, + size=size, + get_intermediate_layer=[self.repa_layer_idx]) + + alpha=0.3 + residual=intermediate_layer_output[0] + intermediate_layer_output = self.projector(intermediate_layer_output[0]) + intermediate_layer_output = alpha * residual + intermediate_layer_output + return student_roi_features, context, intermediate_layer_output + + def encode_masks(self, *args, **kwargs): + return self.model.encode_masks(*args, **kwargs) + + def train(self, mode=True): + self.model.train(mode) + self.training = self.model.training + return self + + def lock_image_tower(self, *args, **kwargs): + return self.model.lock_image_tower(*args, **kwargs) + + def lock_text_tower(self, *args, **kwargs): + return self.model.lock_text_tower(*args, **kwargs) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.model.set_grad_checkpointing(enable) + + @torch.jit.ignore + def no_weight_decay(self): + return self.model.no_weight_decay() + +class DeCLIP_PLUS: + + def __call__(self, batch, student, teacher, vfm_model, args): + losses = {} + context_weight = args.loss_context_weight + content_weight = args.loss_content_weight + region_weight = args.loss_region_weight + need_repa=args.repa_layer_idx!=-1 + if args.distributed: + student = student.module + dtype_map = {"bf16": torch.bfloat16, "amp": torch.float16} + input_dtype = dtype_map.get(args.precision, torch.float32) + images, normed_boxes, image_crops, vfm_image,sd_attn = prepare_inputs(batch, args.device, input_dtype) + loss_ensemble = self.intra_image_distill(student, teacher, vfm_model, images, normed_boxes, image_crops, vfm_image,sd_attn,args) + loss_context, loss_content,loss_region = loss_ensemble[0], loss_ensemble[1], loss_ensemble[2] + losses.update({"loss_context":loss_context * context_weight}) + losses.update({"loss_content":loss_content * content_weight}) + losses.update({"loss_region":loss_region * region_weight}) # 0.3 + if need_repa: + loss_repa=loss_ensemble[2] + losses.update({"loss_repa":loss_repa}) + return losses, len(images) + + def intra_image_distill(self, student, teacher, vfm_model, images, normed_boxes, image_crops, vfm_image,sd_attn,args): + need_repa = args.repa_layer_idx!=-1 + roi_size=(3, 3) + B = images.shape[0] + rois_list = [] + crops_list = [] + + for bboxes_per_image, crops_per_image in zip(normed_boxes, image_crops): + valid = bboxes_per_image[:, -1] > 0.5 + rois_list.append(bboxes_per_image[valid, :4]) + crops_list.append(crops_per_image[valid]) + + image_crops = torch.cat(crops_list) + if need_repa: + student_roi_features, context, intermediate_layer_output = student.encode_pseudo_boxes(images, rois_list, normalize=True, mode = args.mode, size=roi_size) + else: + student_roi_features, context = student.encode_pseudo_boxes(images, rois_list, normalize=True, mode = args.mode, size=roi_size) + + with torch.no_grad(): + teacher_crop_features = teacher.encode_image(image_crops, normalize=True) + intra_vfm_feats = extract_vfm_features(vfm_model, vfm_image,args) # bs,768, h,w + vfm_roi_features= extract_roi_features(intra_vfm_feats,rois_list,normalize=True) + intra_vfm_feats = F.normalize(intra_vfm_feats,dim=1).flatten(start_dim=-2) + intra_vfm_corr = torch.einsum('bci,bcj->bij', intra_vfm_feats, intra_vfm_feats) + refined_intra_vfm_corr = refine_dino(intra_vfm_corr, sd_attn, args.sd_refine_weight) + + student_intra_corr = compute_student_intra_image_similarity(images.shape[0], context, args) + loss_context = context_loss(student_intra_corr, refined_intra_vfm_corr, teacher_temp=0.8) + # loss_content = 1.0 - (student_roi_features * teacher_crop_features).sum(-1).mean() + loss_content = soft_content_distill_loss(student_roi_features,teacher_crop_features) + loss_region= region_scd_loss(student_roi_features,vfm_roi_features) + if need_repa: + loss_repa = repa_loss(intermediate_layer_output, intra_vfm_feats) + return loss_context, loss_content, loss_repa + else: + return loss_context, loss_content,loss_region + +def context_loss(student_corr, teacher_corr, teacher_temp=1.0, student_temp=1.0): + student_log_prob = F.log_softmax(student_corr / student_temp, dim=-1) + with torch.no_grad(): + teacher_prob = F.softmax(teacher_corr / teacher_temp, dim=-1) + kl_loss=F.kl_div(student_log_prob, teacher_prob, reduction='batchmean')* (teacher_temp*student_temp) + return kl_loss + + +def refine_dino(dino_corr, sd_attn, sd_refine_weight): + """ + dino_corr: (bs,hw,hw) + sd_attn: (bs,hw,hw) + """ + residual = dino_corr + dino_corr = torch.bmm(sd_attn, dino_corr) + # dino_corr = torch.bmm(dino_corr, sd_attn.transpose(-2, -1)) + dino_corr_refined = dino_corr * (sd_refine_weight) + residual * (1-sd_refine_weight) # bs, hw,hw + # 强制对角线为1 + bs, hw, _ = dino_corr_refined.shape + device = dino_corr_refined.device + eye = torch.eye(hw, dtype=dino_corr_refined.dtype, device=device).unsqueeze(0).expand(bs, -1, -1) + dino_corr_refined = dino_corr_refined * (1 - eye) + eye + return dino_corr_refined + + +def repa_loss(clip_intermediate_out, vfm_out): + """ + clip_intermediate_out: (bs, nt+1, hs), NOT L2 norm + vfm_out: (bs, hs, nt), ALREADY L2 norm + """ + vfm_out = vfm_out.transpose(1, 2) # (bs, nt, hs) + clip_intermediate_out = clip_intermediate_out[:, 1:] # (bs, nt, hs) + clip_intermediate_out = F.normalize(clip_intermediate_out, dim=-1) + similarity = (clip_intermediate_out * vfm_out).sum(dim=-1) # (bs, nt) + loss = -similarity.mean() + return loss + +def soft_content_distill_loss(student_roi_features, teacher_crop_features, T=1.0): + sim = torch.einsum('bpc,bc->bp', student_roi_features, teacher_crop_features) + weights = F.softmax(sim / T, dim=1) + weighted_student = (student_roi_features * weights.unsqueeze(-1)).sum(dim=1) + weighted_student = F.normalize(weighted_student, dim=-1) + cosine_similarity = (weighted_student * teacher_crop_features).sum(dim=-1) + loss = 1.0 - cosine_similarity.mean() + return loss + +def region_scd_loss(student_roi_features, intra_vfm_roi_feats, T_teacher=1.0, T_student=1.0): + with torch.no_grad(): + intra_vfm_roi_feats=intra_vfm_roi_feats.transpose(-2,-1).contiguous() # bs, L, HS + teacher_corr=torch.einsum('bic,bjc->bij', intra_vfm_roi_feats, intra_vfm_roi_feats) / T_teacher + teacher_prob = F.softmax(teacher_corr, dim=-1) + student_corr=torch.einsum('bic,bjc->bij', student_roi_features, student_roi_features) / T_student + student_log_prob = F.log_softmax(student_corr, dim=-1) + loss = F.kl_div(student_log_prob, teacher_prob, reduction='batchmean') * (T_teacher * T_student) + return loss + + + +# def region_scd_loss(student_intermediate_features, intra_vfm_roi_feats, rois_list, temp=0.3): +# losses = [] +# with torch.no_grad(): +# intra_vfm_roi_feats=intra_vfm_roi_feats.transpose(-2,-1).contiguous() # bs, L, HS +# intra_vfm_roi_feats=F.normalize(intra_vfm_roi_feats,dim=-1) +# teacher_corr=torch.einsum('bic,bjc->bij', intra_vfm_roi_feats, intra_vfm_roi_feats) / temp +# teacher_prob = F.softmax(teacher_corr, dim=-1) +# for x in student_intermediate_features: +# if x.dim() == 3: +# x = x[:, 1:] # discard cls , # bs, nt, HS +# bs,nt,hs=x.shape +# h=w=int(math.sqrt(nt)) +# x=x.transpose(-2,-1).contiguous().view(bs,hs, h,w) +# student_roi_features = extract_roi_features(x,rois_list,size=(5,5)) +# student_roi_features=student_roi_features.transpose(-2,-1).contiguous() +# student_roi_features=F.normalize(student_roi_features,dim=-1) +# student_corr=torch.einsum('bic,bjc->bij', student_roi_features, student_roi_features) / temp +# student_log_prob = F.log_softmax(student_corr, dim=-1) +# loss = F.kl_div(student_log_prob, teacher_prob, reduction='batchmean') * (temp ** 2) +# losses.append(loss) +# if len(losses) == 0: +# return torch.zeros([], dtype=student_roi_features.dtype, device=student_roi_features.device) +# return torch.stack(losses).mean() + + +def extract_roi_features(x, normed_boxes, size=(3,3), normalize=False): + """ + x:(bs,c,h,w) + """ + def _denormalize_boxes(normed_boxes, x): + h, w = x.shape[-2:] + denormed_boxes = [] + for boxes in normed_boxes: + new_boxes = boxes.clone() # FIXME: do not change the value in normed_boxes! + new_boxes[:, [0, 2]] *= w + new_boxes[:, [1, 3]] *= h + denormed_boxes.append(new_boxes) + return denormed_boxes + if size==(1, 1): + roi_feats=roi_align(x, _denormalize_boxes(normed_boxes, x), size, 1.0, -1, True)[..., 0, 0] + else: + roi_feats=roi_align(x, _denormalize_boxes(normed_boxes, x), size, 1.0, -1, True).flatten(start_dim=-2) + if normalize: + roi_feats=F.normalize(roi_feats,dim=1) + return roi_feats + + +def prepare_inputs(batch, device, dtype): + """ + 将输入批次中的数据加载到设备,并转换为指定数据类型。 + """ + images, normed_boxes, image_crops, vfm_image, sd_attn = batch + images = images.to(device=device, dtype=dtype, non_blocking=True) + normed_boxes = normed_boxes.to(device=device, dtype=dtype, non_blocking=True) + image_crops = image_crops.to(device=device, dtype=dtype, non_blocking=True) + vfm_image = vfm_image.to(device=device, dtype=dtype, non_blocking=True) + sd_attn = sd_attn.to(device=device, dtype=dtype, non_blocking=True) + return images, normed_boxes, image_crops, vfm_image, sd_attn + + +def extract_vfm_features(vfm_model, image, args): + """ + 从 VFM 模型中提取特征,并对其进行归一化。 + """ + if "dinov2" in args.use_vfm or "sd_dino" in args.use_vfm or "sam_dino" in args.use_vfm: + vfm_feats = vfm_model.get_intermediate_layers(image, reshape=True)[0] + elif 'sam' in args.use_vfm: + vfm_feats = vfm_model.image_encoder(image) + elif 'dino' in args.use_vfm: + feat = vfm_model.get_intermediate_layers(image)[0] + nb_im = feat.shape[0] + patch_size = vfm_model.patch_embed.patch_size + I, J = image[0].shape[-2] // patch_size, image[0].shape[-2] // patch_size + vfm_feats = feat[:, 1:, :].reshape(nb_im, I, J, -1).permute(0, 3, 1, 2) + else: + raise NotImplementedError(f"VFM mode {args.use_vfm} is not implemented.") + return vfm_feats + +def compute_student_intra_image_similarity(B, context, args): + + N, _ = context[0].shape[1:] if isinstance(context, tuple) else context.shape[1:] + if args.mode in ["qq_vfm_distill", "kk_vfm_distill", "vv_vfm_distill", "sanity_check"]: + context = context.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + context = F.normalize(context, dim=-1).transpose(-2, -1) + student_context_similarity = torch.einsum("b c m, b c n -> b m n", context, context) + + elif args.mode == "csa_vfm_distill": + q_feature, k_feature = context + q_feature = q_feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + k_feature = k_feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + q_feature = F.normalize(q_feature, dim=-1).transpose(-2, -1) + k_feature = F.normalize(k_feature, dim=-1).transpose(-2, -1) + student_context_similarity = (torch.einsum("b c m, b c n -> b m n", q_feature, q_feature) + + torch.einsum("b c m, b c n -> b m n", k_feature, k_feature)) / 2.0 + elif args.mode == "all_vfm_distill": + q_feature, k_feature, v_feature = context + features = [q_feature, k_feature, v_feature] + similarities = [] + for feature in features: + feature = feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + feature = F.normalize(feature, dim=-1).transpose(-2, -1) + similarities.append(torch.einsum("b c m, b c n -> b m n", feature, feature)) + student_context_similarity = sum(similarities) / len(features) + + else: + raise NotImplementedError(f"Mode '{args.mode}' is not implemented.") + + return student_context_similarity \ No newline at end of file diff --git a/src/training/dist_utils.py b/src/training/dist_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1d229214372df339d23621ad8838c813578d093d --- /dev/null +++ b/src/training/dist_utils.py @@ -0,0 +1,228 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +""" +This file contains primitives for multi-gpu communication. +This is useful when doing distributed training. +""" + +import functools +import numpy as np +import torch +import torch.distributed as dist + +_LOCAL_PROCESS_GROUP = None +_MISSING_LOCAL_PG_ERROR = ( + "Local process group is not yet created! Please use detectron2's `launch()` " + "to start processes and initialize pytorch process group. If you need to start " + "processes in other ways, please call comm.create_local_process_group(" + "num_workers_per_machine) after calling torch.distributed.init_process_group()." +) + + +def get_world_size() -> int: + if not dist.is_available(): + return 1 + if not dist.is_initialized(): + return 1 + return dist.get_world_size() + + +def get_rank() -> int: + if not dist.is_available(): + return 0 + if not dist.is_initialized(): + return 0 + return dist.get_rank() + + +@functools.lru_cache() +def create_local_process_group(num_workers_per_machine: int) -> None: + """ + Create a process group that contains ranks within the same machine. + Detectron2's launch() in engine/launch.py will call this function. If you start + workers without launch(), you'll have to also call this. Otherwise utilities + like `get_local_rank()` will not work. + This function contains a barrier. All processes must call it together. + Args: + num_workers_per_machine: the number of worker processes per machine. Typically + the number of GPUs. + """ + global _LOCAL_PROCESS_GROUP + assert _LOCAL_PROCESS_GROUP is None + assert get_world_size() % num_workers_per_machine == 0 + num_machines = get_world_size() // num_workers_per_machine + machine_rank = get_rank() // num_workers_per_machine + for i in range(num_machines): + ranks_on_i = list(range(i * num_workers_per_machine, (i + 1) * num_workers_per_machine)) + pg = dist.new_group(ranks_on_i) + if i == machine_rank: + _LOCAL_PROCESS_GROUP = pg + + +def get_local_process_group(): + """ + Returns: + A torch process group which only includes processes that are on the same + machine as the current process. This group can be useful for communication + within a machine, e.g. a per-machine SyncBN. + """ + assert _LOCAL_PROCESS_GROUP is not None, _MISSING_LOCAL_PG_ERROR + return _LOCAL_PROCESS_GROUP + + +def get_local_rank() -> int: + """ + Returns: + The rank of the current process within the local (per-machine) process group. + """ + if not dist.is_available(): + return 0 + if not dist.is_initialized(): + return 0 + assert _LOCAL_PROCESS_GROUP is not None, _MISSING_LOCAL_PG_ERROR + return dist.get_rank(group=_LOCAL_PROCESS_GROUP) + + +def get_local_size() -> int: + """ + Returns: + The size of the per-machine process group, + i.e. the number of processes per machine. + """ + if not dist.is_available(): + return 1 + if not dist.is_initialized(): + return 1 + assert _LOCAL_PROCESS_GROUP is not None, _MISSING_LOCAL_PG_ERROR + return dist.get_world_size(group=_LOCAL_PROCESS_GROUP) + + +def is_main_process() -> bool: + return get_rank() == 0 + + +def synchronize(): + """ + Helper function to synchronize (barrier) among all processes when + using distributed training + """ + if not dist.is_available(): + return + if not dist.is_initialized(): + return + world_size = dist.get_world_size() + if world_size == 1: + return + if dist.get_backend() == dist.Backend.NCCL: + # This argument is needed to avoid warnings. + # It's valid only for NCCL backend. + dist.barrier(device_ids=[torch.cuda.current_device()]) + else: + dist.barrier() + + +@functools.lru_cache() +def _get_global_gloo_group(): + """ + Return a process group based on gloo backend, containing all the ranks + The result is cached. + """ + if dist.get_backend() == "nccl": + return dist.new_group(backend="gloo") + else: + return dist.group.WORLD + + +def all_gather(data, group=None): + """ + Run all_gather on arbitrary picklable data (not necessarily tensors). + Args: + data: any picklable object + group: a torch process group. By default, will use a group which + contains all ranks on gloo backend. + Returns: + list[data]: list of data gathered from each rank + """ + if get_world_size() == 1: + return [data] + if group is None: + group = _get_global_gloo_group() # use CPU group by default, to reduce GPU RAM usage. + world_size = dist.get_world_size(group) + if world_size == 1: + return [data] + + output = [None for _ in range(world_size)] + dist.all_gather_object(output, data, group=group) + return output + + +def gather(data, dst=0, group=None): + """ + Run gather on arbitrary picklable data (not necessarily tensors). + Args: + data: any picklable object + dst (int): destination rank + group: a torch process group. By default, will use a group which + contains all ranks on gloo backend. + Returns: + list[data]: on dst, a list of data gathered from each rank. Otherwise, + an empty list. + """ + if get_world_size() == 1: + return [data] + if group is None: + group = _get_global_gloo_group() + world_size = dist.get_world_size(group=group) + if world_size == 1: + return [data] + rank = dist.get_rank(group=group) + + if rank == dst: + output = [None for _ in range(world_size)] + dist.gather_object(data, output, dst=dst, group=group) + return output + else: + dist.gather_object(data, None, dst=dst, group=group) + return [] + + +def shared_random_seed(): + """ + Returns: + int: a random number that is the same across all workers. + If workers need a shared RNG, they can use this shared seed to + create one. + All workers must call this function, otherwise it will deadlock. + """ + ints = np.random.randint(2**31) + all_ints = all_gather(ints) + return all_ints[0] + + +def reduce_dict(input_dict, average=True): + """ + Reduce the values in the dictionary from all processes so that process with rank + 0 has the reduced results. + Args: + input_dict (dict): inputs to be reduced. All the values must be scalar CUDA Tensor. + average (bool): whether to do average or sum + Returns: + a dict with the same keys as input_dict, after reduction. + """ + world_size = get_world_size() + if world_size < 2: + return input_dict + with torch.no_grad(): + names = [] + values = [] + # sort the keys so that they are consistent across processes + for k in sorted(input_dict.keys()): + names.append(k) + values.append(input_dict[k]) + values = torch.stack(values, dim=0) + dist.reduce(values, dst=0) + if dist.get_rank() == 0 and average: + # only main process gets accumulated, so only divide by + # world_size in this case + values /= world_size + reduced_dict = {k: v for k, v in zip(names, values)} + return reduced_dict diff --git a/src/training/distributed.py b/src/training/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..7aae9fc3ffced66bafa5ed34ae5dac16ce802fce --- /dev/null +++ b/src/training/distributed.py @@ -0,0 +1,126 @@ +import os + +import torch +import torch.distributed as dist + +try: + import horovod.torch as hvd +except ImportError: + hvd = None + + +def is_global_master(args): + return args.rank == 0 + + +def is_local_master(args): + return args.local_rank == 0 + + +def is_master(args, local=False): + return is_local_master(args) if local else is_global_master(args) + + +def is_using_horovod(): + # NOTE w/ horovod run, OMPI vars should be set, but w/ SLURM PMI vars will be set + # Differentiating between horovod and DDP use via SLURM may not be possible, so horovod arg still required... + ompi_vars = ["OMPI_COMM_WORLD_RANK", "OMPI_COMM_WORLD_SIZE"] + pmi_vars = ["PMI_RANK", "PMI_SIZE"] + if all([var in os.environ for var in ompi_vars]) or all([var in os.environ for var in pmi_vars]): + return True + else: + return False + + +def is_using_distributed(): + if 'WORLD_SIZE' in os.environ: + return int(os.environ['WORLD_SIZE']) > 1 + if 'SLURM_NTASKS' in os.environ: + return int(os.environ['SLURM_NTASKS']) > 1 + return False + + +def world_info_from_env(): + local_rank = 0 + for v in ('LOCAL_RANK', 'MPI_LOCALRANKID', 'SLURM_LOCALID', 'OMPI_COMM_WORLD_LOCAL_RANK'): + if v in os.environ: + local_rank = int(os.environ[v]) + break + global_rank = 0 + for v in ('RANK', 'PMI_RANK', 'SLURM_PROCID', 'OMPI_COMM_WORLD_RANK'): + if v in os.environ: + global_rank = int(os.environ[v]) + break + world_size = 1 + for v in ('WORLD_SIZE', 'PMI_SIZE', 'SLURM_NTASKS', 'OMPI_COMM_WORLD_SIZE'): + if v in os.environ: + world_size = int(os.environ[v]) + break + + return local_rank, global_rank, world_size + + +def init_distributed_device(args): + # Distributed training = training on more than one GPU. + # Works in both single and multi-node scenarios. + args.distributed = False + args.world_size = 1 + args.rank = 0 # global rank + args.local_rank = 0 + if is_using_distributed(): + if 'SLURM_PROCID' in os.environ: + # DDP via SLURM + args.local_rank, args.rank, args.world_size = world_info_from_env() + # SLURM var -> torch.distributed vars in case needed + os.environ['LOCAL_RANK'] = str(args.local_rank) + os.environ['RANK'] = str(args.rank) + os.environ['WORLD_SIZE'] = str(args.world_size) + torch.distributed.init_process_group( + backend=args.dist_backend, + init_method=args.dist_url, + world_size=args.world_size, + rank=args.rank, + ) + else: + # DDP via torchrun, torch.distributed.launch + args.local_rank, _, _ = world_info_from_env() + torch.distributed.init_process_group( + backend=args.dist_backend, + init_method=args.dist_url) + args.world_size = torch.distributed.get_world_size() + args.rank = torch.distributed.get_rank() + args.distributed = True + if torch.cuda.is_available(): + if args.distributed and not args.no_set_device_rank: + device = 'cuda:%d' % args.local_rank + else: + device = 'cuda:0' + torch.cuda.set_device(device) + else: + device = 'cpu' + args.device = device + device = torch.device(device) + return device + + +def broadcast_object(args, obj, src=0): + # broadcast a pickle-able python object from rank-0 to all ranks + if args.horovod: + return hvd.broadcast_object(obj, root_rank=src) + else: + if args.rank == src: + objects = [obj] + else: + objects = [None] + dist.broadcast_object_list(objects, src=src) + return objects[0] + + +def all_gather_object(args, obj, dst=0): + # gather a pickle-able python object across all ranks + if args.horovod: + return hvd.allgather_object(obj) + else: + objects = [None for _ in range(args.world_size)] + dist.all_gather_object(objects, obj) + return objects diff --git a/src/training/file_utils.py b/src/training/file_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7bad290bb4651024855754141a4ebda27fc036e7 --- /dev/null +++ b/src/training/file_utils.py @@ -0,0 +1,83 @@ +import logging +import os +import multiprocessing +import subprocess +import time +import fsspec +import torch +from tqdm import tqdm + +def remote_sync_s3(local_dir, remote_dir): + # skip epoch_latest which can change during sync. + result = subprocess.run(["aws", "s3", "sync", local_dir, remote_dir, '--exclude', '*epoch_latest.pt'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if result.returncode != 0: + logging.error(f"Error: Failed to sync with S3 bucket {result.stderr.decode('utf-8')}") + return False + + logging.info(f"Successfully synced with S3 bucket") + return True + +def remote_sync_fsspec(local_dir, remote_dir): + # FIXME currently this is slow and not recommended. Look into speeding up. + a = fsspec.get_mapper(local_dir) + b = fsspec.get_mapper(remote_dir) + + for k in a: + # skip epoch_latest which can change during sync. + if 'epoch_latest.pt' in k: + continue + + logging.info(f'Attempting to sync {k}') + if k in b and len(a[k]) == len(b[k]): + logging.debug(f'Skipping remote sync for {k}.') + continue + + try: + logging.info(f'Successful sync for {k}.') + b[k] = a[k] + except Exception as e: + logging.info(f'Error during remote sync for {k}: {e}') + return False + + return True + +def remote_sync(local_dir, remote_dir, protocol): + logging.info('Starting remote sync.') + if protocol == 's3': + return remote_sync_s3(local_dir, remote_dir) + elif protocol == 'fsspec': + return remote_sync_fsspec(local_dir, remote_dir) + else: + logging.error('Remote protocol not known') + return False + +def keep_running_remote_sync(sync_every, local_dir, remote_dir, protocol): + while True: + time.sleep(sync_every) + remote_sync(local_dir, remote_dir, protocol) + +def start_sync_process(sync_every, local_dir, remote_dir, protocol): + p = multiprocessing.Process(target=keep_running_remote_sync, args=(sync_every, local_dir, remote_dir, protocol)) + return p + +# Note: we are not currently using this save function. +def pt_save(pt_obj, file_path): + of = fsspec.open(file_path, "wb") + with of as f: + torch.save(pt_obj, file_path) + +def pt_load(file_path, map_location=None): + if file_path.startswith('s3'): + logging.info('Loading remote checkpoint, which may take a bit.') + of = fsspec.open(file_path, "rb") + with of as f: + out = torch.load(f, map_location=map_location, weights_only=False) + return out + +def check_exists(file_path): + try: + with fsspec.open(file_path): + pass + except FileNotFoundError: + return False + return True diff --git a/src/training/integrated_distill.py b/src/training/integrated_distill.py new file mode 100644 index 0000000000000000000000000000000000000000..91e484210c7c86b0f35d44556ebc4838e6eafbbf --- /dev/null +++ b/src/training/integrated_distill.py @@ -0,0 +1,478 @@ +""" +Integrated Distillation - 集成蒸馏基线 + +与 DeCLIP 解耦蒸馏的对比: +- DeCLIP: 在最后一个 Block 的 Q 和 V 矩阵上分别蒸馏,去掉残差连接和 MLP +- Integrated: 在完整 ViT forward 的最终输出特征上同时蒸馏 + +用于消融实验:证明解耦蒸馏避免了优化冲突 +""" + +from typing import List +import torch +import torch.nn.functional as F +from torchvision.ops import roi_align +import torch.nn as nn + + +class DeCLIPWithREPAProjectorIntegrated(nn.Module): + """集成蒸馏版本的 REPA Projector wrapper""" + def __init__(self, declip_model, clip_dim=768, hidden_dim=1024, vfm_dim=768, args=None): + super().__init__() + self.model = declip_model + self.repa_layer_idx = args.repa_layer_idx + self.projector = nn.Sequential( + nn.Linear(clip_dim, hidden_dim), + nn.SiLU(), + nn.Linear(hidden_dim, hidden_dim), + nn.SiLU(), + nn.Linear(hidden_dim, vfm_dim) + ) + self.initialize_projector_weights() + self.logit_scale = self.model.logit_scale + + def initialize_projector_weights(self): + for module in self.projector.modules(): + if isinstance(module, nn.Linear): + nn.init.xavier_uniform_(module.weight) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + + def encode_image(self, *args, **kwargs): + return self.model.encode_image(*args, **kwargs) + + def encode_text(self, *args, **kwargs): + return self.model.encode_text(*args, **kwargs) + + def encode_dense(self, *args, **kwargs): + return self.model.encode_dense(*args, **kwargs) + + def encode_pseudo_boxes_integrated(self, images, rois_list, normalize=False, size=(1, 1)): + """ + 集成蒸馏的特征提取: + - 使用 "vanilla" 模式,完整的 ViT forward + - 返回融合后的最终特征 + """ + # 使用 vanilla 模式,不是 distill 模式 + features = self.model.encode_dense(images, normalize=False, keep_shape=True, mode="vanilla") + + # ROI align 提取 box 特征 + boxes = self._denormalize_boxes(rois_list, features) + roi_feats = roi_align( + features, + boxes, + output_size=size, + spatial_scale=1.0, + sampling_ratio=-1, + aligned=True + ) + + if size == (1, 1): + roi_feats = roi_feats[..., 0, 0] + else: + roi_feats = roi_feats.flatten(start_dim=-2).transpose(-2, -1).contiguous() + + if normalize: + roi_feats = F.normalize(roi_feats, dim=-1) + + return roi_feats, features + + @staticmethod + def _denormalize_boxes(normed_boxes, x): + h, w = x.shape[-2:] + denormed_boxes = [] + for i, boxes in enumerate(normed_boxes): + new_boxes = boxes.clone() + new_boxes[:, [0, 2]] *= w + new_boxes[:, [1, 3]] *= h + # 添加 batch index + batch_idx = torch.full((new_boxes.shape[0], 1), i, dtype=new_boxes.dtype, device=new_boxes.device) + new_boxes = torch.cat([batch_idx, new_boxes], dim=1) + denormed_boxes.append(new_boxes) + return torch.cat(denormed_boxes, dim=0) + + def encode_masks(self, *args, **kwargs): + return self.model.encode_masks(*args, **kwargs) + + def train(self, mode=True): + self.model.train(mode) + self.training = self.model.training + return self + + def lock_image_tower(self, *args, **kwargs): + return self.model.lock_image_tower(*args, **kwargs) + + def lock_text_tower(self, *args, **kwargs): + return self.model.lock_text_tower(*args, **kwargs) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.model.set_grad_checkpointing(enable) + + @torch.jit.ignore + def no_weight_decay(self): + return self.model.no_weight_decay() + + +class IntegratedDistillation: + """ + 集成蒸馏方法类 + + 关键区别: + - 使用完整的 ViT forward(包含残差连接和 MLP) + - Content 和 Context Loss 都作用于同一个融合特征 + - 可能导致梯度冲突 + """ + + def __init__(self, enable_gradient_analysis=False): + """ + Args: + enable_gradient_analysis: 是否启用梯度冲突分析 + """ + self.enable_gradient_analysis = enable_gradient_analysis + self.gradient_logs = [] + + def __call__(self, batch, student, teacher, vfm_model, args): + losses = {} + context_weight = args.loss_context_weight + content_weight = args.loss_content_weight + + need_repa = args.repa_layer_idx != -1 + + if args.distributed: + student = student.module + + dtype_map = {"bf16": torch.bfloat16, "amp": torch.float16} + input_dtype = dtype_map.get(args.precision, torch.float32) + + images, normed_boxes, image_crops, vfm_image = prepare_inputs_integrated(batch, args.device, input_dtype) + + loss_ensemble = self.intra_image_distill_integrated( + student, teacher, vfm_model, images, normed_boxes, image_crops, vfm_image, args + ) + + loss_context, loss_content = loss_ensemble[0], loss_ensemble[1] + + losses.update({"loss_context": loss_context * context_weight}) + losses.update({"loss_content": loss_content * content_weight}) + + if need_repa: + loss_repa = loss_ensemble[2] + losses.update({"loss_repa": loss_repa}) + + return losses, len(images) + + def intra_image_distill_integrated(self, student, teacher, vfm_model, images, normed_boxes, image_crops, vfm_image, args): + """ + 集成蒸馏的核心方法 + + 关键区别: + 1. 使用 "vanilla" 模式的 encode_dense(完整 forward) + 2. 在融合后的特征上计算 Content 和 Context Loss + """ + need_repa = args.repa_layer_idx != -1 + roi_size = (3, 3) + B = images.shape[0] + rois_list = [] + crops_list = [] + + for bboxes_per_image, crops_per_image in zip(normed_boxes, image_crops): + valid = bboxes_per_image[:, -1] > 0.5 + rois_list.append(bboxes_per_image[valid, :4]) + crops_list.append(crops_per_image[valid]) + + image_crops = torch.cat(crops_list) + + # ===== 核心区别:使用 vanilla 模式获取融合特征 ===== + # 这会使用完整的 ViT forward(包含残差连接和 MLP) + student_features = student.encode_dense(images, normalize=False, keep_shape=True, mode="vanilla") + + # 从融合特征中提取 ROI 特征 + student_roi_features = extract_roi_features_integrated(student_features, rois_list, normalize=True, size=roi_size) + + # 计算融合特征的自相似性(用于 Context Loss) + B, C, H, W = student_features.shape + student_features_flat = student_features.flatten(start_dim=-2) # B, C, HW + student_features_norm = F.normalize(student_features_flat, dim=1) + student_intra_corr = torch.einsum('bci,bcj->bij', student_features_norm, student_features_norm) + + with torch.no_grad(): + teacher_crop_features = teacher.encode_image(image_crops, normalize=True) + intra_vfm_feats = extract_vfm_features(vfm_model, vfm_image, args) + + intra_vfm_feats_norm = F.normalize(intra_vfm_feats, dim=1).flatten(start_dim=-2) + intra_vfm_corr = torch.einsum('bci,bcj->bij', intra_vfm_feats_norm, intra_vfm_feats_norm) + + # 计算 Loss + loss_context = context_loss(student_intra_corr, intra_vfm_corr, teacher_temp=0.8) + loss_content = soft_content_distill_loss(student_roi_features, teacher_crop_features) + + if need_repa: + # 如果需要 REPA loss + loss_repa = torch.tensor(0.0, device=images.device) # placeholder + return loss_context, loss_content, loss_repa + else: + return loss_context, loss_content + + +class IntegratedDistillationWithGradientAnalysis(IntegratedDistillation): + """ + 带梯度分析的集成蒸馏 + + 用于记录 Content Loss 和 Context Loss 的梯度冲突情况 + """ + + def __init__(self, save_dir=None, rank=0): + """ + Args: + save_dir: 梯度分析结果保存目录。如果为 None,则只收集到内存不保存文件。 + rank: 分布式训练中的 rank,只有 rank=0 时才保存文件。 + """ + super().__init__(enable_gradient_analysis=True) + self.gradient_cosine_similarities = [] + self.current_iteration = 0 + self.save_dir = save_dir + self.rank = rank + + # 如果指定了保存目录,确保目录存在(只在 rank 0 创建) + if self.save_dir and self.rank == 0: + import os + os.makedirs(self.save_dir, exist_ok=True) + print(f"[GradientAnalysis] Initialized. Save dir: {self.save_dir}") + + def __call__(self, batch, student, teacher, vfm_model, args): + losses = {} + context_weight = args.loss_context_weight + content_weight = args.loss_content_weight + + if args.distributed: + student_module = student.module + else: + student_module = student + + dtype_map = {"bf16": torch.bfloat16, "amp": torch.float16} + input_dtype = dtype_map.get(args.precision, torch.float32) + + images, normed_boxes, image_crops, vfm_image = prepare_inputs_integrated(batch, args.device, input_dtype) + + # 分别计算 content 和 context loss(用于梯度分析) + loss_context, loss_content = self.intra_image_distill_with_gradient_analysis( + student_module, teacher, vfm_model, images, normed_boxes, image_crops, vfm_image, args + ) + + losses.update({"loss_context": loss_context * context_weight}) + losses.update({"loss_content": loss_content * content_weight}) + + self.current_iteration += 1 + + return losses, len(images) + + def intra_image_distill_with_gradient_analysis(self, student, teacher, vfm_model, images, normed_boxes, image_crops, vfm_image, args): + """带梯度分析的集成蒸馏""" + roi_size = (3, 3) + B = images.shape[0] + rois_list = [] + crops_list = [] + + for bboxes_per_image, crops_per_image in zip(normed_boxes, image_crops): + valid = bboxes_per_image[:, -1] > 0.5 + rois_list.append(bboxes_per_image[valid, :4]) + crops_list.append(crops_per_image[valid]) + + image_crops = torch.cat(crops_list) + + # 使用 vanilla 模式获取融合特征 + student_features = student.encode_dense(images, normalize=False, keep_shape=True, mode="vanilla") + + # 从融合特征中提取 ROI 特征 + student_roi_features = extract_roi_features_integrated(student_features, rois_list, normalize=True, size=roi_size) + + # 计算融合特征的自相似性 + B, C, H, W = student_features.shape + student_features_flat = student_features.flatten(start_dim=-2) + student_features_norm = F.normalize(student_features_flat, dim=1) + student_intra_corr = torch.einsum('bci,bcj->bij', student_features_norm, student_features_norm) + + with torch.no_grad(): + teacher_crop_features = teacher.encode_image(image_crops, normalize=True) + intra_vfm_feats = extract_vfm_features(vfm_model, vfm_image, args) + + intra_vfm_feats_norm = F.normalize(intra_vfm_feats, dim=1).flatten(start_dim=-2) + intra_vfm_corr = torch.einsum('bci,bcj->bij', intra_vfm_feats_norm, intra_vfm_feats_norm) + + # 计算 Loss + loss_context = context_loss(student_intra_corr, intra_vfm_corr, teacher_temp=0.8) + loss_content = soft_content_distill_loss(student_roi_features, teacher_crop_features) + + # 梯度分析(每隔一定 iteration 进行) + if self.current_iteration % 100 == 0: + self._analyze_gradient_conflict(student, loss_content, loss_context) + + return loss_context, loss_content + + def _analyze_gradient_conflict(self, student, loss_content, loss_context): + """分析 Content 和 Context Loss 的梯度冲突""" + try: + # 获取需要分析的参数(最后几层) + if hasattr(student, 'visual'): + blocks = student.visual.blocks + elif hasattr(student, 'model') and hasattr(student.model, 'visual'): + blocks = student.model.visual.blocks + else: + return + + # 分析每一层的梯度 + layer_cos_sims = {} + + for layer_idx, block in enumerate(blocks): + # 只获取 requires_grad=True 的参数(跳过冻结的层) + params = [p for p in block.parameters() if p.requires_grad] + if not params: + continue + + # 计算 content loss 对该层的梯度 + grad_content = torch.autograd.grad( + loss_content, params, + retain_graph=True, + allow_unused=True, + create_graph=False + ) + + # 计算 context loss 对该层的梯度 + grad_context = torch.autograd.grad( + loss_context, params, + retain_graph=True, + allow_unused=True, + create_graph=False + ) + + # 将梯度展平并计算余弦相似度 + grad_content_flat = torch.cat([g.flatten() for g in grad_content if g is not None]) + grad_context_flat = torch.cat([g.flatten() for g in grad_context if g is not None]) + + if grad_content_flat.numel() > 0 and grad_context_flat.numel() > 0: + cos_sim = F.cosine_similarity( + grad_content_flat.unsqueeze(0), + grad_context_flat.unsqueeze(0) + ).item() + layer_cos_sims[f"layer_{layer_idx}"] = cos_sim + + record = { + "iteration": self.current_iteration, + "layer_cos_sims": layer_cos_sims + } + self.gradient_cosine_similarities.append(record) + + # 如果指定了保存目录且是 rank 0,立即追加保存到 JSONL 文件 + if self.save_dir and self.rank == 0: + import os + import json + filepath = os.path.join(self.save_dir, "gradient_analysis.jsonl") + with open(filepath, "a") as f: + f.write(json.dumps(record) + "\n") + print(f"[GradientAnalysis] Saved iteration {self.current_iteration}, layers: {len(layer_cos_sims)}") + + except Exception as e: + # 梯度分析失败时输出错误信息 + if self.rank == 0: + print(f"[GradientAnalysis] Error at iteration {self.current_iteration}: {e}") + + def get_gradient_analysis_results(self): + """获取梯度分析结果""" + return self.gradient_cosine_similarities + + +# ============ 辅助函数 ============ + +def context_loss(student_corr, teacher_corr, teacher_temp=1.0, student_temp=1.0): + """Context Loss: KL 散度""" + student_log_prob = F.log_softmax(student_corr / student_temp, dim=-1) + with torch.no_grad(): + teacher_prob = F.softmax(teacher_corr / teacher_temp, dim=-1) + kl_loss = F.kl_div(student_log_prob, teacher_prob, reduction='batchmean') * (teacher_temp * student_temp) + return kl_loss + + +def soft_content_distill_loss(student_roi_features, teacher_crop_features, T=1.0): + """Content Loss: 软对齐""" + sim = torch.einsum('bpc,bc->bp', student_roi_features, teacher_crop_features) + weights = F.softmax(sim / T, dim=1) + weighted_student = (student_roi_features * weights.unsqueeze(-1)).sum(dim=1) + weighted_student = F.normalize(weighted_student, dim=-1) + cosine_similarity = (weighted_student * teacher_crop_features).sum(dim=-1) + loss = 1.0 - cosine_similarity.mean() + return loss + + +def extract_roi_features_integrated(x, normed_boxes, size=(3, 3), normalize=False): + """ + 从特征图中提取 ROI 特征 + + Args: + x: 特征图 (B, C, H, W) + normed_boxes: List[Tensor] 归一化的 bboxes + size: ROI 输出大小 + normalize: 是否归一化 + + Returns: + roi_feats: (N_total_boxes, p, C) 其中 p = size[0] * size[1] + """ + def _denormalize_boxes(normed_boxes, x): + h, w = x.shape[-2:] + denormed_boxes = [] + for i, boxes in enumerate(normed_boxes): + new_boxes = boxes.clone() + new_boxes[:, [0, 2]] *= w + new_boxes[:, [1, 3]] *= h + batch_idx = torch.full((new_boxes.shape[0], 1), i, dtype=new_boxes.dtype, device=new_boxes.device) + new_boxes = torch.cat([batch_idx, new_boxes], dim=1) + denormed_boxes.append(new_boxes) + return torch.cat(denormed_boxes, dim=0) + + boxes = _denormalize_boxes(normed_boxes, x) + + if size == (1, 1): + roi_feats = roi_align(x, boxes, size, 1.0, -1, True)[..., 0, 0] + else: + # roi_align 输出: (N, C, size[0], size[1]) + # flatten 后: (N, C, p) 其中 p = size[0] * size[1] + # transpose 后: (N, p, C) - 与原版保持一致! + roi_feats = roi_align(x, boxes, size, 1.0, -1, True).flatten(start_dim=-2).transpose(-2, -1).contiguous() + + if normalize: + # 归一化在最后一个维度(通道维度) + roi_feats = F.normalize(roi_feats, dim=-1) + + return roi_feats + + +def prepare_inputs_integrated(batch, device, dtype): + """准备集成蒸馏的输入(不需要 sd_attn)""" + if len(batch) == 5: + images, normed_boxes, image_crops, vfm_image, _ = batch # 忽略 sd_attn + else: + images, normed_boxes, image_crops, vfm_image = batch + + images = images.to(device=device, dtype=dtype, non_blocking=True) + normed_boxes = normed_boxes.to(device=device, dtype=dtype, non_blocking=True) + image_crops = image_crops.to(device=device, dtype=dtype, non_blocking=True) + vfm_image = vfm_image.to(device=device, dtype=dtype, non_blocking=True) + + return images, normed_boxes, image_crops, vfm_image + + +def extract_vfm_features(vfm_model, image, args): + """从 VFM 模型中提取特征""" + if "dinov2" in args.use_vfm or "sd_dino" in args.use_vfm or "sam_dino" in args.use_vfm: + vfm_feats = vfm_model.get_intermediate_layers(image, reshape=True)[0] + elif 'sam' in args.use_vfm: + vfm_feats = vfm_model.image_encoder(image) + elif 'dino' in args.use_vfm: + feat = vfm_model.get_intermediate_layers(image)[0] + nb_im = feat.shape[0] + patch_size = vfm_model.patch_embed.patch_size + I, J = image[0].shape[-2] // patch_size, image[0].shape[-2] // patch_size + vfm_feats = feat[:, 1:, :].reshape(nb_im, I, J, -1).permute(0, 3, 1, 2) + else: + raise NotImplementedError(f"VFM mode {args.use_vfm} is not implemented.") + return vfm_feats diff --git a/src/training/logger.py b/src/training/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..6d9abed92568d459cbc8d6094ae3901935d89621 --- /dev/null +++ b/src/training/logger.py @@ -0,0 +1,26 @@ +import logging + + +def setup_logging(log_file, level, include_host=False): + if include_host: + import socket + hostname = socket.gethostname() + formatter = logging.Formatter( + f'%(asctime)s | {hostname} | %(levelname)s | %(message)s', datefmt='%Y-%m-%d,%H:%M:%S') + else: + formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s', datefmt='%Y-%m-%d,%H:%M:%S') + + logging.root.setLevel(level) + loggers = [logging.getLogger(name) for name in logging.root.manager.loggerDict] + for logger in loggers: + logger.setLevel(level) + + stream_handler = logging.StreamHandler() + stream_handler.setFormatter(formatter) + logging.root.addHandler(stream_handler) + + if log_file: + file_handler = logging.FileHandler(filename=log_file) + file_handler.setFormatter(formatter) + logging.root.addHandler(file_handler) + diff --git a/src/training/main.py b/src/training/main.py new file mode 100644 index 0000000000000000000000000000000000000000..c51d23d44e143803f55d81747523f5ea79ddeb7b --- /dev/null +++ b/src/training/main.py @@ -0,0 +1,394 @@ +import glob +import logging +import os +import re +import subprocess +import sys +import random +from datetime import datetime +from typing import List +from tools.k_means import run_kmeans +from tools.precompute_knns import run_knns +from tools.segmentation import run_seg +from training.misc import is_main_process +from training.declip import DeCLIP +from training.declip2 import DeCLIP2 +from training.declip_plus import DeCLIP_PLUS,DeCLIPWithREPAProjector +from training.ablation_sam import DeCLIP_SAM_GSC, build_sam_attention_extractor +from training.ablation_sam import DeCLIPWithREPAProjector as DeCLIPWithREPAProjectorSAM +from training.ablation_ijepa import DeCLIP_IJEPA_GSC, build_ijepa_attention_extractor +from training.ablation_ijepa import DeCLIPWithREPAProjector as DeCLIPWithREPAProjectorIJEPA +from training.integrated_distill import IntegratedDistillation, IntegratedDistillationWithGradientAnalysis +from training.integrated_distill import DeCLIPWithREPAProjectorIntegrated +import numpy as np +import torch +from torch import optim +from torch.cuda.amp import GradScaler +from open_clip import create_model_and_transforms, get_tokenizer, create_model +from training.data import get_data +from training.distributed import is_master, init_distributed_device, broadcast_object +from training.logger import setup_logging +from training.params import parse_args +from training.scheduler import cosine_lr, const_lr, const_lr_cooldown +from training.train import train_one_epoch, evaluate, student_teacher_ensemble +from training.file_utils import pt_load +from .utils import freeze_parameters, build_vfm,context_adapter +from torch.utils.tensorboard import SummaryWriter + +LATEST_CHECKPOINT_NAME = "epoch_latest.pt" + + +def random_seed(seed=42, rank=0): + torch.manual_seed(seed + rank) + np.random.seed(seed + rank) + random.seed(seed + rank) + + +def natural_key(string_): + """See http://www.codinghorror.com/blog/archives/001018.html""" + return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] + + +def get_latest_checkpoint(path: str, remote : bool): + # as writen, this glob recurses, so can pick up checkpoints across multiple sub-folders + if remote: + result = subprocess.run(["aws", "s3", "ls", path + "/"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + print(result) + if result.returncode == 1: + return None + checkpoints = [os.path.join(path, x.split(' ')[-1]) for x in result.stdout.decode().split('\n')[:-1]] + else: + checkpoints = glob.glob(path + '**/*.pt', recursive=True) + if checkpoints: + checkpoints = sorted(checkpoints, key=natural_key) + return checkpoints[-1] + return None + + +def main(args): + args = parse_args(args) + if torch.cuda.is_available(): + # This enables tf32 on Ampere GPUs which is only 8% slower than + # float16 and almost as accurate as float32 + # This was a default in pytorch until 1.12 + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.benchmark = True + torch.backends.cudnn.deterministic = False + + # fully initialize distributed device environment + device = init_distributed_device(args) + # get the name of the experiments + if args.name is None: + # sanitize model name for filesystem / uri use, easier if we don't use / in name as a rule? + model_name_safe = args.model.replace('/', '-') + date_str = datetime.now().strftime("%Y_%m_%d-%H_%M_%S") + if args.distributed: + # sync date_str from master to all ranks + date_str = broadcast_object(args, date_str) + args.name = '-'.join([ + date_str, + f"model_{model_name_safe}", + f"lr_{args.lr}", + f"b_{args.batch_size}", + f"j_{args.workers}", + f"p_{args.precision}", + ]) + log_base_path = os.path.join(args.logs, args.name) + if args.use_tensorboard: + writer = SummaryWriter(log_dir=log_base_path) + else: + writer = None + args.log_path = None + if is_master(args, local=args.log_local): + os.makedirs(log_base_path, exist_ok=True) + log_filename = f'out-{args.rank}' if args.log_local else 'out.log' + args.log_path = os.path.join(log_base_path, log_filename) + if os.path.exists(args.log_path): + print("WARNING, Experiment already exists.") + # Setup text logger + args.log_level = logging.DEBUG if args.debug else logging.INFO + setup_logging(args.log_path, args.log_level) + args.checkpoint_path = os.path.join(log_base_path, "checkpoints") + if args.precision == 'fp16': + logging.warning( + 'It is recommended to use AMP mixed-precision instead of FP16. ' + 'FP16 support needs further verification and tuning, especially for train.') + elif args.distributed: + logging.info( + f'Running in distributed mode with multiple processes. Device: {args.device}.' + f'Process (global: {args.rank}, local {args.local_rank}), total {args.world_size}.') + else: + logging.info(f'Running with a single process. Device {args.device}.') + + if isinstance(args.force_image_size, (tuple, list)) and len(args.force_image_size) == 1: + # arg is nargs, single (square) image size list -> int + args.force_image_size = args.force_image_size[0] + + random_seed(args.seed, 0) + student_model, preprocess_train, preprocess_val = create_model_and_transforms( + args.model, + args.pretrained, + precision=args.precision, + device=device, + jit=args.torchscript, + force_quick_gelu=args.force_quick_gelu, + force_custom_text=args.force_custom_text, + force_patch_dropout=args.force_patch_dropout, + force_image_size=args.force_image_size, + pretrained_image=args.pretrained_image, + image_mean=args.image_mean, + image_std=args.image_std, + aug_cfg=args.aug_cfg, + output_dict=True, + cache_dir=args.cache_dir if args.cache_dir else None, + det_image_size=args.det_image_size, + dataset_type=args.dataset_type, + args=args + ) + + random_seed(args.seed, args.rank) + + teacher_model = create_model( + args.model, + args.pretrained, + device=device, + precision=args.precision, + output_dict=True, + cache_dir=args.cache_dir).to(args.device) + + for p in teacher_model.parameters(): + p.requires_grad = False + if 'Tiny' in args.model: + for p in student_model.parameters(): + p.requires_grad = False + if hasattr(student_model, 'visual'): + args.input_size = student_model.visual.image_size + elif hasattr(student_model, 'vision_model'): + args.input_size = student_model.vision_model.image_size + else: + raise ValueError("student_model must have either 'visual' or 'vision_model' attribute") + if args.lock_image: + student_model.lock_image_tower( + unlocked_groups=args.lock_image_unlocked_groups, + freeze_bn_stats=args.lock_image_freeze_bn_stats,) + if args.grad_checkpointing: + student_model.set_grad_checkpointing() + + student_model = freeze_parameters(student_model,args) + + if args.context_adapter: + context_adapter(student_model,args) + + if args.use_vfm: + vfm_model = build_vfm(args) + if isinstance(vfm_model,List): + vfm_model=[model.to(args.device) for model in vfm_model] + else: + vfm_model = vfm_model.to(args.device) + else: + vfm_model = None + if args.repa_layer_idx!=-1: + if args.version == "ablation_sam": + student_model = DeCLIPWithREPAProjectorSAM(student_model, args=args).to(args.device) + elif args.version == "ablation_ijepa": + student_model = DeCLIPWithREPAProjectorIJEPA(student_model, args=args).to(args.device) + elif args.version in ["integrated", "integrated_grad_analysis"]: + student_model = DeCLIPWithREPAProjectorIntegrated(student_model, args=args).to(args.device) + else: + student_model = DeCLIPWithREPAProjector(student_model, args=args).to(args.device) + + if args.version == "declip+": + method = DeCLIP_PLUS() + elif args.version == "declip2": + method = DeCLIP2() + elif args.version == "ablation_sam": + sam_extractor = build_sam_attention_extractor(args) + method = DeCLIP_SAM_GSC(sam_extractor) + elif args.version == "ablation_ijepa": + ijepa_extractor = build_ijepa_attention_extractor(args) + method = DeCLIP_IJEPA_GSC(ijepa_extractor) + elif args.version == "integrated": + method = IntegratedDistillation() + elif args.version == "integrated_grad_analysis": + # 设置梯度分析结果保存目录(与训练日志在同一目录) + gradient_save_dir = os.path.join("logs", args.name) if args.name else "logs/gradient_analysis" + # 传入 rank,只有 rank=0 时保存文件 + method = IntegratedDistillationWithGradientAnalysis(save_dir=gradient_save_dir, rank=args.rank) + else: + method = DeCLIP() + student_model_without_ddp = student_model + if is_master(args): + logging.info("Model:") + logging.info(f"{str(student_model)}") + logging.info("Params:") + params_file = os.path.join(args.logs, args.name, "params.txt") + with open(params_file, "w") as f: + for name in sorted(vars(args)): + val = getattr(args, name) + logging.info(f" {name}: {val}") + f.write(f"{name}: {val}\n") + + if args.distributed: + if args.use_bn_sync: + if args.repa_layer_idx!=-1: + student_model.model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(student_model.model) + else: + student_model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(student_model) + ddp_args = {} + if args.ddp_static_graph: + # this doesn't exist in older PyTorch, arg only added if enabled + ddp_args['static_graph'] = True + student_model = torch.nn.parallel.DistributedDataParallel(student_model, device_ids=[device], **ddp_args) + student_model_without_ddp=student_model.module + + # create optimizer and scaler + optimizer = None + scaler = None + if args.train_data: + exclude = lambda n, p: p.ndim < 2 or "bn" in n or "ln" in n or "bias" in n or 'logit_scale' in n + include = lambda n, p: not exclude(n, p) + named_parameters = list(student_model_without_ddp.named_parameters()) + gain_or_bias_params = [p for n, p in named_parameters if exclude(n, p) and p.requires_grad] + rest_params = [p for n, p in named_parameters if include(n, p) and p.requires_grad] + optimizer = optim.AdamW( + [ + {"params": gain_or_bias_params, "weight_decay": 0.}, + {"params": rest_params, "weight_decay": args.wd}, + ], + lr=args.lr, + betas=(args.beta1, args.beta2), + eps=args.eps, + ) + scaler = GradScaler() if args.precision == "amp" else None + + # optionally resume from a checkpoint + start_epoch = 0 + if args.resume is not None: + checkpoint = pt_load(args.resume, map_location='cpu') + sd = checkpoint["state_dict"] + if 'epoch' in checkpoint: + # resuming a train checkpoint w/ epoch and optimizer state + start_epoch = checkpoint["epoch"] + student_model_without_ddp.load_state_dict(sd) + if args.dataset_type == "froster": + teacher_model.load_state_dict(sd) + if optimizer is not None: + optimizer.load_state_dict(checkpoint["optimizer"]) + if scaler is not None and 'scaler' in checkpoint: + scaler.load_state_dict(checkpoint['scaler']) + if is_main_process(): + logging.info(f"=> resuming checkpoint '{args.resume}' (epoch {start_epoch})") + else: + # loading a bare (model only) checkpoint for fine-tune or evaluation + student_model_without_ddp.load_state_dict(sd) + if args.dataset_type == "froster": + teacher_model.load_state_dict(checkpoint) + if is_main_process(): + logging.info(f"=> loaded checkpoint '{args.resume}' (epoch {start_epoch})") + # initialize datasets + data = get_data(args, (preprocess_train, preprocess_val), epoch=start_epoch, tokenizer=get_tokenizer(args.model)) + assert len(data), 'At least one train or eval dataset must be specified.' + # create scheduler if train + scheduler = None + if 'train' in data and optimizer is not None: + total_steps = (data["train"].dataloader.num_batches // args.accum_freq) * args.epochs + if args.lr_scheduler == "cosine": + scheduler = cosine_lr(optimizer, args.lr, args.warmup, total_steps) + elif args.lr_scheduler == "const": + scheduler = const_lr(optimizer, args.lr, args.warmup, total_steps) + elif args.lr_scheduler == "const-cooldown": + assert args.epochs_cooldown is not None,\ + "Please specify the number of cooldown epochs for this lr schedule." + cooldown_steps = (data["train"].dataloader.num_batches // args.accum_freq) * args.epochs_cooldown + scheduler = const_lr_cooldown( + optimizer, args.lr, args.warmup, total_steps, + cooldown_steps, args.lr_cooldown_power, args.lr_cooldown_end) + else: + logging.error( + f'Unknown scheduler, {args.lr_scheduler}. Available options are: cosine, const, const-cooldown.') + exit(1) + # determine if this worker should save logs and checkpoints. only do so if it is rank == 0 + args.save_logs = args.logs and args.logs.lower() != 'none' and is_master(args) + os.makedirs(args.checkpoint_path, exist_ok=True) + if 'train' not in data or args.eval or args.precompute_knn: + del teacher_model + if args.k_means: + del vfm_model + run_kmeans(student_model_without_ddp if args.repa_layer_idx ==-1 else student_model_without_ddp.model,data,args) + elif args.run_seg: + del vfm_model + run_seg(student_model_without_ddp if args.repa_layer_idx ==-1 else student_model_without_ddp.model ,data,args) + elif args.precompute_knn: + del student_model + run_knns(vfm_model,data,args) + else: + del vfm_model + evaluate(student_model_without_ddp if args.repa_layer_idx ==-1 else student_model_without_ddp.model, data, start_epoch, args) + return + + if not args.skip_first_eval: + if is_main_process(): + logging.info('Evaluate before training') + evaluate(student_model_without_ddp if args.repa_layer_idx ==-1 else student_model_without_ddp.model, data, start_epoch, args) + for epoch in range(start_epoch, args.epochs): + if is_master(args): + logging.info(f'Start epoch {epoch}') + train_one_epoch(student_model, + teacher_model, + vfm_model, + method, + data,epoch,optimizer, scaler, scheduler, writer, args) + completed_epoch = epoch + 1 + student_state_dict = student_model_without_ddp.state_dict() if args.repa_layer_idx ==-1 else student_model_without_ddp.model.state_dict() + if args.alpha < 1.0: + teacher_state_dict = teacher_model.state_dict() + target_state_dict = student_teacher_ensemble(student_state_dict, teacher_state_dict, args.alpha) + else: + target_state_dict = student_state_dict + + if is_master(args): + # Saving checkpoints. + checkpoint_dict = { + "epoch": completed_epoch, + "name": args.name, + "state_dict": target_state_dict, + "optimizer": optimizer.state_dict()} + + if scaler is not None: + checkpoint_dict["scaler"] = scaler.state_dict() + if completed_epoch == args.epochs or ( + args.save_frequency > 0 and (completed_epoch % args.save_frequency) == 0 + ): + torch.save( + checkpoint_dict, + os.path.join(args.checkpoint_path, f"epoch_{completed_epoch}.pt"), + ) + if args.delete_previous_checkpoint: + previous_checkpoint = os.path.join(args.checkpoint_path, f"epoch_{completed_epoch - 1}.pt") + if os.path.exists(previous_checkpoint): + os.remove(previous_checkpoint) + + if args.save_most_recent: + # try not to corrupt the latest checkpoint if save fails + tmp_save_path = os.path.join(args.checkpoint_path, "tmp.pt") + latest_save_path = os.path.join(args.checkpoint_path, LATEST_CHECKPOINT_NAME) + torch.save(checkpoint_dict, tmp_save_path) + os.replace(tmp_save_path, latest_save_path) + + if completed_epoch % args.zeroshot_frequency == 0: + test_model = create_model( + args.model, + args.pretrained, + device=device, + precision=args.precision, + output_dict=True, + cache_dir=args.cache_dir) + incompatible_keys = test_model.load_state_dict(target_state_dict, strict=False) + logging.info(f"eval find incompatible_keys.missing_keys: {incompatible_keys.missing_keys}") + evaluate(test_model, data, completed_epoch, args) + del test_model + if writer is not None: + writer.close() + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/src/training/misc.py b/src/training/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..01bbe6f9c45890d3120b69efafa4912a4497e589 --- /dev/null +++ b/src/training/misc.py @@ -0,0 +1,687 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +Misc functions, including distributed helpers. + +Mostly copy-paste from torchvision references. +""" +import os +import random +import subprocess +import time +from collections import OrderedDict, defaultdict, deque +import datetime +import pickle +from typing import Optional, List +from copy import deepcopy +import json, time +import numpy as np +import torch +import torch.distributed as dist +from torch import Tensor +from pathlib import Path +import colorsys +import warnings +import re +from open_clip.tokenizer import HFTokenizer, tokenize +warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated') +# needed due to empty tensor bug in pytorch and torchvision 0.5 +import torchvision +__torchvision_need_compat_flag = float(torchvision.__version__.split('.')[1]) < 7 +if __torchvision_need_compat_flag: + from torchvision.ops import _new_empty_tensor + from torchvision.ops.misc import _output_size + +HF_HUB_PREFIX = 'hf-hub:' +_MODEL_CONFIG_PATHS = [Path(__file__).parent.parent / f"model_configs/"] +_MODEL_CONFIGS = {} # directory (model_name: config) of model architecture configs + +def _natural_key(string_): + return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] + +def _rescan_model_configs(): + global _MODEL_CONFIGS + + config_ext = ('.json',) + config_files = [] + for config_path in _MODEL_CONFIG_PATHS: + if config_path.is_file() and config_path.suffix in config_ext: + config_files.append(config_path) + elif config_path.is_dir(): + for ext in config_ext: + config_files.extend(config_path.glob(f'*{ext}')) + + for cf in config_files: + with open(cf, 'r') as f: + model_cfg = json.load(f) + if all(a in model_cfg for a in ('embed_dim', 'vision_cfg', 'text_cfg')): + _MODEL_CONFIGS[cf.stem] = model_cfg + + _MODEL_CONFIGS = {k: v for k, v in sorted(_MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0]))} + + +_rescan_model_configs() # initial populate of model config registry + +def get_model_config(model_name): + if model_name in _MODEL_CONFIGS: + return deepcopy(_MODEL_CONFIGS[model_name]) + else: + return None + +def get_tokenizer(model_name): + if 'EVA' in model_name: + from open_clip import eva_clip + return eva_clip.get_tokenizer(model_name) + # 支持 TinyCLIP 模型 + if 'TinyCLIP' in model_name: + from open_clip import tiny_clip + return tiny_clip.get_tokenizer(model_name) + if model_name.startswith(HF_HUB_PREFIX): + tokenizer = HFTokenizer(model_name[len(HF_HUB_PREFIX):]) + else: + config = get_model_config(model_name) + tokenizer = HFTokenizer( + config['text_cfg']['hf_tokenizer_name']) if 'hf_tokenizer_name' in config['text_cfg'] else tokenize + return tokenizer + + +class CosineScheduler(object): + def __init__(self, base_value, final_value, total_iters, warmup_iters=0, start_warmup_value=0, freeze_iters=0): + super().__init__() + self.final_value = final_value + self.total_iters = total_iters + + freeze_schedule = np.zeros((freeze_iters)) + + warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters) + + iters = np.arange(total_iters - warmup_iters - freeze_iters) + schedule = final_value + 0.5 * (base_value - final_value) * (1 + np.cos(np.pi * iters / len(iters))) + self.schedule = np.concatenate((freeze_schedule, warmup_schedule, schedule)) + + assert len(self.schedule) == self.total_iters + + def __getitem__(self, it): + if it >= self.total_iters: + return self.final_value + else: + return self.schedule[it] + +class SmoothedValue(object): + """Track a series of values and provide access to smoothed values over a + window or the global series average. + """ + + def __init__(self, window_size=20, fmt=None): + if fmt is None: + fmt = "{median:.4f} ({global_avg:.4f})" + self.deque = deque(maxlen=window_size) + self.total = 0.0 + self.count = 0 + self.fmt = fmt + + def update(self, value, n=1): + self.deque.append(value) + self.count += n + self.total += value * n + + def synchronize_between_processes(self): + """ + Warning: does not synchronize the deque! + """ + if not is_dist_avail_and_initialized(): + return + t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda') + dist.barrier() + dist.all_reduce(t) + t = t.tolist() + self.count = int(t[0]) + self.total = t[1] + + @property + def median(self): + d = torch.tensor(list(self.deque)) + if d.shape[0] == 0: + return 0 + return d.median().item() + + @property + def avg(self): + d = torch.tensor(list(self.deque), dtype=torch.float32) + return d.mean().item() + + @property + def global_avg(self): + return self.total / self.count + + @property + def max(self): + return max(self.deque) + + @property + def value(self): + return self.deque[-1] + + def __str__(self): + return self.fmt.format( + median=self.median, + avg=self.avg, + global_avg=self.global_avg, + max=self.max, + value=self.value) + + +def all_gather(data): + """ + Run all_gather on arbitrary picklable data (not necessarily tensors) + Args: + data: any picklable object + Returns: + list[data]: list of data gathered from each rank + """ + world_size = get_world_size() + if world_size == 1: + return [data] + + # serialized to a Tensor + buffer = pickle.dumps(data) + storage = torch.ByteStorage.from_buffer(buffer) + tensor = torch.ByteTensor(storage).to("cuda") + + # obtain Tensor size of each rank + local_size = torch.tensor([tensor.numel()], device="cuda") + size_list = [torch.tensor([0], device="cuda") for _ in range(world_size)] + dist.all_gather(size_list, local_size) + size_list = [int(size.item()) for size in size_list] + max_size = max(size_list) + + # receiving Tensor from all ranks + # we pad the tensor because torch all_gather does not support + # gathering tensors of different shapes + tensor_list = [] + for _ in size_list: + tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device="cuda")) + if local_size != max_size: + padding = torch.empty(size=(max_size - local_size,), dtype=torch.uint8, device="cuda") + tensor = torch.cat((tensor, padding), dim=0) + dist.all_gather(tensor_list, tensor) + data_list = [] + for size, tensor in zip(size_list, tensor_list): + buffer = tensor.cpu().numpy().tobytes()[:size] + data_list.append(pickle.loads(buffer)) + + return data_list + + +def reduce_dict(input_dict, average=True): + """ + Args: + input_dict (dict): all the values will be reduced + average (bool): whether to do average or sum + Reduce the values in the dictionary from all processes so that all processes + have the averaged results. Returns a dict with the same fields as + input_dict, after reduction. + """ + world_size = get_world_size() + if world_size < 2: + return input_dict + with torch.no_grad(): + names = [] + values = [] + # sort the keys so that they are consistent across processes + for k in sorted(input_dict.keys()): + names.append(k) + values.append(input_dict[k]) + values = torch.stack(values, dim=0) + dist.all_reduce(values) + if average: + values /= world_size + reduced_dict = {k: v for k, v in zip(names, values)} + return reduced_dict + + +class MetricLogger(object): + def __init__(self, delimiter="\t"): + self.meters = defaultdict(SmoothedValue) + self.delimiter = delimiter + + def update(self, **kwargs): + for k, v in kwargs.items(): + if isinstance(v, torch.Tensor): + v = v.item() + assert isinstance(v, (float, int)) + self.meters[k].update(v) + + def __getattr__(self, attr): + if attr in self.meters: + return self.meters[attr] + if attr in self.__dict__: + return self.__dict__[attr] + raise AttributeError("'{}' object has no attribute '{}'".format( + type(self).__name__, attr)) + + def __str__(self): + loss_str = [] + for name, meter in self.meters.items(): + # print(name, str(meter)) + # import ipdb;ipdb.set_trace() + if meter.count > 0: + loss_str.append( + "{}: {}".format(name, str(meter)) + ) + return self.delimiter.join(loss_str) + + def synchronize_between_processes(self): + for meter in self.meters.values(): + meter.synchronize_between_processes() + + def add_meter(self, name, meter): + self.meters[name] = meter + + def log_every(self, iterable, print_freq, header=None, logger=None): + if logger is None: + print_func = print + else: + print_func = logger.info + + i = 0 + if not header: + header = '' + start_time = time.time() + end = time.time() + iter_time = SmoothedValue(fmt='{avg:.4f}') + data_time = SmoothedValue(fmt='{avg:.4f}') + space_fmt = ':' + str(len(str(len(iterable)))) + 'd' + if torch.cuda.is_available(): + log_msg = self.delimiter.join([ + header, + '[{0' + space_fmt + '}/{1}]', + 'eta: {eta}', + '{meters}', + 'time: {time}', + 'data: {data}', + 'max mem: {memory:.0f}' + ]) + else: + log_msg = self.delimiter.join([ + header, + '[{0' + space_fmt + '}/{1}]', + 'eta: {eta}', + '{meters}', + 'time: {time}', + 'data: {data}' + ]) + MB = 1024.0 * 1024.0 + for obj in iterable: + data_time.update(time.time() - end) + yield obj + + iter_time.update(time.time() - end) + if i % print_freq == 0 or i == len(iterable) - 1: + eta_seconds = iter_time.global_avg * (len(iterable) - i) + eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) + if torch.cuda.is_available(): + print_func(log_msg.format( + i, len(iterable), eta=eta_string, + meters=str(self), + time=str(iter_time), data=str(data_time), + memory=torch.cuda.max_memory_allocated() / MB)) + else: + print_func(log_msg.format( + i, len(iterable), eta=eta_string, + meters=str(self), + time=str(iter_time), data=str(data_time))) + i += 1 + end = time.time() + total_time = time.time() - start_time + total_time_str = str(datetime.timedelta(seconds=int(total_time))) + print_func('{} Total time: {} ({:.4f} s / it)'.format( + header, total_time_str, total_time / len(iterable))) + + +def get_sha(): + cwd = os.path.dirname(os.path.abspath(__file__)) + + def _run(command): + return subprocess.check_output(command, cwd=cwd).decode('ascii').strip() + sha = 'N/A' + diff = "clean" + branch = 'N/A' + try: + sha = _run(['git', 'rev-parse', 'HEAD']) + subprocess.check_output(['git', 'diff'], cwd=cwd) + diff = _run(['git', 'diff-index', 'HEAD']) + diff = "has uncommited changes" if diff else "clean" + branch = _run(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) + except Exception: + pass + message = f"sha: {sha}, status: {diff}, branch: {branch}" + return message + +class CollateFn: + def __init__(self, resolution): + self.resolution = resolution + + def __call__(self, batch): + batch = list(zip(*batch)) + batch[0] = self.nested_tensor_from_tensor_list_fixed(batch[0]) + return tuple(batch) + + def nested_tensor_from_tensor_list_fixed(self, tensor_list: List[Tensor]): + # TODO make this more general + if tensor_list[0].ndim == 3: + if torchvision._is_tracing(): + return _onnx_nested_tensor_from_tensor_list(tensor_list) + max_size = [3,self.resolution[0],self.resolution[1]] + batch_shape = [len(tensor_list)] + max_size + b, c, h, w = batch_shape + dtype = tensor_list[0].dtype + device = tensor_list[0].device + tensor = torch.zeros(batch_shape, dtype=dtype, device=device) + mask = torch.ones((b, h, w), dtype=torch.bool, device=device) + for img, pad_img, m in zip(tensor_list, tensor, mask): + pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img) + m[: img.shape[1], :img.shape[2]] = False + else: + raise ValueError('not supported') + return NestedTensor(tensor, mask) + +def collate_fn(batch): + batch = list(zip(*batch)) + batch[0] = nested_tensor_from_tensor_list(batch[0]) + return tuple(batch) + +def _max_by_axis(the_list): + # type: (List[List[int]]) -> List[int] + maxes = the_list[0] + for sublist in the_list[1:]: + for index, item in enumerate(sublist): + maxes[index] = max(maxes[index], item) + return maxes + + +class NestedTensor(object): + def __init__(self, tensors, mask: Optional[Tensor]): + self.tensors = tensors + self.mask = mask + if mask == 'auto': + self.mask = torch.zeros_like(tensors).to(tensors.device) + if self.mask.dim() == 3: + self.mask = self.mask.sum(0).to(bool) + elif self.mask.dim() == 4: + self.mask = self.mask.sum(1).to(bool) + else: + raise ValueError("tensors dim must be 3 or 4 but {}({})".format(self.tensors.dim(), self.tensors.shape)) + + def imgsize(self): + res = [] + for i in range(self.tensors.shape[0]): + mask = self.mask[i] + maxH = (~mask).sum(0).max() + maxW = (~mask).sum(1).max() + res.append(torch.Tensor([maxH, maxW])) + return res + + def to(self, device): + # type: (Device) -> NestedTensor # noqa + cast_tensor = self.tensors.to(device) + mask = self.mask + if mask is not None: + assert mask is not None + cast_mask = mask.to(device) + else: + cast_mask = None + return NestedTensor(cast_tensor, cast_mask) + + def to_img_list_single(self, tensor, mask): + assert tensor.dim() == 3, "dim of tensor should be 3 but {}".format(tensor.dim()) + maxH = (~mask).sum(0).max() + maxW = (~mask).sum(1).max() + img = tensor[:, :maxH, :maxW] + return img + + def to_img_list(self): + """remove the padding and convert to img list + + Returns: + [type]: [description] + """ + if self.tensors.dim() == 3: + return self.to_img_list_single(self.tensors, self.mask) + else: + res = [] + for i in range(self.tensors.shape[0]): + tensor_i = self.tensors[i] + mask_i = self.mask[i] + res.append(self.to_img_list_single(tensor_i, mask_i)) + return res + + @property + def device(self): + return self.tensors.device + + def decompose(self): + return self.tensors, self.mask + + def __repr__(self): + return str(self.tensors) + + @property + def shape(self): + return { + 'tensors.shape': self.tensors.shape, + 'mask.shape': self.mask.shape + } + + +def nested_tensor_from_tensor_list(tensor_list: List[Tensor]): + # TODO make this more general + if tensor_list[0].ndim == 3: + if torchvision._is_tracing(): + # nested_tensor_from_tensor_list() does not export well to ONNX + # call _onnx_nested_tensor_from_tensor_list() instead + return _onnx_nested_tensor_from_tensor_list(tensor_list) + + # TODO make it support different-sized images + max_size = _max_by_axis([list(img.shape) for img in tensor_list]) + # min_size = tuple(min(s) for s in zip(*[img.shape for img in tensor_list])) + batch_shape = [len(tensor_list)] + max_size + b, c, h, w = batch_shape + dtype = tensor_list[0].dtype + device = tensor_list[0].device + tensor = torch.zeros(batch_shape, dtype=dtype, device=device) + mask = torch.ones((b, h, w), dtype=torch.bool, device=device) + for img, pad_img, m in zip(tensor_list, tensor, mask): + pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img) + m[: img.shape[1], :img.shape[2]] = False + else: + raise ValueError('not supported') + return NestedTensor(tensor, mask) + +# _onnx_nested_tensor_from_tensor_list() is an implementation of +# nested_tensor_from_tensor_list() that is supported by ONNX tracing. +@torch.jit.unused +def _onnx_nested_tensor_from_tensor_list(tensor_list: List[Tensor]) -> NestedTensor: + max_size = [] + for i in range(tensor_list[0].dim()): + max_size_i = torch.max(torch.stack([img.shape[i] for img in tensor_list]).to(torch.float32)).to(torch.int64) + max_size.append(max_size_i) + max_size = tuple(max_size) + + # work around for + # pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img) + # m[: img.shape[1], :img.shape[2]] = False + # which is not yet supported in onnx + padded_imgs = [] + padded_masks = [] + for img in tensor_list: + padding = [(s1 - s2) for s1, s2 in zip(max_size, tuple(img.shape))] + padded_img = torch.nn.functional.pad(img, (0, padding[2], 0, padding[1], 0, padding[0])) + padded_imgs.append(padded_img) + + m = torch.zeros_like(img[0], dtype=torch.int, device=img.device) + padded_mask = torch.nn.functional.pad(m, (0, padding[2], 0, padding[1]), "constant", 1) + padded_masks.append(padded_mask.to(torch.bool)) + + tensor = torch.stack(padded_imgs) + mask = torch.stack(padded_masks) + + return NestedTensor(tensor, mask=mask) + + +def setup_for_distributed(is_master): + """ + This function disables printing when not in master process + """ + import builtins as __builtin__ + builtin_print = __builtin__.print + + def print(*args, **kwargs): + force = kwargs.pop('force', False) + if is_master or force: + builtin_print(*args, **kwargs) + + __builtin__.print = print + + +def is_dist_avail_and_initialized(): + if not dist.is_available(): + return False + if not dist.is_initialized(): + return False + return True + + +def get_world_size(): + if not is_dist_avail_and_initialized(): + return 1 + return dist.get_world_size() + + +def get_rank(): + if not is_dist_avail_and_initialized(): + return 0 + return dist.get_rank() + + +def is_main_process(): + return get_rank() == 0 + + +def save_on_master(*args, **kwargs): + if is_main_process(): + torch.save(*args, **kwargs) + + +def init_distributed_mode(args): + if 'WORLD_SIZE' in os.environ and os.environ['WORLD_SIZE'] != '': # 'RANK' in os.environ and + # args.rank = int(os.environ["RANK"]) + # args.world_size = int(os.environ['WORLD_SIZE']) + # args.gpu = args.local_rank = int(os.environ['LOCAL_RANK']) + + # launch by torch.distributed.launch + # Single node + # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 1 --rank 0 ... + # Multi nodes + # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 2 --rank 0 --dist-url 'tcp://IP_OF_NODE0:FREEPORT' ... + # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 2 --rank 1 --dist-url 'tcp://IP_OF_NODE0:FREEPORT' ... + + local_world_size = int(os.environ['WORLD_SIZE']) + args.world_size = args.world_size * local_world_size + args.gpu = args.local_rank = int(os.environ['LOCAL_RANK']) + args.rank = args.rank * local_world_size + args.local_rank + print('world size: {}, rank: {}, local rank: {}'.format(args.world_size, args.rank, args.local_rank)) + print(json.dumps(dict(os.environ), indent=2)) + elif 'SLURM_PROCID' in os.environ: + args.rank = int(os.environ['SLURM_PROCID']) + args.gpu = args.local_rank = int(os.environ['SLURM_LOCALID']) + args.world_size = int(os.environ['SLURM_NPROCS']) + + print('world size: {}, world rank: {}, local rank: {}, device_count: {}'.format(args.world_size, args.rank, args.local_rank, torch.cuda.device_count())) + else: + print('Not using distributed mode') + args.distributed = False + args.world_size = 1 + args.rank = 0 + args.local_rank = 0 + return + + print("world_size:{} rank:{} local_rank:{}".format(args.world_size, args.rank, args.local_rank)) + args.distributed = True + torch.cuda.set_device(args.local_rank) + args.dist_backend = 'nccl' + print('| distributed init (rank {}): {}'.format(args.rank, args.dist_url), flush=True) + torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url, + world_size=args.world_size, rank=args.rank) + print("Before torch.distributed.barrier()") + torch.distributed.barrier() + print("End torch.distributed.barrier()") + setup_for_distributed(args.rank == 0) + + +@torch.no_grad() +def accuracy(output, target, topk=(1,)): + """Computes the precision@k for the specified values of k""" + if target.numel() == 0: + return [torch.zeros([], device=output.device)] + maxk = max(topk) + batch_size = target.size(0) + + _, pred = output.topk(maxk, 1, True, True) + pred = pred.t() + correct = pred.eq(target.view(1, -1).expand_as(pred)) + + res = [] + for k in topk: + correct_k = correct[:k].view(-1).float().sum(0) + res.append(correct_k.mul_(100.0 / batch_size)) + return res + + +def interpolate(input, size=None, scale_factor=None, mode="nearest", align_corners=None): + # type: (Tensor, Optional[List[int]], Optional[float], str, Optional[bool]) -> Tensor + """ + Equivalent to nn.functional.interpolate, but with support for empty batch sizes. + This will eventually be supported natively by PyTorch, and this + class can go away. + """ + if __torchvision_need_compat_flag < 0.7: + if input.numel() > 0: + return torch.nn.functional.interpolate( + input, size, scale_factor, mode, align_corners + ) + + output_shape = _output_size(2, input, size, scale_factor) + output_shape = list(input.shape[:-2]) + list(output_shape) + return _new_empty_tensor(input, output_shape) + else: + return torchvision.ops.misc.interpolate(input, size, scale_factor, mode, align_corners) + + + +class color_sys(): + def __init__(self, num_colors) -> None: + self.num_colors = num_colors + colors=[] + for i in np.arange(0., 360., 360. / num_colors): + hue = i/360. + lightness = (50 + np.random.rand() * 10)/100. + saturation = (90 + np.random.rand() * 10)/100. + colors.append(tuple([int(j*255) for j in colorsys.hls_to_rgb(hue, lightness, saturation)])) + self.colors = colors + + def __call__(self, idx): + return self.colors[idx] + +def inverse_sigmoid(x, eps=1e-3): + x = x.clamp(min=0, max=1) + x1 = x.clamp(min=eps) + x2 = (1 - x).clamp(min=eps) + return torch.log(x1/x2) + +def clean_state_dict(state_dict): + new_state_dict = OrderedDict() + for k, v in state_dict.items(): + if k[:7] == 'module.': + k = k[7:] # remove `module.` + new_state_dict[k] = v + return new_state_dict \ No newline at end of file diff --git a/src/training/mismatch_analysis.py b/src/training/mismatch_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..17c09ff7fa772e1a83dad71f2a2d47789c605768 --- /dev/null +++ b/src/training/mismatch_analysis.py @@ -0,0 +1,126 @@ +import json +import logging +import os +from typing import Dict, List, Tuple + +import torch + + +def _label_to_name(label: int, label2cat_id: Dict[int, int], cats: Dict[int, dict]) -> str: + """Return human readable category name for a dataset label.""" + cat_id = label2cat_id.get(label) + if cat_id is None: + return f"label_{label}" + cat_info = cats.get(cat_id, {}) + return cat_info.get("name", f"cat_{cat_id}") + + +def _top_mismatch_pairs( + preds: torch.Tensor, + labels: torch.Tensor, + num_classes: int, + label2cat_id: Dict[int, int], + cats: Dict[int, dict], + top_k: int = 30, +) -> Tuple[float, List[dict]]: + """Compute mismatch rate and the most frequent gt->pred pairs.""" + if labels.numel() == 0: + return 0.0, [] + mismatch_mask = preds != labels + total_mismatch = mismatch_mask.sum().item() + mismatch_rate = float(total_mismatch) / float(labels.numel()) + if total_mismatch == 0: + return mismatch_rate, [] + + pair_labels = torch.stack([labels[mismatch_mask], preds[mismatch_mask]], dim=1) + # flatten pair (gt, pred) to single index for counting + flat = pair_labels[:, 0] * num_classes + pair_labels[:, 1] + counts = torch.bincount(flat, minlength=num_classes * num_classes) + # guard in case bincount returns empty + if counts.numel() == 0: + return mismatch_rate, [] + + values, indices = torch.topk(counts, k=min(top_k, counts.numel())) + results = [] + for idx, cnt in zip(indices.tolist(), values.tolist()): + if cnt == 0: + continue + gt_label = idx // num_classes + pred_label = idx % num_classes + results.append( + { + "gt_label": int(gt_label), + "pred_label": int(pred_label), + "gt_name": _label_to_name(gt_label, label2cat_id, cats), + "pred_name": _label_to_name(pred_label, label2cat_id, cats), + "count": int(cnt), + "ratio_within_mismatch": float(cnt) / float(total_mismatch), + } + ) + return mismatch_rate, results + + +def save_mismatch_reports( + preds_dict: Dict[str, torch.Tensor], + labels: torch.Tensor, + dataset, + save_dir: str, + epoch: int, + top_k: int = 30, +) -> None: + """ + Save mismatch statistics to disk. + + Args: + preds_dict: mapping from head name to top1 predictions. + labels: ground-truth labels (long tensor). + dataset: dataset object providing label2cat_id and coco.cats metadata. + save_dir: root directory to write reports. + epoch: current epoch number (used in filenames). + top_k: number of most frequent mismatch pairs to keep. + """ + if not hasattr(dataset, "label2cat_id") or not hasattr(dataset, "coco") or not hasattr(dataset.coco, "cats"): + logging.warning("Dataset missing category metadata, skip mismatch report.") + return + + os.makedirs(save_dir, exist_ok=True) + label2cat_id = dataset.label2cat_id + cats = dataset.coco.cats + num_classes = len(label2cat_id) + + summary = {} + for head, preds in preds_dict.items(): + if preds.numel() != labels.numel(): + logging.warning("Preds and labels length mismatch for head %s, skip.", head) + continue + mismatch_rate, top_pairs = _top_mismatch_pairs( + preds=preds, + labels=labels, + num_classes=num_classes, + label2cat_id=label2cat_id, + cats=cats, + top_k=top_k, + ) + report = { + "epoch": int(epoch), + "total_samples": int(labels.numel()), + "total_mismatch": int((preds != labels).sum().item()), + "mismatch_rate": mismatch_rate, + "top_pairs": top_pairs, + } + summary[head] = report + filename = os.path.join(save_dir, f"{head}_mismatch_epoch{epoch}.json") + try: + with open(filename, "w") as f: + json.dump(report, f, indent=2) + except OSError as e: + logging.error("Failed to write mismatch report for %s: %s", head, e) + + # save a combined summary for quick inspection + combined_path = os.path.join(save_dir, f"mismatch_summary_epoch{epoch}.json") + try: + with open(combined_path, "w") as f: + json.dump(summary, f, indent=2) + except OSError as e: + logging.error("Failed to write combined mismatch summary: %s", e) + diff --git a/src/training/params.py b/src/training/params.py new file mode 100644 index 0000000000000000000000000000000000000000..b17c89d11435fe4d2e95a2432e0df304b8c68cb4 --- /dev/null +++ b/src/training/params.py @@ -0,0 +1,515 @@ +import argparse +import ast + + +def get_default_params(model_name): + # Params from paper (https://arxiv.org/pdf/2103.00020.pdf) + model_name = model_name.lower() + if "vit" in model_name: + return {"lr": 5.0e-4, "beta1": 0.9, "beta2": 0.98, "eps": 1.0e-6} + else: + return {"lr": 5.0e-4, "beta1": 0.9, "beta2": 0.999, "eps": 1.0e-8} + + +class ParseKwargs(argparse.Action): + def __call__(self, parser, namespace, values, option_string=None): + kw = {} + for value in values: + key, value = value.split('=') + try: + kw[key] = ast.literal_eval(value) + except ValueError: + kw[key] = str(value) # fallback to string (avoid need to escape on command line) + setattr(namespace, self.dest, kw) + + +def parse_args(args): + parser = argparse.ArgumentParser() + parser.add_argument( + "--max-boxes", + type=int, + default=20, + ) + parser.add_argument( + "--max-masks", + type=int, + default=20) + parser.add_argument( + "--skip-first-eval", + action="store_true", + default=False) + parser.add_argument( + "--eval", + action="store_true", + default=False) + parser.add_argument( + "--downsample-factor", + type=int, + default=16) + parser.add_argument( + "--alpha", + type=float, + default=2.0, # not used when alpha >=1.0 + ) + parser.add_argument( + "--use_vfm", + type=str, + choices=["sam-B", "sam-L","dinov2-L","dinov2-B","dino-B-8","dino-B-16","sd_dino","sam_dino"], + default="", + ) + parser.add_argument( + "--crop-scale", + type=float, + default=1.0, + ) + parser.add_argument( + "--image-crop-size", + type=int, + default=-1, + ) + parser.add_argument( + "--pre-transforms", + action="store_true", + default=False, + ) + parser.add_argument( + "--max-size", + type=int, + default=1024, + ) + + parser.add_argument( + "--min-size", + type=int, + default=8, + ) + parser.add_argument( + "--max-split", + type=int, + default=6, + ) + parser.add_argument( + "--cache-dir", + type=str, + default="checkpoints", + ) + parser.add_argument( + "--use-knn", + type=str, + default="", + ) + parser.add_argument( + "--loss_content_weight", + type=float, + default=1.0, + ) + parser.add_argument( + "--loss_context_weight", + type=float, + default=0.1, + ) + parser.add_argument( + "--loss_region_weight", + type=float, + default=1.0, + help="loss for Region Correlation Enhancement", + ) + parser.add_argument( + "--train-ratio", + type=float, + default=1.0, + ) + parser.add_argument( + "--l1-weight", + type=float, + default=0.10, + ) + + parser.add_argument( + "--det-image-size", + type=int, + default=1024, + ) + parser.add_argument( + "--train-image-size", + type=int, + default=1024, + ) + + parser.add_argument( + "--image-ave-pool", + action="store_true", + default=False, + ) + + parser.add_argument( + "--train-image-root", + type=str, + default="data/coco/val2017", + ) + parser.add_argument( + "--train-ceph-root", + type=str, + default="", + ) + parser.add_argument( + "--val-image-root", + type=str, + default="data/coco/val2017", + ) + parser.add_argument( + "--val-segm-root", + type=str, + default="data/coco/annotations/panoptic_val2017", + ) + parser.add_argument( + "--train-segm-root", + type=str, + default="data/coco/annotations/panoptic_val2017", + ) + parser.add_argument( + "--embed-path", + type=str, + default="metadata/coco_clip_hand_craft_RN50.npy", + ) + parser.add_argument( + "--train-embed-path", + type=str, + default="", + ) + parser.add_argument( + "--train-data", + type=str, + default="", + help="Path to file(s) with training data. When using webdataset, " + "multiple datasources can be combined using the `::` separator.", + ) + parser.add_argument( + "--val-data", + type=str, + default="data/coco/annotations/instances_val2017_100.json" + ) + parser.add_argument( + "--dataset-type", + choices=['proposals_distill', "region_clip", "grid_distill","knn_grid_distill","coco_caption","dift_grid_distill","dift_proposals_distill","ablation_sam","ablation_ijepa"], + default="grid_distill", + help="Which type of dataset to process." + ) + parser.add_argument( + "--test-type", + choices=['coco_panoptic'], + default="coco_panoptic", + help="Which type of dataset to process." + ) + parser.add_argument( + "--logs", + type=str, + default="./logs/", + help="Where to store tensorboard logs. Use None to avoid storing logs.", + ) + parser.add_argument( + "--enable-mismatch-report", + action="store_true", + default=False, + help="Enable saving mismatch statistics (gt->pred pairs) during eval.", + ) + parser.add_argument( + "--use-tensorboard", + action="store_true", + default=False, + help="Where to store tensorboard logs.", + ) + parser.add_argument( + "--precompute-knn", + action="store_true", + default=False, + help="Where to precompute-knn.", + ) + + parser.add_argument( + "--cache-self-attn", + type=str, + default="", + help="Whether to use precomputed SD attention", + ) + + parser.add_argument( + "--log-local", + action="store_true", + default=False, + help="log files on local master, otherwise global master only.", + ) + parser.add_argument( + "--name", + type=str, + default=None, + help="Optional identifier for the experiment when storing logs. Otherwise use current time.", + ) + parser.add_argument( + "--workers", type=int, default=1, help="Number of dataloader workers per GPU." + ) + parser.add_argument( + "--batch-size", type=int, default=64, help="Batch size per GPU." + ) + parser.add_argument( + "--epochs", type=int, default=32, help="Number of epochs to train for." + ) + parser.add_argument("--lr", type=float, default=1e-5, help="Learning rate.") + parser.add_argument("--beta1", type=float, default=None, help="Adam beta 1.") + parser.add_argument("--beta2", type=float, default=None, help="Adam beta 2.") + parser.add_argument("--eps", type=float, default=None, help="Adam epsilon.") + parser.add_argument("--wd", type=float, default=0.2, help="Weight decay.") + parser.add_argument( + "--warmup", type=int, default=10000, help="Number of steps to warmup for." + ) + parser.add_argument( + "--use-bn-sync", + default=False, + action="store_true", + help="Whether to use batch norm sync.") + parser.add_argument( + "--skip-scheduler", + action="store_true", + default=False, + help="Use this flag to skip the learning rate decay.", + ) + parser.add_argument( + "--lr-scheduler", + type=str, + default='cosine', + help="LR scheduler. One of: 'cosine', 'const' (constant), 'const-cooldown' (constant w/ cooldown). Default: cosine", + ) + parser.add_argument( + "--lr-cooldown-end", type=float, default=0.0, + help="End learning rate for cooldown schedule. Default: 0" + ) + parser.add_argument( + "--lr-cooldown-power", type=float, default=1.0, + help="Power for polynomial cooldown schedule. Default: 1.0 (linear decay)" + ) + parser.add_argument( + "--save-frequency", type=int, default=1, help="How often to save checkpoints." + ) + parser.add_argument( + "--save-most-recent", + action="store_true", + default=False, + help="Always save the most recent model trained to epoch_latest.pt.", + ) + parser.add_argument( + "--zeroshot-frequency", type=int, default=2, help="How often to run zero shot." + ) + parser.add_argument( + "--resume", + default=None, + type=str, + help="path to latest checkpoint (default: none)", + ) + parser.add_argument( + "--precision", + choices=["amp", "amp_bf16", "amp_bfloat16", "bf16", "fp16", "fp32"], + default="amp", + help="Floating point precision." + ) + parser.add_argument( + "--mode", + choices=["qq", "kk", "vv","csa", "qq_vfm_distill","kk_vfm_distill", + "vv_vfm_distill","csa_vfm_distill","all_vfm_distill","maskclip","vanilla","sanity_check",], + default="qq_vfm_distill", + help="Choosing an attention mode for training and inference" + ) + + parser.add_argument( + "--version", + choices=["declip","declip2", "declip+", "ablation_sam", "ablation_ijepa", "integrated", "integrated_grad_analysis"], + default="declip+", + help="Choosing an version for training") + + + parser.add_argument( + "--model", + type=str, + default="RN50", + help="Name of the vision backbone to use.", + ) + parser.add_argument( + "--pretrained", + default='', + type=str, + help="Use a pretrained CLIP model weights with the specified tag or file path.", + ) + parser.add_argument( + "--pretrained-image", + default=False, + action='store_true', + help="Load imagenet pretrained weights for image tower backbone if available.", + ) + parser.add_argument( + "--lock-image", + default=False, + action='store_true', + help="Lock full image tower by disabling gradients.", + ) + parser.add_argument( + "--lock-image-unlocked-groups", + type=int, + default=3, # freeze at 2 + help="Leave last n image tower layer groups unlocked.", + ) + parser.add_argument( + "--lock-image-freeze-bn-stats", + default=True, + action='store_true', + help="Freeze BatchNorm running stats in image tower for any locked layers.", + ) + parser.add_argument( + "--k-means", + default=False, + action='store_true', + help="run k-means on evaluation set", + ) + parser.add_argument( + "--run-seg", + default=False, + action='store_true', + help="run open-vocabulary segmentation on evaluation set", + ) + parser.add_argument( + "--context-adapter", + default=False, + action='store_true', + help="whether add adapter to context feats", + ) + parser.add_argument( + "--custom-freeze-para", + default=False, + action='store_true', + help="whether enable custom parameter freezing", + ) + parser.add_argument( + "--repa_layer_idx", + type=int, + default=-1, + help="layer idx to run vfm repa regularization", + ) + + parser.add_argument( + "--sd-refine-weight", + type=float, + default=1.0, + help="weight for sd-guide smoothing, dino_corr_refined = dino_corr * (sd_refine_weight) + residual * (1-sd_refine_weight)", + ) + + + parser.add_argument( + '--image-mean', type=float, nargs='+', default=None, metavar='MEAN', + help='Override default image mean value of dataset') + parser.add_argument( + '--image-std', type=float, nargs='+', default=None, metavar='STD', + help='Override default image std deviation of of dataset') + parser.add_argument('--aug-cfg', nargs='*', default={}, action=ParseKwargs) + parser.add_argument( + "--grad-checkpointing", + default=False, + action='store_true', + help="Enable gradient checkpointing.", + ) + parser.add_argument( + "--gather-with-grad", + default=False, + action="store_true", + help="enable full distributed gradient for feature gather" + ) + parser.add_argument( + '--force-image-size', type=int, nargs='+', default=None, + help='Override default image size' + ) + parser.add_argument( + "--force-quick-gelu", + default=False, + action='store_true', + help="Force use of QuickGELU activation for non-OpenAI transformer models.", + ) + parser.add_argument( + "--force-patch-dropout", + default=None, + type=float, + help="Override the patch dropout during training, for fine tuning with no dropout near the end as in the paper", + ) + parser.add_argument( + "--force-custom-text", + default=False, + action='store_true', + help="Force use of CustomTextCLIP model (separate text-tower).", + ) + parser.add_argument( + "--torchscript", + default=False, + action='store_true', + help="torch.jit.script the model, also uses jit version of OpenAI models if pretrained=='openai'", + ) + parser.add_argument( + "--accum-freq", type=int, default=1, help="Update the model every --acum-freq steps." + ) + # arguments for distributed training + parser.add_argument( + "--dist-url", + default="env://", + type=str, + help="url used to set up distributed training", + ) + parser.add_argument( + "--dist-backend", default="nccl", type=str, help="distributed backend" + ) + parser.add_argument( + "--debug", + default=False, + action="store_true", + help="If true, more information is logged." + ) + parser.add_argument( + "--copy-codebase", + default=False, + action="store_true", + help="If true, we copy the entire base on the log directory, and execute from there." + ) + parser.add_argument( + "--ddp-static-graph", + default=False, + action='store_true', + help="Enable static graph optimization for DDP in PyTorch >= 1.11.", + ) + parser.add_argument( + "--no-set-device-rank", + default=False, + action="store_true", + help="Don't set device index from local rank (when CUDA_VISIBLE_DEVICES restricted to one per proc)." + ) + parser.add_argument( + "--seed", type=int, default=0, help="Default random seed." + ) + parser.add_argument( + "--grad-clip-norm", type=float, default=None, help="Gradient clip." + ) + parser.add_argument( + "--log-every-n-steps", + type=int, + default=100, + ) + + parser.add_argument( + "--delete-previous-checkpoint", + default=False, + action="store_true", + help="If true, delete previous checkpoint after storing a new one." + ) + + args = parser.parse_args(args) + + # If some params are not passed, we use the default values based on model name. + default_params = get_default_params(args.model) + for name, val in default_params.items(): + if getattr(args, name) is None: + setattr(args, name, val) + + return args diff --git a/src/training/precision.py b/src/training/precision.py new file mode 100644 index 0000000000000000000000000000000000000000..202c9ca5b707d36f1aa903e768c221dad38c7ef5 --- /dev/null +++ b/src/training/precision.py @@ -0,0 +1,11 @@ +import torch +from contextlib import suppress + + +def get_autocast(precision): + if precision == 'amp': + return torch.cuda.amp.autocast + elif precision in ['bfloat16', 'bf16']: + return lambda: torch.cuda.amp.autocast(dtype=torch.bfloat16) + else: + return suppress \ No newline at end of file diff --git a/src/training/profile.py b/src/training/profile.py new file mode 100644 index 0000000000000000000000000000000000000000..f10372cdef306e5e199db432b23062df1c098cf9 --- /dev/null +++ b/src/training/profile.py @@ -0,0 +1,158 @@ +import argparse + +import torch +import open_clip +import pandas as pd +from fvcore.nn import FlopCountAnalysis, flop_count_str, ActivationCountAnalysis + + +parser = argparse.ArgumentParser(description='OpenCLIP Profiler') + +# benchmark specific args +parser.add_argument('--model', metavar='NAME', default='', + help='model(s) to profile') +parser.add_argument('--results-file', default='', type=str, metavar='FILENAME', + help='Output csv file for results') + + +def profile_fvcore( + model, + image_input_size=(3, 224, 224), + text_input_size=(77,), + batch_size=1, + detailed=False, + force_cpu=False +): + if force_cpu: + model = model.to('cpu') + device, dtype = next(model.parameters()).device, next(model.parameters()).dtype + example_image_input = torch.ones((batch_size,) + image_input_size, device=device, dtype=dtype) + example_text_input = torch.ones((batch_size,) + text_input_size, device=device, dtype=torch.int64) + fca = FlopCountAnalysis(model, (example_image_input, example_text_input)) + aca = ActivationCountAnalysis(model, (example_image_input, example_text_input)) + if detailed: + fcs = flop_count_str(fca) + print(fcs) + return fca.total(), aca.total() + + +def profile_fvcore_text( + model, + text_input_size=(77,), + batch_size=1, + detailed=False, + force_cpu=False +): + if force_cpu: + model = model.to('cpu') + device = next(model.parameters()).device + example_input = torch.ones((batch_size,) + text_input_size, device=device, dtype=torch.int64) + fca = FlopCountAnalysis(model, example_input) + aca = ActivationCountAnalysis(model, example_input) + if detailed: + fcs = flop_count_str(fca) + print(fcs) + return fca.total(), aca.total() + + +def profile_fvcore_image( + model, + image_input_size=(3, 224, 224), + batch_size=1, + detailed=False, + force_cpu=False +): + if force_cpu: + model = model.to('cpu') + device, dtype = next(model.parameters()).device, next(model.parameters()).dtype + example_input = torch.ones((batch_size,) + image_input_size, device=device, dtype=dtype) + fca = FlopCountAnalysis(model, example_input) + aca = ActivationCountAnalysis(model, example_input) + if detailed: + fcs = flop_count_str(fca) + print(fcs) + return fca.total(), aca.total() + + +def count_params(model): + return sum([m.numel() for m in model.parameters()]) + + +def profile_model(model_name): + model = open_clip.create_model(model_name, force_custom_text=True, pretrained_hf=False) + model.eval() + if torch.cuda.is_available(): + model = model.cuda() + + if isinstance(model.visual.image_size, (tuple, list)): + image_input_size = (3,) + tuple(model.visual.image_size[-2:]) + else: + image_input_size = (3, model.visual.image_size, model.visual.image_size) + text_input_size = (77,) + + results = {} + results['model'] = model_name + results['image_size'] = image_input_size[1] + + model_cfg = open_clip.get_model_config(model_name) + if model_cfg: + vision_cfg = open_clip.CLIPVisionCfg(**model_cfg['vision_cfg']) + text_cfg = open_clip.CLIPTextCfg(**model_cfg['text_cfg']) + results['image_width'] = int(vision_cfg.width) + results['text_width'] = int(text_cfg.width) + results['embed_dim'] = int(model_cfg['embed_dim']) + else: + results['image_width'] = 0 + results['text_width'] = 0 + results['embed_dim'] = 0 + + retries = 2 + while retries: + retries -= 1 + try: + macs, acts = profile_fvcore( + model, image_input_size=image_input_size, text_input_size=text_input_size, force_cpu=not retries) + + image_macs, image_acts = profile_fvcore_image( + model.visual, image_input_size=image_input_size, force_cpu=not retries) + + text_macs, text_acts = profile_fvcore_text( + model.text, text_input_size=text_input_size, force_cpu=not retries) + + results['gmacs'] = round(macs / 1e9, 2) + results['macts'] = round(acts / 1e6, 2) + results['mparams'] = round(count_params(model) / 1e6, 2) + results['image_gmacs'] = round(image_macs / 1e9, 2) + results['image_macts'] = round(image_acts / 1e6, 2) + results['image_mparams'] = round(count_params(model.visual) / 1e6, 2) + results['text_gmacs'] = round(text_macs / 1e9, 2) + results['text_macts'] = round(text_acts / 1e6, 2) + results['text_mparams'] = round(count_params(model.text) / 1e6, 2) + except RuntimeError as e: + pass + return results + + +def main(): + args = parser.parse_args() + + # FIXME accept a text file name to allow lists of models in txt/csv + if args.model == 'all': + parsed_model = open_clip.list_models() + else: + parsed_model = args.model.split(',') + + results = [] + for m in parsed_model: + row = profile_model(m) + results.append(row) + + df = pd.DataFrame(results, columns=results[0].keys()) + df = df.sort_values('gmacs') + print(df) + if args.results_file: + df.to_csv(args.results_file, index=False) + + +if __name__ == '__main__': + main() diff --git a/src/training/region_clip.py b/src/training/region_clip.py new file mode 100644 index 0000000000000000000000000000000000000000..962a4dbb0bad81f80fc2509f13e0e37cb94a2de2 --- /dev/null +++ b/src/training/region_clip.py @@ -0,0 +1,67 @@ +import numpy as np +import torch +import torch.nn.functional as F +import torch.nn as nn + + +def get_fed_loss_inds(gt_classes, num_sample_cats, C): + appeared = torch.unique(gt_classes) # C' + prob = appeared.new_ones(C).float() + if len(appeared) < num_sample_cats: + prob[appeared] = 0 + more_appeared = torch.multinomial( + prob, num_sample_cats - len(appeared), + replacement=False) + appeared = torch.cat([appeared, more_appeared]) + return appeared + + +class RegionCLIP(nn.Module): + def __init__(self, args): + super().__init__() + embed_path = args.train_embed_path + noun_embeddings = torch.from_numpy(np.load(embed_path)) + noun_embeddings = F.normalize(noun_embeddings, dim=-1) + self.register_buffer("noun_embeddings", noun_embeddings) + self.place_holder = nn.Parameter(torch.ones(1)) + + def __call__(self, batch, model, dist_model, loss, device, cast_dtype, + distributed, args): + if distributed: + model = model.module + images, boxes = batch + images = images.to(device=device, dtype=cast_dtype, non_blocking=True) + boxes = boxes.to(device=device, non_blocking=True) + + boxes_list = [] + boxes_label_list = [] + + for boxes_per_image in boxes: + boxes_per_image = boxes_per_image[boxes_per_image[:, -1] > 0.5] + boxes_label_list.append(boxes_per_image[:, 4].long()) + boxes_list.append(boxes_per_image[:, :4]) + boxes_labels = torch.cat(boxes_label_list) + box_features = model.encode_pseudo_boxes(images, boxes_list, normalize=True, + extract_type=args.extract_type) + temp = model.logit_scale.exp().detach() + boxes2nouns = box_features @ self.noun_embeddings.T * temp + target = torch.zeros_like(boxes2nouns) + target[range(len(boxes_labels)), boxes_labels] = 1.0 + + appeared = get_fed_loss_inds(boxes_labels, 100, self.noun_embeddings.shape[0]) + target = target[:, appeared] + boxes2nouns = boxes2nouns[:, appeared] + + loss_cls = F.binary_cross_entropy_with_logits(boxes2nouns, target, reduction='none') # B x C + loss_cls = loss_cls.sum(-1).mean() + + image_size = model.visual.image_size + if isinstance(image_size, int): + tar_h = tar_w = image_size + else: + tar_h, tar_w = image_size + images = F.interpolate(images, size=(tar_h, tar_w), mode='bilinear') + + losses = dict(loss_contrast=loss_cls * args.contrast_weight) + + return losses, len(images), temp diff --git a/src/training/scheduler.py b/src/training/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..fba76fcf1720b11d136a5ab6d3a58ab2fbe42f74 --- /dev/null +++ b/src/training/scheduler.py @@ -0,0 +1,53 @@ +import numpy as np + + +def assign_learning_rate(optimizer, new_lr): + for param_group in optimizer.param_groups: + param_group["lr"] = new_lr + + +def _warmup_lr(base_lr, warmup_length, step): + return base_lr * (step + 1) / warmup_length + + +def const_lr(optimizer, base_lr, warmup_length, steps): + def _lr_adjuster(step): + if step < warmup_length: + lr = _warmup_lr(base_lr, warmup_length, step) + else: + lr = base_lr + assign_learning_rate(optimizer, lr) + return lr + return _lr_adjuster + + +def const_lr_cooldown(optimizer, base_lr, warmup_length, steps, cooldown_steps, cooldown_power=1.0, cooldown_end_lr=0.): + def _lr_adjuster(step): + start_cooldown_step = steps - cooldown_steps + if step < warmup_length: + lr = _warmup_lr(base_lr, warmup_length, step) + else: + if step < start_cooldown_step: + lr = base_lr + else: + e = step - start_cooldown_step + es = steps - start_cooldown_step + # linear decay if power == 1; polynomial decay otherwise; + decay = (1 - (e/es)) ** cooldown_power + lr = decay * (base_lr - cooldown_end_lr) + cooldown_end_lr + assign_learning_rate(optimizer, lr) + return lr + return _lr_adjuster + + +def cosine_lr(optimizer, base_lr, warmup_length, steps): + def _lr_adjuster(step): + if step < warmup_length: + lr = _warmup_lr(base_lr, warmup_length, step) + else: + e = step - warmup_length + es = steps - warmup_length + lr = 0.5 * (1 + np.cos(np.pi * e / es)) * base_lr + assign_learning_rate(optimizer, lr) + return lr + return _lr_adjuster diff --git a/src/training/train.py b/src/training/train.py new file mode 100644 index 0000000000000000000000000000000000000000..12c7116e1e98d9bb4a4ee58d9cb511b9bec1f2de --- /dev/null +++ b/src/training/train.py @@ -0,0 +1,179 @@ +import json +import logging +import math +import time +import torch +from training.misc import is_main_process +from open_clip import get_cast_dtype +from .distributed import is_master +from .zero_shot import multi_gpu_sync, zero_shot_eval +from .precision import get_autocast +import os + +class AverageMeter(object): + """Computes and stores the average and current value""" + + def __init__(self): + self.reset() + + def reset(self): + self.val = 0 + self.avg = 0 + self.sum = 0 + self.count = 0 + + def update(self, val, n=1): + self.val = val + self.sum += val * n + self.count += n + self.avg = self.sum / self.count + +def postprocess_clip_output(model_out): + return { + "image_features": model_out[0], + "text_features": model_out[1], + "logit_scale": model_out[2] + } + +def unwrap_model(model): + if hasattr(model, 'module'): + return model.module + else: + return model + +def backward(total_loss, scaler): + if scaler is not None: + scaler.scale(total_loss).backward() + else: + total_loss.backward() + +def format_time(seconds): + hours = int(seconds // 3600) + minutes = int((seconds % 3600) // 60) + seconds = int(seconds % 60) + return f"{hours}h {minutes}m {seconds}s" + +@torch.no_grad() +def student_teacher_ensemble(student, teacher, alpha=0.5): + target_state_dict = {} + for k, v in student.items(): + if k in teacher: + target_state_dict[k] = v * alpha + teacher[k] * (1.0 - alpha) + else: + continue + return target_state_dict + + +def train_one_epoch(model, teacher_model, vfm_model, method, data, epoch, optimizer, scaler, scheduler, writer, args): + autocast = get_autocast(args.precision) + model.train() + data['train'].set_epoch(epoch) # set epoch in process safe manner via sampler or shared_epoch + dataloader = data['train'].dataloader + num_batches_per_epoch = dataloader.num_batches // args.accum_freq + sample_digits = math.ceil(math.log(dataloader.num_samples + 1, 10)) + losses_m = {} + batch_time_m = AverageMeter() + data_time_m = AverageMeter() + end = time.time() + epoch_start_time = time.time() + for i, batch in enumerate(dataloader): + i_accum = i // args.accum_freq + step = num_batches_per_epoch * epoch + i_accum + if not args.skip_scheduler: + scheduler(step) + data_time_m.update(time.time() - end) + optimizer.zero_grad() + assert args.accum_freq == 1, "accum freq disabled" + with autocast(): + losses, batch_size = method(batch, model, teacher_model, vfm_model, args) + total_loss = sum(losses.values()) + losses["loss"] = total_loss + backward(total_loss, scaler) + if scaler is not None: + if args.grad_clip_norm is not None: + scaler.unscale_(optimizer) + torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip_norm, norm_type=2.0) + scaler.step(optimizer) + scaler.update() + else: + if args.grad_clip_norm is not None: + torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip_norm, norm_type=2.0) + optimizer.step() + + batch_time_m.update(time.time() - end) + end = time.time() + batch_count = i_accum + 1 + + # compute the epoch remaining time + elapsed_time = time.time() - epoch_start_time + avg_iteration_time = elapsed_time / batch_count + remaining_iterations = num_batches_per_epoch - batch_count + estimated_remaining_time = avg_iteration_time * remaining_iterations + formatted_eta = format_time(estimated_remaining_time) + if is_master(args) and (i_accum % args.log_every_n_steps == 0 or batch_count == num_batches_per_epoch): + # batch_size = len(images) + num_samples = batch_count * batch_size * args.accum_freq * args.world_size + samples_per_epoch = dataloader.num_samples + percent_complete = 100.0 * batch_count / num_batches_per_epoch + + # NOTE loss is coarsely sampled, just master node and per log update + for key, val in losses.items(): + if key not in losses_m: + losses_m[key] = AverageMeter() + losses_m[key].update(val.item(), batch_size) + + loss_log = " ".join( + [ + f"{loss_name.capitalize()}: {loss_m.val:#.5g} ({loss_m.avg:#.5g})" + for loss_name, loss_m in losses_m.items() + ] + ) + samples_per_second = args.accum_freq * args.batch_size * args.world_size / batch_time_m.val + samples_per_second_per_gpu = args.accum_freq * args.batch_size / batch_time_m.val + logging.info( + f"Train Epoch: {epoch} [{num_samples:>{sample_digits}}/{samples_per_epoch} ({percent_complete:.0f}%)] " + f"ETA: {formatted_eta} " + f"Data (t): {data_time_m.avg:.3f} " + f"Batch (t): {batch_time_m.avg:.3f} " + f"LR: {optimizer.param_groups[0]['lr']:6f} "+ loss_log + ) + # Save train loss / etc. Using non avg meter values as loggers have their own smoothing + log_data = { + "data_time": data_time_m.val, + "batch_time": batch_time_m.val, + "samples_per_second": samples_per_second, + "samples_per_second_per_gpu": samples_per_second_per_gpu, + "lr": optimizer.param_groups[0]["lr"] + } + log_data.update({name:val.val for name,val in losses_m.items()}) + # resetting batch / data time meters per log window + batch_time_m.reset() + data_time_m.reset() + + +def evaluate(model, data, epoch, args): + metrics = {} + model.eval() + zero_shot_metrics = zero_shot_eval(model, data, epoch, args) + if not is_master(args): + return {} + metrics.update(zero_shot_metrics) + if not metrics: + return metrics + + keys = ''.join([f"{k}, " for k in metrics.keys() if 'all' in k])[:-2] + values = ''.join([f'{round(v, 4):.4f}, ' for k, v in metrics.items() if 'all' in k])[:-2] + + logging.info( + f"Eval Epoch: {epoch-1}. " + + f"{keys}: {values}." + ) + # TODO save the results as plots + logging.info(metrics) + + if args.save_logs: + with open(os.path.join(args.checkpoint_path, "results.json"), "a+") as f: + f.write(json.dumps(metrics)) + f.write("\n") + + return metrics diff --git a/src/training/utils.py b/src/training/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bafe10222374e3b3fb0cf58ab05ca80f016876c6 --- /dev/null +++ b/src/training/utils.py @@ -0,0 +1,385 @@ + +import torch +import torch.nn.functional as F +import numpy as np +import os +from contextlib import nullcontext +from src.segment_anything import sam_model_registry +import torch.nn as nn +# 延迟导入 diffusion_model,避免在不需要时触发 diffusers 依赖 +# from diffusion_model.stable_diffusion import diffusion +from open_clip.eva_clip.eva_vit_model import Attention + +def context_adapter(clip, args): + last_block_attn=clip.visual.blocks[-1].attn + attn_config=extract_attention_config(last_block_attn) + new_attn=CustomAttention(args.mode, **attn_config) + device = next(last_block_attn.parameters()).device + new_attn = new_attn.to(device) + with torch.no_grad(): + for param_name, param_value in last_block_attn.named_parameters(): + if param_name in new_attn.state_dict(): + new_attn.state_dict()[param_name].copy_(param_value) + clip.visual.blocks[-1].attn = new_attn + + +class CustomAttention(Attention): + def __init__(self, mode, *args, **kwargs): + super().__init__(*args, **kwargs) + self.mode=mode + if mode=="csa_vfm_distill": + self.q_adapter = nn.Sequential( + nn.Linear(self.proj.in_features, 1024), + nn.SiLU(), + nn.Linear(1024, 1024), + nn.SiLU(), + nn.Linear(1024, self.proj.in_features)) + + self.k_adapter = nn.Sequential( + nn.Linear(self.proj.in_features, 1024), + nn.SiLU(), + nn.Linear(1024, 1024), + nn.SiLU(), + nn.Linear(1024, self.proj.in_features)) + else: + self.context_adapter = nn.Sequential( + nn.Linear(self.proj.in_features, 1024), + nn.SiLU(), + nn.Linear(1024, 1024), + nn.SiLU(), + nn.Linear(1024, self.proj.in_features)) + self.alpha=0.7 + self._reset_mlp_parameters() + + def _reset_mlp_parameters(self): + if self.mode == "csa_vfm_distill": + for layer in self.q_adapter: + if isinstance(layer, nn.Linear): + nn.init.xavier_uniform_(layer.weight) + if layer.bias is not None: + nn.init.zeros_(layer.bias) + for layer in self.k_adapter: + if isinstance(layer, nn.Linear): + nn.init.xavier_uniform_(layer.weight) + if layer.bias is not None: + nn.init.zeros_(layer.bias) + else: + for layer in self.context_adapter: + if isinstance(layer, nn.Linear): + nn.init.xavier_uniform_(layer.weight) + if layer.bias is not None: + nn.init.zeros_(layer.bias) + + def ss_attn(self, x, mode): + B, N, C = x.shape + if self.subln: + q = F.linear(input=x, weight=self.q_proj.weight, bias=self.q_bias) + k = F.linear(input=x, weight=self.k_proj.weight, bias=None) + v = F.linear(input=x, weight=self.v_proj.weight, bias=self.v_bias) + if self.mode=="csa_vfm_distill": + q_distill = self.q_adapter(q) + k_distill = self.k_adapter(k) + q_distill=q + q_distill*(self.alpha) + k_distill=k + k_distill*(self.alpha) + + q_distill=q_distill.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) + k_distill=k_distill.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) + q_distill = q_distill.contiguous().view(B*self.num_heads, N, -1) + k_distill = k_distill.contiguous().view(B*self.num_heads, N, -1) + elif self.mode=="qq_vfm_distill": + q_distill=self.context_adapter(q) + q_distill=q_distill.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) + q_distill = q_distill.contiguous().view(B*self.num_heads, N, -1) + else: + raise NotImplementedError + + q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) # B, num_heads, N, C + k = k.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) + v = v.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) + else: + qkv_bias = None + if self.q_bias is not None: + qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias)) + + qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias) + qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # 3, B, num_heads, N, C + q, k, v = qkv[0], qkv[1], qkv[2] + + q = q.contiguous().view(B*self.num_heads, N, -1) + k = k.contiguous().view(B*self.num_heads, N, -1) + v = v.contiguous().view(B*self.num_heads, N, -1) + if 'qq' in mode: + q_attn = torch.bmm(q, q.transpose(1, 2)) # self.scale + attn_weights = F.softmax(q_attn, dim=-1) + elif 'csa' in mode: + q_attn = torch.bmm(q, q.transpose(1, 2)) # self.scale + k_attn = torch.bmm(k, k.transpose(1, 2)) # self.scale + attn_weights = F.softmax(q_attn + k_attn, dim=-1) + elif 'vv' in mode: + v_attn = torch.bmm(v, v.transpose(1, 2)) # self.scale + attn_weights = F.softmax(v_attn, dim=-1) + elif 'kk' in mode: + k_attn = torch.bmm(k, k.transpose(1, 2)) # self.scale + attn_weights = F.softmax(k_attn, dim=-1) + elif 'all' in mode: + q_attn = torch.bmm(q, q.transpose(1, 2)) # self.scale + k_attn = torch.bmm(k, k.transpose(1, 2)) # self.scale + v_attn = torch.bmm(v, v.transpose(1, 2)) # self.scale + _attn = (q_attn+k_attn+v_attn)/3.0 + attn_weights = F.softmax(_attn, dim=-1) + else: + raise NotImplementedError(f"Mode '{mode}' is not implemented.") + + attn_output = torch.bmm(attn_weights, v) + attn_output = attn_output.transpose(0, 1).contiguous().view(N, B, C).transpose(0, 1) # B,N,C + attn_output = self.inner_attn_ln(attn_output) + attn_output = self.proj(attn_output) + attn_output = self.proj_drop(attn_output) + + if mode=="qq_vfm_distill": + return attn_output, q_distill[:,1:] + elif mode=="kk_vfm_distill": + return attn_output, k[:,1:] + elif mode=="csa_vfm_distill": + return attn_output, (q_distill[:,1:], k_distill[:,1:]) + elif mode=="vv_vfm_distill": + return attn_output, v[:,1:] + elif mode=="all_vfm_distill": + return attn_output, (q[:,1:], k[:,1:], v[:,1:]) + else: + return attn_output + + +def extract_attention_config(attn_module): + config = { + "dim": attn_module.proj.in_features, # 输入维度 + "num_heads": attn_module.num_heads, # 多头注意力的头数 + "qkv_bias": attn_module.q_bias is not None, # QKV 是否使用偏置 + "qk_scale": attn_module.scale, # QK 的缩放因子 + "attn_drop": attn_module.attn_drop.p, # Dropout 概率 + "proj_drop": attn_module.proj_drop.p, # 输出投影的 Dropout 概率 + "subln": attn_module.subln, # 是否使用 SubLayerNorm + "rope": attn_module.rope, + "norm_layer": type(attn_module.inner_attn_ln), # 使用的归一化层类型 + "xattn": getattr(attn_module, "xattn", False), # 是否使用 xattn 模式 + } + return config + +def get_autocast(precision): + if precision == "bf16": + return lambda: torch.autocast("cuda", dtype=torch.bfloat16) + elif precision == "amp": + return lambda: torch.cuda.amp.autocast() + else: + return lambda: nullcontext() + +def mask2box(mask): + ys, xs = np.where(mask) + y0, y1 = ys.min(), ys.max() + x0, x1 = xs.min(), xs.max() + return x0, y0, x1, y1 + + + + +def build_vfm(args): + name=args.use_vfm + sam_ckpts = { + "sam-B": "/opt/tiger/xiaomoguhzz/sam/sam_vit_b_01ec64.pth", + "sam-L": "/opt/tiger/xiaomoguhzz/sam/sam_vit_l_0b3195.pth", + } + + dinov2_ckpts = { + "dinov2-L": "dinov2_vitl14_reg", + "dinov2-B": "dinov2_vitb14_reg", + "dinov2-B-noreg": "dinov2_vitb14", + "dinov2-L-noreg": "dinov2_vitl14", + } + + dino_ckpts = { + "dino-B-8": "dino_vitb8", + "dino-B-16": "dino_vitb16", + } + + vfm = None + + if name.startswith("dinov2"): + if name in dinov2_ckpts: + model_name = dinov2_ckpts[name] + try: + vfm = torch.hub.load('facebookresearch/dinov2', model_name).half() + except Exception as e: + raise RuntimeError(f"Failed to load DINOv2 model '{name}': {e}") + else: + raise NotImplementedError(f"VLM model '{name}' not supported under DINOv2 category.") + + elif name.startswith("dino"): + if name in dino_ckpts: + model_name = dino_ckpts[name] + try: + vfm = torch.hub.load('facebookresearch/dino:main', model_name).half() + except Exception as e: + raise RuntimeError(f"Failed to load DINO model '{name}': {e}") + else: + raise NotImplementedError(f"VLM model '{name}' not supported under DINO category.") + + elif name.startswith("sd_dino"): + model_name = dinov2_ckpts['dinov2-B'] + try: + dinov2 = torch.hub.load('facebookresearch/dinov2', model_name).half().eval() + except Exception as e: + raise RuntimeError(f"Failed to load DINOv2 model '{name}': {e}") + + try: + # 延迟导入:只在 sd_dino 模式下才导入 diffusers 相关依赖 + from diffusion_model.stable_diffusion import diffusion + sd=diffusion(attention_layers_to_use=[-4, -6],model='v2.1', time_step=45, device=args.device, dtype=torch.float16).eval() + except Exception as e: + raise RuntimeError(f"Failed to load diffusion model") + for p in dinov2.parameters(): + p.requires_grad = False + for p in sd.parameters(): + p.requires_grad = False + return [dinov2, sd] + + elif name.startswith("sam_dino"): + + name='dinov2-B' + model_name = dinov2_ckpts[name] + try: + dinov2 = torch.hub.load('facebookresearch/dinov2', model_name).half() + except Exception as e: + raise RuntimeError(f"Failed to load DINOv2 model '{name}': {e}") + sam = sam_model_registry['vit_l'](checkpoint="/opt/tiger/xiaomoguhzz/sam/sam_vit_l_0b3195.pth").half() + for p in dinov2.parameters(): + p.requires_grad = False + for p in sam.parameters(): + p.requires_grad = False + return [dinov2, sam] + + elif name.startswith("sam"): + if name in sam_ckpts: + vit_type = "vit_b" if "B" in name else "vit_l" + checkpoint_path = sam_ckpts[name] + try: + vfm = sam_model_registry[vit_type](checkpoint=checkpoint_path).half() + except Exception as e: + raise RuntimeError(f"Failed to load SAM model '{name}' with checkpoint '{checkpoint_path}': {e}") + else: + raise NotImplementedError(f"VLM model '{name}' not supported under SAM category.") + else: + raise NotImplementedError(f"VLM model '{name}' not supported.") + + for p in vfm.parameters(): + p.requires_grad = False + + return vfm + +def freeze_parameters(model, args): + freeze_keys = get_freeze_keys(args) + for name, param in model.named_parameters(): + if name in freeze_keys: + param.requires_grad = False + return model + +def get_freeze_keys(args): + if args.model=="ViT-B-16": + return ViTB_16_freeze_keys + elif args.model=="ViT-L-14" or args.model=="ViT-L-14-336": + return ViTL_14_freeze_keys + elif args.model=="EVA02-CLIP-B-16": + if args.custom_freeze_para: + return custom_EVA_ViTB_16_freeze_keys + if args.mode=="qq_vfm_distill": + return ViTB_EVA_16_qq_Distill_keys + elif args.mode=="kk_vfm_distill": + return ViTB_EVA_16_kk_Distill_keys + elif args.mode=="sanity_check": + return sanity_check_freeze_keys + else: + return BASE_EVA_ViTB_16_freeze_keys + elif args.model=="EVA02-CLIP-L-14-336": + if args.custom_freeze_para: + return custom_EVA_ViTL_14_freeze_keys + if args.mode=="qq_vfm_distill": + return ViTL_EVA_14_qq_Distill_keys + elif args.mode=="kk_vfm_distill": + return ViTL_EVA_14_kk_Distill_keys + elif args.mode=="sanity_check": + return sanity_check_freeze_keys + else: + return BASE_EVA_ViTL_14_freeze_keys + elif args.model=="siglip-so400m-patch14-384": + return siglip_384_Distill_Freeze_keys + elif "TinyCLIP" in args.model: + # TinyCLIP-auto-ViT-63M-32-Text-31M 有12层,最后一个block索引为11 + return TinyCLIP_63M_freeze_keys + + +TinyCLIP_63M_freeze_keys=[ + '_image_encoder.visual.transformer.resblocks.11.ln_2.weight', + '_image_encoder.visual.transformer.resblocks.11.ln_2.bias', + '_image_encoder.visual.transformer.resblocks.11.mlp.c_fc.weight', + '_image_encoder.visual.transformer.resblocks.11.mlp.c_fc.bias', + '_image_encoder.visual.transformer.resblocks.11.mlp.c_proj.weight', + '_image_encoder.visual.transformer.resblocks.11.mlp.c_proj.bias', +] + +ViTB_16_freeze_keys=[ + 'visual.transformer.resblocks.11.ln_2.weight', + 'visual.transformer.resblocks.11.ln_2.bias', + 'visual.transformer.resblocks.11.mlp.c_fc.weight', + 'visual.transformer.resblocks.11.mlp.c_fc.bias', + 'visual.transformer.resblocks.11.mlp.c_proj.weight', + 'visual.transformer.resblocks.11.mlp.c_proj.bias'] + +ViTL_14_freeze_keys=[ + 'visual.transformer.resblocks.23.ln_2.weight', + 'visual.transformer.resblocks.23.ln_2.bias', + 'visual.transformer.resblocks.23.mlp.c_fc.weight', + 'visual.transformer.resblocks.23.mlp.c_fc.bias', + 'visual.transformer.resblocks.23.mlp.c_proj.weight', + 'visual.transformer.resblocks.23.mlp.c_proj.bias'] + +BASE_EVA_ViTB_16_freeze_keys=[ + 'logit_scale', + 'visual.blocks.11.norm2.weight', + 'visual.blocks.11.norm2.bias', + 'visual.blocks.11.mlp.w1.weight', + 'visual.blocks.11.mlp.w1.bias', + 'visual.blocks.11.mlp.w2.weight', + 'visual.blocks.11.mlp.w2.bias', + 'visual.blocks.11.mlp.w3.weight', + 'visual.blocks.11.mlp.w3.bias', + 'visual.blocks.11.mlp.ffn_ln.weight', + 'visual.blocks.11.mlp.ffn_ln.bias'] + +BASE_EVA_ViTL_14_freeze_keys=[ + 'logit_scale', + 'visual.blocks.23.norm2.weight', + 'visual.blocks.23.norm2.bias', + 'visual.blocks.23.mlp.w1.weight', + 'visual.blocks.23.mlp.w1.bias', + 'visual.blocks.23.mlp.w2.weight', + 'visual.blocks.23.mlp.w2.bias', + 'visual.blocks.23.mlp.w3.weight', + 'visual.blocks.23.mlp.w3.bias', + 'visual.blocks.23.mlp.ffn_ln.weight', + 'visual.blocks.23.mlp.ffn_ln.bias'] + +custom_EVA_ViTB_16_freeze_keys=['logit_scale'] +custom_EVA_ViTL_14_freeze_keys=['logit_scale'] + +sanity_check_freeze_keys=['logit_scale'] +ViTB_EVA_16_qq_Distill_keys=['visual.blocks.11.attn.k_proj.weight', + ] + BASE_EVA_ViTB_16_freeze_keys +ViTL_EVA_14_qq_Distill_keys=['visual.blocks.23.attn.k_proj.weight', + ] + BASE_EVA_ViTL_14_freeze_keys +ViTB_EVA_16_kk_Distill_keys=['visual.blocks.11.attn.q_proj.weight','visual.blocks.11.attn.q_bias'] + BASE_EVA_ViTB_16_freeze_keys +ViTL_EVA_14_kk_Distill_keys=['visual.blocks.23.attn.q_proj.weight','visual.blocks.23.attn.q_bias'] + BASE_EVA_ViTL_14_freeze_keys + +siglip_384_Distill_Freeze_keys=['logit_scale', + 'logit_bias', + 'vision_model.head.probe', + ] + diff --git a/src/training/zero_shot.py b/src/training/zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..a6c5bbfb2f57342c44493824a2c3ad8878757e19 --- /dev/null +++ b/src/training/zero_shot.py @@ -0,0 +1,247 @@ +import logging +import os +import torch +import torch.nn.functional as F +from training.dist_utils import all_gather +from tqdm import tqdm +from .distributed import is_master +from open_clip import get_cast_dtype +from .precision import get_autocast +from training.mismatch_analysis import save_mismatch_reports + +def run(model, dataloader, args): + cls_embeddings = dataloader.dataset.embeddings + cls_embeddings = F.normalize(torch.from_numpy(cls_embeddings).float(), dim=-1) + cls_embeddings = cls_embeddings.to(args.device) + autocast = get_autocast(args.precision) + cast_dtype = get_cast_dtype(args.precision) + if cast_dtype is not None: + cls_embeddings = cls_embeddings.to(dtype=cast_dtype) + if 'distill' in args.mode: + if args.mode=="qq_vfm_distill": + inference_mode="qq" + elif args.mode=="kk_vfm_distill": + inference_mode="kk" + elif args.mode=="csa_vfm_distill": + inference_mode="csa" + elif args.mode=="vv_vfm_distill": + inference_mode="vv" + elif args.mode=="all_vfm_distill": + inference_mode="all" + elif args.mode=="sanity_check": + inference_mode="vanilla" + else: + inference_mode = args.mode + with torch.no_grad(): + correct_rois = [] + correct_maskpool = [] + correct_crops = [] + similarity_crops = [] + similarity_rois = [] + similarity_maskpool = [] + all_box_sizes = [] + all_is_thing = [] + all_cls_labels = [] + roi_top1_list = [] + crop_top1_list = [] + maskpool_top1_list = [] + for _, images, bboxes, image_crops, gt_masks, masked_image_crops in tqdm(dataloader, disable=not is_master(args)): + images = images.to(args.device) + bboxes = bboxes.to(args.device) + image_crops = image_crops.to(args.device) + masked_image_crops = masked_image_crops.to(args.device) + gt_masks = gt_masks.to(args.device) + if cast_dtype is not None: + images = images.to(dtype=cast_dtype) + bboxes = bboxes.to(dtype=cast_dtype) + image_crops = image_crops.to(dtype=cast_dtype) + masked_image_crops = masked_image_crops.to(dtype=cast_dtype) + gt_masks = gt_masks.to(dtype=cast_dtype) + image_crops_list = [] + gt_masks_list = [] + cls_labels = [] + rois = [] + box_sizes = [] + is_thing = [] + for bboxes_per_image, crops_per_image, gt_mask, masked_crops_per_image \ + in zip(bboxes, image_crops, gt_masks, masked_image_crops): + valid = bboxes_per_image[:, 5] > 0.5 + rois.append(bboxes_per_image[valid, :4]) + cls_labels.append(bboxes_per_image[valid, 4]) + image_crops_list.append(crops_per_image[valid]) + gt_masks_list.append(gt_mask[valid]) + box_sizes.append(bboxes_per_image[valid, 6]) + is_thing.append(bboxes_per_image[valid, 7]) + cls_labels = torch.cat(cls_labels, dim=0).to(torch.long) + if cls_labels.shape[0] == 0: + continue + image_crops = torch.cat(image_crops_list) + box_sizes = torch.cat(box_sizes, dim=0).float() + is_thing = torch.cat(is_thing, dim=0) + all_box_sizes.append(box_sizes) + all_is_thing.append(is_thing) + with autocast(): + # predict + module = model + roi_extractor = module.encode_pseudo_boxes + mask_pooler = module.encode_masks + + roi_features = roi_extractor(images, + rois, + normalize=True, + mode=inference_mode) + + maskpool_features = mask_pooler(images, + gt_masks_list, + normalize=True, + mode=inference_mode) + # New way to obtain crop features + if args.image_ave_pool: + feature_map = module.visual.encode_dense(image_crops, keep_shape=True) + crop_features = feature_map.mean(dim=(-2, -1)) + crop_features = F.normalize(crop_features, dim=-1) + else: + crop_features = module.encode_image(image_crops, normalize=True) + + if cast_dtype is not None: + roi_features = roi_features.to(dtype=cast_dtype) + crop_features = crop_features.to(dtype=cast_dtype) + maskpool_features = maskpool_features.to(dtype=cast_dtype) + roi_logits = roi_features @ cls_embeddings.T + crop_logits = crop_features @ cls_embeddings.T + maskpool_logits = maskpool_features @ cls_embeddings.T + + _, roi_top5_inds = roi_logits.topk(5) + _, crop_top5_inds = crop_logits.topk(5) + _, maskpool_top5_inds = maskpool_logits.topk(5) + if args.enable_mismatch_report: + roi_top1 = roi_logits.argmax(dim=1) + crop_top1 = crop_logits.argmax(dim=1) + maskpool_top1 = maskpool_logits.argmax(dim=1) + correct_rois.append(roi_top5_inds == cls_labels.view(-1, 1)) + correct_crops.append(crop_top5_inds == cls_labels.view(-1, 1)) + correct_maskpool.append(maskpool_top5_inds == cls_labels.view(-1, 1)) + if args.enable_mismatch_report: + roi_top1_list.append(roi_top1) + crop_top1_list.append(crop_top1) + maskpool_top1_list.append(maskpool_top1) + + similarity_rois.append(torch.gather(roi_logits, dim=1, index=cls_labels.view(-1, 1))[:, 0]) + similarity_crops.append(torch.gather(crop_logits, dim=1, index=cls_labels.view(-1, 1))[:, 0]) + similarity_maskpool.append(torch.gather(maskpool_logits, dim=1, index=cls_labels.view(-1, 1))[:, 0]) + all_cls_labels.append(cls_labels) + # TODO: gather correct matrix across gpus + correct_rois = torch.cat(correct_rois).float() + correct_crops = torch.cat(correct_crops).float() + correct_maskpool = torch.cat(correct_maskpool).float() + similarity_rois = torch.cat(similarity_rois).float() + similarity_crops = torch.cat(similarity_crops).float() + similarity_maskpool = torch.cat(similarity_maskpool).float() + all_box_sizes = torch.cat(all_box_sizes) + all_is_thing = torch.cat(all_is_thing) + all_cls_labels = torch.cat(all_cls_labels) + if args.enable_mismatch_report: + roi_top1_preds = torch.cat(roi_top1_list).long() + crop_top1_preds = torch.cat(crop_top1_list).long() + maskpool_top1_preds = torch.cat(maskpool_top1_list).long() + else: + roi_top1_preds = None + crop_top1_preds = None + maskpool_top1_preds = None + if args.distributed: + correct_rois = multi_gpu_sync(correct_rois) + correct_crops = multi_gpu_sync(correct_crops) + correct_maskpool = multi_gpu_sync(correct_maskpool) + all_box_sizes = multi_gpu_sync(all_box_sizes) + all_is_thing = multi_gpu_sync(all_is_thing) + similarity_rois = multi_gpu_sync(similarity_rois) + similarity_crops = multi_gpu_sync(similarity_crops) + similarity_maskpool = multi_gpu_sync(similarity_maskpool) + all_cls_labels = multi_gpu_sync(all_cls_labels) + if args.enable_mismatch_report: + roi_top1_preds = multi_gpu_sync(roi_top1_preds) + crop_top1_preds = multi_gpu_sync(crop_top1_preds) + maskpool_top1_preds = multi_gpu_sync(maskpool_top1_preds) + + return correct_rois, correct_crops, correct_maskpool, \ + similarity_rois, similarity_crops, similarity_maskpool, \ + all_box_sizes, all_is_thing, all_cls_labels, \ + roi_top1_preds, crop_top1_preds, maskpool_top1_preds + + +def multi_gpu_sync(x): + device = x.device + x_list = all_gather(x.cpu()) + x = torch.cat([res.to(device) for res in x_list]) + return x + + +def macc_with_is_thing(correct_matrix, is_thing, all_cls_labels, prefix): + def _macc(corrects, cls_labels): + min_id = cls_labels.min().item() + max_id = cls_labels.max().item() + cand_labels = list(range(min_id, max_id+1)) + + acc_per_cls = [] + + for lb in cand_labels: + corrects_per_cls = corrects[cls_labels == lb] + if corrects_per_cls.shape[0] == 0: + continue + acc_per_cls.append(corrects_per_cls.mean().half().item()) + + return sum(acc_per_cls) / len(acc_per_cls) + + results = {} + thing_correct_matrix = correct_matrix[is_thing > 0] + stuff_correct_matrix = correct_matrix[is_thing < 1] + + thing_cls_labels = all_cls_labels[is_thing > 0].long() + stuff_cls_labels = all_cls_labels[is_thing < 1].long() + + thing_top1_acc = _macc(thing_correct_matrix[:, 0], thing_cls_labels) + thing_top5_acc = _macc(thing_correct_matrix.sum(-1), thing_cls_labels) + + stuff_top1_acc = _macc(stuff_correct_matrix[:, 0], stuff_cls_labels) + stuff_top5_acc = _macc(stuff_correct_matrix.sum(-1), stuff_cls_labels) + + results[f'{prefix}.thing.macc1'] = thing_top1_acc + results[f'{prefix}.thing.macc5'] = thing_top5_acc + results[f'{prefix}.stuff.macc1'] = stuff_top1_acc + results[f'{prefix}.stuff.macc5'] = stuff_top5_acc + + return results + + +def zero_shot_eval(model, data, epoch, args): + if 'val' not in data: + return {} + if args.zeroshot_frequency == 0: + return {} + if (epoch % args.zeroshot_frequency) != 0 and epoch != args.epochs: + return {} + logging.info('Region classifier') + results = {} + correct_rois, correct_crops, correct_maskpool, \ + similarity_rois, similarity_crops, similarity_maskpool, \ + all_box_sizes, all_is_thing, all_cls_labels, \ + roi_top1_preds, crop_top1_preds, maskpool_top1_preds = run(model, data['val'].dataloader, args) + results.update(macc_with_is_thing(correct_rois, all_is_thing, all_cls_labels, 'rois')) + results.update(macc_with_is_thing(correct_crops, all_is_thing, all_cls_labels, 'crops')) + results.update(macc_with_is_thing(correct_maskpool, all_is_thing, all_cls_labels, 'maskpool')) + + if args.enable_mismatch_report: + # Save mismatch analysis for reviewer + try: + save_dir = os.path.join(args.logs, args.name) + dataset = data['val'].dataloader.dataset + preds_dict = { + "roi": roi_top1_preds, + "crop": crop_top1_preds, + "maskpool": maskpool_top1_preds, + } + save_mismatch_reports(preds_dict, all_cls_labels, dataset, save_dir, epoch, top_k=30) + except Exception as e: + logging.error("Failed to save mismatch reports: %s", e) + + return results diff --git a/tools/plot_radar.py b/tools/plot_radar.py new file mode 100644 index 0000000000000000000000000000000000000000..8a3ee1c996a8c5b5cc2b6ad3b89b00c60b259467 --- /dev/null +++ b/tools/plot_radar.py @@ -0,0 +1,163 @@ +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.patches import Patch + +# 数据 +labels = [ + 'ADE847', 'Context459', 'ADE150', 'Context59', 'VOC20', 'VOC21', + 'OV-COCO', 'OV-LVIS', 'Obj365', 'COCO', + 'Context60', 'COCO-Obj', 'CityScape', 'Context59', 'ADE', 'COCO-Stf' +] + + +declip = [40, 40, 40, 40, 40, 40, + 40, 40, 40, 40, + 40, 40, 40, 40, 40, 40] + +catseg = [31.37,35.52,35.01,37.98,39.16,38.07, + 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0] + +clipself = [0, 0, 0, 0, 0, 0, + 36.68, 33.6, 39.00,39.51, + 0, 0, 0, 0, 0, 0] + +clearclip = [0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 36.94, 36.26, 36.58, 36.63, 30.50, 37.78] + + +declip_value = [15.3, 21.4, 36.3, 60.6, 96.6, 81.3, + 48.3, 41.5, 20.0, 41.0, + 35.3, 36.4, 32.8, 39.2, 21.9, 25.3] + +catseg_value = [12.0, 19.0, 31.8, 57.5, 94.6, 77.3, + 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0] + +clipself_value = [0, 0, 0, 0, 0, 0, + 44.3, 34.9, 19.5,40.5, + 0, 0, 0, 0, 0, 0] + +clearclip_value = [0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 32.6, 33.0, 30.0, 35.9, 16.7, 23.9] + +# 设置不均匀的角度 +# 第一组占90度 +group1_angles = np.linspace(0, np.deg2rad(90), 6).tolist() # 0-90度 +gap1 = np.deg2rad(50) # 50度的间隔 + +# 第二组占60度 +group2_angles = np.linspace(np.deg2rad(90) + gap1, np.deg2rad(90) + gap1 + np.deg2rad(60), 4).tolist() # 140-200度 +gap2 = np.deg2rad(50) # 50度的间隔 + +# 第三组占90度 +group3_angles = np.linspace(np.deg2rad(90) + gap1 + np.deg2rad(60) + gap2, np.deg2rad(90) + gap1 + np.deg2rad(60) + gap2 + np.deg2rad(90), 6).tolist() # 250-340度 + +# 最后20度与第一组的间隔 +angles = group1_angles + group2_angles + group3_angles +angles += angles[:1] # 闭合曲线 + +# 数据补充,首尾相连 +declip = np.concatenate((declip, [declip[0]])) +catseg = np.concatenate((catseg, [catseg[0]])) +clipself = np.concatenate((clipself, [clipself[0]])) +clearclip = np.concatenate((clearclip, [clearclip[0]])) + + +# 创建图形,调整figsize +fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(polar=True)) + +# 设置雷达图的范围(r轴),最大值为 50 +ax.set_ylim(0, 40.5) + +# 控制径向环的数量和位置 +ax.set_yticks([10, 20, 30, 40]) # 手动设置径向环的值 + +# 绘制每组数据的区域,增加透明度 +ax.fill(angles, declip, color='#3dab5a', alpha=0.15, label='DECLIP', zorder=1) +ax.fill(angles, catseg, color='#ad4fa0', alpha=0.2, label='Previous SOTA CATSeg', zorder=1) +ax.fill(angles, clipself, color='#2b83bc', alpha=0.2, label='Previous SOTA CLIPSelf', zorder=1) +ax.fill(angles, clearclip, color='#db3939', alpha=0.2, label='Previous SOTA ClearCLIP', zorder=1) + +# 绘制边框线 +ax.plot(angles, declip, color='#52b36a', linewidth=1.5, linestyle='solid', zorder=2) +ax.plot(angles, catseg, color='#ad4fa0', linewidth=1.5, linestyle='solid', zorder=2) +ax.plot(angles, clipself, color='#2b83bc', linewidth=1.5, linestyle='solid', zorder=2) +ax.plot(angles, clearclip, color='#db3939', linewidth=1.5, linestyle='solid', zorder=2) + + +# 绘制数据点 +ax.scatter(angles, declip, facecolors='white', edgecolors='#3dab5a', s=35, zorder=3, linewidth=1.5, alpha=0.9) +ax.scatter(angles, catseg, facecolors='white', edgecolors='#ad4fa0', s=35, zorder=3, linewidth=1.5, alpha=0.9) +ax.scatter(angles, clipself, facecolors='white', edgecolors='#2b83bc', s=35, zorder=3, linewidth=1.5, alpha=0.9) +ax.scatter(angles, clearclip, facecolors='white', edgecolors='#db3939', s=35, zorder=3, linewidth=1.5, alpha=0.9) + + +# 设置标签 +ax.set_xticks(angles[:-1]) +ax.set_xticklabels([]) # 不显示标签文字 + +# 隐藏径向标签 +ax.set_yticklabels([]) + +# 调整参考线为实线,并降低宽度 +ax.spines['polar'].set_visible(False) +ax.grid(True, linestyle='-', linewidth=0.5) + +# 在每个数据点上标注其对应的值,分别处理不同组的数据位置 +for index,(angle, position,value) in enumerate(zip(angles, declip,declip_value)): + if value > 0: + if index<6: + ax.text(angle, position+1, f'{value:.1f}', color='#0b9444', fontsize=12, + ha='left', va='center') + elif index>=6 and index < 10: + ax.text(angle, position+0.5, f'{value:.1f}', color='#0b9444', fontsize=12, + ha='right', va='bottom') + else: + ax.text(angle, position+1.5, f'{value:.1f}', color='#0b9444', fontsize=12, + ha='left', va='top') + +for angle, position,value in zip(angles, catseg ,catseg_value): + if value > 0: + ax.text(angle, position-1, f'{value}', color='#92278f', fontsize=12, + ha='right', va='top') # catseg + +for angle, position,value in zip(angles, clipself,clipself_value): + if value > 0: + ax.text(angle, position-1, f'{value}', color='#213f9a', fontsize=12, + ha='left', va='top') # clipself + +for angle, position,value in zip(angles, clearclip,clearclip_value): + if value > 0: + ax.text(angle, position-1.0, f'{value}', color='#bf1e2d', fontsize=12, + ha='right', va='bottom') # clearclip + + +# 添加图例 +legend_elements = [ + Patch(facecolor='#3dab5a', edgecolor='#3dab5a', label='DeCLIP'), + Patch(facecolor='#ad4fa0', edgecolor='#ad4fa0', label='Previous SOTA CATSeg'), + Patch(facecolor='#2b83bc', edgecolor='#2b83bc', label='Previous SOTA CLIPSelf'), + Patch(facecolor='#db3939', edgecolor='#db3939', label='Previous SOTA ClearCLIP'), + +] +ax.legend(handles=legend_elements, + frameon=False, + fontsize='large', + loc='center', + bbox_to_anchor=(0.26, 0.99)) + +# 设置x轴标签背景颜色为不透明 +for label in ax.get_xticklabels(): + label.set_bbox(dict(facecolor='white', edgecolor='none', alpha=1.0)) + +# 调整图形布局,增加边距 +plt.tight_layout() + +# 保存图片 +plt.savefig('radar_chart.png', dpi=400, bbox_inches='tight', transparent=True) + +# 显示图像 +plt.close() \ No newline at end of file diff --git a/tools/plot_radar_release.py b/tools/plot_radar_release.py new file mode 100644 index 0000000000000000000000000000000000000000..9fa60b9a710423045f8a21a61a98c923ae317713 --- /dev/null +++ b/tools/plot_radar_release.py @@ -0,0 +1,155 @@ +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.patches import Patch + +# dataset +labels = [ + 'ADE847', 'Context459', 'ADE150', 'Context59', 'VOC20', 'VOC21', + 'OV-COCO', 'OV-LVIS', 'Obj365', 'COCO', + 'Context60', 'COCO-Obj', 'CityScape', 'Context59', 'ADE', 'COCO-Stf' +] + +declip = [40, 40, 40, 40, 40, 40, + 40, 40, 40, 40, + 40, 40, 40, 40, 40, 40] # scale value + +# Data has been desensitized here; you can fill in your own data. +declip_value = [20, 20, 20, 20, 20, 20, + 20, 20, 20, 20, + 20, 20, 20, 20, 20, 20] + +catseg_value = [10, 10, 10, 10, 10, 10, + 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0] + +clipself_value = [0, 0, 0, 0, 0, 0, + 10, 10, 10,10, + 0, 0, 0, 0, 0, 0] + +clearclip_value = [0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 10, 10, 10, 10, 10, 10] + +def calc_ratio(base, num, den): + return [base[i] * (num[i] / den[i]) if den[i] != 0 else 0 for i in range(len(base))] + +catseg = calc_ratio(declip, catseg_value, declip_value) +clipself = calc_ratio(declip, clipself_value, declip_value) +clearclip = calc_ratio(declip, clearclip_value, declip_value) + +# Set non-uniform angles +# The first group occupies 90 degrees +group1_angles = np.linspace(0, np.deg2rad(90), 6).tolist() # 0-90 degrees +gap1 = np.deg2rad(50) # 50 degree gap + +# The second group occupies 60 degrees +group2_angles = np.linspace(np.deg2rad(90) + gap1, np.deg2rad(90) + gap1 + np.deg2rad(60), 4).tolist() # 140-200 degrees +gap2 = np.deg2rad(50) # 50 degree gap + +# The third group occupies 90 degrees +group3_angles = np.linspace(np.deg2rad(90) + gap1 + np.deg2rad(60) + gap2, np.deg2rad(90) + gap1 + np.deg2rad(60) + gap2 + np.deg2rad(90), 6).tolist() # 250-340 degrees + +# The last 20 degrees gap with the first group +angles = group1_angles + group2_angles + group3_angles +angles += angles[:1] # Close the curve + +# Data supplement, connect the first and last +declip = np.concatenate((declip, [declip[0]])) +catseg = np.concatenate((catseg, [catseg[0]])) +clipself = np.concatenate((clipself, [clipself[0]])) +clearclip = np.concatenate((clearclip, [clearclip[0]])) + +# Create figure, adjust figsize +fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(polar=True)) + +# Set the range of the radar chart (r-axis), max value is 50 +ax.set_ylim(0, 40.5) + +# Control the number and position of radial rings +ax.set_yticks([10, 20, 30, 40]) # Manually set the values of the radial rings + +# Draw the area for each data group, increase transparency +ax.fill(angles, declip, color='#3dab5a', alpha=0.15, label='DECLIP', zorder=1) +ax.fill(angles, catseg, color='#ad4fa0', alpha=0.2, label='Previous SOTA CATSeg', zorder=1) +ax.fill(angles, clipself, color='#2b83bc', alpha=0.2, label='Previous SOTA CLIPSelf', zorder=1) +ax.fill(angles, clearclip, color='#db3939', alpha=0.2, label='Previous SOTA ClearCLIP', zorder=1) + +# Draw border lines +ax.plot(angles, declip, color='#52b36a', linewidth=1.5, linestyle='solid', zorder=2) +ax.plot(angles, catseg, color='#ad4fa0', linewidth=1.5, linestyle='solid', zorder=2) +ax.plot(angles, clipself, color='#2b83bc', linewidth=1.5, linestyle='solid', zorder=2) +ax.plot(angles, clearclip, color='#db3939', linewidth=1.5, linestyle='solid', zorder=2) + +# Draw data points +ax.scatter(angles, declip, facecolors='white', edgecolors='#3dab5a', s=35, zorder=3, linewidth=1.5, alpha=0.9) +ax.scatter(angles, catseg, facecolors='white', edgecolors='#ad4fa0', s=35, zorder=3, linewidth=1.5, alpha=0.9) +ax.scatter(angles, clipself, facecolors='white', edgecolors='#2b83bc', s=35, zorder=3, linewidth=1.5, alpha=0.9) +ax.scatter(angles, clearclip, facecolors='white', edgecolors='#db3939', s=35, zorder=3, linewidth=1.5, alpha=0.9) + +# Set labels +ax.set_xticks(angles[:-1]) +ax.set_xticklabels([]) # Do not show label text + +# Hide radial labels +ax.set_yticklabels([]) + +# Adjust reference lines to solid and reduce width +ax.spines['polar'].set_visible(False) +ax.grid(True, linestyle='-', linewidth=0.5) + +# Annotate each data point with its corresponding value, handle different group positions separately +for index, (angle, position, value) in enumerate(zip(angles, declip, declip_value)): + if value > 0: + if index < 6: + ax.text(angle, position + 1, f'{value:.1f}', color='#0b9444', fontsize=12, + ha='left', va='center') + elif index >= 6 and index < 10: + ax.text(angle, position + 0.5, f'{value:.1f}', color='#0b9444', fontsize=12, + ha='right', va='bottom') + else: + ax.text(angle, position + 1.5, f'{value:.1f}', color='#0b9444', fontsize=12, + ha='left', va='top') + +for angle, position, value in zip(angles, catseg, catseg_value): + if value > 0: + ax.text(angle, position - 1, f'{value}', color='#92278f', fontsize=12, + ha='right', va='top') # catseg + +for angle, position, value in zip(angles, clipself, clipself_value): + if value > 0: + ax.text(angle, position - 1, f'{value}', color='#213f9a', fontsize=12, + ha='left', va='top') # clipself + +for angle, position, value in zip(angles, clearclip, clearclip_value): + if value > 0: + ax.text(angle, position - 1.0, f'{value}', color='#bf1e2d', fontsize=12, + ha='right', va='bottom') # clearclip + +# Add legend +legend_elements = [ + Patch(facecolor='#3dab5a', edgecolor='#3dab5a', label='DeCLIP'), + Patch(facecolor='#ad4fa0', edgecolor='#ad4fa0', label='Previous SOTA CATSeg'), + Patch(facecolor='#2b83bc', edgecolor='#2b83bc', label='Previous SOTA CLIPSelf'), + Patch(facecolor='#db3939', edgecolor='#db3939', label='Previous SOTA ClearCLIP'), + +] +ax.legend(handles=legend_elements, + frameon=False, + fontsize='large', + loc='center', + bbox_to_anchor=(0.26, 0.99)) + +# Set x-axis label background to opaque +for label in ax.get_xticklabels(): + label.set_bbox(dict(facecolor='white', edgecolor='none', alpha=1.0)) + +# Adjust figure layout, increase margin +plt.tight_layout() + +# Save image +plt.savefig('radar_chart.png', dpi=400, bbox_inches='tight', transparent=True) + +# Show image +plt.close() + + diff --git a/tools/plot_radar_yulin_iclr.py b/tools/plot_radar_yulin_iclr.py new file mode 100644 index 0000000000000000000000000000000000000000..e0e161fc334a68c3dd02b446bd20de7dc1034d52 --- /dev/null +++ b/tools/plot_radar_yulin_iclr.py @@ -0,0 +1,153 @@ +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.patches import Patch + +# ========================= +# 数据与预处理 +# ========================= +labels = [ + 'MATH-500', 'AIME24', 'AIME25', 'GSM8K', 'AMC23', 'Olympiad', + 'MATH-500', 'AIME24', 'AIME25', 'GSM8K', 'AMC23', 'Olympiad', + 'MATH-500', 'AIME24', 'AIME25', 'GSM8K', 'AMC23', 'Olympiad', + 'MATH-500', 'AIME24', 'AIME25', 'GSM8K', 'AMC23', 'Olympiad', +] + +ReBalance_value = [83.0, 36.7, 30.0, 78.3, 80.0, 43.9, + 92.6, 56.7, 40.0, 91.6, 95.0, 57.0, + 94.0, 73.3, 56.7, 96.3, 100.0, 66.3, + 95.2, 70.0, 63.3, 96.8, 95.0, 68.6] + +CoD_value = [80.2, 33.3, 13.3, 69.5, 62.5, 35.2, + 90.0, 46.7, 36.7, 84.5, 85.0, 47.5, + 93.8, 66.7, 53.3, 95.6, 95.0, 62.2, + 93.8, 63.3, 46.7, 96.2, 92.5, 67.7] + +SEAL_value = [78.6, 23.3, 26.7, 76.4, 53.8, 32.7, + 90.6, 43.3, 26.7, 88.4, 77.5, 53.9, + 93.4, 63.3, 50.0, 95.7, 90.0, 62.3, + 92.6, 63.3, 56.7, 96.2, 95.0, 67.5] + +def normalize_values(target, base_values, method_values): + normalized = [] + for base, value in zip(base_values, method_values): + if base == 0 or value == 0: + normalized.append(0) + else: + normalized.append((value / base) * target) + return normalized + +def enhance_contrast(values, power=2.0, target_max=40): + arr = np.array(values, dtype=float) + arr_scaled = arr ** power + return (arr_scaled / arr_scaled.max()) * target_max + +# 数据准备 +ReBalance_target = 40 +ReBalance = normalize_values(ReBalance_target, ReBalance_value, ReBalance_value) +CoD = normalize_values(ReBalance_target, ReBalance_value, CoD_value) +SEAL = normalize_values(ReBalance_target, ReBalance_value, SEAL_value) + +ReBalance = enhance_contrast(ReBalance, power=2.0, target_max=ReBalance_target) +CoD = enhance_contrast(CoD, power=2.0, target_max=ReBalance_target) +SEAL = enhance_contrast(SEAL, power=2.0, target_max=ReBalance_target) + +# 设置角度 +num_groups = 4 +tasks_per_group = 6 +gap_deg = 18 +group_arc = (360 - num_groups * gap_deg) / num_groups +point_arc = group_arc / tasks_per_group + +angles = [] +current_angle = 0 +for g in range(num_groups): + for t in range(tasks_per_group): + angles.append(np.deg2rad(current_angle)) + current_angle += point_arc + current_angle += gap_deg + +# 首尾相连 +angles += [angles[0]] +ReBalance = np.concatenate((ReBalance, [ReBalance[0]])) +CoD = np.concatenate((CoD, [CoD[0]])) +SEAL = np.concatenate((SEAL, [SEAL[0]])) + +# ========================= +# 绘图 (CVPR/NIPS 风格) +# ========================= +colors = { + "ReBalance": "#00E676", # 荧光绿 + "CoD": "#FFB300", # 亮橙黄 + "SEAL": "#00B0FF", # 亮青蓝 +} + +markers = {"ReBalance": "o", "CoD": "s", "SEAL": "D"} +linestyles = {"ReBalance": "-", "CoD": "--", "SEAL": "-."} + +fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(polar=True)) + +# 额外绘制半径为40的圆圈 +theta = np.linspace(0, 2*np.pi, 500) +ax.plot(theta, np.full_like(theta, 40), + color="black", linewidth=1.2, linestyle="-", zorder=0.5) + +ax.set_ylim(0, 44) + +# 背景与网格 +ax.set_facecolor("white") +ax.grid(True, color="gray", linestyle="--", linewidth=0.6, alpha=0.6) +ax.spines["polar"].set_visible(False) +ax.set_yticks([]) # 移除半径方向的刻度 +ax.set_yticklabels([]) # 移除半径方向的刻度标签 + +# 绘制每个方法 +def plot_method(values, angles, label): + # 淡淡背景填充 + if label=="ReBalance": + ax.fill(angles, values, color=colors[label], alpha=0.05, zorder=1) + else: + ax.fill(angles, values, color=colors[label], alpha=0.1, zorder=1) + # 折线 + ax.plot(angles, values, color=colors[label], + linewidth=2.2, linestyle=linestyles[label], + label=label, zorder=2) + # 数据点 + ax.scatter(angles, values, + facecolors="white", edgecolors=colors[label], + linewidths=1.5, marker=markers[label], + s=55, zorder=3) + +plot_method(ReBalance, angles, "ReBalance") +plot_method(CoD, angles, "CoD") +plot_method(SEAL, angles, "SEAL") + +# ========================= +# 在中心画一个灰色实心圆点(带黑色边框) +# ========================= +ax.scatter(0, 0, + c="gray", edgecolors="black", + s=120, zorder=5, linewidths=1.0) + +# 标签 +ax.set_xticks(angles[:-1]) +ax.set_xticklabels(labels, fontsize=12, color="black") +for label in ax.get_xticklabels(): + label.set_horizontalalignment("center") + +# 图例 +legend_elements = [ + Patch(facecolor=colors["ReBalance"], edgecolor=colors["ReBalance"], label="ReBalance (Ours)"), + Patch(facecolor=colors["CoD"], edgecolor=colors["CoD"], label="CoD"), + Patch(facecolor=colors["SEAL"], edgecolor=colors["SEAL"], label="SEAL"), +] +ax.legend( + handles=legend_elements, + frameon=False, + fontsize=14, + loc="upper center", + bbox_to_anchor=(0.78, 1.12), +) + +plt.tight_layout() +plt.savefig("radar_chart_cvpr_with_center.png", dpi=300, transparent=True) +plt.close() \ No newline at end of file diff --git a/tools/plot_radar_yulin_iclrv2.py b/tools/plot_radar_yulin_iclrv2.py new file mode 100644 index 0000000000000000000000000000000000000000..139c1c00534d67cd0000631ee794a3967418c583 --- /dev/null +++ b/tools/plot_radar_yulin_iclrv2.py @@ -0,0 +1,176 @@ +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.patches import Patch + +# ========================= +# 数据与预处理 +# ========================= +labels = [ + 'MATH-500', 'AIME24', 'AIME25', 'GSM8K', 'AMC23', 'Olympiad', + 'MATH-500', 'AIME24', 'AIME25', 'GSM8K', 'AMC23', 'Olympiad', + 'MATH-500', 'AIME24', 'AIME25', 'GSM8K', 'AMC23', 'Olympiad', + 'MATH-500', 'AIME24', 'AIME25', 'GSM8K', 'AMC23', 'Olympiad', +] +# ! 原始版本 +# baseline=[79.6, 23.3, 16.7, 76.0, 55.0, 32.6, +# 89.8, 40.0, 26.7, 89.2, 75.0, 46.9, +# 93.8, 66.7, 56.7, 95.1, 95.0, 60.6, +# 94.8, 66.7, 46.7, 96.3, 87.5, 66.7] + +# ReBalance_value = [83.0, 36.7, 30.0, 78.3, 80.0, 43.9, +# 92.6, 56.7, 40.0, 91.6, 95.0, 57.0, +# 94.0, 73.3, 56.7, 96.3, 100.0, 66.3, +# 95.2, 70.0, 63.3, 96.8, 95.0, 68.6] + +# SEAL_value = [78.6, 23.3, 26.7, 76.4, 53.8, 32.7, +# 90.6, 43.3, 26.7, 88.4, 77.5, 53.9, +# 93.4, 63.3, 50.0, 95.7, 90.0, 62.3, +# 92.6, 63.3, 56.7, 96.2, 95.0, 67.5] +# ! 为了对称,第一组和第四组调换位置 +# 94.8, 66.7, 46.7, 96.3, 87.5, 66.7 +baseline=[94.8, 66.7, 46.7, 96.3, 87.5, 66.7, + 89.8, 40.0, 26.7, 89.2, 75.0, 46.9, + 93.8, 66.7, 56.7, 95.1, 95.0, 60.6, + 79.6, 23.3, 16.7, 76.0, 55.0, 32.6] + +# 95.2, 70.0, 63.3, 96.8, 95.0, 68.6 +ReBalance_value = [95.2, 70.0, 63.3, 96.8, 95.0, 68.6, + 92.6, 56.7, 40.0, 91.6, 95.0, 57.0, + 94.0, 73.3, 56.7, 96.3, 100.0, 66.3, + 83.0, 36.7, 30.0, 78.3, 80.0, 43.9] + +# 92.6, 63.3, 56.7, 96.2, 95.0, 67.5 +SEAL_value = [92.6, 63.3, 56.7, 96.2, 95.0, 67.5, + 90.6, 43.3, 26.7, 88.4, 77.5, 53.9, + 93.4, 63.3, 50.0, 95.7, 90.0, 62.3, + 78.6, 23.3, 26.7, 76.4, 53.8, 32.7] + +# ========================= +# 归一化和增强对比度 +# ========================= +def normalize_values(target, base_values, method_values): + normalized = [] + for base, value in zip(base_values, method_values): + if base == 0 or value == 0: + normalized.append(0) + else: + normalized.append((value / base) * target) + return normalized + +def enhance_contrast(values, power=2.0, target_max=40): + arr = np.array(values, dtype=float) + arr_scaled = arr ** power + return (arr_scaled / arr_scaled.max()) * target_max + +target = 40 +Baseline = normalize_values(target, ReBalance_value, baseline) +ReBalance = normalize_values(target, ReBalance_value, ReBalance_value) +SEAL = normalize_values(target, ReBalance_value, SEAL_value) + +Baseline = enhance_contrast(Baseline, power=2.0, target_max=target) +ReBalance = enhance_contrast(ReBalance, power=2.0, target_max=target) +SEAL = enhance_contrast(SEAL, power=2.0, target_max=target) + +# ========================= +# 设置角度 +# ========================= +num_groups = 4 +tasks_per_group = 6 +gap_deg = 16 +group_arc = (360 - num_groups * gap_deg) / num_groups +point_arc = group_arc / tasks_per_group + +angles = [] +current_angle = 0 +for g in range(num_groups): + for t in range(tasks_per_group): + angles.append(np.deg2rad(current_angle)) + current_angle += point_arc + current_angle += gap_deg + +# 首尾相连 +angles += [angles[0]] +Baseline = np.concatenate((Baseline, [Baseline[0]])) +ReBalance = np.concatenate((ReBalance, [ReBalance[0]])) +SEAL = np.concatenate((SEAL, [SEAL[0]])) + +# ========================= +# 绘图 (CVPR/NIPS 风格) +# ========================= +colors = { + "Baseline": "#00B0FF", # 亮青蓝 + "ReBalance": "#00E676", # 荧光绿 + "SEAL": "#FFB300", # 亮橙黄 +} + +markers = { + "Baseline": "s", + "ReBalance": "o", + "SEAL": "D", +} + +linestyles = { + "Baseline": "--", + "ReBalance": "-", + "SEAL": "-.", +} + +fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(polar=True)) + +# 半径=40的参考圆 +theta = np.linspace(0, 2*np.pi, 500) +ax.plot(theta, np.full_like(theta, 40), + color="black", linewidth=1.2, linestyle="-", zorder=0.5) + +ax.set_ylim(0, 44) + +# 背景与网格 +ax.set_facecolor("white") +ax.grid(True, color="gray", linestyle="--", linewidth=0.6, alpha=0.6) +ax.spines["polar"].set_visible(False) +ax.set_yticks([]) +ax.set_yticklabels([]) + +# 通用绘图函数 +def plot_method(values, angles, label): + ax.fill(angles, values, color=colors[label], alpha=0.1, zorder=1) + ax.plot(angles, values, color=colors[label], + linewidth=2.2, linestyle=linestyles[label], + label=label, zorder=2) + ax.scatter(angles, values, + facecolors="white", edgecolors=colors[label], + linewidths=1.5, marker=markers[label], + s=55, zorder=3) + +plot_method(Baseline, angles, "Baseline") +plot_method(ReBalance, angles, "ReBalance") +plot_method(SEAL, angles, "SEAL") + +# 中心灰点 +ax.scatter(0, 0, c="gray", edgecolors="black", + s=120, zorder=5, linewidths=1.0) + +# 标签 +ax.set_xticks(angles[:-1]) +ax.set_xticklabels(labels, fontsize=12, color="black") +for label in ax.get_xticklabels(): + label.set_horizontalalignment("center") + +# 图例 +legend_elements = [ + Patch(facecolor=colors["Baseline"], edgecolor=colors["Baseline"], label="Baseline"), + Patch(facecolor=colors["SEAL"], edgecolor=colors["SEAL"], label="SEAL"), + Patch(facecolor=colors["ReBalance"], edgecolor=colors["ReBalance"], label="ReBalance (Ours)"), + +] +ax.legend( + handles=legend_elements, + frameon=False, + fontsize=14, + loc="upper center", + bbox_to_anchor=(0.68, 1.21), +) + +plt.tight_layout() +plt.savefig("radar_chart_cvpr_with_baseline.png", dpi=300, transparent=True) +plt.close() \ No newline at end of file diff --git a/tools/plot_radarv2.1.py b/tools/plot_radarv2.1.py new file mode 100644 index 0000000000000000000000000000000000000000..dbcdcccbbb8652fce2182be4ab805cc491ad8770 --- /dev/null +++ b/tools/plot_radarv2.1.py @@ -0,0 +1,125 @@ +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.patches import Patch + +# 数据 +labels = [ + 'ADE847', 'PC459', 'ADE150', 'PC59', 'VOC20', 'VOC21', + 'OV-COCO', 'OV-LVIS', 'Obj365', 'COCO', + 'PC60', 'COCO-Obj', 'City', 'PC59', 'ADE', 'COCO-Stf' +] + +declip_value = [15.3, 21.4, 36.3, 60.6, 96.6, 81.3, + 49.5, 41.5, 20.0, 41.5, + 37.9, 38.7, 35.7, 41.6, 23.1, 26.8] + +catseg_value = [12.0, 19.0, 31.8, 57.5, 94.6, 77.3, + 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0] + +clipself_value = [0, 0, 0, 0, 0, 0, + 44.3, 34.9, 19.5, 40.5, + 0, 0, 0, 0, 0, 0] + +clearclip_value = [0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 32.6, 33.0, 30.0, 35.9, 16.7, 23.9] + +declip_target = 40 + +# 自动计算归一化值 +def normalize_values(target, base_values, method_values): + normalized = [] + for base, value in zip(base_values, method_values): + if base == 0 or value == 0: + normalized.append(0) + else: + normalized.append((value / base) * target) + return normalized + +declip = normalize_values(declip_target, declip_value, declip_value) +catseg = normalize_values(declip_target, declip_value, catseg_value) +clipself = normalize_values(declip_target, declip_value, clipself_value) +clearclip = normalize_values(declip_target, declip_value, clearclip_value) + +# 设置不均匀的角度 +group1_angles = np.linspace(0, np.deg2rad(90), 6).tolist() +gap1 = np.deg2rad(50) +group2_angles = np.linspace(np.deg2rad(90) + gap1, np.deg2rad(90) + gap1 + np.deg2rad(60), 4).tolist() +gap2 = np.deg2rad(50) +group3_angles = np.linspace(np.deg2rad(90) + gap1 + np.deg2rad(60) + gap2, np.deg2rad(90) + gap1 + np.deg2rad(60) + gap2 + np.deg2rad(90), 6).tolist() +angles = group1_angles + group2_angles + group3_angles +angles += angles[:1] + +# 数据补充,首尾相连 +declip = np.concatenate((declip, [declip[0]])) +catseg = np.concatenate((catseg, [catseg[0]])) +clipself = np.concatenate((clipself, [clipself[0]])) +clearclip = np.concatenate((clearclip, [clearclip[0]])) + +fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(polar=True)) +ax.set_ylim(0, 41.5) + +# 添加径向为40的圆 +r_circle = 41.5 +theta = np.linspace(0, 2 * np.pi, 500) +ax.plot(theta, [r_circle] * len(theta), color='black', linestyle='-', linewidth=1.2, alpha=1.0, zorder=0) + +ax.set_yticks([10,20,30,40]) + +# === 只替换下方 DeCLIP 相关的颜色 === +declip_color = '#8c6d53' +catseg_color = '#91acdd' +clipself_color = '#79b453' +clearclip_color = '#c55a11' + +ax.fill(angles, declip, color=declip_color, alpha=0.15, label='DECLIP', zorder=1) +ax.fill(angles, catseg, color=catseg_color, alpha=0.2, label='Previous SOTA CATSeg', zorder=1) +ax.fill(angles, clipself, color=clipself_color, alpha=0.2, label='Previous SOTA CLIPSelf', zorder=1) +ax.fill(angles, clearclip, color=clearclip_color, alpha=0.2, label='Previous SOTA ClearCLIP', zorder=1) + +ax.plot(angles, declip, color=declip_color, linewidth=1.5, linestyle='solid', zorder=2) +ax.plot(angles, catseg, color=catseg_color, linewidth=1.5, linestyle='dashed', zorder=2) +ax.plot(angles, clipself, color=clipself_color, linewidth=1.5, linestyle='dashed', zorder=2) +ax.plot(angles, clearclip, color=clearclip_color, linewidth=1.5, linestyle='dashed', zorder=2) + +ax.scatter(angles, declip, facecolors=declip_color, s=35, zorder=3, alpha=0.9) +ax.scatter(angles, catseg, facecolors=catseg_color, s=35, zorder=3, alpha=0.9) +ax.scatter(angles, clipself, facecolors=clipself_color, s=35, zorder=3, alpha=0.9) +ax.scatter(angles, clearclip, facecolors=clearclip_color, s=35, zorder=3, alpha=0.9) + +# 设置标签 +ax.set_xticks(angles[:-1]) +ax.set_xticklabels(labels, fontsize=12, ha='center', va='top', color='black') + +# for index,(angle, position,value) in enumerate(zip(angles, declip,declip_value)): +# if value > 0: +# if index<6: +# ax.text(angle, position+1, f'{value:.1f}', color=declip_color, fontsize=12, +# ha='left', va='center') +# elif index>=6 and index < 10: +# ax.text(angle, position+0.5, f'{value:.1f}', color=declip_color, fontsize=12, +# ha='right', va='bottom') +# else: +# ax.text(angle, position+1.5, f'{value:.1f}', color=declip_color, fontsize=12, +# ha='left', va='top') + +# 图例 +legend_elements = [ + Patch(facecolor=declip_color, edgecolor=declip_color, label='DeCLIP (Ours)'), + Patch(facecolor=catseg_color, edgecolor=catseg_color, label='CATSeg (OVSS SOTA)'), + Patch(facecolor=clipself_color, edgecolor=clipself_color, label='CLIPSelf (OVD SOTA)'), + Patch(facecolor=clearclip_color, edgecolor=clearclip_color, label='ClearCLIP (ZSSS SOTA)'), +] +ax.legend( + handles=legend_elements, + frameon=True, + fontsize='large', + loc='center', + bbox_to_anchor=(0.26, 0.99), + framealpha=0.5 +) +ax.set_yticklabels([]) +plt.tight_layout() +plt.savefig('radar_chart.png', dpi=200, bbox_inches='tight', transparent=True) +plt.close() \ No newline at end of file diff --git a/tools/plot_radarv2.2.1.py b/tools/plot_radarv2.2.1.py new file mode 100644 index 0000000000000000000000000000000000000000..bc6142dd033dc0556f68765b0ea696dcac232b15 --- /dev/null +++ b/tools/plot_radarv2.2.1.py @@ -0,0 +1,127 @@ +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.patches import Patch +import matplotlib.patheffects as PathEffects + +# 数据 +labels = [ + 'ADE847', 'PC459', 'ADE150', 'PC59', 'VOC20', 'VOC21', + 'OV-COCO', 'OV-LVIS', 'Obj365', 'COCO', + 'PC60', 'COCO-Obj', 'City', 'PC59', 'ADE', 'COCO-Stf' +] + +declip_value = [15.3, 21.4, 36.3, 60.6, 96.6, 81.3, + 49.5, 41.5, 20.0, 41.5, + 37.9, 38.7, 35.7, 41.6, 23.1, 26.8] + +catseg_value = [12.0, 19.0, 31.8, 57.5, 94.6, 77.3, + 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0] + +clipself_value = [0, 0, 0, 0, 0, 0, + 44.3, 34.9, 19.5, 40.5, + 0, 0, 0, 0, 0, 0] + +clearclip_value = [0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 32.6, 33.0, 30.0, 35.9, 16.7, 23.9] + +declip_target = 40 + +# 自动计算归一化值 +def normalize_values(target, base_values, method_values): + normalized = [] + for base, value in zip(base_values, method_values): + if base == 0 or value == 0: + normalized.append(0) + else: + normalized.append((value / base) * target) + return normalized + +# 颜色设置 +declip_color = '#6c4f3d' # 调深原来的颜色 +catseg_color = '#89a7e5' +clipself_color = '#74b451' +clearclip_color = '#c55a17' + +declip = normalize_values(declip_target, declip_value, declip_value) +catseg = normalize_values(declip_target, declip_value, catseg_value) +print(catseg) +exit() +clipself = normalize_values(declip_target, declip_value, clipself_value) +clearclip = normalize_values(declip_target, declip_value, clearclip_value) + +# 均匀分布角度 +num_labels = len(labels) +angles = np.linspace(0, 2 * np.pi, num_labels, endpoint=False).tolist() +angles += angles[:1] # 首尾相连 + +# 数据补充,首尾相连 +declip = np.concatenate((declip, [declip[0]])) +catseg = np.concatenate((catseg, [catseg[0]])) +clipself = np.concatenate((clipself, [clipself[0]])) +clearclip = np.concatenate((clearclip, [clearclip[0]])) + +fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(polar=True)) +ax.set_ylim(0, 42) + +# 主线与对比线条 +ax.plot(angles, declip, color=declip_color, linewidth=3.2, linestyle='solid', zorder=3, + path_effects=[PathEffects.withStroke(linewidth=6, foreground="white")]) +ax.plot(angles, catseg, color=catseg_color, linewidth=2.6, linestyle='dashed', zorder=2) # 粗细调为2.6 +ax.plot(angles, clipself, color=clipself_color, linewidth=2.6, linestyle='dashed', zorder=2) # 粗细调为2.6 +ax.plot(angles, clearclip, color=clearclip_color, linewidth=2.6, linestyle='dashed', zorder=2) # 粗细调为2.6 + +ax.fill(angles, catseg, color=catseg_color, alpha=0.05, zorder=1) +ax.fill(angles, clipself, color=clipself_color, alpha=0.05, zorder=1) +ax.fill(angles, clearclip, color=clearclip_color, alpha=0.05, zorder=1) +# 散点 +ax.scatter(angles, declip, facecolors=declip_color, s=65, zorder=4, alpha=0.95, linewidth=1, edgecolors='white') +ax.scatter(angles, catseg, facecolors=catseg_color, s=55, zorder=3, alpha=0.9, linewidth=0.6, edgecolors='white') +ax.scatter(angles, clipself, facecolors=clipself_color, s=55, zorder=3, alpha=0.9, linewidth=0.6, edgecolors='white') +ax.scatter(angles, clearclip, facecolors=clearclip_color, s=55, zorder=3, alpha=0.9, linewidth=0.6, edgecolors='white') + +# 极径线、主圆线 +theta = np.linspace(0, 2 * np.pi, 500) +ax.plot(theta, [42] * len(theta), color='black', linestyle='-', linewidth=1.5, alpha=0.7, zorder=0) +ax.set_yticks([10, 20, 30, 40]) +ax.set_yticklabels([]) # 不显示极径标签 + +# DeCLIP关键点标数值(只标非0点,白边防遮挡) +for idx, (angle, val, raw_val) in enumerate(zip(angles, declip, declip_value + [declip_value[0]])): + if raw_val > 0: + if (idx == 0 or idx == len(declip) - 1) or idx == 8: + txt = ax.text(angle + 0.05, val, f'{raw_val:.1f}', color=declip_color, fontsize=12.5, fontweight='bold', + ha='center', va='center', zorder=5) + txt.set_path_effects([PathEffects.withStroke(linewidth=3, foreground="white")]) + else: + txt = ax.text(angle, val, f'{raw_val:.1f}', color=declip_color, fontsize=12.5, fontweight='bold', + ha='center', va='center', zorder=5) + txt.set_path_effects([PathEffects.withStroke(linewidth=3, foreground="white")]) + +# 只显示自定义标签,不显示角度刻度 +ax.set_xticks(angles[:-1]) # 只设置你的label角度 +ax.set_xticklabels(labels, fontsize=13, fontweight='bold', + path_effects=[PathEffects.withStroke(linewidth=3, foreground="white")]) + +# 图例 +legend_elements = [ + Patch(facecolor=declip_color, edgecolor='white', label='DeCLIP (Ours)'), + Patch(facecolor=catseg_color, edgecolor='white', label='CATSeg (OVSS SOTA)'), + Patch(facecolor=clipself_color, edgecolor='white', label='CLIPSelf (OVD SOTA)'), + Patch(facecolor=clearclip_color, edgecolor='white', label='ClearCLIP (ZSSS SOTA)'), +] +ax.legend( + handles=legend_elements, + frameon=True, + fontsize=12, + loc='upper center', + bbox_to_anchor=(0.5, 1.16), + ncol=2, + framealpha=0.1, + borderaxespad=0.4, + handleheight=1.3 +) + +plt.tight_layout() +plt.savefig('radar_chart.png', dpi=300, bbox_inches='tight', transparent=True) \ No newline at end of file diff --git a/tools/plot_radarv2.2.py b/tools/plot_radarv2.2.py new file mode 100644 index 0000000000000000000000000000000000000000..0a8f56224c88dd53ec621c65d50419fa3a250319 --- /dev/null +++ b/tools/plot_radarv2.2.py @@ -0,0 +1,133 @@ +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.patches import Patch, Wedge +import matplotlib.patheffects as PathEffects + +# 数据 +labels = [ + 'ADE847', 'PC459', 'ADE150', 'PC59', 'VOC20', 'VOC21', + 'OV-COCO', 'OV-LVIS', 'Obj365', 'COCO', + 'PC60', 'COCO-Obj', 'City', 'PC59', 'ADE', 'COCO-Stf' +] + +declip_value = [15.3, 21.4, 36.3, 60.6, 96.6, 81.3, + 49.5, 41.5, 20.0, 41.5, + 37.9, 38.7, 35.7, 41.6, 23.1, 26.8] + +catseg_value = [12.0, 19.0, 31.8, 57.5, 94.6, 77.3, + 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0] + +clipself_value = [0, 0, 0, 0, 0, 0, + 44.3, 34.9, 19.5, 40.5, + 0, 0, 0, 0, 0, 0] + +clearclip_value = [0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 32.6, 33.0, 30.0, 35.9, 16.7, 23.9] + +declip_target = 40 + +# 自动计算归一化值 +def normalize_values(target, base_values, method_values): + normalized = [] + for base, value in zip(base_values, method_values): + if base == 0 or value == 0: + normalized.append(0) + else: + normalized.append((value / base) * target) + return normalized + +# 颜色设置 +declip_color = '#8c6d53' +catseg_color = '#91acdd' +clipself_color = '#79b453' +clearclip_color = '#c55a11' + +declip = normalize_values(declip_target, declip_value, declip_value) +catseg = normalize_values(declip_target, declip_value, catseg_value) +clipself = normalize_values(declip_target, declip_value, clipself_value) +clearclip = normalize_values(declip_target, declip_value, clearclip_value) + +# 均匀分布角度 +num_labels = len(labels) +angles = np.linspace(0, 2 * np.pi, num_labels, endpoint=False).tolist() +angles += angles[:1] # 首尾相连 + +# 数据补充,首尾相连 +declip = np.concatenate((declip, [declip[0]])) +catseg = np.concatenate((catseg, [catseg[0]])) +clipself = np.concatenate((clipself, [clipself[0]])) +clearclip = np.concatenate((clearclip, [clearclip[0]])) + +fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(polar=True)) +ax.set_ylim(0, 42) + + +# 2. 主线与对比线条 +ax.plot(angles, declip, color=declip_color, linewidth=3.2, linestyle='solid', zorder=3, + path_effects=[PathEffects.withStroke(linewidth=6, foreground="white")]) +ax.plot(angles, catseg, color=catseg_color, linewidth=2.0, linestyle='dashed', zorder=2) +ax.plot(angles, clipself, color=clipself_color, linewidth=2.0, linestyle='dashed', zorder=2) +ax.plot(angles, clearclip, color=clearclip_color, linewidth=2.0, linestyle='dashed', zorder=2) + +# 3. 区域填充 +ax.fill(angles, declip, color=declip_color, alpha=0.1, zorder=1) +ax.fill(angles, catseg, color=catseg_color, alpha=0.1, zorder=1) +ax.fill(angles, clipself, color=clipself_color, alpha=0.1, zorder=1) +ax.fill(angles, clearclip, color=clearclip_color, alpha=0.1, zorder=1) + +# 4. 散点 +ax.scatter(angles, declip, facecolors=declip_color, s=65, zorder=4, alpha=0.95, linewidth=1, edgecolors='white') +ax.scatter(angles, catseg, facecolors=catseg_color, s=50, zorder=3, alpha=0.85, linewidth=0.5, edgecolors='white') +ax.scatter(angles, clipself, facecolors=clipself_color, s=50, zorder=3, alpha=0.85, linewidth=0.5, edgecolors='white') +ax.scatter(angles, clearclip, facecolors=clearclip_color, s=50, zorder=3, alpha=0.85, linewidth=0.5, edgecolors='white') + +# 8. 极径线、主圆线 +theta = np.linspace(0, 2 * np.pi, 500) +ax.plot(theta, [42] * len(theta), color='black', linestyle='-', linewidth=1.5, alpha=0.7, zorder=0) +ax.set_yticks([10, 20, 30, 40]) +ax.set_yticklabels([]) # 不显示极径标签 + + +# 6. DeCLIP关键点标数值(只标非0点,白边防遮挡) +for idx, (angle, val, raw_val) in enumerate(zip(angles, declip, declip_value + [declip_value[0]])): + if raw_val > 0: + if (idx==0 or idx==len(declip)-1) or idx==8: + txt = ax.text(angle+0.05, val, f'{raw_val:.1f}', color=declip_color, fontsize=12.5, fontweight='bold', + ha='center', va='center', zorder=5) + txt.set_path_effects([PathEffects.withStroke(linewidth=3, foreground="white")]) + else: + txt = ax.text(angle, val, f'{raw_val:.1f}', color=declip_color, fontsize=12.5, fontweight='bold', + ha='center', va='center', zorder=5) + txt.set_path_effects([PathEffects.withStroke(linewidth=3, foreground="white")]) + +# 5. 只显示自定义标签,不显示角度刻度 +ax.set_xticks(angles[:-1]) # 只设置你的label角度 + +ax.set_xticklabels(labels, fontsize=13, fontweight='bold', + path_effects=[PathEffects.withStroke(linewidth=3, foreground="white")]) + + + + +# 9. 图例 +legend_elements = [ + Patch(facecolor=declip_color, edgecolor='white', label='DeCLIP (Ours)'), + Patch(facecolor=catseg_color, edgecolor='white', label='CATSeg (OVSS SOTA)'), + Patch(facecolor=clipself_color, edgecolor='white', label='CLIPSelf (OVD SOTA)'), + Patch(facecolor=clearclip_color, edgecolor='white', label='ClearCLIP (ZSSS SOTA)'), +] +ax.legend( + handles=legend_elements, + frameon=True, + fontsize=12, + loc='upper center', + bbox_to_anchor=(0.5, 1.16), + ncol=2, + framealpha=0.1, + borderaxespad=0.4, + handleheight=1.3 +) +plt.tight_layout() +plt.savefig('radar_chart.png', dpi=300, bbox_inches='tight', transparent=True) \ No newline at end of file diff --git a/tools/plot_radarv2.3.py b/tools/plot_radarv2.3.py new file mode 100644 index 0000000000000000000000000000000000000000..7951b54da1a8f049e3c9b8387fd7c00982ad64a5 --- /dev/null +++ b/tools/plot_radarv2.3.py @@ -0,0 +1,124 @@ +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.patches import Patch, Wedge +import matplotlib.patheffects as PathEffects + +# 数据 +labels = [ + 'SN200_ap', 'SN200_head', 'SN200_tail', + 'LV-VIS_val', 'LV-VIS_test', 'OVIS', 'YTVIS19','YTVIS21','BURST', + 'REAL_AR', 'REAL_mIoU', 'TOYL_AR', 'TOYL_mIoU' +] + +declip_value = [26.4, 28.2, 27.7, + 37.7,30.9,29.3,54.8,49.1,10.1, + 37.6, 72.2, 32.6, 68.7] + +Open3DIS_value = [23.7, 21.2, 21.8, + 0, 0, 0, 0,0,0, + 0, 0, 0, 0,] + +CLIP_VIS_value = [0, 0, 0, + 32.2,25.3,18.5,42.1,37.9,8.3, + 0, 0, 0, 0] + +oryon_value = [0, 0, 0, + 0, 0, 0, 0, 0, 0, + 32.2,66.5,30.3,68.1] + +declip_target = 40 +# 自动计算归一化值 +def normalize_values(target, base_values, method_values): + normalized = [] + for base, value in zip(base_values, method_values): + if base == 0 or value == 0: + normalized.append(0) + else: + normalized.append((value / base) * target) + return normalized + +# 颜色设置 +declip_color = '#6c4f3d' # 调深原来的颜色 +Open3DIS_color = '#b04fc0' # 洋红紫 +CLIP_VIS_color = '#ffc145' # 琥珀黄 +oryon_color = '#3de1b5' # 青柠绿 + +declip = normalize_values(declip_target, declip_value, declip_value) +Open3DIS = normalize_values(declip_target, declip_value, Open3DIS_value) +CLIP_VIS = normalize_values(declip_target, declip_value, CLIP_VIS_value) +oryon = normalize_values(declip_target, declip_value, oryon_value) + +# 均匀分布角度 +num_labels = len(labels) +angles = np.linspace(0, 2 * np.pi, num_labels, endpoint=False).tolist() +angles += angles[:1] # 首尾相连 + +# 数据补充,首尾相连 +declip = np.concatenate((declip, [declip[0]])) +Open3DIS = np.concatenate((Open3DIS, [Open3DIS[0]])) +CLIP_VIS = np.concatenate((CLIP_VIS, [CLIP_VIS[0]])) +oryon = np.concatenate((oryon, [oryon[0]])) + +fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(polar=True)) +ax.set_ylim(0, 43) + +# 主线与对比线条 +ax.plot(angles, declip, color=declip_color, linewidth=3.2, linestyle='solid', zorder=3, + path_effects=[PathEffects.withStroke(linewidth=6, foreground="white")]) +ax.plot(angles, Open3DIS, color=Open3DIS_color, linewidth=2.6, linestyle='dashed', zorder=2) # 粗细调为2.6 +ax.plot(angles, CLIP_VIS, color=CLIP_VIS_color, linewidth=2.6, linestyle='dashed', zorder=2) # 粗细调为2.6 +ax.plot(angles, oryon, color=oryon_color, linewidth=2.6, linestyle='dashed', zorder=2) # 粗细调为2.6 + +ax.fill(angles, Open3DIS, color=Open3DIS_color, alpha=0.05, zorder=1) +ax.fill(angles, CLIP_VIS, color=CLIP_VIS_color, alpha=0.05, zorder=1) +ax.fill(angles, oryon, color=oryon_color, alpha=0.05, zorder=1) +# 散点 +ax.scatter(angles, declip, facecolors=declip_color, s=65, zorder=4, alpha=0.95, linewidth=1, edgecolors='white') +ax.scatter(angles, Open3DIS, facecolors=Open3DIS_color, s=55, zorder=3, alpha=0.9, linewidth=0.6, edgecolors='white') +ax.scatter(angles, CLIP_VIS, facecolors=CLIP_VIS_color, s=55, zorder=3, alpha=0.9, linewidth=0.6, edgecolors='white') +ax.scatter(angles, oryon, facecolors=oryon_color, s=55, zorder=3, alpha=0.9, linewidth=0.6, edgecolors='white') + +# 极径线、主圆线 +theta = np.linspace(0, 2 * np.pi, 500) +ax.plot(theta, [43] * len(theta), color='black', linestyle='-', linewidth=1.5, alpha=0.7, zorder=0) +ax.set_yticks([10, 20, 30, 40]) +ax.set_yticklabels([]) # 不显示极径标签 + +# DeCLIP关键点标数值(只标非0点,白边防遮挡) +for idx, (angle, val, raw_val) in enumerate(zip(angles, declip, declip_value + [declip_value[0]])): + if raw_val > 0: + if idx == 0 or idx == len(declip) - 1: + txt = ax.text(angle+0.1, val, f'{raw_val:.1f}', color=declip_color, fontsize=12.5, fontweight='bold', + ha='center', va='center', zorder=5) + txt.set_path_effects([PathEffects.withStroke(linewidth=3, foreground="white")]) + else: + txt = ax.text(angle, val, f'{raw_val:.1f}', color=declip_color, fontsize=12.5, fontweight='bold', + ha='center', va='center', zorder=5) + txt.set_path_effects([PathEffects.withStroke(linewidth=3, foreground="white")]) + +# 只显示自定义标签,不显示角度刻度 +ax.set_xticks(angles[:-1]) # 只设置你的label角度 +ax.set_xticklabels(labels, fontsize=13, fontweight='bold',rotation=30, + path_effects=[PathEffects.withStroke(linewidth=3, foreground="white")]) + +# 图例 +legend_elements = [ + Patch(facecolor=declip_color, edgecolor='white', label='DeCLIP (Ours)'), + Patch(facecolor=Open3DIS_color, edgecolor='white', label='Open3DIS (OV3DIS SOTA)'), + Patch(facecolor=CLIP_VIS_color, edgecolor='white', label='CLIP-VIS (OVVIS SOTA)'), + Patch(facecolor=oryon_color, edgecolor='white', label='Oryon (OV6DP SOTA)')] + +ax.legend( + handles=legend_elements, + frameon=True, + fontsize=12, + loc='upper center', + bbox_to_anchor=(0.5, 1.16), + ncol=2, + framealpha=0.1, + borderaxespad=0.4, + handleheight=1.3 +) + +plt.tight_layout() +plt.savefig('radar_chart_extend.png', dpi=300, bbox_inches='tight', transparent=True) \ No newline at end of file diff --git a/tools/plot_radarv2.py b/tools/plot_radarv2.py new file mode 100644 index 0000000000000000000000000000000000000000..f6414e3679d4700c7a5626212a695bb5e3e3c274 --- /dev/null +++ b/tools/plot_radarv2.py @@ -0,0 +1,132 @@ +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.patches import Patch + +# 数据 +labels = [ + 'ADE847', 'PC459', 'ADE150', 'PC59', 'VOC20', 'VOC21', + 'OV-COCO', 'OV-LVIS', 'Obj365', 'COCO', + 'PC60', 'COCO-Obj', 'City', 'PC59', 'ADE', 'COCO-Stf' +] + +declip_value = [15.3, 21.4, 36.3, 60.6, 96.6, 81.3, + 49.5, 41.5, 20.0, 41.5, + 37.9, 38.7, 35.7, 41.6, 23.1, 26.8] + +catseg_value = [12.0, 19.0, 31.8, 57.5, 94.6, 77.3, + 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0] + +clipself_value = [0, 0, 0, 0, 0, 0, + 44.3, 34.9, 19.5, 40.5, + 0, 0, 0, 0, 0, 0] + +clearclip_value = [0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 32.6, 33.0, 30.0, 35.9, 16.7, 23.9] + +declip_target = 40 + +# 自动计算归一化值 +def normalize_values(target, base_values, method_values): + """根据 base_values 和 method_values 的比例计算归一化值""" + normalized = [] + for base, value in zip(base_values, method_values): + if base == 0 or value == 0: # 如果值为 0,不进行计算,直接保留 0 + normalized.append(0) + else: + normalized.append((value / base) * target) + return normalized + +declip = normalize_values(declip_target, declip_value, declip_value) +catseg = normalize_values(declip_target, declip_value, catseg_value) +clipself = normalize_values(declip_target, declip_value, clipself_value) +clearclip = normalize_values(declip_target, declip_value, clearclip_value) + +# 设置不均匀的角度 +group1_angles = np.linspace(0, np.deg2rad(90), 6).tolist() # 0-90度 +gap1 = np.deg2rad(50) # 50度的间隔 +group2_angles = np.linspace(np.deg2rad(90) + gap1, np.deg2rad(90) + gap1 + np.deg2rad(60), 4).tolist() # 140-200度 +gap2 = np.deg2rad(50) # 50度的间隔 +group3_angles = np.linspace(np.deg2rad(90) + gap1 + np.deg2rad(60) + gap2, np.deg2rad(90) + gap1 + np.deg2rad(60) + gap2 + np.deg2rad(90), 6).tolist() # 250-340度 +angles = group1_angles + group2_angles + group3_angles +angles += angles[:1] # 闭合曲线 + +# 数据补充,首尾相连 +declip = np.concatenate((declip, [declip[0]])) +catseg = np.concatenate((catseg, [catseg[0]])) +clipself = np.concatenate((clipself, [clipself[0]])) +clearclip = np.concatenate((clearclip, [clearclip[0]])) + +# 创建图形,调整figsize +fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(polar=True)) +ax.set_ylim(0, 41.5) + +# 添加径向为40的圆 +r_circle = 41.5 +theta = np.linspace(0, 2 * np.pi, 500) +ax.plot(theta, [r_circle] * len(theta), color='black', linestyle='-', linewidth=1.2, alpha=1.0, zorder=0) + +# 移除径向线的刻度 +ax.set_yticks([10,20,30,40]) + +# 绘制每组数据的区域,增加透明度 +ax.fill(angles, declip, color='#3dab5a', alpha=0.15, label='DECLIP', zorder=1) +ax.fill(angles, catseg, color='#ad4fa0', alpha=0.2, label='Previous SOTA CATSeg', zorder=1) +ax.fill(angles, clipself, color='#2b83bc', alpha=0.2, label='Previous SOTA CLIPSelf', zorder=1) +ax.fill(angles, clearclip, color='#C65F10', alpha=0.2, label='Previous SOTA ClearCLIP', zorder=1) + +# 绘制边框线 +ax.plot(angles, declip, color='#52b36a', linewidth=1.5, linestyle='solid', zorder=2) +ax.plot(angles, catseg, color='#ad4fa0', linewidth=1.5, linestyle='solid', zorder=2) +ax.plot(angles, clipself, color='#2b83bc', linewidth=1.5, linestyle='solid', zorder=2) +ax.plot(angles, clearclip, color='#C65F10', linewidth=1.5, linestyle='solid', zorder=2) + +# 绘制数据点 +ax.scatter(angles, declip, facecolors='#3dab5a', s=35, zorder=3, alpha=0.9) +ax.scatter(angles, catseg, facecolors='#ad4fa0', s=35, zorder=3, alpha=0.9) +ax.scatter(angles, clipself, facecolors='#2b83bc', s=35, zorder=3, alpha=0.9) +ax.scatter(angles, clearclip, facecolors='#C65F10', s=35, zorder=3, alpha=0.9) + +# 设置标签 +ax.set_xticks(angles[:-1]) +ax.set_xticklabels(labels, fontsize=12, ha='center', va='top', color='black') # 标签颜色透明 + + +# 在每个数据点上标注其对应的值(移除 declip 的数值标注部分) +for angle, position, value in zip(angles, catseg, catseg_value): + if value > 0: + ax.text(angle, position - 1, f'{value}', color='#92278f', fontsize=12, ha='right', va='top') + +for angle, position, value in zip(angles, clipself, clipself_value): + if value > 0: + ax.text(angle, position - 1, f'{value}', color='#213f9a', fontsize=12, ha='left', va='top') + +for angle, position, value in zip(angles, clearclip, clearclip_value): + if value > 0: + ax.text(angle, position - 1.0, f'{value}', color='#C65F10', fontsize=12, ha='right', va='bottom') + +# 添加图例 +legend_elements = [ + Patch(facecolor='#3dab5a', edgecolor='#3dab5a', label='DeCLIP (Ours)'), + Patch(facecolor='#ad4fa0', edgecolor='#ad4fa0', label='CATSeg (OVSS SOTA)'), + Patch(facecolor='#2b83bc', edgecolor='#2b83bc', label='CLIPSelf (OVD SOTA)'), + Patch(facecolor='#C65F10', edgecolor='#C65F10', label='ClearCLIP (ZSSS SOTA)'), +] +ax.legend( + handles=legend_elements, + frameon=True, + fontsize='large', + loc='center', + bbox_to_anchor=(0.26, 0.99), + framealpha=0.5 +) +ax.set_yticklabels([]) +# 调整图形布局 +plt.tight_layout() + +# 保存图片 +plt.savefig('radar_chart.png', dpi=200, bbox_inches='tight', transparent=True) + +# 显示图像 +plt.close() \ No newline at end of file diff --git a/tools/precompute_knns.py b/tools/precompute_knns.py new file mode 100644 index 0000000000000000000000000000000000000000..5730e4ede96d75645d657431f905d585ee2de0e6 --- /dev/null +++ b/tools/precompute_knns.py @@ -0,0 +1,81 @@ +import torch +import torch.nn.functional as F +import numpy as np +from tqdm import tqdm +from training.distributed import is_master +from training.precision import get_autocast +import os +import json +import faiss +@torch.no_grad() + + +def save_features_to_disk(features, image_ids, save_dir, batch_idx): + """ + 将特征保存到磁盘 + """ + os.makedirs(save_dir, exist_ok=True) + feature_file = os.path.join(save_dir, f"features_batch_{batch_idx}.npy") + ids_file = os.path.join(save_dir, f"ids_batch_{batch_idx}.npy") + np.save(feature_file, features) + np.save(ids_file, image_ids) + print(f"Batch {batch_idx}: Saved features to {feature_file} and {ids_file}") + +def run_knns(model, data, args): + """ + 分批提取特征并保存到磁盘,每 save_interval 次迭代保存一次 + """ + model.eval() + autocast = get_autocast(args.precision) + save_dir="coco_knn_results" + batch_idx = 0 # 用于标记保存的 batch 文件编号 + save_interval=300 + # 临时存储特征和ID的列表 + temp_feats = [] + temp_ids = [] + + with torch.no_grad(): + for iter_idx, (_, _, _, proxy_image, image_ids) in enumerate( + tqdm(data['train'].dataloader, disable=not is_master(args)) + ): + proxy_image = proxy_image.to(args.device) + with autocast(): + # 提取 VFM 特征 + if args.use_vfm == "sam": + vfm_feats = model.image_encoder(proxy_image) + elif args.use_vfm == "dino": + feat = model.get_intermediate_layers(proxy_image)[0] + nb_im = feat.shape[0] + patch_size = model.patch_embed.patch_size + I, J = proxy_image[0].shape[-2] // patch_size, proxy_image[0].shape[-2] // patch_size + vfm_feats = feat[:, 1:, :].reshape(nb_im, I, J, -1).permute(0, 3, 1, 2) + else: # dinov2 + vfm_feats = model.get_intermediate_layers(proxy_image, reshape=True)[0] + + # 展平特征 + bs, c, h, w = vfm_feats.shape + flattened_feats = vfm_feats.view(bs, c, -1).mean(dim=-1).cpu().numpy() # 平均池化到 (bs, channel) + temp_feats.append(flattened_feats) + temp_ids.extend(image_ids) # 存储图像ID + + # 每 save_interval 次迭代保存一次特征到磁盘 + if (iter_idx + 1) % save_interval == 0: + temp_feats = np.concatenate(temp_feats, axis=0) # 拼接当前缓存的所有特征 + temp_ids = np.array(temp_ids) + save_features_to_disk(temp_feats, temp_ids, save_dir, batch_idx) + batch_idx += 1 + + # 清空临时缓存 + temp_feats = [] + temp_ids = [] + + # 保存剩余的特征(如果有未满 save_interval 的特征) + if temp_feats: + temp_feats = np.concatenate(temp_feats, axis=0) + temp_ids = np.array(temp_ids) + save_features_to_disk(temp_feats, temp_ids, save_dir, batch_idx) + print(f"Final Batch {batch_idx}: Saved remaining features.") + + +if __name__=="__main__": + pass \ No newline at end of file diff --git a/tools/segmentation.py b/tools/segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..038cd8728301c8d47b01f36b60a260d024436644 --- /dev/null +++ b/tools/segmentation.py @@ -0,0 +1,124 @@ +import logging +import math +import torch +import torch.nn.functional as F +import numpy as np +from tqdm import tqdm +from open_clip import create_model +from open_clip.model import get_cast_dtype +from training.distributed import is_master +from training.precision import get_autocast +from training.zero_shot import multi_gpu_sync +import os +import torch.nn as nn +import matplotlib.pyplot as plt +def run_seg(model, data, args): + dataloader=data['val'].dataloader + model.eval() + autocast = get_autocast(args.precision) + cast_dtype = get_cast_dtype(args.precision) + cls_embeddings = dataloader.dataset.embeddings + cls_embeddings = F.normalize(torch.from_numpy(cls_embeddings).float(), dim=-1) + cls_embeddings = cls_embeddings.to(args.device) + if cast_dtype is not None: + cls_embeddings = cls_embeddings.to(dtype=cast_dtype) + unnorm = UnNormalize([0.48145466, 0.4578275, 0.40821073], [0.26862954, 0.26130258, 0.27577711]) + baseline_model = create_model( + args.model, # same ! + args.pretrained, + device=args.device, + precision=args.precision, + output_dict=True, + cache_dir="ckpt_path" # cache dir of pre-trained models + ).to(args.device) + with torch.no_grad(): + # _, images, bboxes, image_crops, gt_masks, masked_image_crops, proxy_imgs + # for images, gt_masks, image_names, image_shapes in tqdm(dataloader, disable=not is_master(args)): + logging.info('Region classifier') + for image_names, images, _, _, gt_masks, _, _ in tqdm(data['val'].dataloader, disable=not is_master(args)): + images = images.to(args.device) + if cast_dtype is not None: + images = images.to(dtype=cast_dtype) + tar_h,tar_w=images.shape[-2]//4,images.shape[-1]//4 + with autocast(): + # predict + if args.distributed and not args.horovod: + module = model.module + baseline_module=baseline_model.module + else: + module = model + baseline_module=baseline_model + feature_maps = module.encode_dense(images, + normalize=True, + keep_shape=False, + mode="ss", + ex_feats=None) + + baseline_feature_maps = baseline_module.encode_dense(images, + normalize=True, + keep_shape=False, + mode="only_v", + ex_feats=None) + + bs, N, C = feature_maps.shape + h, w = int(math.sqrt(N)), int(math.sqrt(N)) + + # 计算 logits + logits = (feature_maps @ cls_embeddings.T) * 40 + baseline_logits = (baseline_feature_maps @ cls_embeddings.T) * 40 + + # 变换形状 + logits = logits.permute(0, 2, 1).reshape(bs, -1, h, w) + baseline_logits = baseline_logits.permute(0, 2, 1).reshape(bs, -1, h, w) + + # 插值 + seg_logits = nn.functional.interpolate(logits, size=(tar_h, tar_w), mode='bilinear') + baseline_seg_logits = nn.functional.interpolate(baseline_logits, size=(tar_h, tar_w), mode='bilinear') + + batch_size = seg_logits.shape[0] + + for i in range(batch_size): + # 处理主模型的预测 + seg_logits_i = seg_logits[i] * model.logit_scale + seg_logits_i = seg_logits_i.softmax(0) # n_queries * w * h + seg_pred = seg_logits_i.argmax(0, keepdim=True) + seg_pred = seg_pred.data.cpu().numpy().squeeze(0) + + # 处理基线模型的预测 + baseline_seg_logits_i = baseline_seg_logits[i] * model.logit_scale + baseline_seg_logits_i = baseline_seg_logits_i.softmax(0) # n_queries * w * h + baseline_seg_pred = baseline_seg_logits_i.argmax(0, keepdim=True) + baseline_seg_pred = baseline_seg_pred.data.cpu().numpy().squeeze(0) + + # 可视化 + fig, ax = plt.subplots(1, 3, figsize=(18, 6)) + ax[0].imshow(unnorm(images)[0].permute(1, 2, 0).detach().cpu()) + ax[0].axis('off') + ax[0].set_title("Original Image", fontsize=14) + ax[1].imshow(seg_pred, cmap='turbo') + ax[1].axis('off') + ax[1].set_title("ss distill Result", fontsize=14) + ax[2].imshow(baseline_seg_pred, cmap='turbo') + ax[2].axis('off') + ax[2].set_title("only_v Result", fontsize=14) + plt.tight_layout() + log_base_path = os.path.join(args.logs, args.name) + plt.savefig(f"{log_base_path}/{image_names[i].split('.')[0]}.jpg", bbox_inches='tight') + plt.close() + +class UnNormalize(object): + def __init__(self, mean, std): + self.mean = mean + self.std = std + + def __call__(self, image): + image2 = torch.clone(image) + if len(image2.shape) == 4: + # batched + image2 = image2.permute(1, 0, 2, 3).contiguous() + for t, m, s in zip(image2, self.mean, self.std): + t.mul_(s).add_(m) + return image2.permute(1, 0, 2, 3).contiguous() + +if __name__=="__main__": + pass \ No newline at end of file diff --git a/tools/vis_featmap_corr.py b/tools/vis_featmap_corr.py new file mode 100644 index 0000000000000000000000000000000000000000..bcf771112a636ee7fdc4b33aa8c3e737dfe7b50d --- /dev/null +++ b/tools/vis_featmap_corr.py @@ -0,0 +1,137 @@ +import math +import sys +import os +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) +import torch +import torchvision.transforms as T +from PIL import Image +from featup.util import UnNormalize,remove_axes +from featup.plotting import plot_feats, plot_lang_heatmaps +from open_clip.factory import create_model, get_tokenizer +from open_clip.transform import det_image_transform, image_transform +import matplotlib.pyplot as plt +import torch.nn.functional as F +from src.segment_anything import sam_model_registry +from torchvision import transforms + +device= torch.device("cuda:7" if torch.cuda.is_available() else "cpu") +image_path = "CECloud_code/test_images/animal (25).jpg" +output_path="test_result" +model_name="EVA02-CLIP-B-16" +# model_name="EVA02-CLIP-L-14-336" +ckpt="checkpoints/EVA02_CLIP_B_psz16_s8B.pt" +token_choosen = 1505 + +@torch.no_grad() +def vis_feat_corr(vfm="sam"): + image_size=1024 if model_name=="EVA02-CLIP-B-16" else 896 + vlm = create_model( + model_name, + "eva", + precision="fp32", + device=device, + jit=False, + force_quick_gelu=False, + force_custom_text=False, + force_patch_dropout=None, + force_image_size=None, + pretrained_image=False, + pretrained_hf=True, + cache_dir=ckpt, + output_dict=None).to(device) + image_mean = getattr(vlm.visual, 'image_mean', None) + image_std = getattr(vlm.visual, 'image_std', None) + unnorm = UnNormalize(image_mean, image_std) + vlm_transform=det_image_transform( + image_size, + is_train=False, + mean=image_mean, + std=image_std, + fill_color=0) + if vfm=="dino": + resolution = 512 + vfm = torch.hub.load('facebookresearch/dino:main', 'dino_vitb8').half().to(device) + elif vfm=="dinov2": + resolution = 896 + vfm = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitb14_reg').half().to(device) + else: + resolution = 1024 + vfm = sam_model_registry["vit_b"](checkpoint="/mnt/SSD8T/home/wjj/code/ProxyCLIP/sam_ckpts/sam_vit_b_01ec64.pth").half().to(device) + vfm_transform=det_image_transform( + resolution, + is_train=False, + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225], + fill_color=0) + raw_img=Image.open(image_path) + vlm_image = vlm_transform(raw_img).unsqueeze(0).to(device,non_blocking=True) + vfm_image= vfm_transform(raw_img).unsqueeze(0).to(device,non_blocking=True).half() + if vfm=="sam": + vfm_feats=vfm.image_encoder(vfm_image).flatten(2, 3) + elif vfm=="dino": + feat = vfm.get_intermediate_layers(vfm_image)[0] + nb_im = feat.shape[0] + patch_size = vfm.patch_embed.patch_size + I, J = vfm_image[0].shape[-2] // patch_size, vfm_image[0].shape[-2] // patch_size + vfm_feats = feat[:, 1:, :].reshape(nb_im, I, J, -1).permute(0, 3, 1, 2).flatten(2, 3) + else: # dinov2 + vfm_feats = vfm.get_intermediate_layers(vfm_image, reshape=True)[0].flatten(2, 3) + normed_vfm_feats= F.normalize(vfm_feats, dim=1) + vfm_similarity = torch.einsum("b c m, b c n -> b m n", normed_vfm_feats, normed_vfm_feats) + vlm_feats, q_feats = vlm.encode_dense(vlm_image, + normalize=True, + keep_shape=True, + mode="ss_vfm_distill", + ex_feats=None) + vfm_feats = vfm_feats.reshape(vlm_feats.shape[0],-1,vlm_feats.shape[2],vlm_feats.shape[3]) + vfm_feats_vis=vfm_feats.squeeze(0).mean(dim=0).detach().cpu().numpy() + N, _ = q_feats.shape[1:] + H, W = int(math.sqrt(N)),int(math.sqrt(N)) + q_feats = q_feats.transpose(0, 1).contiguous().view(N, vlm_image.shape[0], -1).transpose(0, 1) + q_feats = F.normalize(q_feats, dim=-1).transpose(-2,-1) + vlm_similarity=torch.einsum("b c m, b c n -> b m n", q_feats, q_feats) + vlm_similarity = vlm_similarity.squeeze(0)[token_choosen, :].view(H,W).cpu().detach().numpy() + vfm_similarity = vfm_similarity.squeeze(0)[token_choosen, :].view(H,W).cpu().detach().numpy() + # 计算原图中token的坐标 + token_index = token_choosen # 选择的token索引 + H, W = 64, 64 # 特征图的大小 + original_size = 1024 # 原图大小 + downsample_factor = original_size // H # 下采样因子 + + # 计算token在特征图中的行列坐标 + row = token_index // H + col = token_index % H + + # 计算token在原图中的坐标 + original_row = row * downsample_factor + original_col = col * downsample_factor + + fig, ax = plt.subplots(1, 4, figsize=(24, 6)) + ax[0].imshow(unnorm(vlm_image)[0].permute(1,2,0).detach().cpu()) + ax[0].axis('off') + ax[0].set_title('Raw Image') + # 在原图上绘制标记 + ax[0].scatter(original_col, original_row, color='red', s=100, edgecolor='yellow', marker='o') # 标记位置 + + + im1 = ax[1].imshow(vfm_similarity, cmap='jet', interpolation='nearest') + ax[1].axis('off') + ax[1].set_title('vfm similarities') + plt.colorbar(im1, ax=ax[1], fraction=0.046, pad=0.04) + + im2 = ax[2].imshow(vlm_similarity, cmap='jet', interpolation='nearest') + ax[2].axis('off') + ax[2].set_title('vlm similarities') + plt.colorbar(im2, ax=ax[2], fraction=0.046, pad=0.04) + + ax[3].imshow(vfm_feats_vis, cmap='jet', interpolation='nearest') + ax[3].axis('off') + ax[3].set_title('vfm_feats') + + plt.savefig(os.path.join(output_path,"token_sim.jpg"), dpi=300, bbox_inches='tight') + plt.close() + +if __name__=="__main__": + if not os.path.exists(output_path): + os.mkdir(output_path) + vis_feat_corr(vfm="dinov2") diff --git a/tools/vis_k_means.py b/tools/vis_k_means.py new file mode 100644 index 0000000000000000000000000000000000000000..86ef765f8bd7468f6413a049ce8c4fe25da33477 --- /dev/null +++ b/tools/vis_k_means.py @@ -0,0 +1,75 @@ +from PIL import Image +from featup.util import UnNormalize +import matplotlib.pyplot as plt +from open_clip.transform import det_image_transform +import numpy as np +import torch +import os +from tqdm import tqdm +model_name="EVA02-CLIP-B-16" +# model_name="EVA02-CLIP-L-14-336" +ckpt="logs/exp34/checkpoints/epoch_6.pt" +mean=[0.48145466, 0.4578275, 0.40821073] +std=[0.26862954, 0.26130258, 0.27577711] +val_image_root="/mnt/SSD8T/home/wjj/dataset/standard_coco/val2017" +k_means_root="logs/test" +device="cuda:0" +output_path="test_result" +def visualize_segmentation(image, mask, output_path, alpha=0.5): + """ + 可视化图像的分割掩码,并保存结果到指定位置。 + 参数: + - image: 原图,形状为 (C, H, W) + - mask: 上采样后的掩码,形状为 (1, 1, H, W) + - output_path: 输出图像的保存路径 + - alpha: 掩码的透明度 + """ + # 将 mask 转换为 numpy 数组 + mask_np = mask.squeeze().cpu().numpy() # 形状为 (H, W) + unnorm = UnNormalize(mean, std) + image = unnorm(image.unsqueeze(0))[0] + + # 定义颜色映射 + def create_color_map(num_classes): + colors = plt.get_cmap('jet', num_classes) + return (colors(np.arange(num_classes))[:, :3] * 255).astype(np.uint8) + + num_classes = int(mask_np.max() + 1) # 类别数 + color_map = create_color_map(num_classes) + + # 创建一个 RGB 图像来存储掩码的颜色 + mask_color = np.zeros((mask_np.shape[0], mask_np.shape[1], 3), dtype=np.uint8) + + for class_id in range(num_classes): + mask_color[mask_np == class_id] = color_map[class_id] + + # 调整透明度 + image_np = image.permute(1, 2, 0).cpu().numpy() # 转换为 (H, W, C) + image_np = (image_np * 255).astype(np.uint8) # 假设原图在 [0, 1] 范围内 + + # 创建一个透明图像 + overlay = (mask_color * alpha + image_np * (1 - alpha)).astype(np.uint8) + + # 可视化并保存结果 + plt.figure(figsize=(10, 10)) + plt.imshow(overlay) + plt.axis('off') + plt.title('Image with Segmentation Overlay') + plt.savefig(output_path, bbox_inches='tight', pad_inches=0) + plt.close() + +if __name__=="__main__": + preprocess_val_det = det_image_transform( + 256, + is_train=False, + mean=mean, + std=std) + files=os.listdir(k_means_root) + k_means_files=[i for i in files if i.endswith(".npy")] + for file in tqdm(k_means_files, desc="Processing files"): + image_name=file.replace(".npy",".jpg") + _image=Image.open(os.path.join(val_image_root,image_name)) + _image=preprocess_val_det(_image).to(device) + _mask = torch.from_numpy(np.load(os.path.join(k_means_root,file))).unsqueeze(0).unsqueeze(0).to(torch.float32).to(device) + _mask=torch.nn.functional.interpolate(_mask,size=(_image.shape[-2], _image.shape[-1])) + visualize_segmentation(_image,_mask,os.path.join(output_path,image_name))