{"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":71549,"databundleVersionId":8561470,"sourceType":"competition"},{"sourceId":183439689,"sourceType":"kernelVersion"}],"dockerImageVersionId":30733,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# 2 Model Approach with one model specilizing in Sagittal input while the other specializes in ROI Axial input","metadata":{}},{"cell_type":"code","source":"!unzip -q /kaggle/input/rsna2024-lsdc-making-dataset/_output_.zip ","metadata":{"execution":{"iopub.status.busy":"2024-09-26T00:19:59.961239Z","iopub.execute_input":"2024-09-26T00:19:59.961535Z","iopub.status.idle":"2024-09-26T00:25:10.063058Z","shell.execute_reply.started":"2024-09-26T00:19:59.961510Z","shell.execute_reply":"2024-09-26T00:25:10.061470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport gc\nimport sys\nfrom PIL import Image\nimport cv2\nimport math, random\nimport numpy as np\nimport pandas as pd\nfrom glob import glob\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import KFold\n\nfrom collections import OrderedDict\n\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\nfrom torch.utils.data import DataLoader, Dataset\nfrom torch.optim import AdamW\n\nimport timm\nfrom transformers import get_cosine_schedule_with_warmup\n\nimport albumentations as A\n\nfrom sklearn.model_selection import KFold","metadata":{"execution":{"iopub.status.busy":"2024-09-26T00:25:10.066076Z","iopub.execute_input":"2024-09-26T00:25:10.066705Z","iopub.status.idle":"2024-09-26T00:25:21.690848Z","shell.execute_reply.started":"2024-09-26T00:25:10.066671Z","shell.execute_reply":"2024-09-26T00:25:21.689820Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rd = '/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification'","metadata":{"execution":{"iopub.status.busy":"2024-09-26T00:25:21.696185Z","iopub.execute_input":"2024-09-26T00:25:21.696483Z","iopub.status.idle":"2024-09-26T00:25:21.700760Z","shell.execute_reply.started":"2024-09-26T00:25:21.696452Z","shell.execute_reply":"2024-09-26T00:25:21.699900Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Config","metadata":{}},{"cell_type":"code","source":"NOT_DEBUG = True # True -> run naormally, False -> debug mode, with lesser computing cost\n\nOUTPUT_DIR = f'rsna24-results'\ndevice = 'cuda:0' if torch.cuda.is_available() else 'cpu'\nN_WORKERS = os.cpu_count() \nUSE_AMP = True # can change True if using T4 or newer than Ampere\nSEED = 8620\n\nIMG_SIZE = [512, 512]\nIN_CHANS = 30\nN_LABELS = 25\nN_CLASSES = 3 * N_LABELS\n\nAUG_PROB = 0.75\n\nN_FOLDS = 5 if NOT_DEBUG else 2\nEPOCHS = 20 if NOT_DEBUG else 2\nMODEL_NAME = \"tf_efficientnet_b3.ns_jft_in1k\" if NOT_DEBUG else \"tf_efficientnet_b0.ns_jft_in1k\"\n\nGRAD_ACC = 2\nTGT_BATCH_SIZE = 32\nBATCH_SIZE = TGT_BATCH_SIZE // GRAD_ACC\nMAX_GRAD_NORM = None\nEARLY_STOPPING_EPOCH = 3\n\nLR = 2e-4 * TGT_BATCH_SIZE / 32\nWD = 1e-2\nAUG = True","metadata":{"execution":{"iopub.status.busy":"2024-09-26T00:25:21.701942Z","iopub.execute_input":"2024-09-26T00:25:21.702422Z","iopub.status.idle":"2024-09-26T00:25:21.794223Z","shell.execute_reply.started":"2024-09-26T00:25:21.702385Z","shell.execute_reply":"2024-09-26T00:25:21.793258Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.makedirs(OUTPUT_DIR, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2024-09-26T00:25:21.795606Z","iopub.execute_input":"2024-09-26T00:25:21.795920Z","iopub.status.idle":"2024-09-26T00:25:21.805136Z","shell.execute_reply.started":"2024-09-26T00:25:21.795895Z","shell.execute_reply":"2024-09-26T00:25:21.804466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def set_random_seed(seed: int = 8620, deterministic: bool = False):\n    \"\"\"Set seeds\"\"\"\n    random.seed(seed)\n    np.random.seed(seed)\n    os.environ[\"PYTHONHASHSEED\"] = str(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)  # type: ignore\n    torch.backends.cudnn.benchmark = True\n    torch.backends.cudnn.deterministic = deterministic  # type: ignore\n\nset_random_seed(SEED)","metadata":{"execution":{"iopub.status.busy":"2024-09-26T00:25:21.806425Z","iopub.execute_input":"2024-09-26T00:25:21.806765Z","iopub.status.idle":"2024-09-26T00:25:21.821817Z","shell.execute_reply.started":"2024-09-26T00:25:21.806734Z","shell.execute_reply":"2024-09-26T00:25:21.821000Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Open Dataframes","metadata":{}},{"cell_type":"code","source":"df = pd.read_csv(f'{rd}/train.csv')\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2024-09-26T00:25:21.822886Z","iopub.execute_input":"2024-09-26T00:25:21.823138Z","iopub.status.idle":"2024-09-26T00:25:21.925188Z","shell.execute_reply.started":"2024-09-26T00:25:21.823104Z","shell.execute_reply":"2024-09-26T00:25:21.924198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Change the state to Label.\n\nThe dataframe contains some Nans, which we will replace with -100 so that We and function can ignore them when calculating the loss and score.","metadata":{}},{"cell_type":"code","source":"df = df.fillna(-100)","metadata":{"execution":{"iopub.status.busy":"2024-09-26T00:25:21.926416Z","iopub.execute_input":"2024-09-26T00:25:21.926726Z","iopub.status.idle":"2024-09-26T00:25:21.941473Z","shell.execute_reply.started":"2024-09-26T00:25:21.926700Z","shell.execute_reply":"2024-09-26T00:25:21.940575Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label2id = {'Normal/Mild': 0, 'Moderate':1, 'Severe':2}\ndf = df.replace(label2id)\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2024-09-26T00:25:21.945522Z","iopub.execute_input":"2024-09-26T00:25:21.945990Z","iopub.status.idle":"2024-09-26T00:25:22.015147Z","shell.execute_reply.started":"2024-09-26T00:25:21.945961Z","shell.execute_reply":"2024-09-26T00:25:22.014102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CONDITIONS = [\n    'Spinal Canal Stenosis', \n    'Left Neural Foraminal Narrowing', \n    'Right Neural Foraminal Narrowing',\n    'Left Subarticular Stenosis',\n    'Right Subarticular Stenosis'\n]\n\nLEVELS = [\n    'L1/L2',\n    'L2/L3',\n    'L3/L4',\n    'L4/L5',\n    'L5/S1',\n]","metadata":{"execution":{"iopub.status.busy":"2024-09-26T00:25:22.016483Z","iopub.execute_input":"2024-09-26T00:25:22.016863Z","iopub.status.idle":"2024-09-26T00:25:22.022640Z","shell.execute_reply.started":"2024-09-26T00:25:22.016829Z","shell.execute_reply":"2024-09-26T00:25:22.021585Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Define Dataset\n\nThis implementation is very slow and leaves a lot of room for improvement.","metadata":{}},{"cell_type":"code","source":"class RSNA24Dataset(Dataset):\n    def __init__(self, df, phase='train', transform=None):\n        self.df = df\n        self.transform = transform\n        self.phase = phase\n    \n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        x = np.zeros((512, 512, 20), dtype=np.uint8)\n        axial_x = np.zeros((512, 512, 10), dtype=np.uint8)\n        t = self.df.iloc[idx]\n        st_id = int(t['study_id'])\n        label = t[1:].values.astype(np.int64)\n        \n        # Sagittal T1\n        for i in range(0, 10, 1):\n            try:\n                p = f'./cvt_png/{st_id}/Sagittal T1/{i:03d}.png'\n                img = Image.open(p).convert('L')\n                img = np.array(img)\n                x[..., i] = img.astype(np.uint8)\n            except:\n                #print(f'failed to load on {st_id}, Sagittal T1')\n                pass\n            \n        # Sagittal T2/STIR\n        for i in range(0, 10, 1):\n            try:\n                p = f'./cvt_png/{st_id}/Sagittal T2_STIR/{i:03d}.png'\n                img = Image.open(p).convert('L')\n                img = np.array(img)\n                x[..., i+10] = img.astype(np.uint8)\n            except:\n                #print(f'failed to load on {st_id}, Sagittal T2/STIR')\n                pass\n            \n        # Axial T2\n        axt2 = glob(f'./cvt_png/{st_id}/Axial T2/*.png')\n        axt2 = sorted(axt2)\n    \n        step = len(axt2) / 10.0\n        st = len(axt2)/2.0 - 4.0*step\n        end = len(axt2)+0.0001\n                \n        for i, j in enumerate(np.arange(st, end, step)):\n            try:\n                p = axt2[max(0, int((j-0.5001).round()))]\n                img = Image.open(p).convert('L')\n                img = np.array(img)\n                axial_x[..., i] = img.astype(np.uint8)\n            except:\n                #print(f'failed to load on {st_id}, Sagittal T2/STIR')\n                pass  \n            \n        assert np.sum(x)>0\n        axial_crop = A.Compose([\n                    A.CenterCrop(190, 190),\n                    A.RandomBrightnessContrast(brightness_limit=(-0.2, 0.2), contrast_limit=(-0.2, 0.2), p=AUG_PROB),\n                    A.OneOf([\n                        A.MotionBlur(blur_limit=5),\n                        A.MedianBlur(blur_limit=5),\n                        A.GaussianBlur(blur_limit=5),\n                        A.GaussNoise(var_limit=(5.0, 30.0)),\n                    ], p=AUG_PROB),\n\n                    A.OneOf([\n                        A.OpticalDistortion(distort_limit=1.0),\n                        A.GridDistortion(num_steps=5, distort_limit=1.),\n                        A.ElasticTransform(alpha=3),\n                    ], p=AUG_PROB),\n\n                    A.ShiftScaleRotate(shift_limit=0.1, scale_limit=0.1, rotate_limit=15, border_mode=0, p=AUG_PROB),\n                    A.CoarseDropout(max_holes=16, max_height=64, max_width=64, min_holes=1, min_height=8, min_width=8, p=AUG_PROB),\n                    A.Normalize(mean=0.5, std=0.5)\n                ])\n        \n        if self.transform is not None:\n            x = self.transform(image=x)['image']\n            axial_x = axial_crop(image=axial_x)['image']\n            #axial_x = self.transform(image=axial_x)['image']\n        \n        x = x.transpose(2, 0, 1)\n        axial_x = axial_x.transpose(2, 0, 1)\n                \n        return x, axial_x, label","metadata":{"execution":{"iopub.status.busy":"2024-09-26T01:07:46.151188Z","iopub.execute_input":"2024-09-26T01:07:46.151805Z","iopub.status.idle":"2024-09-26T01:07:46.170308Z","shell.execute_reply.started":"2024-09-26T01:07:46.151772Z","shell.execute_reply":"2024-09-26T01:07:46.169481Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Define Data Augmentaion\nData augmentation is important because the number of images used for training is extremely small.\nSee [this notebook](https://www.kaggle.com/code/haqishen/1st-place-soluiton-code-small-ver) by [Qishen Ha](https://www.kaggle.com/haqishen) for help setting up this augmentation.","metadata":{}},{"cell_type":"code","source":"transforms_train = A.Compose([\n    A.RandomBrightnessContrast(brightness_limit=(-0.2, 0.2), contrast_limit=(-0.2, 0.2), p=AUG_PROB),\n    A.OneOf([\n        A.MotionBlur(blur_limit=5),\n        A.MedianBlur(blur_limit=5),\n        A.GaussianBlur(blur_limit=5),\n        A.GaussNoise(var_limit=(5.0, 30.0)),\n    ], p=AUG_PROB),\n\n    A.OneOf([\n        A.OpticalDistortion(distort_limit=1.0),\n        A.GridDistortion(num_steps=5, distort_limit=1.),\n        A.ElasticTransform(alpha=3),\n    ], p=AUG_PROB),\n\n    A.ShiftScaleRotate(shift_limit=0.1, scale_limit=0.1, rotate_limit=15, border_mode=0, p=AUG_PROB),\n    A.Resize(IMG_SIZE[0], IMG_SIZE[1]),\n    A.CoarseDropout(max_holes=16, max_height=64, max_width=64, min_holes=1, min_height=8, min_width=8, p=AUG_PROB),    \n    A.Normalize(mean=0.5, std=0.5)\n])\n\ntransforms_val = A.Compose([\n    A.Resize(IMG_SIZE[0], IMG_SIZE[1]),\n    A.Normalize(mean=0.5, std=0.5)\n])\n","metadata":{"execution":{"iopub.status.busy":"2024-09-26T01:07:49.430620Z","iopub.execute_input":"2024-09-26T01:07:49.430977Z","iopub.status.idle":"2024-09-26T01:07:49.440636Z","shell.execute_reply.started":"2024-09-26T01:07:49.430947Z","shell.execute_reply":"2024-09-26T01:07:49.439769Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Trying Data Loader\nChecking if the data loader works properly.","metadata":{}},{"cell_type":"code","source":"tmp_ds = RSNA24Dataset(df, phase='train', transform=transforms_train)\ntmp_dl = DataLoader(\n            tmp_ds,\n            batch_size=1,\n            shuffle=False,\n            pin_memory=True,\n            drop_last=False,\n            num_workers=0\n            )\n\nfor i, (a_x, x, t) in enumerate(tmp_dl):\n    if i==5:break\n    print(type(a_x))\n    print('x stat:', x.shape, x.min(), x.max(),x.mean(), x.std())\n    print(t, t.shape)\n    y = x.numpy().transpose(0,2,3,1)[0,...,:3]\n    y = (y + 1) / 2\n    plt.imshow(y)\n    plt.show()\n    print('y stat:', y.shape, y.min(), y.max(),y.mean(), y.std())\n    print()\nplt.close()\ndel tmp_ds, tmp_dl","metadata":{"execution":{"iopub.status.busy":"2024-09-26T01:07:52.286509Z","iopub.execute_input":"2024-09-26T01:07:52.286904Z","iopub.status.idle":"2024-09-26T01:07:55.956196Z","shell.execute_reply.started":"2024-09-26T01:07:52.286871Z","shell.execute_reply":"2024-09-26T01:07:55.955359Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Define Model\nWe use timm, which is commonly used for image classification.","metadata":{}},{"cell_type":"code","source":"import timm\nimport torch.nn as nn\n\nSagittal_channels = 20\nAxial_channels = 10\n\nclass SagittalNet(nn.Module):\n    def __init__(self, num_classes, in_channels=Sagittal_channels):\n        super().__init__()\n        self.encoder = timm.create_model('seresnet50', in_chans=in_channels, num_classes=75, pretrained=True)\n    def forward(self, x):\n        b_size = x.size(0)\n        out = self.encoder(x)\n        #out = out.reshape(b_size, 25, 3)\n        #out = F.softmax(out, -1)\n        return out\n    \nclass AxialNet(nn.Module):\n    def __init__(self, num_classes, in_channels=Axial_channels):\n        super().__init__()\n        self.encoder = timm.create_model('seresnet50', in_chans=in_channels, num_classes=75, pretrained=True)\n    def forward(self, x):\n        b_size = x.size(0)\n        out = self.encoder(x)\n        #out = out.reshape(b_size, 25, 3)\n        #out = F.softmax(out, -1)\n        return out\n    \nclass LumbarNet(nn.Module):\n    def __init__(self, num_classes=75):\n        super().__init__()\n        self.axial = AxialNet(num_classes)\n        self.sagittal = SagittalNet(num_classes)\n    def forward(self, x, ax):\n        out = (self.axial(ax) + self.sagittal(x)) / 2.0\n        return out","metadata":{"execution":{"iopub.status.busy":"2024-09-26T01:07:59.766698Z","iopub.execute_input":"2024-09-26T01:07:59.767077Z","iopub.status.idle":"2024-09-26T01:07:59.777857Z","shell.execute_reply.started":"2024-09-26T01:07:59.767042Z","shell.execute_reply":"2024-09-26T01:07:59.776919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#net = LumbarNet()\n#test = torch.rand(2, 10, 512, 512)\n#test1 = torch.rand(2, 20, 512, 512)\n#net(test1, test).shape","metadata":{"execution":{"iopub.status.busy":"2024-09-25T19:54:26.896835Z","iopub.execute_input":"2024-09-25T19:54:26.897186Z","iopub.status.idle":"2024-09-25T19:54:39.094089Z","shell.execute_reply.started":"2024-09-25T19:54:26.897159Z","shell.execute_reply":"2024-09-25T19:54:39.093198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Testing Model\nChecking if the model works properly.","metadata":{}},{"cell_type":"markdown","source":"# Train loop","metadata":{}},{"cell_type":"code","source":"#autocast = torch.cuda.amp.autocast(enabled=USE_AMP, dtype=torch.bfloat16) # if your gpu is newer Ampere, you can use this, lesser appearance of nan than half\nautocast = torch.cuda.amp.autocast(enabled=USE_AMP, dtype=torch.half) # you can use with T4 gpu. or newer\nscaler = torch.cuda.amp.GradScaler(enabled=USE_AMP, init_scale=4096)\n\nskf = KFold(n_splits=N_FOLDS, shuffle=True, random_state=SEED)\nfor fold, (trn_idx, val_idx) in enumerate(skf.split(range(len(df)))):\n    print('#'*30)\n    print(f'start fold{fold}')\n    print('#'*30)\n    print(len(trn_idx), len(val_idx))\n    df_train = df.iloc[trn_idx]\n    df_valid = df.iloc[val_idx]\n\n    train_ds = RSNA24Dataset(df_train, phase='train', transform=transforms_train)\n    train_dl = DataLoader(\n                train_ds,\n                batch_size=BATCH_SIZE,\n                shuffle=True,\n                pin_memory=True,\n                drop_last=True,\n                num_workers=N_WORKERS\n                )\n\n    valid_ds = RSNA24Dataset(df_valid, phase='valid', transform=transforms_val)\n    valid_dl = DataLoader(\n                valid_ds,\n                batch_size=BATCH_SIZE*2,\n                shuffle=False,\n                pin_memory=True,\n                drop_last=False,\n                num_workers=N_WORKERS\n                )\n\n    model = LumbarNet()\n    model.to(device)\n    \n    optimizer = AdamW(model.parameters(), lr=LR, weight_decay=WD)\n\n    warmup_steps = EPOCHS/10 * len(train_dl) // GRAD_ACC\n    num_total_steps = EPOCHS * len(train_dl) // GRAD_ACC\n    num_cycles = 0.475\n    scheduler = get_cosine_schedule_with_warmup(optimizer,\n                                                num_warmup_steps=warmup_steps,\n                                                num_training_steps=num_total_steps,\n                                                num_cycles=num_cycles)\n\n    weights = torch.tensor([1.0, 2.0, 4.0])\n    criterion = nn.CrossEntropyLoss(weight=weights.to(device))\n    criterion2 = nn.CrossEntropyLoss(weight=weights)\n\n    best_loss = 1.2\n    best_wll = 1.2\n    es_step = 0\n\n    for epoch in range(1, EPOCHS+1):\n        print(f'start epoch {epoch}')\n        model.train()\n        total_loss = 0\n        with tqdm(train_dl, leave=True) as pbar:\n            optimizer.zero_grad()\n            for idx, (x, ax, t) in enumerate(pbar):  \n                x = x.to(device)\n                ax = ax.to(device)\n                t = t.to(device)\n                \n                with autocast:\n                    loss = 0\n                    y = model(x, ax)\n                    for col in range(N_LABELS):\n                        pred = y[:,col*3:col*3+3]\n                        gt = t[:,col]\n                        loss = loss + criterion(pred, gt) / N_LABELS\n                        \n                    total_loss += loss.item()\n                    if GRAD_ACC > 1:\n                        loss = loss / GRAD_ACC\n    \n                if not math.isfinite(loss):\n                    print(f\"Loss is {loss}, stopping training\")\n                    sys.exit(1)\n    \n                pbar.set_postfix(\n                    OrderedDict(\n                        loss=f'{loss.item()*GRAD_ACC:.6f}',\n                        lr=f'{optimizer.param_groups[0][\"lr\"]:.3e}'\n                    )\n                )\n                scaler.scale(loss).backward()\n\n                torch.nn.utils.clip_grad_norm_(model.parameters(), MAX_GRAD_NORM or 1e9)\n                \n                if (idx + 1) % GRAD_ACC == 0:\n                    scaler.step(optimizer)\n                    scaler.update()\n                    optimizer.zero_grad()\n                    if scheduler is not None:\n                        scheduler.step()                    \n    \n        train_loss = total_loss/len(train_dl)\n        print(f'train_loss:{train_loss:.6f}')\n\n        total_loss = 0\n        y_preds = []\n        labels = []\n        \n        model.eval()\n        with tqdm(valid_dl, leave=True) as pbar:\n            with torch.no_grad():\n                for idx, (x, ax, t) in enumerate(pbar):\n                    \n                    x = x.to(device)\n                    ax = ax.to(device)\n                    t = t.to(device)\n                        \n                    with autocast:\n                        loss = 0\n                        loss_ema = 0\n                        y = model(x, ax)\n                        for col in range(N_LABELS):\n                            pred = y[:,col*3:col*3+3]\n                            gt = t[:,col]\n \n                            loss = loss + criterion(pred, gt) / N_LABELS\n                            y_pred = pred.float()\n                            y_preds.append(y_pred.cpu())\n                            labels.append(gt.cpu())\n                        \n                        total_loss += loss.item()   \n    \n        val_loss = total_loss/len(valid_dl)\n        \n        y_preds = torch.cat(y_preds, dim=0)\n        labels = torch.cat(labels)\n        val_wll = criterion2(y_preds, labels)\n        \n        print(f'val_loss:{val_loss:.6f}, val_wll:{val_wll:.6f}')\n\n        if val_loss < best_loss or val_wll < best_wll:\n            \n            es_step = 0\n\n            if device!='cuda:0':\n                model.to('cuda:0')                \n                \n            if val_loss < best_loss:\n                print(f'epoch:{epoch}, best loss updated from {best_loss:.6f} to {val_loss:.6f}')\n                best_loss = val_loss\n                \n            if val_wll < best_wll:\n                print(f'epoch:{epoch}, best wll_metric updated from {best_wll:.6f} to {val_wll:.6f}')\n                best_wll = val_wll\n                fname = f'{OUTPUT_DIR}/best_wll_model_fold-{fold}.pt'\n                torch.save(model.state_dict(), fname)\n            \n            if device!='cuda:0':\n                model.to(device)\n            \n        else:\n            es_step += 1\n            if es_step >= EARLY_STOPPING_EPOCH:\n                print('early stopping')\n                break  \n                                ","metadata":{"execution":{"iopub.status.busy":"2024-09-26T01:08:02.530839Z","iopub.execute_input":"2024-09-26T01:08:02.531205Z","iopub.status.idle":"2024-09-26T05:47:34.150915Z","shell.execute_reply.started":"2024-09-26T01:08:02.531175Z","shell.execute_reply":"2024-09-26T05:47:34.134900Z"},"trusted":true},"execution_count":null,"outputs":[]}]}