{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Segformer + Mix Transformer B2\nTrying to reproduce [hengck23's training log](https://www.kaggle.com/datasets/hengck23/hubmap-discuss-00).","metadata":{}},{"cell_type":"markdown","source":"# Setups","metadata":{}},{"cell_type":"code","source":"! pip install timm -q","metadata":{"execution":{"iopub.status.busy":"2022-09-18T13:42:38.784613Z","iopub.execute_input":"2022-09-18T13:42:38.785597Z","iopub.status.idle":"2022-09-18T13:42:50.474282Z","shell.execute_reply.started":"2022-09-18T13:42:38.785474Z","shell.execute_reply":"2022-09-18T13:42:50.473096Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import math\nfrom functools import partial\nfrom pathlib import Path \n\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nimport cv2\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import StratifiedKFold\nfrom timm.models.layers import DropPath, to_2tuple, trunc_normal_\nfrom timm.scheduler import CosineLRScheduler\nimport torch\nimport torch.cuda.amp as amp\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.optim import AdamW\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchmetrics import MeanMetric, Dice\nfrom tqdm import tqdm\n\n# plot\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-09-18T13:42:50.476606Z","iopub.execute_input":"2022-09-18T13:42:50.477331Z","iopub.status.idle":"2022-09-18T13:42:55.279891Z","shell.execute_reply.started":"2022-09-18T13:42:50.477288Z","shell.execute_reply":"2022-09-18T13:42:55.278789Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Config","metadata":{}},{"cell_type":"code","source":"DEBUG = False\nFOLD = 0\nN_FOLDS = 4\nIMG_SIZE = 768\nBATCH_SIZE = 6\nLR = 5e-5\nSEED = 43\n\nif DEBUG:\n    EPOCHS = 5\nelse:\n    EPOCHS = 100","metadata":{"execution":{"iopub.status.busy":"2022-09-18T13:42:55.281750Z","iopub.execute_input":"2022-09-18T13:42:55.282652Z","iopub.status.idle":"2022-09-18T13:42:55.290296Z","shell.execute_reply.started":"2022-09-18T13:42:55.282614Z","shell.execute_reply":"2022-09-18T13:42:55.288376Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Utils","metadata":{}},{"cell_type":"code","source":"def rle2mask(rle, size):\n    rle = np.array(list(map(int, rle.split())))\n    label = np.zeros((size*size), dtype=np.uint8)\n    for start, end in zip(rle[::2], rle[1::2]):\n        label[start:start+end] = 1\n    return label.reshape(size, size).T\n\ndef mask2rle(mask):\n    pixels = mask.T.flatten()   \n    pixels = np.concatenate([[0], pixels, [0]])\n    runs = np.where(pixels[1:] != pixels[:-1])[0]\n    runs[1::2] -= runs[::2]\n    return ' '.join(str(x) for x in runs)","metadata":{"execution":{"iopub.status.busy":"2022-09-18T13:42:55.292947Z","iopub.execute_input":"2022-09-18T13:42:55.293969Z","iopub.status.idle":"2022-09-18T13:42:55.304405Z","shell.execute_reply.started":"2022-09-18T13:42:55.293927Z","shell.execute_reply":"2022-09-18T13:42:55.303472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Dataset","metadata":{}},{"cell_type":"code","source":"class HubmapHpaDataset(Dataset):\n    def __init__(\n        self,\n        df: pd.DataFrame, \n        img_path: Path,\n        transform: callable = None, \n        return_class: bool = False\n    ):\n        self.df = df\n        self.img_path = img_path\n        self.transform = transform\n        self.return_class = return_class\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        \n        im = self.img_path / f\"{self.df['id'].iloc[idx]}.tiff\"\n        img = cv2.imread(str(im))\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        \n        mask = rle2mask(rle=self.df['rle'].iloc[idx], size=self.df['img_width'].iloc[idx])\n        mask = np.expand_dims(mask, axis=2)\n        \n        if self.transform:\n            result = self.transform(image=img, mask=mask)\n            img, mask = result['image'], result['mask']\n            \n        if self.return_class:\n            return img, mask, self.df['organ'].iloc[idx]\n        return img, mask\n\n\ndef get_transform(augment: bool=False):\n    ops = []\n    if augment:\n        # geometric\n        ops += [\n            A.HorizontalFlip(p=0.5),\n            A.RandomRotate90(p=1),\n            A.ShiftScaleRotate(\n                shift_limit=0.0625, \n                scale_limit=[-0.2, 1], \n                rotate_limit=45,\n                p=0.9\n            )\n        ]\n        # color\n        ops += [\n            A.OneOf([\n                A.HueSaturationValue(hue_shift_limit=10,\n                                    sat_shift_limit=15,\n                                    val_shift_limit=10,\n                                    p=0.2),\n                A.CLAHE(clip_limit=2, p=0.2),\n                A.RandomBrightnessContrast(p=0.2),\n                A.ColorJitter(\n                    brightness=0.1, \n                    contrast=0.2, \n                    saturation=0.2, \n                    hue=0.5,\n                    p=0.4)\n            ]),\n        ]\n        # other\n        ops += [\n            A.ImageCompression(quality_lower=50, quality_upper=100, p=0.5),\n        ]\n        \n    ops += [\n            A.Resize(IMG_SIZE, IMG_SIZE),\n            A.CenterCrop(IMG_SIZE, IMG_SIZE),\n            A.Normalize(\n                mean=[0.82784054, 0.80224235, 0.8201268],\n                std=[0.16691974, 0.19275635, 0.17306973],\n            ),\n            ToTensorV2(transpose_mask=True)\n        ]\n    return A.Compose(ops)","metadata":{"execution":{"iopub.status.busy":"2022-09-18T13:42:55.307005Z","iopub.execute_input":"2022-09-18T13:42:55.307751Z","iopub.status.idle":"2022-09-18T13:42:55.321295Z","shell.execute_reply.started":"2022-09-18T13:42:55.307711Z","shell.execute_reply":"2022-09-18T13:42:55.320370Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model","metadata":{}},{"cell_type":"markdown","source":"## Mix Transfomer","metadata":{}},{"cell_type":"code","source":"class DWConv(nn.Module):\n    def __init__(self, dim=768):\n        super(DWConv, self).__init__()\n        self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)\n    \n    def forward(self, x, H, W):\n        B, N, C = x.shape\n        x = x.transpose(1, 2).view(B, C, H, W)\n        x = self.dwconv(x)\n        x = x.flatten(2).transpose(1, 2)\n        \n        return x\n\n\nclass Mlp(nn.Module):\n    def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):\n        super().__init__()\n        out_features = out_features or in_features\n        hidden_features = hidden_features or in_features\n        self.fc1 = nn.Linear(in_features, hidden_features)\n        self.dwconv = DWConv(hidden_features)\n        self.act = act_layer()\n        self.fc2 = nn.Linear(hidden_features, out_features)\n        self.drop = nn.Dropout(drop)\n        \n        self.apply(self._init_weights)\n    \n    def _init_weights(self, m):\n        if isinstance(m, nn.Linear):\n            trunc_normal_(m.weight, std=.02)\n            if isinstance(m, nn.Linear) and m.bias is not None:\n                nn.init.constant_(m.bias, 0)\n        elif isinstance(m, nn.LayerNorm):\n            nn.init.constant_(m.bias, 0)\n            nn.init.constant_(m.weight, 1.0)\n        elif isinstance(m, nn.Conv2d):\n            fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n            fan_out //= m.groups\n            m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))\n            if m.bias is not None:\n                m.bias.data.zero_()\n    \n    def forward(self, x, H, W):\n        x = self.fc1(x)\n        x = self.dwconv(x, H, W)\n        x = self.act(x)\n        x = self.drop(x)\n        x = self.fc2(x)\n        x = self.drop(x)\n        return x\n\n\nclass Attention(nn.Module):\n    def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1):\n        super().__init__()\n        assert dim % num_heads == 0, f\"dim {dim} should be divided by num_heads {num_heads}.\"\n        \n        self.dim = dim\n        self.num_heads = num_heads\n        head_dim = dim // num_heads\n        self.scale = qk_scale or head_dim ** -0.5\n        \n        self.q = nn.Linear(dim, dim, bias=qkv_bias)\n        self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)\n        self.attn_drop = nn.Dropout(attn_drop)\n        self.proj = nn.Linear(dim, dim)\n        self.proj_drop = nn.Dropout(proj_drop)\n        \n        self.sr_ratio = sr_ratio\n        if sr_ratio > 1:\n            self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)\n            self.norm = nn.LayerNorm(dim)\n        \n        self.apply(self._init_weights)\n    \n    def _init_weights(self, m):\n        if isinstance(m, nn.Linear):\n            trunc_normal_(m.weight, std=.02)\n            if isinstance(m, nn.Linear) and m.bias is not None:\n                nn.init.constant_(m.bias, 0)\n        elif isinstance(m, nn.LayerNorm):\n            nn.init.constant_(m.bias, 0)\n            nn.init.constant_(m.weight, 1.0)\n        elif isinstance(m, nn.Conv2d):\n            fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n            fan_out //= m.groups\n            m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))\n            if m.bias is not None:\n                m.bias.data.zero_()\n    \n    def forward(self, x, H, W):\n        B, N, C = x.shape\n        q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)\n        \n        if self.sr_ratio > 1:\n            x_ = x.permute(0, 2, 1).reshape(B, C, H, W)\n            x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)\n            x_ = self.norm(x_)\n            kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)\n        else:\n            kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)\n        k, v = kv[0], kv[1]\n        \n        attn = (q @ k.transpose(-2, -1)) * self.scale\n        attn = attn.softmax(dim=-1)\n        attn = self.attn_drop(attn)\n        \n        x = (attn @ v).transpose(1, 2).reshape(B, N, C)\n        x = self.proj(x)\n        x = self.proj_drop(x)\n        \n        return x\n\n\nclass Block(nn.Module):\n    \n    def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,\n                 drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1):\n        super().__init__()\n        self.norm1 = norm_layer(dim)\n        self.attn = Attention(\n            dim,\n            num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,\n            attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio)\n        # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here\n        self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()\n        self.norm2 = norm_layer(dim)\n        mlp_hidden_dim = int(dim * mlp_ratio)\n        self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)\n        \n        self.apply(self._init_weights)\n    \n    def _init_weights(self, m):\n        if isinstance(m, nn.Linear):\n            trunc_normal_(m.weight, std=.02)\n            if isinstance(m, nn.Linear) and m.bias is not None:\n                nn.init.constant_(m.bias, 0)\n        elif isinstance(m, nn.LayerNorm):\n            nn.init.constant_(m.bias, 0)\n            nn.init.constant_(m.weight, 1.0)\n        elif isinstance(m, nn.Conv2d):\n            fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n            fan_out //= m.groups\n            m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))\n            if m.bias is not None:\n                m.bias.data.zero_()\n    \n    def forward(self, x, H, W):\n        x = x + self.drop_path(self.attn(self.norm1(x), H, W))\n        x = x + self.drop_path(self.mlp(self.norm2(x), H, W))\n        \n        return x\n\n\nclass OverlapPatchEmbed(nn.Module):\n    \"\"\" Image to Patch Embedding\n    \"\"\"\n    \n    def __init__(self, img_size=224, patch_size=7, stride=4, in_chans=3, embed_dim=768):\n        super().__init__()\n        img_size = to_2tuple(img_size)\n        patch_size = to_2tuple(patch_size)\n        \n        self.img_size = img_size\n        self.patch_size = patch_size\n        self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1]\n        self.num_patches = self.H * self.W\n        self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride,\n                              padding=(patch_size[0] // 2, patch_size[1] // 2))\n        self.norm = nn.LayerNorm(embed_dim)\n        \n        self.apply(self._init_weights)\n    \n    def _init_weights(self, m):\n        if isinstance(m, nn.Linear):\n            trunc_normal_(m.weight, std=.02)\n            if isinstance(m, nn.Linear) and m.bias is not None:\n                nn.init.constant_(m.bias, 0)\n        elif isinstance(m, nn.LayerNorm):\n            nn.init.constant_(m.bias, 0)\n            nn.init.constant_(m.weight, 1.0)\n        elif isinstance(m, nn.Conv2d):\n            fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n            fan_out //= m.groups\n            m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))\n            if m.bias is not None:\n                m.bias.data.zero_()\n    \n    def forward(self, x):\n        x = self.proj(x)\n        _, _, H, W = x.shape\n        x = x.flatten(2).transpose(1, 2)\n        x = self.norm(x)\n        \n        return x, H, W\n\n\nclass MixVisionTransformer(nn.Module):\n    def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dims=[64, 128, 256, 512],\n                 num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0.,\n                 attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm,\n                 depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]):\n        super().__init__()\n        self.num_classes = num_classes\n        self.depths = depths\n        self.embed_dims = embed_dims\n        \n        # patch_embed\n        self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_chans=in_chans,\n                                              embed_dim=embed_dims[0])\n        self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_chans=embed_dims[0],\n                                              embed_dim=embed_dims[1])\n        self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_chans=embed_dims[1],\n                                              embed_dim=embed_dims[2])\n        self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_chans=embed_dims[2],\n                                              embed_dim=embed_dims[3])\n        \n        # transformer encoder\n        dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]  # stochastic depth decay rule\n        cur = 0\n        self.block1 = nn.ModuleList([Block(\n            dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale,\n            drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,\n            sr_ratio=sr_ratios[0])\n            for i in range(depths[0])])\n        self.norm1 = norm_layer(embed_dims[0])\n        \n        cur += depths[0]\n        self.block2 = nn.ModuleList([Block(\n            dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale,\n            drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,\n            sr_ratio=sr_ratios[1])\n            for i in range(depths[1])])\n        self.norm2 = norm_layer(embed_dims[1])\n        \n        cur += depths[1]\n        self.block3 = nn.ModuleList([Block(\n            dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale,\n            drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,\n            sr_ratio=sr_ratios[2])\n            for i in range(depths[2])])\n        self.norm3 = norm_layer(embed_dims[2])\n        \n        cur += depths[2]\n        self.block4 = nn.ModuleList([Block(\n            dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale,\n            drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,\n            sr_ratio=sr_ratios[3])\n            for i in range(depths[3])])\n        self.norm4 = norm_layer(embed_dims[3])\n        \n        # classification head\n        # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity()\n        \n        self.apply(self._init_weights)\n    \n    def _init_weights(self, m):\n        if isinstance(m, nn.Linear):\n            trunc_normal_(m.weight, std=.02)\n            if isinstance(m, nn.Linear) and m.bias is not None:\n                nn.init.constant_(m.bias, 0)\n        elif isinstance(m, nn.LayerNorm):\n            nn.init.constant_(m.bias, 0)\n            nn.init.constant_(m.weight, 1.0)\n        elif isinstance(m, nn.Conv2d):\n            fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n            fan_out //= m.groups\n            m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))\n            if m.bias is not None:\n                m.bias.data.zero_()\n    \n    def init_weights(self, pretrained=None):\n        pass\n        # if isinstance(pretrained, str):\n        #     logger = get_root_logger()\n        #     load_checkpoint(self, pretrained, map_location='cpu', strict=False, logger=logger)\n    \n    def reset_drop_path(self, drop_path_rate):\n        dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))]\n        cur = 0\n        for i in range(self.depths[0]):\n            self.block1[i].drop_path.drop_prob = dpr[cur + i]\n        \n        cur += self.depths[0]\n        for i in range(self.depths[1]):\n            self.block2[i].drop_path.drop_prob = dpr[cur + i]\n        \n        cur += self.depths[1]\n        for i in range(self.depths[2]):\n            self.block3[i].drop_path.drop_prob = dpr[cur + i]\n        \n        cur += self.depths[2]\n        for i in range(self.depths[3]):\n            self.block4[i].drop_path.drop_prob = dpr[cur + i]\n    \n    def freeze_patch_emb(self):\n        self.patch_embed1.requires_grad = False\n    \n    @torch.jit.ignore\n    def no_weight_decay(self):\n        return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'}  # has pos_embed may be better\n    \n    def get_classifier(self):\n        return self.head\n    \n    def reset_classifier(self, num_classes, global_pool=''):\n        self.num_classes = num_classes\n        self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()\n    \n    def forward_features(self, x):\n        B = x.shape[0]\n        outs = []\n        \n        # stage 1\n        x, H, W = self.patch_embed1(x)\n        for i, blk in enumerate(self.block1):\n            x = blk(x, H, W)\n        x = self.norm1(x)\n        x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()\n        outs.append(x)\n        \n        # stage 2\n        x, H, W = self.patch_embed2(x)\n        for i, blk in enumerate(self.block2):\n            x = blk(x, H, W)\n        x = self.norm2(x)\n        x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()\n        outs.append(x)\n        \n        # stage 3\n        x, H, W = self.patch_embed3(x)\n        for i, blk in enumerate(self.block3):\n            x = blk(x, H, W)\n        x = self.norm3(x)\n        x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()\n        outs.append(x)\n        \n        # stage 4\n        x, H, W = self.patch_embed4(x)\n        for i, blk in enumerate(self.block4):\n            x = blk(x, H, W)\n        x = self.norm4(x)\n        x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()\n        outs.append(x)\n        \n        return outs\n    \n    def forward(self, x):\n        x = self.forward_features(x)\n        # x = self.head(x)\n        \n        return x\n\n\n\n\nclass mit_b0(MixVisionTransformer):\n    def __init__(self, **kwargs):\n        super(mit_b0, self).__init__(\n            patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],\n            qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],\n            drop_rate=0.0, drop_path_rate=0.1)\n\n\nclass mit_b1(MixVisionTransformer):\n    def __init__(self, **kwargs):\n        super(mit_b1, self).__init__(\n            patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],\n            qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],\n            drop_rate=0.0, drop_path_rate=0.1)\n\n\nclass mit_b2(MixVisionTransformer):\n    def __init__(self, **kwargs):\n        super(mit_b2, self).__init__(\n            patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],\n            qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1],\n            drop_rate=0.0, drop_path_rate=0.1)\n\n\nclass mit_b3(MixVisionTransformer):\n    def __init__(self, **kwargs):\n        super(mit_b3, self).__init__(\n            patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],\n            qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1],\n            drop_rate=0.0, drop_path_rate=0.1)\n\n\nclass mit_b4(MixVisionTransformer):\n    def __init__(self, **kwargs):\n        super(mit_b4, self).__init__(\n            patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],\n            qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1],\n            drop_rate=0.0, drop_path_rate=0.1)\n\nclass mit_b5(MixVisionTransformer):\n    def __init__(self, **kwargs):\n        super(mit_b5, self).__init__(\n            patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],\n            qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1],\n            drop_rate=0.0, drop_path_rate=0.1)","metadata":{"execution":{"iopub.status.busy":"2022-09-18T13:42:55.323004Z","iopub.execute_input":"2022-09-18T13:42:55.323378Z","iopub.status.idle":"2022-09-18T13:42:55.589505Z","shell.execute_reply.started":"2022-09-18T13:42:55.323343Z","shell.execute_reply":"2022-09-18T13:42:55.588238Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Segformer","metadata":{}},{"cell_type":"code","source":"class MixUpSample(nn.Module):\n    def __init__( self, scale_factor=2):\n        super().__init__()\n        self.mixing = nn.Parameter(torch.tensor(0.5))\n        self.scale_factor = scale_factor\n    \n    def forward(self, x):\n        x = self.mixing *F.interpolate(x, scale_factor=self.scale_factor, mode='bilinear', align_corners=False) \\\n            + (1-self.mixing )*F.interpolate(x, scale_factor=self.scale_factor, mode='nearest')\n        return x\n    \n    \nclass SegformerDecoder(nn.Module):\n    def __init__(\n            self,\n            encoder_dim = [32, 64, 160, 256],\n            decoder_dim = 256,\n    ):\n        super().__init__()\n        self.mixing = nn.Parameter(torch.FloatTensor([0.5,0.5,0.5,0.5]))\n        self.mlp = nn.ModuleList([\n            nn.Sequential(\n                nn.Conv2d(dim, decoder_dim, 1, padding= 0,  bias=False), #follow mmseg to use conv-bn-relu\n                nn.BatchNorm2d(decoder_dim),\n                nn.ReLU(inplace=True),\n                MixUpSample(2**i) if i!=0 else nn.Identity(),\n            ) for i, dim in enumerate(encoder_dim)])\n        \n        self.fuse = nn.Sequential(\n            nn.Conv2d(len(encoder_dim) * decoder_dim, decoder_dim, 1, padding=0, bias=False),\n            nn.BatchNorm2d(decoder_dim),\n            nn.ReLU(inplace=True),\n            # nn.Conv2d(decoder_dim, decoder_dim, 3, padding=1, bias=False),\n            # nn.BatchNorm2d(decoder_dim),\n            # nn.ReLU(inplace=True),\n        )\n    \n    def forward(self, feature):\n        \n        out = []\n        for i,f in enumerate(feature):\n            f = self.mlp[i](f)\n            out.append(f)\n         \n        x = self.fuse(torch.cat(out, dim = 1))\n        return x, out","metadata":{"execution":{"iopub.status.busy":"2022-09-18T13:42:55.593394Z","iopub.execute_input":"2022-09-18T13:42:55.593750Z","iopub.status.idle":"2022-09-18T13:42:55.608556Z","shell.execute_reply.started":"2022-09-18T13:42:55.593706Z","shell.execute_reply":"2022-09-18T13:42:55.607338Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Net","metadata":{}},{"cell_type":"code","source":"class Net(nn.Module):\n    def __init__(self, builder):\n        super(Net, self).__init__()\n        self.dropout = nn.Dropout(0.1)\n        \n        self.encoder = builder()\n        encoder_dim = self.encoder.embed_dims\n        #[64, 128, 320, 512]\n        \n        self.decoder = SegformerDecoder(\n            encoder_dim = encoder_dim,\n            decoder_dim = 320,\n        )\n        self.logit = nn.Sequential(\n            nn.Conv2d(320, 1, kernel_size=1, padding=0),\n        )\n        self.aux = nn.ModuleList([\n            nn.Conv2d(encoder_dim[i], 1, kernel_size=1, padding=0) for i in range(4)\n        ])\n    \n    \n    def forward(self, x, aux:bool=True):\n        encoder = self.encoder(x)\n        last, _ = self.decoder(encoder)\n        last  = self.dropout(last)\n        logit = self.logit(last)\n        logit = F.interpolate(logit, size=None, scale_factor=4, mode='bilinear', align_corners=False)\n        if aux:\n            outputs = [self.aux[i](encoder[i]) for i in range(4)]\n            return logit, outputs\n        else:\n            return logit","metadata":{"execution":{"iopub.status.busy":"2022-09-18T13:42:55.610566Z","iopub.execute_input":"2022-09-18T13:42:55.610963Z","iopub.status.idle":"2022-09-18T13:42:55.623632Z","shell.execute_reply.started":"2022-09-18T13:42:55.610924Z","shell.execute_reply":"2022-09-18T13:42:55.622558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Loss","metadata":{}},{"cell_type":"code","source":"def my_loss(logit, outputs, mask, lambda_aux:float=0.2):\n    loss = F.binary_cross_entropy_with_logits(logit, mask)\n    # NOTE: Only use aux 2 loss\n    loss += lambda_aux * criterion_aux_loss(outputs[2], mask)\n    return loss\n\ndef criterion_aux_loss(logit, mask):\n    mask = F.interpolate(mask,size=logit.shape[-2:], mode='nearest')\n    loss = F.binary_cross_entropy_with_logits(logit,mask)\n    return loss","metadata":{"execution":{"iopub.status.busy":"2022-09-18T13:42:55.625147Z","iopub.execute_input":"2022-09-18T13:42:55.625674Z","iopub.status.idle":"2022-09-18T13:42:55.637963Z","shell.execute_reply.started":"2022-09-18T13:42:55.625636Z","shell.execute_reply":"2022-09-18T13:42:55.636844Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Trainer","metadata":{}},{"cell_type":"code","source":"class Trainer:\n    def __init__(\n        self, \n        model,\n        train_loader, \n        valid_loader,\n        loss, \n        metric,\n        optimizer,\n        scheduler\n    ):\n        self.model = model\n        self.train_loader = train_loader\n        self.valid_loader = valid_loader\n        self.loss = loss\n        self.metric = metric\n        self.optimizer = optimizer\n        self.scaler = amp.GradScaler(enabled=True)\n        self.scheduler = scheduler\n        self.best_loss = 9999\n        self.best_metric = 0\n        self.history = {\n            'epochs': [],\n            'train_loss': [],\n            'train_metric': [],\n            'valid_loss': [],\n            'valid_metric': [],\n            'lr': []\n        }\n        \n    def fit(self, epochs):\n        self.model.cuda()\n        for epoch in range(epochs):\n            self.history['epochs'].append(epoch)\n            \n            # Train epoch\n            self.model.train()\n            mean_loss = MeanMetric().cuda()\n            mean_metric = MeanMetric().cuda()\n            for x, y in tqdm(self.train_loader, desc=f\"Train epoch {epoch}\"):\n                x, y = x.half().cuda(), y.half().cuda()\n                \n                self.optimizer.zero_grad()\n                with amp.autocast(enabled=True):\n                    logit, outputs = self.model(x)\n                    loss = self.loss(logit, outputs, y.float())\n                self.scaler.scale(loss).backward()\n                self.scaler.unscale_(self.optimizer)\n                self.scaler.step(self.optimizer)\n                self.scaler.update()\n\n                mean_loss.update(loss)\n                mean_metric.update(self.metric(logit, y.long()))\n                \n            self.history['train_loss'].append(mean_loss.compute().item())\n            self.history['train_metric'].append(mean_metric.compute().item())\n            self.history['lr'].append(self.scheduler.get_epoch_values(epoch))\n            self.scheduler.step(epoch+1)\n            \n            # Valid epoch\n            self.model.eval()\n            mean_loss = MeanMetric().cuda()\n            mean_metric = MeanMetric().cuda()\n            with torch.no_grad():\n                for x, y in tqdm(self.valid_loader, desc=f\"Valid epoch {epoch}\"):\n                    x, y = x.cuda(), y.cuda()\n                    logit, outputs = self.model(x)\n                    loss = self.loss(logit, outputs, y.float())\n\n                    mean_loss.update(loss)\n                    mean_metric.update(self.metric(logit, y.long()))\n            \n            self.history['valid_loss'].append(mean_loss.compute().item())\n            self.history['valid_metric'].append(mean_metric.compute().item())\n            \n            self.save_if_best()\n            self.plot_test()\n            torch.cuda.empty_cache()\n    \n    def save_if_best(self):\n        if self.best_loss > self.history['valid_loss'][-1]:\n            self.best_loss = self.history['valid_loss'][-1]\n            print(f\"save best loss model: {self.best_loss:.4f}\")\n            torch.save(self.model, f'model_best_loss_{FOLD}.pth')\n        else:\n            print(f\"loss: {self.history['valid_loss'][-1]:.4f}\")\n\n        if self.best_metric < self.history['valid_metric'][-1]:\n            self.best_metric = self.history['valid_metric'][-1]\n            print(f\"save best metric model: {self.best_metric:.4f}\")\n            torch.save(self.model, f'model_best_metric_{FOLD}.pth')\n        else:\n            print(f\"metric: {self.history['valid_metric'][-1]:.4f}\")\n            \n    def plot_test(self):\n        transform = get_transform(augment=False)\n        img = cv2.imread(\"../input/hubmap-organ-segmentation/test_images/10078.tiff\")\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        X = transform(image=img)['image']\n        X = X.cuda()\n        with torch.no_grad():\n            Y = self.model(X.unsqueeze(0), aux=False).squeeze(0).sigmoid()\n        img = X.cpu().numpy().transpose(1,2,0)\n        pred = Y.cpu().numpy()[0]\n        pred_255 = (pred*255).astype(np.uint8)\n        thres = cv2.threshold(pred_255, 0, 255, cv2.THRESH_OTSU)[0] / 255\n        mask_pred = (pred > thres).astype(np.int8)\n        fig, axes = plt.subplots(1, 3, figsize=(9,3))\n        axes[0].imshow(img)\n        axes[0].set_title(\"Input\")\n        axes[1].imshow(pred)\n        axes[1].set_title(\"Pred\")\n        axes[2].imshow(mask_pred)\n        axes[2].set_title(\"Mask\")\n        plt.show()\n        \n    def plot_history(self):\n        fig, axes = plt.subplots(1, 3, figsize=(20, 6))\n        \n        axes[0].set_title('Loss')\n        axes[0].plot(self.history['epochs'], self.history['train_loss'], 'r', label='train')\n        axes[0].plot(self.history['epochs'], self.history['valid_loss'], 'g', label='valid')\n        axes[0].legend()\n        axes[0].grid()\n        \n        axes[1].set_title('Metric')\n        axes[1].plot(self.history['epochs'], self.history['train_metric'], 'r', label='train')\n        axes[1].plot(self.history['epochs'], self.history['valid_metric'], 'g', label='valid')\n        axes[1].legend()\n        axes[1].grid()\n        \n        # losses\n        axes[2].set_title('Learning Rate')\n        axes[2].plot(self.history['epochs'], self.history['lr'], 'b')\n        axes[2].grid()\n\n        plt.plot()\n        plt.show()\n            ","metadata":{"execution":{"iopub.status.busy":"2022-09-18T13:42:55.642641Z","iopub.execute_input":"2022-09-18T13:42:55.643075Z","iopub.status.idle":"2022-09-18T13:42:55.673593Z","shell.execute_reply.started":"2022-09-18T13:42:55.642997Z","shell.execute_reply":"2022-09-18T13:42:55.672325Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Run","metadata":{}},{"cell_type":"code","source":"data_path = Path('/kaggle/input/hubmap-organ-segmentation')\n\nall_df = pd.read_csv(data_path / 'train.csv')\nFOLDS = StratifiedKFold(n_splits=N_FOLDS, shuffle=True, random_state=SEED)\nfor fold, (train_idxs, val_idxs) in enumerate(FOLDS.split(X=all_df, y=all_df[\"organ\"])):\n    if fold != FOLD:\n        continue\n    train_df, valid_df = all_df.iloc[train_idxs].reset_index(drop=True), all_df.iloc[val_idxs].reset_index(drop=True)\ndel all_df\nprint(len(train_df), len(valid_df))\n\nimg_path = data_path / 'train_images'\n\ntrain_dataset = HubmapHpaDataset(\n    df = train_df,\n    img_path = img_path,\n    transform = get_transform(augment=True)\n)\nvalid_dataset = HubmapHpaDataset(\n    df = valid_df,\n    img_path = img_path,\n    transform = get_transform(augment=False)\n)\n\ntrain_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True, num_workers=2)\nvalid_loader = DataLoader(valid_dataset, batch_size=1, shuffle=False, num_workers=2)","metadata":{"execution":{"iopub.status.busy":"2022-09-18T13:42:55.676049Z","iopub.execute_input":"2022-09-18T13:42:55.676385Z","iopub.status.idle":"2022-09-18T13:42:56.079957Z","shell.execute_reply.started":"2022-09-18T13:42:55.676356Z","shell.execute_reply":"2022-09-18T13:42:56.078971Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Net(builder=mit_b2)\noptimizer = AdamW(model.parameters(), lr=LR)\nscheduler = CosineLRScheduler(optimizer, t_initial=EPOCHS, lr_min=1e-6, \n                              warmup_t=EPOCHS//5, warmup_lr_init=LR/10, warmup_prefix=True)\nmetric = Dice(\n    average='samples',\n    ignore_index=0,\n).cuda()","metadata":{"execution":{"iopub.status.busy":"2022-09-18T13:42:56.081470Z","iopub.execute_input":"2022-09-18T13:42:56.081826Z","iopub.status.idle":"2022-09-18T13:42:59.953709Z","shell.execute_reply.started":"2022-09-18T13:42:56.081790Z","shell.execute_reply":"2022-09-18T13:42:59.952702Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"trainer = Trainer(\n    model=model,\n    train_loader=train_loader, \n    valid_loader=valid_loader,\n    loss=my_loss, \n    metric=metric,\n    optimizer=optimizer,\n    scheduler=scheduler\n)","metadata":{"execution":{"iopub.status.busy":"2022-09-18T13:42:59.955277Z","iopub.execute_input":"2022-09-18T13:42:59.955642Z","iopub.status.idle":"2022-09-18T13:42:59.961125Z","shell.execute_reply.started":"2022-09-18T13:42:59.955605Z","shell.execute_reply":"2022-09-18T13:42:59.959707Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"trainer.fit(EPOCHS)","metadata":{"execution":{"iopub.status.busy":"2022-09-18T13:42:59.962636Z","iopub.execute_input":"2022-09-18T13:42:59.963284Z","iopub.status.idle":"2022-09-18T13:58:13.766104Z","shell.execute_reply.started":"2022-09-18T13:42:59.963248Z","shell.execute_reply":"2022-09-18T13:58:13.764998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"trainer.plot_history()","metadata":{"execution":{"iopub.status.busy":"2022-09-18T13:58:13.769105Z","iopub.execute_input":"2022-09-18T13:58:13.769881Z","iopub.status.idle":"2022-09-18T13:58:14.232373Z","shell.execute_reply.started":"2022-09-18T13:58:13.769838Z","shell.execute_reply":"2022-09-18T13:58:14.231482Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(f\"Best loss: {trainer.best_loss:.4f}\")\nprint(f\"Best dice: {trainer.best_metric:.4f}\")","metadata":{"execution":{"iopub.status.busy":"2022-09-18T13:58:14.235337Z","iopub.execute_input":"2022-09-18T13:58:14.235617Z","iopub.status.idle":"2022-09-18T13:58:14.243033Z","shell.execute_reply.started":"2022-09-18T13:58:14.235590Z","shell.execute_reply":"2022-09-18T13:58:14.241974Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Predict Test","metadata":{}},{"cell_type":"code","source":"del trainer\ntransform = get_transform(augment=False)\nimg = cv2.imread(\"../input/hubmap-organ-segmentation/test_images/10078.tiff\")\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\nX = transform(image=img)['image']\nX = X.cuda()","metadata":{"execution":{"iopub.status.busy":"2022-09-18T13:58:14.244480Z","iopub.execute_input":"2022-09-18T13:58:14.245041Z","iopub.status.idle":"2022-09-18T13:58:14.293382Z","shell.execute_reply.started":"2022-09-18T13:58:14.245001Z","shell.execute_reply":"2022-09-18T13:58:14.292337Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = torch.load(f'model_best_loss_{FOLD}.pth', map_location=\"cpu\")\nmodel.cuda()\nmodel.eval()\nwith torch.no_grad():\n    Y = model(X.unsqueeze(0), aux=False).squeeze(0).sigmoid()\nimg = X.cpu().numpy().transpose(1,2,0)\npred_best_loss = Y.cpu().numpy()[0]\npred_255 = (pred_best_loss*255).astype(np.uint8)\nthres = cv2.threshold(pred_255, 0, 255, cv2.THRESH_OTSU)[0] / 255\nmask_pred_best_loss = (pred_best_loss > thres).astype(np.int8)\ndel model\n\nmodel = torch.load(f'model_best_metric_{FOLD}.pth', map_location=\"cpu\")\nmodel.cuda()\nmodel.eval()\nwith torch.no_grad():\n    Y = model(X.unsqueeze(0), aux=False).squeeze(0).sigmoid()\npred_best_dice = Y.cpu().numpy()[0]\npred_255 = (pred_best_dice*255).astype(np.uint8)\nthres = cv2.threshold(pred_255, 0, 255, cv2.THRESH_OTSU)[0] / 255\nmask_pred_best_dice = (pred_best_dice > thres).astype(np.int8)\ndel model","metadata":{"execution":{"iopub.status.busy":"2022-09-18T13:58:14.294864Z","iopub.execute_input":"2022-09-18T13:58:14.295468Z","iopub.status.idle":"2022-09-18T13:58:15.130539Z","shell.execute_reply.started":"2022-09-18T13:58:14.295430Z","shell.execute_reply":"2022-09-18T13:58:15.129579Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, axes = plt.subplots(2, 3, figsize=(12,8))\naxes[0, 0].imshow(img)\naxes[0, 0].set_title(\"Input\")\naxes[0, 1].imshow(pred_best_loss)\naxes[0, 1].set_title(\"Pred by Best Loss\")\naxes[0, 2].imshow(mask_pred_best_loss)\naxes[0, 2].set_title(\"Mask by Best Loss\")\naxes[1, 0].imshow(img)\naxes[1, 0].set_title(\"Input\")\naxes[1, 1].imshow(pred_best_dice)\naxes[1, 1].set_title(\"Pred by Best Dice\")\naxes[1, 2].imshow(mask_pred_best_dice)\naxes[1, 2].set_title(\"Mask by Best Dice\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-09-18T13:58:15.132173Z","iopub.execute_input":"2022-09-18T13:58:15.132537Z","iopub.status.idle":"2022-09-18T13:58:16.198471Z","shell.execute_reply.started":"2022-09-18T13:58:15.132501Z","shell.execute_reply":"2022-09-18T13:58:16.197622Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}