xiaomoguhzz commited on
Commit
c50dde6
·
verified ·
1 Parent(s): 8314ec8

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. experimental/SimFeatUp/featup/featurizers/maskclip/simple_tokenizer.py +138 -0
  2. experimental/SimFeatUp/featup/featurizers/maskclip/xclip.py +247 -0
  3. experimental/SimFeatUp/featup/featurizers/maskclip/xmodel.py +535 -0
  4. experimental/SimFeatUp/featup/featurizers/modules/__init__.py +0 -0
  5. experimental/SimFeatUp/featup/featurizers/modules/layers.py +309 -0
  6. experimental/SimFeatUp/featup/featurizers/modules/resnet.py +339 -0
  7. experimental/SimFeatUp/featup/featurizers/modules/vgg.py +366 -0
  8. experimental/build_env/declip/download_eva_clip.sh +284 -0
  9. experimental/build_env/declip/install_mmcv_mmdet.sh +61 -0
  10. experimental/build_env/declip/requirements_verified.txt +24 -0
  11. experimental/build_env/fix_mmcv_pytorch26.sh +111 -0
  12. experimental/build_env/fix_mmcv_pytorch26_v2.sh +144 -0
  13. experimental/build_env/fix_mmcv_temp.py +26 -0
  14. experimental/build_env/mmcv_pytorch26_compatibility_fix.md +145 -0
  15. experimental/build_env/proxyclip/README.md +190 -0
  16. experimental/build_env/proxyclip/activate.sh +20 -0
  17. experimental/build_env/proxyclip/download_datasets.sh +312 -0
  18. experimental/build_env/proxyclip/requirements.txt +32 -0
  19. experimental/build_env/proxyclip/setup_data_paths.py +155 -0
  20. experimental/build_env/proxyclip/setup_env.sh +85 -0
  21. scripts/ablation_ijepa/debug_ijepa_gsc_eva_vitL14_336_coco.sh +49 -0
  22. scripts/ablation_ijepa/debug_ijepa_gsc_eva_vitb16_coco.sh +49 -0
  23. scripts/ablation_ijepa/dist_ijepa_gsc_eva_vitL14_336_coco.sh +64 -0
  24. scripts/ablation_ijepa/dist_ijepa_gsc_eva_vitb16_coco.sh +65 -0
  25. scripts/ablation_ijepa/resume_ijepa_gsc_eva_vitL14_336.sh +50 -0
  26. scripts/ablation_sam/debug_sam_gsc_eva_vitL14_336_coco.sh +49 -0
  27. scripts/ablation_sam/debug_sam_gsc_eva_vitb16_coco.sh +49 -0
  28. scripts/ablation_sam/dist_sam_gsc_eva_vitL14_336_coco.sh +65 -0
  29. scripts/ablation_sam/dist_sam_gsc_eva_vitb16_coco.sh +66 -0
  30. scripts/declip+/DeCLIP+_eva_vitb16_coco.sh +17 -0
  31. scripts/declip+/dist_DeCLIP+_eva_vitL14_336_coco.sh +17 -0
  32. scripts/declip+/dist_DeCLIP+_eva_vitL14_336_lvis.sh +17 -0
  33. scripts/declip+/dist_DeCLIP+_eva_vitb16_coco.sh +17 -0
  34. scripts/declip+/dist_DeCLIP+_eva_vitb16_coco_seg.sh +17 -0
  35. scripts/declip+/dist_DeCLIP+_eva_vitb16_lvis.sh +17 -0
  36. scripts/declip/dist_eva_vitL14_336_coco.sh +21 -0
  37. scripts/declip/dist_eva_vitb16_coco.sh +65 -0
  38. scripts/declip/dist_tinyclip_vitb16_coco.sh +15 -0
  39. scripts/declip/eva_vitb16_coco.sh +18 -0
  40. scripts/declip/tinyclip_vitb16_coco.sh +16 -0
  41. scripts/decoupling_ablation/debug_integrated_eva_vitL14_336_coco.sh +46 -0
  42. scripts/decoupling_ablation/debug_integrated_eva_vitb16_coco.sh +47 -0
  43. scripts/decoupling_ablation/debug_integrated_openai_vitL14_coco.sh +44 -0
  44. scripts/decoupling_ablation/debug_integrated_openai_vitb16_coco.sh +44 -0
  45. scripts/decoupling_ablation/dist_integrated_eva_vitL14_336_coco.sh +61 -0
  46. scripts/decoupling_ablation/dist_integrated_eva_vitb16_coco.sh +69 -0
  47. scripts/decoupling_ablation/dist_integrated_openai_vitL14_coco.sh +59 -0
  48. scripts/decoupling_ablation/dist_integrated_openai_vitb16_coco.sh +60 -0
  49. scripts/decoupling_ablation/resume_all_experiments.sh +92 -0
  50. scripts/decoupling_ablation/resume_integrated.sh +49 -0
