{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":14101002,"sourceType":"datasetVersion","datasetId":8980466}],"dockerImageVersionId":31193,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## Environment Info","metadata":{}},{"cell_type":"code","source":"import sys\nimport torch\nimport subprocess\n\nprint(\"🔍 Gathering system information...\\n\")\n\n# Get CUDA Version\ntry:\n    nvcc_out = subprocess.check_output([\"nvcc\", \"--version\"], encoding=\"utf-8\")\n    cuda_version = nvcc_out.split(\"release \")[1].split(\",\")[0]\nexcept:\n    cuda_version = \"Unknown\"\n\n# Get GCC Version\ntry:\n    gcc_out = subprocess.check_output([\"gcc\", \"--version\"], encoding=\"utf-8\")\n    gcc_version = gcc_out.split(\"\\n\")[0]\nexcept:\n    gcc_version = \"Unknown\"\n\n# Format the output for Markdown\ninfo_text = f\"\"\"\n## 🛠 Environment Specifications\nUse this dataset with the following environment (Kaggle Default):\n\n- **Python**: `{sys.version.split()[0]}`\n- **PyTorch**: `{torch.__version__}`\n- **CUDA**: `{cuda_version}`\n- **GCC**: `{gcc_version}`\n- **GPU Architecture**: Linux x86_64\n\n## 📦 Included Wheels\n- `mamba_ssm` (State Space Model)\n- `causal_conv1d` (Core dependency)\n- `detectron2` (Object Detection Library)\n\"\"\"\n\nprint(\"-\" * 50)\nprint(\"👇 COPY THE TEXT BELOW TO YOUR DATASET DESCRIPTION 👇\")\nprint(\"-\" * 50)\nprint(info_text)\nprint(\"-\" * 50)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-19T07:59:11.913411Z","iopub.execute_input":"2026-01-19T07:59:11.914015Z","iopub.status.idle":"2026-01-19T07:59:18.065121Z","shell.execute_reply.started":"2026-01-19T07:59:11.913989Z","shell.execute_reply":"2026-01-19T07:59:18.064509Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Auto-Install","metadata":{}},{"cell_type":"code","source":"import glob\nimport os\nimport subprocess\nimport sys\n\n# ====================================================\n# 🔍 AUTO-DISCOVERY SETUP\n# ====================================================\nprint(\"🔍 Searching for pre-compiled wheels in /kaggle/input...\")\n\nDATASET_PATH = None\n# Walk through the input directory to find where the wheels are\nfor root, dirs, files in os.walk(\"/kaggle/input\"):\n    for file in files:\n        if file.startswith(\"mamba_ssm\") and file.endswith(\".whl\"):\n            DATASET_PATH = root\n            break\n    if DATASET_PATH:\n        break\n\nif DATASET_PATH:\n    print(f\"✅ Found wheels directory: {DATASET_PATH}\")\nelse:\n    print(\"❌ ERROR: Could not find wheel files!\")\n    print(\"👉 ACTION REQUIRED: Click 'Add Input' on the right sidebar and add your dataset.\")\n    raise FileNotFoundError(\"Dataset not attached.\")\n\n# ====================================================\n# 🚀 INSTALLATION SCRIPT\n# ====================================================\n\ndef install_whl(pattern, force=False):\n    # Search inside the discovered path\n    files = glob.glob(os.path.join(DATASET_PATH, pattern))\n    if not files:\n        print(f\"⚠️ Warning: No file matching '{pattern}' found. Skipping.\")\n        return\n    \n    whl_path = files[0]\n    print(f\"📦 Installing: {os.path.basename(whl_path)}\")\n    \n    cmd = f\"pip install \\\"{whl_path}\\\" --no-deps\"\n    if force:\n        cmd += \" --force-reinstall\"\n        \n    subprocess.run(cmd, shell=True, check=True)\n\nprint(\"\\n🚀 Starting installation...\")\n\n# 1. Install Mamba components\ninstall_whl(\"causal_conv1d*.whl\", force=True)\ninstall_whl(\"mamba_ssm*.whl\", force=True)\n\n# 2. Install Detectron2\ninstall_whl(\"detectron2*.whl\", force=True)\n\n# 3. Install dependencies\nprint(\"🔧 Installing dependencies...\")\nsubprocess.run(\"pip install fvcore iopath omegaconf yacs termcolor cloudpickle tabulate pydot future hydra-core antlr4-python3-runtime\", shell=True)\n\nprint(\"\\n✅ Installation Complete!\")","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-01-19T07:59:18.066137Z","iopub.execute_input":"2026-01-19T07:59:18.066412Z","iopub.status.idle":"2026-01-19T07:59:47.176707Z","shell.execute_reply.started":"2026-01-19T07:59:18.066394Z","shell.execute_reply":"2026-01-19T07:59:47.175973Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Smoke Test","metadata":{}},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport numpy as np\nimport os\nimport cv2\n\n# Import Mamba & Detectron2\nfrom mamba_ssm import Mamba\nfrom detectron2.config import get_cfg\nfrom detectron2.engine import DefaultTrainer\nfrom detectron2.modeling import BACKBONE_REGISTRY, Backbone, ShapeSpec, build_model\nfrom detectron2.structures import ImageList, Instances, Boxes\nfrom detectron2 import model_zoo\nfrom detectron2.utils.events import EventStorage\n\nprint(\"🧪 Starting Integration Test (Mamba + Detectron2)...\")\n\n# ---------------------------------------------------------\n# 1. Define a Minimal Mamba Backbone\n# ---------------------------------------------------------\n\n# 🔴 FIX: Clean registry to allow cell re-execution\nif \"SimpleMambaBackbone\" in BACKBONE_REGISTRY:\n    del BACKBONE_REGISTRY._obj_map[\"SimpleMambaBackbone\"]\n\n@BACKBONE_REGISTRY.register()\nclass SimpleMambaBackbone(Backbone):\n    def __init__(self, cfg, input_shape: ShapeSpec):\n        super().__init__()\n        dim = 128\n        self.conv = nn.Conv2d(3, dim, kernel_size=4, stride=4) # Patch embed\n        \n        # The Core Mamba Layer\n        self.mamba = Mamba(\n            d_model=dim,\n            d_state=16,\n            d_conv=4,\n            expand=2\n        )\n        \n        self.norm = nn.LayerNorm(dim)\n        \n        # We only output one feature level \"p4\" with stride 4\n        self._out_features = [\"p4\"]\n        self._out_feature_channels = {\"p4\": dim}\n        self._out_feature_strides = {\"p4\": 4}\n\n    def forward(self, x):\n        # x: [B, 3, H, W]\n        x = self.conv(x) # [B, Dim, H/4, W/4]\n        B, C, H, W = x.shape\n        \n        # Flatten for Mamba: [B, C, L] -> [B, L, C]\n        x_flat = x.flatten(2).transpose(1, 2)\n        \n        # Run Mamba (This triggers the custom CUDA kernel)\n        x_mamba = self.mamba(x_flat)\n        x_mamba = self.norm(x_mamba)\n        \n        # Reshape back: [B, L, C] -> [B, C, H, W]\n        out = x_mamba.transpose(1, 2).reshape(B, C, H, W)\n        \n        return {\"p4\": out}\n\n# ---------------------------------------------------------\n# 2. Setup Configuration\n# ---------------------------------------------------------\ncfg = get_cfg()\ncfg.merge_from_file(model_zoo.get_config_file(\"COCO-Detection/faster_rcnn_R_50_FPN_1x.yaml\"))\n\ncfg.MODEL.BACKBONE.NAME = \"SimpleMambaBackbone\"\ncfg.MODEL.RPN.IN_FEATURES = [\"p4\"] \ncfg.MODEL.ROI_HEADS.IN_FEATURES = [\"p4\"] \n\n# FIX: Override Anchor Generator sizes to match single-level feature map\ncfg.MODEL.ANCHOR_GENERATOR.SIZES = [[32, 64, 128, 256, 512]]\ncfg.MODEL.ANCHOR_GENERATOR.ASPECT_RATIOS = [[0.5, 1.0, 2.0]]\n\ncfg.MODEL.PIXEL_MEAN = [128.0, 128.0, 128.0]\ncfg.MODEL.DEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\nprint(f\"⚙️ Device: {cfg.MODEL.DEVICE}\")\n\n# ---------------------------------------------------------\n# 3. Create Dummy Data & Model\n# ---------------------------------------------------------\ntry:\n    model = build_model(cfg)\n    model.train()\n    optimizer = torch.optim.SGD(model.parameters(), lr=0.01)\n\n    # Fake Input Data (Batch size 2)\n    images = torch.rand(2, 3, 256, 256).to(cfg.MODEL.DEVICE) * 255\n    \n    # Fake Ground Truth\n    gt_instances = Instances((256, 256))\n    gt_instances.gt_boxes = Boxes(torch.tensor([[10, 10, 50, 50], [60, 60, 100, 100]]).float().to(cfg.MODEL.DEVICE))\n    gt_instances.gt_classes = torch.tensor([0, 1]).long().to(cfg.MODEL.DEVICE)\n\n    inputs = [{\"image\": img, \"instances\": gt_instances} for img in images]\n\n    # ---------------------------------------------------------\n    # 4. Run Forward & Backward Pass\n    # ---------------------------------------------------------\n    with EventStorage(0) as storage:\n        print(\"➡️ Running Forward Pass...\")\n        loss_dict = model(inputs)\n        losses = sum(loss_dict.values())\n        print(f\"   Loss: {losses.item():.4f}\")\n        \n        print(\"⬅️ Running Backward Pass...\")\n        optimizer.zero_grad()\n        losses.backward()\n        optimizer.step()\n        \n    print(\"\\n✅ SUCCESS: Mamba integrated with Detectron2 is working correctly!\")\n    \nexcept Exception as e:\n    print(f\"\\n❌ FAILED: {e}\")\n    import traceback\n    traceback.print_exc()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-19T07:59:47.177521Z","iopub.execute_input":"2026-01-19T07:59:47.177918Z","iopub.status.idle":"2026-01-19T08:00:03.783266Z","shell.execute_reply.started":"2026-01-19T07:59:47.177888Z","shell.execute_reply":"2026-01-19T08:00:03.782615Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"##","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}