Skip to content

Example

This example code is based on an existing tutorial made for the Speck2f Devkit, adapted for the specksim using sinabs’ Specksim documentation

Getting Started

  • OS : Ubuntu 24.04.3 LTS
  • Python : 3.12.3
  • Package Manager : uv
  • Model

A Jupyter notebook is also recommended to have better control over the running code.

Installing Dependencies

The python libraries needed to run the notebook successfully

%pip install sinabs
%pip install torch
%pip install torchvision
%pip install daiedge-vlab
%pip install numpy==1.26.4

import sys
print(sys.version)

The dependencies can also be managed using the uv package manager using the following command:

$ uv add sinabs torch torchvision daiedge-vlab numpy

or by downloading the requirements.txt file and adding them to python

$ uv add -r requirements.txt
# or
$ pip install -r requirements.txt

The names can be changed as long as the file extensions remain correct (see comments ‘#’)

# Main python libraries
import os
from pathlib import Path
# Dependencies
import numpy as np
import pickle
import torch
import torch.nn as nn
from torchvision import datasets
from daiedge_vlab import dAIEdgeVLabAPI
# Model Specific
from sinabs.from_torch import from_model

SAVING_DIR = "./saves"
MODEL_FILENAME = "snn_mnist.pth" # Must end with '.pth'
DATASET_FILENAME = "mnist_noDVS.pkl" # Must end with '.pkl'
WEIGHTS_FILENAME = "cnn_weights.pt" # Must end with '.pt'
# Saving paths
MODEL_SAVE_PATH = os.path.join(SAVING_DIR, MODEL_FILENAME)
DATASET_SAVE_PATH = os.path.join(SAVING_DIR, DATASET_FILENAME)

# Create export folder
os.makedirs(SAVING_DIR, exist_ok=True)

Model Architecture

Creating the CNN architecture

The Specksim (and all sinabs compatible targets, such as the Speck2f) are limited in the model architecture.

Since the Specksim is a simulation of a target, it doesn’t have as strict of limitations as the others :

  • Define the architecture using torch.nn.Sequential()
  • Make sure the architecture is sinabs-convertible (appropriate layers)

If more information is deemed necessary about the Specksim, it can be obtained from sinabs’ documentation page

# Architecture
cnn = nn.Sequential(
    nn.Conv2d(1, 20, 5, 1, bias=False),
    nn.ReLU(),
    nn.AvgPool2d(2, 2),
    nn.Conv2d(20, 32, 5, 1, bias=False),
    nn.ReLU(),
    nn.AvgPool2d(2, 2),
    nn.Conv2d(32, 128, 3, 1, bias=False),
    nn.ReLU(),
    nn.AvgPool2d(2, 2),
    nn.Flatten(),
    nn.Linear(128, 500, bias=False),
    nn.ReLU(),
    nn.Linear(500, 10, bias=False),
)
# Defining the input shape, necessary for the model conversion inside the benchmark
input_shape = [1, 28, 28]

# Obtain notebook's current directory, weights must be placed in the same directory as this notebook
weights_path = Path.cwd().resolve() / WEIGHTS_FILENAME

# Loading the weights directly, training was already done beforehand to save time
cnn.load_state_dict(torch.load(weights_path, map_location='cpu'))
# Converting the CNN architecture to a Spikial Neural Network (SNN)
snn = from_model(cnn, add_spiking_output=True, batch_size=1).spiking_model

Dataset

Defining dataset class

Here, we use torchvision’s MNIST dataset to simplify implementation. Creating a class and implementing methods will be useful for getting the necessary data.

The convert_raster_to_events() functions is used to transform the dataset into a format readable by the specksim simulator. Unlike the Speck2f, which needs to have a list of Samna spike events (DVSEvent), the specksim requires that the samples to forward (do the inference on) are of type np.record.

Thankfully, the Specksim implementation on the VLab supports both types of dataset and converts it, if needed, to be able to benchmark the model.

class MNIST_Dataset(datasets.MNIST):
    def __init__(self, root, train=True, spiking=False, t_window=100):
        super().__init__(root, train=train, download=True)
        self.spiking = spiking
        self.t_window = t_window

    def __getitem__(self, index):
        img, target = self.data[index], self.targets[index]

        if self.spiking:
            img = (
                np.random.rand(self.t_window, 1, *img.size()) < img.numpy() / 255.0
            ).astype(float)
            img = torch.from_numpy(img).float()
        else:
            # Convert image to tensor
            img = torch.from_numpy(img.numpy()).float()
            img.unsqueeze_(0)

        return img, target
    
def convert_raster_to_events(spike_train: torch.tensor):
    dtype = [("t", np.uint32), ("p", np.uint32), ("y", np.uint32), ("x", np.uint32)]
    event_list = []
    max_raster = spike_train.max()
    for val in range(int(max_raster), 0, -1):
        t, ch, y, x = torch.where(spike_train == val)
        ev_data = torch.stack((t, ch, y, x), dim=0).T
        ev_data = ev_data.repeat(val, 1)
        event_list.extend(ev_data)
    ev_data = torch.stack(sorted(event_list, key=lambda event: event[0]), dim=0).numpy()
    return np.array([tuple(x) for x in ev_data], dtype=dtype)
t_window = 100
test_dataset = MNIST_Dataset("./dataset", train=False, spiking=True, t_window=t_window)

# Should follow dataset style {input, output}
event_list = []
for n in range(100):
    events = convert_raster_to_events(test_dataset[n][0])
    label = int(test_dataset[n][1])
    event_list.append([events, label])

benchmark_dataset = event_list

Vlab

Exporting model & dataset

Once the model and dataset are ready, we can export them to be sent to the VLab for benchmarking

  • Model The SNN gets exported as a pytorch .pth file

  • Dataset We use pickle to save the dataset as a compact format .pkld

  • Parameters Inside the VLab, the SNN will get converted into a SpecksimNetwork. For this, we need the model’s input shape

torch.save(snn, MODEL_SAVE_PATH)

with open(DATASET_SAVE_PATH, "wb") as f:
    pickle.dump(benchmark_dataset, f)
    
parameters = {
    "input_shape" : input_shape
}

Launching the Benchmark

Before launching the benchmark, make sure that setup.yaml contains the correct information. Refer to dAIEdge-VLab Python Client documentation for installation of the package and definition of the setup.yaml file.

If an error occurs, we cannot progress further.

api = dAIEdgeVLabAPI("setup.yaml")

benchmark_id = api.startBenchmark(
    target = "specksim",
    runtime = "speck",
    model_path = MODEL_SAVE_PATH,
    dataset = DATASET_SAVE_PATH,
    parameters = parameters
)

result = api.waitBenchmarkResult(benchmark_id)

Obtaining Results

Once the berchmarking process has finished, the results can be read from result.

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"]

print(result.keys())

report = result["report"]

if report is None:
    print(result["error_log"])
    print(result["user_log"])
    raise RuntimeError("Something went wrong while benchmarking model")

for key in report.keys():
    if report[key] != None and key != 'spiking_activity':
        print(f"\"{key}\": {report[key]}")