{"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":"## Summary\n\n#### [<u>Improved version</u>](https://www.kaggle.com/code/egortrushin/gr-icrgw-pl-pipeline-improved)\n- Option to change image size\n- Mixed pre (only useful with T4x2, on P100 this slows down training). This helps to use GPU memory more efficiently\n- Training using 2 GPUs - with 2 GPUs we have more memory and higher speed\n- Other numerous small changes\n\n#### <u>Present version</u>\n- Training with 4-folds\n- LR scheduler: cosine with warmup\n- Use of CSVLogger with consequent visualization of the optimization process. Since I train without internet, I am limited to *local* CSVLogger or TensorBoardLogger. Alternatively you can train with internet and WanddbLogger.\n- Submission part is rewritten to make it cleaner and to allow easy work with multi-fold models","metadata":{"papermill":{"duration":0.006778,"end_time":"2023-06-19T16:31:04.615884","exception":false,"start_time":"2023-06-19T16:31:04.609106","status":"completed"},"tags":[]}},{"cell_type":"markdown","source":"### Training part","metadata":{"papermill":{"duration":0.005909,"end_time":"2023-06-19T16:31:04.628035","exception":false,"start_time":"2023-06-19T16:31:04.622126","status":"completed"},"tags":[]}},{"cell_type":"code","source":"import sys\nsys.path.append(\"../input/pretrained-models-pytorch\")\nsys.path.append(\"../input/efficientnet-pytorch\")\nsys.path.append(\"/kaggle/input/smp-github/segmentation_models.pytorch-master\")\nsys.path.append(\"/kaggle/input/timm-pretrained-resnest/resnest/\")\nimport segmentation_models_pytorch as smp","metadata":{"_kg_hide-output":true,"papermill":{"duration":7.652044,"end_time":"2023-06-19T16:31:12.286435","exception":false,"start_time":"2023-06-19T16:31:04.634391","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-09T17:03:19.202481Z","iopub.execute_input":"2023-08-09T17:03:19.202931Z","iopub.status.idle":"2023-08-09T17:03:19.208613Z","shell.execute_reply.started":"2023-08-09T17:03:19.202898Z","shell.execute_reply":"2023-08-09T17:03:19.207326Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!mkdir -p /root/.cache/torch/hub/checkpoints/\n!cp /kaggle/input/efficientnet-weight-pytorch/resnest50-528c19ca.pth /root/.cache/torch/hub/checkpoints/resnest50-528c19ca.pth\n!cp /kaggle/input/timm-pretrained-resnest/resnest/gluon_resnest26-50eb607c.pth /root/.cache/torch/hub/checkpoints/gluon_resnest26-50eb607c.pth","metadata":{"_kg_hide-output":true,"papermill":{"duration":2.964417,"end_time":"2023-06-19T16:31:15.257467","exception":false,"start_time":"2023-06-19T16:31:12.29305","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-09T17:03:19.214517Z","iopub.execute_input":"2023-08-09T17:03:19.215345Z","iopub.status.idle":"2023-08-09T17:03:23.275752Z","shell.execute_reply.started":"2023-08-09T17:03:19.215307Z","shell.execute_reply":"2023-08-09T17:03:23.2742Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%writefile config.yaml\n\ndata_path: \"/kaggle/input/contrails-images-ash-color\"\noutput_dir: \"models\"\n\nfolds:\n    n_splits: 4\n    random_state: 42\ntrain_folds: [0, 1, 2, 3]\n    \nseed: 42\n\ntrain_bs: 32\nvalid_bs: 16\nworkers: 2\n\nprogress_bar_refresh_rate: 1\n\nearly_stop:\n    monitor: \"val_loss\"\n    mode: \"min\"\n    patience: 999\n    verbose: 1\n\ntrainer:\n    max_epochs: 20\n    min_epochs: 20\n    enable_progress_bar: True\n    precision: \"16-mixed\"\n    devices: 2\n\nmodel:\n    seg_model: \"Unet\"\n    encoder_name: \"timm-resnest26d\"\n    loss_smooth: 1.0\n    image_size: 512\n    optimizer_params:\n        lr: 0.0005\n        weight_decay: 0.0\n    scheduler:\n        name: \"cosine_with_hard_restarts_schedule_with_warmup\"\n        params:\n            cosine_with_hard_restarts_schedule_with_warmup:\n                num_warmup_steps: 350\n                num_training_steps: 3150\n                num_cycles: 1","metadata":{"papermill":{"duration":0.01767,"end_time":"2023-06-19T16:31:15.28168","exception":false,"start_time":"2023-06-19T16:31:15.26401","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-09T17:03:23.278877Z","iopub.execute_input":"2023-08-09T17:03:23.279367Z","iopub.status.idle":"2023-08-09T17:03:23.288646Z","shell.execute_reply.started":"2023-08-09T17:03:23.27932Z","shell.execute_reply":"2023-08-09T17:03:23.287523Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"%%writefile config.yaml\n\ndata_path: \"/kaggle/input/contrails-images-ash-color\"\noutput_dir: \"models\"\n\nseed: 42\n\ntrain_bs: 16\nvalid_bs: 64\nworkers: 2\n\nprogress_bar_refresh_rate: 1\n\nearly_stop:\n    monitor: \"val_loss\"\n    mode: \"min\"\n    patience: 999\n    verbose: 1\n\ntrainer:\n    max_epochs: 2 #27\n    min_epochs: 1 #25\n    enable_progress_bar: True\n    precision: \"16-mixed\"\n    devices: 2\n\nmodel:\n    seg_model: \"Unet\"\n    encoder_name: \"timm-resnest50d\" #\"tu-tf_efficientnetv2_s.in21k_ft_in1k\"#\n    loss_smooth: 1.0\n    image_size: 512 #384\n    optimizer_params:\n        lr: 0.0005 #6\n        weight_decay: 0.01 # #0.01, 0.02\n    scheduler:\n        name: \"CosineAnnealingLR\"\n        params:\n            CosineAnnealingLR:\n                T_max: 5\n                eta_min: 1.0e-6\n                last_epoch: -1\n            ReduceLROnPlateau:\n                mode: \"min\"\n                factor: 0.31622776602\n                patience: 4\n                verbose: True","metadata":{}},{"cell_type":"code","source":"# Dataset\n\nimport torch\nimport numpy as np\nimport torchvision.transforms as T\n\nclass ContrailsDataset(torch.utils.data.Dataset):\n    def __init__(self, df, image_size=256, train=True):\n\n        self.df = df\n        self.trn = train\n        self.normalize_image = T.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))\n        self.image_size = image_size\n        if image_size != 256:\n            self.resize_image = T.transforms.Resize(image_size)\n\n    def __getitem__(self, index):\n        row = self.df.iloc[index]\n        con_path = row.path\n        con = np.load(str(con_path))\n\n        img = con[..., :-1]\n        label = con[..., -1]\n\n        label = torch.tensor(label)\n\n        img = torch.tensor(np.reshape(img, (256, 256, 3))).to(torch.float32).permute(2, 0, 1)\n\n        if self.image_size != 256:\n            img = self.resize_image(img)\n\n        img = self.normalize_image(img)\n\n        return img.float(), label.float()\n\n    def __len__(self):\n        return len(self.df)","metadata":{"papermill":{"duration":0.019445,"end_time":"2023-06-19T16:31:15.307395","exception":false,"start_time":"2023-06-19T16:31:15.28795","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-09T17:03:23.292966Z","iopub.execute_input":"2023-08-09T17:03:23.293399Z","iopub.status.idle":"2023-08-09T17:03:23.94014Z","shell.execute_reply.started":"2023-08-09T17:03:23.29336Z","shell.execute_reply":"2023-08-09T17:03:23.938833Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Lightning module\n\nimport torch\nimport pytorch_lightning as pl\nimport segmentation_models_pytorch as smp\nfrom torch.optim.lr_scheduler import CosineAnnealingLR, ReduceLROnPlateau\nfrom torch.optim import AdamW\nimport torch.nn as nn\nfrom torchmetrics.functional import dice\nfrom transformers import get_cosine_with_hard_restarts_schedule_with_warmup\n\nseg_models = {\n    \"Unet\": smp.Unet,\n    \"Unet++\": smp.UnetPlusPlus,\n    \"MAnet\": smp.MAnet,\n    \"Linknet\": smp.Linknet,\n    \"FPN\": smp.FPN,\n    \"PSPNet\": smp.PSPNet,\n    \"PAN\": smp.PAN,\n    \"DeepLabV3\": smp.DeepLabV3,\n    \"DeepLabV3+\": smp.DeepLabV3Plus,\n}\n\n\nclass LightningModule(pl.LightningModule):\n    def __init__(self, config):\n        super().__init__()\n        self.config = config\n        self.model = model = seg_models[config[\"seg_model\"]](\n            encoder_name=config[\"encoder_name\"],\n            encoder_weights=\"imagenet\",\n            in_channels=3,\n            classes=1,\n            activation=None,\n        )\n        self.loss_module = smp.losses.DiceLoss(mode=\"binary\", smooth=config[\"loss_smooth\"])\n        self.val_step_outputs = []\n        self.val_step_labels = []\n\n    def forward(self, batch):\n        imgs = batch\n        preds = self.model(imgs)\n        return preds\n\n    def configure_optimizers(self):\n        optimizer = AdamW(self.parameters(), **self.config[\"optimizer_params\"])\n\n        if self.config[\"scheduler\"][\"name\"] == \"CosineAnnealingLR\":\n            scheduler = CosineAnnealingLR(\n                optimizer,\n                **self.config[\"scheduler\"][\"params\"][\"CosineAnnealingLR\"],\n            )\n            lr_scheduler_dict = {\"scheduler\": scheduler, \"interval\": \"step\"}\n            return {\"optimizer\": optimizer, \"lr_scheduler\": lr_scheduler_dict}\n        elif self.config[\"scheduler\"][\"name\"] == \"ReduceLROnPlateau\":\n            scheduler = ReduceLROnPlateau(\n                optimizer,\n                **self.config[\"scheduler\"][\"params\"][\"ReduceLROnPlateau\"],\n            )\n            lr_scheduler = {\"scheduler\": scheduler, \"monitor\": \"val_loss\"}\n            return {\"optimizer\": optimizer, \"lr_scheduler\": lr_scheduler}\n        elif self.config[\"scheduler\"][\"name\"] == \"cosine_with_hard_restarts_schedule_with_warmup\":\n            scheduler = get_cosine_with_hard_restarts_schedule_with_warmup(\n                optimizer,\n                **self.config[\"scheduler\"][\"params\"][self.config[\"scheduler\"][\"name\"]],\n            )\n            lr_scheduler_dict = {\"scheduler\": scheduler, \"interval\": \"step\"}\n            return {\"optimizer\": optimizer, \"lr_scheduler\": lr_scheduler_dict}\n\n    def training_step(self, batch, batch_idx):\n        imgs, labels = batch\n        preds = self.model(imgs)\n        if self.config[\"image_size\"] != 256:\n            preds = torch.nn.functional.interpolate(preds, size=256, mode='bilinear')\n        loss = self.loss_module(preds, labels)\n        self.log(\"train_loss\", loss, on_step=True, on_epoch=True, prog_bar=True, batch_size=16)\n\n        for param_group in self.trainer.optimizers[0].param_groups:\n            lr = param_group[\"lr\"]\n        self.log(\"lr\", lr, on_step=True, on_epoch=False, prog_bar=True)\n\n        return loss\n\n    def validation_step(self, batch, batch_idx):\n        imgs, labels = batch\n        preds = self.model(imgs)\n        if self.config[\"image_size\"] != 256:\n            preds = torch.nn.functional.interpolate(preds, size=256, mode='bilinear')\n        loss = self.loss_module(preds, labels)\n        self.log(\"val_loss\", loss, on_step=False, on_epoch=True, prog_bar=True)\n        self.val_step_outputs.append(preds)\n        self.val_step_labels.append(labels)\n\n    def on_validation_epoch_end(self):\n        all_preds = torch.cat(self.val_step_outputs)\n        all_labels = torch.cat(self.val_step_labels)\n        all_preds = torch.sigmoid(all_preds)\n        self.val_step_outputs.clear()\n        self.val_step_labels.clear()\n        val_dice = dice(all_preds, all_labels.long())\n        self.log(\"val_dice\", val_dice, on_step=False, on_epoch=True, prog_bar=True)\n        if self.trainer.global_rank == 0:\n            print(f\"\\nEpoch: {self.current_epoch}\", flush=True)","metadata":{"_kg_hide-output":true,"papermill":{"duration":11.362208,"end_time":"2023-06-19T16:31:26.676005","exception":false,"start_time":"2023-06-19T16:31:15.313797","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-09T17:03:23.944304Z","iopub.execute_input":"2023-08-09T17:03:23.945258Z","iopub.status.idle":"2023-08-09T17:03:23.970643Z","shell.execute_reply.started":"2023-08-09T17:03:23.945214Z","shell.execute_reply":"2023-08-09T17:03:23.969481Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import warnings\n\nwarnings.filterwarnings(\"ignore\")\n\nimport gc\nimport os\nimport torch\nimport yaml\nimport pandas as pd\nimport pytorch_lightning as pl\nfrom pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping, TQDMProgressBar\nfrom torch.utils.data import DataLoader\nfrom sklearn.model_selection import KFold\nfrom pytorch_lightning.loggers import CSVLogger\n\ntorch.set_float32_matmul_precision(\"medium\")\n\nwith open(\"config.yaml\", \"r\") as file_obj:\n    config = yaml.safe_load(file_obj)","metadata":{"execution":{"iopub.status.busy":"2023-08-09T17:03:23.974323Z","iopub.execute_input":"2023-08-09T17:03:23.974743Z","iopub.status.idle":"2023-08-09T17:03:23.997917Z","shell.execute_reply.started":"2023-08-09T17:03:23.974714Z","shell.execute_reply":"2023-08-09T17:03:23.99685Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Actual training\n\npl.seed_everything(config[\"seed\"])\n\ngc.enable()\n\ncontrails = os.path.join(config[\"data_path\"], \"contrails/\")\ntrain_path = os.path.join(config[\"data_path\"], \"train_df.csv\")\nvalid_path = os.path.join(config[\"data_path\"], \"valid_df.csv\")\n\ntrain_df = pd.read_csv(train_path)\nvalid_df = pd.read_csv(valid_path)\n\ntrain_df[\"path\"] = contrails + train_df[\"record_id\"].astype(str) + \".npy\"\nvalid_df[\"path\"] = contrails + valid_df[\"record_id\"].astype(str) + \".npy\"\n\ndf = pd.concat([train_df, valid_df]).reset_index()\n\nFold = KFold(shuffle=True, **config[\"folds\"])\nfor n, (trn_index, val_index) in enumerate(Fold.split(df)):\n    df.loc[val_index, \"kfold\"] = int(n)\ndf[\"kfold\"] = df[\"kfold\"].astype(int)\n\nfor fold in config[\"train_folds\"]:\n    print(f\"\\n###### Fold {fold}\")\n    trn_df = df[df.kfold != fold].reset_index(drop=True)\n    vld_df = df[df.kfold == fold].reset_index(drop=True)\n\n    dataset_train = ContrailsDataset(trn_df, config[\"model\"][\"image_size\"], train=True)\n    dataset_validation = ContrailsDataset(vld_df, config[\"model\"][\"image_size\"], train=False)\n\n    data_loader_train = DataLoader(\n        dataset_train,\n        batch_size=config[\"train_bs\"],\n        shuffle=True,\n        num_workers=config[\"workers\"],\n    )\n    data_loader_validation = DataLoader(\n        dataset_validation,\n        batch_size=config[\"valid_bs\"],\n        shuffle=False,\n        num_workers=config[\"workers\"],\n    )\n\n    checkpoint_callback = ModelCheckpoint(\n        save_weights_only=True,\n        monitor=\"val_dice\",\n        dirpath=config[\"output_dir\"],\n        mode=\"max\",\n        filename=f\"model-f{fold}-{{val_dice:.4f}}\",\n        save_top_k=1,\n        verbose=1,\n    )\n\n    progress_bar_callback = TQDMProgressBar(\n        refresh_rate=config[\"progress_bar_refresh_rate\"]\n    )\n\n    early_stop_callback = EarlyStopping(**config[\"early_stop\"])\n\n\n    trainer = pl.Trainer(\n        callbacks=[checkpoint_callback, early_stop_callback, progress_bar_callback],\n        logger=CSVLogger(save_dir=f'logs_f{fold}/'),\n        **config[\"trainer\"],\n    )\n\n    model = LightningModule(config[\"model\"])\n\n    trainer.fit(model, data_loader_train, data_loader_validation)\n\n    del (\n        dataset_train,\n        dataset_validation,\n        data_loader_train,\n        data_loader_validation,\n        model,\n        trainer,\n        checkpoint_callback,\n        progress_bar_callback,\n        early_stop_callback,\n    )\n    torch.cuda.empty_cache()\n    gc.collect()","metadata":{"_kg_hide-output":true,"papermill":{"duration":24514.89225,"end_time":"2023-06-19T23:20:01.574928","exception":false,"start_time":"2023-06-19T16:31:26.682678","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-06T13:59:45.752051Z","iopub.execute_input":"2023-08-06T13:59:45.754721Z"}}},{"cell_type":"markdown","source":"import seaborn as sn\nimport matplotlib.pyplot as plt\n\nfor fold in config[\"train_folds\"]:\n    metrics = pd.read_csv(f\"/kaggle/working/logs_f{fold}/lightning_logs/version_0/metrics.csv\")\n    del metrics[\"step\"]\n    del metrics[\"lr\"]\n    del metrics[\"train_loss_step\"]\n    metrics.set_index(\"epoch\", inplace=True)\n    g = sn.relplot(data=metrics, kind=\"line\")\n    plt.title(f\"Fold {fold}\")\n    plt.gcf().set_size_inches(15, 5)\n    plt.grid()\n    plt.show()","metadata":{"papermill":{"duration":3.026291,"end_time":"2023-06-19T23:20:04.647468","exception":false,"start_time":"2023-06-19T23:20:01.621177","status":"completed"},"tags":[]}},{"cell_type":"markdown","source":"### Submission part","metadata":{"papermill":{"duration":0.034236,"end_time":"2023-06-19T23:20:04.717358","exception":false,"start_time":"2023-06-19T23:20:04.683122","status":"completed"},"tags":[]}},{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport gc\nimport os\nimport glob\n\nimport numpy as np\nimport pandas as pd\n\nimport torch\nfrom torch import nn\nfrom torch.utils.data import Dataset, DataLoader\n\nimport pytorch_lightning as pl\nimport torchvision.transforms as T\nimport yaml","metadata":{"papermill":{"duration":0.043302,"end_time":"2023-06-19T23:20:04.79632","exception":false,"start_time":"2023-06-19T23:20:04.753018","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-09T17:03:23.999741Z","iopub.execute_input":"2023-08-09T17:03:24.000148Z","iopub.status.idle":"2023-08-09T17:03:24.011441Z","shell.execute_reply.started":"2023-08-09T17:03:24.000113Z","shell.execute_reply":"2023-08-09T17:03:24.010441Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_size = 32\nnum_workers = 1\nTHR = 0.5\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\ndata = '/kaggle/input/google-research-identify-contrails-reduce-global-warming'\ndata_root = '/kaggle/input/google-research-identify-contrails-reduce-global-warming/test/'\nsubmission = pd.read_csv(os.path.join(data, 'sample_submission.csv'), index_col='record_id')","metadata":{"papermill":{"duration":0.051719,"end_time":"2023-06-19T23:20:04.882363","exception":false,"start_time":"2023-06-19T23:20:04.830644","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-09T17:03:24.012977Z","iopub.execute_input":"2023-08-09T17:03:24.013934Z","iopub.status.idle":"2023-08-09T17:03:24.03406Z","shell.execute_reply.started":"2023-08-09T17:03:24.013892Z","shell.execute_reply":"2023-08-09T17:03:24.032883Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filenames = os.listdir(data_root)\ntest_df = pd.DataFrame(filenames, columns=['record_id'])\ntest_df['path'] = data_root + test_df['record_id'].astype(str)","metadata":{"papermill":{"duration":0.047494,"end_time":"2023-06-19T23:20:04.964162","exception":false,"start_time":"2023-06-19T23:20:04.916668","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-09T17:03:24.035844Z","iopub.execute_input":"2023-08-09T17:03:24.037318Z","iopub.status.idle":"2023-08-09T17:03:24.047184Z","shell.execute_reply.started":"2023-08-09T17:03:24.037277Z","shell.execute_reply":"2023-08-09T17:03:24.045973Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class ContrailsDataset(torch.utils.data.Dataset):\n    def __init__(self, df, image_size=256, train=True):\n        \n        self.df = df\n        self.trn = train\n        self.df_idx: pd.DataFrame = pd.DataFrame({'idx': os.listdir(f'/kaggle/input/google-research-identify-contrails-reduce-global-warming/test')})\n        self.normalize_image = T.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))\n        self.image_size = image_size\n        if image_size != 256:\n            self.resize_image = T.transforms.Resize(image_size)\n    \n    def read_record(self, directory):\n        record_data = {}\n        for x in [\n            \"band_11\", \n            \"band_14\", \n            \"band_15\"\n        ]:\n\n            record_data[x] = np.load(os.path.join(directory, x + \".npy\"))\n\n        return record_data\n\n    def normalize_range(self, data, bounds):\n        \"\"\"Maps data to the range [0, 1].\"\"\"\n        return (data - bounds[0]) / (bounds[1] - bounds[0])\n    \n    def get_false_color(self, record_data):\n        _T11_BOUNDS = (243, 303)\n        _CLOUD_TOP_TDIFF_BOUNDS = (-4, 5)\n        _TDIFF_BOUNDS = (-4, 2)\n        \n        N_TIMES_BEFORE = 4\n\n        r = self.normalize_range(record_data[\"band_15\"] - record_data[\"band_14\"], _TDIFF_BOUNDS)\n        g = self.normalize_range(record_data[\"band_14\"] - record_data[\"band_11\"], _CLOUD_TOP_TDIFF_BOUNDS)\n        b = self.normalize_range(record_data[\"band_14\"], _T11_BOUNDS)\n        false_color = np.clip(np.stack([r, g, b], axis=2), 0, 1)\n        img = false_color[..., N_TIMES_BEFORE]\n\n        return img\n    \n    def __getitem__(self, index):\n        row = self.df.iloc[index]\n        con_path = row.path\n        data = self.read_record(con_path)    \n        \n        img = self.get_false_color(data)\n        \n        img = torch.tensor(np.reshape(img, (256, 256, 3))).to(torch.float32).permute(2, 0, 1)\n        \n        if self.image_size != 256:\n            img = self.resize_image(img)\n        \n        img = self.normalize_image(img)\n        \n        image_id = int(self.df_idx.iloc[index]['idx'])\n            \n        return img.float(), torch.tensor(image_id)\n    \n    def __len__(self):\n        return len(self.df)","metadata":{"papermill":{"duration":0.051882,"end_time":"2023-06-19T23:20:05.050518","exception":false,"start_time":"2023-06-19T23:20:04.998636","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-09T17:03:24.049101Z","iopub.execute_input":"2023-08-09T17:03:24.049801Z","iopub.status.idle":"2023-08-09T17:03:24.06866Z","shell.execute_reply.started":"2023-08-09T17:03:24.049759Z","shell.execute_reply":"2023-08-09T17:03:24.067275Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def rle_encode(x, fg_val=1):\n    \"\"\"\n    Args:\n        x:  numpy array of shape (height, width), 1 - mask, 0 - background\n    Returns: run length encoding as list\n    \"\"\"\n\n    dots = np.where(\n        x.T.flatten() == fg_val)[0]  # .T sets Fortran order down-then-right\n    run_lengths = []\n    prev = -2\n    for b in dots:\n        if b > prev + 1:\n            run_lengths.extend((b + 1, 0))\n        run_lengths[-1] += 1\n        prev = b\n    return run_lengths\n\ndef list_to_string(x):\n    \"\"\"\n    Converts list to a string representation\n    Empty list returns '-'\n    \"\"\"\n    if x: # non-empty list\n        s = str(x).replace(\"[\", \"\").replace(\"]\", \"\").replace(\",\", \"\")\n    else:\n        s = '-'\n    return s","metadata":{"papermill":{"duration":0.047155,"end_time":"2023-06-19T23:20:05.132492","exception":false,"start_time":"2023-06-19T23:20:05.085337","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-09T17:03:24.07373Z","iopub.execute_input":"2023-08-09T17:03:24.074141Z","iopub.status.idle":"2023-08-09T17:03:24.08831Z","shell.execute_reply.started":"2023-08-09T17:03:24.074109Z","shell.execute_reply":"2023-08-09T17:03:24.087102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class LightningModule(pl.LightningModule):\n\n    def __init__(self, config):\n        super().__init__()\n        self.model = smp.Unet(encoder_name=config[\"encoder_name\"],\n                                  encoder_weights=None,\n                                  in_channels=3,\n                                  classes=1,\n                                  activation=None,\n                                  )\n    def forward(self, batch):\n        return self.model(batch)","metadata":{"papermill":{"duration":0.04277,"end_time":"2023-06-19T23:20:05.210285","exception":false,"start_time":"2023-06-19T23:20:05.167515","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-09T17:03:24.090004Z","iopub.execute_input":"2023-08-09T17:03:24.091261Z","iopub.status.idle":"2023-08-09T17:03:24.105405Z","shell.execute_reply.started":"2023-08-09T17:03:24.091215Z","shell.execute_reply":"2023-08-09T17:03:24.104018Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class LightningModule_1(pl.LightningModule):\n\n    def __init__(self, config):\n        super().__init__()\n        self.model = smp.Unet(encoder_name=\"timm-resnest50d\",\n                                  encoder_weights=None,\n                                  in_channels=3,\n                                  classes=1,\n                                  activation=None,\n                                  )\n    def forward(self, batch):\n        return self.model(batch)","metadata":{"execution":{"iopub.status.busy":"2023-08-09T17:03:24.10756Z","iopub.execute_input":"2023-08-09T17:03:24.108113Z","iopub.status.idle":"2023-08-09T17:03:24.120086Z","shell.execute_reply.started":"2023-08-09T17:03:24.10801Z","shell.execute_reply":"2023-08-09T17:03:24.118935Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"MODEL_PATH = \"/kaggle/input/google-rearch-model/models/\"\n#with open(os.path.join(MODEL_PATH, \"config.yaml\"), \"r\") as file_obj:\n#    config = yaml.safe_load(file_obj)","metadata":{"papermill":{"duration":0.042748,"end_time":"2023-06-19T23:20:05.287747","exception":false,"start_time":"2023-06-19T23:20:05.244999","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-09T17:03:24.123177Z","iopub.execute_input":"2023-08-09T17:03:24.124338Z","iopub.status.idle":"2023-08-09T17:03:24.132764Z","shell.execute_reply.started":"2023-08-09T17:03:24.124287Z","shell.execute_reply":"2023-08-09T17:03:24.131637Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ds_384 = ContrailsDataset(\n        test_df,\n        384,\n        train = False\n    )\n \ntest_dl_384 = DataLoader(test_ds_384, batch_size=batch_size, num_workers = num_workers)","metadata":{"papermill":{"duration":0.04492,"end_time":"2023-06-19T23:20:05.367529","exception":false,"start_time":"2023-06-19T23:20:05.322609","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-09T17:03:24.134076Z","iopub.execute_input":"2023-08-09T17:03:24.134432Z","iopub.status.idle":"2023-08-09T17:03:24.149403Z","shell.execute_reply.started":"2023-08-09T17:03:24.13438Z","shell.execute_reply":"2023-08-09T17:03:24.148227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ds = ContrailsDataset(\n        test_df,\n        config[\"model\"][\"image_size\"],\n        train = False\n    )\n \ntest_dl = DataLoader(test_ds, batch_size=batch_size, num_workers = num_workers)","metadata":{"execution":{"iopub.status.busy":"2023-08-09T17:03:24.153282Z","iopub.execute_input":"2023-08-09T17:03:24.153646Z","iopub.status.idle":"2023-08-09T17:03:24.174758Z","shell.execute_reply.started":"2023-08-09T17:03:24.153608Z","shell.execute_reply":"2023-08-09T17:03:24.173462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gc.enable()\nmodel_path_ls=['/kaggle/input/google-rearch-model/models/model-f1-26_384val_dice0.6659.ckpt',\n               '/kaggle/input/google-rearch-model/models/model-f3-26_384val_dice0.6613.ckpt']\nall_preds = {}\n\nfor i, model_path in enumerate(glob.glob(MODEL_PATH + '*.ckpt')):\n    print(model_path)\n    try:\n        model = LightningModule(config[\"model\"]).load_from_checkpoint(model_path, config=config[\"model\"])\n    except:\n        model =  LightningModule_1(config[\"model\"]).load_from_checkpoint(model_path, config=config[\"model\"])\n        \n    model.to(device)\n    model.eval()\n\n    model_preds = {}\n    if model_path not in model_path_ls:\n        for _, data in enumerate(test_dl):\n            images, image_id = data\n\n            images = images.to(device)\n\n            with torch.no_grad():\n                predicted_mask = model(images[:, :, :, :])\n            if config[\"model\"][\"image_size\"] != 256:\n                predicted_mask = torch.nn.functional.interpolate(predicted_mask, size=256, mode='bilinear')\n            predicted_mask = torch.sigmoid(predicted_mask).cpu().detach().numpy()\n\n            for img_num in range(0, images.shape[0]):\n                current_mask = predicted_mask[img_num, :, :, :]\n                current_image_id = image_id[img_num].item()\n                model_preds[current_image_id] = current_mask\n    else:\n        for _, data in enumerate(test_dl_384):\n            images, image_id = data\n\n            images = images.to(device)\n\n            with torch.no_grad():\n                predicted_mask = model(images[:, :, :, :])\n            if config[\"model\"][\"image_size\"] != 256:\n                predicted_mask = torch.nn.functional.interpolate(predicted_mask, size=256, mode='bilinear')\n            predicted_mask = torch.sigmoid(predicted_mask).cpu().detach().numpy()\n\n            for img_num in range(0, images.shape[0]):\n                current_mask = predicted_mask[img_num, :, :, :]\n                current_image_id = image_id[img_num].item()\n                model_preds[current_image_id] = current_mask\n        \n    all_preds[f\"f{i}\"] = model_preds\n    \n    del model    \n    torch.cuda.empty_cache()\n    gc.collect() ","metadata":{"_kg_hide-output":true,"papermill":{"duration":20.013989,"end_time":"2023-06-19T23:20:25.41591","exception":false,"start_time":"2023-06-19T23:20:05.401921","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-09T17:03:24.178946Z","iopub.execute_input":"2023-08-09T17:03:24.179336Z","iopub.status.idle":"2023-08-09T17:03:40.80095Z","shell.execute_reply.started":"2023-08-09T17:03:24.179303Z","shell.execute_reply":"2023-08-09T17:03:40.799662Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(all_preds))","metadata":{"execution":{"iopub.status.busy":"2023-08-09T17:03:40.80306Z","iopub.execute_input":"2023-08-09T17:03:40.803453Z","iopub.status.idle":"2023-08-09T17:03:40.810083Z","shell.execute_reply.started":"2023-08-09T17:03:40.803414Z","shell.execute_reply":"2023-08-09T17:03:40.808845Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for index in submission.index.tolist():\n    for i in range(len(glob.glob(MODEL_PATH + '*.ckpt'))):\n        if i == 0:\n            predicted_mask = all_preds[f\"f{i}\"][index]\n        else:\n            predicted_mask += all_preds[f\"f{i}\"][index]\n    predicted_mask = predicted_mask / len(glob.glob(MODEL_PATH + '*.ckpt'))\n    predicted_mask_with_threshold = np.zeros((256, 256))\n    predicted_mask_with_threshold[predicted_mask[0, :, :] < THR] = 0\n    predicted_mask_with_threshold[predicted_mask[0, :, :] > THR] = 1\n    submission.loc[int(index), 'encoded_pixels'] = list_to_string(rle_encode(predicted_mask_with_threshold))","metadata":{"papermill":{"duration":0.055736,"end_time":"2023-06-19T23:20:25.512178","exception":false,"start_time":"2023-06-19T23:20:25.456442","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-09T17:03:40.812069Z","iopub.execute_input":"2023-08-09T17:03:40.812623Z","iopub.status.idle":"2023-08-09T17:03:40.831272Z","shell.execute_reply.started":"2023-08-09T17:03:40.812585Z","shell.execute_reply":"2023-08-09T17:03:40.830227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission","metadata":{"papermill":{"duration":0.059774,"end_time":"2023-06-19T23:20:25.61126","exception":false,"start_time":"2023-06-19T23:20:25.551486","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-09T17:03:40.833539Z","iopub.execute_input":"2023-08-09T17:03:40.834275Z","iopub.status.idle":"2023-08-09T17:03:40.845392Z","shell.execute_reply.started":"2023-08-09T17:03:40.834227Z","shell.execute_reply":"2023-08-09T17:03:40.84338Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.to_csv('submission.csv')","metadata":{"papermill":{"duration":0.051108,"end_time":"2023-06-19T23:20:25.705459","exception":false,"start_time":"2023-06-19T23:20:25.654351","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-09T17:03:40.847801Z","iopub.execute_input":"2023-08-09T17:03:40.848798Z","iopub.status.idle":"2023-08-09T17:03:40.856825Z","shell.execute_reply.started":"2023-08-09T17:03:40.848759Z","shell.execute_reply":"2023-08-09T17:03:40.855686Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}