├── .github └── workflows │ └── publish.yml ├── .gitignore ├── BiRefNet_node.py ├── README.md ├── __init__.py ├── assets ├── 00.jpg ├── 01.jpg ├── 02.jpg └── Screenshot-2024-03-21-at-19.26.21.png ├── config.py ├── dataset.py ├── debug.ipynb ├── install.py ├── models ├── __init__.py ├── backbones │ ├── __init__.py │ ├── build_backbone.py │ ├── pvt_v2.py │ └── swin_v1.py ├── baseline.py ├── modules │ ├── __init__.py │ ├── aspp.py │ ├── attentions.py │ ├── decoder_blocks.py │ ├── deform_conv.py │ ├── ing.py │ ├── lateral_blocks.py │ ├── mlp.py │ └── utils.py └── refinement │ ├── __init__.py │ ├── refiner.py │ └── stem_layer.py ├── preproc.py ├── pyproject.toml ├── requirements.txt ├── utils.py └── workflow └── example_workflow.json /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish to Comfy registry 2 | on: 3 | workflow_dispatch: 4 | push: 5 | branches: 6 | - main 7 | paths: 8 | - "pyproject.toml" 9 | 10 | jobs: 11 | publish-node: 12 | name: Publish Custom Node to registry 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Check out code 16 | uses: actions/checkout@v4 17 | - name: Publish Custom Node 18 | uses: Comfy-Org/publish-node-action@main 19 | with: 20 | ## Add your own personal access token to your Github Repository secrets and reference it here. 21 | personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }} 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | __pycache__/ 3 | 4 | .DS_Store 5 | -------------------------------------------------------------------------------- /BiRefNet_node.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | sys.path.insert(0, os.path.dirname(__file__)) 4 | 5 | from collections import defaultdict 6 | import folder_paths 7 | from models.baseline import BiRefNet 8 | from config import Config 9 | 10 | import cv2 11 | import numpy as np 12 | from PIL import Image 13 | 14 | import torch 15 | import torch.nn as nn 16 | from torchvision import transforms 17 | 18 | from loguru import logger 19 | from folder_paths import models_dir 20 | from utils import check_download_model 21 | 22 | config = Config() 23 | 24 | class BiRefNet_img_processor: 25 | def __init__(self, config): 26 | self.config = config 27 | self.data_size = (config.size, config.size) 28 | self.transform_image = transforms.Compose([ 29 | transforms.Resize(self.data_size), 30 | transforms.ToTensor(), 31 | transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), 32 | ]) 33 | 34 | def __call__(self, _image: np.array): 35 | _image_rs = cv2.resize(_image, (self.config.size, self.config.size), interpolation=cv2.INTER_LINEAR) 36 | _image_rs = Image.fromarray(np.uint8(_image_rs*255)).convert('RGB') 37 | image = self.transform_image(_image_rs) 38 | return image 39 | 40 | class BiRefNet_node: 41 | def __init__(self): 42 | self.ready = False 43 | 44 | def load(self, weight_path, device, verbose=False): 45 | try: 46 | map_location = 'cpu' if device == 'cpu' else None 47 | if device == 'mps' and torch.backends.mps.is_available(): 48 | map_location = torch.device('mps') 49 | 50 | self.model = BiRefNet() 51 | state_dict = torch.load(weight_path, map_location=map_location) 52 | unwanted_prefix = '_orig_mod.' 53 | for k, v in list(state_dict.items()): 54 | if k.startswith(unwanted_prefix): 55 | state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k) 56 | 57 | self.model.load_state_dict(state_dict) 58 | self.model.to(device) 59 | self.model.eval() 60 | 61 | self.processor = BiRefNet_img_processor(config) 62 | self.ready = True 63 | if verbose: 64 | logger.debug("Model loaded successfully on device: {}".format(device)) 65 | except Exception as e: 66 | logger.error(f"Failed to load the model: {e}") 67 | self.ready = False 68 | raise RuntimeError(f"Model loading failed: {e}") 69 | 70 | 71 | # Correctly move INPUT_TYPES to the class level 72 | @classmethod 73 | def INPUT_TYPES(cls): 74 | # Example structure, adjust according to your actual input requirements 75 | return { 76 | "required": { 77 | "image": ("IMAGE", {}), 78 | "device": (["auto", "cpu", "mps"] + [f"cuda:{i}" for i in range(torch.cuda.device_count())], {"default": "auto"}), 79 | }, 80 | "optional": { 81 | # Define optional inputs if any 82 | } 83 | } 84 | 85 | RETURN_TYPES = ("MASK", ) 86 | RETURN_NAMES = ("mask", ) 87 | FUNCTION = "matting" 88 | CATEGORY = "Fooocus" 89 | 90 | def matting(self, image, device): 91 | # process auto device 92 | if device == "auto": 93 | if torch.backends.mps.is_available(): 94 | device = "mps" 95 | elif torch.cuda.is_available(): 96 | device = "cuda" 97 | else: 98 | device = "cpu" 99 | 100 | if not self.ready: 101 | weight_path = os.path.join(models_dir, "BiRefNet", "BiRefNet-ep480.pth") 102 | check_download_model(weight_path) 103 | self.load(weight_path, device=device) 104 | 105 | image = image.squeeze().numpy() 106 | img = self.processor(image) 107 | inputs = img[None, ...].to(device) 108 | logger.debug(f"{inputs.shape}") 109 | 110 | with torch.no_grad(): 111 | self.model.to(device) # Move the model to the selected device 112 | scaled_preds = self.model(inputs)[-1].sigmoid() 113 | 114 | res = nn.functional.interpolate( 115 | scaled_preds[0].unsqueeze(0), 116 | size=image.shape[:2], 117 | mode='bilinear', 118 | align_corners=True 119 | ) 120 | return res 121 | 122 | 123 | NODE_CLASS_MAPPINGS = { 124 | "BiRefNet": BiRefNet_node, 125 | } 126 | 127 | # A dictionary that contains the friendly/humanly readable titles for the nodes 128 | NODE_DISPLAY_NAME_MAPPINGS = { 129 | "BiRefNet": "BiRefNet Segmentation", 130 | } 131 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ComfyUI-BiRefNet 2 | 3 | ## Introduction 4 | 5 | Bilateral Reference Network achieves SOTA result in multi Salient Object Segmentation dataset, this repo pack BiRefNet as ComfyUI nodes, and make this SOTA model easier use for everyone. 6 | 7 | ## Installation 8 | 9 | 1. Go to comfyUI custom_nodes folder, `ComfyUI/custom_nodes/` 10 | 2. `git clone https://github.com/viperyl/ComfyUI-BiRefNet.git ` 11 | 3. `pip install requirements.txt` 12 | 13 | ## Download Model Checkpoints 14 | 15 | Before using BiRefNet, download the model checkpoints with Git LFS: 16 | 17 | 1. Ensure `git lfs` is installed. If not, [install it](https://git-lfs.github.com/). 18 | 2. Download the checkpoints to the ComfyUI models directory by pulling the large model files using git lfs: 19 | ```bash 20 | cd ./models/ 21 | git clone https://huggingface.co/ViperYX/BiRefNet 22 | cd BiRefNet 23 | git lfs install 24 | git lfs pull 25 | ``` 26 | 27 | ## Usage 28 | 29 | The demo workflow placed in `workflow/example_workflow.json` 30 | 31 | ![plot](./assets/Screenshot-2024-03-21-at-19.26.21.png) 32 | 33 | ## Sample Result 34 | 35 | ![](./assets/00.jpg) 36 | 37 | ![](./assets/01.jpg) 38 | 39 | ![](./assets/02.jpg) 40 | 41 | # Acknowledgments 42 | 43 | Thanks to BiRefNet repo owner [ZhengPeng7/BiRefNet: Bilateral Reference for High-Resolution Dichotomous Image Segmentation (github.com)](https://github.com/zhengpeng7/birefnet) 44 | 45 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | import folder_paths 3 | from .BiRefNet_node import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS 4 | 5 | NODE_CLASS_MAPPINGS = {**NODE_CLASS_MAPPINGS} 6 | NODE_DISPLAY_NAME_MAPPINGS = {**NODE_DISPLAY_NAME_MAPPINGS} 7 | __all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS'] 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /assets/00.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viperyl/ComfyUI-BiRefNet/484c90b74c5229206e1f0573e594434eac4ca151/assets/00.jpg -------------------------------------------------------------------------------- /assets/01.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viperyl/ComfyUI-BiRefNet/484c90b74c5229206e1f0573e594434eac4ca151/assets/01.jpg -------------------------------------------------------------------------------- /assets/02.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viperyl/ComfyUI-BiRefNet/484c90b74c5229206e1f0573e594434eac4ca151/assets/02.jpg -------------------------------------------------------------------------------- /assets/Screenshot-2024-03-21-at-19.26.21.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viperyl/ComfyUI-BiRefNet/484c90b74c5229206e1f0573e594434eac4ca151/assets/Screenshot-2024-03-21-at-19.26.21.png -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | import os 2 | import math 3 | from folder_paths import models_dir 4 | 5 | 6 | class Config(): 7 | def __init__(self) -> None: 8 | self.ms_supervision = True 9 | self.out_ref = self.ms_supervision and True 10 | self.dec_ipt = True 11 | self.dec_ipt_split = True 12 | self.locate_head = False 13 | self.cxt_num = [0, 3][1] # multi-scale skip connections from encoder 14 | self.mul_scl_ipt = ['', 'add', 'cat'][2] 15 | self.refine = ['', 'itself', 'RefUNet', 'Refiner', 'RefinerPVTInChannels4'][0] 16 | self.progressive_ref = self.refine and True 17 | self.ender = self.progressive_ref and False 18 | self.scale = self.progressive_ref and 2 19 | self.dec_att = ['', 'ASPP', 'ASPPDeformable'][2] 20 | self.squeeze_block = ['', 'BasicDecBlk_x1', 'ResBlk_x4', 'ASPP_x3', 'ASPPDeformable_x3'][1] 21 | self.dec_blk = ['BasicDecBlk', 'ResBlk', 'HierarAttDecBlk'][0] 22 | self.auxiliary_classification = False 23 | self.refine_iteration = 1 24 | self.freeze_bb = False 25 | self.precisionHigh = True 26 | self.compile = True 27 | self.load_all = True 28 | self.verbose_eval = True 29 | 30 | self.size = 1024 31 | self.batch_size = 2 32 | self.IoU_finetune_last_epochs = [0, -40][1] # choose 0 to skip 33 | if self.dec_blk == 'HierarAttDecBlk': 34 | self.batch_size = 2 ** [0, 1, 2, 3, 4][2] 35 | self.model = [ 36 | 'BiRefNet', 37 | ][0] 38 | 39 | # Components 40 | self.lat_blk = ['BasicLatBlk'][0] 41 | self.dec_channels_inter = ['fixed', 'adap'][0] 42 | 43 | # Backbone 44 | self.bb = [ 45 | 'vgg16', 'vgg16bn', 'resnet50', # 0, 1, 2 46 | 'pvt_v2_b2', 'pvt_v2_b5', # 3-bs10, 4-bs5 47 | 'swin_v1_b', 'swin_v1_l' # 5-bs9, 6-bs6 48 | ][6] 49 | self.lateral_channels_in_collection = { 50 | 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64], 51 | 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64], 52 | 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192], 53 | }[self.bb] 54 | if self.mul_scl_ipt == 'cat': 55 | self.lateral_channels_in_collection = [channel * 2 for channel in self.lateral_channels_in_collection] 56 | self.cxt = self.lateral_channels_in_collection[1:][::-1][-self.cxt_num:] if self.cxt_num else [] 57 | self.sys_home_dir = models_dir 58 | self.weights_root_dir = os.path.join(self.sys_home_dir, "BiRefNet") 59 | self.weights = { 60 | 'pvt_v2_b2': os.path.join(self.weights_root_dir, 'pvt_v2_b2.pth'), 61 | 'pvt_v2_b5': os.path.join(self.weights_root_dir, ['pvt_v2_b5.pth', 'pvt_v2_b5_22k.pth'][0]), 62 | 'swin_v1_b': os.path.join(self.weights_root_dir, ['swin_base_patch4_window12_384_22kto1k.pth', 'swin_base_patch4_window12_384_22k.pth'][0]), 63 | 'swin_v1_l': os.path.join(self.weights_root_dir, ['swin_large_patch4_window12_384_22kto1k.pth', 'swin_large_patch4_window12_384_22k.pth'][0]), 64 | } 65 | 66 | # Training 67 | self.num_workers = 5 # will be decrease to min(it, batch_size) at the initialization of the data_loader 68 | self.optimizer = ['Adam', 'AdamW'][0] 69 | self.lr = 1e-5 * math.sqrt(self.batch_size / 5) # adapt the lr linearly 70 | self.lr_decay_epochs = [1e4] # Set to negative N to decay the lr in the last N-th epoch. 71 | self.lr_decay_rate = 0.5 72 | self.only_S_MAE = False 73 | self.SDPA_enabled = False # Bug. Slower and errors occur in multi-GPUs 74 | 75 | # Data 76 | self.data_root_dir = os.path.join(self.sys_home_dir, 'datasets/dis') 77 | self.dataset = ['DIS5K', 'COD', 'SOD'][0] 78 | self.preproc_methods = ['flip', 'enhance', 'rotate', 'pepper', 'crop'][:4] 79 | 80 | # Loss 81 | self.lambdas_pix_last = { 82 | # not 0 means opening this loss 83 | # original rate -- 1 : 30 : 1.5 : 0.2, bce x 30 84 | 'bce': 30 * 1, # high performance 85 | 'iou': 0.5 * 1, # 0 / 255 86 | 'iou_patch': 0.5 * 0, # 0 / 255, win_size = (64, 64) 87 | 'mse': 150 * 0, # can smooth the saliency map 88 | 'triplet': 3 * 0, 89 | 'reg': 100 * 0, 90 | 'ssim': 10 * 1, # help contours, 91 | 'cnt': 5 * 0, # help contours 92 | } 93 | self.lambdas_cls = { 94 | 'ce': 5.0 95 | } 96 | # Adv 97 | self.lambda_adv_g = 10. * 0 # turn to 0 to avoid adv training 98 | self.lambda_adv_d = 3. * (self.lambda_adv_g > 0) 99 | 100 | # others 101 | self.device = [0, 'cpu'][0] # .to(0) = .to('cuda:0') 102 | 103 | self.batch_size_valid = 1 104 | self.rand_seed = 7 105 | -------------------------------------------------------------------------------- /dataset.py: -------------------------------------------------------------------------------- 1 | import os 2 | import cv2 3 | from tqdm import tqdm 4 | from PIL import Image 5 | from torch.utils import data 6 | from torchvision import transforms 7 | 8 | from preproc import preproc 9 | from config import Config 10 | from glob import glob 11 | 12 | 13 | Image.MAX_IMAGE_PIXELS = None # remove DecompressionBombWarning 14 | config = Config() 15 | _class_labels_TR_sorted = 'Airplane, Ant, Antenna, Archery, Axe, BabyCarriage, Bag, BalanceBeam, Balcony, Balloon, Basket, BasketballHoop, Beatle, Bed, Bee, Bench, Bicycle, BicycleFrame, BicycleStand, Boat, Bonsai, BoomLift, Bridge, BunkBed, Butterfly, Button, Cable, CableLift, Cage, Camcorder, Cannon, Canoe, Car, CarParkDropArm, Carriage, Cart, Caterpillar, CeilingLamp, Centipede, Chair, Clip, Clock, Clothes, CoatHanger, Comb, ConcretePumpTruck, Crack, Crane, Cup, DentalChair, Desk, DeskChair, Diagram, DishRack, DoorHandle, Dragonfish, Dragonfly, Drum, Earphone, Easel, ElectricIron, Excavator, Eyeglasses, Fan, Fence, Fencing, FerrisWheel, FireExtinguisher, Fishing, Flag, FloorLamp, Forklift, GasStation, Gate, Gear, Goal, Golf, GymEquipment, Hammock, Handcart, Handcraft, Handrail, HangGlider, Harp, Harvester, Headset, Helicopter, Helmet, Hook, HorizontalBar, Hydrovalve, IroningTable, Jewelry, Key, KidsPlayground, Kitchenware, Kite, Knife, Ladder, LaundryRack, Lightning, Lobster, Locust, Machine, MachineGun, MagazineRack, Mantis, Medal, MemorialArchway, Microphone, Missile, MobileHolder, Monitor, Mosquito, Motorcycle, MovingTrolley, Mower, MusicPlayer, MusicStand, ObservationTower, Octopus, OilWell, OlympicLogo, OperatingTable, OutdoorFitnessEquipment, Parachute, Pavilion, Piano, Pipe, PlowHarrow, PoleVault, Punchbag, Rack, Racket, Rifle, Ring, Robot, RockClimbing, Rope, Sailboat, Satellite, Scaffold, Scale, Scissor, Scooter, Sculpture, Seadragon, Seahorse, Seal, SewingMachine, Ship, Shoe, ShoppingCart, ShoppingTrolley, Shower, Shrimp, Signboard, Skateboarding, Skeleton, Skiing, Spade, SpeedBoat, Spider, Spoon, Stair, Stand, Stationary, SteeringWheel, Stethoscope, Stool, Stove, StreetLamp, SweetStand, Swing, Sword, TV, Table, TableChair, TableLamp, TableTennis, Tank, Tapeline, Teapot, Telescope, Tent, TobaccoPipe, Toy, Tractor, TrafficLight, TrafficSign, Trampoline, TransmissionTower, Tree, Tricycle, TrimmerCover, Tripod, Trombone, Truck, Trumpet, Tuba, UAV, Umbrella, UnevenBars, UtilityPole, VacuumCleaner, Violin, Wakesurfing, Watch, WaterTower, WateringPot, Well, WellLid, Wheel, Wheelchair, WindTurbine, Windmill, WineGlass, WireWhisk, Yacht' 16 | class_labels_TR_sorted = _class_labels_TR_sorted.split(', ') 17 | 18 | 19 | class MyData(data.Dataset): 20 | def __init__(self, data_root, image_size, is_train=True): 21 | self.size_train = image_size 22 | self.size_test = image_size 23 | self.keep_size = not config.size 24 | self.data_size = (config.size, config.size) 25 | self.is_train = is_train 26 | self.load_all = config.load_all 27 | self.device = config.device 28 | self.dataset = data_root.replace('\\', '/').split('/')[-1] 29 | if self.is_train and config.auxiliary_classification: 30 | self.cls_name2id = {_name: _id for _id, _name in enumerate(class_labels_TR_sorted)} 31 | self.transform_image = transforms.Compose([ 32 | transforms.Resize(self.data_size), 33 | transforms.ToTensor(), 34 | transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), 35 | ][self.load_all or self.keep_size:]) 36 | self.transform_label = transforms.Compose([ 37 | transforms.Resize(self.data_size), 38 | transforms.ToTensor(), 39 | ][self.load_all or self.keep_size:]) 40 | ## 'im' and 'gt' need modifying 41 | image_root = os.path.join(data_root, 'im') 42 | self.image_paths = [os.path.join(image_root, p) for p in os.listdir(image_root)] 43 | self.label_paths = [p.replace('/im/', '/gt/').replace('.jpg', '.png') for p in self.image_paths] 44 | if self.load_all: 45 | self.images_loaded, self.labels_loaded = [], [] 46 | self.class_labels_loaded = [] 47 | # for image_path, label_path in zip(self.image_paths, self.label_paths): 48 | for image_path, label_path in tqdm(zip(self.image_paths, self.label_paths), total=len(self.image_paths)): 49 | _image = cv2.imread(image_path) 50 | _label = cv2.imread(label_path, cv2.IMREAD_GRAYSCALE) 51 | if not self.keep_size: 52 | _image_rs = cv2.resize(_image, (config.size, config.size), interpolation=cv2.INTER_LINEAR) 53 | _label_rs = cv2.resize(_label, (config.size, config.size), interpolation=cv2.INTER_LINEAR) 54 | self.images_loaded.append( 55 | Image.fromarray(cv2.cvtColor(_image_rs, cv2.COLOR_BGR2RGB)).convert('RGB') 56 | ) 57 | self.labels_loaded.append( 58 | Image.fromarray(_label_rs).convert('L') 59 | ) 60 | self.class_labels_loaded.append( 61 | self.cls_name2id[label_path.split('/')[-1].split('#')[3]] if self.is_train and config.auxiliary_classification else -1 62 | ) 63 | 64 | 65 | def __getitem__(self, index): 66 | 67 | if self.load_all: 68 | image = self.images_loaded[index] 69 | class_label = self.class_labels_loaded[index] if self.is_train and config.auxiliary_classification else -1 70 | else: 71 | image = Image.open(self.image_paths[index]).convert('RGB') 72 | 73 | # loading image and label 74 | if self.is_train: 75 | image, label = preproc(image, image, preproc_methods=config.preproc_methods) 76 | # else: 77 | # if _label.shape[0] > 2048 or _label.shape[1] > 2048: 78 | # _image = cv2.resize(_image, (2048, 2048), interpolation=cv2.INTER_LINEAR) 79 | # _label = cv2.resize(_label, (2048, 2048), interpolation=cv2.INTER_LINEAR) 80 | 81 | image, label = self.transform_image(image), self.transform_label(label) 82 | 83 | if self.is_train: 84 | return image, label, class_label 85 | else: 86 | return image, label, self.label_paths[index] 87 | 88 | def __len__(self): 89 | return len(self.image_paths) 90 | 91 | 92 | class YouData(data.Dataset): 93 | def __init__(self, data_root, image_size, is_train=True): 94 | self.size_train = image_size 95 | self.size_test = image_size 96 | self.keep_size = not config.size 97 | self.data_size = (config.size, config.size) 98 | self.is_train = is_train 99 | self.load_all = config.load_all 100 | self.device = config.device 101 | self.dataset = data_root.replace('\\', '/').split('/')[-1] 102 | if self.is_train and config.auxiliary_classification: 103 | self.cls_name2id = {_name: _id for _id, _name in enumerate(class_labels_TR_sorted)} 104 | self.transform_image = transforms.Compose([ 105 | transforms.Resize(self.data_size), 106 | transforms.ToTensor(), 107 | transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), 108 | ][self.load_all or self.keep_size:]) 109 | ## 'im' and 'gt' need modifying 110 | self.image_paths = glob(data_root + "/*") 111 | self.img_sizes = [] 112 | if self.load_all: 113 | self.images_loaded, self.labels_loaded = [], [] 114 | for image_path in tqdm(self.image_paths, total=len(self.image_paths)): 115 | _image = cv2.imread(image_path) 116 | if not self.keep_size: 117 | _image_rs = cv2.resize(_image, (config.size, config.size), interpolation=cv2.INTER_LINEAR) 118 | self.images_loaded.append( 119 | Image.fromarray(cv2.cvtColor(_image_rs, cv2.COLOR_BGR2RGB)).convert('RGB') 120 | ) 121 | self.img_sizes.append(_image.shape[:2]) 122 | 123 | 124 | def __getitem__(self, index): 125 | 126 | if self.load_all: 127 | image = self.images_loaded[index] 128 | else: 129 | image = Image.open(self.image_paths[index]).convert('RGB') 130 | 131 | # loading image and label 132 | if self.is_train: 133 | image, _ = preproc(image, image, preproc_methods=config.preproc_methods) 134 | 135 | image = self.transform_image(image) 136 | size = self.img_sizes[index] 137 | return image, size 138 | 139 | def __len__(self): 140 | return len(self.image_paths) 141 | -------------------------------------------------------------------------------- /debug.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 6, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "from PIL import Image\n", 10 | "import numpy as np\n", 11 | "import cv2" 12 | ] 13 | }, 14 | { 15 | "cell_type": "code", 16 | "execution_count": 10, 17 | "metadata": {}, 18 | "outputs": [], 19 | "source": [ 20 | "img = Image.open(\"/data/ssd1/tmp/meihup_facedata/571a7061-f2c6-4e6b-ad0e-a7ca72f8f2ea.png\")\n", 21 | "img = np.array(img)\n", 22 | "img = img /255" 23 | ] 24 | }, 25 | { 26 | "cell_type": "code", 27 | "execution_count": 11, 28 | "metadata": {}, 29 | "outputs": [ 30 | { 31 | "data": { 32 | "text/plain": [ 33 | "(1080, 1080, 3)" 34 | ] 35 | }, 36 | "execution_count": 11, 37 | "metadata": {}, 38 | "output_type": "execute_result" 39 | } 40 | ], 41 | "source": [ 42 | "img.shape" 43 | ] 44 | }, 45 | { 46 | "cell_type": "code", 47 | "execution_count": 12, 48 | "metadata": {}, 49 | "outputs": [], 50 | "source": [ 51 | "a = cv2.resize(img, (1024, 1024))" 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": 13, 57 | "metadata": {}, 58 | "outputs": [ 59 | { 60 | "data": { 61 | "text/plain": [ 62 | "(1024, 1024, 3)" 63 | ] 64 | }, 65 | "execution_count": 13, 66 | "metadata": {}, 67 | "output_type": "execute_result" 68 | } 69 | ], 70 | "source": [ 71 | "a.shape" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": 14, 77 | "metadata": {}, 78 | "outputs": [ 79 | { 80 | "data": { 81 | "text/plain": [ 82 | "(1080, 1080, 3)" 83 | ] 84 | }, 85 | "execution_count": 14, 86 | "metadata": {}, 87 | "output_type": "execute_result" 88 | } 89 | ], 90 | "source": [ 91 | "img.shape" 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "execution_count": null, 97 | "metadata": {}, 98 | "outputs": [], 99 | "source": [] 100 | } 101 | ], 102 | "metadata": { 103 | "kernelspec": { 104 | "display_name": "comfyUI", 105 | "language": "python", 106 | "name": "python3" 107 | }, 108 | "language_info": { 109 | "codemirror_mode": { 110 | "name": "ipython", 111 | "version": 3 112 | }, 113 | "file_extension": ".py", 114 | "mimetype": "text/x-python", 115 | "name": "python", 116 | "nbconvert_exporter": "python", 117 | "pygments_lexer": "ipython3", 118 | "version": "3.10.0" 119 | } 120 | }, 121 | "nbformat": 4, 122 | "nbformat_minor": 2 123 | } 124 | -------------------------------------------------------------------------------- /install.py: -------------------------------------------------------------------------------- 1 | # import sys 2 | # import locale 3 | # import subprocess 4 | # import threading 5 | 6 | # # copied from https://github.com/ltdrdata/ComfyUI-Impact-Pack/blob/Main/install.py#L37 7 | # def handle_stream(stream, is_stdout): 8 | # stream.reconfigure(encoding=locale.getpreferredencoding(), errors='replace') 9 | 10 | # for msg in stream: 11 | # if is_stdout: 12 | # print(msg, end="", file=sys.stdout) 13 | # else: 14 | # print(msg, end="", file=sys.stderr) 15 | 16 | # # copied from https://github.com/ltdrdata/ComfyUI-Impact-Pack/blob/Main/install.py#L37 17 | # def process_wrap(cmd_str, cwd=None, handler=None): 18 | # print(f"[Impact Pack] EXECUTE: {cmd_str} in '{cwd}'") 19 | # process = subprocess.Popen(cmd_str, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1) 20 | 21 | # if handler is None: 22 | # handler = handle_stream 23 | 24 | # stdout_thread = threading.Thread(target=handler, args=(process.stdout, True)) 25 | # stderr_thread = threading.Thread(target=handler, args=(process.stderr, False)) 26 | 27 | # stdout_thread.start() 28 | # stderr_thread.start() 29 | 30 | # stdout_thread.join() 31 | # stderr_thread.join() 32 | 33 | # return process.wait() 34 | 35 | # pip_install = [sys.executable, "-s", "-m", "pip", "install"] 36 | 37 | # process_wrap(pip_install + ['-r', 'requirements.txt'], cwd=__file__) -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viperyl/ComfyUI-BiRefNet/484c90b74c5229206e1f0573e594434eac4ca151/models/__init__.py -------------------------------------------------------------------------------- /models/backbones/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viperyl/ComfyUI-BiRefNet/484c90b74c5229206e1f0573e594434eac4ca151/models/backbones/__init__.py -------------------------------------------------------------------------------- /models/backbones/build_backbone.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | from collections import OrderedDict 4 | from torchvision.models import vgg16, vgg16_bn, VGG16_Weights, VGG16_BN_Weights, resnet50, ResNet50_Weights 5 | from models.backbones.pvt_v2 import pvt_v2_b2, pvt_v2_b5 6 | from models.backbones.swin_v1 import swin_v1_t, swin_v1_s, swin_v1_b, swin_v1_l 7 | from config import Config 8 | from utils import check_download_model 9 | 10 | 11 | config = Config() 12 | 13 | def build_backbone(bb_name, pretrained=True, params_settings=''): 14 | if bb_name == 'vgg16': 15 | bb_net = list(vgg16(pretrained=VGG16_Weights.DEFAULT if pretrained else None).children())[0] 16 | bb = nn.Sequential(OrderedDict({'conv1': bb_net[:4], 'conv2': bb_net[4:9], 'conv3': bb_net[9:16], 'conv4': bb_net[16:23]})) 17 | elif bb_name == 'vgg16bn': 18 | bb_net = list(vgg16_bn(pretrained=VGG16_BN_Weights.DEFAULT if pretrained else None).children())[0] 19 | bb = nn.Sequential(OrderedDict({'conv1': bb_net[:6], 'conv2': bb_net[6:13], 'conv3': bb_net[13:23], 'conv4': bb_net[23:33]})) 20 | elif bb_name == 'resnet50': 21 | bb_net = list(resnet50(pretrained=ResNet50_Weights.DEFAULT if pretrained else None).children()) 22 | bb = nn.Sequential(OrderedDict({'conv1': nn.Sequential(*bb_net[0:3]), 'conv2': bb_net[4], 'conv3': bb_net[5], 'conv4': bb_net[6]})) 23 | else: 24 | bb = eval('{}({})'.format(bb_name, params_settings)) 25 | if pretrained: 26 | bb = load_weights(bb, bb_name) 27 | return bb 28 | 29 | def load_weights(model, model_name): 30 | check_download_model(config.weights[model_name]) # download the weights if not exists 31 | save_model = torch.load(config.weights[model_name], map_location=torch.device('cpu')) 32 | model_dict = model.state_dict() 33 | state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model.items() if k in model_dict.keys()} 34 | # to ignore the weights with mismatched size when I modify the backbone itself. 35 | if not state_dict: 36 | save_model_keys = list(save_model.keys()) 37 | sub_item = save_model_keys[0] if len(save_model_keys) == 1 else None 38 | state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model[sub_item].items() if k in model_dict.keys()} 39 | if not state_dict or not sub_item: 40 | print('Weights are not successfully loaded. Check the state dict of weights file.') 41 | return None 42 | else: 43 | print('Found correct weights in the "{}" item of loaded state_dict.'.format(sub_item)) 44 | model_dict.update(state_dict) 45 | model.load_state_dict(model_dict) 46 | return model 47 | -------------------------------------------------------------------------------- /models/backbones/pvt_v2.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | from functools import partial 4 | 5 | from timm.models.layers import DropPath, to_2tuple, trunc_normal_ 6 | from timm.models.registry import register_model 7 | 8 | import math 9 | 10 | from config import Config 11 | 12 | config = Config() 13 | 14 | class Mlp(nn.Module): 15 | def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): 16 | super().__init__() 17 | out_features = out_features or in_features 18 | hidden_features = hidden_features or in_features 19 | self.fc1 = nn.Linear(in_features, hidden_features) 20 | self.dwconv = DWConv(hidden_features) 21 | self.act = act_layer() 22 | self.fc2 = nn.Linear(hidden_features, out_features) 23 | self.drop = nn.Dropout(drop) 24 | 25 | self.apply(self._init_weights) 26 | 27 | def _init_weights(self, m): 28 | if isinstance(m, nn.Linear): 29 | trunc_normal_(m.weight, std=.02) 30 | if isinstance(m, nn.Linear) and m.bias is not None: 31 | nn.init.constant_(m.bias, 0) 32 | elif isinstance(m, nn.LayerNorm): 33 | nn.init.constant_(m.bias, 0) 34 | nn.init.constant_(m.weight, 1.0) 35 | elif isinstance(m, nn.Conv2d): 36 | fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels 37 | fan_out //= m.groups 38 | m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) 39 | if m.bias is not None: 40 | m.bias.data.zero_() 41 | 42 | def forward(self, x, H, W): 43 | x = self.fc1(x) 44 | x = self.dwconv(x, H, W) 45 | x = self.act(x) 46 | x = self.drop(x) 47 | x = self.fc2(x) 48 | x = self.drop(x) 49 | return x 50 | 51 | 52 | class Attention(nn.Module): 53 | def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1): 54 | super().__init__() 55 | assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}." 56 | 57 | self.dim = dim 58 | self.num_heads = num_heads 59 | head_dim = dim // num_heads 60 | self.scale = qk_scale or head_dim ** -0.5 61 | 62 | self.q = nn.Linear(dim, dim, bias=qkv_bias) 63 | self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias) 64 | self.attn_drop_prob = attn_drop 65 | self.attn_drop = nn.Dropout(attn_drop) 66 | self.proj = nn.Linear(dim, dim) 67 | self.proj_drop = nn.Dropout(proj_drop) 68 | 69 | self.sr_ratio = sr_ratio 70 | if sr_ratio > 1: 71 | self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio) 72 | self.norm = nn.LayerNorm(dim) 73 | 74 | self.apply(self._init_weights) 75 | 76 | def _init_weights(self, m): 77 | if isinstance(m, nn.Linear): 78 | trunc_normal_(m.weight, std=.02) 79 | if isinstance(m, nn.Linear) and m.bias is not None: 80 | nn.init.constant_(m.bias, 0) 81 | elif isinstance(m, nn.LayerNorm): 82 | nn.init.constant_(m.bias, 0) 83 | nn.init.constant_(m.weight, 1.0) 84 | elif isinstance(m, nn.Conv2d): 85 | fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels 86 | fan_out //= m.groups 87 | m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) 88 | if m.bias is not None: 89 | m.bias.data.zero_() 90 | 91 | def forward(self, x, H, W): 92 | B, N, C = x.shape 93 | q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) 94 | 95 | if self.sr_ratio > 1: 96 | x_ = x.permute(0, 2, 1).reshape(B, C, H, W) 97 | x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1) 98 | x_ = self.norm(x_) 99 | kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) 100 | else: 101 | kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) 102 | k, v = kv[0], kv[1] 103 | 104 | if config.SDPA_enabled: 105 | x = torch.nn.functional.scaled_dot_product_attention( 106 | q, k, v, 107 | attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False 108 | ).transpose(1, 2).reshape(B, N, C) 109 | else: 110 | attn = (q @ k.transpose(-2, -1)) * self.scale 111 | attn = attn.softmax(dim=-1) 112 | attn = self.attn_drop(attn) 113 | 114 | x = (attn @ v).transpose(1, 2).reshape(B, N, C) 115 | x = self.proj(x) 116 | x = self.proj_drop(x) 117 | 118 | return x 119 | 120 | 121 | class Block(nn.Module): 122 | 123 | def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., 124 | drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1): 125 | super().__init__() 126 | self.norm1 = norm_layer(dim) 127 | self.attn = Attention( 128 | dim, 129 | num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, 130 | attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio) 131 | # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here 132 | self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() 133 | self.norm2 = norm_layer(dim) 134 | mlp_hidden_dim = int(dim * mlp_ratio) 135 | self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) 136 | 137 | self.apply(self._init_weights) 138 | 139 | def _init_weights(self, m): 140 | if isinstance(m, nn.Linear): 141 | trunc_normal_(m.weight, std=.02) 142 | if isinstance(m, nn.Linear) and m.bias is not None: 143 | nn.init.constant_(m.bias, 0) 144 | elif isinstance(m, nn.LayerNorm): 145 | nn.init.constant_(m.bias, 0) 146 | nn.init.constant_(m.weight, 1.0) 147 | elif isinstance(m, nn.Conv2d): 148 | fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels 149 | fan_out //= m.groups 150 | m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) 151 | if m.bias is not None: 152 | m.bias.data.zero_() 153 | 154 | def forward(self, x, H, W): 155 | x = x + self.drop_path(self.attn(self.norm1(x), H, W)) 156 | x = x + self.drop_path(self.mlp(self.norm2(x), H, W)) 157 | 158 | return x 159 | 160 | 161 | class OverlapPatchEmbed(nn.Module): 162 | """ Image to Patch Embedding 163 | """ 164 | 165 | def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768): 166 | super().__init__() 167 | img_size = to_2tuple(img_size) 168 | patch_size = to_2tuple(patch_size) 169 | 170 | self.img_size = img_size 171 | self.patch_size = patch_size 172 | self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1] 173 | self.num_patches = self.H * self.W 174 | self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride, 175 | padding=(patch_size[0] // 2, patch_size[1] // 2)) 176 | self.norm = nn.LayerNorm(embed_dim) 177 | 178 | self.apply(self._init_weights) 179 | 180 | def _init_weights(self, m): 181 | if isinstance(m, nn.Linear): 182 | trunc_normal_(m.weight, std=.02) 183 | if isinstance(m, nn.Linear) and m.bias is not None: 184 | nn.init.constant_(m.bias, 0) 185 | elif isinstance(m, nn.LayerNorm): 186 | nn.init.constant_(m.bias, 0) 187 | nn.init.constant_(m.weight, 1.0) 188 | elif isinstance(m, nn.Conv2d): 189 | fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels 190 | fan_out //= m.groups 191 | m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) 192 | if m.bias is not None: 193 | m.bias.data.zero_() 194 | 195 | def forward(self, x): 196 | x = self.proj(x) 197 | _, _, H, W = x.shape 198 | x = x.flatten(2).transpose(1, 2) 199 | x = self.norm(x) 200 | 201 | return x, H, W 202 | 203 | 204 | class PyramidVisionTransformerImpr(nn.Module): 205 | def __init__(self, img_size=224, patch_size=16, in_channels=3, num_classes=1000, embed_dims=[64, 128, 256, 512], 206 | num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0., 207 | attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm, 208 | depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]): 209 | super().__init__() 210 | self.num_classes = num_classes 211 | self.depths = depths 212 | 213 | # patch_embed 214 | self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_channels=in_channels, 215 | embed_dim=embed_dims[0]) 216 | self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_channels=embed_dims[0], 217 | embed_dim=embed_dims[1]) 218 | self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_channels=embed_dims[1], 219 | embed_dim=embed_dims[2]) 220 | self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_channels=embed_dims[2], 221 | embed_dim=embed_dims[3]) 222 | 223 | # transformer encoder 224 | dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule 225 | cur = 0 226 | self.block1 = nn.ModuleList([Block( 227 | dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale, 228 | drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, 229 | sr_ratio=sr_ratios[0]) 230 | for i in range(depths[0])]) 231 | self.norm1 = norm_layer(embed_dims[0]) 232 | 233 | cur += depths[0] 234 | self.block2 = nn.ModuleList([Block( 235 | dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale, 236 | drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, 237 | sr_ratio=sr_ratios[1]) 238 | for i in range(depths[1])]) 239 | self.norm2 = norm_layer(embed_dims[1]) 240 | 241 | cur += depths[1] 242 | self.block3 = nn.ModuleList([Block( 243 | dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale, 244 | drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, 245 | sr_ratio=sr_ratios[2]) 246 | for i in range(depths[2])]) 247 | self.norm3 = norm_layer(embed_dims[2]) 248 | 249 | cur += depths[2] 250 | self.block4 = nn.ModuleList([Block( 251 | dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale, 252 | drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, 253 | sr_ratio=sr_ratios[3]) 254 | for i in range(depths[3])]) 255 | self.norm4 = norm_layer(embed_dims[3]) 256 | 257 | # classification head 258 | # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity() 259 | 260 | self.apply(self._init_weights) 261 | 262 | def _init_weights(self, m): 263 | if isinstance(m, nn.Linear): 264 | trunc_normal_(m.weight, std=.02) 265 | if isinstance(m, nn.Linear) and m.bias is not None: 266 | nn.init.constant_(m.bias, 0) 267 | elif isinstance(m, nn.LayerNorm): 268 | nn.init.constant_(m.bias, 0) 269 | nn.init.constant_(m.weight, 1.0) 270 | elif isinstance(m, nn.Conv2d): 271 | fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels 272 | fan_out //= m.groups 273 | m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) 274 | if m.bias is not None: 275 | m.bias.data.zero_() 276 | 277 | def init_weights(self, pretrained=None): 278 | if isinstance(pretrained, str): 279 | logger = 1 280 | #load_checkpoint(self, pretrained, map_location='cpu', strict=False, logger=logger) 281 | 282 | def reset_drop_path(self, drop_path_rate): 283 | dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))] 284 | cur = 0 285 | for i in range(self.depths[0]): 286 | self.block1[i].drop_path.drop_prob = dpr[cur + i] 287 | 288 | cur += self.depths[0] 289 | for i in range(self.depths[1]): 290 | self.block2[i].drop_path.drop_prob = dpr[cur + i] 291 | 292 | cur += self.depths[1] 293 | for i in range(self.depths[2]): 294 | self.block3[i].drop_path.drop_prob = dpr[cur + i] 295 | 296 | cur += self.depths[2] 297 | for i in range(self.depths[3]): 298 | self.block4[i].drop_path.drop_prob = dpr[cur + i] 299 | 300 | def freeze_patch_emb(self): 301 | self.patch_embed1.requires_grad = False 302 | 303 | @torch.jit.ignore 304 | def no_weight_decay(self): 305 | return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'} # has pos_embed may be better 306 | 307 | def get_classifier(self): 308 | return self.head 309 | 310 | def reset_classifier(self, num_classes, global_pool=''): 311 | self.num_classes = num_classes 312 | self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() 313 | 314 | def forward_features(self, x): 315 | B = x.shape[0] 316 | outs = [] 317 | 318 | # stage 1 319 | x, H, W = self.patch_embed1(x) 320 | for i, blk in enumerate(self.block1): 321 | x = blk(x, H, W) 322 | x = self.norm1(x) 323 | x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() 324 | outs.append(x) 325 | 326 | # stage 2 327 | x, H, W = self.patch_embed2(x) 328 | for i, blk in enumerate(self.block2): 329 | x = blk(x, H, W) 330 | x = self.norm2(x) 331 | x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() 332 | outs.append(x) 333 | 334 | # stage 3 335 | x, H, W = self.patch_embed3(x) 336 | for i, blk in enumerate(self.block3): 337 | x = blk(x, H, W) 338 | x = self.norm3(x) 339 | x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() 340 | outs.append(x) 341 | 342 | # stage 4 343 | x, H, W = self.patch_embed4(x) 344 | for i, blk in enumerate(self.block4): 345 | x = blk(x, H, W) 346 | x = self.norm4(x) 347 | x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() 348 | outs.append(x) 349 | 350 | return outs 351 | 352 | # return x.mean(dim=1) 353 | 354 | def forward(self, x): 355 | x = self.forward_features(x) 356 | # x = self.head(x) 357 | 358 | return x 359 | 360 | 361 | class DWConv(nn.Module): 362 | def __init__(self, dim=768): 363 | super(DWConv, self).__init__() 364 | self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim) 365 | 366 | def forward(self, x, H, W): 367 | B, N, C = x.shape 368 | x = x.transpose(1, 2).view(B, C, H, W).contiguous() 369 | x = self.dwconv(x) 370 | x = x.flatten(2).transpose(1, 2) 371 | 372 | return x 373 | 374 | 375 | def _conv_filter(state_dict, patch_size=16): 376 | """ convert patch embedding weight from manual patchify + linear proj to conv""" 377 | out_dict = {} 378 | for k, v in state_dict.items(): 379 | if 'patch_embed.proj.weight' in k: 380 | v = v.reshape((v.shape[0], 3, patch_size, patch_size)) 381 | out_dict[k] = v 382 | 383 | return out_dict 384 | 385 | 386 | ## @register_model 387 | class pvt_v2_b0(PyramidVisionTransformerImpr): 388 | def __init__(self, **kwargs): 389 | super(pvt_v2_b0, self).__init__( 390 | patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], 391 | qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], 392 | drop_rate=0.0, drop_path_rate=0.1) 393 | 394 | 395 | 396 | ## @register_model 397 | class pvt_v2_b1(PyramidVisionTransformerImpr): 398 | def __init__(self, **kwargs): 399 | super(pvt_v2_b1, self).__init__( 400 | patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], 401 | qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], 402 | drop_rate=0.0, drop_path_rate=0.1) 403 | 404 | ## @register_model 405 | class pvt_v2_b2(PyramidVisionTransformerImpr): 406 | def __init__(self, in_channels=3, **kwargs): 407 | super(pvt_v2_b2, self).__init__( 408 | patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], 409 | qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1], 410 | drop_rate=0.0, drop_path_rate=0.1, in_channels=in_channels) 411 | 412 | ## @register_model 413 | class pvt_v2_b3(PyramidVisionTransformerImpr): 414 | def __init__(self, **kwargs): 415 | super(pvt_v2_b3, self).__init__( 416 | patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], 417 | qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1], 418 | drop_rate=0.0, drop_path_rate=0.1) 419 | 420 | ## @register_model 421 | class pvt_v2_b4(PyramidVisionTransformerImpr): 422 | def __init__(self, **kwargs): 423 | super(pvt_v2_b4, self).__init__( 424 | patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], 425 | qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1], 426 | drop_rate=0.0, drop_path_rate=0.1) 427 | 428 | 429 | ## @register_model 430 | class pvt_v2_b5(PyramidVisionTransformerImpr): 431 | def __init__(self, **kwargs): 432 | super(pvt_v2_b5, self).__init__( 433 | patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], 434 | qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1], 435 | drop_rate=0.0, drop_path_rate=0.1) 436 | -------------------------------------------------------------------------------- /models/backbones/swin_v1.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------- 2 | # Swin Transformer 3 | # Copyright (c) 2021 Microsoft 4 | # Licensed under The MIT License [see LICENSE for details] 5 | # Written by Ze Liu, Yutong Lin, Yixuan Wei 6 | # -------------------------------------------------------- 7 | 8 | import torch 9 | import torch.nn as nn 10 | import torch.nn.functional as F 11 | import torch.utils.checkpoint as checkpoint 12 | import numpy as np 13 | from timm.models.layers import DropPath, to_2tuple, trunc_normal_ 14 | 15 | from config import Config 16 | 17 | 18 | config = Config() 19 | 20 | class Mlp(nn.Module): 21 | """ Multilayer perceptron.""" 22 | 23 | def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): 24 | super().__init__() 25 | out_features = out_features or in_features 26 | hidden_features = hidden_features or in_features 27 | self.fc1 = nn.Linear(in_features, hidden_features) 28 | self.act = act_layer() 29 | self.fc2 = nn.Linear(hidden_features, out_features) 30 | self.drop = nn.Dropout(drop) 31 | 32 | def forward(self, x): 33 | x = self.fc1(x) 34 | x = self.act(x) 35 | x = self.drop(x) 36 | x = self.fc2(x) 37 | x = self.drop(x) 38 | return x 39 | 40 | 41 | def window_partition(x, window_size): 42 | """ 43 | Args: 44 | x: (B, H, W, C) 45 | window_size (int): window size 46 | 47 | Returns: 48 | windows: (num_windows*B, window_size, window_size, C) 49 | """ 50 | B, H, W, C = x.shape 51 | x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) 52 | windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) 53 | return windows 54 | 55 | 56 | def window_reverse(windows, window_size, H, W): 57 | """ 58 | Args: 59 | windows: (num_windows*B, window_size, window_size, C) 60 | window_size (int): Window size 61 | H (int): Height of image 62 | W (int): Width of image 63 | 64 | Returns: 65 | x: (B, H, W, C) 66 | """ 67 | B = int(windows.shape[0] / (H * W / window_size / window_size)) 68 | x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) 69 | x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) 70 | return x 71 | 72 | 73 | class WindowAttention(nn.Module): 74 | """ Window based multi-head self attention (W-MSA) module with relative position bias. 75 | It supports both of shifted and non-shifted window. 76 | 77 | Args: 78 | dim (int): Number of input channels. 79 | window_size (tuple[int]): The height and width of the window. 80 | num_heads (int): Number of attention heads. 81 | qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True 82 | qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set 83 | attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 84 | proj_drop (float, optional): Dropout ratio of output. Default: 0.0 85 | """ 86 | 87 | def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.): 88 | 89 | super().__init__() 90 | self.dim = dim 91 | self.window_size = window_size # Wh, Ww 92 | self.num_heads = num_heads 93 | head_dim = dim // num_heads 94 | self.scale = qk_scale or head_dim ** -0.5 95 | 96 | # define a parameter table of relative position bias 97 | self.relative_position_bias_table = nn.Parameter( 98 | torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH 99 | 100 | # get pair-wise relative position index for each token inside the window 101 | coords_h = torch.arange(self.window_size[0]) 102 | coords_w = torch.arange(self.window_size[1]) 103 | coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing='ij')) # 2, Wh, Ww 104 | coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww 105 | relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww 106 | relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 107 | relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 108 | relative_coords[:, :, 1] += self.window_size[1] - 1 109 | relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 110 | relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww 111 | self.register_buffer("relative_position_index", relative_position_index) 112 | 113 | self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) 114 | self.attn_drop_prob = attn_drop 115 | self.attn_drop = nn.Dropout(attn_drop) 116 | self.proj = nn.Linear(dim, dim) 117 | self.proj_drop = nn.Dropout(proj_drop) 118 | 119 | trunc_normal_(self.relative_position_bias_table, std=.02) 120 | self.softmax = nn.Softmax(dim=-1) 121 | 122 | def forward(self, x, mask=None): 123 | """ Forward function. 124 | 125 | Args: 126 | x: input features with shape of (num_windows*B, N, C) 127 | mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None 128 | """ 129 | B_, N, C = x.shape 130 | qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) 131 | q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) 132 | 133 | q = q * self.scale 134 | 135 | if config.SDPA_enabled: 136 | x = torch.nn.functional.scaled_dot_product_attention( 137 | q, k, v, 138 | attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False 139 | ).transpose(1, 2).reshape(B_, N, C) 140 | else: 141 | attn = (q @ k.transpose(-2, -1)) 142 | 143 | relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view( 144 | self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH 145 | relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww 146 | attn = attn + relative_position_bias.unsqueeze(0) 147 | 148 | if mask is not None: 149 | nW = mask.shape[0] 150 | attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0) 151 | attn = attn.view(-1, self.num_heads, N, N) 152 | attn = self.softmax(attn) 153 | else: 154 | attn = self.softmax(attn) 155 | 156 | attn = self.attn_drop(attn) 157 | 158 | x = (attn @ v).transpose(1, 2).reshape(B_, N, C) 159 | x = self.proj(x) 160 | x = self.proj_drop(x) 161 | return x 162 | 163 | 164 | class SwinTransformerBlock(nn.Module): 165 | """ Swin Transformer Block. 166 | 167 | Args: 168 | dim (int): Number of input channels. 169 | num_heads (int): Number of attention heads. 170 | window_size (int): Window size. 171 | shift_size (int): Shift size for SW-MSA. 172 | mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. 173 | qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True 174 | qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. 175 | drop (float, optional): Dropout rate. Default: 0.0 176 | attn_drop (float, optional): Attention dropout rate. Default: 0.0 177 | drop_path (float, optional): Stochastic depth rate. Default: 0.0 178 | act_layer (nn.Module, optional): Activation layer. Default: nn.GELU 179 | norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm 180 | """ 181 | 182 | def __init__(self, dim, num_heads, window_size=7, shift_size=0, 183 | mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0., 184 | act_layer=nn.GELU, norm_layer=nn.LayerNorm): 185 | super().__init__() 186 | self.dim = dim 187 | self.num_heads = num_heads 188 | self.window_size = window_size 189 | self.shift_size = shift_size 190 | self.mlp_ratio = mlp_ratio 191 | assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size" 192 | 193 | self.norm1 = norm_layer(dim) 194 | self.attn = WindowAttention( 195 | dim, window_size=to_2tuple(self.window_size), num_heads=num_heads, 196 | qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) 197 | 198 | self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() 199 | self.norm2 = norm_layer(dim) 200 | mlp_hidden_dim = int(dim * mlp_ratio) 201 | self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) 202 | 203 | self.H = None 204 | self.W = None 205 | 206 | def forward(self, x, mask_matrix): 207 | """ Forward function. 208 | 209 | Args: 210 | x: Input feature, tensor size (B, H*W, C). 211 | H, W: Spatial resolution of the input feature. 212 | mask_matrix: Attention mask for cyclic shift. 213 | """ 214 | B, L, C = x.shape 215 | H, W = self.H, self.W 216 | assert L == H * W, "input feature has wrong size" 217 | 218 | shortcut = x 219 | x = self.norm1(x) 220 | x = x.view(B, H, W, C) 221 | 222 | # pad feature maps to multiples of window size 223 | pad_l = pad_t = 0 224 | pad_r = (self.window_size - W % self.window_size) % self.window_size 225 | pad_b = (self.window_size - H % self.window_size) % self.window_size 226 | x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b)) 227 | _, Hp, Wp, _ = x.shape 228 | 229 | # cyclic shift 230 | if self.shift_size > 0: 231 | shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) 232 | attn_mask = mask_matrix 233 | else: 234 | shifted_x = x 235 | attn_mask = None 236 | 237 | # partition windows 238 | x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C 239 | x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C 240 | 241 | # W-MSA/SW-MSA 242 | attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C 243 | 244 | # merge windows 245 | attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) 246 | shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C 247 | 248 | # reverse cyclic shift 249 | if self.shift_size > 0: 250 | x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) 251 | else: 252 | x = shifted_x 253 | 254 | if pad_r > 0 or pad_b > 0: 255 | x = x[:, :H, :W, :].contiguous() 256 | 257 | x = x.view(B, H * W, C) 258 | 259 | # FFN 260 | x = shortcut + self.drop_path(x) 261 | x = x + self.drop_path(self.mlp(self.norm2(x))) 262 | 263 | return x 264 | 265 | 266 | class PatchMerging(nn.Module): 267 | """ Patch Merging Layer 268 | 269 | Args: 270 | dim (int): Number of input channels. 271 | norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm 272 | """ 273 | def __init__(self, dim, norm_layer=nn.LayerNorm): 274 | super().__init__() 275 | self.dim = dim 276 | self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) 277 | self.norm = norm_layer(4 * dim) 278 | 279 | def forward(self, x, H, W): 280 | """ Forward function. 281 | 282 | Args: 283 | x: Input feature, tensor size (B, H*W, C). 284 | H, W: Spatial resolution of the input feature. 285 | """ 286 | B, L, C = x.shape 287 | assert L == H * W, "input feature has wrong size" 288 | 289 | x = x.view(B, H, W, C) 290 | 291 | # padding 292 | pad_input = (H % 2 == 1) or (W % 2 == 1) 293 | if pad_input: 294 | x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2)) 295 | 296 | x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C 297 | x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C 298 | x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C 299 | x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C 300 | x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C 301 | x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C 302 | 303 | x = self.norm(x) 304 | x = self.reduction(x) 305 | 306 | return x 307 | 308 | 309 | class BasicLayer(nn.Module): 310 | """ A basic Swin Transformer layer for one stage. 311 | 312 | Args: 313 | dim (int): Number of feature channels 314 | depth (int): Depths of this stage. 315 | num_heads (int): Number of attention head. 316 | window_size (int): Local window size. Default: 7. 317 | mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4. 318 | qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True 319 | qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. 320 | drop (float, optional): Dropout rate. Default: 0.0 321 | attn_drop (float, optional): Attention dropout rate. Default: 0.0 322 | drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 323 | norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm 324 | downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None 325 | use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. 326 | """ 327 | 328 | def __init__(self, 329 | dim, 330 | depth, 331 | num_heads, 332 | window_size=7, 333 | mlp_ratio=4., 334 | qkv_bias=True, 335 | qk_scale=None, 336 | drop=0., 337 | attn_drop=0., 338 | drop_path=0., 339 | norm_layer=nn.LayerNorm, 340 | downsample=None, 341 | use_checkpoint=False): 342 | super().__init__() 343 | self.window_size = window_size 344 | self.shift_size = window_size // 2 345 | self.depth = depth 346 | self.use_checkpoint = use_checkpoint 347 | 348 | # build blocks 349 | self.blocks = nn.ModuleList([ 350 | SwinTransformerBlock( 351 | dim=dim, 352 | num_heads=num_heads, 353 | window_size=window_size, 354 | shift_size=0 if (i % 2 == 0) else window_size // 2, 355 | mlp_ratio=mlp_ratio, 356 | qkv_bias=qkv_bias, 357 | qk_scale=qk_scale, 358 | drop=drop, 359 | attn_drop=attn_drop, 360 | drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, 361 | norm_layer=norm_layer) 362 | for i in range(depth)]) 363 | 364 | # patch merging layer 365 | if downsample is not None: 366 | self.downsample = downsample(dim=dim, norm_layer=norm_layer) 367 | else: 368 | self.downsample = None 369 | 370 | def forward(self, x, H, W): 371 | """ Forward function. 372 | 373 | Args: 374 | x: Input feature, tensor size (B, H*W, C). 375 | H, W: Spatial resolution of the input feature. 376 | """ 377 | 378 | # calculate attention mask for SW-MSA 379 | Hp = int(np.ceil(H / self.window_size)) * self.window_size 380 | Wp = int(np.ceil(W / self.window_size)) * self.window_size 381 | img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1 382 | h_slices = (slice(0, -self.window_size), 383 | slice(-self.window_size, -self.shift_size), 384 | slice(-self.shift_size, None)) 385 | w_slices = (slice(0, -self.window_size), 386 | slice(-self.window_size, -self.shift_size), 387 | slice(-self.shift_size, None)) 388 | cnt = 0 389 | for h in h_slices: 390 | for w in w_slices: 391 | img_mask[:, h, w, :] = cnt 392 | cnt += 1 393 | 394 | mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1 395 | mask_windows = mask_windows.view(-1, self.window_size * self.window_size) 396 | attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) 397 | attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) 398 | 399 | for blk in self.blocks: 400 | blk.H, blk.W = H, W 401 | if self.use_checkpoint: 402 | x = checkpoint.checkpoint(blk, x, attn_mask) 403 | else: 404 | x = blk(x, attn_mask) 405 | if self.downsample is not None: 406 | x_down = self.downsample(x, H, W) 407 | Wh, Ww = (H + 1) // 2, (W + 1) // 2 408 | return x, H, W, x_down, Wh, Ww 409 | else: 410 | return x, H, W, x, H, W 411 | 412 | 413 | class PatchEmbed(nn.Module): 414 | """ Image to Patch Embedding 415 | 416 | Args: 417 | patch_size (int): Patch token size. Default: 4. 418 | in_channels (int): Number of input image channels. Default: 3. 419 | embed_dim (int): Number of linear projection output channels. Default: 96. 420 | norm_layer (nn.Module, optional): Normalization layer. Default: None 421 | """ 422 | 423 | def __init__(self, patch_size=4, in_channels=3, embed_dim=96, norm_layer=None): 424 | super().__init__() 425 | patch_size = to_2tuple(patch_size) 426 | self.patch_size = patch_size 427 | 428 | self.in_channels = in_channels 429 | self.embed_dim = embed_dim 430 | 431 | self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size) 432 | if norm_layer is not None: 433 | self.norm = norm_layer(embed_dim) 434 | else: 435 | self.norm = None 436 | 437 | def forward(self, x): 438 | """Forward function.""" 439 | # padding 440 | _, _, H, W = x.size() 441 | if W % self.patch_size[1] != 0: 442 | x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1])) 443 | if H % self.patch_size[0] != 0: 444 | x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0])) 445 | 446 | x = self.proj(x) # B C Wh Ww 447 | if self.norm is not None: 448 | Wh, Ww = x.size(2), x.size(3) 449 | x = x.flatten(2).transpose(1, 2) 450 | x = self.norm(x) 451 | x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww) 452 | 453 | return x 454 | 455 | 456 | class SwinTransformer(nn.Module): 457 | """ Swin Transformer backbone. 458 | A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` - 459 | https://arxiv.org/pdf/2103.14030 460 | 461 | Args: 462 | pretrain_img_size (int): Input image size for training the pretrained model, 463 | used in absolute postion embedding. Default 224. 464 | patch_size (int | tuple(int)): Patch size. Default: 4. 465 | in_channels (int): Number of input image channels. Default: 3. 466 | embed_dim (int): Number of linear projection output channels. Default: 96. 467 | depths (tuple[int]): Depths of each Swin Transformer stage. 468 | num_heads (tuple[int]): Number of attention head of each stage. 469 | window_size (int): Window size. Default: 7. 470 | mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4. 471 | qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True 472 | qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. 473 | drop_rate (float): Dropout rate. 474 | attn_drop_rate (float): Attention dropout rate. Default: 0. 475 | drop_path_rate (float): Stochastic depth rate. Default: 0.2. 476 | norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. 477 | ape (bool): If True, add absolute position embedding to the patch embedding. Default: False. 478 | patch_norm (bool): If True, add normalization after patch embedding. Default: True. 479 | out_indices (Sequence[int]): Output from which stages. 480 | frozen_stages (int): Stages to be frozen (stop grad and set eval mode). 481 | -1 means not freezing any parameters. 482 | use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. 483 | """ 484 | 485 | def __init__(self, 486 | pretrain_img_size=224, 487 | patch_size=4, 488 | in_channels=3, 489 | embed_dim=96, 490 | depths=[2, 2, 6, 2], 491 | num_heads=[3, 6, 12, 24], 492 | window_size=7, 493 | mlp_ratio=4., 494 | qkv_bias=True, 495 | qk_scale=None, 496 | drop_rate=0., 497 | attn_drop_rate=0., 498 | drop_path_rate=0.2, 499 | norm_layer=nn.LayerNorm, 500 | ape=False, 501 | patch_norm=True, 502 | out_indices=(0, 1, 2, 3), 503 | frozen_stages=-1, 504 | use_checkpoint=False): 505 | super().__init__() 506 | 507 | self.pretrain_img_size = pretrain_img_size 508 | self.num_layers = len(depths) 509 | self.embed_dim = embed_dim 510 | self.ape = ape 511 | self.patch_norm = patch_norm 512 | self.out_indices = out_indices 513 | self.frozen_stages = frozen_stages 514 | 515 | # split image into non-overlapping patches 516 | self.patch_embed = PatchEmbed( 517 | patch_size=patch_size, in_channels=in_channels, embed_dim=embed_dim, 518 | norm_layer=norm_layer if self.patch_norm else None) 519 | 520 | # absolute position embedding 521 | if self.ape: 522 | pretrain_img_size = to_2tuple(pretrain_img_size) 523 | patch_size = to_2tuple(patch_size) 524 | patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]] 525 | 526 | self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1])) 527 | trunc_normal_(self.absolute_pos_embed, std=.02) 528 | 529 | self.pos_drop = nn.Dropout(p=drop_rate) 530 | 531 | # stochastic depth 532 | dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule 533 | 534 | # build layers 535 | self.layers = nn.ModuleList() 536 | for i_layer in range(self.num_layers): 537 | layer = BasicLayer( 538 | dim=int(embed_dim * 2 ** i_layer), 539 | depth=depths[i_layer], 540 | num_heads=num_heads[i_layer], 541 | window_size=window_size, 542 | mlp_ratio=mlp_ratio, 543 | qkv_bias=qkv_bias, 544 | qk_scale=qk_scale, 545 | drop=drop_rate, 546 | attn_drop=attn_drop_rate, 547 | drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], 548 | norm_layer=norm_layer, 549 | downsample=PatchMerging if (i_layer < self.num_layers - 1) else None, 550 | use_checkpoint=use_checkpoint) 551 | self.layers.append(layer) 552 | 553 | num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)] 554 | self.num_features = num_features 555 | 556 | # add a norm layer for each output 557 | for i_layer in out_indices: 558 | layer = norm_layer(num_features[i_layer]) 559 | layer_name = f'norm{i_layer}' 560 | self.add_module(layer_name, layer) 561 | 562 | self._freeze_stages() 563 | 564 | def _freeze_stages(self): 565 | if self.frozen_stages >= 0: 566 | self.patch_embed.eval() 567 | for param in self.patch_embed.parameters(): 568 | param.requires_grad = False 569 | 570 | if self.frozen_stages >= 1 and self.ape: 571 | self.absolute_pos_embed.requires_grad = False 572 | 573 | if self.frozen_stages >= 2: 574 | self.pos_drop.eval() 575 | for i in range(0, self.frozen_stages - 1): 576 | m = self.layers[i] 577 | m.eval() 578 | for param in m.parameters(): 579 | param.requires_grad = False 580 | 581 | def init_weights(self, pretrained=None): 582 | """Initialize the weights in backbone. 583 | 584 | Args: 585 | pretrained (str, optional): Path to pre-trained weights. 586 | Defaults to None. 587 | """ 588 | 589 | def _init_weights(m): 590 | if isinstance(m, nn.Linear): 591 | trunc_normal_(m.weight, std=.02) 592 | if isinstance(m, nn.Linear) and m.bias is not None: 593 | nn.init.constant_(m.bias, 0) 594 | elif isinstance(m, nn.LayerNorm): 595 | nn.init.constant_(m.bias, 0) 596 | nn.init.constant_(m.weight, 1.0) 597 | 598 | if isinstance(pretrained, str): 599 | self.apply(_init_weights) 600 | logger = get_root_logger() 601 | load_checkpoint(self, pretrained, strict=False, logger=logger) 602 | elif pretrained is None: 603 | self.apply(_init_weights) 604 | else: 605 | raise TypeError('pretrained must be a str or None') 606 | 607 | def forward(self, x): 608 | """Forward function.""" 609 | x = self.patch_embed(x) 610 | 611 | Wh, Ww = x.size(2), x.size(3) 612 | if self.ape: 613 | # interpolate the position embedding to the corresponding size 614 | absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic') 615 | x = (x + absolute_pos_embed) # B Wh*Ww C 616 | 617 | outs = []#x.contiguous()] 618 | x = x.flatten(2).transpose(1, 2) 619 | x = self.pos_drop(x) 620 | for i in range(self.num_layers): 621 | layer = self.layers[i] 622 | x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww) 623 | 624 | if i in self.out_indices: 625 | norm_layer = getattr(self, f'norm{i}') 626 | x_out = norm_layer(x_out) 627 | 628 | out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous() 629 | outs.append(out) 630 | 631 | return tuple(outs) 632 | 633 | def train(self, mode=True): 634 | """Convert the model into training mode while keep layers freezed.""" 635 | super(SwinTransformer, self).train(mode) 636 | self._freeze_stages() 637 | 638 | def swin_v1_t(): 639 | model = SwinTransformer(embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7) 640 | return model 641 | 642 | def swin_v1_s(): 643 | model = SwinTransformer(embed_dim=96, depths=[2, 2, 18, 2], num_heads=[3, 6, 12, 24], window_size=7) 644 | return model 645 | 646 | def swin_v1_b(): 647 | model = SwinTransformer(embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12) 648 | return model 649 | 650 | def swin_v1_l(): 651 | model = SwinTransformer(embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12) 652 | return model 653 | -------------------------------------------------------------------------------- /models/baseline.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | from collections import OrderedDict 4 | import torch 5 | import torch.nn as nn 6 | import torch.nn.functional as F 7 | from torchvision.models import vgg16, vgg16_bn 8 | from torchvision.models import resnet50 9 | from kornia.filters import laplacian 10 | 11 | from models.backbones.build_backbone import build_backbone 12 | from models.modules.decoder_blocks import BasicDecBlk, ResBlk, HierarAttDecBlk 13 | from models.modules.lateral_blocks import BasicLatBlk 14 | from models.modules.aspp import ASPP, ASPPDeformable 15 | from models.modules.ing import * 16 | from models.refinement.refiner import Refiner, RefinerPVTInChannels4, RefUNet 17 | from models.refinement.stem_layer import StemLayer 18 | 19 | from config import Config 20 | from dataset import class_labels_TR_sorted 21 | 22 | 23 | class BiRefNet(nn.Module): 24 | def __init__(self): 25 | super(BiRefNet, self).__init__() 26 | self.config = Config() 27 | self.epoch = 1 28 | self.bb = build_backbone(self.config.bb, pretrained=True) 29 | 30 | channels = self.config.lateral_channels_in_collection 31 | 32 | if self.config.auxiliary_classification: 33 | self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) 34 | self.cls_head = nn.Sequential( 35 | nn.Linear(channels[0], len(class_labels_TR_sorted)) 36 | ) 37 | 38 | if self.config.squeeze_block: 39 | self.squeeze_module = nn.Sequential(*[ 40 | eval(self.config.squeeze_block.split('_x')[0])(channels[0]+sum(self.config.cxt), channels[0]) 41 | for _ in range(eval(self.config.squeeze_block.split('_x')[1])) 42 | ]) 43 | 44 | self.decoder = Decoder(channels) 45 | 46 | if self.config.locate_head: 47 | self.locate_header = nn.ModuleList([ 48 | BasicDecBlk(channels[0], channels[-1]), 49 | nn.Sequential( 50 | nn.Conv2d(channels[-1], 1, 1, 1, 0), 51 | ) 52 | ]) 53 | 54 | if self.config.ender: 55 | self.dec_end = nn.Sequential( 56 | nn.Conv2d(1, 16, 3, 1, 1), 57 | nn.Conv2d(16, 1, 3, 1, 1), 58 | nn.ReLU(inplace=True), 59 | ) 60 | 61 | # refine patch-level segmentation 62 | if self.config.refine: 63 | if self.config.refine == 'itself': 64 | self.stem_layer = StemLayer(in_channels=3+1, inter_channels=48, out_channels=3) 65 | else: 66 | self.refiner = eval('{}({})'.format(self.config.refine, 'in_channels=3+1')) 67 | 68 | if self.config.freeze_bb: 69 | # Freeze the backbone... 70 | print(self.named_parameters()) 71 | for key, value in self.named_parameters(): 72 | if 'bb.' in key and 'refiner.' not in key: 73 | value.requires_grad = False 74 | 75 | def forward_enc(self, x): 76 | if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']: 77 | x1 = self.bb.conv1(x); x2 = self.bb.conv2(x1); x3 = self.bb.conv3(x2); x4 = self.bb.conv4(x3) 78 | else: 79 | x1, x2, x3, x4 = self.bb(x) 80 | if self.config.mul_scl_ipt == 'cat': 81 | B, C, H, W = x.shape 82 | x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True)) 83 | x1 = torch.cat([x1, F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)], dim=1) 84 | x2 = torch.cat([x2, F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)], dim=1) 85 | x3 = torch.cat([x3, F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)], dim=1) 86 | x4 = torch.cat([x4, F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)], dim=1) 87 | elif self.config.mul_scl_ipt == 'add': 88 | B, C, H, W = x.shape 89 | x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True)) 90 | x1 = x1 + F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True) 91 | x2 = x2 + F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True) 92 | x3 = x3 + F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True) 93 | x4 = x4 + F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True) 94 | class_preds = self.cls_head(self.avgpool(x4).view(x4.shape[0], -1)) if self.training and self.config.auxiliary_classification else None 95 | if self.config.cxt: 96 | x4 = torch.cat( 97 | ( 98 | *[ 99 | F.interpolate(x1, size=x4.shape[2:], mode='bilinear', align_corners=True), 100 | F.interpolate(x2, size=x4.shape[2:], mode='bilinear', align_corners=True), 101 | F.interpolate(x3, size=x4.shape[2:], mode='bilinear', align_corners=True), 102 | ][-len(self.config.cxt):], 103 | x4 104 | ), 105 | dim=1 106 | ) 107 | return (x1, x2, x3, x4), class_preds 108 | 109 | def forward_ori(self, x): 110 | ########## Encoder ########## 111 | (x1, x2, x3, x4), class_preds = self.forward_enc(x) 112 | if self.config.squeeze_block: 113 | x4 = self.squeeze_module(x4) 114 | ########## Decoder ########## 115 | features = [x, x1, x2, x3, x4] 116 | if self.config.out_ref: 117 | features.append(laplacian(torch.mean(x, dim=1).unsqueeze(1), kernel_size=5)) 118 | scaled_preds = self.decoder(features) 119 | return scaled_preds, class_preds 120 | 121 | def forward_ref(self, x, pred): 122 | # refine patch-level segmentation 123 | if pred.shape[2:] != x.shape[2:]: 124 | pred = F.interpolate(pred, size=x.shape[2:], mode='bilinear', align_corners=True) 125 | # pred = pred.sigmoid() 126 | if self.config.refine == 'itself': 127 | x = self.stem_layer(torch.cat([x, pred], dim=1)) 128 | scaled_preds, class_preds = self.forward_ori(x) 129 | else: 130 | scaled_preds = self.refiner([x, pred]) 131 | class_preds = None 132 | return scaled_preds, class_preds 133 | 134 | def forward_ref_end(self, x): 135 | # remove the grids of concatenated preds 136 | return self.dec_end(x) if self.config.ender else x 137 | 138 | 139 | def forward(self, x): 140 | scaled_preds, class_preds = self.forward_ori(x) 141 | class_preds_lst = [class_preds] 142 | return [scaled_preds, class_preds_lst] if self.training else scaled_preds 143 | 144 | 145 | class Decoder(nn.Module): 146 | def __init__(self, channels): 147 | super(Decoder, self).__init__() 148 | self.config = Config() 149 | DecoderBlock = eval(self.config.dec_blk) 150 | LateralBlock = eval(self.config.lat_blk) 151 | 152 | if self.config.dec_ipt: 153 | self.split = self.config.dec_ipt_split 154 | N_dec_ipt = 64 155 | DBlock = SimpleConvs 156 | ic = 64 157 | ipt_cha_opt = 1 158 | self.ipt_blk4 = DBlock(2**8*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic) 159 | self.ipt_blk3 = DBlock(2**6*3 if self.split else 3, [N_dec_ipt, channels[1]//8][ipt_cha_opt], inter_channels=ic) 160 | self.ipt_blk2 = DBlock(2**4*3 if self.split else 3, [N_dec_ipt, channels[2]//8][ipt_cha_opt], inter_channels=ic) 161 | self.ipt_blk1 = DBlock(2**0*3 if self.split else 3, [N_dec_ipt, channels[3]//8][ipt_cha_opt], inter_channels=ic) 162 | else: 163 | self.split = None 164 | 165 | self.decoder_block4 = DecoderBlock(channels[0], channels[1]) 166 | self.decoder_block3 = DecoderBlock(channels[1]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[2]) 167 | self.decoder_block2 = DecoderBlock(channels[2]+([N_dec_ipt, channels[1]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3]) 168 | self.decoder_block1 = DecoderBlock(channels[3]+([N_dec_ipt, channels[2]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3]//2) 169 | self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2+([N_dec_ipt, channels[3]//8][ipt_cha_opt] if self.config.dec_ipt else 0), 1, 1, 1, 0)) 170 | 171 | self.lateral_block4 = LateralBlock(channels[1], channels[1]) 172 | self.lateral_block3 = LateralBlock(channels[2], channels[2]) 173 | self.lateral_block2 = LateralBlock(channels[3], channels[3]) 174 | 175 | if self.config.ms_supervision: 176 | self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0) 177 | self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0) 178 | self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0) 179 | 180 | if self.config.out_ref: 181 | _N = 16 182 | # self.gdt_convs_4 = nn.Sequential(nn.Conv2d(channels[1], _N, 3, 1, 1), nn.BatchNorm2d(_N), nn.ReLU(inplace=True)) 183 | self.gdt_convs_3 = nn.Sequential(nn.Conv2d(channels[2], _N, 3, 1, 1), nn.BatchNorm2d(_N), nn.ReLU(inplace=True)) 184 | self.gdt_convs_2 = nn.Sequential(nn.Conv2d(channels[3], _N, 3, 1, 1), nn.BatchNorm2d(_N), nn.ReLU(inplace=True)) 185 | 186 | # self.gdt_convs_pred_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) 187 | self.gdt_convs_pred_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) 188 | self.gdt_convs_pred_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) 189 | 190 | # self.gdt_convs_attn_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) 191 | self.gdt_convs_attn_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) 192 | self.gdt_convs_attn_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) 193 | 194 | 195 | def get_patches_batch(self, x, p): 196 | _size_h, _size_w = p.shape[2:] 197 | patches_batch = [] 198 | for idx in range(x.shape[0]): 199 | columns_x = torch.split(x[idx], split_size_or_sections=_size_w, dim=-1) 200 | patches_x = [] 201 | for column_x in columns_x: 202 | patches_x += [p.unsqueeze(0) for p in torch.split(column_x, split_size_or_sections=_size_h, dim=-2)] 203 | patch_sample = torch.cat(patches_x, dim=1) 204 | patches_batch.append(patch_sample) 205 | return torch.cat(patches_batch, dim=0) 206 | 207 | def forward(self, features): 208 | if self.config.out_ref: 209 | outs_gdt_pred = [] 210 | outs_gdt_label = [] 211 | x, x1, x2, x3, x4, gdt_gt = features 212 | else: 213 | x, x1, x2, x3, x4 = features 214 | outs = [] 215 | p4 = self.decoder_block4(x4) 216 | m4 = self.conv_ms_spvn_4(p4) if self.config.ms_supervision else None 217 | _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True) 218 | _p3 = _p4 + self.lateral_block4(x3) 219 | if self.config.dec_ipt: 220 | patches_batch = self.get_patches_batch(x, _p3) if self.split else x 221 | _p3 = torch.cat((_p3, self.ipt_blk4(F.interpolate(patches_batch, size=x3.shape[2:], mode='bilinear', align_corners=True))), 1) 222 | 223 | p3 = self.decoder_block3(_p3) 224 | m3 = self.conv_ms_spvn_3(p3) if self.config.ms_supervision else None 225 | if self.config.out_ref: 226 | # >> GT: 227 | # m3 --dilation--> m3_dia 228 | # G_3^gt * m3_dia --> G_3^m, which is the label of gradient 229 | m3_dia = m3 230 | gdt_label_main_3 = gdt_gt * F.interpolate(m3_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True) 231 | outs_gdt_label.append(gdt_label_main_3) 232 | # >> Pred: 233 | # p3 --conv--BN--> F_3^G, where F_3^G predicts the \hat{G_3} with xx 234 | # F_3^G --sigmoid--> A_3^G 235 | p3_gdt = self.gdt_convs_3(p3) 236 | gdt_pred_3 = self.gdt_convs_pred_3(p3_gdt) 237 | outs_gdt_pred.append(gdt_pred_3) 238 | gdt_attn_3 = self.gdt_convs_attn_3(p3_gdt).sigmoid() 239 | # >> Finally: 240 | # p3 = p3 * A_3^G 241 | p3 = p3 * gdt_attn_3 242 | _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True) 243 | _p2 = _p3 + self.lateral_block3(x2) 244 | if self.config.dec_ipt: 245 | patches_batch = self.get_patches_batch(x, _p2) if self.split else x 246 | _p2 = torch.cat((_p2, self.ipt_blk3(F.interpolate(patches_batch, size=x2.shape[2:], mode='bilinear', align_corners=True))), 1) 247 | 248 | p2 = self.decoder_block2(_p2) 249 | m2 = self.conv_ms_spvn_2(p2) if self.config.ms_supervision else None 250 | if self.config.out_ref: 251 | # >> GT: 252 | m2_dia = m2 253 | gdt_label_main_2 = gdt_gt * F.interpolate(m2_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True) 254 | outs_gdt_label.append(gdt_label_main_2) 255 | # >> Pred: 256 | p2_gdt = self.gdt_convs_2(p2) 257 | gdt_pred_2 = self.gdt_convs_pred_2(p2_gdt) 258 | outs_gdt_pred.append(gdt_pred_2) 259 | gdt_attn_2 = self.gdt_convs_attn_2(p2_gdt).sigmoid() 260 | # >> Finally: 261 | p2 = p2 * gdt_attn_2 262 | _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True) 263 | _p1 = _p2 + self.lateral_block2(x1) 264 | if self.config.dec_ipt: 265 | patches_batch = self.get_patches_batch(x, _p1) if self.split else x 266 | _p1 = torch.cat((_p1, self.ipt_blk2(F.interpolate(patches_batch, size=x1.shape[2:], mode='bilinear', align_corners=True))), 1) 267 | 268 | _p1 = self.decoder_block1(_p1) 269 | _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True) 270 | if self.config.dec_ipt: 271 | patches_batch = self.get_patches_batch(x, _p1) if self.split else x 272 | _p1 = torch.cat((_p1, self.ipt_blk1(F.interpolate(patches_batch, size=x.shape[2:], mode='bilinear', align_corners=True))), 1) 273 | p1_out = self.conv_out1(_p1) 274 | 275 | if self.config.ms_supervision: 276 | outs.append(m4) 277 | outs.append(m3) 278 | outs.append(m2) 279 | outs.append(p1_out) 280 | return outs if not (self.config.out_ref and self.training) else ([outs_gdt_pred, outs_gdt_label], outs) 281 | 282 | 283 | class SimpleConvs(nn.Module): 284 | def __init__( 285 | self, in_channels: int, out_channels: int, inter_channels=64 286 | ) -> None: 287 | super().__init__() 288 | self.conv1 = nn.Conv2d(in_channels, inter_channels, 3, 1, 1) 289 | self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, 1) 290 | 291 | def forward(self, x): 292 | return self.conv_out(self.conv1(x)) 293 | -------------------------------------------------------------------------------- /models/modules/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viperyl/ComfyUI-BiRefNet/484c90b74c5229206e1f0573e594434eac4ca151/models/modules/__init__.py -------------------------------------------------------------------------------- /models/modules/aspp.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | from models.modules.deform_conv import DeformableConv2d 5 | from config import Config 6 | 7 | 8 | config = Config() 9 | 10 | 11 | class ASPPComplex(nn.Module): 12 | def __init__(self, in_channels=64, out_channels=None, output_stride=16): 13 | super(ASPPComplex, self).__init__() 14 | self.down_scale = 1 15 | if out_channels is None: 16 | out_channels = in_channels 17 | self.in_channelster = 256 // self.down_scale 18 | if output_stride == 16: 19 | dilations = [1, 6, 12, 18] 20 | elif output_stride == 8: 21 | dilations = [1, 12, 24, 36] 22 | else: 23 | raise NotImplementedError 24 | 25 | self.aspp1 = _ASPPModule(in_channels, self.in_channelster, 1, padding=0, dilation=dilations[0]) 26 | self.aspp2 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[1], dilation=dilations[1]) 27 | self.aspp3 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[2], dilation=dilations[2]) 28 | self.aspp4 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[3], dilation=dilations[3]) 29 | 30 | self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)), 31 | nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False), 32 | nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(), 33 | nn.ReLU(inplace=True)) 34 | self.conv1 = nn.Conv2d(self.in_channelster * 5, out_channels, 1, bias=False) 35 | self.bn1 = nn.BatchNorm2d(out_channels) 36 | self.relu = nn.ReLU(inplace=True) 37 | self.dropout = nn.Dropout(0.5) 38 | 39 | def forward(self, x): 40 | x1 = self.aspp1(x) 41 | x2 = self.aspp2(x) 42 | x3 = self.aspp3(x) 43 | x4 = self.aspp4(x) 44 | x5 = self.global_avg_pool(x) 45 | x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True) 46 | x = torch.cat((x1, x2, x3, x4, x5), dim=1) 47 | 48 | x = self.conv1(x) 49 | x = self.bn1(x) 50 | x = self.relu(x) 51 | 52 | return self.dropout(x) 53 | 54 | 55 | class _ASPPModule(nn.Module): 56 | def __init__(self, in_channels, planes, kernel_size, padding, dilation): 57 | super(_ASPPModule, self).__init__() 58 | self.atrous_conv = nn.Conv2d(in_channels, planes, kernel_size=kernel_size, 59 | stride=1, padding=padding, dilation=dilation, bias=False) 60 | self.bn = nn.BatchNorm2d(planes) 61 | self.relu = nn.ReLU(inplace=True) 62 | 63 | def forward(self, x): 64 | x = self.atrous_conv(x) 65 | x = self.bn(x) 66 | 67 | return self.relu(x) 68 | 69 | class ASPP(nn.Module): 70 | def __init__(self, in_channels=64, out_channels=None, output_stride=16): 71 | super(ASPP, self).__init__() 72 | self.down_scale = 1 73 | if out_channels is None: 74 | out_channels = in_channels 75 | self.in_channelster = 256 // self.down_scale 76 | if output_stride == 16: 77 | dilations = [1, 6, 12, 18] 78 | elif output_stride == 8: 79 | dilations = [1, 12, 24, 36] 80 | else: 81 | raise NotImplementedError 82 | 83 | self.aspp1 = _ASPPModule(in_channels, self.in_channelster, 1, padding=0, dilation=dilations[0]) 84 | self.aspp2 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[1], dilation=dilations[1]) 85 | self.aspp3 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[2], dilation=dilations[2]) 86 | self.aspp4 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[3], dilation=dilations[3]) 87 | 88 | self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)), 89 | nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False), 90 | nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(), 91 | nn.ReLU(inplace=True)) 92 | self.conv1 = nn.Conv2d(self.in_channelster * 5, out_channels, 1, bias=False) 93 | self.bn1 = nn.BatchNorm2d(out_channels) 94 | self.relu = nn.ReLU(inplace=True) 95 | self.dropout = nn.Dropout(0.5) 96 | 97 | def forward(self, x): 98 | x1 = self.aspp1(x) 99 | x2 = self.aspp2(x) 100 | x3 = self.aspp3(x) 101 | x4 = self.aspp4(x) 102 | x5 = self.global_avg_pool(x) 103 | x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True) 104 | x = torch.cat((x1, x2, x3, x4, x5), dim=1) 105 | 106 | x = self.conv1(x) 107 | x = self.bn1(x) 108 | x = self.relu(x) 109 | 110 | return self.dropout(x) 111 | 112 | 113 | ##################### Deformable 114 | class _ASPPModuleDeformable(nn.Module): 115 | def __init__(self, in_channels, planes, kernel_size, padding): 116 | super(_ASPPModuleDeformable, self).__init__() 117 | self.atrous_conv = DeformableConv2d(in_channels, planes, kernel_size=kernel_size, 118 | stride=1, padding=padding, bias=False) 119 | self.bn = nn.BatchNorm2d(planes) 120 | self.relu = nn.ReLU(inplace=True) 121 | 122 | def forward(self, x): 123 | x = self.atrous_conv(x) 124 | x = self.bn(x) 125 | 126 | return self.relu(x) 127 | 128 | 129 | class ASPPDeformable(nn.Module): 130 | def __init__(self, in_channels, out_channels=None, num_parallel_block=1): 131 | super(ASPPDeformable, self).__init__() 132 | self.down_scale = 1 133 | if out_channels is None: 134 | out_channels = in_channels 135 | self.in_channelster = 256 // self.down_scale 136 | 137 | self.aspp1 = _ASPPModuleDeformable(in_channels, self.in_channelster, 1, padding=0) 138 | self.aspp_deforms = nn.ModuleList([ 139 | _ASPPModuleDeformable(in_channels, self.in_channelster, 3, padding=1) for _ in range(num_parallel_block) 140 | ]) 141 | 142 | self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)), 143 | nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False), 144 | nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(), 145 | nn.ReLU(inplace=True)) 146 | self.conv1 = nn.Conv2d(self.in_channelster * (2 + len(self.aspp_deforms)), out_channels, 1, bias=False) 147 | self.bn1 = nn.BatchNorm2d(out_channels) 148 | self.relu = nn.ReLU(inplace=True) 149 | self.dropout = nn.Dropout(0.5) 150 | 151 | def forward(self, x): 152 | x1 = self.aspp1(x) 153 | x_aspp_deforms = [aspp_deform(x) for aspp_deform in self.aspp_deforms] 154 | x5 = self.global_avg_pool(x) 155 | x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True) 156 | x = torch.cat((x1, *x_aspp_deforms, x5), dim=1) 157 | 158 | x = self.conv1(x) 159 | x = self.bn1(x) 160 | x = self.relu(x) 161 | 162 | return self.dropout(x) 163 | -------------------------------------------------------------------------------- /models/modules/attentions.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | from torch import nn 4 | from torch.nn import init 5 | 6 | 7 | class SEWeightModule(nn.Module): 8 | def __init__(self, channels, reduction=16): 9 | super(SEWeightModule, self).__init__() 10 | self.avg_pool = nn.AdaptiveAvgPool2d(1) 11 | self.fc1 = nn.Conv2d(channels, channels//reduction, kernel_size=1, padding=0) 12 | self.relu = nn.ReLU(inplace=True) 13 | self.fc2 = nn.Conv2d(channels//reduction, channels, kernel_size=1, padding=0) 14 | self.sigmoid = nn.Sigmoid() 15 | 16 | def forward(self, x): 17 | out = self.avg_pool(x) 18 | out = self.fc1(out) 19 | out = self.relu(out) 20 | out = self.fc2(out) 21 | weight = self.sigmoid(out) 22 | return weight 23 | 24 | 25 | class PSA(nn.Module): 26 | 27 | def __init__(self, in_channels, S=4, reduction=4): 28 | super().__init__() 29 | self.S = S 30 | 31 | _convs = [] 32 | for i in range(S): 33 | _convs.append(nn.Conv2d(in_channels//S, in_channels//S, kernel_size=2*(i+1)+1, padding=i+1)) 34 | self.convs = nn.ModuleList(_convs) 35 | 36 | self.se_block = SEWeightModule(in_channels//S, reduction=S*reduction) 37 | 38 | self.softmax = nn.Softmax(dim=1) 39 | 40 | def forward(self, x): 41 | b, c, h, w = x.size() 42 | 43 | # Step1: SPC module 44 | SPC_out = x.view(b, self.S, c//self.S, h, w) #bs,s,ci,h,w 45 | for idx, conv in enumerate(self.convs): 46 | SPC_out[:,idx,:,:,:] = conv(SPC_out[:,idx,:,:,:].clone()) 47 | 48 | # Step2: SE weight 49 | se_out=[] 50 | for idx in range(self.S): 51 | se_out.append(self.se_block(SPC_out[:, idx, :, :, :])) 52 | SE_out = torch.stack(se_out, dim=1) 53 | SE_out = SE_out.expand_as(SPC_out) 54 | 55 | # Step3: Softmax 56 | softmax_out = self.softmax(SE_out) 57 | 58 | # Step4: SPA 59 | PSA_out = SPC_out * softmax_out 60 | PSA_out = PSA_out.view(b, -1, h, w) 61 | 62 | return PSA_out 63 | 64 | 65 | class SGE(nn.Module): 66 | 67 | def __init__(self, groups): 68 | super().__init__() 69 | self.groups=groups 70 | self.avg_pool = nn.AdaptiveAvgPool2d(1) 71 | self.weight=nn.Parameter(torch.zeros(1,groups,1,1)) 72 | self.bias=nn.Parameter(torch.zeros(1,groups,1,1)) 73 | self.sig=nn.Sigmoid() 74 | 75 | def forward(self, x): 76 | b, c, h,w=x.shape 77 | x=x.view(b*self.groups,-1,h,w) #bs*g,dim//g,h,w 78 | xn=x*self.avg_pool(x) #bs*g,dim//g,h,w 79 | xn=xn.sum(dim=1,keepdim=True) #bs*g,1,h,w 80 | t=xn.view(b*self.groups,-1) #bs*g,h*w 81 | 82 | t=t-t.mean(dim=1,keepdim=True) #bs*g,h*w 83 | std=t.std(dim=1,keepdim=True)+1e-5 84 | t=t/std #bs*g,h*w 85 | t=t.view(b,self.groups,h,w) #bs,g,h*w 86 | 87 | t=t*self.weight+self.bias #bs,g,h*w 88 | t=t.view(b*self.groups,1,h,w) #bs*g,1,h*w 89 | x=x*self.sig(t) 90 | x=x.view(b,c,h,w) 91 | 92 | return x 93 | 94 | -------------------------------------------------------------------------------- /models/modules/decoder_blocks.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | from models.modules.aspp import ASPP, ASPPDeformable 4 | from models.modules.attentions import PSA, SGE 5 | from config import Config 6 | 7 | 8 | config = Config() 9 | 10 | 11 | class BasicDecBlk(nn.Module): 12 | def __init__(self, in_channels=64, out_channels=64, inter_channels=64): 13 | super(BasicDecBlk, self).__init__() 14 | inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64 15 | self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1) 16 | self.relu_in = nn.ReLU(inplace=True) 17 | if config.dec_att == 'ASPP': 18 | self.dec_att = ASPP(in_channels=inter_channels) 19 | elif config.dec_att == 'ASPPDeformable': 20 | self.dec_att = ASPPDeformable(in_channels=inter_channels) 21 | self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1) 22 | self.bn_in = nn.BatchNorm2d(inter_channels) 23 | self.bn_out = nn.BatchNorm2d(out_channels) 24 | 25 | def forward(self, x): 26 | x = self.conv_in(x) 27 | x = self.bn_in(x) 28 | x = self.relu_in(x) 29 | if hasattr(self, 'dec_att'): 30 | x = self.dec_att(x) 31 | x = self.conv_out(x) 32 | x = self.bn_out(x) 33 | return x 34 | 35 | 36 | class ResBlk(nn.Module): 37 | def __init__(self, in_channels=64, out_channels=None, inter_channels=64): 38 | super(ResBlk, self).__init__() 39 | if out_channels is None: 40 | out_channels = in_channels 41 | inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64 42 | 43 | self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1) 44 | self.bn_in = nn.BatchNorm2d(inter_channels) 45 | self.relu_in = nn.ReLU(inplace=True) 46 | 47 | if config.dec_att == 'ASPP': 48 | self.dec_att = ASPP(in_channels=inter_channels) 49 | elif config.dec_att == 'ASPPDeformable': 50 | self.dec_att = ASPPDeformable(in_channels=inter_channels) 51 | 52 | self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1) 53 | self.bn_out = nn.BatchNorm2d(out_channels) 54 | 55 | self.conv_resi = nn.Conv2d(in_channels, out_channels, 1, 1, 0) 56 | 57 | def forward(self, x): 58 | _x = self.conv_resi(x) 59 | x = self.conv_in(x) 60 | x = self.bn_in(x) 61 | x = self.relu_in(x) 62 | if hasattr(self, 'dec_att'): 63 | x = self.dec_att(x) 64 | x = self.conv_out(x) 65 | x = self.bn_out(x) 66 | return x + _x 67 | 68 | 69 | class HierarAttDecBlk(nn.Module): 70 | def __init__(self, in_channels=64, out_channels=None, inter_channels=64): 71 | super(HierarAttDecBlk, self).__init__() 72 | if out_channels is None: 73 | out_channels = in_channels 74 | inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64 75 | self.split_y = 8 # must be divided by channels of all intermediate features 76 | self.split_x = 8 77 | 78 | self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, 1) 79 | 80 | self.psa = PSA(inter_channels*self.split_y*self.split_x, S=config.batch_size) 81 | self.sge = SGE(groups=config.batch_size) 82 | 83 | if config.dec_att == 'ASPP': 84 | self.dec_att = ASPP(in_channels=inter_channels) 85 | elif config.dec_att == 'ASPPDeformable': 86 | self.dec_att = ASPPDeformable(in_channels=inter_channels) 87 | self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, 1) 88 | 89 | def forward(self, x): 90 | x = self.conv_in(x) 91 | N, C, H, W = x.shape 92 | x_patchs = x.reshape(N, -1, H//self.split_y, W//self.split_x) 93 | 94 | # Hierarchical attention: group attention X patch spatial attention 95 | x_patchs = self.psa(x_patchs) # Group Channel Attention -- each group is a single image 96 | x_patchs = self.sge(x_patchs) # Patch Spatial Attention 97 | x = x.reshape(N, C, H, W) 98 | if hasattr(self, 'dec_att'): 99 | x = self.dec_att(x) 100 | x = self.conv_out(x) 101 | return x 102 | -------------------------------------------------------------------------------- /models/modules/deform_conv.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | from torchvision.ops import deform_conv2d 4 | 5 | 6 | class DeformableConv2d(nn.Module): 7 | def __init__(self, 8 | in_channels, 9 | out_channels, 10 | kernel_size=3, 11 | stride=1, 12 | padding=1, 13 | bias=False): 14 | 15 | super(DeformableConv2d, self).__init__() 16 | 17 | assert type(kernel_size) == tuple or type(kernel_size) == int 18 | 19 | kernel_size = kernel_size if type(kernel_size) == tuple else (kernel_size, kernel_size) 20 | self.stride = stride if type(stride) == tuple else (stride, stride) 21 | self.padding = padding 22 | 23 | self.offset_conv = nn.Conv2d(in_channels, 24 | 2 * kernel_size[0] * kernel_size[1], 25 | kernel_size=kernel_size, 26 | stride=stride, 27 | padding=self.padding, 28 | bias=True) 29 | 30 | nn.init.constant_(self.offset_conv.weight, 0.) 31 | nn.init.constant_(self.offset_conv.bias, 0.) 32 | 33 | self.modulator_conv = nn.Conv2d(in_channels, 34 | 1 * kernel_size[0] * kernel_size[1], 35 | kernel_size=kernel_size, 36 | stride=stride, 37 | padding=self.padding, 38 | bias=True) 39 | 40 | nn.init.constant_(self.modulator_conv.weight, 0.) 41 | nn.init.constant_(self.modulator_conv.bias, 0.) 42 | 43 | self.regular_conv = nn.Conv2d(in_channels, 44 | out_channels=out_channels, 45 | kernel_size=kernel_size, 46 | stride=stride, 47 | padding=self.padding, 48 | bias=bias) 49 | 50 | def forward(self, x): 51 | #h, w = x.shape[2:] 52 | #max_offset = max(h, w)/4. 53 | 54 | offset = self.offset_conv(x)#.clamp(-max_offset, max_offset) 55 | modulator = 2. * torch.sigmoid(self.modulator_conv(x)) 56 | 57 | x = deform_conv2d( 58 | input=x, 59 | offset=offset, 60 | weight=self.regular_conv.weight, 61 | bias=self.regular_conv.bias, 62 | padding=self.padding, 63 | mask=modulator, 64 | stride=self.stride, 65 | ) 66 | return x 67 | -------------------------------------------------------------------------------- /models/modules/ing.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | from models.modules.mlp import MLPLayer 3 | 4 | 5 | class BlockA(nn.Module): 6 | def __init__(self, in_channels=64, out_channels=64, inter_channels=64, mlp_ratio=4.): 7 | super(BlockA, self).__init__() 8 | inter_channels = in_channels 9 | self.conv = nn.Conv2d(in_channels, inter_channels, 3, 1, 1) 10 | self.norm1 = nn.LayerNorm(inter_channels) 11 | self.ffn = MLPLayer(in_features=inter_channels, 12 | hidden_features=int(inter_channels * mlp_ratio), 13 | act_layer=nn.GELU, 14 | drop=0.) 15 | self.norm2 = nn.LayerNorm(inter_channels) 16 | 17 | def forward(self, x): 18 | B, C, H, W = x.shape 19 | _x = self.conv(x) 20 | _x = _x.flatten(2).transpose(1, 2) 21 | _x = self.norm1(_x) 22 | x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() 23 | 24 | x = x + _x 25 | _x1 = self.ffn(x) 26 | _x1 = self.norm2(_x1) 27 | _x1 = _x1.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() 28 | x = x + _x1 29 | return x -------------------------------------------------------------------------------- /models/modules/lateral_blocks.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | from functools import partial 6 | 7 | from config import Config 8 | 9 | 10 | config = Config() 11 | 12 | 13 | class BasicLatBlk(nn.Module): 14 | def __init__(self, in_channels=64, out_channels=64, inter_channels=64): 15 | super(BasicLatBlk, self).__init__() 16 | inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64 17 | self.conv = nn.Conv2d(in_channels, out_channels, 1, 1, 0) 18 | 19 | def forward(self, x): 20 | x = self.conv(x) 21 | return x 22 | -------------------------------------------------------------------------------- /models/modules/mlp.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | from functools import partial 4 | 5 | from timm.models.layers import DropPath, to_2tuple, trunc_normal_ 6 | from timm.models.registry import register_model 7 | 8 | import math 9 | 10 | 11 | class MLPLayer(nn.Module): 12 | def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): 13 | super().__init__() 14 | out_features = out_features or in_features 15 | hidden_features = hidden_features or in_features 16 | self.fc1 = nn.Linear(in_features, hidden_features) 17 | self.act = act_layer() 18 | self.fc2 = nn.Linear(hidden_features, out_features) 19 | self.drop = nn.Dropout(drop) 20 | 21 | def forward(self, x): 22 | x = self.fc1(x) 23 | x = self.act(x) 24 | x = self.drop(x) 25 | x = self.fc2(x) 26 | x = self.drop(x) 27 | return x 28 | 29 | 30 | class Attention(nn.Module): 31 | def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1): 32 | super().__init__() 33 | assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}." 34 | 35 | self.dim = dim 36 | self.num_heads = num_heads 37 | head_dim = dim // num_heads 38 | self.scale = qk_scale or head_dim ** -0.5 39 | 40 | self.q = nn.Linear(dim, dim, bias=qkv_bias) 41 | self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias) 42 | self.attn_drop = nn.Dropout(attn_drop) 43 | self.proj = nn.Linear(dim, dim) 44 | self.proj_drop = nn.Dropout(proj_drop) 45 | 46 | self.sr_ratio = sr_ratio 47 | if sr_ratio > 1: 48 | self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio) 49 | self.norm = nn.LayerNorm(dim) 50 | 51 | def forward(self, x, H, W): 52 | B, N, C = x.shape 53 | q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) 54 | 55 | if self.sr_ratio > 1: 56 | x_ = x.permute(0, 2, 1).reshape(B, C, H, W) 57 | x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1) 58 | x_ = self.norm(x_) 59 | kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) 60 | else: 61 | kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) 62 | k, v = kv[0], kv[1] 63 | 64 | attn = (q @ k.transpose(-2, -1)) * self.scale 65 | attn = attn.softmax(dim=-1) 66 | attn = self.attn_drop(attn) 67 | 68 | x = (attn @ v).transpose(1, 2).reshape(B, N, C) 69 | x = self.proj(x) 70 | x = self.proj_drop(x) 71 | return x 72 | 73 | 74 | class Block(nn.Module): 75 | def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., 76 | drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1): 77 | super().__init__() 78 | self.norm1 = norm_layer(dim) 79 | self.attn = Attention( 80 | dim, 81 | num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, 82 | attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio) 83 | # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here 84 | self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() 85 | self.norm2 = norm_layer(dim) 86 | mlp_hidden_dim = int(dim * mlp_ratio) 87 | self.mlp = MLPLayer(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) 88 | 89 | def forward(self, x, H, W): 90 | x = x + self.drop_path(self.attn(self.norm1(x), H, W)) 91 | x = x + self.drop_path(self.mlp(self.norm2(x), H, W)) 92 | return x 93 | 94 | 95 | class OverlapPatchEmbed(nn.Module): 96 | """ Image to Patch Embedding 97 | """ 98 | 99 | def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768): 100 | super().__init__() 101 | img_size = to_2tuple(img_size) 102 | patch_size = to_2tuple(patch_size) 103 | 104 | self.img_size = img_size 105 | self.patch_size = patch_size 106 | self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1] 107 | self.num_patches = self.H * self.W 108 | self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride, 109 | padding=(patch_size[0] // 2, patch_size[1] // 2)) 110 | self.norm = nn.LayerNorm(embed_dim) 111 | 112 | def forward(self, x): 113 | x = self.proj(x) 114 | _, _, H, W = x.shape 115 | x = x.flatten(2).transpose(1, 2) 116 | x = self.norm(x) 117 | return x, H, W 118 | 119 | -------------------------------------------------------------------------------- /models/modules/utils.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | 3 | 4 | def build_act_layer(act_layer): 5 | if act_layer == 'ReLU': 6 | return nn.ReLU(inplace=True) 7 | elif act_layer == 'SiLU': 8 | return nn.SiLU(inplace=True) 9 | elif act_layer == 'GELU': 10 | return nn.GELU() 11 | 12 | raise NotImplementedError(f'build_act_layer does not support {act_layer}') 13 | 14 | 15 | def build_norm_layer(dim, 16 | norm_layer, 17 | in_format='channels_last', 18 | out_format='channels_last', 19 | eps=1e-6): 20 | layers = [] 21 | if norm_layer == 'BN': 22 | if in_format == 'channels_last': 23 | layers.append(to_channels_first()) 24 | layers.append(nn.BatchNorm2d(dim)) 25 | if out_format == 'channels_last': 26 | layers.append(to_channels_last()) 27 | elif norm_layer == 'LN': 28 | if in_format == 'channels_first': 29 | layers.append(to_channels_last()) 30 | layers.append(nn.LayerNorm(dim, eps=eps)) 31 | if out_format == 'channels_first': 32 | layers.append(to_channels_first()) 33 | else: 34 | raise NotImplementedError( 35 | f'build_norm_layer does not support {norm_layer}') 36 | return nn.Sequential(*layers) 37 | 38 | 39 | class to_channels_first(nn.Module): 40 | 41 | def __init__(self): 42 | super().__init__() 43 | 44 | def forward(self, x): 45 | return x.permute(0, 3, 1, 2) 46 | 47 | 48 | class to_channels_last(nn.Module): 49 | 50 | def __init__(self): 51 | super().__init__() 52 | 53 | def forward(self, x): 54 | return x.permute(0, 2, 3, 1) 55 | -------------------------------------------------------------------------------- /models/refinement/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viperyl/ComfyUI-BiRefNet/484c90b74c5229206e1f0573e594434eac4ca151/models/refinement/__init__.py -------------------------------------------------------------------------------- /models/refinement/refiner.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | from collections import OrderedDict 4 | import torch 5 | import torch.nn as nn 6 | import torch.nn.functional as F 7 | from torchvision.models import vgg16, vgg16_bn 8 | from torchvision.models import resnet50 9 | 10 | from config import Config 11 | from dataset import class_labels_TR_sorted 12 | from models.backbones.build_backbone import build_backbone 13 | from models.modules.decoder_blocks import BasicDecBlk 14 | from models.modules.lateral_blocks import BasicLatBlk 15 | from models.modules.ing import * 16 | from models.refinement.stem_layer import StemLayer 17 | 18 | 19 | class RefinerPVTInChannels4(nn.Module): 20 | def __init__(self, in_channels=3+1): 21 | super(RefinerPVTInChannels4, self).__init__() 22 | self.config = Config() 23 | self.epoch = 1 24 | self.bb = build_backbone(self.config.bb, params_settings='in_channels=4') 25 | 26 | lateral_channels_in_collection = { 27 | 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64], 28 | 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64], 29 | 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192], 30 | } 31 | channels = lateral_channels_in_collection[self.config.bb] 32 | self.squeeze_module = BasicDecBlk(channels[0], channels[0]) 33 | 34 | self.decoder = Decoder(channels) 35 | 36 | if 0: 37 | for key, value in self.named_parameters(): 38 | if 'bb.' in key: 39 | value.requires_grad = False 40 | 41 | def forward(self, x): 42 | if isinstance(x, list): 43 | x = torch.cat(x, dim=1) 44 | ########## Encoder ########## 45 | if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']: 46 | x1 = self.bb.conv1(x) 47 | x2 = self.bb.conv2(x1) 48 | x3 = self.bb.conv3(x2) 49 | x4 = self.bb.conv4(x3) 50 | else: 51 | x1, x2, x3, x4 = self.bb(x) 52 | 53 | x4 = self.squeeze_module(x4) 54 | 55 | ########## Decoder ########## 56 | 57 | features = [x, x1, x2, x3, x4] 58 | scaled_preds = self.decoder(features) 59 | 60 | return scaled_preds 61 | 62 | 63 | class Refiner(nn.Module): 64 | def __init__(self, in_channels=3+1): 65 | super(Refiner, self).__init__() 66 | self.config = Config() 67 | self.epoch = 1 68 | self.stem_layer = StemLayer(in_channels=in_channels, inter_channels=48, out_channels=3) 69 | self.bb = build_backbone(self.config.bb) 70 | 71 | lateral_channels_in_collection = { 72 | 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64], 73 | 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64], 74 | 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192], 75 | } 76 | channels = lateral_channels_in_collection[self.config.bb] 77 | self.squeeze_module = BasicDecBlk(channels[0], channels[0]) 78 | 79 | self.decoder = Decoder(channels) 80 | 81 | if 0: 82 | for key, value in self.named_parameters(): 83 | if 'bb.' in key: 84 | value.requires_grad = False 85 | 86 | def forward(self, x): 87 | if isinstance(x, list): 88 | x = torch.cat(x, dim=1) 89 | x = self.stem_layer(x) 90 | ########## Encoder ########## 91 | if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']: 92 | x1 = self.bb.conv1(x) 93 | x2 = self.bb.conv2(x1) 94 | x3 = self.bb.conv3(x2) 95 | x4 = self.bb.conv4(x3) 96 | else: 97 | x1, x2, x3, x4 = self.bb(x) 98 | 99 | x4 = self.squeeze_module(x4) 100 | 101 | ########## Decoder ########## 102 | 103 | features = [x, x1, x2, x3, x4] 104 | scaled_preds = self.decoder(features) 105 | 106 | return scaled_preds 107 | 108 | 109 | class Decoder(nn.Module): 110 | def __init__(self, channels): 111 | super(Decoder, self).__init__() 112 | self.config = Config() 113 | DecoderBlock = eval('BasicDecBlk') 114 | LateralBlock = eval('BasicLatBlk') 115 | 116 | self.decoder_block4 = DecoderBlock(channels[0], channels[1]) 117 | self.decoder_block3 = DecoderBlock(channels[1], channels[2]) 118 | self.decoder_block2 = DecoderBlock(channels[2], channels[3]) 119 | self.decoder_block1 = DecoderBlock(channels[3], channels[3]//2) 120 | 121 | self.lateral_block4 = LateralBlock(channels[1], channels[1]) 122 | self.lateral_block3 = LateralBlock(channels[2], channels[2]) 123 | self.lateral_block2 = LateralBlock(channels[3], channels[3]) 124 | 125 | if self.config.ms_supervision: 126 | self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0) 127 | self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0) 128 | self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0) 129 | self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2, 1, 1, 1, 0)) 130 | 131 | def forward(self, features): 132 | x, x1, x2, x3, x4 = features 133 | outs = [] 134 | p4 = self.decoder_block4(x4) 135 | _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True) 136 | _p3 = _p4 + self.lateral_block4(x3) 137 | 138 | p3 = self.decoder_block3(_p3) 139 | _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True) 140 | _p2 = _p3 + self.lateral_block3(x2) 141 | 142 | p2 = self.decoder_block2(_p2) 143 | _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True) 144 | _p1 = _p2 + self.lateral_block2(x1) 145 | 146 | _p1 = self.decoder_block1(_p1) 147 | _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True) 148 | p1_out = self.conv_out1(_p1) 149 | 150 | if self.config.ms_supervision: 151 | outs.append(self.conv_ms_spvn_4(p4)) 152 | outs.append(self.conv_ms_spvn_3(p3)) 153 | outs.append(self.conv_ms_spvn_2(p2)) 154 | outs.append(p1_out) 155 | return outs 156 | 157 | 158 | class RefUNet(nn.Module): 159 | # Refinement 160 | def __init__(self, in_channels=3+1): 161 | super(RefUNet, self).__init__() 162 | self.encoder_1 = nn.Sequential( 163 | nn.Conv2d(in_channels, 64, 3, 1, 1), 164 | nn.Conv2d(64, 64, 3, 1, 1), 165 | nn.BatchNorm2d(64), 166 | nn.ReLU(inplace=True) 167 | ) 168 | 169 | self.encoder_2 = nn.Sequential( 170 | nn.MaxPool2d(2, 2, ceil_mode=True), 171 | nn.Conv2d(64, 64, 3, 1, 1), 172 | nn.BatchNorm2d(64), 173 | nn.ReLU(inplace=True) 174 | ) 175 | 176 | self.encoder_3 = nn.Sequential( 177 | nn.MaxPool2d(2, 2, ceil_mode=True), 178 | nn.Conv2d(64, 64, 3, 1, 1), 179 | nn.BatchNorm2d(64), 180 | nn.ReLU(inplace=True) 181 | ) 182 | 183 | self.encoder_4 = nn.Sequential( 184 | nn.MaxPool2d(2, 2, ceil_mode=True), 185 | nn.Conv2d(64, 64, 3, 1, 1), 186 | nn.BatchNorm2d(64), 187 | nn.ReLU(inplace=True) 188 | ) 189 | 190 | self.pool4 = nn.MaxPool2d(2, 2, ceil_mode=True) 191 | ##### 192 | self.decoder_5 = nn.Sequential( 193 | nn.Conv2d(64, 64, 3, 1, 1), 194 | nn.BatchNorm2d(64), 195 | nn.ReLU(inplace=True) 196 | ) 197 | ##### 198 | self.decoder_4 = nn.Sequential( 199 | nn.Conv2d(128, 64, 3, 1, 1), 200 | nn.BatchNorm2d(64), 201 | nn.ReLU(inplace=True) 202 | ) 203 | 204 | self.decoder_3 = nn.Sequential( 205 | nn.Conv2d(128, 64, 3, 1, 1), 206 | nn.BatchNorm2d(64), 207 | nn.ReLU(inplace=True) 208 | ) 209 | 210 | self.decoder_2 = nn.Sequential( 211 | nn.Conv2d(128, 64, 3, 1, 1), 212 | nn.BatchNorm2d(64), 213 | nn.ReLU(inplace=True) 214 | ) 215 | 216 | self.decoder_1 = nn.Sequential( 217 | nn.Conv2d(128, 64, 3, 1, 1), 218 | nn.BatchNorm2d(64), 219 | nn.ReLU(inplace=True) 220 | ) 221 | 222 | self.conv_d0 = nn.Conv2d(64, 1, 3, 1, 1) 223 | 224 | self.upscore2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) 225 | 226 | def forward(self, x): 227 | outs = [] 228 | if isinstance(x, list): 229 | x = torch.cat(x, dim=1) 230 | hx = x 231 | 232 | hx1 = self.encoder_1(hx) 233 | hx2 = self.encoder_2(hx1) 234 | hx3 = self.encoder_3(hx2) 235 | hx4 = self.encoder_4(hx3) 236 | 237 | hx = self.decoder_5(self.pool4(hx4)) 238 | hx = torch.cat((self.upscore2(hx), hx4), 1) 239 | 240 | d4 = self.decoder_4(hx) 241 | hx = torch.cat((self.upscore2(d4), hx3), 1) 242 | 243 | d3 = self.decoder_3(hx) 244 | hx = torch.cat((self.upscore2(d3), hx2), 1) 245 | 246 | d2 = self.decoder_2(hx) 247 | hx = torch.cat((self.upscore2(d2), hx1), 1) 248 | 249 | d1 = self.decoder_1(hx) 250 | 251 | x = self.conv_d0(d1) 252 | outs.append(x) 253 | return outs 254 | -------------------------------------------------------------------------------- /models/refinement/stem_layer.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | from models.modules.utils import build_act_layer, build_norm_layer 3 | 4 | 5 | class StemLayer(nn.Module): 6 | r""" Stem layer of InternImage 7 | Args: 8 | in_channels (int): number of input channels 9 | out_channels (int): number of output channels 10 | act_layer (str): activation layer 11 | norm_layer (str): normalization layer 12 | """ 13 | 14 | def __init__(self, 15 | in_channels=3+1, 16 | inter_channels=48, 17 | out_channels=96, 18 | act_layer='GELU', 19 | norm_layer='BN'): 20 | super().__init__() 21 | self.conv1 = nn.Conv2d(in_channels, 22 | inter_channels, 23 | kernel_size=3, 24 | stride=1, 25 | padding=1) 26 | self.norm1 = build_norm_layer( 27 | inter_channels, norm_layer, 'channels_first', 'channels_first' 28 | ) 29 | self.act = build_act_layer(act_layer) 30 | self.conv2 = nn.Conv2d(inter_channels, 31 | out_channels, 32 | kernel_size=3, 33 | stride=1, 34 | padding=1) 35 | self.norm2 = build_norm_layer( 36 | out_channels, norm_layer, 'channels_first', 'channels_first' 37 | ) 38 | 39 | def forward(self, x): 40 | x = self.conv1(x) 41 | x = self.norm1(x) 42 | x = self.act(x) 43 | x = self.conv2(x) 44 | x = self.norm2(x) 45 | return x 46 | -------------------------------------------------------------------------------- /preproc.py: -------------------------------------------------------------------------------- 1 | from PIL import Image, ImageEnhance 2 | import random 3 | import numpy as np 4 | import random 5 | 6 | 7 | def preproc(image, label, preproc_methods=['flip']): 8 | if 'flip' in preproc_methods: 9 | image, label = cv_random_flip(image, label) 10 | if 'crop' in preproc_methods: 11 | image, label = random_crop(image, label) 12 | if 'rotate' in preproc_methods: 13 | image, label = random_rotate(image, label) 14 | if 'enhance' in preproc_methods: 15 | image = color_enhance(image) 16 | if 'pepper' in preproc_methods: 17 | label = random_pepper(label) 18 | return image, label 19 | 20 | 21 | def cv_random_flip(img, label): 22 | if random.random() > 0.5: 23 | img = img.transpose(Image.FLIP_LEFT_RIGHT) 24 | label = label.transpose(Image.FLIP_LEFT_RIGHT) 25 | return img, label 26 | 27 | 28 | def random_crop(image, label): 29 | border = 30 30 | image_width = image.size[0] 31 | image_height = image.size[1] 32 | border = int(min(image_width, image_height) * 0.1) 33 | crop_win_width = np.random.randint(image_width - border, image_width) 34 | crop_win_height = np.random.randint(image_height - border, image_height) 35 | random_region = ( 36 | (image_width - crop_win_width) >> 1, (image_height - crop_win_height) >> 1, (image_width + crop_win_width) >> 1, 37 | (image_height + crop_win_height) >> 1) 38 | return image.crop(random_region), label.crop(random_region) 39 | 40 | 41 | def random_rotate(image, label, angle=15): 42 | mode = Image.BICUBIC 43 | if random.random() > 0.8: 44 | random_angle = np.random.randint(-angle, angle) 45 | image = image.rotate(random_angle, mode) 46 | label = label.rotate(random_angle, mode) 47 | return image, label 48 | 49 | 50 | def color_enhance(image): 51 | bright_intensity = random.randint(5, 15) / 10.0 52 | image = ImageEnhance.Brightness(image).enhance(bright_intensity) 53 | contrast_intensity = random.randint(5, 15) / 10.0 54 | image = ImageEnhance.Contrast(image).enhance(contrast_intensity) 55 | color_intensity = random.randint(0, 20) / 10.0 56 | image = ImageEnhance.Color(image).enhance(color_intensity) 57 | sharp_intensity = random.randint(0, 30) / 10.0 58 | image = ImageEnhance.Sharpness(image).enhance(sharp_intensity) 59 | return image 60 | 61 | 62 | def random_gaussian(image, mean=0.1, sigma=0.35): 63 | def gaussianNoisy(im, mean=mean, sigma=sigma): 64 | for _i in range(len(im)): 65 | im[_i] += random.gauss(mean, sigma) 66 | return im 67 | 68 | img = np.asarray(image) 69 | width, height = img.shape 70 | img = gaussianNoisy(img[:].flatten(), mean, sigma) 71 | img = img.reshape([width, height]) 72 | return Image.fromarray(np.uint8(img)) 73 | 74 | 75 | def random_pepper(img, N=0.0015): 76 | img = np.array(img) 77 | noiseNum = int(N * img.shape[0] * img.shape[1]) 78 | for i in range(noiseNum): 79 | randX = random.randint(0, img.shape[0] - 1) 80 | randY = random.randint(0, img.shape[1] - 1) 81 | if random.randint(0, 1) == 0: 82 | img[randX, randY] = 0 83 | else: 84 | img[randX, randY] = 255 85 | return Image.fromarray(img) 86 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "comfyui-birefnet" 3 | description = "Bilateral Reference Network achieves SOTA result in multi Salient Object Segmentation dataset, this repo pack BiRefNet as ComfyUI nodes, and make this SOTA model easier use for everyone." 4 | version = "1.0.0" 5 | license = "LICENSE" 6 | dependencies = ["kornia", "loguru", "opencv-python", "timm", "prettytable", "scipy"] 7 | 8 | [project.urls] 9 | Repository = "https://github.com/viperyl/ComfyUI-BiRefNet" 10 | # Used by Comfy Registry https://comfyregistry.org 11 | 12 | [tool.comfy] 13 | PublisherId = "viper" 14 | DisplayName = "ComfyUI-BiRefNet" 15 | Icon = "" 16 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | kornia 2 | loguru 3 | opencv-python 4 | timm 5 | prettytable 6 | scipy -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | def check_download_model(model_path, repo_id="ViperYX/BiRefNet"): 5 | if not os.path.exists(model_path): 6 | folder_path = os.path.dirname(model_path) 7 | if not os.path.exists(folder_path): 8 | os.makedirs(folder_path) 9 | file_name = os.path.basename(model_path) 10 | print(f"Downloading BiRefNet model to: {model_path}") 11 | from huggingface_hub import snapshot_download 12 | snapshot_download(repo_id=repo_id, 13 | allow_patterns=[f"*{file_name}*"], 14 | local_dir=folder_path, 15 | local_dir_use_symlinks=False) 16 | return True 17 | return False 18 | -------------------------------------------------------------------------------- /workflow/example_workflow.json: -------------------------------------------------------------------------------- 1 | { 2 | "last_node_id": 4, 3 | "last_link_id": 3, 4 | "nodes": [ 5 | { 6 | "id": 2, 7 | "type": "LoadImage", 8 | "pos": [ 9 | 496, 10 | 553 11 | ], 12 | "size": { 13 | "0": 315, 14 | "1": 314 15 | }, 16 | "flags": {}, 17 | "order": 0, 18 | "mode": 0, 19 | "outputs": [ 20 | { 21 | "name": "IMAGE", 22 | "type": "IMAGE", 23 | "links": [ 24 | 1 25 | ], 26 | "shape": 3, 27 | "slot_index": 0 28 | }, 29 | { 30 | "name": "MASK", 31 | "type": "MASK", 32 | "links": null, 33 | "shape": 3 34 | } 35 | ], 36 | "properties": { 37 | "Node name for S&R": "LoadImage" 38 | }, 39 | "widgets_values": [ 40 | "1024x1024-1Accessories1Bag3811492306_4ae60c73b6_o.jpg", 41 | "image" 42 | ] 43 | }, 44 | { 45 | "id": 4, 46 | "type": "PreviewImage", 47 | "pos": [ 48 | 1529, 49 | 552 50 | ], 51 | "size": { 52 | "0": 210, 53 | "1": 246 54 | }, 55 | "flags": {}, 56 | "order": 3, 57 | "mode": 0, 58 | "inputs": [ 59 | { 60 | "name": "images", 61 | "type": "IMAGE", 62 | "link": 3 63 | } 64 | ], 65 | "properties": { 66 | "Node name for S&R": "PreviewImage" 67 | } 68 | }, 69 | { 70 | "id": 3, 71 | "type": "MaskToImage", 72 | "pos": [ 73 | 1244, 74 | 552 75 | ], 76 | "size": { 77 | "0": 210, 78 | "1": 26 79 | }, 80 | "flags": {}, 81 | "order": 2, 82 | "mode": 0, 83 | "inputs": [ 84 | { 85 | "name": "mask", 86 | "type": "MASK", 87 | "link": 2 88 | } 89 | ], 90 | "outputs": [ 91 | { 92 | "name": "IMAGE", 93 | "type": "IMAGE", 94 | "links": [ 95 | 3 96 | ], 97 | "shape": 3, 98 | "slot_index": 0 99 | } 100 | ], 101 | "properties": { 102 | "Node name for S&R": "MaskToImage" 103 | } 104 | }, 105 | { 106 | "id": 1, 107 | "type": "BiRefNet", 108 | "pos": [ 109 | 882, 110 | 557 111 | ], 112 | "size": { 113 | "0": 315, 114 | "1": 58 115 | }, 116 | "flags": {}, 117 | "order": 1, 118 | "mode": 0, 119 | "inputs": [ 120 | { 121 | "name": "image", 122 | "type": "IMAGE", 123 | "link": 1 124 | } 125 | ], 126 | "outputs": [ 127 | { 128 | "name": "mask", 129 | "type": "Mask", 130 | "links": [ 131 | 2 132 | ], 133 | "shape": 3, 134 | "slot_index": 0 135 | } 136 | ], 137 | "properties": { 138 | "Node name for S&R": "BiRefNet" 139 | }, 140 | "widgets_values": [ 141 | "cuda:0" 142 | ] 143 | } 144 | ], 145 | "links": [ 146 | [ 147 | 1, 148 | 2, 149 | 0, 150 | 1, 151 | 0, 152 | "IMAGE" 153 | ], 154 | [ 155 | 2, 156 | 1, 157 | 0, 158 | 3, 159 | 0, 160 | "MASK" 161 | ], 162 | [ 163 | 3, 164 | 3, 165 | 0, 166 | 4, 167 | 0, 168 | "IMAGE" 169 | ] 170 | ], 171 | "groups": [], 172 | "config": {}, 173 | "extra": {}, 174 | "version": 0.4 175 | } --------------------------------------------------------------------------------