{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":112509,"databundleVersionId":14254895,"sourceType":"competition"},{"sourceId":14499735,"sourceType":"datasetVersion","datasetId":9261309},{"sourceId":14521451,"sourceType":"datasetVersion","datasetId":9274638}],"dockerImageVersionId":31236,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# The following code will only execute\n# successfully when compression is complete\n\nimport kagglehub\n\n# Download latest version\npath = kagglehub.dataset_download(\"suman2208/mamba-aux-model\")\n\nprint(\"Path to dataset files:\", path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T18:07:21.142224Z","iopub.execute_input":"2026-01-16T18:07:21.142514Z","iopub.status.idle":"2026-01-16T18:07:21.571138Z","shell.execute_reply.started":"2026-01-16T18:07:21.142488Z","shell.execute_reply":"2026-01-16T18:07:21.570309Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport cv2\nimport pandas as pd\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport timm\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nfrom torch.utils.data import Dataset, DataLoader\nfrom tqdm import tqdm\n\n# ======================================================\n# 1. Configuration\n# ======================================================\nclass Config:\n    TEST_CSV = \"/kaggle/input/csiro-biomass/test.csv\"\n    IMAGE_ROOT = \"/kaggle/input/csiro-biomass/test\"\n    WEIGHTS_PATH = \"/kaggle/input/mamba-aux-2/best_model (10).pt\"\n    \n    IMG_SIZE = 518\n    BATCH_SIZE = 16\n    DEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n    BACKBONE = \"vit_large_patch14_dinov2\"\n\n# ======================================================\n# 2. Model Architecture (MUST MATCH TRAINING EXACTLY)\n# ======================================================\nclass LocalMambaBlock(nn.Module):\n    def __init__(self, dim, kernel_size=5, expand_ratio=2, dropout=0.0):\n        super().__init__()\n        self.norm = nn.LayerNorm(dim)\n        hidden_dim = int(dim * expand_ratio)\n        self.in_proj = nn.Linear(dim, hidden_dim * 2)\n        self.conv = nn.Conv1d(hidden_dim, hidden_dim, kernel_size=kernel_size, \n                              padding=kernel_size//2, groups=hidden_dim)\n        self.act = nn.SiLU()\n        self.out_proj = nn.Linear(hidden_dim, dim)\n        self.drop = nn.Dropout(dropout)\n\n    def forward(self, x):\n        residual = x\n        x = self.norm(x)\n        x_proj = self.in_proj(x)\n        x1, x2 = x_proj.chunk(2, dim=-1)\n        x1 = x1.transpose(1, 2)\n        x1 = self.conv(x1)\n        x1 = x1.transpose(1, 2)\n        x1 = self.act(x1)\n        out = x1 * F.silu(x2)\n        out = self.out_proj(out)\n        out = self.drop(out)\n        return residual + out\n\nclass MambaFusionRegressor(nn.Module):\n    def __init__(self, backbone_name, pretrained=False, meta_dim=4):\n        super().__init__()\n        self.backbone = timm.create_model(backbone_name, pretrained=pretrained, num_classes=0, global_pool='', dynamic_img_size=True)\n        nf = self.backbone.num_features\n        self.fusion = nn.Sequential(\n            LocalMambaBlock(nf, kernel_size=5, dropout=0.2), \n            LocalMambaBlock(nf, kernel_size=21, dropout=0.2)\n        )\n        self.pool = nn.AdaptiveAvgPool1d(1)\n        \n        # --- FIXED: Restored full architecture to match checkpoint ---\n        self.aux_meta_predictor = nn.Sequential(\n            nn.Linear(nf, 256), \n            nn.LayerNorm(256), \n            nn.GELU(), \n            nn.Dropout(0.2),\n            nn.Linear(256, 128), \n            nn.GELU(), \n            nn.Linear(128, meta_dim)\n        )\n        # -------------------------------------------------------------\n\n        in_dim = nf \n        self.head_green = nn.Sequential(nn.Linear(in_dim, in_dim//2), nn.GELU(), nn.Dropout(0.2), nn.Linear(in_dim//2, 1))\n        self.head_clover = nn.Sequential(nn.Linear(in_dim, in_dim//2), nn.GELU(), nn.Dropout(0.2), nn.Linear(in_dim//2, 1))\n        self.head_dead = nn.Sequential(nn.Linear(in_dim, in_dim//2), nn.GELU(), nn.Dropout(0.2), nn.Linear(in_dim//2, 1))\n\n    def forward(self, left, right):\n        l_feat = self.backbone(left)\n        r_feat = self.backbone(right)\n        x = torch.cat([l_feat, r_feat], dim=1)\n        x = self.fusion(x)\n        x = x.transpose(1, 2)\n        visual_feat = self.pool(x).flatten(1)\n        \n        green = F.relu(self.head_green(visual_feat))\n        clover = F.relu(self.head_clover(visual_feat))\n        dead = F.relu(self.head_dead(visual_feat))\n        gdm = green + clover\n        total = gdm + dead\n        \n        # Note: aux_meta_predictor is ignored during this forward pass, \n        # but it must exist for weights to load.\n        \n        return torch.cat([green, clover, dead, gdm, total], dim=1)\n\n# ======================================================\n# 3. Dataset & Utils\n# ======================================================\nclass TestDataset(Dataset):\n    def __init__(self, df, image_root, img_size):\n        self.df = df\n        self.image_root = image_root\n        self.tfms = A.Compose([A.Resize(img_size, img_size), A.Normalize(), ToTensorV2()])\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        row = self.df.iloc[idx]\n        fname = row[\"image_path\"]\n        path = os.path.join(self.image_root, fname)\n        \n        img = cv2.imread(path)\n        if img is None: \n            # Fallback logic for path issues\n            if \"test/\" in fname: \n                alt_path = os.path.join(self.image_root, fname.replace(\"test/\", \"\"))\n                img = cv2.imread(alt_path)\n            \n            if img is None:\n                # print(f\"Warning: Image not found {path}\")\n                img = np.zeros((Config.IMG_SIZE, Config.IMG_SIZE*2, 3), dtype=np.uint8)\n        \n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        h, w, c = img.shape\n        left = self.tfms(image=img[:, :w//2])[\"image\"]\n        right = self.tfms(image=img[:, w//2:])[\"image\"]\n        return left, right, fname\n\n# ======================================================\n# 4. Main Execution\n# ======================================================\ndef main():\n    print(f\"🚀 Starting Inference on {Config.DEVICE}\")\n    \n    # Load Data & Deduplicate\n    test_df = pd.read_csv(Config.TEST_CSV)\n    test_df = test_df.drop_duplicates(subset=['image_path']).reset_index(drop=True)\n    \n    dataset = TestDataset(test_df, Config.IMAGE_ROOT, Config.IMG_SIZE)\n    loader = DataLoader(dataset, batch_size=Config.BATCH_SIZE, shuffle=False, num_workers=2)\n\n    # Load Model\n    model = MambaFusionRegressor(Config.BACKBONE).to(Config.DEVICE)\n    \n    # Load Weights (Safe Method)\n    ckpt = torch.load(Config.WEIGHTS_PATH, map_location=Config.DEVICE)\n    state = ckpt['state_dict'] if 'state_dict' in ckpt else ckpt\n    \n    # Remove 'module.' prefix if present\n    clean_state = {k.replace('module.', ''): v for k, v in state.items()}\n    \n    # Load state dict (strict=False handles minor mismatches, but major layers must match)\n    model.load_state_dict(clean_state, strict=False)\n    model.eval()\n\n    results = []\n    \n    print(\"🔮 Predicting...\")\n    with torch.no_grad():\n        for l, r, paths in tqdm(loader):\n            l, r = l.to(Config.DEVICE), r.to(Config.DEVICE)\n            \n            # TTA Inference\n            pred = (model(l, r) + model(torch.flip(l, [-1]), torch.flip(r, [-1]))) / 2.0\n            pred = pred.cpu().numpy()\n            \n            for i, path in enumerate(paths):\n                p = np.maximum(pred[i], 0)\n                results.append({\n                    \"image_path\": path,\n                    \"Dry_Green_g\": p[0],\n                    \"Dry_Clover_g\": p[1],\n                    \"Dry_Dead_g\": p[2],\n                    \"GDM_g\": p[3],\n                    \"Dry_Total_g\": p[4]\n                })\n\n    # ======================================================\n    # 5. Formatting (Long Format)\n    # ======================================================\n    print(\"Formatting submission...\")\n    df_pred = pd.DataFrame(results)\n    \n    # Clean ID: \"test/ID123.jpg\" -> \"ID123\" (strip spaces just in case)\n    df_pred['id'] = df_pred['image_path'].apply(lambda x: os.path.splitext(os.path.basename(x))[0]).str.strip()\n    \n    # Melt\n    target_cols = [\"Dry_Green_g\", \"Dry_Clover_g\", \"Dry_Dead_g\", \"GDM_g\", \"Dry_Total_g\"]\n    melted = df_pred.melt(id_vars=['id'], value_vars=target_cols, \n                          var_name='target_type', value_name='target')\n    \n    # Create sample_id (ID + '__' + variable)\n    melted['sample_id'] = melted['id'] + '__' + melted['target_type']\n    \n    # Final Selection\n    submission = melted[['sample_id', 'target']].sort_values(by='sample_id')\n    \n    submission.to_csv(\"submission.csv\", index=False)\n    print(\"✅ Saved submission.csv\")\n    print(submission.head())\n\nif __name__ == \"__main__\":\n    main()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T20:22:32.655931Z","iopub.execute_input":"2026-01-16T20:22:32.656444Z","iopub.status.idle":"2026-01-16T20:22:39.867425Z","shell.execute_reply.started":"2026-01-16T20:22:32.656419Z","shell.execute_reply":"2026-01-16T20:22:39.866582Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pd.read_csv(\"submission.csv\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T20:22:44.358105Z","iopub.execute_input":"2026-01-16T20:22:44.358815Z","iopub.status.idle":"2026-01-16T20:22:44.463534Z","shell.execute_reply.started":"2026-01-16T20:22:44.358779Z","shell.execute_reply":"2026-01-16T20:22:44.462866Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}