saliacoel commited on
Commit
d7390a9
·
verified ·
1 Parent(s): 6432d29

Upload config.py

Browse files
Files changed (1) hide show
  1. config.py +229 -0
config.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import math
3
+
4
+
5
+ class Config():
6
+ def __init__(self) -> None:
7
+ # Main active settings
8
+ self.batch_size = 8 # Multi-GPU+BF16 training for 76GB / 62GB, without/with compile, on each A100.
9
+ self.compile = True # 1. PyTorch<=2.0.1 has an inherent CPU memory leak problem; 2.0.1<PyTorch<2.5.0 cannot successfully compile.
10
+ self.mixed_precision = ['no', 'fp16', 'bf16', 'fp8'][2] # 2. FP8 doesn't show acceleration in the torch.compile mode.
11
+ self.SDPA_enabled = True # H200x1 + compile==True. None: 43GB + 14s, math: 43GB + 15s, mem_eff: 35GB + 15s.
12
+ # H200x1 + compile==False. None: 54GB + 25s, math: 51GB + 26s, mem_eff: 40GB + 25s.
13
+
14
+ # PATH settings
15
+ # Make up your file system as: SYS_HOME_DIR/codes/dis/BiRefNet, SYS_HOME_DIR/datasets/dis/xx, SYS_HOME_DIR/weights/xx
16
+ self.sys_home_dir = [os.path.expanduser('~'), '/workspace'][1] # Default, custom
17
+ self.data_root_dir = os.path.join(self.sys_home_dir, 'datasets/dis')
18
+
19
+ # TASK settings
20
+ self.task = ['DIS5K', 'COD', 'HRSOD', 'General', 'General-2K', 'Matting'][0]
21
+ self.testsets = {
22
+ # Benchmarks
23
+ 'DIS5K': ','.join(['DIS-VD', 'DIS-TE1', 'DIS-TE2', 'DIS-TE3', 'DIS-TE4'][:1]),
24
+ 'COD': ','.join(['CHAMELEON', 'NC4K', 'TE-CAMO', 'TE-COD10K']),
25
+ 'HRSOD': ','.join(['DAVIS-S', 'TE-HRSOD', 'TE-UHRSD', 'DUT-OMRON', 'TE-DUTS']),
26
+ # Practical use
27
+ 'General': ','.join(['DIS-VD', 'TE-P3M-500-NP']),
28
+ 'General-2K': ','.join(['DIS-VD', 'TE-P3M-500-NP']),
29
+ 'Matting': ','.join(['TE-P3M-500-NP', 'TE-AM-2k']),
30
+ }[self.task]
31
+ datasets_all = '+'.join([ds for ds in (os.listdir(os.path.join(self.data_root_dir, self.task)) if os.path.isdir(os.path.join(self.data_root_dir, self.task)) else []) if ds not in self.testsets.split(',')])
32
+ self.training_set = {
33
+ 'DIS5K': ['DIS-TR', 'DIS-TR+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4'][0],
34
+ 'COD': 'TR-COD10K+TR-CAMO',
35
+ 'HRSOD': ['TR-DUTS', 'TR-HRSOD', 'TR-UHRSD', 'TR-DUTS+TR-HRSOD', 'TR-DUTS+TR-UHRSD', 'TR-HRSOD+TR-UHRSD', 'TR-DUTS+TR-HRSOD+TR-UHRSD'][5],
36
+ 'General': datasets_all,
37
+ 'General-2K': datasets_all,
38
+ 'Matting': datasets_all,
39
+ }[self.task]
40
+
41
+ # Data settings
42
+ self.size = (1024, 1024) if self.task not in ['General-2K'] else (2560, 1440) # wid, hei. Can be overwritten by dynamic_size in training.
43
+ self.dynamic_size = [None, ((512-256, 2048+256), (512-256, 2048+256))][0] # wid, hei. It might cause errors in using compile.
44
+ self.background_color_synthesis = False # whether to use pure bg color to replace the original backgrounds.
45
+
46
+ # Faster-Training settings
47
+ self.precisionHigh = True
48
+ self.load_all = False and self.dynamic_size is None # Turn it on/off by your case. It may consume a lot of CPU memory. And for multi-GPU (N), it would cost N times the CPU memory to load the data.
49
+ # Machines with > 70GB CPU memory can run the whole training on DIS5K with default setting.
50
+ # 2. Higher PyTorch version may fix it: https://github.com/pytorch/pytorch/issues/119607.
51
+ # 3. But compile in 2.0.1 < Pytorch < 2.5.0 seems to bring no acceleration for training.
52
+
53
+ # MODEL settings
54
+ self.ms_supervision = True
55
+ self.out_ref = self.ms_supervision and True
56
+ self.dec_ipt = True
57
+ self.dec_ipt_split = True
58
+ self.cxt_num = [0, 3][1] # multi-scale skip connections from encoder
59
+ self.mul_scl_ipt = ['', 'add', 'cat'][2]
60
+ self.dec_att = ['', 'ASPP', 'ASPPDeformable'][2]
61
+ self.squeeze_block = ['', 'BasicDecBlk_x1', 'ResBlk_x4', 'ASPP_x3', 'ASPPDeformable_x3'][1]
62
+ self.dec_blk = ['BasicDecBlk', 'ResBlk'][0]
63
+
64
+ # TRAINING settings
65
+ self.finetune_last_epochs = [
66
+ 0,
67
+ {
68
+ 'DIS5K': -40,
69
+ 'COD': -20,
70
+ 'HRSOD': -20,
71
+ 'General': -20,
72
+ 'General-2K': -20,
73
+ 'Matting': -10,
74
+ }[self.task]
75
+ ][1] # choose 0 to skip
76
+ self.lr = (1e-4 if 'DIS5K' in self.task else 1e-5) * math.sqrt(self.batch_size / 4) # DIS needs high lr to converge faster. Adapt the lr linearly
77
+ self.num_workers = max(4, self.batch_size) # will be decreased to min(it, batch_size) at the initialization of the data_loader
78
+
79
+ # Backbone settings
80
+ #
81
+ # PATCH (ComfyUI_BiRefNet_ONNX_Exporter):
82
+ # Pin backbone explicitly so you never have to edit config.py at runtime,
83
+ # and so list index drift can't change the selected backbone.
84
+ self.bb = 'swin_v1_l'
85
+
86
+ # Original (kept for reference):
87
+ # self.bb = [
88
+ # 'vgg16', 'vgg16bn', 'resnet50',
89
+ #
90
+ # 'swin_v1_l', 'swin_v1_b',
91
+ # 'swin_v1_s', 'swin_v1_t',
92
+ #
93
+ # 'pvt_v2_b5', 'pvt_v2_b2',
94
+ # 'pvt_v2_b1', 'pvt_v2_b0',
95
+ #
96
+ # 'dino_v3_7b', 'dino_v3_h_plus', 'dino_v3_l',
97
+ # 'dino_v3_b', 'dino_v3_s_plus', 'dino_v3_s',
98
+ # ][3]
99
+
100
+ self.freeze_bb = 'dino_v3' in self.bb
101
+ self.lateral_channels_in_collection = {
102
+ 'vgg16': [512, 512, 256, 128], 'vgg16bn': [512, 512, 256, 128], 'resnet50': [2048, 1024, 512, 256],
103
+
104
+ 'dino_v3_7b': [4096] * 4, 'dino_v3_h_plus': [1280] * 4, 'dino_v3_l': [1024] * 4,
105
+ 'dino_v3_b': [768] * 4, 'dino_v3_s_plus': [384] * 4, 'dino_v3_s': [384] * 4,
106
+
107
+ 'swin_v1_l': [1536, 768, 384, 192], 'swin_v1_b': [1024, 512, 256, 128],
108
+ 'swin_v1_s': [768, 384, 192, 96], 'swin_v1_t': [768, 384, 192, 96],
109
+
110
+ 'pvt_v2_b5': [512, 320, 128, 64], 'pvt_v2_b2': [512, 320, 128, 64],
111
+ 'pvt_v2_b1': [512, 320, 128, 64], 'pvt_v2_b0': [256, 160, 64, 32],
112
+ }[self.bb]
113
+ if self.mul_scl_ipt == 'cat':
114
+ self.lateral_channels_in_collection = [channel * 2 for channel in self.lateral_channels_in_collection]
115
+ self.cxt = self.lateral_channels_in_collection[1:][::-1][-self.cxt_num:] if self.cxt_num else []
116
+
117
+ # MODEL settings - inactive
118
+ self.lat_blk = ['BasicLatBlk'][0]
119
+ self.dec_channels_inter = ['fixed', 'adap'][0]
120
+ self.auxiliary_classification = False # Only for DIS5K, where class labels are saved in `dataset.py`.
121
+ self.model = [
122
+ 'BiRefNet',
123
+ ][0]
124
+
125
+ # TRAINING settings - inactive
126
+ self.preproc_methods = ['flip', 'enhance', 'rotate', 'pepper', 'crop'][:4 if not self.background_color_synthesis else 1]
127
+ self.optimizer = ['Adam', 'AdamW'][1]
128
+ self.lr_decay_epochs = [1e5] # Set to negative N to decay the lr in the last N-th epoch.
129
+ self.lr_decay_rate = 0.5
130
+ # Loss
131
+ if self.task in ['Matting']:
132
+ self.lambdas_pix_last = {
133
+ 'bce': 30 * 1,
134
+ 'iou': 0.5 * 0,
135
+ 'iou_patch': 0.5 * 0,
136
+ 'mae': 100 * 1,
137
+ 'mse': 30 * 0,
138
+ 'triplet': 3 * 0,
139
+ 'reg': 100 * 0,
140
+ 'ssim': 10 * 1,
141
+ 'cnt': 5 * 0,
142
+ 'structure': 5 * 0,
143
+ }
144
+ elif self.task in ['General', 'General-2K']:
145
+ self.lambdas_pix_last = {
146
+ 'bce': 30 * 1,
147
+ 'iou': 0.5 * 1,
148
+ 'iou_patch': 0.5 * 0,
149
+ 'mae': 100 * 1,
150
+ 'mse': 30 * 0,
151
+ 'triplet': 3 * 0,
152
+ 'reg': 100 * 0,
153
+ 'ssim': 10 * 1,
154
+ 'cnt': 5 * 0,
155
+ 'structure': 5 * 0,
156
+ }
157
+ else:
158
+ self.lambdas_pix_last = {
159
+ # not 0 means opening this loss
160
+ # original rate -- 1 : 30 : 1.5 : 0.2, bce x 30
161
+ 'bce': 30 * 1, # high performance
162
+ 'iou': 0.5 * 1, # 0 / 255
163
+ 'iou_patch': 0.5 * 0, # 0 / 255, win_size = (64, 64)
164
+ 'mae': 30 * 0,
165
+ 'mse': 30 * 0, # can smooth the saliency map
166
+ 'triplet': 3 * 0,
167
+ 'reg': 100 * 0,
168
+ 'ssim': 10 * 1, # help contours,
169
+ 'cnt': 5 * 0, # help contours
170
+ 'structure': 5 * 0, # structure loss from codes of MVANet. A little improvement on DIS-TE[1,2,3], a bit more decrease on DIS-TE4.
171
+ }
172
+ self.lambdas_cls = {
173
+ 'ce': 5.0
174
+ }
175
+
176
+ # PATH settings - inactive
177
+ self.weights_root_dir = os.path.join(self.sys_home_dir, 'weights/cv')
178
+ model_name_to_weights_file = {
179
+ 'dino_v3_7b': 'vit_7b_patch16_dinov3.lvd1689m.pth', 'dino_v3_h_plus': 'vit_huge_plus_patch16_dinov3.lvd1689m.pth',
180
+ 'dino_v3_l': 'vit_large_patch16_dinov3.lvd1689m.pth', 'dino_v3_b': 'vit_base_patch16_dinov3.lvd1689m.pth',
181
+ 'dino_v3_s_plus': 'vit_small_plus_patch16_dinov3.lvd1689m.pth', 'dino_v3_s': 'vit_small_patch16_dinov3.lvd1689m.pth',
182
+ 'swin_v1_l': 'swin_large_patch4_window12_384_22kto1k.pth', 'swin_v1_b': 'swin_base_patch4_window12_384_22kto1k.pth',
183
+ 'swin_v1_t': 'swin_tiny_patch4_window7_224_22kto1k_finetune.pth', 'swin_v1_s': 'swin_small_patch4_window7_224_22kto1k_finetune.pth',
184
+ 'pvt_v2_b5': 'pvt_v2_b5.pth', 'pvt_v2_b2': 'pvt_v2_b2.pth', 'pvt_v2_b1': 'pvt_v2_b1.pth', 'pvt_v2_b0': 'pvt_v2_b0.pth',
185
+ }
186
+ self.weights = {}
187
+ for model_name, weights_file in model_name_to_weights_file.items():
188
+ if 'dino_v3' in model_name:
189
+ model_name_dir = 'DINOv3-timm'
190
+ elif 'swin_v1' in model_name:
191
+ model_name_dir = ''
192
+ elif 'pvt_v2' in model_name:
193
+ model_name_dir = ''
194
+ else:
195
+ model_name_dir = ''
196
+ self.weights[model_name] = os.path.join(self.weights_root_dir, model_name_dir, weights_file)
197
+
198
+
199
+ # Callbacks - inactive
200
+ self.verbose_eval = True
201
+ self.only_S_MAE = False
202
+
203
+ # others
204
+ self.device = [0, 'cpu'][0] # .to(0) == .to('cuda:0')
205
+
206
+ self.batch_size_valid = 1
207
+ self.rand_seed = 7
208
+ run_sh_file = [f for f in os.listdir('.') if 'train.sh' == f] + [os.path.join('..', f) for f in os.listdir('..') if 'train.sh' == f]
209
+ if run_sh_file:
210
+ with open(run_sh_file[0], 'r') as f:
211
+ lines = f.readlines()
212
+ self.save_last = int([l.strip() for l in lines if "'{}')".format(self.task) in l and 'val_last=' in l][0].split('val_last=')[-1].split()[0])
213
+ self.save_step = int([l.strip() for l in lines if "'{}')".format(self.task) in l and 'step=' in l][0].split('step=')[-1].split()[0])
214
+
215
+
216
+ # Return task for choosing settings in shell scripts.
217
+ if __name__ == '__main__':
218
+ import argparse
219
+
220
+
221
+ parser = argparse.ArgumentParser(description='Only choose one argument to activate.')
222
+ parser.add_argument('--print_task', action='store_true', help='print task name')
223
+ parser.add_argument('--print_testsets', action='store_true', help='print validation set')
224
+ args = parser.parse_args()
225
+
226
+ config = Config()
227
+ for arg_name, arg_value in args._get_kwargs():
228
+ if arg_value:
229
+ print(config.__getattribute__(arg_name[len('print_'):]))