{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2ec81ce2",
   "metadata": {},
   "source": [
    "# Dependencies\n",
    "---\n",
    "The python libraries needed in order to run the notebook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f2c20882",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install sinabs\n",
    "%pip install torch\n",
    "%pip install torchvision\n",
    "%pip install daiedge-vlab\n",
    "%pip install numpy==1.26.4\n",
    "\n",
    "import sys\n",
    "print(sys.version)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2b8bee82",
   "metadata": {},
   "source": [
    "We import everything needed, setup the names of the exported files in advance and create the directory for the exported files\n",
    "\n",
    "The names can be changed but the file extension must remain correct (see comments '#')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "791461d5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Main python libraries\n",
    "import os\n",
    "from pathlib import Path\n",
    "# Dependencies\n",
    "import numpy as np\n",
    "import pickle\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "from torchvision import datasets\n",
    "from daiedge_vlab import dAIEdgeVLabAPI\n",
    "# Model Specific\n",
    "from sinabs.from_torch import from_model\n",
    "\n",
    "SAVING_DIR = \"./saves\"\n",
    "MODEL_FILENAME = \"snn_mnist.pth\" # Must end with '.pth'\n",
    "DATASET_FILENAME = \"mnist_noDVS.pkl\" # Must end with '.pkl'\n",
    "WEIGHTS_FILENAME = \"cnn_weights.pt\" # Must end with '.pt'\n",
    "# Saving paths\n",
    "MODEL_SAVE_PATH = os.path.join(SAVING_DIR, MODEL_FILENAME)\n",
    "DATASET_SAVE_PATH = os.path.join(SAVING_DIR, DATASET_FILENAME)\n",
    "\n",
    "# Create export folder\n",
    "os.makedirs(SAVING_DIR, exist_ok=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c5f6659",
   "metadata": {},
   "source": [
    "# Creating the CNN architecture\n",
    "The Specksim (and all sinabs compatible targets, such as the Speck2f) are limited in the model architecture.\n",
    "\n",
    "Since the Specksim is a simulation of a target, it doesn't have as strict of limitations as the others :\n",
    "- Define the architecture using torch.nn.Sequential()\n",
    "- Make sure the architecture is sinabs-convertible (appropriate layers)\n",
    "\n",
    "If more information is deemed necessary about the Specksim, it can be obtained from sinabs' [documentation page](https://sinabs.readthedocs.io/v3.1.3/speck/specksim.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4e54d4a9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Architecture\n",
    "cnn = nn.Sequential(\n",
    "    nn.Conv2d(1, 20, 5, 1, bias=False),\n",
    "    nn.ReLU(),\n",
    "    nn.AvgPool2d(2, 2),\n",
    "    nn.Conv2d(20, 32, 5, 1, bias=False),\n",
    "    nn.ReLU(),\n",
    "    nn.AvgPool2d(2, 2),\n",
    "    nn.Conv2d(32, 128, 3, 1, bias=False),\n",
    "    nn.ReLU(),\n",
    "    nn.AvgPool2d(2, 2),\n",
    "    nn.Flatten(),\n",
    "    nn.Linear(128, 500, bias=False),\n",
    "    nn.ReLU(),\n",
    "    nn.Linear(500, 10, bias=False),\n",
    ")\n",
    "# Defining the input shape, necessary for the model conversion inside the benchmark\n",
    "input_shape = [1, 28, 28]\n",
    "\n",
    "# Obtain notebook's current directory, weights must be placed in the same directory as this notebook\n",
    "weights_path = Path.cwd().resolve() / WEIGHTS_FILENAME\n",
    "\n",
    "# Loading the weights directly, training was already done beforehand to save time\n",
    "cnn.load_state_dict(torch.load(weights_path, map_location='cpu'))\n",
    "# Converting the CNN architecture to a Spikial Neural Network (SNN)\n",
    "snn = from_model(cnn, add_spiking_output=True, batch_size=1).spiking_model"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e051c7b1",
   "metadata": {},
   "source": [
    "# Defining dataset class\n",
    "We use here torchvision's MNIST dataset to simplify implementation.\n",
    "creating a class and implementing methods will be useful for getting the necessary data\n",
    "\n",
    "The `convert_raster_to_events()` functions is used to transform the dataset into a format readable by the specksim simulator.\n",
    "Unlike the Speck2f, which needs to have a list of Samna spike events, the specksim requires that the samples to forward (do the inference) to be of type np.record\n",
    "\n",
    "Thankfully, the VLab supports both types of dataset and converts, if needed, to be able to benchmark the model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "988c4baa",
   "metadata": {},
   "outputs": [],
   "source": [
    "class MNIST_Dataset(datasets.MNIST):\n",
    "    def __init__(self, root, train=True, spiking=False, t_window=100):\n",
    "        super().__init__(root, train=train, download=True)\n",
    "        self.spiking = spiking\n",
    "        self.t_window = t_window\n",
    "\n",
    "    def __getitem__(self, index):\n",
    "        img, target = self.data[index], self.targets[index]\n",
    "\n",
    "        if self.spiking:\n",
    "            img = (\n",
    "                np.random.rand(self.t_window, 1, *img.size()) < img.numpy() / 255.0\n",
    "            ).astype(float)\n",
    "            img = torch.from_numpy(img).float()\n",
    "        else:\n",
    "            # Convert image to tensor\n",
    "            img = torch.from_numpy(img.numpy()).float()\n",
    "            img.unsqueeze_(0)\n",
    "\n",
    "        return img, target\n",
    "    \n",
    "def convert_raster_to_events(spike_train: torch.tensor):\n",
    "    dtype = [(\"t\", np.uint32), (\"p\", np.uint32), (\"y\", np.uint32), (\"x\", np.uint32)]\n",
    "    event_list = []\n",
    "    max_raster = spike_train.max()\n",
    "    for val in range(int(max_raster), 0, -1):\n",
    "        t, ch, y, x = torch.where(spike_train == val)\n",
    "        ev_data = torch.stack((t, ch, y, x), dim=0).T\n",
    "        ev_data = ev_data.repeat(val, 1)\n",
    "        event_list.extend(ev_data)\n",
    "    ev_data = torch.stack(sorted(event_list, key=lambda event: event[0]), dim=0).numpy()\n",
    "    return np.array([tuple(x) for x in ev_data], dtype=dtype)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fe0f6429",
   "metadata": {},
   "outputs": [],
   "source": [
    "t_window = 100\n",
    "test_dataset = MNIST_Dataset(\"./dataset\", train=False, spiking=True, t_window=t_window)\n",
    "\n",
    "# Should follow dataset style {input, output}\n",
    "event_list = []\n",
    "for n in range(100):\n",
    "    events = convert_raster_to_events(test_dataset[n][0])\n",
    "    label = int(test_dataset[n][1])\n",
    "    event_list.append([events, label])\n",
    "\n",
    "benchmark_dataset = event_list"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "798dd0c2",
   "metadata": {},
   "source": [
    "# Exporting model & dataset\n",
    "Once the model and dataset are ready, we can export them to be sent to the VLab for benchmarking\n",
    "\n",
    "### Model\n",
    "The SNN gets exported as a pytorch file\n",
    "\n",
    "### Dataset\n",
    "We use pickle to save the dataset as a compact format\n",
    "\n",
    "### Parameters\n",
    "Inside the VLab, the SNN will get converted into a SpecksimNetwork. For this, we need the model's input shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "668c4ca3",
   "metadata": {},
   "outputs": [],
   "source": [
    "torch.save(snn, MODEL_SAVE_PATH)\n",
    "\n",
    "with open(DATASET_SAVE_PATH, \"wb\") as f:\n",
    "    pickle.dump(benchmark_dataset, f)\n",
    "    \n",
    "parameters = {\n",
    "    \"input_shape\" : input_shape\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "82174e23",
   "metadata": {},
   "source": [
    "# Launching the Benchmark\n",
    "Before launching the benchmark, make sure that `setup.yaml` contains the correct information"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b6acfdf6",
   "metadata": {},
   "outputs": [],
   "source": [
    "api = dAIEdgeVLabAPI(\"setup.yaml\")\n",
    "\n",
    "benchmark_id = api.startBenchmark(\n",
    "    target = \"specksim\",\n",
    "    runtime = \"speck\",\n",
    "    model_path = MODEL_SAVE_PATH,\n",
    "    dataset = DATASET_SAVE_PATH,\n",
    "    parameters = parameters\n",
    ")\n",
    "\n",
    "result = api.waitBenchmarkResult(benchmark_id)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3d7a9285",
   "metadata": {},
   "source": [
    "# Obtaining the results\n",
    "Once the berchmarking process has finished, the results can be read from `result`.\n",
    "\n",
    "If something were to happen and the benchmarking process failed, the returned report will be of type None and no information can be obtained. In this case, it is recommended to rerun the VLab benchmark or debug the problem from `result[\"user_log\"]`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d194d88b",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(result.keys())\n",
    "\n",
    "report = result[\"report\"]\n",
    "\n",
    "if report is None:\n",
    "    print(result[\"error_log\"])\n",
    "    print(result[\"user_log\"])\n",
    "    raise RuntimeError(\"Something went wrong while benchmarking model\")\n",
    "\n",
    "for key in report.keys():\n",
    "    if report[key] != None and key != 'spiking_activity':\n",
    "        print(f\"\\\"{key}\\\": {report[key]}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv (3.12.3)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
