config.py 11 KB

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