Skip to content

Specksim

Specksim is a high performance Spiking-Convolutional Neural Network simulator which is written in C++ and bound to our backend library samna. It simulates the SNN completely event-based and is a good representation of how our DYNAP-CNN architecture hardware processes events. It is designed to help users who do not have access to our chips to test their networks to see how they would perform if they were deployed on the chip. Furthermore, the network architectures that normally could not have been deployed to our hardware due to memory constrains can be tested in specksim. Specksim package is completely bound to Python, which means that any and all of its features can be used easily from Python. - Sinabs

The specksim is a simulator of the speck devkits from Synsense and available for benchmarking in the VLab through the python API.

Main Limitations

some of the limitations from the sinabs conversion mentioned on the devkit’s page still apply but with generaly less restrictions

Sinabs

The VLab still has to convert the given model to a format readable by the simulator, so Sinabs’ conversion limitations are in place.

Model architecture
  • torch.nn.Sequential definition (nn.X)
  • each weight layer (nn.Conv2d, nn.Linear) should be followed by a spiking layer (sinabs.layers.IAF, sinabs.layers.IAFSqueeze).
  • output layer has to be a spiking layer
Operations
  • weight layers

    • nn.Conv2d
    • nn.Linear
  • Biases are not supported

  • Pooling layers

    • nn.AvgPool2d
    • sinabs.layers.SumPool2d
  • Padding is not supported

  • Stride considered equal to kernel size

  • Spiking layers

    • sinabs.layers.IAF
    • sinabs.layers.IAFSqueeze
    • LIF layers are not supported
Input/Output
  • Input has to be of type np.record(‘x’, ‘y’, ’t’, ‘p’)
    • each key is of type np.uint32

To benchmark on this target, a Spiking Neural Network (SNN) and its dataset are needed in order to perform inferences to collect metrics such as the accuracy of the model. Since the simulator is run on a computer, latency is to be considered with a grain of salt as it does not represent correct on-device metrics.

For datasets, the specksim supports models which inputs are either classic data (non-neuromorphic, such as MNIST) or neuromorphic (such as DVSgestures).

Essentials

Model Architecture/Conversion

The model must be a PyTorch SNN, saved as a .pth file. The architecture must be explicitely defined using Torch.nn.Sequential and converted to a spiking model using the Sinabs python package.

import torch.nn as nn
from sinabs.from_torch import from_model

cnn = nn.Sequential(
    ...
)
input_shape = [C, H, W]

# Loading the weights directly
cnn.load_state_dict(torch.load(weights_path, map_location='cpu'))

snn = from_model(model=cnn, add_spiking_output=True, batch_size=1).spiking_model
torch.save(snn, "snn.pth")

Since the input shape cannot be extracted from the model, the user needs to specify it when running the benchmark, this can be done through parameters.

parameters = {
    "input_shape" : input_shape
}

Dataset

The dataset msut be provided as either a classic data representation (C, H, W) or a list of Samna DvsEvent, saved in a file with the .pkl extension. The easiest way is to pickle a subset (or mini-batch) of the testing dataset.

torchvision could be used for example to import MNIST’s dataset

from torchvision import datasets

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

# Exporting
with open(DATASET_SAVE_PATH, "wb") as f:
    pickle.dump(benchmark_dataset, f)

Launching the Benchmark

A benchmark for this target can only be performed using the dAIEdge-VLab API, requiring the user to provide a dataset, as this option is not available through the Web UI

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)

Benchmark Results

Once the benchmarking process complete, the resulting metrics collected by VLab are obtained inside the report (result["report"]). This report is a JSON object containing different values and metrics measured throughout the benchmark.

Some of these values are: "model_size", "parameter_count", "accuracy" and "latency".

report = result["report"]

# Observing every metric available
for key in report.keys():
    if key is not None:
        print(f'"{key}" : {report[key]}')

In case an error occurs while the benchmark was running, the report is not generated and no information can be obtained. Best practice is to verify if the report returned correctly, otherwise, check the logs

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

In-Depth

The benchmarking implemetation for this target is available in the Specksim target repository. This provides users with full visibility into the configuration of the Specksim, the python packages used and their respective versions, as well as the methods used to measure and calculate metrics, enabling full transparency of the benchmarking process. Additionally, it shows the expected input file formats and the formats of the resulting outputs.