Example
This example code is based on an existing tutorial made available by Sinabs and adapted in order to work with VLab.
This example will go through the notions of:
- How to define a standard CNN model unsing toch.nn.Sequential
- Load an NMNIST dataset from Tonic and train the model
- Convert the model to SNN and the dataset to a list of DvsEvents using sinabs and samna
- Run the benchmarking using the dAIEdgeVlab Python Client API
- Analyse the spiking activity (through time and coordinates) and power consumption
Getting Started
For the making of this example, the following were used:
- OS : Ubuntu 24.04.3 LTS
- Python : 3.12.3
- Package Manager : uv
- Model
A notebook is also recommended to have better control over the running code
Installing Dependencies
%pip install sinabs
%pip install tonic
%pip install tqdm
%pip install ipywidgets
%pip install matplotlib
%pip install daiedge-vlab
%pip install numpy==1.26.4
import sys
print(sys.version)The dependecies can also be managed using the uv package manager using the following command:
$ uv add sinabs tonic tqdm ipywidgets matplotlib daiedge-vlab numpyor by downloading the requirements.txt file and adding them to python
$ uv add -r requirements.txt
# or
$ pip install -r requirements.txtThe names can be changed as long as the file extensions remain correct (see comments ‘#’)
# Main python libraries
import io, os
from collections import defaultdict, Counter
# Dependencies
from tqdm.notebook import tqdm
import matplotlib.pyplot as plt
import numpy as np
import pickle
import torch
from torch import nn
from torch.optim import SGD
from torch.nn import CrossEntropyLoss
from torch.utils.data import DataLoader, Subset
from tonic.transforms import ToFrame
from tonic.datasets.nmnist import NMNIST
from daiedge_vlab import dAIEdgeVLabAPI
# Model Specific
import samna
from sinabs.from_torch import from_model
# Main directories
ROOT_DIR = "."
EXPORT_DIR = os.path.join(ROOT_DIR, "saves")
MODEL_FILENAME = "vlab_nmnist.pth" # Must end with '.pth'
DATASET_FILENAME = "NMNIST_DVS.pkl" # Must end with '.pkl'
WEIGHTS_FILENAME = "cnn_weights.pt" # Must end with '.pt'
# Saving paths
MODEL_SAVE_PATH = os.path.join(EXPORT_DIR, MODEL_FILENAME)
DATASET_SAVE_PATH = os.path.join(EXPORT_DIR, DATASET_FILENAME)
# Create export folder
os.makedirs(EXPORT_DIR, exist_ok=True)
RUN_TRAINING = FalseThis example notebook can perform training on a new model or import pre-existing and pre-trained weights to skip over time-consuming cells by setting the RUN_TRAINING to the desired state.
CNN model/dataset
Create the CNN model
Speck™ constrains the model architecture and operations and requires the explicite definition of the layers.
The general architecture should follow the following principle:
Conv -> ReLU (-> Pooling)
# Define a CNN model
cnn = nn.Sequential(
# [2,34,34] -> [8,17,17]
nn.Conv2d(in_channels=2, out_channels=8, kernel_size=(3,3), padding=(1,1), bias=False),
nn.ReLU(),
nn.AvgPool2d(2,2),
# [8,17,17] -> [16,8,8]
nn.Conv2d(in_channels=8, out_channels=16, kernel_size=(3,3), padding=(1,1), bias=False),
nn.ReLU(),
nn.AvgPool2d(2,2),
# [16*8*8] -> [16,4,4]
nn.Conv2d(in_channels=16, out_channels=16, kernel_size=(3,3), padding=(1,1), stride=(2,2), bias=False),
nn.ReLU(),
# [16*4*4] -> [10]
nn.Flatten(),
nn.Linear(16*4*4, 10, bias=False),
nn.ReLU()
)
INPUT_SHAPE = [2, 34, 34]
for layer in cnn.modules():
if isinstance(layer, (nn.Conv2d, nn.Linear)):
nn.init.xavier_normal_(layer.weight.data)
if not RUN_TRAINING:
# 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, batch_size=4).spiking_modelHere, we also state the model’s input shape which is necessary for the benchmark, and, if the training is to be skipped, we load the pre-trained weights and perform the conversion.
Training
Create the classic dataset
In this example, we use the NMNIST dataset (2x34x34), a variation on the MNIST dataset used specifically for Neuromorphic models. It differs from the original MNIST dataset (1x28x28), using 2 polarity channels and some padding that comes from a moving neuromorphic camera.
Here, the Tonic python library, allows the conversion to a classic representation.
# define a transform that accumulate the events into a single frame image
to_frame = ToFrame(sensor_size=NMNIST.sensor_size, n_time_bins=1)
cnn_train_dataset = NMNIST(save_to=ROOT_DIR, train=True, transform=to_frame)
cnn_test_dataset = NMNIST(save_to=ROOT_DIR, train=False, transform=to_frame)Train the CNN model
epochs = 3
lr = 1e-3
batch_size = 4
num_worker = 4
shuffle = True
cnn_train_dataloader = DataLoader(cnn_train_dataset, batch_size=batch_size, num_workers=num_worker, drop_last=True, shuffle=shuffle)
cnn_test_dataloader = DataLoader(cnn_test_dataset, batch_size=batch_size, num_workers=num_worker, drop_last=True, shuffle=shuffle)
optimizer = SGD(params=cnn.parameters(), lr=lr)
criterion = CrossEntropyLoss()
for e in range(epochs):
# Training
train_p_bar = tqdm(cnn_train_dataloader)
for data, label in train_p_bar:
data = data.squeeze(dim=1).to(dtype=torch.float)
optimizer.zero_grad()
output = cnn(data)
loss = criterion(output, label)
loss.backward()
optimizer.step()
train_p_bar.set_description(f"Epoch {e} - Traning loss: {round(loss.item(), 4)}")
# Validation
correct_predictions = []
with torch.no_grad():
test_p_bar = tqdm(cnn_test_dataloader)
for data, label in test_p_bar:
data = data.squeeze(dim=1).to(dtype= torch.float)
output = cnn(data)
pred = output.argmax(dim=1, keepdim=True)
correct_predictions.append(pred.eq(label.view_as(pred)))
test_p_bar.set_description(f"Epoch {e} - Testing model")
correct_predictions = torch.cat(correct_predictions)
print(f"Epoch {e} - accuracy: {correct_predictions.sum().item()/(len(correct_predictions))*100} %")CNN to SNN conversion
Convert the CNN model to SNN model
snn = from_model(model=cnn, batch_size=batch_size).spiking_modelVLab
Create the VLab dataset
To be able to perform a benchmark on the Speck2f Devkit, the dataset has to be transoformed into a list of samna DVSEvents.
The NMNIST dataset is also ordered, meaning every ‘0’ sample comes before the ‘1’ samples and so on.
snn_test_dataset = NMNIST(save_to=ROOT_DIR, train=False)
subset_indices = list(range(0,len(snn_test_dataset), 100)) # Take every 100th sample
snn_test_dataset = Subset(snn_test_dataset, subset_indices)
dataset_event_stream = []
for events, label in snn_test_dataset:
image_event_stream = []
for ev in events:
dvs_ev = samna.speck2f.event.DvsEvent()
dvs_ev.x = ev['x']
dvs_ev.y = ev['y']
dvs_ev.timestamp = ev['t'] - events['t'][0]
dvs_ev.p = ev['p']
image_event_stream.append(dvs_ev)
dataset_event_stream.append([image_event_stream, label])Export model & event 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 ‘.pkl’
-
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(dataset_event_stream, f)
parameters = {
"input_shape" : INPUT_SHAPE
}Launch the VLab benchmark
In our case, the testing dataset contains enought values for 100 inferences, but we choose to only do 50. If the benchmark needed to be done on every single value, then the inference_number parameter can be changed.
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 = "speck2fdevkit",
runtime = "speck",
model_path = MODEL_SAVE_PATH,
dataset = DATASET_SAVE_PATH,
parameters = parameters,
inference_number = 50
)
print(benchmark_id)
result = api.waitBenchmarkResult(benchmark_id)if the benchmark fails because of a model that is too big to fit on the target, it can still be benchmarked on a simulator, if only the accuracy and spiking activity are needed, setting the target as "specksim".
Beware of the inference times though, since the benchmark is not done on the target, the times can differ greatly from the real cases.
Results
Get the results
report = result["report"]
if report is None:
print(result["error_log"])
print(result["user_log"])
raise RuntimeError("Something went wrong while benchmarking model")
chip_layers_ordering = report["chip_layers_ordering"]
print(f"Chip layers ordering: {chip_layers_ordering}")
raw_bytes = result["raw_output"]
buffer = io.BytesIO(raw_bytes)
data = np.load(buffer, allow_pickle=True)
spiking_activity = data['spiking_activity']
power_monitoring = data['power_monitoring']Model Information
model_size = report["model_size"]/1e3 # Originally in Bytes
param_count = report["nb_parameters_model"]
accuracy = report["accuracy"]
power_cons_mW = report["power_consumption"]*1e3 # Originally in Watts
power_cons_uW = power_cons_mW*1e3
print(f"Model Size: {model_size:.3f} KB")
print(f"Parameter Count: {param_count}")
print(f"Power Consumed: {power_cons_mW:.3f}mW ({power_cons_uW:.3f}uW)")
print(f"Model Accuracy: {accuracy*100}%")Spiking Activity Analysis through time
The speck2f only contains 9 cores, numbered from 0 to 8, but adding the pre-processing DVS layer adds the layer 13 to the mix. This layer is separated from the others and does not count towards to 9 cores of the chip.
We regroup the timestamps to 100 different groups and plot them to a bar graph to observe the spiking evolution of the model.
n_time_steps = 100
inference_to_analyse = 0
print(f"Number of inferences: {len(spiking_activity)}")
print(f"Inference analysed: {inference_to_analyse}")
monitored_events = spiking_activity[inference_to_analyse]
print(f"Total number of events for the inference: {len(monitored_events)}")
# Extract timestamps and layers
timestamps = [e.timestamp for e in monitored_events]
layers = [e.layer for e in monitored_events]
# Get min and max timestamp
min_t, max_t = min(timestamps), max(timestamps)
print(f"first value at {min_t}")
# Create 100 bins equally spaced
bins = np.linspace(min_t, max_t, n_time_steps+1) # 101 edges = 100 bins
bin_centers = (bins[:-1] + bins[1:]) / 2 # for x-axis
# Unique layers
unique_layers = sorted(set(layers))
# Count spikes per bin per layer
counts = np.zeros((len(unique_layers), len(bins)-1), dtype=int)
layer_to_idx = {layer: i for i, layer in enumerate(unique_layers)}
for e in monitored_events:
bin_idx = np.searchsorted(bins, e.timestamp, side="right") - 1
if 0 <= bin_idx < len(bins)-1:
counts[layer_to_idx[e.layer], bin_idx] += 1
# Plot stacked bar chart
bottom = np.zeros(len(bins)-1)
plt.figure(figsize=(12, 6))
for i, layer in enumerate(unique_layers):
plt.bar(bin_centers, counts[i],
bottom=bottom,
width=(bins[1] - bins[0]), # bar width = bin size
align="center",
label=f"Layer {layer}")
bottom += counts[i]
plt.title("Spike activity per layer (stacked)")
plt.xlabel("Time [us]")
plt.xticks(ticks=np.arange(start=0, stop=max_t+1, step=round(max_t//6, -4)))
plt.ylabel("Spike count")
plt.legend(loc='upper left')
plt.axis([0, max_t, 0, 1.1 * bottom.max()])
plt.tight_layout()
plt.savefig(fname="spiking_activity_bar")
plt.show()If successful, the code above should print a bar graph with every layer’s spikes from their timestamps
During the benchmark, everytime a neuron spikes, the activation timestamp gets logged. We then group every single one, per inference, then layer.
Spiking Activity Analysis through coordinates
For this one, we check for the coordinates of the neuron (x,y) to see how the different features and layers react to the input data.
from matplotlib.ticker import MaxNLocator
save_folder = ROOT_DIR
image_name = "heatmaps_layer_"
print(f"Number of inferences: {len(spiking_activity)}")
print(f"Inference analysed: {inference_to_analyse}")
events = spiking_activity[inference_to_analyse]
print(f"Total number of events for the inference: {len(events)}")
event_per_layer_count = Counter(event.layer for event in events)
layers_concerned = list(event_per_layer_count.keys())
print(f"Layers concerned: {layers_concerned}")
print(f"Number of events per layers: {dict(event_per_layer_count)}")
# iterate through every layer in the inference
for layer_number in layers_concerned:
# obtain all spiking events / nb of features for current layer
layer_events = [event for event in events if event.layer == layer_number]
num_features = max(e.feature for e in layer_events) + 1
# get the highest value of x/y of feature maps
# used to size up the feature maps' grids
all_xs = [e.x for e in layer_events]
all_ys = [e.y for e in layer_events]
global_max_x = max(all_xs) if all_xs else 0
global_max_y = max(all_ys) if all_ys else 0
# actual values for grids
grid_height = global_max_y + 1
grid_width = global_max_x + 1
# iterate once through every feature map to get the highest value of activations
# useful to set the colorbar values (same max value for colorbar for every feature in the layer)
heatmaps = []
for feature in range(num_features):
filtered = [e for e in layer_events if e.feature == feature]
heatmap = np.zeros((grid_height, grid_width), dtype=int)
for e in filtered:
heatmap[e.y, e.x] += 1
heatmaps.append(heatmap)
# If zero activations in the feature set max to 1 (error handling)
global_max = max(hm.max() for hm in heatmaps) if heatmaps else 1
if global_max == 0:
global_max = 1
# Setup subplots
cols = min(num_features, 4)
rows = int(np.ceil(num_features / cols))
fig, axes = plt.subplots(rows, cols, figsize=(4*cols, 4*rows))
axes = np.atleast_2d(axes)
# Build every subplot
for feature in range(num_features):
heatmap = heatmaps[feature]
h, w = heatmap.shape
ax = axes[feature // cols, feature % cols]
im = ax.imshow(heatmap, cmap='hot', origin='lower', vmin=0, vmax=global_max)
ax.set_title(f"Feature {feature}")
ax.set_xlabel("X")
ax.set_ylabel("Y")
# MaxNLocator is used to only show integer indexes
ax.xaxis.set_major_locator(MaxNLocator(integer=True, min_n_ticks=1, nbins=5))
ax.yaxis.set_major_locator(MaxNLocator(integer=True, min_n_ticks=1, nbins=5))
# Only show integers on the colorbar (since activations are only integers)
cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
cbar.locator = MaxNLocator(integer=True)
cbar.update_ticks()
# Delete unused / unbuilt grids
for f in range(num_features, rows*cols):
fig.delaxes(axes[f // cols, f % cols])
# Saving the image file to folder
plt.suptitle(f"Spike Heatmaps - Layer {layer_number}")
plt.tight_layout()
plt.savefig(f"{save_folder}/{image_name}{layer_number}.png", dpi=300)
plt.close()
print(f"Saved heatmaps as {image_name}{layer_number}.png")If successful, the code above should print a series of subplots showing the activation density of the neurons per feature per layer
- The brighter the pixel, the more activations the neuron makes
In this example’s case, there are 4 layers of “computing” (0-3) and 1 pre-processing layer (13)
The image below represents the spiking activity for the layer 0

Power Consumption Analysis
The target can also measure the power consumption from various sources on the chip, such as RAM or logic.
During the benchmark, this power consumption is measured on a per-inference basis and can be viewed and plotted, as demonstrated by the code snippet below.
The GRAPH_AXIS flag limits the viewing window to either the spiking activity 's_a', or the whole measured values during inference 'p_m'
# ['s_a', 'p_m']
# Either on par with spiking_activity or power measurements
GRAPH_AXIS = 'p_m'
measurements = power_monitoring[inference_to_analyse]
# Channel names
p_track_name = ["io", "ram", "logic", "pixel digital", "pixel analog"]
# Group data by channel
data_by_channel = defaultdict(lambda: {"timestamps": [], "values": []})
# Splitting measurements into their own channel's list
for m in measurements:
data_by_channel[m.channel]["timestamps"].append(m.timestamp/1e6)
data_by_channel[m.channel]["values"].append(m.value*1e3)
# Creation of a new figure
plt.figure(num="Power Consumption", figsize=(16, 6))
# plotting measurements into graph
# If unrecognised name, falling back to channel N
for channel, data in data_by_channel.items():
label = p_track_name[channel] if channel < len(p_track_name) else f"Channel {channel}"
plt.plot(data["timestamps"], data["values"], label=label)
# Obtaining max values for limiting graph lengths
max_value = max([v for d in data_by_channel.values() for v in d["values"]])
max_timestamp = max([t for d in data_by_channel.values() for t in d["timestamps"]])
# Drawing the graph
plt.title(f"Idle Power: {power_cons_mW:.3f} mW")
plt.xlabel("time [s]")
plt.xticks(ticks=np.arange(start=0, stop=max_timestamp, step=0.05))
plt.ylabel("power [mW]")
plt.axhline(y=power_cons_mW, linestyle='--', color='k')
plt.legend(loc="upper right", fontsize=10)
if GRAPH_AXIS == 'p_m':
plt.axis([0, max_timestamp, 0, 1.1*max_value]) # On par with power measurements
elif GRAPH_AXIS == 's_a':
plt.axis([0, max_t/1e6, 0, 1.1*max_value]) # On par with spiking activity (us to s)
else:
raise ValueError("GRAPH_AXIS value not valid")
plt.grid(True)
plt.tight_layout()
plt.savefig(f"power_consumption.png", dpi=300)
plt.show()Once the cell is finished running, we should see one of the two graphs appearing
- The graph shows the power consumption over time for each of the speck sink nodes’ channels
- The dashed line shows the average power consumption over the inference’s length
Depending on the flag state at the top of the cell, the plot can either show:
- all the measured values during inference (
'p_m')
- the measured values focused on the spiking activity timestamps (
's_a')