experimental/SimFeatUp/featup/featurizers/maskclip/simple_tokenizer.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gzip
2
+ import html
3
+ import os
4
+ from collections.abc import Sequence
5
+ from functools import lru_cache
6
+
7
+ import ftfy
8
+ import regex as re
9
+
10
+
11
+ @lru_cache()
12
+ def default_bpe():
13
+ return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
14
+
15
+
16
+ @lru_cache()
17
+ def bytes_to_unicode():
18
+ """
19
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
20
+ The reversible bpe codes work on unicode strings.
21
+ This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
22
+ When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
23
+ This is a signficant percentage of your normal, say, 32K bpe vocab.
24
+ To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
25
+ And avoids mapping to whitespace/control characters the bpe code barfs on.
26
+ """
27
+ bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
28
+ cs = bs[:]
29
+ n = 0
30
+ for b in range(2**8):
31
+ if b not in bs:
32
+ bs.append(b)
33
+ cs.append(2**8+n)
34
+ n += 1
35
+ cs = [chr(n) for n in cs]
36
+ return dict(zip(bs, cs))
37
+
38
+
39
+ def get_pairs(word):
40
+ """Return set of symbol pairs in a word.
41
+ Word is represented as tuple of symbols (symbols being variable-length strings).
42
+ """
43
+ pairs = set()
44
+ prev_char = word[0]
45
+ for char in word[1:]:
46
+ pairs.add((prev_char, char))
47
+ prev_char = char
48
+ return pairs
49
+
50
+
51
+ def basic_clean(text):
52
+ # note: pretty hacky but it is okay!
53
+ # ge: bad.this is used by the cli_multi_label.py script
54
+ if not isinstance(text, str):
55
+ text = ', '.join(text)
56
+
57
+ text = ftfy.fix_text(text)
58
+ text = html.unescape(html.unescape(text))
59
+ return text.strip()
60
+
61
+
62
+ def whitespace_clean(text):
63
+ text = re.sub(r'\s+', ' ', text)
64
+ text = text.strip()
65
+ return text
66
+
67
+
68
+ class SimpleTokenizer(object):
69
+ def __init__(self, bpe_path: str = default_bpe()):
70
+ self.byte_encoder = bytes_to_unicode()
71
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
72
+ merges = gzip.open(bpe_path).read().decode("utf-8").split('\n')
73
+ merges = merges[1:49152-256-2+1]
74
+ merges = [tuple(merge.split()) for merge in merges]
75
+ vocab = list(bytes_to_unicode().values())
76
+ vocab = vocab + [v+'</w>' for v in vocab]
77
+ for merge in merges:
78
+ vocab.append(''.join(merge))
79
+ vocab.extend(['<|startoftext|>', '<|endoftext|>'])
80
+ self.encoder = dict(zip(vocab, range(len(vocab))))
81
+ self.decoder = {v: k for k, v in self.encoder.items()}
82
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
83
+ self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'}
84
+ 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)
85
+
86
+ def bpe(self, token):
87
+ if token in self.cache:
88
+ return self.cache[token]
89
+ word = tuple(token[:-1]) + ( token[-1] + '</w>',)
90
+ pairs = get_pairs(word)
91
+
92
+ if not pairs:
93
+ return token+'</w>'
94
+
95
+ while True:
96
+ bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf')))
97
+ if bigram not in self.bpe_ranks:
98
+ break
99
+ first, second = bigram
100
+ new_word = []
101
+ i = 0
102
+ while i < len(word):
103
+ try:
104
+ j = word.index(first, i)
105
+ new_word.extend(word[i:j])
106
+ i = j
107
+ except:
108
+ new_word.extend(word[i:])
109
+ break
110
+
111
+ if word[i] == first and i < len(word)-1 and word[i+1] == second:
112
+ new_word.append(first+second)
113
+ i += 2
114
+ else:
115
+ new_word.append(word[i])
116
+ i += 1
117
+ new_word = tuple(new_word)
118
+ word = new_word
119
+ if len(word) == 1:
120
+ break
121
+ else:
122
+ pairs = get_pairs(word)
123
+ word = ' '.join(word)
124
+ self.cache[token] = word
125
+ return word
126
+
127
+ def encode(self, text):
128
+ bpe_tokens = []
129
+ text = whitespace_clean(basic_clean(text)).lower()
130
+ for token in re.findall(self.pat, text):
131
+ token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
132
+ bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))
133
+ return bpe_tokens
134
+
135
+ def decode(self, tokens):
136
+ text = ''.join([self.decoder[token] for token in tokens])
137
+ text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('</w>', ' ')
138
+ return text
experimental/SimFeatUp/featup/featurizers/maskclip/xclip.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import os
3
+ import urllib
4
+ import warnings
5
+ from typing import Any, Union, List
6
+ from pkg_resources import packaging
7
+
8
+ import torch
9
+ from PIL import Image
10
+ from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
11
+ from tqdm import tqdm
12
+
13
+ from .xmodel import build_model
14
+ from .simple_tokenizer import SimpleTokenizer as _Tokenizer
15
+
16
+ try:
17
+ from torchvision.transforms import InterpolationMode
18
+
19
+ BICUBIC = InterpolationMode.BICUBIC
20
+ except ImportError:
21
+ BICUBIC = Image.BICUBIC
22
+
23
+ if packaging.version.parse(torch.__version__) < packaging.version.parse("1.7.1"):
24
+ warnings.warn("PyTorch version 1.7.1 or higher is recommended")
25
+
26
+ __all__ = ["available_models", "load", "tokenize"]
27
+ _tokenizer = _Tokenizer()
28
+
29
+ _MODELS = {
30
+ "RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt",
31
+ "RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt",
32
+ "RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt",
33
+ "RN50x16": "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt",
34
+ "RN50x64": "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt",
35
+ "ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt",
36
+ "ViT-B/16": "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt",
37
+ "ViT-L/14": "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt",
38
+ "ViT-L/14@336px": "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt",
39
+ }
40
+
41
+
42
+ def _download(url: str, root: str):
43
+ os.makedirs(root, exist_ok=True)
44
+ filename = os.path.basename(url)
45
+
46
+ expected_sha256 = url.split("/")[-2]
47
+ download_target = os.path.join(root, filename)
48
+
49
+ if os.path.exists(download_target) and not os.path.isfile(download_target):
50
+ raise RuntimeError(f"{download_target} exists and is not a regular file")
51
+
52
+ if os.path.isfile(download_target):
53
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256:
54
+ return download_target
55
+ else:
56
+ warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
57
+
58
+ print(f"Downloading CLIP model from {url}")
59
+ with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
60
+ with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True,
61
+ unit_divisor=1024) as loop:
62
+ while True:
63
+ buffer = source.read(8192)
64
+ if not buffer:
65
+ break
66
+
67
+ output.write(buffer)
68
+ loop.update(len(buffer))
69
+
70
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256:
71
+ raise RuntimeError("Model has been downloaded but the SHA256 checksum does not not match")
72
+
73
+ return download_target
74
+
75
+
76
+ def _convert_image_to_rgb(image):
77
+ return image.convert("RGB")
78
+
79
+
80
+ def _transform(n_px):
81
+ return Compose([
82
+ Resize(n_px, interpolation=BICUBIC),
83
+ CenterCrop(n_px),
84
+ _convert_image_to_rgb,
85
+ ToTensor(),
86
+ Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
87
+ ])
88
+
89
+
90
+ def available_models() -> List[str]:
91
+ """Returns the names of available CLIP models"""
92
+ return list(_MODELS.keys())
93
+
94
+
95
+ TORCH_HUB_ROOT = os.path.expandvars(os.getenv("$TORCH_HUB_ROOT", "$HOME/.torch_hub"))
96
+
97
+
98
+ def load(
99
+ name: str,
100
+ device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu",
101
+ jit: bool = False,
102
+ download_root: str = None
103
+ ):
104
+ """Load a CLIP model
105
+
106
+ Parameters
107
+ ----------
108
+ name : str
109
+ A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
110
+
111
+ device : Union[str, torch.device]
112
+ The device to put the loaded model
113
+
114
+ jit : bool
115
+ Whether to load the optimized JIT model or more hackable non-JIT model (default).
116
+
117
+ download_root: str
118
+ path to download the model files; by default, it uses "~/.torch_hub/clip"
119
+
120
+ Returns
121
+ -------
122
+ model : torch.nn.Module
123
+ The CLIP model
124
+
125
+ preprocess : Callable[[PIL.Image], torch.Tensor]
126
+ A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
127
+ """
128
+ if name in _MODELS:
129
+ model_path = _download(_MODELS[name], download_root or TORCH_HUB_ROOT)
130
+ elif os.path.isfile(name):
131
+ model_path = name
132
+ else:
133
+ raise RuntimeError(f"Model {name} not found; available models = {available_models()}")
134
+
135
+ with open(model_path, 'rb') as opened_file:
136
+ try:
137
+ # loading JIT archive
138
+ model = torch.jit.load(opened_file, map_location=device if jit else "cpu").eval()
139
+ state_dict = None
140
+ except RuntimeError:
141
+ # loading saved state dict
142
+ if jit:
143
+ warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead")
144
+ jit = False
145
+ state_dict = torch.load(opened_file, map_location="cpu")
146
+
147
+ if not jit:
148
+ model = build_model(state_dict or model.state_dict()).to(device)
149
+ if str(device) == "cpu":
150
+ model.float()
151
+ return model, _transform(model.visual.input_resolution)
152
+
153
+ # patch the device names
154
+ device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[])
155
+ device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
156
+
157
+ def patch_device(module):
158
+ try:
159
+ graphs = [module.graph] if hasattr(module, "graph") else []
160
+ except RuntimeError:
161
+ graphs = []
162
+
163
+ if hasattr(module, "forward1"):
164
+ graphs.append(module.forward1.graph)
165
+
166
+ for graph in graphs:
167
+ for node in graph.findAllNodes("prim::Constant"):
168
+ if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"):
169
+ node.copyAttributes(device_node)
170
+
171
+ model.apply(patch_device)
172
+ patch_device(model.encode_image)
173
+ patch_device(model.encode_text)
174
+
175
+ # patch dtype to float32 on CPU
176
+ if str(device) == "cpu":
177
+ float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
178
+ float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
179
+ float_node = float_input.node()
180
+
181
+ def patch_float(module):
182
+ try:
183
+ graphs = [module.graph] if hasattr(module, "graph") else []
184
+ except RuntimeError:
185
+ graphs = []
186
+
187
+ if hasattr(module, "forward1"):
188
+ graphs.append(module.forward1.graph)
189
+
190
+ for graph in graphs:
191
+ for node in graph.findAllNodes("aten::to"):
192
+ inputs = list(node.inputs())
193
+ for i in [1, 2]: # dtype can be the second or third argument to aten::to()
194
+ if inputs[i].node()["value"] == 5:
195
+ inputs[i].node().copyAttributes(float_node)
196
+
197
+ model.apply(patch_float)
198
+ patch_float(model.encode_image)
199
+ patch_float(model.encode_text)
200
+
201
+ model.float()
202
+
203
+ return model, _transform(model.input_resolution.item())
204
+
205
+
206
+ def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = False) -> Union[
207
+ torch.IntTensor, torch.LongTensor]:
208
+ """
209
+ Returns the tokenized representation of given input string(s)
210
+
211
+ Parameters
212
+ ----------
213
+ texts : Union[str, List[str]]
214
+ An input string or a list of input strings to tokenize
215
+
216
+ context_length : int
217
+ The context length to use; all CLIP models use 77 as the context length
218
+
219
+ truncate: bool
220
+ Whether to truncate the text in case its encoding is longer than the context length
221
+
222
+ Returns
223
+ -------
224
+ A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length].
225
+ We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long.
226
+ """
227
+ if isinstance(texts, str):
228
+ texts = [texts]
229
+
230
+ sot_token = _tokenizer.encoder["<|startoftext|>"]
231
+ eot_token = _tokenizer.encoder["<|endoftext|>"]
232
+ all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts]
233
+ if packaging.version.parse(torch.__version__) < packaging.version.parse("1.8.0"):
234
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
235
+ else:
236
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.int)
237
+
238
+ for i, tokens in enumerate(all_tokens):
239
+ if len(tokens) > context_length:
240
+ if truncate:
241
+ tokens = tokens[:context_length]
242
+ tokens[-1] = eot_token
243
+ else:
244
+ raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}")
245
+ result[i, :len(tokens)] = torch.tensor(tokens)
246
+
247
+ return result
experimental/SimFeatUp/featup/featurizers/maskclip/xmodel.py ADDED
@@ -0,0 +1,535 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from typing import Tuple, Union
3
+
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch import nn
8
+
9
+ from .interpolate import interpolate_positional_embedding
10
+
11
+
12
+ class Bottleneck(nn.Module):
13
+ expansion = 4
14
+
15
+ def __init__(self, inplanes, planes, stride=1):
16
+ super().__init__()
17
+
18
+ # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
19
+ self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
20
+ self.bn1 = nn.BatchNorm2d(planes)
21
+ self.relu1 = nn.ReLU(inplace=True)
22
+
23
+ self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
24
+ self.bn2 = nn.BatchNorm2d(planes)
25
+ self.relu2 = nn.ReLU(inplace=True)
26
+
27
+ self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
28
+
29
+ self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
30
+ self.bn3 = nn.BatchNorm2d(planes * self.expansion)
31
+ self.relu3 = nn.ReLU(inplace=True)
32
+
33
+ self.downsample = None
34
+ self.stride = stride
35
+
36
+ if stride > 1 or inplanes != planes * Bottleneck.expansion:
37
+ # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
38
+ self.downsample = nn.Sequential(OrderedDict([
39
+ ("-1", nn.AvgPool2d(stride)),
40
+ ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
41
+ ("1", nn.BatchNorm2d(planes * self.expansion))
42
+ ]))
43
+
44
+ def forward(self, x: torch.Tensor):
45
+ identity = x
46
+
47
+ out = self.relu1(self.bn1(self.conv1(x)))
48
+ out = self.relu2(self.bn2(self.conv2(out)))
49
+ out = self.avgpool(out)
50
+ out = self.bn3(self.conv3(out))
51
+
52
+ if self.downsample is not None:
53
+ identity = self.downsample(x)
54
+
55
+ out += identity
56
+ out = self.relu3(out)
57
+ return out
58
+
59
+
60
+ class AttentionPool2d(nn.Module):
61
+ def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
62
+ super().__init__()
63
+ self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
64
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
65
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
66
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
67
+ self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
68
+ self.num_heads = num_heads
69
+ self.spacial_dim = spacial_dim
70
+
71
+ def forward(self, x):
72
+ x = x.flatten(start_dim=2).permute(2, 0, 1) # NCHW -> (HW)NC
73
+ x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
74
+ x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
75
+ x, _ = F.multi_head_attention_forward(
76
+ query=x[:1], key=x, value=x,
77
+ embed_dim_to_check=x.shape[-1],
78
+ num_heads=self.num_heads,
79
+ q_proj_weight=self.q_proj.weight,
80
+ k_proj_weight=self.k_proj.weight,
81
+ v_proj_weight=self.v_proj.weight,
82
+ in_proj_weight=None,
83
+ in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
84
+ bias_k=None,
85
+ bias_v=None,
86
+ add_zero_attn=False,
87
+ dropout_p=0,
88
+ out_proj_weight=self.c_proj.weight,
89
+ out_proj_bias=self.c_proj.bias,
90
+ use_separate_proj_weight=True,
91
+ training=self.training,
92
+ need_weights=False
93
+ )
94
+ return x.squeeze(0)
95
+
96
+ def forward_v(self, x: torch.Tensor):
97
+ """
98
+ Forward function for computing the value features for dense prediction (i.e., features for every image patch).
99
+ """
100
+ _, _, w, h = x.shape
101
+ x = x.flatten(start_dim=2).permute(2, 0, 1) # NCHW -> (HW)NC
102
+ x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
103
+
104
+ # Interpolate positional embedding to match the size of the input
105
+ interpolated_pe = interpolate_positional_embedding(self.positional_embedding, x.permute(1, 0, 2), patch_size=1, w=w, h=h)
106
+ x = x + interpolated_pe[:, None, :] # (HW+1)NC
107
+
108
+ v_in = F.linear(x, self.v_proj.weight, self.v_proj.bias)
109
+ v_out = F.linear(v_in, self.c_proj.weight, self.c_proj.bias)
110
+ v_out = v_out.permute(1, 0, 2) # (HW+1)NC -> N(HW+1)C
111
+ return v_out
112
+
113
+
114
+ class ModifiedResNet(nn.Module):
115
+ """
116
+ A ResNet class that is similar to torchvision's but contains the following changes:
117
+ - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
118
+ - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
119
+ - The final pooling layer is a QKV attention instead of an average pool
120
+ """
121
+
122
+ def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
123
+ super().__init__()
124
+ self.output_dim = output_dim
125
+ self.input_resolution = input_resolution
126
+
127
+ # the 3-layer stem
128
+ self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
129
+ self.bn1 = nn.BatchNorm2d(width // 2)
130
+ self.relu1 = nn.ReLU(inplace=True)
131
+ self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
132
+ self.bn2 = nn.BatchNorm2d(width // 2)
133
+ self.relu2 = nn.ReLU(inplace=True)
134
+ self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
135
+ self.bn3 = nn.BatchNorm2d(width)
136
+ self.relu3 = nn.ReLU(inplace=True)
137
+ self.avgpool = nn.AvgPool2d(2)
138
+
139
+ # residual layers
140
+ self._inplanes = width # this is a *mutable* variable used during construction
141
+ self.layer1 = self._make_layer(width, layers[0])
142
+ self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
143
+ self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
144
+ self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
145
+
146
+ embed_dim = width * 32 # the ResNet feature dimension
147
+ self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
148
+
149
+ def _make_layer(self, planes, blocks, stride=1):
150
+ layers = [Bottleneck(self._inplanes, planes, stride)]
151
+
152
+ self._inplanes = planes * Bottleneck.expansion
153
+ for _ in range(1, blocks):
154
+ layers.append(Bottleneck(self._inplanes, planes))
155
+
156
+ return nn.Sequential(*layers)
157
+
158
+ def forward(self, x, patch_output: bool = False):
159
+ def stem(x):
160
+ x = self.relu1(self.bn1(self.conv1(x)))
161
+ x = self.relu2(self.bn2(self.conv2(x)))
162
+ x = self.relu3(self.bn3(self.conv3(x)))
163
+ x = self.avgpool(x)
164
+ return x
165
+
166
+ x = x.type(self.conv1.weight.dtype)
167
+ x = stem(x)
168
+ x = self.layer1(x)
169
+ x = self.layer2(x)
170
+ x = self.layer3(x)
171
+ x = self.layer4(x)
172
+
173
+ if patch_output:
174
+ x = self.attnpool.forward_v(x)
175
+ x = x[:, 1:, :] # remove the cls token
176
+ else:
177
+ x = self.attnpool(x)
178
+
179
+ return x
180
+
181
+
182
+ class LayerNorm(nn.LayerNorm):
183
+ """Subclass torch's LayerNorm to handle fp16."""
184
+
185
+ def forward(self, x: torch.Tensor):
186
+ orig_type = x.dtype
187
+ ret = super().forward(x.type(torch.float32))
188
+ return ret.type(orig_type)
189
+
190
+
191
+ class QuickGELU(nn.Module):
192
+ def forward(self, x: torch.Tensor):
193
+ return x * torch.sigmoid(1.702 * x)
194
+
195
+
196
+ class ResidualAttentionBlock(nn.Module):
197
+ def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
198
+ super().__init__()
199
+
200
+ self.attn = nn.MultiheadAttention(d_model, n_head)
201
+ self.ln_1 = LayerNorm(d_model)
202
+ self.mlp = nn.Sequential(OrderedDict([
203
+ ("c_fc", nn.Linear(d_model, d_model * 4)),
204
+ ("gelu", QuickGELU()),
205
+ ("c_proj", nn.Linear(d_model * 4, d_model))
206
+ ]))
207
+ self.ln_2 = LayerNorm(d_model)
208
+ self.attn_mask = attn_mask
209
+
210
+ # self.n_head = n_head
211
+ # self.head_dim = d_model // n_head
212
+ # self.scale = self.head_dim ** -0.5
213
+
214
+ def attention(self, x: torch.Tensor):
215
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
216
+ return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
217
+
218
+ def forward_x(self, x: torch.Tensor):
219
+ """
220
+ Forward function for computing the value features for dense prediction (i.e., features for every image patch).
221
+ """
222
+ return x
223
+
224
+ def forward(self, x: torch.Tensor):
225
+ x = x + self.attention(self.ln_1(x))
226
+ x = x + self.mlp(self.ln_2(x))
227
+ return x
228
+
229
+ # TODO: qq, kk, vv forward
230
+ def forward_qkv(self, x: torch.Tensor):
231
+ """
232
+ Forward function for computing the value features for dense prediction (i.e., features for every image patch).
233
+ """
234
+ # Get the weights and biases for the value projection, multihead attention uses 3 * embed_dim for the input projection
235
+ # x [197, 4, 768]
236
+ _, bsz, embed_dim = x.shape
237
+ v_in_proj_weight = self.attn.in_proj_weight[-self.attn.embed_dim:]
238
+ v_in_proj_bias = self.attn.in_proj_bias[-self.attn.embed_dim:]
239
+
240
+ q_in_proj_weight = self.attn.in_proj_weight[:self.attn.embed_dim]
241
+ q_in_proj_bias = self.attn.in_proj_bias[:self.attn.embed_dim:]
242
+
243
+ v_in = F.linear(self.ln_1(x), v_in_proj_weight, v_in_proj_bias)
244
+ # v_out = F.linear(v_in, self.attn.out_proj.weight, self.attn.out_proj.bias)
245
+
246
+ q_in = F.linear(self.ln_1(x), q_in_proj_weight, q_in_proj_bias)
247
+ # q_out = F.linear(q_in, self.attn.out_proj.weight, self.attn.out_proj.bias)
248
+
249
+ q_in = q_in.contiguous().view(-1, bsz * self.n_head, self.head_dim).transpose(0, 1)
250
+ v_in = v_in.contiguous().view(-1, bsz * self.n_head, self.head_dim).transpose(0, 1)
251
+
252
+ qq_attn = torch.bmm(q_in, q_in.transpose(1, 2)) * self.scale
253
+ attn_weights = F.softmax(qq_attn, dim=-1)
254
+ attn_output = torch.bmm(attn_weights, v_in) # [12, 197, 64]
255
+
256
+ attn_output = attn_output.transpose(0, 1).contiguous().view(-1, bsz, embed_dim)
257
+ out = F.linear(attn_output, self.attn.out_proj.weight, self.attn.out_proj.bias)
258
+
259
+ # Using the value features works the best. Adding this to 'x' or feeding 'v' to the LayerNorm then MLP degrades the performance
260
+ return out
261
+
262
+
263
+
264
+ class Transformer(nn.Module):
265
+ def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
266
+ super().__init__()
267
+ self.width = width
268
+ self.layers = layers
269
+ self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
270
+
271
+ def forward(self, x: torch.Tensor):
272
+ return self.resblocks(x)
273
+
274
+
275
+ class VisionTransformer(nn.Module):
276
+ def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):
277
+ super().__init__()
278
+ self.input_resolution = input_resolution
279
+ self.output_dim = output_dim
280
+ self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
281
+
282
+ scale = width ** -0.5
283
+ self.class_embedding = nn.Parameter(scale * torch.randn(width))
284
+ self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
285
+ self.ln_pre = LayerNorm(width)
286
+
287
+ self.transformer = Transformer(width, layers, heads)
288
+
289
+ self.ln_post = LayerNorm(width)
290
+ self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
291
+
292
+ self.patch_size = patch_size
293
+
294
+ def forward(self, x: torch.Tensor, patch_output: bool = False):
295
+ _, _, w, h = x.shape
296
+
297
+ x = self.conv1(x) # shape = [*, width, grid, grid]
298
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
299
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
300
+ 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]
301
+ x = x + interpolate_positional_embedding(self.positional_embedding, x, patch_size=self.patch_size, w=w, h=h)
302
+ x = self.ln_pre(x)
303
+
304
+ x = x.permute(1, 0, 2) # NLD -> LND
305
+
306
+ if patch_output:
307
+ *layers, last_resblock = self.transformer.resblocks
308
+ penultimate = nn.Sequential(*layers)
309
+
310
+ x = penultimate(x)
311
+ x = last_resblock.forward_x(x)
312
+ x = x.permute(1, 0, 2) # LND -> NLD
313
+
314
+ # Extract the patch tokens, not the class token
315
+ x = x[:, 1:, :]
316
+ x = self.ln_post(x)
317
+ if self.proj is not None:
318
+ # This is equivalent to conv1d
319
+ x = x @ self.proj
320
+ return x
321
+
322
+ x = self.transformer(x)
323
+ x = x.permute(1, 0, 2) # LND -> NLD
324
+
325
+ x = self.ln_post(x[:, 0, :])
326
+
327
+ if self.proj is not None:
328
+ x = x @ self.proj
329
+
330
+ return x
331
+
332
+
333
+ class CLIP(nn.Module):
334
+ def __init__(self,
335
+ embed_dim: int,
336
+ # vision
337
+ image_resolution: int,
338
+ vision_layers: Union[Tuple[int, int, int, int], int],
339
+ vision_width: int,
340
+ vision_patch_size: int,
341
+ # text
342
+ context_length: int,
343
+ vocab_size: int,
344
+ transformer_width: int,
345
+ transformer_heads: int,
346
+ transformer_layers: int
347
+ ):
348
+ super().__init__()
349
+
350
+ self.context_length = context_length
351
+
352
+ if isinstance(vision_layers, (tuple, list)):
353
+ vision_heads = vision_width * 32 // 64
354
+ self.visual = ModifiedResNet(
355
+ layers=vision_layers,
356
+ output_dim=embed_dim,
357
+ heads=vision_heads,
358
+ input_resolution=image_resolution,
359
+ width=vision_width
360
+ )
361
+ else:
362
+ vision_heads = vision_width // 64
363
+ self.visual = VisionTransformer(
364
+ input_resolution=image_resolution,
365
+ patch_size=vision_patch_size,
366
+ width=vision_width,
367
+ layers=vision_layers,
368
+ heads=vision_heads,
369
+ output_dim=embed_dim
370
+ )
371
+
372
+ self.transformer = Transformer(
373
+ width=transformer_width,
374
+ layers=transformer_layers,
375
+ heads=transformer_heads,
376
+ attn_mask=self.build_attention_mask()
377
+ )
378
+
379
+ self.vocab_size = vocab_size
380
+ self.token_embedding = nn.Embedding(vocab_size, transformer_width)
381
+ self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
382
+ self.ln_final = LayerNorm(transformer_width)
383
+
384
+ self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
385
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
386
+
387
+ self.initialize_parameters()
388
+
389
+ def initialize_parameters(self):
390
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
391
+ nn.init.normal_(self.positional_embedding, std=0.01)
392
+
393
+ if isinstance(self.visual, ModifiedResNet):
394
+ if self.visual.attnpool is not None:
395
+ std = self.visual.attnpool.c_proj.in_features ** -0.5
396
+ nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
397
+ nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
398
+ nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
399
+ nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
400
+
401
+ for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
402
+ for name, param in resnet_block.named_parameters():
403
+ if name.endswith("bn3.weight"):
404
+ nn.init.zeros_(param)
405
+
406
+ proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
407
+ attn_std = self.transformer.width ** -0.5
408
+ fc_std = (2 * self.transformer.width) ** -0.5
409
+ for block in self.transformer.resblocks:
410
+ nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
411
+ nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
412
+ nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
413
+ nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
414
+
415
+ if self.text_projection is not None:
416
+ nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
417
+
418
+ def build_attention_mask(self):
419
+ # lazily create causal attention mask, with full attention between the vision tokens
420
+ # pytorch uses additive attention mask; fill with -inf
421
+ mask = torch.empty(self.context_length, self.context_length)
422
+ mask.fill_(float("-inf"))
423
+ mask.triu_(1) # zero out the lower diagonal
424
+ return mask
425
+
426
+ @property
427
+ def dtype(self):
428
+ return self.visual.conv1.weight.dtype
429
+
430
+ def encode_image(self, image):
431
+ return self.visual(image.type(self.dtype))
432
+
433
+ def get_patch_encodings(self, image) -> torch.Tensor:
434
+ """ Get the encodings for each patch in the image """
435
+ return self.visual(image.type(self.dtype), patch_output=True)
436
+
437
+ def get_image_encoder_projection(self) -> nn.Parameter:
438
+ """ Get vision transformer projection matrix."""
439
+ assert isinstance(self.visual, VisionTransformer)
440
+ return self.visual.proj
441
+
442
+ def encode_text(self, text):
443
+ x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
444
+
445
+ x = x + self.positional_embedding.type(self.dtype)
446
+ x = x.permute(1, 0, 2) # NLD -> LND
447
+ x = self.transformer(x)
448
+ x = x.permute(1, 0, 2) # LND -> NLD
449
+ x = self.ln_final(x).type(self.dtype)
450
+
451
+ # x.shape = [batch_size, n_ctx, transformer.width]
452
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
453
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
454
+
455
+ return x
456
+
457
+ def forward(self, image, text):
458
+ image_features = self.encode_image(image)
459
+ text_features = self.encode_text(text)
460
+
461
+ # normalized features
462
+ image_features = image_features / image_features.norm(dim=1, keepdim=True)
463
+ text_features = text_features / text_features.norm(dim=1, keepdim=True)
464
+
465
+ # cosine similarity as logits
466
+ logit_scale = self.logit_scale.exp()
467
+ logits_per_image = logit_scale * image_features @ text_features.t()
468
+ logits_per_text = logits_per_image.t()
469
+
470
+ # shape = [global_batch_size, global_batch_size]
471
+ return logits_per_image, logits_per_text
472
+
473
+
474
+ def convert_weights(model: nn.Module):
475
+ """Convert applicable model parameters to fp16"""
476
+
477
+ def _convert_weights_to_fp16(l):
478
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
479
+ l.weight.data = l.weight.data.half()
480
+ if l.bias is not None:
481
+ l.bias.data = l.bias.data.half()
482
+
483
+ if isinstance(l, nn.MultiheadAttention):
484
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
485
+ tensor = getattr(l, attr)
486
+ if tensor is not None:
487
+ tensor.data = tensor.data.half()
488
+
489
+ for name in ["text_projection", "proj"]:
490
+ if hasattr(l, name):
491
+ attr = getattr(l, name)
492
+ if attr is not None:
493
+ attr.data = attr.data.half()
494
+
495
+ model.apply(_convert_weights_to_fp16)
496
+
497
+
498
+ def build_model(state_dict: dict):
499
+ vit = "visual.proj" in state_dict
500
+
501
+ if vit:
502
+ vision_width = state_dict["visual.conv1.weight"].shape[0]
503
+ vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
504
+ vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
505
+ grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
506
+ image_resolution = vision_patch_size * grid_size
507
+ else:
508
+ 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]]
509
+ vision_layers = tuple(counts)
510
+ vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
511
+ output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
512
+ vision_patch_size = None
513
+ assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
514
+ image_resolution = output_width * 32
515
+
516
+ embed_dim = state_dict["text_projection"].shape[1]
517
+ context_length = state_dict["positional_embedding"].shape[0]
518
+ vocab_size = state_dict["token_embedding.weight"].shape[0]
519
+ transformer_width = state_dict["ln_final.weight"].shape[0]
520
+ transformer_heads = transformer_width // 64
521
+ transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith("transformer.resblocks")))
522
+
523
+ model = CLIP(
524
+ embed_dim,
525
+ image_resolution, vision_layers, vision_width, vision_patch_size,
526
+ context_length, vocab_size, transformer_width, transformer_heads, transformer_layers
527
+ )
528
+
529
+ for key in ["input_resolution", "context_length", "vocab_size"]:
530
+ if key in state_dict:
531
+ del state_dict[key]
532
+
533
+ convert_weights(model)
534
+ model.load_state_dict(state_dict)
535
+ return model.eval()
experimental/SimFeatUp/featup/featurizers/modules/__init__.py ADDED
File without changes
experimental/SimFeatUp/featup/featurizers/modules/layers.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from functools import partial
5
+ import math
6
+
7
+ __all__ = ['forward_hook', 'AdaptiveAvgPool2d', 'Add', 'AvgPool2d', 'BatchNorm2d', 'Clone', 'Conv2d', 'ConvTranspose2d',
8
+ 'Dropout', 'Identity', 'LeakyReLU', 'Linear', 'MaxPool2d', 'Multiply', 'ReLU', 'Sequential', 'safe_divide',
9
+ 'ZeroPad2d', 'LayerNorm', 'GELU', 'einsum', 'Softmax']
10
+
11
+
12
+ def safe_divide(a, b):
13
+ return a / (b + b.eq(0).type(b.type()) * 1e-9) * b.ne(0).type(b.type())
14
+
15
+
16
+ def forward_hook(self, input, output):
17
+ if type(input[0]) in (list, tuple):
18
+ self.X = []
19
+ for i in input[0]:
20
+ x = i.detach()
21
+ x.requires_grad = True
22
+ self.X.append(x)
23
+ else:
24
+ self.X = input[0].detach()
25
+ self.X.requires_grad = True
26
+
27
+ self.Y = output
28
+
29
+
30
+ class RelProp(nn.Module):
31
+ def __init__(self):
32
+ super(RelProp, self).__init__()
33
+ # if not self.training:
34
+ self.register_forward_hook(forward_hook)
35
+
36
+ def gradprop(self, Z, X, S):
37
+ C = torch.autograd.grad(Z, X, S, retain_graph=True)
38
+ return C
39
+
40
+ def relprop(self, R, alpha=1):
41
+ return R
42
+
43
+
44
+ class RelPropSimple(RelProp):
45
+ def relprop(self, R, alpha=1):
46
+ Z = self.forward(self.X)
47
+ S = safe_divide(R, Z)
48
+ C = self.gradprop(Z, self.X, S)
49
+
50
+ if torch.is_tensor(self.X) == False:
51
+ outputs = []
52
+ outputs.append(self.X[0] * C[0])
53
+ outputs.append(self.X[1] * C[1])
54
+ else:
55
+ outputs = self.X * C[0]
56
+ return outputs
57
+
58
+
59
+ class Identity(nn.Identity, RelProp):
60
+ pass
61
+
62
+
63
+ class ReLU(nn.ReLU, RelProp):
64
+ pass
65
+
66
+
67
+ class GELU(nn.GELU, RelProp):
68
+ pass
69
+
70
+ class LeakyReLU(nn.LeakyReLU, RelProp):
71
+ pass
72
+
73
+ class Softmax(nn.Softmax, RelProp):
74
+ pass
75
+
76
+ class einsum(RelPropSimple):
77
+ def __init__(self, equation):
78
+ super().__init__()
79
+ self.equation = equation
80
+ def forward(self, *operands):
81
+ return torch.einsum(self.equation, *operands)
82
+
83
+ class Dropout(nn.Dropout, RelProp):
84
+ pass
85
+
86
+
87
+ class MaxPool2d(nn.MaxPool2d, RelPropSimple):
88
+ pass
89
+
90
+ class LayerNorm(nn.LayerNorm, RelProp):
91
+ pass
92
+
93
+ class AdaptiveAvgPool2d(nn.AdaptiveAvgPool2d, RelProp):
94
+ def relprop(self, R, alpha=1):
95
+ px = torch.clamp(self.X, min=0)
96
+
97
+ def f(x1):
98
+ Z1 = F.adaptive_avg_pool2d(x1, self.output_size)
99
+ S1 = safe_divide(R, Z1)
100
+ C1 = x1 * self.gradprop(Z1, x1, S1)[0]
101
+ return C1
102
+
103
+ activator_relevances = f(px)
104
+ out = activator_relevances
105
+ return out
106
+
107
+
108
+ class ZeroPad2d(nn.ZeroPad2d, RelPropSimple):
109
+ def relprop(self, R, alpha=1):
110
+ Z = self.forward(self.X)
111
+ S = safe_divide(R, Z)
112
+ C = self.gradprop(Z, self.X, S)
113
+ outputs = self.X * C[0]
114
+ return outputs
115
+
116
+
117
+ class AvgPool2d(nn.AvgPool2d, RelPropSimple):
118
+ pass
119
+
120
+
121
+ class Add(RelPropSimple):
122
+ def forward(self, inputs):
123
+ return torch.add(*inputs)
124
+
125
+ def relprop(self, R, alpha):
126
+ Z = self.forward(self.X)
127
+ S = safe_divide(R, Z)
128
+ C = self.gradprop(Z, self.X, S)
129
+
130
+ a = self.X[0] * C[0]
131
+ b = self.X[1] * C[1]
132
+
133
+ a_sum = a.sum()
134
+ b_sum = b.sum()
135
+
136
+ a_fact = safe_divide(a_sum.abs(), a_sum.abs() + b_sum.abs()) * R.sum()
137
+ b_fact = safe_divide(b_sum.abs(), a_sum.abs() + b_sum.abs()) * R.sum()
138
+
139
+ a = a * safe_divide(a_fact, a.sum())
140
+ b = b * safe_divide(b_fact, b.sum())
141
+
142
+ outputs = [a, b]
143
+
144
+ return outputs
145
+
146
+
147
+ class Clone(RelProp):
148
+ def forward(self, input, num):
149
+ self.__setattr__('num', num)
150
+ outputs = []
151
+ for _ in range(num):
152
+ outputs.append(input)
153
+
154
+ return outputs
155
+
156
+ def relprop(self, R, alpha = 1):
157
+ Z = []
158
+ for _ in range(self.num):
159
+ Z.append(self.X)
160
+ S = [safe_divide(r, z) for r, z in zip(R, Z)]
161
+ C = self.gradprop(Z, self.X, S)[0]
162
+
163
+ R = self.X * C
164
+
165
+ return R
166
+
167
+
168
+ class Multiply(RelPropSimple):
169
+ def forward(self, inputs):
170
+ return torch.mul(*inputs)
171
+
172
+ def relprop(self, R, alpha=1):
173
+ x0 = torch.clamp(self.X[0], min=0)
174
+ x1 = torch.clamp(self.X[1], min=0)
175
+ x = [x0, x1]
176
+ Z = self.forward(x)
177
+ S = safe_divide(R, Z)
178
+ C = self.gradprop(Z, x, S)
179
+ outputs = []
180
+ outputs.append(x[0] * C[0])
181
+ outputs.append(x[1] * C[1])
182
+ return outputs
183
+
184
+ class Sequential(nn.Sequential):
185
+ def relprop(self, R, alpha=1):
186
+ for m in reversed(self._modules.values()):
187
+ R = m.relprop(R, alpha)
188
+ return R
189
+
190
+
191
+
192
+ class BatchNorm2d(nn.BatchNorm2d, RelProp):
193
+ def relprop(self, R, alpha=1):
194
+ X = self.X
195
+ beta = 1 - alpha
196
+ weight = self.weight.unsqueeze(0).unsqueeze(2).unsqueeze(3) / (
197
+ (self.running_var.unsqueeze(0).unsqueeze(2).unsqueeze(3).pow(2) + self.eps).pow(0.5))
198
+ Z = X * weight + 1e-9
199
+ S = R / Z
200
+ Ca = S * weight
201
+ R = self.X * (Ca)
202
+ return R
203
+
204
+
205
+ class Linear(nn.Linear, RelProp):
206
+ def relprop(self, R, alpha=1):
207
+ beta = alpha - 1
208
+ pw = torch.clamp(self.weight, min=0)
209
+ nw = torch.clamp(self.weight, max=0)
210
+ px = torch.clamp(self.X, min=0)
211
+ nx = torch.clamp(self.X, max=0)
212
+
213
+ # def f(w1, w2, x1, x2):
214
+ # Z1 = F.linear(x1, w1)
215
+ # Z2 = F.linear(x2, w2)
216
+ # S1 = safe_divide(R, Z1)
217
+ # S2 = safe_divide(R, Z2)
218
+ # C1 = x1 * self.gradprop(Z1, x1, S1)[0]
219
+ # C2 = x2 * self.gradprop(Z2, x2, S2)[0]
220
+ # return C1 #+ C2
221
+
222
+ def f(w1, w2, x1, x2):
223
+ Z1 = F.linear(x1, w1)
224
+ Z2 = F.linear(x2, w2)
225
+ Z = Z1 + Z2
226
+ S = safe_divide(R, Z)
227
+ C1 = x1 * self.gradprop(Z1, x1, S)[0]
228
+ C2 = x2 * self.gradprop(Z2, x2, S)[0]
229
+ return C1 + C2
230
+
231
+ activator_relevances = f(pw, nw, px, nx)
232
+ inhibitor_relevances = f(nw, pw, px, nx)
233
+
234
+ out = alpha * activator_relevances - beta * inhibitor_relevances
235
+
236
+ return out
237
+
238
+
239
+
240
+ class Conv2d(nn.Conv2d, RelProp):
241
+
242
+ def relprop(self, R, alpha=1):
243
+ if self.X.shape[1] == 3:
244
+ pw = torch.clamp(self.weight, min=0)
245
+ nw = torch.clamp(self.weight, max=0)
246
+ X = self.X
247
+ L = self.X * 0 + \
248
+ torch.min(torch.min(torch.min(self.X, dim=1, keepdim=True)[0], dim=2, keepdim=True)[0], dim=3,
249
+ keepdim=True)[0]
250
+ H = self.X * 0 + \
251
+ torch.max(torch.max(torch.max(self.X, dim=1, keepdim=True)[0], dim=2, keepdim=True)[0], dim=3,
252
+ keepdim=True)[0]
253
+ Za = torch.conv2d(X, self.weight, bias=None, stride=self.stride, padding=self.padding) - \
254
+ torch.conv2d(L, pw, bias=None, stride=self.stride, padding=self.padding) - \
255
+ torch.conv2d(H, nw, bias=None, stride=self.stride, padding=self.padding) + 1e-9
256
+
257
+ S = R / Za
258
+ C = X * self.gradprop2(S, self.weight) - L * self.gradprop2(S, pw) - H * self.gradprop2(S, nw)
259
+ R = C
260
+ else:
261
+ beta = alpha - 1
262
+ pw = torch.clamp(self.weight, min=0)
263
+ nw = torch.clamp(self.weight, max=0)
264
+ px = torch.clamp(self.X, min=0)
265
+ nx = torch.clamp(self.X, max=0)
266
+
267
+ def f(w1, w2, x1, x2):
268
+ Z1 = F.conv2d(x1, w1, bias=self.bias, stride=self.stride, padding=self.padding, groups=self.groups)
269
+ Z2 = F.conv2d(x2, w2, bias=self.bias, stride=self.stride, padding=self.padding, groups=self.groups)
270
+ Z = Z1 + Z2
271
+ S = safe_divide(R, Z)
272
+ C1 = x1 * self.gradprop(Z1, x1, S)[0]
273
+ C2 = x2 * self.gradprop(Z2, x2, S)[0]
274
+ return C1 + C2
275
+
276
+ activator_relevances = f(pw, nw, px, nx)
277
+ inhibitor_relevances = f(nw, pw, px, nx)
278
+
279
+ R = alpha * activator_relevances - beta * inhibitor_relevances
280
+ return R
281
+
282
+
283
+
284
+ class ConvTranspose2d(nn.ConvTranspose2d, RelProp):
285
+ def relprop(self, R, alpha=1):
286
+ pw = torch.clamp(self.weight, min=0)
287
+ px = torch.clamp(self.X, min=0)
288
+
289
+ def f(w1, x1):
290
+ Z1 = F.conv_transpose2d(x1, w1, bias=None, stride=self.stride, padding=self.padding,
291
+ output_padding=self.output_padding)
292
+ S1 = safe_divide(R, Z1)
293
+ C1 = x1 * self.gradprop(Z1, x1, S1)[0]
294
+ return C1
295
+
296
+ activator_relevances = f(pw, px)
297
+ R = activator_relevances
298
+ return R
299
+
300
+
301
+
302
+ if __name__ == '__main__':
303
+ convt = ConvTranspose2d(100, 50, kernel_size=3, stride=2, padding=1, output_padding=1, bias=False).cuda()
304
+
305
+ rand = torch.rand((1, 100, 224, 224)).cuda()
306
+ out = convt(rand)
307
+ rel = convt.relprop(out)
308
+
309
+ print(out.shape)
experimental/SimFeatUp/featup/featurizers/modules/resnet.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import torch.nn.functional as F
3
+ import torch.utils.model_zoo as model_zoo
4
+
5
+ from featup.featurizers.modules.layers import *
6
+ import torch
7
+
8
+ __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
9
+ 'resnet152']
10
+
11
+ model_urls = {
12
+ 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
13
+ 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
14
+ 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
15
+ 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
16
+ 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
17
+ }
18
+
19
+
20
+ def conv3x3(in_planes, out_planes, stride=1):
21
+ """3x3 convolution with padding"""
22
+ return Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
23
+ padding=1, bias=False)
24
+
25
+
26
+ def conv1x1(in_planes, out_planes, stride=1):
27
+ """1x1 convolution"""
28
+ return Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
29
+
30
+
31
+ class BasicBlock(nn.Module):
32
+ expansion = 1
33
+
34
+ def __init__(self, inplanes, planes, stride=1, downsample=None):
35
+ super(BasicBlock, self).__init__()
36
+ self.clone = Clone()
37
+
38
+ self.conv1 = conv3x3(inplanes, planes, stride)
39
+ self.bn1 = BatchNorm2d(planes)
40
+ self.conv2 = conv3x3(planes, planes)
41
+ self.bn2 = BatchNorm2d(planes)
42
+ self.downsample = downsample
43
+ self.stride = stride
44
+
45
+ self.relu1 = ReLU(inplace=True)
46
+ self.relu2 = ReLU(inplace=True)
47
+
48
+ self.add = Add()
49
+
50
+ self.register_forward_hook(forward_hook)
51
+
52
+ def forward(self, x):
53
+ x1, x2 = self.clone(x, 2)
54
+
55
+ out = self.conv1(x1)
56
+ out = self.bn1(out)
57
+ out = self.relu1(out)
58
+
59
+ out = self.conv2(out)
60
+ out = self.bn2(out)
61
+
62
+ if self.downsample is not None:
63
+ x2 = self.downsample(x2)
64
+
65
+ out = self.add([out, x2])
66
+ out = self.relu2(out)
67
+
68
+ return out
69
+
70
+ def relprop(self, R, alpha):
71
+ out = self.relu2.relprop(R, alpha)
72
+ out, x2 = self.add.relprop(out, alpha)
73
+
74
+ if self.downsample is not None:
75
+ x2 = self.downsample.relprop(x2, alpha)
76
+
77
+ out = self.bn2.relprop(out, alpha)
78
+ out = self.conv2.relprop(out, alpha)
79
+
80
+ out = self.relu1.relprop(out, alpha)
81
+ out = self.bn1.relprop(out, alpha)
82
+ x1 = self.conv1.relprop(out, alpha)
83
+
84
+ return self.clone.relprop([x1, x2], alpha)
85
+
86
+
87
+ class Bottleneck(nn.Module):
88
+ expansion = 4
89
+
90
+ def __init__(self, inplanes, planes, stride=1, downsample=None):
91
+ super(Bottleneck, self).__init__()
92
+
93
+ self.conv1 = conv1x1(inplanes, planes)
94
+ self.bn1 = BatchNorm2d(planes)
95
+ self.conv2 = conv3x3(planes, planes, stride)
96
+ self.bn2 = BatchNorm2d(planes)
97
+ self.conv3 = conv1x1(planes, planes * self.expansion)
98
+ self.bn3 = BatchNorm2d(planes * self.expansion)
99
+ self.downsample = downsample
100
+ self.stride = stride
101
+
102
+ self.relu1 = ReLU(inplace=True)
103
+ self.relu2 = ReLU(inplace=True)
104
+ self.relu3 = ReLU(inplace=True)
105
+
106
+ self.add = Add()
107
+
108
+ self.register_forward_hook(forward_hook)
109
+
110
+ def forward(self, x):
111
+
112
+ out = self.conv1(x)
113
+ out = self.bn1(out)
114
+ out = self.relu1(out)
115
+
116
+ out = self.conv2(out)
117
+ out = self.bn2(out)
118
+ out = self.relu2(out)
119
+
120
+ out = self.conv3(out)
121
+ out = self.bn3(out)
122
+
123
+ if self.downsample is not None:
124
+ x = self.downsample(x)
125
+
126
+ out = self.add([out, x])
127
+ out = self.relu3(out)
128
+
129
+ return out
130
+
131
+ def relprop(self, R, alpha):
132
+ out = self.relu3.relprop(R, alpha)
133
+
134
+ out, x = self.add.relprop(out, alpha)
135
+
136
+ if self.downsample is not None:
137
+ x = self.downsample.relprop(x, alpha)
138
+
139
+ out = self.bn3.relprop(out, alpha)
140
+ out = self.conv3.relprop(out, alpha)
141
+
142
+ out = self.relu2.relprop(out, alpha)
143
+ out = self.bn2.relprop(out, alpha)
144
+ out = self.conv2.relprop(out, alpha)
145
+
146
+ out = self.relu1.relprop(out, alpha)
147
+ out = self.bn1.relprop(out, alpha)
148
+ x1 = self.conv1.relprop(out, alpha)
149
+
150
+ return x1 + x
151
+
152
+
153
+ class ResNet(nn.Module):
154
+
155
+ def __init__(self, block, layers, num_classes=1000, long=False, zero_init_residual=False):
156
+ super(ResNet, self).__init__()
157
+ self.inplanes = 64
158
+ self.conv1 = Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
159
+ self.bn1 = BatchNorm2d(64)
160
+ self.relu = ReLU(inplace=True)
161
+ self.maxpool = MaxPool2d(kernel_size=3, stride=2, padding=1)
162
+ self.layer1 = self._make_layer(block, 64, layers[0])
163
+ self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
164
+ self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
165
+ self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
166
+ self.avgpool = AdaptiveAvgPool2d((1, 1))
167
+ self.fc = Linear(512 * block.expansion, num_classes)
168
+ self.long = long
169
+ self.num_classes = num_classes
170
+
171
+ for m in self.modules():
172
+ if isinstance(m, nn.Conv2d):
173
+ nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
174
+ elif isinstance(m, nn.BatchNorm2d):
175
+ nn.init.constant_(m.weight, 1)
176
+ nn.init.constant_(m.bias, 0)
177
+
178
+ # Zero-initialize the last BN in each residual branch,
179
+ # so that the residual branch starts with zeros, and each residual block behaves like an identity.
180
+ # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
181
+ if zero_init_residual:
182
+ for m in self.modules():
183
+ if isinstance(m, Bottleneck):
184
+ nn.init.constant_(m.bn3.weight, 0)
185
+ elif isinstance(m, BasicBlock):
186
+ nn.init.constant_(m.bn2.weight, 0)
187
+
188
+ def _make_layer(self, block, planes, blocks, stride=1):
189
+ downsample = None
190
+ if stride != 1 or self.inplanes != planes * block.expansion:
191
+ downsample = Sequential(
192
+ conv1x1(self.inplanes, planes * block.expansion, stride),
193
+ BatchNorm2d(planes * block.expansion),
194
+ )
195
+
196
+ layers = []
197
+ layers.append(block(self.inplanes, planes, stride, downsample))
198
+ self.inplanes = planes * block.expansion
199
+ for _ in range(1, blocks):
200
+ layers.append(block(self.inplanes, planes))
201
+
202
+ return Sequential(*layers)
203
+
204
+ def CLRP(self, x):
205
+ maxindex = torch.argmax(x, dim=1)
206
+ R = torch.ones(x.shape, device=x.device)
207
+ R /= -self.num_classes
208
+ for i in range(R.size(0)):
209
+ R[i, maxindex[i]] = 1
210
+ return R
211
+
212
+ def forward(self, img):
213
+ x = self.conv1(img)
214
+ x = self.bn1(x)
215
+ x = self.relu(x)
216
+ x = self.maxpool(x)
217
+ layer1 = self.layer1(x)
218
+ layer2 = self.layer2(layer1)
219
+ layer3 = self.layer3(layer2)
220
+ layer4 = self.layer4(layer3)
221
+
222
+ x = self.avgpool(layer4)
223
+ x = x.view(x.size(0), -1)
224
+ return self.fc(x)
225
+
226
+ def get_layer(self, img, layer_num):
227
+ x = self.conv1(img)
228
+ x = self.bn1(x)
229
+ x = self.relu(x)
230
+ x = self.maxpool(x)
231
+ layer1 = self.layer1(x)
232
+ if layer_num == 1:
233
+ return layer1
234
+ layer2 = self.layer2(layer1)
235
+ if layer_num == 2:
236
+ return layer2
237
+ layer3 = self.layer3(layer2)
238
+ if layer_num == 3:
239
+ return layer3
240
+ layer4 = self.layer4(layer3)
241
+ if layer_num == 4 or layer_num == -1:
242
+ return layer4
243
+ if isinstance(layer_num, tuple):
244
+ return [[layer1, layer2, layer3, layer4][i-1] for i in layer_num]
245
+
246
+ raise ValueError(f"Unknown layer num: {layer_num}")
247
+
248
+ def relevance_cam(self, large_img, layer_num, upsampler):
249
+ small_img = F.interpolate(large_img, size=(224, 224), mode='bilinear')
250
+ layer1, layer2, layer3, layer4 = self.get_layer(small_img, (1, 2, 3, 4))
251
+ x = self.avgpool(layer4)
252
+ x = x.view(x.size(0), -1)
253
+ z = self.fc(x)
254
+
255
+ R = self.CLRP(z)
256
+ R = self.fc.relprop(R, 1)
257
+ R = R.reshape_as(self.avgpool.Y)
258
+ R4 = self.avgpool.relprop(R, 1)
259
+
260
+ if layer_num == 4:
261
+ r_weight4 = torch.mean(R4, dim=(2, 3), keepdim=True)
262
+ r_cam4 = upsampler(large_img, source=layer4) * r_weight4
263
+ r_cam4 = torch.sum(r_cam4, dim=(1), keepdim=True)
264
+ return r_cam4
265
+ elif layer_num == 3:
266
+ R3 = self.layer4.relprop(R4, 1)
267
+ r_weight3 = torch.mean(R3, dim=(2, 3), keepdim=True)
268
+ r_cam3 = upsampler(large_img, source=layer3) * r_weight3
269
+ r_cam3 = torch.sum(r_cam3, dim=(1), keepdim=True)
270
+ return r_cam3
271
+ elif layer_num == 2:
272
+ R3 = self.layer4.relprop(R4, 1)
273
+ R2 = self.layer3.relprop(R3, 1)
274
+ r_weight2 = torch.mean(R2, dim=(2, 3), keepdim=True)
275
+ r_cam2 = upsampler(large_img, source=layer2) * r_weight2
276
+ r_cam2 = torch.sum(r_cam2, dim=(1), keepdim=True)
277
+ return r_cam2
278
+ else:
279
+ raise ValueError(f"Unknown layer_num: {layer_num}")
280
+
281
+
282
+ def resnet18(pretrained=False, **kwargs):
283
+ """Constructs a ResNet-18 model.
284
+
285
+ Args:
286
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
287
+ """
288
+ model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
289
+ if pretrained:
290
+ model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))
291
+ return model
292
+
293
+
294
+ def resnet34(pretrained=False, **kwargs):
295
+ """Constructs a ResNet-34 model.
296
+
297
+ Args:
298
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
299
+ """
300
+ model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
301
+ if pretrained:
302
+ model.load_state_dict(model_zoo.load_url(model_urls['resnet34']))
303
+ return model
304
+
305
+
306
+ def resnet50(pretrained=False, long=False, **kwargs):
307
+ """Constructs a ResNet-50 model.
308
+
309
+ Args:
310
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
311
+ """
312
+ model = ResNet(Bottleneck, [3, 4, 6, 3], long=long, **kwargs)
313
+ if pretrained:
314
+ model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
315
+ return model
316
+
317
+
318
+ def resnet101(pretrained=False, **kwargs):
319
+ """Constructs a ResNet-101 model.
320
+
321
+ Args:
322
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
323
+ """
324
+ model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
325
+ if pretrained:
326
+ model.load_state_dict(model_zoo.load_url(model_urls['resnet101']))
327
+ return model
328
+
329
+
330
+ def resnet152(pretrained=False, **kwargs):
331
+ """Constructs a ResNet-152 model.
332
+
333
+ Args:
334
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
335
+ """
336
+ model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
337
+ if pretrained:
338
+ model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))
339
+ return model
experimental/SimFeatUp/featup/featurizers/modules/vgg.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ import torch.utils.model_zoo as model_zoo
5
+ import torch
6
+ from featup.featurizers.modules.layers import *
7
+
8
+ __all__ = [
9
+ 'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn',
10
+ 'vgg19_bn', 'vgg19',
11
+ ]
12
+
13
+
14
+ model_urls = {
15
+ 'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
16
+ 'vgg13': 'https://download.pytorch.org/models/vgg13-c768596a.pth',
17
+ 'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth',
18
+ 'vgg19': 'https://download.pytorch.org/models/vgg19-dcbb9e9d.pth',
19
+ 'vgg11_bn': 'https://download.pytorch.org/models/vgg11_bn-6002323d.pth',
20
+ 'vgg13_bn': 'https://download.pytorch.org/models/vgg13_bn-abd245e5.pth',
21
+ 'vgg16_bn': 'https://download.pytorch.org/models/vgg16_bn-6c64b313.pth',
22
+ 'vgg19_bn': 'https://download.pytorch.org/models/vgg19_bn-c79401a0.pth',
23
+ }
24
+
25
+ class VGG_spread(nn.Module):
26
+
27
+ def __init__(self, features, num_classes=1000, init_weights=True):
28
+ super(VGG_spread, self).__init__()
29
+ self.features = features
30
+ self.avgpool = AdaptiveAvgPool2d((7, 7))
31
+ self.classifier = Sequential(
32
+ Linear(512 * 7 * 7, 4096),
33
+ ReLU(True),
34
+ Dropout(),
35
+ Linear(4096, 4096),
36
+ ReLU(True),
37
+ Dropout(),
38
+ Linear(4096, num_classes),
39
+ )
40
+ if init_weights:
41
+ self._initialize_weights()
42
+
43
+ def forward(self, x):
44
+ for layer in self.features:
45
+ x = layer(x)
46
+ x = self.avgpool(x)
47
+ x = x.view(x.size(0), -1)
48
+ x = self.classifier(x)
49
+ return x
50
+
51
+ def relprop(self, R, alpha):
52
+ x = self.classifier.relprop(R, alpha)
53
+ x = x.reshape_as(next(reversed(self.features._modules.values())).Y)
54
+ x = self.avgpool.relprop(x, alpha)
55
+ x = self.features.relprop(x, alpha)
56
+ return x
57
+
58
+ def m_relprop(self, R, pred, alpha):
59
+ x = self.classifier.m_relprop(R, pred, alpha)
60
+ if torch.is_tensor(x) == False:
61
+ for i in range(len(x)):
62
+ x[i] = x[i].reshape_as(next(reversed(self.features._modules.values())).Y)
63
+ else:
64
+ x = x.reshape_as(next(reversed(self.features._modules.values())).Y)
65
+ x = self.avgpool.m_relprop(x, pred, alpha)
66
+ x = self.features.m_relprop(x, pred, alpha)
67
+ return x
68
+
69
+ def RAP_relprop(self, R):
70
+ x1 = self.classifier.RAP_relprop(R)
71
+ if torch.is_tensor(x1) == False:
72
+ for i in range(len(x1)):
73
+ x1[i] = x1[i].reshape_as(next(reversed(self.features._modules.values())).Y)
74
+ else:
75
+ x1 = x1.reshape_as(next(reversed(self.features._modules.values())).Y)
76
+ x1 = self.avgpool.RAP_relprop(x1)
77
+ x1 = self.features.RAP_relprop(x1)
78
+ return x1
79
+
80
+ def _initialize_weights(self):
81
+ for m in self.modules():
82
+ if isinstance(m, nn.Conv2d):
83
+ nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
84
+ if m.bias is not None:
85
+ nn.init.constant_(m.bias, 0)
86
+ elif isinstance(m, nn.BatchNorm2d):
87
+ nn.init.constant_(m.weight, 1)
88
+ nn.init.constant_(m.bias, 0)
89
+ elif isinstance(m, nn.Linear):
90
+ nn.init.normal_(m.weight, 0, 0.01)
91
+ nn.init.constant_(m.bias, 0)
92
+
93
+
94
+ class VGG(nn.Module):
95
+
96
+ def __init__(self, features, num_classes=1000, init_weights=True):
97
+ super(VGG, self).__init__()
98
+ self.features = features
99
+ self.avgpool = AdaptiveAvgPool2d((7, 7))
100
+ self.classifier = Sequential(
101
+ Linear(512 * 7 * 7, 4096),
102
+ ReLU(True),
103
+ Dropout(),
104
+ Linear(4096, 4096),
105
+ ReLU(True),
106
+ Dropout(),
107
+ Linear(4096, num_classes),
108
+ )
109
+ self.num_classes = num_classes
110
+ if init_weights:
111
+ self._initialize_weights()
112
+
113
+ def CLRP(self, x, maxindex = [None]):
114
+ if maxindex == [None]:
115
+ maxindex = torch.argmax(x, dim=1)
116
+ R = torch.ones(x.shape, x.device)
117
+ R /= -self.num_classes
118
+ for i in range(R.size(0)):
119
+ R[i, maxindex[i]] = 1
120
+ return R
121
+
122
+ def upsample(self, source, guidance_unscaled, upsampler, scale):
123
+ _, _, H, W = source.shape
124
+ guidance = F.interpolate(guidance_unscaled, size=(H * scale, W * scale), mode='bilinear')
125
+ return upsampler(source, guidance)
126
+
127
+ def forward(self, x,mode='output', target_class = [None], upsampler=None, scale=1):
128
+ inp = copy.deepcopy(x)
129
+ for i, layer in enumerate(self.features):
130
+ x = layer(x)
131
+ if mode.lstrip('-').isnumeric():
132
+ if int(mode) == i:
133
+ target_layer = x
134
+
135
+ x = self.avgpool(x)
136
+ x = x.view(x.size(0), -1)
137
+ x = self.classifier(x)
138
+
139
+ if mode == 'output':
140
+ return x
141
+
142
+ R = self.CLRP(x, target_class)
143
+ R = self.classifier.relprop(R)
144
+ R = R.reshape_as(next(reversed(self.features._modules.values())).Y)
145
+ R = self.avgpool.relprop(R)
146
+
147
+ for i in range(len(self.features)-1, int(mode), -1):
148
+ R = self.features[i].relprop(R)
149
+
150
+ if upsampler is not None:
151
+ target_layer = self.upsample(target_layer, inp, upsampler, scale)
152
+
153
+ r_weight = torch.mean(R, dim=(2, 3), keepdim=True)
154
+ r_cam = target_layer * r_weight
155
+ r_cam = torch.sum(r_cam, dim=(1), keepdim=True)
156
+ return r_cam, x
157
+
158
+
159
+
160
+ def relprop(self, R, alpha, flag=-1):
161
+ x = self.classifier.relprop(R, alpha)
162
+ x = x.reshape_as(next(reversed(self.features._modules.values())).Y)
163
+ x = self.avgpool.relprop(x, alpha)
164
+ # x = self.features.relprop(x, alpha)
165
+ for i in range(43, flag, -1):
166
+ x = self.features[i].relprop(x, alpha)
167
+ return x
168
+
169
+ def m_relprop(self, R, pred, alpha):
170
+ x = self.classifier.m_relprop(R, pred, alpha)
171
+ if torch.is_tensor(x) == False:
172
+ for i in range(len(x)):
173
+ x[i] = x[i].reshape_as(next(reversed(self.features._modules.values())).Y)
174
+ else:
175
+ x = x.reshape_as(next(reversed(self.features._modules.values())).Y)
176
+ x = self.avgpool.m_relprop(x, pred, alpha)
177
+ x = self.features.m_relprop(x, pred, alpha)
178
+ return x
179
+
180
+ def RAP_relprop(self, R):
181
+ x1 = self.classifier.RAP_relprop(R)
182
+ if torch.is_tensor(x1) == False:
183
+ for i in range(len(x1)):
184
+ x1[i] = x1[i].reshape_as(next(reversed(self.features._modules.values())).Y)
185
+ else:
186
+ x1 = x1.reshape_as(next(reversed(self.features._modules.values())).Y)
187
+ x1 = self.avgpool.RAP_relprop(x1)
188
+ x1 = self.features.RAP_relprop(x1)
189
+
190
+ return x1
191
+ def _initialize_weights(self):
192
+ for m in self.modules():
193
+ if isinstance(m, nn.Conv2d):
194
+ nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
195
+ if m.bias is not None:
196
+ nn.init.constant_(m.bias, 0)
197
+ elif isinstance(m, nn.BatchNorm2d):
198
+ nn.init.constant_(m.weight, 1)
199
+ nn.init.constant_(m.bias, 0)
200
+ elif isinstance(m, nn.Linear):
201
+ nn.init.normal_(m.weight, 0, 0.01)
202
+ nn.init.constant_(m.bias, 0)
203
+
204
+ def make_layers(cfg, batch_norm=False):
205
+ layers = []
206
+ in_channels = 3
207
+
208
+ for v in cfg:
209
+ if v == 'M':
210
+ layers += [MaxPool2d(kernel_size=2, stride=2)]
211
+ else:
212
+ conv2d = Conv2d(in_channels, v, kernel_size=3, padding=1)
213
+ if batch_norm:
214
+ layers += [conv2d, BatchNorm2d(v), ReLU(inplace=True)]
215
+ else:
216
+ layers += [conv2d, ReLU(inplace=True)]
217
+ in_channels = v
218
+
219
+ return Sequential(*layers)
220
+
221
+ def make_layers_list(cfg, batch_norm=False):
222
+ layers = []
223
+ in_channels = 3
224
+ for v in cfg:
225
+ if v == 'M':
226
+ layers += [MaxPool2d(kernel_size=2, stride=2)]
227
+ else:
228
+ conv2d = Conv2d(in_channels, v, kernel_size=3, padding=1)
229
+ if batch_norm:
230
+ layers += [conv2d, BatchNorm2d(v), ReLU(inplace=True)]
231
+ else:
232
+ layers += [conv2d, ReLU(inplace=True)]
233
+ in_channels = v
234
+ return layers
235
+
236
+
237
+ cfg = {
238
+ 'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
239
+ 'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
240
+ 'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
241
+ 'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
242
+ }
243
+
244
+
245
+ def vgg11(pretrained=False, **kwargs):
246
+ """VGG 11-layer model (configuration "A")
247
+
248
+ Args:
249
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
250
+ """
251
+ if pretrained:
252
+ kwargs['init_weights'] = False
253
+ model = VGG(make_layers(cfg['A']), **kwargs)
254
+ if pretrained:
255
+ model.load_state_dict(model_zoo.load_url(model_urls['vgg11']))
256
+ return model
257
+
258
+
259
+ def vgg11_bn(pretrained=False, **kwargs):
260
+ """VGG 11-layer model (configuration "A") with batch normalization
261
+
262
+ Args:
263
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
264
+ """
265
+ if pretrained:
266
+ kwargs['init_weights'] = False
267
+ model = VGG(make_layers(cfg['A'], batch_norm=True), **kwargs)
268
+ if pretrained:
269
+ model.load_state_dict(model_zoo.load_url(model_urls['vgg11_bn']))
270
+ return model
271
+
272
+
273
+ def vgg13(pretrained=False, **kwargs):
274
+ """VGG 13-layer model (configuration "B")
275
+
276
+ Args:
277
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
278
+ """
279
+ if pretrained:
280
+ kwargs['init_weights'] = False
281
+ model = VGG(make_layers(cfg['B']), **kwargs)
282
+ if pretrained:
283
+ model.load_state_dict(model_zoo.load_url(model_urls['vgg13']))
284
+ return model
285
+
286
+
287
+ def vgg13_bn(pretrained=False, **kwargs):
288
+ """VGG 13-layer model (configuration "B") with batch normalization
289
+
290
+ Args:
291
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
292
+ """
293
+ if pretrained:
294
+ kwargs['init_weights'] = False
295
+ model = VGG(make_layers(cfg['B'], batch_norm=True), **kwargs)
296
+ if pretrained:
297
+ model.load_state_dict(model_zoo.load_url(model_urls['vgg13_bn']))
298
+ return model
299
+
300
+
301
+ def vgg16(pretrained=False, **kwargs):
302
+ """VGG 16-layer model (configuration "D")
303
+
304
+ Args:
305
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
306
+ """
307
+ if pretrained:
308
+ kwargs['init_weights'] = False
309
+ model = VGG(make_layers(cfg['D']), **kwargs)
310
+ if pretrained:
311
+ model.load_state_dict(model_zoo.load_url(model_urls['vgg16']))
312
+ return model
313
+
314
+ def vgg16_spread(pretrained=False, **kwargs):
315
+ """VGG 16-layer model (configuration "D")
316
+
317
+ Args:
318
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
319
+ """
320
+ if pretrained:
321
+ kwargs['init_weights'] = False
322
+ model = VGG_spread(make_layers_list(cfg['D']), **kwargs)
323
+ if pretrained:
324
+ model.load_state_dict(model_zoo.load_url(model_urls['vgg16']))
325
+ return model
326
+
327
+ def vgg16_bn(pretrained=False, **kwargs):
328
+ """VGG 16-layer model (configuration "D") with batch normalization
329
+
330
+ Args:
331
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
332
+ """
333
+ if pretrained:
334
+ kwargs['init_weights'] = False
335
+ model = VGG(make_layers(cfg['D'], batch_norm=True), **kwargs)
336
+ if pretrained:
337
+ model.load_state_dict(model_zoo.load_url(model_urls['vgg16_bn']))
338
+ return model
339
+
340
+
341
+ def vgg19(pretrained=False, **kwargs):
342
+ """VGG 19-layer model (configuration "E")
343
+
344
+ Args:
345
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
346
+ """
347
+ if pretrained:
348
+ kwargs['init_weights'] = False
349
+ model = VGG(make_layers(cfg['E']), **kwargs)
350
+ if pretrained:
351
+ model.load_state_dict(model_zoo.load_url(model_urls['vgg19']))
352
+ return model
353
+
354
+
355
+ def vgg19_bn(pretrained=False, **kwargs):
356
+ """VGG 19-layer model (configuration 'E') with batch normalization
357
+
358
+ Args:
359
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
360
+ """
361
+ if pretrained:
362
+ kwargs['init_weights'] = False
363
+ model = VGG(make_layers(cfg['E'], batch_norm=True), **kwargs)
364
+ if pretrained:
365
+ model.load_state_dict(model_zoo.load_url(model_urls['vgg19_bn']))
366
+ return model
experimental/build_env/declip/download_eva_clip.sh ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # DeCLIP 环境构建脚本
3
+ # 下载 EVA-CLIP、I-JEPA 预训练权重和 COCO 数据集到 /opt/tiger/xiaomoguhzz/
4
+
5
+ set -e
6
+
7
+ # 在任意 cd 之前解析脚本所在目录和项目根目录,避免后续 cd 导致 PROJECT_DIR 错误
8
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
9
+ PROJECT_DIR="$(dirname "$(dirname "${SCRIPT_DIR}")")"
10
+
11
+ BASE_DIR="/opt/tiger/xiaomoguhzz"
12
+ COCO_DIR="${BASE_DIR}/standard_coco"
13
+ IJEPA_DIR="${BASE_DIR}/ijepa"
14
+
15
+ # 创建目录
16
+ mkdir -p "${BASE_DIR}"
17
+ mkdir -p "${COCO_DIR}"
18
+ mkdir -p "${IJEPA_DIR}"
19
+
20
+ echo "================================================"
21
+ echo "DeCLIP 环境构建脚本"
22
+ echo "目标目录: ${BASE_DIR}"
23
+ echo "================================================"
24
+
25
+ # ==================== EVA-CLIP 权重下载 ====================
26
+ echo ""
27
+ echo "[1/4] 下载 EVA-CLIP 预训练权重..."
28
+ echo "------------------------------------------------"
29
+
30
+ if [ -f "${BASE_DIR}/EVA02_CLIP_L_336_psz14_s6B.pt" ]; then
31
+ echo "EVA02_CLIP_L_336_psz14_s6B.pt 已存在,跳过下载"
32
+ else
33
+ echo "正在下载 EVA02_CLIP_L_336_psz14_s6B.pt..."
34
+ huggingface-cli download QuanSun/EVA-CLIP EVA02_CLIP_L_336_psz14_s6B.pt --local-dir "${BASE_DIR}" --local-dir-use-symlinks False
35
+ fi
36
+
37
+ if [ -f "${BASE_DIR}/EVA02_CLIP_B_psz16_s8B.pt" ]; then
38
+ echo "EVA02_CLIP_B_psz16_s8B.pt 已存在,跳过下载"
39
+ else
40
+ echo "正在下载 EVA02_CLIP_B_psz16_s8B.pt..."
41
+ huggingface-cli download QuanSun/EVA-CLIP EVA02_CLIP_B_psz16_s8B.pt --local-dir "${BASE_DIR}" --local-dir-use-symlinks False
42
+ fi
43
+
44
+ echo "EVA-CLIP 权重下载完成!"
45
+
46
+ # ==================== CLIPSelf proposals 权重下载 ====================
47
+ echo ""
48
+ echo "[1.2/4] 下载 CLIPSelf proposals 权重..."
49
+ echo "------------------------------------------------"
50
+
51
+ if [ -f "${BASE_DIR}/fvit_eva_vitb16_ovcoco_clipself_proposals.pth" ]; then
52
+ echo "fvit_eva_vitb16_ovcoco_clipself_proposals.pth 已存在,跳过下载"
53
+ else
54
+ echo "正在下载 fvit_eva_vitb16_ovcoco_clipself_proposals.pth..."
55
+ huggingface-cli download xiaomoguhzz/xiaomogu_pami fvit_eva_vitb16_ovcoco_clipself_proposals.pth --repo-type model --local-dir "${BASE_DIR}"
56
+ fi
57
+
58
+ if [ -f "${BASE_DIR}/fvit_eva_vitl14_ovcoco_clipself_proposals.pth" ]; then
59
+ echo "fvit_eva_vitl14_ovcoco_clipself_proposals.pth 已存在,跳过下载"
60
+ else
61
+ echo "正在下载 fvit_eva_vitl14_ovcoco_clipself_proposals.pth..."
62
+ huggingface-cli download xiaomoguhzz/xiaomogu_pami fvit_eva_vitl14_ovcoco_clipself_proposals.pth --repo-type model --local-dir "${BASE_DIR}"
63
+ fi
64
+
65
+ echo "CLIPSelf proposals 权重下载完成!"
66
+
67
+ # ==================== SAM 权重下载 ====================
68
+ echo ""
69
+ echo "[1.5/4] 下载 SAM 预训练权重..."
70
+ echo "------------------------------------------------"
71
+
72
+ if [ -f "${BASE_DIR}/sam_vit_l_0b3195.pth" ]; then
73
+ echo "sam_vit_l_0b3195.pth 已存在,跳过下载"
74
+ else
75
+ echo "正在下载 SAM-L (约 1.25GB)..."
76
+ wget -c https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth -O "${BASE_DIR}/sam_vit_l_0b3195.pth"
77
+ fi
78
+
79
+ if [ -f "${BASE_DIR}/sam_vit_b_01ec64.pth" ]; then
80
+ echo "sam_vit_b_01ec64.pth 已存在,跳过下载"
81
+ else
82
+ echo "正在下载 SAM-B (约 375MB)..."
83
+ wget -c https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth -O "${BASE_DIR}/sam_vit_b_01ec64.pth"
84
+ fi
85
+
86
+ echo "SAM 权重下载完成!"
87
+
88
+ # ==================== I-JEPA 权重下载 ====================
89
+ echo ""
90
+ echo "[2/4] 下载 I-JEPA 预训练权重..."
91
+ echo "------------------------------------------------"
92
+
93
+ if [ -f "${IJEPA_DIR}/IN1K-vit.h.14-300e.pth.tar" ]; then
94
+ echo "IN1K-vit.h.14-300e.pth.tar 已存在,跳过下载"
95
+ else
96
+ echo "正在下载 I-JEPA ViT-H/14 (224x224, ~9.7GB)..."
97
+ wget -c https://dl.fbaipublicfiles.com/ijepa/IN1K-vit.h.14-300e.pth.tar -O "${IJEPA_DIR}/IN1K-vit.h.14-300e.pth.tar"
98
+ fi
99
+
100
+ if [ -f "${IJEPA_DIR}/IN1K-vit.h.16-448px-300e.pth.tar" ]; then
101
+ echo "IN1K-vit.h.16-448px-300e.pth.tar 已存在,跳过下载"
102
+ else
103
+ echo "正在下载 I-JEPA ViT-H/16 (448x448, ~9.7GB)..."
104
+ 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"
105
+ fi
106
+
107
+ echo "I-JEPA 权重下载完成!"
108
+
109
+ # ==================== COCO 数据集下载 ====================
110
+ echo ""
111
+ echo "[3/4] 下载 COCO 数据集..."
112
+ echo "------------------------------------------------"
113
+
114
+ cd "${COCO_DIR}"
115
+
116
+ # 定义下载函数
117
+ download_and_extract() {
118
+ local url=$1
119
+ local zip_name=$2
120
+ local check_file=$3
121
+
122
+ if [ -f "${check_file}" ] || [ -d "${check_file}" ]; then
123
+ echo "${zip_name} 相关文件已存在,跳过"
124
+ return 0
125
+ fi
126
+
127
+ if [ ! -f "${zip_name}" ]; then
128
+ echo "正在下载 ${zip_name}..."
129
+ wget -c "${url}"
130
+ fi
131
+
132
+ echo "正在解压 ${zip_name}..."
133
+ unzip -o -q "${zip_name}"
134
+ rm -f "${zip_name}"
135
+ }
136
+
137
+ # 检查图像目录是否完整 (train2017 应有 118287 张, val2017 应有 5000 张)
138
+ check_images_exist() {
139
+ local dir=$1
140
+ local min_count=$2
141
+ if [ -d "${dir}" ]; then
142
+ local count=$(ls "${dir}" 2>/dev/null | wc -l)
143
+ if [ "${count}" -ge "${min_count}" ]; then
144
+ return 0
145
+ fi
146
+ fi
147
+ return 1
148
+ }
149
+
150
+ # 下载标注文件
151
+ if [ -f "${COCO_DIR}/annotations/instances_train2017.json" ]; then
152
+ echo "annotations_trainval2017 已存在,跳过"
153
+ else
154
+ download_and_extract "http://images.cocodataset.org/annotations/annotations_trainval2017.zip" "annotations_trainval2017.zip" "${COCO_DIR}/annotations/instances_train2017.json"
155
+ fi
156
+
157
+ if [ -f "${COCO_DIR}/annotations/panoptic_val2017.json" ]; then
158
+ echo "panoptic_annotations 已存在,跳过"
159
+ else
160
+ download_and_extract "http://images.cocodataset.org/annotations/panoptic_annotations_trainval2017.zip" "panoptic_annotations_trainval2017.zip" "${COCO_DIR}/annotations/panoptic_val2017.json"
161
+ # 解压内部的 panoptic 分割图像 zip
162
+ cd "${COCO_DIR}/annotations"
163
+ if [ -f "panoptic_val2017.zip" ]; then
164
+ echo "正在解压 panoptic_val2017.zip..."
165
+ unzip -o -q panoptic_val2017.zip &
166
+ fi
167
+ if [ -f "panoptic_train2017.zip" ]; then
168
+ echo "正在解压 panoptic_train2017.zip..."
169
+ unzip -o -q panoptic_train2017.zip &
170
+ fi
171
+ wait
172
+ rm -f panoptic_val2017.zip panoptic_train2017.zip 2>/dev/null
173
+ cd "${COCO_DIR}"
174
+ fi
175
+
176
+ # 并行下载和解压图像(如果需要)
177
+ NEED_TRAIN=false
178
+ NEED_VAL=false
179
+
180
+ if check_images_exist "${COCO_DIR}/train2017" 100000; then
181
+ echo "train2017 已存在 ($(ls ${COCO_DIR}/train2017 | wc -l) 张图像),跳过"
182
+ else
183
+ NEED_TRAIN=true
184
+ fi
185
+
186
+ if check_images_exist "${COCO_DIR}/val2017" 4000; then
187
+ echo "val2017 已存在 ($(ls ${COCO_DIR}/val2017 | wc -l) 张图像),跳过"
188
+ else
189
+ NEED_VAL=true
190
+ fi
191
+
192
+ # 并行下载
193
+ if [ "${NEED_TRAIN}" = true ] || [ "${NEED_VAL}" = true ]; then
194
+ echo "开始并行下载图像..."
195
+
196
+ if [ "${NEED_TRAIN}" = true ] && [ ! -f "train2017.zip" ]; then
197
+ echo "正在下载 train2017.zip (约 18GB)..."
198
+ wget -c http://images.cocodataset.org/zips/train2017.zip &
199
+ TRAIN_PID=$!
200
+ fi
201
+
202
+ if [ "${NEED_VAL}" = true ] && [ ! -f "val2017.zip" ]; then
203
+ echo "正在下载 val2017.zip (约 1GB)..."
204
+ wget -c http://images.cocodataset.org/zips/val2017.zip &
205
+ VAL_PID=$!
206
+ fi
207
+
208
+ # 等待下载完成
209
+ [ -n "${TRAIN_PID}" ] && wait ${TRAIN_PID}
210
+ [ -n "${VAL_PID}" ] && wait ${VAL_PID}
211
+
212
+ echo "下载完成,开始并行解压..."
213
+
214
+ # 并行解压
215
+ if [ "${NEED_TRAIN}" = true ] && [ -f "train2017.zip" ]; then
216
+ echo "正在解压 train2017.zip..."
217
+ unzip -o -q train2017.zip && rm -f train2017.zip &
218
+ TRAIN_UNZIP_PID=$!
219
+ fi
220
+
221
+ if [ "${NEED_VAL}" = true ] && [ -f "val2017.zip" ]; then
222
+ echo "正在解压 val2017.zip..."
223
+ unzip -o -q val2017.zip && rm -f val2017.zip &
224
+ VAL_UNZIP_PID=$!
225
+ fi
226
+
227
+ # 等待解压完成
228
+ [ -n "${TRAIN_UNZIP_PID}" ] && wait ${TRAIN_UNZIP_PID}
229
+ [ -n "${VAL_UNZIP_PID}" ] && wait ${VAL_UNZIP_PID}
230
+ fi
231
+
232
+ # ==================== 安装依赖和项目 ====================
233
+ echo ""
234
+ echo "[4/4] 安装依赖和 DeCLIP 项目..."
235
+ echo "------------------------------------------------"
236
+
237
+ # 安装 faiss-cpu (用于特征检索和相似度搜索)
238
+ echo "安装 faiss-cpu..."
239
+ pip install faiss-cpu
240
+
241
+ # 安装 panopticapi (COCO Panoptic 数据集处理工具)
242
+ echo "安装 panopticapi..."
243
+ pip install git+https://github.com/cocodataset/panopticapi.git
244
+
245
+ # 安装 tensorboard (训练可视化)
246
+ echo "安装 tensorboard..."
247
+ pip install tensorboard
248
+
249
+ # 安装 torch 和 xformers (需要匹配版本)
250
+ echo "安装 torch==2.6.0+cu124 和 xformers==0.0.29.post2..."
251
+ pip install torch==2.6.0+cu124 torchvision --index-url https://download.pytorch.org/whl/cu124
252
+ pip install xformers==0.0.29.post2
253
+
254
+ # 使用脚本开头已解析的项目根目录(避免因前面 cd 到 COCO_DIR 导致 PROJECT_DIR 变成 /opt/tiger)
255
+ cd "${PROJECT_DIR}"
256
+ echo "项目目录: ${PROJECT_DIR}"
257
+
258
+ # 使用 setup.py 安装项目(包名为 open_clip_torch)
259
+ # 如果 pyproject.toml 存在,先备份
260
+ if [ -f "pyproject.toml" ]; then
261
+ mv pyproject.toml pyproject.toml.bak
262
+ echo "已备份 pyproject.toml"
263
+ fi
264
+
265
+ pip install -e .
266
+ echo "DeCLIP 项目安装完成!(包名: open_clip_torch)"
267
+
268
+ echo ""
269
+ echo "================================================"
270
+ echo "环境构建完成!"
271
+ echo "================================================"
272
+ echo ""
273
+ echo "EVA-CLIP 权重位置:"
274
+ ls -lh "${BASE_DIR}"/EVA02_CLIP_*.pt 2>/dev/null || echo " (未找到权重文件)"
275
+ echo ""
276
+ echo "I-JEPA 权重位置:"
277
+ ls -lh "${IJEPA_DIR}"/*.pth.tar 2>/dev/null || echo " (未找到权重文件)"
278
+ echo ""
279
+ echo "COCO 数据集结构:"
280
+ echo " ${COCO_DIR}/"
281
+ echo " ├── annotations/"
282
+ ls "${COCO_DIR}/annotations/" 2>/dev/null | head -10 | sed 's/^/ │ ├── /'
283
+ echo " ├── train2017/ ($(ls ${COCO_DIR}/train2017 2>/dev/null | wc -l) 张图像)"
284
+ echo " └── val2017/ ($(ls ${COCO_DIR}/val2017 2>/dev/null | wc -l) 张图像)"
experimental/build_env/declip/install_mmcv_mmdet.sh ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # 安装 mmcv-full 1.7.2 和 mmdetection v2.28.1
3
+ # 用于 F-ViT OV-COCO 检测评估
4
+ # 环境要求: PyTorch 2.6.x + CUDA 12.4
5
+
6
+ set -e
7
+
8
+ INSTALL_DIR=/opt/tiger/xiaomoguhzz
9
+
10
+ echo "=========================================="
11
+ echo "Installing mmcv-full 1.7.2 and mmdetection v2.28.1"
12
+ echo "Install directory: ${INSTALL_DIR}"
13
+ echo "=========================================="
14
+
15
+ # Step 1: 安装 mmcv-full 1.7.2 (预编译包)
16
+ echo "Installing mmcv-full 1.7.2 via pip..."
17
+ pip install mmcv-full==1.7.2 -f https://download.openmmlab.com/mmcv/dist/cu124/torch2.6/index.html
18
+
19
+ # Step 2: 安装 mmdetection v2.28.1
20
+ cd ${INSTALL_DIR}
21
+
22
+ if [ -d "mmdetection" ]; then
23
+ echo "mmdetection directory exists, skipping clone..."
24
+ else
25
+ echo "Cloning mmdetection..."
26
+ git clone https://github.com/open-mmlab/mmdetection.git
27
+ fi
28
+
29
+ cd mmdetection
30
+ git checkout v2.28.1
31
+
32
+ echo "Installing mmdetection..."
33
+ pip install -e . -v
34
+
35
+ echo "=========================================="
36
+ echo "Installation complete!"
37
+ echo "mmcv-full: 1.7.2 (pip installed)"
38
+ echo "mmdetection: ${INSTALL_DIR}/mmdetection"
39
+ echo "=========================================="
40
+
41
+ # Step 3: 应用 PyTorch 2.6.0 兼容性修复
42
+ echo ""
43
+ echo "Applying PyTorch 2.6.0 compatibility fix..."
44
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
45
+ if [ -f "${SCRIPT_DIR}/../fix_mmcv_pytorch26.sh" ]; then
46
+ bash "${SCRIPT_DIR}/../fix_mmcv_pytorch26.sh"
47
+ else
48
+ echo "Warning: fix_mmcv_pytorch26.sh not found, skipping compatibility fix"
49
+ echo "If you encounter '_use_replicated_tensor_module' errors, run:"
50
+ echo " bash ${SCRIPT_DIR}/../fix_mmcv_pytorch26.sh"
51
+ fi
52
+
53
+ echo ""
54
+ echo "=========================================="
55
+ echo "Installation and fixes complete!"
56
+ echo "=========================================="
57
+
58
+ # 验证安装
59
+ echo "Verifying installation..."
60
+ python -c "from mmcv.ops import nms; print('CUDA ops OK'); import mmcv; print(f'mmcv version: {mmcv.__version__}')"
61
+ python -c "import mmdet; print(f'mmdet version: {mmdet.__version__}')"
experimental/build_env/declip/requirements_verified.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DeCLIP 验证可行的依赖版本组合
2
+ # 测试环境: Python 3.11, CUDA 12.4
3
+ # 测试日期: 2026-01-18
4
+
5
+ # 核心深度学习框架
6
+ torch==2.6.0+cu124
7
+ torchvision # 需与 torch 版本匹配,pip install torchvision --upgrade
8
+ xformers==0.0.29.post2
9
+ flash-attn==2.8.0.post2
10
+
11
+ # 数值计算
12
+ numpy<2 # scipy/sklearn 需要 numpy 1.x,使用 pip install "numpy<2"
13
+
14
+ # 数据处理和评估
15
+ faiss-cpu
16
+ tensorboard
17
+ panopticapi @ git+https://github.com/cocodataset/panopticapi.git
18
+
19
+ # 注意事项:
20
+ # 1. xformers 和 flash-attn 版本需要匹配,否则会报错:
21
+ # - xformers 0.0.32.post1 要求 flash-attn >=2.7.1,<=2.8.2
22
+ # - xformers 0.0.29.post2 兼容 flash-attn 2.8.0.post2
23
+ # 2. numpy 2.x 与 scipy/sklearn 不兼容,需降级到 numpy<2
24
+ # 3. 安装项目本身: pip install -e . --no-deps (在项目根目录执行)
experimental/build_env/fix_mmcv_pytorch26.sh ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # mmcv-full 1.7.2 与 PyTorch 2.6.0 兼容性修复脚本
3
+ #
4
+ # 问题:MMDistributedDataParallel 缺少 _use_replicated_tensor_module 属性检查
5
+ # 解决:添加 hasattr 检查,确保兼容性
6
+ #
7
+ # 使用方法:
8
+ # bash fix_mmcv_pytorch26.sh
9
+
10
+ set -e
11
+
12
+ echo "========================================"
13
+ echo "mmcv-full 1.7.2 PyTorch 2.6.0 兼容性修复"
14
+ echo "========================================"
15
+ echo ""
16
+
17
+ # 1. 查找 mmcv 安装路径
18
+ echo "[1/4] 查找 mmcv 安装路径..."
19
+ MMCV_FILE=$(python3 -c "from mmcv.parallel import MMDistributedDataParallel; import inspect; print(inspect.getfile(MMDistributedDataParallel))" 2>/dev/null)
20
+
21
+ if [ -z "$MMCV_FILE" ]; then
22
+ echo "❌ 错误:无法找到 mmcv 安装路径"
23
+ echo "请确保已安装 mmcv-full"
24
+ exit 1
25
+ fi
26
+
27
+ echo "✓ 找到 mmcv distributed.py:"
28
+ echo " $MMCV_FILE"
29
+ echo ""
30
+
31
+ # 2. 备份原文件
32
+ echo "[2/4] 备份原文件..."
33
+ if [ -f "${MMCV_FILE}.bak" ]; then
34
+ echo "✓ 备份文件已存在,跳过备份"
35
+ else
36
+ cp "$MMCV_FILE" "${MMCV_FILE}.bak"
37
+ echo "✓ 备份完成:${MMCV_FILE}.bak"
38
+ fi
39
+ echo ""
40
+
41
+ # 3. 应用修复
42
+ echo "[3/4] 应用修复..."
43
+ python3 << EOF
44
+ import sys
45
+
46
+ file_path = "$MMCV_FILE"
47
+
48
+ # 读取文件
49
+ with open(file_path, 'r') as f:
50
+ lines = f.readlines()
51
+
52
+ # 检查是否需要修复
53
+ if len(lines) <= 160:
54
+ print("❌ 错误:文件行数不足,无法修复")
55
+ sys.exit(1)
56
+
57
+ # 检查是否已经修复过
58
+ if 'hasattr(self, ' in lines[160]:
59
+ print("✓ 文件已经修复过,无需重复修复")
60
+ sys.exit(0)
61
+
62
+ # 检查第160行是否包含需要修复的代码
63
+ if 'self._use_replicated_tensor_module' not in lines[160]:
64
+ print("❌ 警告:第160行代码与预期不符")
65
+ print("当前第160行内容:")
66
+ print(lines[160])
67
+ print("\n可能 mmcv 版本不匹配,请手动检查")
68
+ sys.exit(1)
69
+
70
+ # 应用修复
71
+ lines[160] = " (hasattr(self, '_use_replicated_tensor_module') and self._use_replicated_tensor_module) else self.module\n"
72
+
73
+ # 写回文件
74
+ with open(file_path, 'w') as f:
75
+ f.writelines(lines)
76
+
77
+ print("✓ 修复应用成功")
78
+ EOF
79
+
80
+ if [ $? -ne 0 ]; then
81
+ echo ""
82
+ echo "修复失败,请检查上述错误信息"
83
+ exit 1
84
+ fi
85
+ echo ""
86
+
87
+ # 4. 验证修复
88
+ echo "[4/4] 验证修复..."
89
+ echo "修复后的代码(第159-161行):"
90
+ echo "---"
91
+ sed -n '159,161p' "$MMCV_FILE"
92
+ echo "---"
93
+ echo ""
94
+
95
+ # 检查是否包含 hasattr
96
+ if grep -q "hasattr(self, '_use_replicated_tensor_module')" "$MMCV_FILE"; then
97
+ echo "✅ 修复验证成功!"
98
+ echo ""
99
+ echo "========================================"
100
+ echo "修复完成!"
101
+ echo "========================================"
102
+ echo ""
103
+ echo "现在可以正常使用多卡分布式训练/推理了"
104
+ echo ""
105
+ echo "如需恢复原文件,执行:"
106
+ echo " cp ${MMCV_FILE}.bak $MMCV_FILE"
107
+ else
108
+ echo "❌ 修复验证失败"
109
+ echo "文件已修改,但未检测到预期的 hasattr 检查"
110
+ exit 1
111
+ fi
experimental/build_env/fix_mmcv_pytorch26_v2.sh ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # 一键修复 mmcv 与 PyTorch 2.6 兼容问题
3
+ # 修复点:
4
+ # 1) mmcv/parallel/_functions.py: int device -> torch.device
5
+ # 2) (可选) mmcv/parallel/distributed.py: _use_replicated_tensor_module 兼容
6
+
7
+ set -euo pipefail
8
+
9
+ echo "========================================"
10
+ echo "mmcv + PyTorch 2.6 兼容性修复 (v2)"
11
+ echo "========================================"
12
+
13
+ # 1) 定位 mmcv 目录
14
+ MMCV_DIR="$(python3 - <<'PY'
15
+ import os
16
+ import sys
17
+
18
+ def find_mmcv_parallel_path():
19
+ for p in sys.path:
20
+ cand = os.path.join(p, "mmcv", "parallel")
21
+ if os.path.isfile(os.path.join(cand, "_functions.py")):
22
+ return cand
23
+ return ""
24
+
25
+ print(find_mmcv_parallel_path())
26
+ PY
27
+ )"
28
+
29
+ if [[ -z "${MMCV_DIR}" ]]; then
30
+ echo "❌ 无法定位 mmcv 安装路径"
31
+ exit 1
32
+ fi
33
+
34
+ FUNC_FILE="${MMCV_DIR}/_functions.py"
35
+ DIST_FILE="${MMCV_DIR}/distributed.py"
36
+
37
+ echo "[1/4] mmcv 路径:${MMCV_DIR}"
38
+ echo "[2/4] 备份文件..."
39
+
40
+ if [[ -f "${FUNC_FILE}" && ! -f "${FUNC_FILE}.bak" ]]; then
41
+ cp "${FUNC_FILE}" "${FUNC_FILE}.bak"
42
+ fi
43
+ if [[ -f "${DIST_FILE}" && ! -f "${DIST_FILE}.bak" ]]; then
44
+ cp "${DIST_FILE}" "${DIST_FILE}.bak"
45
+ fi
46
+ echo "✓ 备份完成"
47
+
48
+ echo "[3/4] 修复 _functions.py ..."
49
+ python3 - <<PY
50
+ import sys
51
+ import re
52
+
53
+ func_file = "${FUNC_FILE}"
54
+ with open(func_file, "r") as f:
55
+ lines = f.readlines()
56
+
57
+ patched = False
58
+ def _child_indent(idx):
59
+ j = idx - 1
60
+ while j >= 0 and lines[j].strip() == "":
61
+ j -= 1
62
+ while j >= 0 and not lines[j].rstrip().endswith(":"):
63
+ j -= 1
64
+ if j >= 0:
65
+ base = re.match(r"^\\s*", lines[j]).group(0)
66
+ return base + ("\\t" if "\\t" in base else " ")
67
+ return " "
68
+
69
+ def _replace_line(idx):
70
+ indent = _child_indent(idx)
71
+ lines[idx] = (indent
72
+ + "streams = [_get_stream(torch.device('cuda', d) if isinstance(d, int) else d) "
73
+ + "for d in target_gpus]\\n")
74
+ return True
75
+
76
+ for i, line in enumerate(lines):
77
+ if "streams" in line and "_get_stream" in line and "target_gpus" in line:
78
+ patched = _replace_line(i)
79
+ break
80
+
81
+ if not patched:
82
+ for i, line in enumerate(lines):
83
+ if "if torch.cuda.is_available()" in line and "target_gpus" in line:
84
+ j = i + 1
85
+ while j < len(lines) and lines[j].strip() == "":
86
+ j += 1
87
+ if j < len(lines):
88
+ patched = _replace_line(j)
89
+ break
90
+
91
+ if not patched:
92
+ print("❌ 未找到可替换的 streams 行,请手动检查 _functions.py")
93
+ sys.exit(1)
94
+
95
+ if not any(l.strip().startswith("import torch") for l in lines):
96
+ lines.insert(0, "import torch\\n")
97
+
98
+ with open(func_file, "w") as f:
99
+ f.writelines(lines)
100
+
101
+ print("✓ _functions.py 修复完成")
102
+ PY
103
+
104
+ echo "[4/4] (可选) 修复 distributed.py ..."
105
+ python3 - <<PY
106
+ dist_file = "${DIST_FILE}"
107
+ with open(dist_file, "r") as f:
108
+ lines = f.readlines()
109
+
110
+ if any("hasattr(self, '_use_replicated_tensor_module')" in l for l in lines):
111
+ print("✓ distributed.py 已修复过,跳过")
112
+ raise SystemExit(0)
113
+
114
+ patched = False
115
+ for i, line in enumerate(lines):
116
+ if "module_to_run" in line and "_replicated_tensor_module" in line and line.rstrip().endswith("\\\\"):
117
+ # 兼容下一行是 self._use_replicated_tensor_module 的写法
118
+ if i + 1 < len(lines) and "self._use_replicated_tensor_module" in lines[i + 1]:
119
+ lines[i] = " module_to_run = self._replicated_tensor_module if \\\\\\n"
120
+ lines[i + 1] = (" (hasattr(self, '_use_replicated_tensor_module') "
121
+ "and self._use_replicated_tensor_module) else self.module\\n")
122
+ patched = True
123
+ break
124
+ if "module_to_run" in line and "self._use_replicated_tensor_module" in line:
125
+ lines[i] = " module_to_run = self._replicated_tensor_module if \\\\\\n"
126
+ lines[i + 1] = (" (hasattr(self, '_use_replicated_tensor_module') "
127
+ "and self._use_replicated_tensor_module) else self.module\\n")
128
+ patched = True
129
+ break
130
+
131
+ if patched:
132
+ with open(dist_file, "w") as f:
133
+ f.writelines(lines)
134
+ print("✓ distributed.py 修复完成")
135
+ else:
136
+ print("⚠ distributed.py 未找到目标行,跳过")
137
+ PY
138
+
139
+ echo "========================================"
140
+ echo "修复完成"
141
+ echo "如需回滚:"
142
+ echo " cp ${FUNC_FILE}.bak ${FUNC_FILE}"
143
+ echo " cp ${DIST_FILE}.bak ${DIST_FILE}"
144
+ echo "========================================"
experimental/build_env/fix_mmcv_temp.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """临时修复脚本:修复 mmcv distributed.py 的兼容性问题"""
3
+
4
+ file_path = "/home/tiger/.local/lib/python3.11/site-packages/mmcv/parallel/distributed.py"
5
+
6
+ # 读取文件
7
+ with open(file_path, 'r') as f:
8
+ lines = f.readlines()
9
+
10
+ # 修改第160行(索引159)
11
+ if len(lines) > 159 and 'self._use_replicated_tensor_module else self.module' in lines[159]:
12
+ lines[159] = " (hasattr(self, '_use_replicated_tensor_module') and self._use_replicated_tensor_module) else self.module\n"
13
+
14
+ # 写回文件
15
+ with open(file_path, 'w') as f:
16
+ f.writelines(lines)
17
+
18
+ print("✅ 修复完成!")
19
+ print("\n修改后的代码(第159-162行):")
20
+ print(''.join(lines[158:162]))
21
+ else:
22
+ print("❌ 第160行内容不符,当前内容:")
23
+ if len(lines) > 159:
24
+ print(lines[159])
25
+ else:
26
+ print("文件行数不足")
experimental/build_env/mmcv_pytorch26_compatibility_fix.md ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mmcv-full 1.7.2 与 PyTorch 2.6.0 兼容性修复
2
+
3
+ ## 问题描述
4
+
5
+ 在 PyTorch 2.6.0 + CUDA 12.4 环境下使用 mmcv-full 1.7.2 进行多卡分布式推理时,会遇到以下错误:
6
+
7
+ ```
8
+ AttributeError: 'MMDistributedDataParallel' object has no attribute '_use_replicated_tensor_module'
9
+ ```
10
+
11
+ **错误位置**:`/home/tiger/.local/lib/python3.11/site-packages/mmcv/parallel/distributed.py:160`
12
+
13
+ **根本原因**:PyTorch 2.6.0 引入了新的 `_use_replicated_tensor_module` 属性,但 mmcv-full 1.7.2 直接访问该属性而没有检查其是否存在,导致在旧版本 PyTorch 或特定情况下报错。
14
+
15
+ ## 修复方案
16
+
17
+ ### 方法1:修改 mmcv 源码(推荐)
18
+
19
+ 修改 `mmcv/parallel/distributed.py` 文件的第160行,添加 `hasattr` 检查:
20
+
21
+ **修复步骤**:
22
+
23
+ 1. **备份原文件**:
24
+ ```bash
25
+ cp /home/tiger/.local/lib/python3.11/site-packages/mmcv/parallel/distributed.py \
26
+ /home/tiger/.local/lib/python3.11/site-packages/mmcv/parallel/distributed.py.bak
27
+ ```
28
+
29
+ 2. **执行修复脚本**:
30
+ ```bash
31
+ python3 << 'EOF'
32
+ file_path = "/home/tiger/.local/lib/python3.11/site-packages/mmcv/parallel/distributed.py"
33
+
34
+ # 从备份恢复(如果需要)
35
+ import shutil
36
+ import os
37
+ if os.path.exists(file_path + ".bak"):
38
+ shutil.copy(file_path + ".bak", file_path)
39
+
40
+ # 读取文件
41
+ with open(file_path, 'r') as f:
42
+ lines = f.readlines()
43
+
44
+ # 修改第159-160行(索引从0开始是158-159)
45
+ # 原始代码:
46
+ # module_to_run = self._replicated_tensor_module if \
47
+ # self._use_replicated_tensor_module else self.module
48
+ #
49
+ # 修改为:
50
+ lines[159] = " module_to_run = self._replicated_tensor_module if \\\n"
51
+ lines[160] = " (hasattr(self, '_use_replicated_tensor_module') and self._use_replicated_tensor_module) else self.module\n"
52
+
53
+ # 写回文件
54
+ with open(file_path, 'w') as f:
55
+ f.writelines(lines)
56
+
57
+ print("✅ 修复完成!")
58
+ print("\n修改后的代码(第159-161行):")
59
+ print(''.join(lines[158:162]))
60
+ EOF
61
+ ```
62
+
63
+ 3. **验证修复**:
64
+ ```bash
65
+ sed -n '159,161p' /home/tiger/.local/lib/python3.11/site-packages/mmcv/parallel/distributed.py
66
+ ```
67
+
68
+ 期望输出:
69
+ ```python
70
+ module_to_run = self._replicated_tensor_module if \
71
+ (hasattr(self, '_use_replicated_tensor_module') and self._use_replicated_tensor_module) else self.module
72
+
73
+ ```
74
+
75
+ ### 方法2:降级 PyTorch(不推荐)
76
+
77
+ 降级到 PyTorch 2.1.x 或 2.2.x,但会失去新版本的功能和性能优化。
78
+
79
+ ## 补充:PyTorch 2.6 + mmcv 1.7.2 的 Scatter 兼容问题
80
+
81
+ ### 问题描述
82
+
83
+ 在多卡训练/推理时,可能出现以下错误(来自 `mmcv/parallel/_functions.py`):
84
+
85
+ ```
86
+ AttributeError: 'int' object has no attribute 'type'
87
+ ```
88
+
89
+ 该问题的根因是 `_get_stream` 在 PyTorch 2.6 中期望 `torch.device`,
90
+ 但 mmcv 传入的是 int 类型的 GPU id。
91
+
92
+ ### 一键修复脚本(推荐)
93
+
94
+ 运行仓库内脚本:
95
+
96
+ ```bash
97
+ bash /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/build_env/fix_mmcv_pytorch26_v2.sh
98
+ ```
99
+
100
+ 该脚本会:
101
+
102
+ - 自动定位 `mmcv/parallel/_functions.py`
103
+ - 备份原文件(`.bak`)
104
+ - 将 `streams = [_get_stream(device) for device in target_gpus]`
105
+ 修改为兼容 PyTorch 2.6 的 `torch.device` 写法
106
+ - 可选修复 `distributed.py` 中 `_use_replicated_tensor_module` 的兼容问题
107
+
108
+ ### 手工修复要点(仅供参考)
109
+
110
+ 目标代码片段应类似:
111
+
112
+ ```python
113
+ streams = [
114
+ _get_stream(torch.device('cuda', d) if isinstance(d, int) else d)
115
+ for d in target_gpus
116
+ ]
117
+ ```
118
+
119
+ ## 修复验证
120
+
121
+ 修复后,运行多卡推理脚本应该正常工作:
122
+
123
+ ```bash
124
+ cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/failure_case_analysis/scripts
125
+ bash run_inference.sh 0 8
126
+ ```
127
+
128
+ ## 相关问题记录
129
+
130
+ - **日期**:2026-01-24
131
+ - **环境**:PyTorch 2.6.0+cu124, mmcv-full 1.7.2, CUDA 12.4
132
+ - **影响范围**:所有使用 `MMDistributedDataParallel` 的多卡分布式训练/推理代码
133
+ - **修复状态**:已修复并验证
134
+
135
+ ## 参考资料
136
+
137
+ - mmcv GitHub Issue: https://github.com/open-mmlab/mmcv/issues
138
+ - PyTorch 2.6.0 Release Notes: https://github.com/pytorch/pytorch/releases/tag/v2.6.0
139
+ - mmcv 兼容性说明: https://github.com/open-mmlab/mmcv/blob/master/docs/en/compatibility.md
140
+
141
+ ## 注意事项
142
+
143
+ 1. 该修复是临时方案,建议长期使用 mmcv 2.x 版本以获得更好的兼容性
144
+ 2. 如果重新安装 mmcv-full,需要重新应用此修复
145
+ 3. 修复后的代码保持向后兼容,不影响旧版本 PyTorch 的使用
experimental/build_env/proxyclip/README.md ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ProxyCLIP Environment Setup
2
+
3
+ This directory contains scripts to set up the ProxyCLIP semantic segmentation environment.
4
+
5
+ ## Quick Start
6
+
7
+ ```bash
8
+ # 1. Setup environment (one-time)
9
+ bash setup_env.sh
10
+
11
+ # 2. Activate environment
12
+ source activate.sh
13
+
14
+ # 3. Download datasets (optional, can select specific ones)
15
+ bash download_datasets.sh
16
+
17
+ # 4. Run evaluation
18
+ cd ../../ProxyCLIP
19
+ python eval.py --config ./configs/cfg_voc20.py
20
+ ```
21
+
22
+ ## Environment Details
23
+
24
+ The environment includes:
25
+ - Python 3.10
26
+ - PyTorch 2.6.0 + CUDA 12.4
27
+ - mmcv 2.1.0
28
+ - mmengine 0.10.4
29
+ - mmdet 3.3.0
30
+ - mmsegmentation 1.2.2
31
+
32
+ ## Scripts
33
+
34
+ | Script | Description |
35
+ |--------|-------------|
36
+ | `setup_env.sh` | Creates uv virtual environment and installs all dependencies |
37
+ | `activate.sh` | Activates the virtual environment |
38
+ | `download_datasets.sh` | Downloads semantic segmentation datasets |
39
+ | `setup_data_paths.py` | Helps configure data paths in config files |
40
+ | `requirements.txt` | Python dependencies |
41
+
42
+ ## Datasets
43
+
44
+ The following 8 datasets are supported:
45
+
46
+ | Dataset | Size | Notes |
47
+ |---------|------|-------|
48
+ | Pascal VOC 2012 | ~2GB | Automatic download |
49
+ | Pascal Context | ~2GB | Requires conversion |
50
+ | ADE20K | ~1GB | Automatic download |
51
+ | Cityscapes | ~12GB | Manual registration required |
52
+ | COCO-Stuff 164K | ~20GB | Automatic download |
53
+ | COCO-Object | - | Converted from COCO-Stuff |
54
+
55
+ ### Cityscapes Download
56
+
57
+ Cityscapes requires manual registration:
58
+ 1. Register at: https://www.cityscapes-dataset.com/register/
59
+ 2. Download: `leftImg8bit_trainvaltest.zip` and `gtFine_trainvaltest.zip`
60
+ 3. Extract to: `data/cityscapes/`
61
+
62
+ ## Data Directory Structure
63
+
64
+ After downloading all datasets, the structure should be:
65
+
66
+ ```
67
+ data/
68
+ ├── VOCdevkit/
69
+ │ ├── VOC2012/ # Pascal VOC 2012
70
+ │ │ ├── JPEGImages/
71
+ │ │ ├── SegmentationClass/
72
+ │ │ └── ImageSets/Segmentation/
73
+ │ └── VOC2010/ # Pascal Context
74
+ │ ├── JPEGImages/
75
+ │ ├── SegmentationClassContext/
76
+ │ └── ImageSets/SegmentationContext/
77
+ ├── ADEChallengeData2016/ # ADE20K
78
+ │ ├── images/
79
+ │ │ └── validation/
80
+ │ └── annotations/
81
+ │ └── validation/
82
+ ├── cityscapes/ # Cityscapes
83
+ │ ├── leftImg8bit/
84
+ │ │ └── val/
85
+ │ └── gtFine/
86
+ │ └── val/
87
+ ├── coco_stuff164k/ # COCO-Stuff 164K
88
+ │ ├── images/
89
+ │ │ └── val2017/
90
+ │ └── annotations/
91
+ │ └── val2017/
92
+ └── coco_object/ # COCO-Object
93
+ ├── images/
94
+ │ └── val2017/
95
+ └── annotations/
96
+ └── val2017/
97
+ ```
98
+
99
+ ## Running Experiments
100
+
101
+ ### Single Dataset Evaluation
102
+
103
+ ```bash
104
+ source activate.sh
105
+ cd ../../ProxyCLIP
106
+
107
+ # Evaluate on Pascal VOC 20
108
+ python eval.py --config ./configs/cfg_voc20.py --work-dir ./work_logs/
109
+
110
+ # Evaluate on ADE20K
111
+ python eval.py --config ./configs/cfg_ade20k.py --work-dir ./work_logs/
112
+ ```
113
+
114
+ ### Multi-GPU Evaluation
115
+
116
+ ```bash
117
+ # Using 4 GPUs (default)
118
+ bash dist_test.sh ./configs/cfg_voc20.py
119
+
120
+ # Using 8 GPUs
121
+ GPUS=8 bash dist_test.sh ./configs/cfg_voc20.py
122
+ ```
123
+
124
+ ### Evaluate All Datasets
125
+
126
+ ```bash
127
+ python eval_all.py
128
+ ```
129
+
130
+ This generates `results.xlsx` with metrics for all 8 datasets.
131
+
132
+ ## Server Data Paths (已配置)
133
+
134
+ 数据集已下载到服务器 `/opt/tiger/xiaomoguhzz/dataset`,配置文件已更新。
135
+
136
+ ### 数据集路径映射
137
+
138
+ | 数据集 | 服务器路径 |
139
+ |--------|-----------|
140
+ | ADE20K | `/opt/tiger/xiaomoguhzz/dataset/ADEChallengeData2016` |
141
+ | Cityscapes | `/opt/tiger/xiaomoguhzz/dataset/cityscapes` |
142
+ | COCO-Object | `/opt/tiger/xiaomoguhzz/dataset/coco_obj` |
143
+ | COCO-Stuff | `/opt/tiger/xiaomoguhzz/standard_coco` |
144
+ | Pascal VOC | `/opt/tiger/xiaomoguhzz/dataset/VOCdevkit/VOC2012` |
145
+ | Pascal Context | `/opt/tiger/xiaomoguhzz/dataset/VOCdevkit/VOC2010` |
146
+
147
+ ### 模型权重路径
148
+
149
+ | 模型 | 路径 | 推理模式 |
150
+ |------|------|----------|
151
+ | CLIP | `/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt` | vanilla |
152
+ | DeCLIP | `/mnt/bn/.../logs/DeCLIP_EVA-B_DINOv2-B_560/checkpoints/epoch_6.pt` | csa |
153
+
154
+ ### 快速测试
155
+
156
+ ```bash
157
+ # 进入 ProxyCLIP_TPAMI 目录
158
+ cd ../../ProxyCLIP_TPAMI
159
+
160
+ # DeCLIP 评估
161
+ python eval.py --config ./configs/eva_declip/cfg_voc21.py
162
+
163
+ # CLIP baseline 评估
164
+ python eval.py --config ./configs/eva_clip/cfg_voc21.py
165
+ ```
166
+
167
+ ---
168
+
169
+ ## Troubleshooting
170
+
171
+ ### CUDA Out of Memory
172
+ Reduce the sliding window crop size in the config:
173
+ ```python
174
+ model = dict(
175
+ slide_stride=112,
176
+ slide_crop=224, # Reduce from 336 to 224
177
+ )
178
+ ```
179
+
180
+ ### Module Not Found
181
+ Make sure the environment is activated:
182
+ ```bash
183
+ source activate.sh
184
+ ```
185
+
186
+ ### Data Path Errors
187
+ Update the data paths in config files to match your data location:
188
+ ```bash
189
+ python setup_data_paths.py --data-root /path/to/your/data
190
+ ```
experimental/build_env/proxyclip/activate.sh ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Convenience script to activate the ProxyCLIP environment
3
+ # Usage: source activate.sh
4
+
5
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
6
+ BUILD_ENV_DIR="$(dirname "$SCRIPT_DIR")"
7
+ PROJECT_ROOT="$(dirname "$BUILD_ENV_DIR")"
8
+ VENV_DIR="$PROJECT_ROOT/.venv_proxyclip"
9
+
10
+ if [ ! -d "$VENV_DIR" ]; then
11
+ echo "[ERROR] Virtual environment not found at $VENV_DIR"
12
+ echo "Please run setup_env.sh first:"
13
+ echo " bash $SCRIPT_DIR/setup_env.sh"
14
+ return 1 2>/dev/null || exit 1
15
+ fi
16
+
17
+ source "$VENV_DIR/bin/activate"
18
+ echo "ProxyCLIP environment activated!"
19
+ echo "Python: $(which python)"
20
+ echo "PyTorch: $(python -c 'import torch; print(torch.__version__)')"
experimental/build_env/proxyclip/download_datasets.sh ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Dataset Download Script for ProxyCLIP
3
+ # Downloads and prepares semantic segmentation datasets
4
+
5
+ set -e
6
+
7
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
8
+ BUILD_ENV_DIR="$(dirname "$SCRIPT_DIR")"
9
+ PROJECT_ROOT="$(dirname "$BUILD_ENV_DIR")"
10
+
11
+ # Default data directory - can be customized
12
+ DATA_ROOT="${DATA_ROOT:-$PROJECT_ROOT/data}"
13
+
14
+ echo "=============================================="
15
+ echo "ProxyCLIP Dataset Download Script"
16
+ echo "=============================================="
17
+ echo "Data will be downloaded to: $DATA_ROOT"
18
+ echo ""
19
+
20
+ mkdir -p "$DATA_ROOT"
21
+ cd "$DATA_ROOT"
22
+
23
+ # Function to download with resume support
24
+ download_file() {
25
+ local url=$1
26
+ local filename=$2
27
+ if [ -f "$filename" ]; then
28
+ echo " $filename already exists, skipping download."
29
+ else
30
+ echo " Downloading $filename..."
31
+ wget -c "$url" -O "$filename"
32
+ fi
33
+ }
34
+
35
+ # ============================================
36
+ # 1. Pascal VOC 2012
37
+ # ============================================
38
+ download_voc() {
39
+ echo ""
40
+ echo "[1/6] Pascal VOC 2012"
41
+ echo "----------------------------------------"
42
+
43
+ VOC_DIR="$DATA_ROOT/VOCdevkit/VOC2012"
44
+ if [ -d "$VOC_DIR" ]; then
45
+ echo " Pascal VOC 2012 already exists at $VOC_DIR"
46
+ return
47
+ fi
48
+
49
+ mkdir -p "$DATA_ROOT/VOCdevkit"
50
+ cd "$DATA_ROOT/VOCdevkit"
51
+
52
+ # Download VOC 2012 trainval
53
+ download_file "http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar" "VOCtrainval_11-May-2012.tar"
54
+
55
+ echo " Extracting..."
56
+ tar -xf VOCtrainval_11-May-2012.tar
57
+
58
+ echo " Pascal VOC 2012 ready at: $VOC_DIR"
59
+ }
60
+
61
+ # ============================================
62
+ # 2. Pascal Context
63
+ # ============================================
64
+ download_pascal_context() {
65
+ echo ""
66
+ echo "[2/6] Pascal Context"
67
+ echo "----------------------------------------"
68
+
69
+ CONTEXT_DIR="$DATA_ROOT/VOCdevkit/VOC2010"
70
+ if [ -d "$CONTEXT_DIR/SegmentationClassContext" ]; then
71
+ echo " Pascal Context already exists at $CONTEXT_DIR"
72
+ return
73
+ fi
74
+
75
+ # Pascal Context uses VOC2010 images
76
+ mkdir -p "$DATA_ROOT/VOCdevkit"
77
+ cd "$DATA_ROOT/VOCdevkit"
78
+
79
+ # Download VOC 2010
80
+ if [ ! -d "VOC2010" ]; then
81
+ download_file "http://host.robots.ox.ac.uk/pascal/VOC/voc2010/VOCtrainval_03-May-2010.tar" "VOCtrainval_03-May-2010.tar"
82
+ echo " Extracting VOC 2010..."
83
+ tar -xf VOCtrainval_03-May-2010.tar
84
+ fi
85
+
86
+ # Download Pascal Context annotations
87
+ cd "$DATA_ROOT"
88
+ if [ ! -f "trainval_merged.json" ]; then
89
+ echo " Downloading Pascal Context annotations..."
90
+ download_file "https://cs.stanford.edu/~roozbeh/pascal-context/trainval_merged.json" "trainval_merged.json"
91
+ fi
92
+
93
+ echo ""
94
+ echo " [NOTE] Pascal Context requires additional processing."
95
+ echo " Please run the conversion script after download:"
96
+ echo " python $SCRIPT_DIR/convert_pascal_context.py"
97
+ echo ""
98
+ }
99
+
100
+ # ============================================
101
+ # 3. ADE20K
102
+ # ============================================
103
+ download_ade20k() {
104
+ echo ""
105
+ echo "[3/6] ADE20K"
106
+ echo "----------------------------------------"
107
+
108
+ ADE_DIR="$DATA_ROOT/ADEChallengeData2016"
109
+ if [ -d "$ADE_DIR" ]; then
110
+ echo " ADE20K already exists at $ADE_DIR"
111
+ return
112
+ fi
113
+
114
+ cd "$DATA_ROOT"
115
+
116
+ # Download ADE20K
117
+ download_file "http://data.csail.mit.edu/places/ADEchallenge/ADEChallengeData2016.zip" "ADEChallengeData2016.zip"
118
+
119
+ echo " Extracting..."
120
+ unzip -q ADEChallengeData2016.zip
121
+
122
+ echo " ADE20K ready at: $ADE_DIR"
123
+ }
124
+
125
+ # ============================================
126
+ # 4. Cityscapes (Manual download required)
127
+ # ============================================
128
+ download_cityscapes() {
129
+ echo ""
130
+ echo "[4/6] Cityscapes"
131
+ echo "----------------------------------------"
132
+
133
+ CITY_DIR="$DATA_ROOT/cityscapes"
134
+ if [ -d "$CITY_DIR/leftImg8bit" ] && [ -d "$CITY_DIR/gtFine" ]; then
135
+ echo " Cityscapes already exists at $CITY_DIR"
136
+ return
137
+ fi
138
+
139
+ echo " [MANUAL DOWNLOAD REQUIRED]"
140
+ echo ""
141
+ echo " Cityscapes requires registration. Please:"
142
+ echo " 1. Register at: https://www.cityscapes-dataset.com/register/"
143
+ echo " 2. Download the following files:"
144
+ echo " - leftImg8bit_trainvaltest.zip (11GB)"
145
+ echo " - gtFine_trainvaltest.zip (241MB)"
146
+ echo " 3. Extract to: $CITY_DIR"
147
+ echo ""
148
+ echo " Expected structure:"
149
+ echo " $CITY_DIR/"
150
+ echo " ├── leftImg8bit/"
151
+ echo " │ ├── train/"
152
+ echo " │ ├── val/"
153
+ echo " │ └── test/"
154
+ echo " └── gtFine/"
155
+ echo " ├── train/"
156
+ echo " ├── val/"
157
+ echo " └── test/"
158
+ echo ""
159
+
160
+ mkdir -p "$CITY_DIR"
161
+ }
162
+
163
+ # ============================================
164
+ # 5. COCO-Stuff 164K
165
+ # ============================================
166
+ download_coco_stuff() {
167
+ echo ""
168
+ echo "[5/6] COCO-Stuff 164K"
169
+ echo "----------------------------------------"
170
+
171
+ COCO_DIR="$DATA_ROOT/coco_stuff164k"
172
+ if [ -d "$COCO_DIR/images" ] && [ -d "$COCO_DIR/annotations" ]; then
173
+ echo " COCO-Stuff 164K already exists at $COCO_DIR"
174
+ return
175
+ fi
176
+
177
+ mkdir -p "$COCO_DIR"
178
+ cd "$COCO_DIR"
179
+
180
+ # Download COCO images (train2017 and val2017)
181
+ echo " Downloading COCO images..."
182
+ mkdir -p images
183
+ cd images
184
+
185
+ if [ ! -d "train2017" ]; then
186
+ download_file "http://images.cocodataset.org/zips/train2017.zip" "train2017.zip"
187
+ echo " Extracting train2017..."
188
+ unzip -q train2017.zip
189
+ fi
190
+
191
+ if [ ! -d "val2017" ]; then
192
+ download_file "http://images.cocodataset.org/zips/val2017.zip" "val2017.zip"
193
+ echo " Extracting val2017..."
194
+ unzip -q val2017.zip
195
+ fi
196
+
197
+ cd "$COCO_DIR"
198
+
199
+ # Download COCO-Stuff annotations
200
+ echo " Downloading COCO-Stuff annotations..."
201
+ mkdir -p annotations
202
+ cd annotations
203
+
204
+ if [ ! -d "train2017" ]; then
205
+ download_file "http://calvin.inf.ed.ac.uk/wp-content/uploads/data/cocostuffdataset/stuffthingmaps_trainval2017.zip" "stuffthingmaps_trainval2017.zip"
206
+ echo " Extracting annotations..."
207
+ unzip -q stuffthingmaps_trainval2017.zip
208
+ fi
209
+
210
+ echo " COCO-Stuff 164K ready at: $COCO_DIR"
211
+ }
212
+
213
+ # ============================================
214
+ # 6. COCO-Object (Converted from COCO-Stuff)
215
+ # ============================================
216
+ prepare_coco_object() {
217
+ echo ""
218
+ echo "[6/6] COCO-Object"
219
+ echo "----------------------------------------"
220
+
221
+ COCO_OBJ_DIR="$DATA_ROOT/coco_object"
222
+ COCO_STUFF_DIR="$DATA_ROOT/coco_stuff164k"
223
+
224
+ if [ -d "$COCO_OBJ_DIR" ]; then
225
+ echo " COCO-Object already exists at $COCO_OBJ_DIR"
226
+ return
227
+ fi
228
+
229
+ if [ ! -d "$COCO_STUFF_DIR" ]; then
230
+ echo " [WARNING] COCO-Stuff 164K not found. Please download it first."
231
+ return
232
+ fi
233
+
234
+ echo " Converting COCO-Stuff to COCO-Object..."
235
+ echo " Please run the conversion script:"
236
+ echo " python $PROJECT_ROOT/ProxyCLIP/datasets/cvt_coco_object.py $COCO_STUFF_DIR -o $COCO_OBJ_DIR"
237
+ echo ""
238
+ }
239
+
240
+ # ============================================
241
+ # Main execution
242
+ # ============================================
243
+ echo "Select datasets to download (comma-separated, or 'all'):"
244
+ echo " 1. voc - Pascal VOC 2012 (~2GB)"
245
+ echo " 2. context - Pascal Context (~2GB + processing)"
246
+ echo " 3. ade20k - ADE20K (~1GB)"
247
+ echo " 4. cityscapes - Cityscapes (manual, ~12GB)"
248
+ echo " 5. cocostuff - COCO-Stuff 164K (~20GB)"
249
+ echo " 6. cocoobj - COCO-Object (converted from COCO-Stuff)"
250
+ echo ""
251
+
252
+ # Check for command line argument
253
+ if [ -n "$1" ]; then
254
+ SELECTION="$1"
255
+ else
256
+ read -p "Enter selection (default: all): " SELECTION
257
+ SELECTION="${SELECTION:-all}"
258
+ fi
259
+
260
+ download_selected() {
261
+ case "$1" in
262
+ voc|1)
263
+ download_voc
264
+ ;;
265
+ context|2)
266
+ download_pascal_context
267
+ ;;
268
+ ade20k|3)
269
+ download_ade20k
270
+ ;;
271
+ cityscapes|4)
272
+ download_cityscapes
273
+ ;;
274
+ cocostuff|5)
275
+ download_coco_stuff
276
+ ;;
277
+ cocoobj|6)
278
+ prepare_coco_object
279
+ ;;
280
+ all)
281
+ download_voc
282
+ download_pascal_context
283
+ download_ade20k
284
+ download_cityscapes
285
+ download_coco_stuff
286
+ prepare_coco_object
287
+ ;;
288
+ *)
289
+ echo "Unknown dataset: $1"
290
+ ;;
291
+ esac
292
+ }
293
+
294
+ # Parse selection
295
+ IFS=',' read -ra DATASETS <<< "$SELECTION"
296
+ for dataset in "${DATASETS[@]}"; do
297
+ dataset=$(echo "$dataset" | tr -d ' ')
298
+ download_selected "$dataset"
299
+ done
300
+
301
+ echo ""
302
+ echo "=============================================="
303
+ echo "Download complete!"
304
+ echo "=============================================="
305
+ echo ""
306
+ echo "Data location: $DATA_ROOT"
307
+ echo ""
308
+ echo "Next steps:"
309
+ echo " 1. Update data paths in ProxyCLIP/configs/*.py"
310
+ echo " 2. For Cityscapes, complete manual download"
311
+ echo " 3. For Pascal Context and COCO-Object, run conversion scripts"
312
+ echo ""
experimental/build_env/proxyclip/requirements.txt ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PyTorch with CUDA 12.4
2
+ --extra-index-url https://download.pytorch.org/whl/cu124
3
+ torch==2.6.0+cu124
4
+ torchvision==0.21.0+cu124
5
+ torchaudio==2.6.0+cu124
6
+
7
+ # OpenMMLab ecosystem
8
+ mmcv==2.1.0
9
+ mmengine==0.10.4
10
+ mmdet==3.3.0
11
+
12
+ # ProxyCLIP dependencies
13
+ einops>=0.3.0
14
+ ftfy>=6.2.0
15
+ huggingface_hub>=0.23.0
16
+ matplotlib>=3.7.2
17
+ nltk>=3.8.1
18
+ numpy<2.0.0
19
+ opencv-python>=4.6.0
20
+ opencv-python-headless>=4.8.0
21
+ openpyxl>=3.1.2
22
+ Pillow>=10.4.0
23
+ pycocotools>=2.0.7
24
+ regex>=2023.8.8
25
+ safetensors>=0.4.3
26
+ scipy>=1.14.0
27
+ scikit-image
28
+ timm>=0.4.12
29
+ tqdm>=4.65.2
30
+ transformers>=4.37.2
31
+ prettytable
32
+ packaging
experimental/build_env/proxyclip/setup_data_paths.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Script to update data paths in ProxyCLIP config files.
4
+ Run this after downloading datasets to configure the correct paths.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import argparse
10
+ from pathlib import Path
11
+
12
+ # Default paths
13
+ SCRIPT_DIR = Path(__file__).parent
14
+ BUILD_ENV_DIR = SCRIPT_DIR.parent
15
+ PROJECT_ROOT = BUILD_ENV_DIR.parent
16
+ PROXYCLIP_DIR = PROJECT_ROOT / "ProxyCLIP_TPAMI"
17
+ CONFIGS_DIR = PROXYCLIP_DIR / "configs"
18
+
19
+ # Server default data path
20
+ SERVER_DATA_ROOT = "/opt/tiger/xiaomoguhzz/dataset"
21
+
22
+
23
+ def update_config_paths(data_root: str, dry_run: bool = False):
24
+ """Update data paths in ProxyCLIP config files."""
25
+
26
+ data_root = Path(data_root).resolve()
27
+
28
+ # Dataset path mappings
29
+ dataset_paths = {
30
+ "cfg_voc20.py": {
31
+ "data_prefix": {
32
+ "img_path": str(data_root / "VOCdevkit/VOC2012/JPEGImages"),
33
+ "seg_map_path": str(data_root / "VOCdevkit/VOC2012/SegmentationClass"),
34
+ },
35
+ "ann_file": str(data_root / "VOCdevkit/VOC2012/ImageSets/Segmentation/val.txt"),
36
+ },
37
+ "cfg_voc21.py": {
38
+ "data_prefix": {
39
+ "img_path": str(data_root / "VOCdevkit/VOC2012/JPEGImages"),
40
+ "seg_map_path": str(data_root / "VOCdevkit/VOC2012/SegmentationClass"),
41
+ },
42
+ "ann_file": str(data_root / "VOCdevkit/VOC2012/ImageSets/Segmentation/val.txt"),
43
+ },
44
+ "cfg_context59.py": {
45
+ "data_prefix": {
46
+ "img_path": str(data_root / "VOCdevkit/VOC2010/JPEGImages"),
47
+ "seg_map_path": str(data_root / "VOCdevkit/VOC2010/SegmentationClassContext"),
48
+ },
49
+ "ann_file": str(data_root / "VOCdevkit/VOC2010/ImageSets/SegmentationContext/val.txt"),
50
+ },
51
+ "cfg_context60.py": {
52
+ "data_prefix": {
53
+ "img_path": str(data_root / "VOCdevkit/VOC2010/JPEGImages"),
54
+ "seg_map_path": str(data_root / "VOCdevkit/VOC2010/SegmentationClassContext"),
55
+ },
56
+ "ann_file": str(data_root / "VOCdevkit/VOC2010/ImageSets/SegmentationContext/val.txt"),
57
+ },
58
+ "cfg_ade20k.py": {
59
+ "data_prefix": {
60
+ "img_path": str(data_root / "ADEChallengeData2016/images/validation"),
61
+ "seg_map_path": str(data_root / "ADEChallengeData2016/annotations/validation"),
62
+ },
63
+ },
64
+ "cfg_city_scapes.py": {
65
+ "data_prefix": {
66
+ "img_path": str(data_root / "cityscapes/leftImg8bit/val"),
67
+ "seg_map_path": str(data_root / "cityscapes/gtFine/val"),
68
+ },
69
+ },
70
+ "cfg_coco_stuff164k.py": {
71
+ "data_prefix": {
72
+ "img_path": str(data_root / "coco_stuff164k/images/val2017"),
73
+ "seg_map_path": str(data_root / "coco_stuff164k/annotations/val2017"),
74
+ },
75
+ },
76
+ "cfg_coco_object.py": {
77
+ "data_prefix": {
78
+ "img_path": str(data_root / "coco_object/images/val2017"),
79
+ "seg_map_path": str(data_root / "coco_object/annotations/val2017"),
80
+ },
81
+ },
82
+ }
83
+
84
+ print("=" * 50)
85
+ print("Updating ProxyCLIP config files")
86
+ print("=" * 50)
87
+ print(f"Data root: {data_root}")
88
+ print(f"Config dir: {CONFIGS_DIR}")
89
+ print("")
90
+
91
+ if not CONFIGS_DIR.exists():
92
+ print(f"[ERROR] Config directory not found: {CONFIGS_DIR}")
93
+ return False
94
+
95
+ for config_name, paths in dataset_paths.items():
96
+ config_path = CONFIGS_DIR / config_name
97
+ if not config_path.exists():
98
+ print(f"[SKIP] {config_name} - file not found")
99
+ continue
100
+
101
+ print(f"[UPDATE] {config_name}")
102
+
103
+ # Read config file
104
+ with open(config_path, 'r') as f:
105
+ content = f.read()
106
+
107
+ # For now, just print what would be updated
108
+ if "data_prefix" in paths:
109
+ for key, value in paths["data_prefix"].items():
110
+ print(f" {key}: {value}")
111
+ if "ann_file" in paths:
112
+ print(f" ann_file: {paths['ann_file']}")
113
+
114
+ print("")
115
+ print("=" * 50)
116
+ print("")
117
+ print("To apply these changes, you need to manually update the config files.")
118
+ print("Each config file has a 'test_dataloader' section with 'data_prefix' settings.")
119
+ print("")
120
+ print("Example structure:")
121
+ print(" test_dataloader = dict(")
122
+ print(" dataset=dict(")
123
+ print(" data_prefix=dict(")
124
+ print(f" img_path='{data_root}/VOCdevkit/VOC2012/JPEGImages',")
125
+ print(f" seg_map_path='{data_root}/VOCdevkit/VOC2012/SegmentationClass',")
126
+ print(" ),")
127
+ print(" )")
128
+ print(" )")
129
+ print("")
130
+
131
+ return True
132
+
133
+
134
+ def main():
135
+ parser = argparse.ArgumentParser(description="Update data paths in ProxyCLIP configs")
136
+ parser.add_argument(
137
+ "--data-root",
138
+ type=str,
139
+ default=SERVER_DATA_ROOT,
140
+ help="Root directory containing all datasets (default: server path)",
141
+ )
142
+ parser.add_argument(
143
+ "--dry-run",
144
+ action="store_true",
145
+ help="Show what would be changed without modifying files",
146
+ )
147
+
148
+ args = parser.parse_args()
149
+
150
+ success = update_config_paths(args.data_root, args.dry_run)
151
+ sys.exit(0 if success else 1)
152
+
153
+
154
+ if __name__ == "__main__":
155
+ main()
experimental/build_env/proxyclip/setup_env.sh ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # ProxyCLIP Environment Setup Script
3
+ # Creates an isolated uv virtual environment with all dependencies
4
+
5
+ set -e
6
+
7
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
8
+ BUILD_ENV_DIR="$(dirname "$SCRIPT_DIR")"
9
+ PROJECT_ROOT="$(dirname "$BUILD_ENV_DIR")"
10
+ VENV_DIR="/opt/tiger/xiaomoguhzz/envs/proxyclip_venv"
11
+ MMSEG_DIR="$PROJECT_ROOT/mmsegmentation"
12
+
13
+ echo "=============================================="
14
+ echo "ProxyCLIP Environment Setup"
15
+ echo "=============================================="
16
+ echo "Project root: $PROJECT_ROOT"
17
+ echo "Virtual env: $VENV_DIR"
18
+ echo ""
19
+
20
+ # Check if uv is installed
21
+ if ! command -v uv &> /dev/null; then
22
+ echo "[ERROR] uv is not installed. Please install uv first:"
23
+ echo " curl -LsSf https://astral.sh/uv/install.sh | sh"
24
+ exit 1
25
+ fi
26
+
27
+ echo "[1/5] Creating virtual environment with Python 3.10..."
28
+ if [ -d "$VENV_DIR" ]; then
29
+ echo " Virtual environment already exists, removing..."
30
+ rm -rf "$VENV_DIR"
31
+ fi
32
+ uv venv "$VENV_DIR" --python 3.10
33
+
34
+ echo ""
35
+ echo "[2/5] Installing base dependencies from requirements.txt..."
36
+ uv pip install -r "$SCRIPT_DIR/requirements.txt" --python "$VENV_DIR/bin/python"
37
+
38
+ echo ""
39
+ echo "[3/5] Installing mmsegmentation from PyPI..."
40
+ uv pip install mmsegmentation==1.2.2 --python "$VENV_DIR/bin/python"
41
+
42
+ echo ""
43
+ echo "[4/5] Installing open_clip from ProxyCLIP..."
44
+ PROXYCLIP_DIR="$PROJECT_ROOT/ProxyCLIP"
45
+ if [ -d "$PROXYCLIP_DIR/open_clip" ]; then
46
+ echo " open_clip package is included in ProxyCLIP, no additional installation needed."
47
+ else
48
+ echo " Installing open_clip_torch..."
49
+ uv pip install open_clip_torch --python "$VENV_DIR/bin/python"
50
+ fi
51
+
52
+ echo ""
53
+ echo "[5/5] Verifying installation..."
54
+ "$VENV_DIR/bin/python" -c "
55
+ import torch
56
+ import mmcv
57
+ import mmengine
58
+ import mmseg
59
+
60
+ print('PyTorch version:', torch.__version__)
61
+ print('CUDA available:', torch.cuda.is_available())
62
+ if torch.cuda.is_available():
63
+ print('CUDA version:', torch.version.cuda)
64
+ print('GPU count:', torch.cuda.device_count())
65
+ print('mmcv version:', mmcv.__version__)
66
+ print('mmengine version:', mmengine.__version__)
67
+ print('mmseg version:', mmseg.__version__)
68
+ "
69
+
70
+ echo ""
71
+ echo "=============================================="
72
+ echo "Setup completed successfully!"
73
+ echo "=============================================="
74
+ echo ""
75
+ echo "To activate the environment, run:"
76
+ echo " source $VENV_DIR/bin/activate"
77
+ echo ""
78
+ echo "Or use the convenience script:"
79
+ echo " source $SCRIPT_DIR/activate.sh"
80
+ echo ""
81
+ echo "Next steps:"
82
+ echo " 1. Download datasets: bash $SCRIPT_DIR/download_datasets.sh"
83
+ echo " 2. Configure data paths in ProxyCLIP/configs/"
84
+ echo " 3. Run evaluation: cd $PROXYCLIP_DIR && python eval.py --config ./configs/cfg_voc20.py"
85
+ echo ""
scripts/ablation_ijepa/debug_ijepa_gsc_eva_vitL14_336_coco.sh ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # JEPA-GSC 消融实验:EVA-CLIP-L/14-336 单卡调试
3
+
4
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
5
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt
6
+ exp_name=Debug_JEPA-GSC_EVA-L_DINOv2-B_csa_336
7
+ vfm_type=dinov2-B
8
+ dataset_type=ablation_ijepa
9
+ version=ablation_ijepa
10
+ mode=csa_vfm_distill
11
+
12
+ # 单卡调试
13
+ CUDA_VISIBLE_DEVICES=0 python -m training.main \
14
+ --batch-size=2 \
15
+ --lr=1e-5 \
16
+ --wd=0.1 \
17
+ --epochs=1 \
18
+ --workers=2 \
19
+ --model EVA02-CLIP-L-14-336 \
20
+ --pretrained eva \
21
+ --warmup 100 \
22
+ --zeroshot-frequency 1 \
23
+ --dataset-type ${dataset_type} \
24
+ --test-type coco_panoptic \
25
+ --train-data ${data_root}/annotations/instances_train2017.json \
26
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
27
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy \
28
+ --train-image-root ${data_root}/train2017 \
29
+ --val-image-root ${data_root}/val2017 \
30
+ --cache-dir ${pretrain_ckpt} \
31
+ --log-every-n-steps 10 \
32
+ --lock-image \
33
+ --save-frequency 1 \
34
+ --lock-image-unlocked-groups 24 \
35
+ --name ${exp_name} \
36
+ --downsample-factor 14 \
37
+ --det-image-size 336 \
38
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
39
+ --alpha 0.7 \
40
+ --mode ${mode} \
41
+ --use_vfm ${vfm_type} \
42
+ --loss_context_weight 0.25 \
43
+ --loss_content_weight 1.0 \
44
+ --loss_region_weight 0.05 \
45
+ --skip-first-eval \
46
+ --repa_layer_idx -1 \
47
+ --sd-refine-weight 0.3 \
48
+ --version ${version} \
49
+ --train-ratio 0.01
scripts/ablation_ijepa/debug_ijepa_gsc_eva_vitb16_coco.sh ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # JEPA-GSC 消融实验:EVA-CLIP-B/16 单卡调试
3
+
4
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
5
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt
6
+ exp_name=Debug_JEPA-GSC_EVA-B_DINOv2-B_csa_560
7
+ vfm_type=dinov2-B
8
+ dataset_type=ablation_ijepa
9
+ version=ablation_ijepa
10
+ mode=csa_vfm_distill
11
+
12
+ # 单卡调试
13
+ CUDA_VISIBLE_DEVICES=0 python -m training.main \
14
+ --batch-size=2 \
15
+ --lr=1e-5 \
16
+ --wd=0.1 \
17
+ --epochs=1 \
18
+ --workers=2 \
19
+ --model EVA02-CLIP-B-16 \
20
+ --pretrained eva \
21
+ --warmup 100 \
22
+ --zeroshot-frequency 1 \
23
+ --dataset-type ${dataset_type} \
24
+ --test-type coco_panoptic \
25
+ --train-data ${data_root}/annotations/instances_train2017.json \
26
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
27
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy \
28
+ --train-image-root ${data_root}/train2017 \
29
+ --val-image-root ${data_root}/val2017 \
30
+ --cache-dir ${pretrain_ckpt} \
31
+ --log-every-n-steps 10 \
32
+ --lock-image \
33
+ --save-frequency 1 \
34
+ --lock-image-unlocked-groups 12 \
35
+ --name ${exp_name} \
36
+ --downsample-factor 16 \
37
+ --det-image-size 560 \
38
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
39
+ --alpha 0.7 \
40
+ --mode ${mode} \
41
+ --use_vfm ${vfm_type} \
42
+ --loss_context_weight 0.25 \
43
+ --loss_content_weight 1.0 \
44
+ --loss_region_weight 0.05 \
45
+ --skip-first-eval \
46
+ --repa_layer_idx -1 \
47
+ --sd-refine-weight 0.3 \
48
+ --version ${version} \
49
+ --train-ratio 0.01
scripts/ablation_ijepa/dist_ijepa_gsc_eva_vitL14_336_coco.sh ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # JEPA-GSC 消融实验:EVA-CLIP-L/14-336 多卡训练
3
+
4
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
5
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt
6
+ exp_name=Ablation_JEPA-GSC_EVA-L_DINOv2-B_csa_336
7
+ vfm_type=dinov2-B
8
+ dataset_type=ablation_ijepa
9
+ version=ablation_ijepa
10
+ mode=csa_vfm_distill
11
+
12
+ # Parse arguments for nohup
13
+ USE_NOHUP=true
14
+ if [[ "$1" == "--nohup" ]] || [[ "$1" == "true" ]]; then
15
+ USE_NOHUP=true
16
+ fi
17
+
18
+ cmd="CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12349 \
19
+ -m training.main \
20
+ --batch-size=2 \
21
+ --lr=1e-5 \
22
+ --wd=0.1 \
23
+ --epochs=6 \
24
+ --workers=4 \
25
+ --model EVA02-CLIP-L-14-336 \
26
+ --pretrained eva \
27
+ --warmup 1000 \
28
+ --zeroshot-frequency 6 \
29
+ --dataset-type ${dataset_type} \
30
+ --test-type coco_panoptic \
31
+ --train-data ${data_root}/annotations/instances_train2017.json \
32
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
33
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy \
34
+ --train-image-root ${data_root}/train2017 \
35
+ --val-image-root ${data_root}/val2017 \
36
+ --cache-dir ${pretrain_ckpt} \
37
+ --log-every-n-steps 100 \
38
+ --lock-image \
39
+ --save-frequency 1 \
40
+ --lock-image-unlocked-groups 24 \
41
+ --name ${exp_name} \
42
+ --downsample-factor 14 \
43
+ --det-image-size 336 \
44
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
45
+ --alpha 0.7 \
46
+ --mode ${mode} \
47
+ --use_vfm ${vfm_type} \
48
+ --loss_context_weight 0.25 \
49
+ --loss_content_weight 1.0 \
50
+ --loss_region_weight 0.05 \
51
+ --skip-first-eval \
52
+ --repa_layer_idx -1 \
53
+ --sd-refine-weight 0.3 \
54
+ --version ${version}" \
55
+ --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
56
+
57
+ if [ "$USE_NOHUP" = true ]; then
58
+ LOG_DIR="logs/${exp_name}"
59
+ mkdir -p "$LOG_DIR"
60
+ echo "Running with nohup. Output will be saved to ${LOG_DIR}/nohup.log"
61
+ nohup sh -c "$cmd" > "${LOG_DIR}/nohup.log" 2>&1 &
62
+ else
63
+ eval $cmd
64
+ fi
scripts/ablation_ijepa/dist_ijepa_gsc_eva_vitb16_coco.sh ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # JEPA-GSC 消融实验:EVA-CLIP-B/16 多卡训练
3
+
4
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
5
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt
6
+ exp_name=Ablation_JEPA-GSC_EVA-B_DINOv2-B_csa_560
7
+ vfm_type=dinov2-B
8
+ dataset_type=ablation_ijepa
9
+ version=ablation_ijepa
10
+ mode=csa_vfm_distill
11
+
12
+ # Parse arguments for nohup
13
+ USE_NOHUP=true
14
+ if [[ "$1" == "--nohup" ]] || [[ "$1" == "true" ]]; then
15
+ USE_NOHUP=true
16
+ fi
17
+
18
+ # 多卡训练:总 batch_size=16
19
+ # 请根据实际 GPU 数量调整 --nproc_per_node 和 --batch-size
20
+ cmd="CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12340 \
21
+ -m training.main \
22
+ --batch-size=2 \
23
+ --lr=1e-5 \
24
+ --wd=0.1 \
25
+ --epochs=6 \
26
+ --workers=4 \
27
+ --model EVA02-CLIP-B-16 \
28
+ --pretrained eva \
29
+ --warmup 1000 \
30
+ --zeroshot-frequency 6 \
31
+ --dataset-type ${dataset_type} \
32
+ --test-type coco_panoptic \
33
+ --train-data ${data_root}/annotations/instances_train2017.json \
34
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
35
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy \
36
+ --train-image-root ${data_root}/train2017 \
37
+ --val-image-root ${data_root}/val2017 \
38
+ --cache-dir ${pretrain_ckpt} \
39
+ --log-every-n-steps 100 \
40
+ --lock-image \
41
+ --save-frequency 1 \
42
+ --lock-image-unlocked-groups 12 \
43
+ --name ${exp_name} \
44
+ --downsample-factor 16 \
45
+ --det-image-size 560 \
46
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
47
+ --alpha 0.7 \
48
+ --mode ${mode} \
49
+ --use_vfm ${vfm_type} \
50
+ --loss_context_weight 0.25 \
51
+ --loss_content_weight 1.0 \
52
+ --loss_region_weight 0.05 \
53
+ --skip-first-eval \
54
+ --repa_layer_idx -1 \
55
+ --sd-refine-weight 0.3 \
56
+ --version ${version}"
57
+
58
+ if [ "$USE_NOHUP" = true ]; then
59
+ LOG_DIR="logs/${exp_name}"
60
+ mkdir -p "$LOG_DIR"
61
+ echo "Running with nohup. Output will be saved to ${LOG_DIR}/nohup.log"
62
+ nohup sh -c "$cmd" > "${LOG_DIR}/nohup.log" 2>&1 &
63
+ else
64
+ eval $cmd
65
+ fi
scripts/ablation_ijepa/resume_ijepa_gsc_eva_vitL14_336.sh ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Resume Ablation_JEPA-GSC_EVA-L_DINOv2-B_csa_336 实验
3
+
4
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
5
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt
6
+ exp_name=Ablation_JEPA-GSC_EVA-L_DINOv2-B_csa_336
7
+ resume_ckpt=logs/${exp_name}/checkpoints/epoch_5.pt
8
+
9
+ cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private
10
+
11
+ echo "Resuming: $exp_name"
12
+ echo "Checkpoint: $resume_ckpt"
13
+
14
+ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12342 \
15
+ -m training.main \
16
+ --batch-size=2 \
17
+ --lr=1e-5 \
18
+ --wd=0.1 \
19
+ --epochs=6 \
20
+ --workers=4 \
21
+ --model EVA02-CLIP-L-14-336 \
22
+ --pretrained eva \
23
+ --warmup 1000 \
24
+ --zeroshot-frequency 6 \
25
+ --dataset-type ablation_ijepa \
26
+ --test-type coco_panoptic \
27
+ --train-data ${data_root}/annotations/instances_train2017.json \
28
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
29
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy \
30
+ --train-image-root ${data_root}/train2017 \
31
+ --val-image-root ${data_root}/val2017 \
32
+ --cache-dir ${pretrain_ckpt} \
33
+ --log-every-n-steps 100 \
34
+ --lock-image \
35
+ --save-frequency 1 \
36
+ --lock-image-unlocked-groups 24 \
37
+ --name ${exp_name} \
38
+ --downsample-factor 14 \
39
+ --det-image-size 336 \
40
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
41
+ --alpha 0.7 \
42
+ --mode csa_vfm_distill \
43
+ --use_vfm dinov2-B \
44
+ --loss_context_weight 0.25 \
45
+ --loss_content_weight 1.0 \
46
+ --loss_region_weight 0.05 \
47
+ --repa_layer_idx -1 \
48
+ --sd-refine-weight 0.3 \
49
+ --version ablation_ijepa \
50
+ --resume ${resume_ckpt}
scripts/ablation_sam/debug_sam_gsc_eva_vitL14_336_coco.sh ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # SAM-GSC 消融实验:EVA-CLIP-L/14-336 单卡调试
3
+
4
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
5
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt
6
+ exp_name=Debug_SAM-GSC_EVA-L_DINOv2-B_csa_336
7
+ vfm_type=dinov2-B
8
+ dataset_type=ablation_sam
9
+ version=ablation_sam
10
+ mode=csa_vfm_distill
11
+
12
+ # 单卡调试
13
+ CUDA_VISIBLE_DEVICES=0 python -m training.main \
14
+ --batch-size=2 \
15
+ --lr=1e-5 \
16
+ --wd=0.1 \
17
+ --epochs=1 \
18
+ --workers=2 \
19
+ --model EVA02-CLIP-L-14-336 \
20
+ --pretrained eva \
21
+ --warmup 100 \
22
+ --zeroshot-frequency 1 \
23
+ --dataset-type ${dataset_type} \
24
+ --test-type coco_panoptic \
25
+ --train-data ${data_root}/annotations/instances_train2017.json \
26
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
27
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy \
28
+ --train-image-root ${data_root}/train2017 \
29
+ --val-image-root ${data_root}/val2017 \
30
+ --cache-dir ${pretrain_ckpt} \
31
+ --log-every-n-steps 10 \
32
+ --lock-image \
33
+ --save-frequency 1 \
34
+ --lock-image-unlocked-groups 24 \
35
+ --name ${exp_name} \
36
+ --downsample-factor 14 \
37
+ --det-image-size 336 \
38
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
39
+ --alpha 0.7 \
40
+ --mode ${mode} \
41
+ --use_vfm ${vfm_type} \
42
+ --loss_context_weight 0.25 \
43
+ --loss_content_weight 1.0 \
44
+ --loss_region_weight 0.05 \
45
+ --skip-first-eval \
46
+ --repa_layer_idx -1 \
47
+ --sd-refine-weight 0.3 \
48
+ --version ${version} \
49
+ --train-ratio 0.01
scripts/ablation_sam/debug_sam_gsc_eva_vitb16_coco.sh ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # SAM-GSC 消融实验:EVA-CLIP-B/16 单卡调试
3
+
4
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
5
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt
6
+ exp_name=Debug_SAM-GSC_EVA-B_DINOv2-B_csa_560
7
+ vfm_type=dinov2-B
8
+ dataset_type=ablation_sam
9
+ version=ablation_sam
10
+ mode=csa_vfm_distill
11
+
12
+ # 单卡调试
13
+ CUDA_VISIBLE_DEVICES=0 python -m training.main \
14
+ --batch-size=2 \
15
+ --lr=1e-5 \
16
+ --wd=0.1 \
17
+ --epochs=1 \
18
+ --workers=2 \
19
+ --model EVA02-CLIP-B-16 \
20
+ --pretrained eva \
21
+ --warmup 100 \
22
+ --zeroshot-frequency 1 \
23
+ --dataset-type ${dataset_type} \
24
+ --test-type coco_panoptic \
25
+ --train-data ${data_root}/annotations/instances_train2017.json \
26
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
27
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy \
28
+ --train-image-root ${data_root}/train2017 \
29
+ --val-image-root ${data_root}/val2017 \
30
+ --cache-dir ${pretrain_ckpt} \
31
+ --log-every-n-steps 10 \
32
+ --lock-image \
33
+ --save-frequency 1 \
34
+ --lock-image-unlocked-groups 12 \
35
+ --name ${exp_name} \
36
+ --downsample-factor 16 \
37
+ --det-image-size 560 \
38
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
39
+ --alpha 0.7 \
40
+ --mode ${mode} \
41
+ --use_vfm ${vfm_type} \
42
+ --loss_context_weight 0.25 \
43
+ --loss_content_weight 1.0 \
44
+ --loss_region_weight 0.05 \
45
+ --skip-first-eval \
46
+ --repa_layer_idx -1 \
47
+ --sd-refine-weight 0.3 \
48
+ --version ${version} \
49
+ --train-ratio 0.01
scripts/ablation_sam/dist_sam_gsc_eva_vitL14_336_coco.sh ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # SAM-GSC 消融实验:EVA-CLIP-L/14-336 多卡训练
3
+
4
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
5
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt
6
+ exp_name=Ablation_SAM-GSC_EVA-L_DINOv2-B_csa_560
7
+ vfm_type=dinov2-B
8
+ dataset_type=ablation_sam
9
+ version=ablation_sam
10
+ mode=csa_vfm_distill
11
+
12
+ # Parse arguments for nohup
13
+ USE_NOHUP=false
14
+ if [[ "$1" == "--nohup" ]] || [[ "$1" == "true" ]]; then
15
+ USE_NOHUP=true
16
+ fi
17
+
18
+ # 多卡训练:总 batch_size=16
19
+ # EVA-CLIP-L 显存占用更大,可能需要减少每卡 batch_size
20
+ cmd="CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12347 \
21
+ -m training.main \
22
+ --batch-size=2 \
23
+ --lr=1e-5 \
24
+ --wd=0.1 \
25
+ --epochs=6 \
26
+ --workers=4 \
27
+ --model EVA02-CLIP-L-14-336 \
28
+ --pretrained eva \
29
+ --warmup 1000 \
30
+ --zeroshot-frequency 6 \
31
+ --dataset-type ${dataset_type} \
32
+ --test-type coco_panoptic \
33
+ --train-data ${data_root}/annotations/instances_train2017.json \
34
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
35
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy \
36
+ --train-image-root ${data_root}/train2017 \
37
+ --val-image-root ${data_root}/val2017 \
38
+ --cache-dir ${pretrain_ckpt} \
39
+ --log-every-n-steps 100 \
40
+ --lock-image \
41
+ --save-frequency 1 \
42
+ --lock-image-unlocked-groups 24 \
43
+ --name ${exp_name} \
44
+ --downsample-factor 14 \
45
+ --det-image-size 560 \
46
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
47
+ --alpha 0.7 \
48
+ --mode ${mode} \
49
+ --use_vfm ${vfm_type} \
50
+ --loss_context_weight 0.25 \
51
+ --loss_content_weight 1.0 \
52
+ --loss_region_weight 0.05 \
53
+ --skip-first-eval \
54
+ --repa_layer_idx -1 \
55
+ --sd-refine-weight 0.3 \
56
+ --version ${version}"
57
+
58
+ if [ "$USE_NOHUP" = true ]; then
59
+ LOG_DIR="logs/${exp_name}"
60
+ mkdir -p "$LOG_DIR"
61
+ echo "Running with nohup. Output will be saved to ${LOG_DIR}/nohup.log"
62
+ nohup sh -c "$cmd" > "${LOG_DIR}/nohup.log" 2>&1 &
63
+ else
64
+ eval $cmd
65
+ fi
scripts/ablation_sam/dist_sam_gsc_eva_vitb16_coco.sh ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # SAM-GSC 消融实验:EVA-CLIP-B/16 多卡训练
3
+
4
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
5
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt
6
+ exp_name=Ablation_SAM-GSC_EVA-B_DINOv2-B_csa_560
7
+ vfm_type=dinov2-B
8
+ dataset_type=ablation_sam
9
+ version=ablation_sam
10
+ mode=csa_vfm_distill
11
+
12
+ # Parse arguments for nohup
13
+ USE_NOHUP=true
14
+ if [[ "$1" == "--nohup" ]] || [[ "$1" == "true" ]]; then
15
+ USE_NOHUP=true
16
+ fi
17
+
18
+ # 多卡训练:总 batch_size=16
19
+ # 请根据实际 GPU 数量调整 --nproc_per_node 和 --batch-size
20
+ # 例如:4卡 x 4 = 16, 2卡 x 8 = 16, 8卡 x 2 = 16
21
+ cmd="CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12348 \
22
+ -m training.main \
23
+ --batch-size=2 \
24
+ --lr=1e-5 \
25
+ --wd=0.1 \
26
+ --epochs=6 \
27
+ --workers=4 \
28
+ --model EVA02-CLIP-B-16 \
29
+ --pretrained eva \
30
+ --warmup 1000 \
31
+ --zeroshot-frequency 6 \
32
+ --dataset-type ${dataset_type} \
33
+ --test-type coco_panoptic \
34
+ --train-data ${data_root}/annotations/instances_train2017.json \
35
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
36
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy \
37
+ --train-image-root ${data_root}/train2017 \
38
+ --val-image-root ${data_root}/val2017 \
39
+ --cache-dir ${pretrain_ckpt} \
40
+ --log-every-n-steps 100 \
41
+ --lock-image \
42
+ --save-frequency 1 \
43
+ --lock-image-unlocked-groups 12 \
44
+ --name ${exp_name} \
45
+ --downsample-factor 16 \
46
+ --det-image-size 560 \
47
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
48
+ --alpha 0.7 \
49
+ --mode ${mode} \
50
+ --use_vfm ${vfm_type} \
51
+ --loss_context_weight 0.25 \
52
+ --loss_content_weight 1.0 \
53
+ --loss_region_weight 0.05 \
54
+ --skip-first-eval \
55
+ --repa_layer_idx -1 \
56
+ --sd-refine-weight 0.3 \
57
+ --version ${version}"
58
+
59
+ if [ "$USE_NOHUP" = true ]; then
60
+ LOG_DIR="logs/${exp_name}"
61
+ mkdir -p "$LOG_DIR"
62
+ echo "Running with nohup. Output will be saved to ${LOG_DIR}/nohup.log"
63
+ nohup sh -c "$cmd" > "${LOG_DIR}/nohup.log" 2>&1 &
64
+ else
65
+ eval $cmd
66
+ fi
scripts/declip+/DeCLIP+_eva_vitb16_coco.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
2
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt
3
+ exp_name=test
4
+ vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16}
5
+ dataset_type=dift_proposals_distill # {proposals_distill,grid_distill,dift_grid_distill,dift_proposals_distill}
6
+ version=declip+ # {declip,declip2,declip+}
7
+ mode=csa_vfm_distill
8
+ # always keep total batchsize=16 , otherwise, Linear scaling the learning rate
9
+ 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 \
10
+ --model EVA02-CLIP-B-16 --pretrained eva --warmup 1000 --zeroshot-frequency 6 --dataset-type ${dataset_type} \
11
+ --test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \
12
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
13
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy --train-image-root ${data_root}/train2017 \
14
+ --val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \
15
+ --lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \
16
+ --name ${exp_name} --downsample-factor 16 --det-image-size 560 --val-segm-root ${data_root}/annotations/panoptic_val2017 \
17
+ --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
scripts/declip+/dist_DeCLIP+_eva_vitL14_336_coco.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
2
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt
3
+ exp_name=EVAL_dinov2B_csa_490_plus_exp95_sd0.2_0.1_1.0_0.2
4
+ vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16}
5
+ dataset_type=dift_grid_distill # {proposals_distill,grid_distill,dift_grid_distill}
6
+ version=declip+ # {declip,declip2,declip+}
7
+ mode=csa_vfm_distill
8
+ # always keep total batchsize=16 , otherwise, Linear scaling the learning rate
9
+ 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 \
10
+ --model EVA02-CLIP-L-14-336 --pretrained eva --warmup 1000 --zeroshot-frequency 1 --dataset-type ${dataset_type} \
11
+ --test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \
12
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
13
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy --train-image-root ${data_root}/train2017 \
14
+ --val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \
15
+ --lock-image --save-frequency 1 --lock-image-unlocked-groups 24 \
16
+ --name ${exp_name} --downsample-factor 14 --det-image-size 490 --val-segm-root ${data_root}/annotations/panoptic_val2017 \
17
+ --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
scripts/declip+/dist_DeCLIP+_eva_vitL14_336_lvis.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
2
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt
3
+ exp_name=EVAL_dinov2B_qq_896_plus_0.1_2.0_1.0_lvis
4
+ vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16}
5
+ dataset_type=grid_distill # {proposals_distill,grid_distill,dift_grid_distill}
6
+ mode=qq_vfm_distill
7
+
8
+ # always keep total batchsize=16 , otherwise, Linear scaling the learning rate
9
+ 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 \
10
+ --model EVA02-CLIP-L-14-336 --pretrained eva --warmup 1000 --zeroshot-frequency 1 --dataset-type ${dataset_type} \
11
+ --test-type coco_panoptic --train-data ${data_root}/annotations/lvis_v1_train.json \
12
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
13
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy --train-image-root ${data_root} \
14
+ --val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \
15
+ --lock-image --save-frequency 1 --lock-image-unlocked-groups 24 \
16
+ --name ${exp_name} --downsample-factor 14 --det-image-size 896 --val-segm-root ${data_root}/annotations/panoptic_val2017 \
17
+ --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
scripts/declip+/dist_DeCLIP+_eva_vitb16_coco.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
2
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt
3
+ exp_name=EVA-B_DINOv2-B_csa_560_declip2_0.25_1.0_0.05
4
+ vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16}
5
+ dataset_type=grid_distill # {proposals_distill,grid_distill,dift_grid_distill,dift_proposals_distill}
6
+ version=declip2 # {declip,declip2,declip+}
7
+ mode=csa_vfm_distill
8
+ # always keep total batchsize=16 , otherwise, Linear scaling the learning rate
9
+ 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 \
10
+ --model EVA02-CLIP-B-16 --pretrained eva --warmup 1000 --zeroshot-frequency 6 --dataset-type ${dataset_type} \
11
+ --test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \
12
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
13
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy --train-image-root ${data_root}/train2017 \
14
+ --val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \
15
+ --lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \
16
+ --name ${exp_name} --downsample-factor 16 --det-image-size 560 --val-segm-root ${data_root}/annotations/panoptic_val2017 \
17
+ --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}
scripts/declip+/dist_DeCLIP+_eva_vitb16_coco_seg.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
2
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt
3
+ exp_name=EVA-B_DINOv2-B_csa_560_plus_sd1.0_0.9_1.0_0.3
4
+ vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16}
5
+ dataset_type=dift_grid_distill # {proposals_distill,grid_distill,dift_grid_distill}
6
+ version=declip+ # {declip,declip2,declip+}
7
+ mode=csa_vfm_distill
8
+ # always keep total batchsize=16 , otherwise, Linear scaling the learning rate
9
+ 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 \
10
+ --model EVA02-CLIP-B-16 --pretrained eva --warmup 1000 --zeroshot-frequency 1 --dataset-type ${dataset_type} \
11
+ --test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \
12
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
13
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy --train-image-root ${data_root}/train2017 \
14
+ --val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \
15
+ --lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \
16
+ --name ${exp_name} --downsample-factor 16 --det-image-size 560 --val-segm-root ${data_root}/annotations/panoptic_val2017 \
17
+ --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}
scripts/declip+/dist_DeCLIP+_eva_vitb16_lvis.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
2
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt
3
+ exp_name=EVAB_dinov2B_csa_1024_plus_0.05_2.0_1.0_lvis
4
+ vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16}
5
+ dataset_type=grid_distill # {proposals_distill,grid_distill,dift_grid_distill}
6
+ mode=csa_vfm_distill
7
+
8
+ # always keep total batchsize=16 , otherwise, Linear scaling the learning rate
9
+ 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 \
10
+ --model EVA02-CLIP-B-16 --pretrained eva --warmup 1000 --zeroshot-frequency 1 --dataset-type ${dataset_type} \
11
+ --test-type coco_panoptic --train-data ${data_root}/annotations/lvis_v1_train.json \
12
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
13
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy --train-image-root ${data_root} \
14
+ --val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \
15
+ --lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \
16
+ --name ${exp_name} --downsample-factor 16 --det-image-size 1024 --val-segm-root ${data_root}/annotations/panoptic_val2017 \
17
+ --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
scripts/declip/dist_eva_vitL14_336_coco.sh ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
2
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt
3
+ exp_name=mismatch_report
4
+ vfm_type=dinov2-L # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16}
5
+ mode=csa_vfm_distill
6
+ GPU_IDS=${GPU_IDS:-4} # 手动指定可用 GPU,例如 "0,1,2,3"
7
+ IFS=',' read -r -a GPU_ARR <<< "${GPU_IDS}"
8
+ NUM_GPUS=${#GPU_ARR[@]}
9
+ [ "${NUM_GPUS}" -lt 1 ] && NUM_GPUS=1
10
+ export CUDA_VISIBLE_DEVICES=${GPU_IDS}
11
+
12
+ # always keep total batchsize=16 , otherwise, Linear scaling the learning rate
13
+ 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 \
14
+ --model EVA02-CLIP-L-14-336 --pretrained eva --warmup 1000 --zeroshot-frequency 1 --dataset-type grid_distill \
15
+ --test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \
16
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
17
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy --train-image-root ${data_root}/train2017 \
18
+ --val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \
19
+ --lock-image --save-frequency 1 --lock-image-unlocked-groups 24 \
20
+ --name ${exp_name} --downsample-factor 14 --det-image-size 560 --val-segm-root ${data_root}/annotations/panoptic_val2017 \
21
+ --alpha 0.95 --use_vfm ${vfm_type} --mode ${mode} --loss_context_weight 0.05 --loss_content_weight 1.0 --repa_layer_idx -1 --eval
scripts/declip/dist_eva_vitb16_coco.sh ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # DeCLIP 解耦蒸馏 baseline:EVA-CLIP-B/16 多卡训练
3
+ # 用于与 Integrated 集成蒸馏对比,证明解耦蒸馏避免了优化冲突
4
+ # 注意:不使用 SD Attention,与 Integrated 配置对齐
5
+
6
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
7
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt
8
+ exp_name=DeCLIP_EVA-B_DINOv2-B_560
9
+ vfm_type=dinov2-B
10
+ dataset_type=grid_distill
11
+ version=declip
12
+ mode=csa_vfm_distill
13
+
14
+ # Parse arguments for nohup
15
+ USE_NOHUP=true
16
+ if [[ "$1" == "--nohup" ]] || [[ "$1" == "true" ]]; then
17
+ USE_NOHUP=true
18
+ fi
19
+
20
+ # 多卡训练:总 batch_size=16
21
+ cmd="CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12350 \
22
+ -m training.main \
23
+ --batch-size=2 \
24
+ --lr=1e-5 \
25
+ --wd=0.1 \
26
+ --epochs=6 \
27
+ --workers=4 \
28
+ --model EVA02-CLIP-B-16 \
29
+ --pretrained eva \
30
+ --warmup 1000 \
31
+ --zeroshot-frequency 6 \
32
+ --dataset-type ${dataset_type} \
33
+ --test-type coco_panoptic \
34
+ --train-data ${data_root}/annotations/instances_train2017.json \
35
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
36
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy \
37
+ --train-image-root ${data_root}/train2017 \
38
+ --val-image-root ${data_root}/val2017 \
39
+ --cache-dir ${pretrain_ckpt} \
40
+ --log-every-n-steps 100 \
41
+ --lock-image \
42
+ --save-frequency 1 \
43
+ --lock-image-unlocked-groups 12 \
44
+ --name ${exp_name} \
45
+ --downsample-factor 16 \
46
+ --det-image-size 560 \
47
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
48
+ --alpha 0.7 \
49
+ --mode ${mode} \
50
+ --use_vfm ${vfm_type} \
51
+ --loss_context_weight 0.25 \
52
+ --loss_content_weight 1.0 \
53
+ --loss_region_weight 0.05 \
54
+ --skip-first-eval \
55
+ --repa_layer_idx -1 \
56
+ --version ${version}"
57
+
58
+ if [ "$USE_NOHUP" = true ]; then
59
+ LOG_DIR="logs/${exp_name}"
60
+ mkdir -p "$LOG_DIR"
61
+ echo "Running with nohup. Output will be saved to ${LOG_DIR}/nohup.log"
62
+ nohup sh -c "$cmd" > "${LOG_DIR}/nohup.log" 2>&1 &
63
+ else
64
+ eval $cmd
65
+ fi
scripts/declip/dist_tinyclip_vitb16_coco.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
2
+ pretrain_ckpt=checkpoints/tinyclip_autovit45m_32_text18m_laionyfcc400m.pt
3
+ exp_name=TinyCLIP_B_Dinov2_B_csa_560_0.25_1.0
4
+ vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16}
5
+
6
+ # always keep total batchsize=16 , otherwise, Linear scaling the learning rate
7
+ python3 -m training.main -m training.main --batch-size=2 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \
8
+ --model TinyCLIP-auto-ViT-45M-32-Text-18M --pretrained laionyfcc400m --warmup 1000 --zeroshot-frequency 1 --dataset-type grid_distill \
9
+ --test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \
10
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
11
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy --train-image-root ${data_root}/train2017 \
12
+ --val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \
13
+ --lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \
14
+ --name ${exp_name} --downsample-factor 16 --det-image-size 560 --val-segm-root ${data_root}/annotations/panoptic_val2017 \
15
+ --alpha 0.7 --mode csa_vfm_distill --use_vfm ${vfm_type} --loss_context_weight 0.25 --loss_content_weight 1.0 --version declip
scripts/declip/eva_vitb16_coco.sh ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
2
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt
3
+ exp_name=EVA_B_DINOv2_B_csa_560_0.25_1.0_test
4
+ vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16}
5
+ mode=csa_vfm_distill
6
+
7
+ # Single GPU version for debugging
8
+ # Original: 8 GPUs with batch-size=2 each (total batchsize=16)
9
+ # Single GPU: batch-size=16 to keep total batchsize=16
10
+ python -m training.main --batch-size=2 --lr=1e-5 --wd=0.1 --epochs=6 --workers=4 \
11
+ --model EVA02-CLIP-B-16 --pretrained eva --warmup 1000 --zeroshot-frequency 1 --dataset-type grid_distill \
12
+ --test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \
13
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
14
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy --train-image-root ${data_root}/train2017 \
15
+ --val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \
16
+ --lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \
17
+ --name ${exp_name} --downsample-factor 16 --det-image-size 560 --val-segm-root ${data_root}/annotations/panoptic_val2017 \
18
+ --alpha 0.7 --mode ${mode} --use_vfm ${vfm_type} --loss_context_weight 0.25 --loss_content_weight 1.0 --version declip
scripts/declip/tinyclip_vitb16_coco.sh ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
2
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt
3
+ exp_name=evab_dinov2B_csa_560_0.05_2.0
4
+ vfm_type=dinov2-B # {sam-B, sam-L, dinov2-B, dinov2-L, dino-B-8, dino-B-16}
5
+ dataset_type=grid_distill # {proposals_distill,grid_distill,dift_grid_distill}
6
+
7
+ # always keep total batchsize=16 , otherwise, Linear scaling the learning rate
8
+ 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 \
9
+ --model EVA02-CLIP-B-16 --pretrained eva --warmup 1000 --zeroshot-frequency 1 --dataset-type ${dataset_type} \
10
+ --test-type coco_panoptic --train-data ${data_root}/annotations/instances_train2017.json \
11
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
12
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy --train-image-root ${data_root}/train2017 \
13
+ --val-image-root ${data_root}/val2017 --cache-dir ${pretrain_ckpt} --log-every-n-steps 100 \
14
+ --lock-image --save-frequency 1 --lock-image-unlocked-groups 12 \
15
+ --name ${exp_name} --downsample-factor 16 --det-image-size 560 --val-segm-root ${data_root}/annotations/panoptic_val2017 \
16
+ --alpha 0.7 --mode csa_vfm_distill --use_vfm ${vfm_type} --loss_context_weight 0.05 --loss_content_weight 1.0
scripts/decoupling_ablation/debug_integrated_eva_vitL14_336_coco.sh ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Integrated Distillation 消融实验:EVA-CLIP-L/14-336 单卡调试
3
+
4
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
5
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt
6
+ exp_name=Debug_Integrated_EVA-L_DINOv2-L_336
7
+ vfm_type=dinov2-L
8
+ dataset_type=grid_distill
9
+ version=integrated
10
+ mode=vanilla
11
+
12
+ CUDA_VISIBLE_DEVICES=0 python -m training.main \
13
+ --batch-size=2 \
14
+ --lr=1e-5 \
15
+ --wd=0.1 \
16
+ --epochs=1 \
17
+ --workers=4 \
18
+ --model EVA02-CLIP-L-14-336 \
19
+ --pretrained eva \
20
+ --warmup 100 \
21
+ --zeroshot-frequency 1 \
22
+ --dataset-type ${dataset_type} \
23
+ --test-type coco_panoptic \
24
+ --train-data ${data_root}/annotations/instances_train2017.json \
25
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
26
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy \
27
+ --train-image-root ${data_root}/train2017 \
28
+ --val-image-root ${data_root}/val2017 \
29
+ --cache-dir ${pretrain_ckpt} \
30
+ --log-every-n-steps 10 \
31
+ --lock-image \
32
+ --save-frequency 1 \
33
+ --lock-image-unlocked-groups 24 \
34
+ --name ${exp_name} \
35
+ --downsample-factor 14 \
36
+ --det-image-size 336 \
37
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
38
+ --alpha 0.7 \
39
+ --mode ${mode} \
40
+ --use_vfm ${vfm_type} \
41
+ --loss_context_weight 1.0 \
42
+ --loss_content_weight 1.0 \
43
+ --loss_region_weight 0.05 \
44
+ --skip-first-eval \
45
+ --repa_layer_idx -1 \
46
+ --version ${version}
scripts/decoupling_ablation/debug_integrated_eva_vitb16_coco.sh ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Integrated Distillation 消融实验:EVA-CLIP-B/16 单卡调试
3
+
4
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
5
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt
6
+ exp_name=Debug_Integrated_EVA-B_DINOv2-B_560
7
+ vfm_type=dinov2-B
8
+ dataset_type=grid_distill
9
+ version=integrated
10
+ mode=vanilla
11
+
12
+ # 单卡调试
13
+ CUDA_VISIBLE_DEVICES=0 python -m training.main \
14
+ --batch-size=4 \
15
+ --lr=1e-5 \
16
+ --wd=0.1 \
17
+ --epochs=1 \
18
+ --workers=4 \
19
+ --model EVA02-CLIP-B-16 \
20
+ --pretrained eva \
21
+ --warmup 100 \
22
+ --zeroshot-frequency 1 \
23
+ --dataset-type ${dataset_type} \
24
+ --test-type coco_panoptic \
25
+ --train-data ${data_root}/annotations/instances_train2017.json \
26
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
27
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy \
28
+ --train-image-root ${data_root}/train2017 \
29
+ --val-image-root ${data_root}/val2017 \
30
+ --cache-dir ${pretrain_ckpt} \
31
+ --log-every-n-steps 10 \
32
+ --lock-image \
33
+ --save-frequency 1 \
34
+ --lock-image-unlocked-groups 12 \
35
+ --name ${exp_name} \
36
+ --downsample-factor 16 \
37
+ --det-image-size 560 \
38
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
39
+ --alpha 0.7 \
40
+ --mode ${mode} \
41
+ --use_vfm ${vfm_type} \
42
+ --loss_context_weight 1.0 \
43
+ --loss_content_weight 1.0 \
44
+ --loss_region_weight 0.05 \
45
+ --skip-first-eval \
46
+ --repa_layer_idx -1 \
47
+ --version ${version}
scripts/decoupling_ablation/debug_integrated_openai_vitL14_coco.sh ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Integrated Distillation 消融实验:OpenAI-CLIP-L/14 单卡调试
3
+
4
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
5
+ exp_name=Debug_Integrated_OpenAI-L_DINOv2-L_336
6
+ vfm_type=dinov2-L
7
+ dataset_type=grid_distill
8
+ version=integrated
9
+ mode=vanilla
10
+
11
+ CUDA_VISIBLE_DEVICES=0 python -m training.main \
12
+ --batch-size=2 \
13
+ --lr=1e-5 \
14
+ --wd=0.1 \
15
+ --epochs=1 \
16
+ --workers=4 \
17
+ --model ViT-L-14 \
18
+ --pretrained openai \
19
+ --warmup 100 \
20
+ --zeroshot-frequency 1 \
21
+ --dataset-type ${dataset_type} \
22
+ --test-type coco_panoptic \
23
+ --train-data ${data_root}/annotations/instances_train2017.json \
24
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
25
+ --embed-path metadata/coco_panoptic_clip_hand_craft_ViTL14.npy \
26
+ --train-image-root ${data_root}/train2017 \
27
+ --val-image-root ${data_root}/val2017 \
28
+ --log-every-n-steps 10 \
29
+ --lock-image \
30
+ --save-frequency 1 \
31
+ --lock-image-unlocked-groups 24 \
32
+ --name ${exp_name} \
33
+ --downsample-factor 14 \
34
+ --det-image-size 336 \
35
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
36
+ --alpha 0.7 \
37
+ --mode ${mode} \
38
+ --use_vfm ${vfm_type} \
39
+ --loss_context_weight 1.0 \
40
+ --loss_content_weight 1.0 \
41
+ --loss_region_weight 0.05 \
42
+ --skip-first-eval \
43
+ --repa_layer_idx -1 \
44
+ --version ${version}
scripts/decoupling_ablation/debug_integrated_openai_vitb16_coco.sh ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Integrated Distillation 消融实验:OpenAI-CLIP-B/16 单卡调试
3
+
4
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
5
+ exp_name=Debug_Integrated_OpenAI-B_DINOv2-B_560
6
+ vfm_type=dinov2-B
7
+ dataset_type=grid_distill
8
+ version=integrated
9
+ mode=vanilla
10
+
11
+ CUDA_VISIBLE_DEVICES=0 python -m training.main \
12
+ --batch-size=4 \
13
+ --lr=1e-5 \
14
+ --wd=0.1 \
15
+ --epochs=1 \
16
+ --workers=4 \
17
+ --model ViT-B-16 \
18
+ --pretrained openai \
19
+ --warmup 100 \
20
+ --zeroshot-frequency 1 \
21
+ --dataset-type ${dataset_type} \
22
+ --test-type coco_panoptic \
23
+ --train-data ${data_root}/annotations/instances_train2017.json \
24
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
25
+ --embed-path metadata/coco_panoptic_clip_hand_craft_ViTB16.npy \
26
+ --train-image-root ${data_root}/train2017 \
27
+ --val-image-root ${data_root}/val2017 \
28
+ --log-every-n-steps 10 \
29
+ --lock-image \
30
+ --save-frequency 1 \
31
+ --lock-image-unlocked-groups 12 \
32
+ --name ${exp_name} \
33
+ --downsample-factor 16 \
34
+ --det-image-size 560 \
35
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
36
+ --alpha 0.7 \
37
+ --mode ${mode} \
38
+ --use_vfm ${vfm_type} \
39
+ --loss_context_weight 1.0 \
40
+ --loss_content_weight 1.0 \
41
+ --loss_region_weight 0.05 \
42
+ --skip-first-eval \
43
+ --repa_layer_idx -1 \
44
+ --version ${version}
scripts/decoupling_ablation/dist_integrated_eva_vitL14_336_coco.sh ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Integrated Distillation 消融实验:EVA-CLIP-L/14-336 多卡训练
3
+
4
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
5
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt
6
+ exp_name=Integrated_EVA-L_DINOv2-L_336
7
+ vfm_type=dinov2-L
8
+ dataset_type=grid_distill
9
+ version=integrated
10
+ mode=vanilla
11
+
12
+ USE_NOHUP=true
13
+ if [[ "$1" == "--nohup" ]] || [[ "$1" == "true" ]]; then
14
+ USE_NOHUP=true
15
+ fi
16
+
17
+ cmd="CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12367 \
18
+ -m training.main \
19
+ --batch-size=2 \
20
+ --lr=1e-5 \
21
+ --wd=0.1 \
22
+ --epochs=6 \
23
+ --workers=4 \
24
+ --model EVA02-CLIP-L-14-336 \
25
+ --pretrained eva \
26
+ --warmup 1000 \
27
+ --zeroshot-frequency 6 \
28
+ --dataset-type ${dataset_type} \
29
+ --test-type coco_panoptic \
30
+ --train-data ${data_root}/annotations/instances_train2017.json \
31
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
32
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTL14x336.npy \
33
+ --train-image-root ${data_root}/train2017 \
34
+ --val-image-root ${data_root}/val2017 \
35
+ --cache-dir ${pretrain_ckpt} \
36
+ --log-every-n-steps 100 \
37
+ --lock-image \
38
+ --save-frequency 1 \
39
+ --lock-image-unlocked-groups 24 \
40
+ --name ${exp_name} \
41
+ --downsample-factor 14 \
42
+ --det-image-size 560 \
43
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
44
+ --alpha 0.7 \
45
+ --mode ${mode} \
46
+ --use_vfm ${vfm_type} \
47
+ --loss_context_weight 1.0 \
48
+ --loss_content_weight 1.0 \
49
+ --loss_region_weight 0.05 \
50
+ --skip-first-eval \
51
+ --repa_layer_idx -1 \
52
+ --version ${version}"
53
+
54
+ if [ "$USE_NOHUP" = true ]; then
55
+ LOG_DIR="logs/${exp_name}"
56
+ mkdir -p "$LOG_DIR"
57
+ echo "Running with nohup. Output will be saved to ${LOG_DIR}/nohup.log"
58
+ nohup sh -c "$cmd" > "${LOG_DIR}/nohup.log" 2>&1 &
59
+ else
60
+ eval $cmd
61
+ fi
scripts/decoupling_ablation/dist_integrated_eva_vitb16_coco.sh ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Integrated Distillation 消融实验:EVA-CLIP-B/16 多卡训练
3
+ # 对比 DeCLIP 解耦蒸馏,用于证明解耦蒸馏避免了优化冲突
4
+
5
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
6
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt
7
+ vfm_type=dinov2-B
8
+ dataset_type=grid_distill
9
+ version=integrated_grad_analysis
10
+ mode=vanilla
11
+
12
+ # 根据 version 设置实验名称
13
+ if [[ "$version" == "integrated_grad_analysis" ]]; then
14
+ exp_name=Integrated_EVA-B_DINOv2-B_560_grad_analysis_2loss
15
+ else
16
+ exp_name=Integrated_EVA-B_DINOv2-B_560_2loss
17
+ fi
18
+
19
+ # Parse arguments for nohup
20
+ USE_NOHUP=true
21
+ if [[ "$1" == "--nohup" ]] || [[ "$1" == "true" ]]; then
22
+ USE_NOHUP=true
23
+ fi
24
+
25
+ # 多卡训练:总 batch_size=16
26
+ cmd="CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12348 \
27
+ -m training.main \
28
+ --batch-size=2 \
29
+ --lr=1e-5 \
30
+ --wd=0.1 \
31
+ --epochs=6 \
32
+ --workers=4 \
33
+ --model EVA02-CLIP-B-16 \
34
+ --pretrained eva \
35
+ --warmup 1000 \
36
+ --zeroshot-frequency 6 \
37
+ --dataset-type ${dataset_type} \
38
+ --test-type coco_panoptic \
39
+ --train-data ${data_root}/annotations/instances_train2017.json \
40
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
41
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy \
42
+ --train-image-root ${data_root}/train2017 \
43
+ --val-image-root ${data_root}/val2017 \
44
+ --cache-dir ${pretrain_ckpt} \
45
+ --log-every-n-steps 100 \
46
+ --lock-image \
47
+ --save-frequency 1 \
48
+ --lock-image-unlocked-groups 12 \
49
+ --name ${exp_name} \
50
+ --downsample-factor 16 \
51
+ --det-image-size 560 \
52
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
53
+ --alpha 0.7 \
54
+ --mode ${mode} \
55
+ --use_vfm ${vfm_type} \
56
+ --loss_context_weight 0.25 \
57
+ --loss_content_weight 1.0 \
58
+ --skip-first-eval \
59
+ --repa_layer_idx -1 \
60
+ --version ${version}"
61
+
62
+ if [ "$USE_NOHUP" = true ]; then
63
+ LOG_DIR="logs/${exp_name}"
64
+ mkdir -p "$LOG_DIR"
65
+ echo "Running with nohup. Output will be saved to ${LOG_DIR}/nohup.log"
66
+ nohup sh -c "$cmd" > "${LOG_DIR}/nohup.log" 2>&1 &
67
+ else
68
+ eval $cmd
69
+ fi
scripts/decoupling_ablation/dist_integrated_openai_vitL14_coco.sh ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Integrated Distillation 消融实验:OpenAI-CLIP-L/14 多卡训练
3
+
4
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
5
+ exp_name=Integrated_OpenAI-L_DINOv2-L_336
6
+ vfm_type=dinov2-L
7
+ dataset_type=grid_distill
8
+ version=integrated
9
+ mode=vanilla
10
+
11
+ USE_NOHUP=true
12
+ if [[ "$1" == "--nohup" ]] || [[ "$1" == "true" ]]; then
13
+ USE_NOHUP=true
14
+ fi
15
+
16
+ cmd="CUDA_VISIBLE_DEVICES=0,1,2,3 torchrun --nproc_per_node 4 --master_port 29505 \
17
+ -m training.main \
18
+ --batch-size=4 \
19
+ --lr=1e-5 \
20
+ --wd=0.1 \
21
+ --epochs=6 \
22
+ --workers=4 \
23
+ --model ViT-L-14 \
24
+ --pretrained openai \
25
+ --warmup 1000 \
26
+ --zeroshot-frequency 6 \
27
+ --dataset-type ${dataset_type} \
28
+ --test-type coco_panoptic \
29
+ --train-data ${data_root}/annotations/instances_train2017.json \
30
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
31
+ --embed-path metadata/coco_panoptic_clip_hand_craft_ViTL14.npy \
32
+ --train-image-root ${data_root}/train2017 \
33
+ --val-image-root ${data_root}/val2017 \
34
+ --log-every-n-steps 100 \
35
+ --lock-image \
36
+ --save-frequency 1 \
37
+ --lock-image-unlocked-groups 24 \
38
+ --name ${exp_name} \
39
+ --downsample-factor 14 \
40
+ --det-image-size 336 \
41
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
42
+ --alpha 0.7 \
43
+ --mode ${mode} \
44
+ --use_vfm ${vfm_type} \
45
+ --loss_context_weight 1.0 \
46
+ --loss_content_weight 1.0 \
47
+ --loss_region_weight 0.05 \
48
+ --skip-first-eval \
49
+ --repa_layer_idx -1 \
50
+ --version ${version}"
51
+
52
+ if [ "$USE_NOHUP" = true ]; then
53
+ LOG_DIR="logs/${exp_name}"
54
+ mkdir -p "$LOG_DIR"
55
+ echo "Running with nohup. Output will be saved to ${LOG_DIR}/nohup.log"
56
+ nohup sh -c "$cmd" > "${LOG_DIR}/nohup.log" 2>&1 &
57
+ else
58
+ eval $cmd
59
+ fi
scripts/decoupling_ablation/dist_integrated_openai_vitb16_coco.sh ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Integrated Distillation 消融实验:OpenAI-CLIP-B/16 多卡训练
3
+
4
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
5
+ exp_name=Integrated_OpenAI-B_DINOv2-B_560
6
+ vfm_type=dinov2-B
7
+ dataset_type=grid_distill
8
+ version=integrated
9
+ mode=vanilla
10
+
11
+ USE_NOHUP=true
12
+ if [[ "$1" == "--nohup" ]] || [[ "$1" == "true" ]]; then
13
+ USE_NOHUP=true
14
+ fi
15
+
16
+ # 多卡训练:总 batch_size=16
17
+ cmd="CUDA_VISIBLE_DEVICES=0,1,2,3 torchrun --nproc_per_node 4 --master_port 29504 \
18
+ -m training.main \
19
+ --batch-size=4 \
20
+ --lr=1e-5 \
21
+ --wd=0.1 \
22
+ --epochs=6 \
23
+ --workers=4 \
24
+ --model ViT-B-16 \
25
+ --pretrained openai \
26
+ --warmup 1000 \
27
+ --zeroshot-frequency 6 \
28
+ --dataset-type ${dataset_type} \
29
+ --test-type coco_panoptic \
30
+ --train-data ${data_root}/annotations/instances_train2017.json \
31
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
32
+ --embed-path metadata/coco_panoptic_clip_hand_craft_ViTB16.npy \
33
+ --train-image-root ${data_root}/train2017 \
34
+ --val-image-root ${data_root}/val2017 \
35
+ --log-every-n-steps 100 \
36
+ --lock-image \
37
+ --save-frequency 1 \
38
+ --lock-image-unlocked-groups 12 \
39
+ --name ${exp_name} \
40
+ --downsample-factor 16 \
41
+ --det-image-size 560 \
42
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
43
+ --alpha 0.7 \
44
+ --mode ${mode} \
45
+ --use_vfm ${vfm_type} \
46
+ --loss_context_weight 1.0 \
47
+ --loss_content_weight 1.0 \
48
+ --loss_region_weight 0.05 \
49
+ --skip-first-eval \
50
+ --repa_layer_idx -1 \
51
+ --version ${version}"
52
+
53
+ if [ "$USE_NOHUP" = true ]; then
54
+ LOG_DIR="logs/${exp_name}"
55
+ mkdir -p "$LOG_DIR"
56
+ echo "Running with nohup. Output will be saved to ${LOG_DIR}/nohup.log"
57
+ nohup sh -c "$cmd" > "${LOG_DIR}/nohup.log" 2>&1 &
58
+ else
59
+ eval $cmd
60
+ fi
scripts/decoupling_ablation/resume_all_experiments.sh ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Resume 所有因 evaluation bug 中断的实验
3
+ # Bug 已修复:src/training/data.py 第 715 行 np.asarray -> np.array
4
+
5
+ set -e
6
+
7
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
8
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt
9
+
10
+ # 选择要 resume 的实验
11
+ # 1: Integrated_EVA-B_DINOv2-B_560
12
+ # 2: Integrated_EVA-B_DINOv2-B_560_grad_analysis
13
+ # all: 两个都跑
14
+ EXPERIMENT=${1:-"all"}
15
+
16
+ resume_integrated() {
17
+ local exp_name=$1
18
+ local version=$2
19
+ local resume_ckpt="logs/${exp_name}/checkpoints/epoch_5.pt"
20
+
21
+ if [ ! -f "$resume_ckpt" ]; then
22
+ echo "Checkpoint not found: $resume_ckpt"
23
+ return 1
24
+ fi
25
+
26
+ echo "=============================================="
27
+ echo "Resuming: $exp_name"
28
+ echo "Checkpoint: $resume_ckpt"
29
+ echo "=============================================="
30
+
31
+ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12349 \
32
+ -m training.main \
33
+ --batch-size=2 \
34
+ --lr=1e-5 \
35
+ --wd=0.1 \
36
+ --epochs=6 \
37
+ --workers=4 \
38
+ --model EVA02-CLIP-B-16 \
39
+ --pretrained eva \
40
+ --warmup 1000 \
41
+ --zeroshot-frequency 6 \
42
+ --dataset-type grid_distill \
43
+ --test-type coco_panoptic \
44
+ --train-data ${data_root}/annotations/instances_train2017.json \
45
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
46
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy \
47
+ --train-image-root ${data_root}/train2017 \
48
+ --val-image-root ${data_root}/val2017 \
49
+ --cache-dir ${pretrain_ckpt} \
50
+ --log-every-n-steps 100 \
51
+ --lock-image \
52
+ --save-frequency 1 \
53
+ --lock-image-unlocked-groups 12 \
54
+ --name ${exp_name} \
55
+ --downsample-factor 16 \
56
+ --det-image-size 560 \
57
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
58
+ --alpha 0.7 \
59
+ --mode vanilla \
60
+ --use_vfm dinov2-B \
61
+ --loss_context_weight 1.0 \
62
+ --loss_content_weight 1.0 \
63
+ --loss_region_weight 0.05 \
64
+ --repa_layer_idx -1 \
65
+ --version ${version} \
66
+ --resume ${resume_ckpt}
67
+ }
68
+
69
+ cd /opt/tiger/xiaomoguhzz/DeCLIP_private
70
+
71
+ case $EXPERIMENT in
72
+ "1"|"integrated")
73
+ resume_integrated "Integrated_EVA-B_DINOv2-B_560" "integrated"
74
+ ;;
75
+ "2"|"grad_analysis")
76
+ resume_integrated "Integrated_EVA-B_DINOv2-B_560_grad_analysis" "integrated_grad_analysis"
77
+ ;;
78
+ "all")
79
+ echo "Resuming all experiments sequentially..."
80
+ resume_integrated "Integrated_EVA-B_DINOv2-B_560" "integrated"
81
+ resume_integrated "Integrated_EVA-B_DINOv2-B_560_grad_analysis" "integrated_grad_analysis"
82
+ ;;
83
+ *)
84
+ echo "Usage: $0 [1|integrated|2|grad_analysis|all]"
85
+ echo " 1/integrated - Resume Integrated_EVA-B_DINOv2-B_560"
86
+ echo " 2/grad_analysis - Resume Integrated_EVA-B_DINOv2-B_560_grad_analysis"
87
+ echo " all - Resume all experiments"
88
+ exit 1
89
+ ;;
90
+ esac
91
+
92
+ echo "Done!"
scripts/decoupling_ablation/resume_integrated.sh ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Resume Integrated_EVA-B_DINOv2-B_560 实验
3
+
4
+ data_root=/opt/tiger/xiaomoguhzz/standard_coco
5
+ pretrain_ckpt=/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt
6
+ exp_name=Integrated_EVA-B_DINOv2-B_560
7
+ resume_ckpt=logs/${exp_name}/checkpoints/epoch_5.pt
8
+
9
+ cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private
10
+
11
+ echo "Resuming: $exp_name"
12
+ echo "Checkpoint: $resume_ckpt"
13
+
14
+ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node 8 --master_port 12349 \
15
+ -m training.main \
16
+ --batch-size=2 \
17
+ --lr=1e-5 \
18
+ --wd=0.1 \
19
+ --epochs=6 \
20
+ --workers=4 \
21
+ --model EVA02-CLIP-B-16 \
22
+ --pretrained eva \
23
+ --warmup 1000 \
24
+ --zeroshot-frequency 6 \
25
+ --dataset-type grid_distill \
26
+ --test-type coco_panoptic \
27
+ --train-data ${data_root}/annotations/instances_train2017.json \
28
+ --val-data ${data_root}/annotations/panoptic_val2017.json \
29
+ --embed-path metadata/coco_panoptic_clip_hand_craft_EVACLIP_ViTB16.npy \
30
+ --train-image-root ${data_root}/train2017 \
31
+ --val-image-root ${data_root}/val2017 \
32
+ --cache-dir ${pretrain_ckpt} \
33
+ --log-every-n-steps 100 \
34
+ --lock-image \
35
+ --save-frequency 1 \
36
+ --lock-image-unlocked-groups 12 \
37
+ --name ${exp_name} \
38
+ --downsample-factor 16 \
39
+ --det-image-size 560 \
40
+ --val-segm-root ${data_root}/annotations/panoptic_val2017 \
41
+ --alpha 0.7 \
42
+ --mode vanilla \
43
+ --use_vfm dinov2-B \
44
+ --loss_context_weight 1.0 \
45
+ --loss_content_weight 1.0 \
46
+ --loss_region_weight 0.05 \
47
+ --repa_layer_idx -1 \
48
+ --version integrated \
49
+ --resume ${resume_ckpt}