DS-CNN/KWS inference

This tutorial illustrates how to build a basic speech recognition Akida network that recognizes thirty-two different words.

The model will be first defined as a CNN and trained in Keras, then converted using the CNN2SNN toolkit.

This example uses a Keyword Spotting Dataset prepared using TensorFlow audio recognition example utils.

The words to recognize are first converted to spectrogram images that allows us to use a model architecture that is typically used for image recognition tasks.

1. Load the preprocessed dataset

The TensorFlow speech_commands dataset is used for training and validation. All keywords except “backward”, “follow” and “forward”, are retrieved. These three words are kept to illustrate the edge learning in this edge example. The data are not directly used for training. They are preprocessed, transforming the audio files into MFCC features, well-suited for CNN networks. A pickle file containing the preprocessed data is available on our data server.

import pickle

from tensorflow.keras.utils import get_file

# Fetch pre-processed data for 32 keywords
fname = get_file(
    fname='kws_preprocessed_all_words_except_backward_follow_forward.pkl',
    origin="http://data.brainchip.com/dataset-mirror/kws/kws_preprocessed_all_words_except_backward_follow_forward.pkl",
    cache_subdir='datasets/kws')
with open(fname, 'rb') as f:
    [_, _, x_valid, y_valid, _, _, word_to_index, _] = pickle.load(f)

# Preprocessed dataset parameters
num_classes = len(word_to_index)

print("Wanted words and labels:\n", word_to_index)

Out:

Downloading data from http://data.brainchip.com/dataset-mirror/kws/kws_preprocessed_all_words_except_backward_follow_forward.pkl

   16384/62628765 [..............................] - ETA: 51s
  303104/62628765 [..............................] - ETA: 14s
  720896/62628765 [..............................] - ETA: 10s
 1171456/62628765 [..............................] - ETA: 8s 
 1720320/62628765 [..............................] - ETA: 7s
 2301952/62628765 [>.............................] - ETA: 7s
 2891776/62628765 [>.............................] - ETA: 6s
 3145728/62628765 [>.............................] - ETA: 7s
 3604480/62628765 [>.............................] - ETA: 7s
 3940352/62628765 [>.............................] - ETA: 7s
 4210688/62628765 [=>............................] - ETA: 7s
 4513792/62628765 [=>............................] - ETA: 7s
 4833280/62628765 [=>............................] - ETA: 7s
 5136384/62628765 [=>............................] - ETA: 7s
 5472256/62628765 [=>............................] - ETA: 7s
 5816320/62628765 [=>............................] - ETA: 7s
 6152192/62628765 [=>............................] - ETA: 7s
 6529024/62628765 [==>...........................] - ETA: 7s
 6905856/62628765 [==>...........................] - ETA: 7s
 7274496/62628765 [==>...........................] - ETA: 7s
 7675904/62628765 [==>...........................] - ETA: 7s
 8085504/62628765 [==>...........................] - ETA: 7s
 8470528/62628765 [===>..........................] - ETA: 7s
 8798208/62628765 [===>..........................] - ETA: 7s
 9109504/62628765 [===>..........................] - ETA: 7s
 9428992/62628765 [===>..........................] - ETA: 7s
 9707520/62628765 [===>..........................] - ETA: 7s
10027008/62628765 [===>..........................] - ETA: 7s
10346496/62628765 [===>..........................] - ETA: 7s
10665984/62628765 [====>.........................] - ETA: 7s
11010048/62628765 [====>.........................] - ETA: 7s
11354112/62628765 [====>.........................] - ETA: 7s
11706368/62628765 [====>.........................] - ETA: 7s
12083200/62628765 [====>.........................] - ETA: 7s
12443648/62628765 [====>.........................] - ETA: 7s
12820480/62628765 [=====>........................] - ETA: 7s
13230080/62628765 [=====>........................] - ETA: 6s
13606912/62628765 [=====>........................] - ETA: 6s
14016512/62628765 [=====>........................] - ETA: 6s
14426112/62628765 [=====>........................] - ETA: 6s
14868480/62628765 [======>.......................] - ETA: 6s
15286272/62628765 [======>.......................] - ETA: 6s
15745024/62628765 [======>.......................] - ETA: 6s
16130048/62628765 [======>.......................] - ETA: 6s
16605184/62628765 [======>.......................] - ETA: 6s
17063936/62628765 [=======>......................] - ETA: 6s
17555456/62628765 [=======>......................] - ETA: 6s
18030592/62628765 [=======>......................] - ETA: 5s
18538496/62628765 [=======>......................] - ETA: 5s
19038208/62628765 [========>.....................] - ETA: 5s
19554304/62628765 [========>.....................] - ETA: 5s
20078592/62628765 [========>.....................] - ETA: 5s
20611072/62628765 [========>.....................] - ETA: 5s
21151744/62628765 [=========>....................] - ETA: 5s
21692416/62628765 [=========>....................] - ETA: 5s
22249472/62628765 [=========>....................] - ETA: 5s
22806528/62628765 [=========>....................] - ETA: 5s
23371776/62628765 [==========>...................] - ETA: 4s
23953408/62628765 [==========>...................] - ETA: 4s
24543232/62628765 [==========>...................] - ETA: 4s
25124864/62628765 [===========>..................] - ETA: 4s
25714688/62628765 [===========>..................] - ETA: 4s
26296320/62628765 [===========>..................] - ETA: 4s
26886144/62628765 [===========>..................] - ETA: 4s
27475968/62628765 [============>.................] - ETA: 4s
28065792/62628765 [============>.................] - ETA: 4s
28647424/62628765 [============>.................] - ETA: 4s
29229056/62628765 [=============>................] - ETA: 3s
29810688/62628765 [=============>................] - ETA: 3s
30392320/62628765 [=============>................] - ETA: 3s
30973952/62628765 [=============>................] - ETA: 3s
31563776/62628765 [==============>...............] - ETA: 3s
32153600/62628765 [==============>...............] - ETA: 3s
32735232/62628765 [==============>...............] - ETA: 3s
33325056/62628765 [==============>...............] - ETA: 3s
33914880/62628765 [===============>..............] - ETA: 3s
34504704/62628765 [===============>..............] - ETA: 3s
35094528/62628765 [===============>..............] - ETA: 3s
35684352/62628765 [================>.............] - ETA: 3s
36274176/62628765 [================>.............] - ETA: 2s
36864000/62628765 [================>.............] - ETA: 2s
37453824/62628765 [================>.............] - ETA: 2s
37953536/62628765 [=================>............] - ETA: 2s
38330368/62628765 [=================>............] - ETA: 2s
38772736/62628765 [=================>............] - ETA: 2s
39124992/62628765 [=================>............] - ETA: 2s
39501824/62628765 [=================>............] - ETA: 2s
39927808/62628765 [==================>...........] - ETA: 2s
40321024/62628765 [==================>...........] - ETA: 2s
40763392/62628765 [==================>...........] - ETA: 2s
41148416/62628765 [==================>...........] - ETA: 2s
41607168/62628765 [==================>...........] - ETA: 2s
42033152/62628765 [===================>..........] - ETA: 2s
42500096/62628765 [===================>..........] - ETA: 2s
42926080/62628765 [===================>..........] - ETA: 2s
43409408/62628765 [===================>..........] - ETA: 2s
43884544/62628765 [====================>.........] - ETA: 2s
44236800/62628765 [====================>.........] - ETA: 2s
44613632/62628765 [====================>.........] - ETA: 2s
44982272/62628765 [====================>.........] - ETA: 1s
45342720/62628765 [====================>.........] - ETA: 1s
45711360/62628765 [====================>.........] - ETA: 1s
46071808/62628765 [=====================>........] - ETA: 1s
46465024/62628765 [=====================>........] - ETA: 1s
46850048/62628765 [=====================>........] - ETA: 1s
47259648/62628765 [=====================>........] - ETA: 1s
47652864/62628765 [=====================>........] - ETA: 1s
48087040/62628765 [======================>.......] - ETA: 1s
48513024/62628765 [======================>.......] - ETA: 1s
48881664/62628765 [======================>.......] - ETA: 1s
49274880/62628765 [======================>.......] - ETA: 1s
49594368/62628765 [======================>.......] - ETA: 1s
49913856/62628765 [======================>.......] - ETA: 1s
50257920/62628765 [=======================>......] - ETA: 1s
50593792/62628765 [=======================>......] - ETA: 1s
50946048/62628765 [=======================>......] - ETA: 1s
51322880/62628765 [=======================>......] - ETA: 1s
51691520/62628765 [=======================>......] - ETA: 1s
52092928/62628765 [=======================>......] - ETA: 1s
52469760/62628765 [========================>.....] - ETA: 1s
52871168/62628765 [========================>.....] - ETA: 1s
53280768/62628765 [========================>.....] - ETA: 1s
53682176/62628765 [========================>.....] - ETA: 1s
54116352/62628765 [========================>.....] - ETA: 0s
54550528/62628765 [=========================>....] - ETA: 0s
54984704/62628765 [=========================>....] - ETA: 0s
55435264/62628765 [=========================>....] - ETA: 0s
55902208/62628765 [=========================>....] - ETA: 0s
56360960/62628765 [=========================>....] - ETA: 0s
56844288/62628765 [==========================>...] - ETA: 0s
57327616/62628765 [==========================>...] - ETA: 0s
57827328/62628765 [==========================>...] - ETA: 0s
58335232/62628765 [==========================>...] - ETA: 0s
58834944/62628765 [===========================>..] - ETA: 0s
59351040/62628765 [===========================>..] - ETA: 0s
59883520/62628765 [===========================>..] - ETA: 0s
60407808/62628765 [===========================>..] - ETA: 0s
60948480/62628765 [============================>.] - ETA: 0s
61497344/62628765 [============================>.] - ETA: 0s
62054400/62628765 [============================>.] - ETA: 0s
62611456/62628765 [============================>.] - ETA: 0s
62636032/62628765 [==============================] - 7s 0us/step

62644224/62628765 [==============================] - 7s 0us/step
Wanted words and labels:
 {'six': 23, 'three': 25, 'seven': 21, 'bed': 1, 'eight': 6, 'yes': 31, 'cat': 3, 'on': 18, 'one': 19, 'stop': 24, 'two': 27, 'house': 11, 'five': 7, 'down': 5, 'four': 8, 'go': 9, 'up': 28, 'learn': 12, 'no': 16, 'bird': 2, 'zero': 32, 'nine': 15, 'visual': 29, 'wow': 30, 'sheila': 22, 'marvin': 14, 'off': 17, 'right': 20, 'left': 13, 'happy': 10, 'dog': 4, 'tree': 26, '_silence_': 0}

2. Load a pre-trained native Keras model

The model consists of:

  • a first convolutional layer accepting dense inputs (images),

  • several separable convolutional layers preserving spatial dimensions,

  • a global pooling reducing the spatial dimensions to a single pixel,

  • a last separable convolutional to reduce the number of outputs

  • a final fully connected layer to classify words

All layers are followed by a batch normalization and a ReLU activation.

This model was obtained with unconstrained float weights and activations after 16 epochs of training.

from tensorflow.keras.models import load_model

# Retrieve the model file from the BrainChip data server
model_file = get_file("ds_cnn_kws.h5",
                      "http://data.brainchip.com/models/ds_cnn/ds_cnn_kws.h5",
                      cache_subdir='models')

# Load the native Keras pre-trained model
model_keras = load_model(model_file)
model_keras.summary()

Out:

Downloading data from http://data.brainchip.com/models/ds_cnn/ds_cnn_kws.h5

 16384/158432 [==>...........................] - ETA: 0s
163840/158432 [===============================] - 0s 0us/step

172032/158432 [================================] - 0s 0us/step
Model: "ds_cnn_kws"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 input_1 (InputLayer)        [(None, 49, 10, 1)]       0

 rescaling (Rescaling)       (None, 49, 10, 1)         0

 conv_0 (Conv2D)             (None, 25, 5, 64)         1600

 conv_0_BN (BatchNormalizati  (None, 25, 5, 64)        256
 on)

 conv_0_relu (ReLU)          (None, 25, 5, 64)         0

 separable_1 (SeparableConv2  (None, 25, 5, 64)        4672
 D)

 separable_1_BN (BatchNormal  (None, 25, 5, 64)        256
 ization)

 separable_1_relu (ReLU)     (None, 25, 5, 64)         0

 separable_2 (SeparableConv2  (None, 25, 5, 64)        4672
 D)

 separable_2_BN (BatchNormal  (None, 25, 5, 64)        256
 ization)

 separable_2_relu (ReLU)     (None, 25, 5, 64)         0

 separable_3 (SeparableConv2  (None, 25, 5, 64)        4672
 D)

 separable_3_BN (BatchNormal  (None, 25, 5, 64)        256
 ization)

 separable_3_relu (ReLU)     (None, 25, 5, 64)         0

 separable_4 (SeparableConv2  (None, 25, 5, 64)        4672
 D)

 separable_4_global_avg (Glo  (None, 64)               0
 balAveragePooling2D)

 separable_4_BN (BatchNormal  (None, 64)               256
 ization)

 separable_4_relu (ReLU)     (None, 64)                0

 reshape_1 (Reshape)         (None, 1, 1, 64)          0

 flatten (Flatten)           (None, 64)                0

 dense_5 (Dense)             (None, 33)                2145

 act_softmax (Activation)    (None, 33)                0

=================================================================
Total params: 23,713
Trainable params: 23,073
Non-trainable params: 640
_________________________________________________________________
import numpy as np

from sklearn.metrics import accuracy_score

# Check Keras Model performance
potentials_keras = model_keras.predict(x_valid)
preds_keras = np.squeeze(np.argmax(potentials_keras, 1))

accuracy = accuracy_score(y_valid, preds_keras)
print("Accuracy: " + "{0:.2f}".format(100 * accuracy) + "%")

Out:

Accuracy: 92.85%

3. Load a pre-trained quantized Keras model satisfying Akida NSoC requirements

The above native Keras model is quantized and fine-tuned to get a quantized Keras model satisfying the Akida NSoC requirements. The first convolutional layer uses 8 bits weights, but other layers use 4 bits weights.

All activations are 4 bits except for the final Separable Convolutional that uses binary activations.

Pre-trained weights were obtained after a few training episodes:

  • we train the model with quantized activations only, with weights initialized from those trained in the previous episode (native Keras model),

  • then, we train the model with quantized weights, with both weights and activations initialized from those trained in the previous episode,

  • finally, we train the model with quantized weights and activations and by gradually increasing quantization in the last layer.

The table below summarizes the results obtained when preparing the weights stored under http://data.brainchip.com/models/ds_cnn/ :

Episode

Weights Quant.

Activ. Quant. / last layer

Accuracy

Epochs

1

N/A

N/A

93.06 %

16

2

N/A

4 bits / 4 bits

92.30 %

16

3

8/4 bits

4 bits / 4 bits

92.11 %

16

4

8/4 bits

4 bits / 3 bits

92.38 %

16

5

8/4 bits

4 bits / 2 bits

92.23 %

16

6

8/4 bits

4 bits / 1 bit

92.22 %

16

from akida_models import ds_cnn_kws_pretrained

# Load the pre-trained quantized model
model_keras_quantized = ds_cnn_kws_pretrained()
model_keras_quantized.summary()

# Check Model performance
potentials_keras_q = model_keras_quantized.predict(x_valid)
preds_keras_q = np.squeeze(np.argmax(potentials_keras_q, 1))

accuracy_q = accuracy_score(y_valid, preds_keras_q)
print("Accuracy: " + "{0:.2f}".format(100 * accuracy_q) + "%")

Out:

Downloading data from http://data.brainchip.com/models/ds_cnn/ds_cnn_kws_iq8_wq4_aq4_laq1.h5

 16384/135704 [==>...........................] - ETA: 0s
139264/135704 [==============================] - 0s 0us/step

147456/135704 [================================] - 0s 0us/step
Model: "ds_cnn_kws"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 input_1 (InputLayer)        [(None, 49, 10, 1)]       0

 rescaling (Rescaling)       (None, 49, 10, 1)         0

 conv_0 (QuantizedConv2D)    (None, 25, 5, 64)         1664

 conv_0_relu (ActivationDisc  (None, 25, 5, 64)        0
 reteRelu)

 separable_1 (QuantizedSepar  (None, 25, 5, 64)        4736
 ableConv2D)

 separable_1_relu (Activatio  (None, 25, 5, 64)        0
 nDiscreteRelu)

 separable_2 (QuantizedSepar  (None, 25, 5, 64)        4736
 ableConv2D)

 separable_2_relu (Activatio  (None, 25, 5, 64)        0
 nDiscreteRelu)

 separable_3 (QuantizedSepar  (None, 25, 5, 64)        4736
 ableConv2D)

 separable_3_relu (Activatio  (None, 25, 5, 64)        0
 nDiscreteRelu)

 separable_4 (QuantizedSepar  (None, 25, 5, 64)        4736
 ableConv2D)

 separable_4_global_avg (Glo  (None, 64)               0
 balAveragePooling2D)

 separable_4_relu (Activatio  (None, 64)               0
 nDiscreteRelu)

 reshape_1 (Reshape)         (None, 1, 1, 64)          0

 flatten (Flatten)           (None, 64)                0

 dense_5 (QuantizedDense)    (None, 33)                2145

 act_softmax (Activation)    (None, 33)                0

=================================================================
Total params: 22,753
Trainable params: 22,753
Non-trainable params: 0
_________________________________________________________________
Accuracy: 91.43%

4. Conversion to Akida

We convert the model to Akida and then evaluate the performances on the dataset.

from cnn2snn import convert

# Convert the model
model_akida = convert(model_keras_quantized)
model_akida.summary()

Out:

                Model Summary
______________________________________________
Input shape  Output shape  Sequences  Layers
==============================================
[49, 10, 1]  [1, 1, 33]    1          6
______________________________________________

             SW/conv_0-dense_5 (Software)
_______________________________________________________
Layer (type)             Output shape  Kernel shape
=======================================================
conv_0 (InputConv.)      [25, 5, 64]   (5, 5, 1, 64)
_______________________________________________________
separable_1 (Sep.Conv.)  [25, 5, 64]   (3, 3, 64, 1)
_______________________________________________________
                                       (1, 1, 64, 64)
_______________________________________________________
separable_2 (Sep.Conv.)  [25, 5, 64]   (3, 3, 64, 1)
_______________________________________________________
                                       (1, 1, 64, 64)
_______________________________________________________
separable_3 (Sep.Conv.)  [25, 5, 64]   (3, 3, 64, 1)
_______________________________________________________
                                       (1, 1, 64, 64)
_______________________________________________________
separable_4 (Sep.Conv.)  [1, 1, 64]    (3, 3, 64, 1)
_______________________________________________________
                                       (1, 1, 64, 64)
_______________________________________________________
dense_5 (Fully.)         [1, 1, 33]    (1, 1, 64, 33)
_______________________________________________________
# Check Akida model performance
preds_akida = model_akida.predict_classes(x_valid, num_classes=num_classes)

accuracy = accuracy_score(y_valid, preds_akida)
print("Accuracy: " + "{0:.2f}".format(100 * accuracy) + "%")

# For non-regression purpose
assert accuracy > 0.9

Out:

Accuracy: 91.34%

5. Confusion matrix

The confusion matrix provides a good summary of what mistakes the network is making.

Per scikit-learn convention it displays the true class in each row (ie on each row you can see what the network predicted for the corresponding word).

Please refer to the Tensorflow audio recognition example for a detailed explanation of the confusion matrix.

import itertools
import matplotlib.pyplot as plt

from sklearn.metrics import confusion_matrix

# Create confusion matrix
cm = confusion_matrix(y_valid, preds_akida,
                      labels=list(word_to_index.values()))

# Normalize
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]

# Display confusion matrix
plt.rcParams["figure.figsize"] = (16, 16)
plt.figure()

title = 'Confusion matrix'
cmap = plt.cm.Blues

plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(word_to_index))
plt.xticks(tick_marks, word_to_index, rotation=45)
plt.yticks(tick_marks, word_to_index)

thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
    plt.text(j,
             i,
             format(cm[i, j], '.2f'),
             horizontalalignment="center",
             color="white" if cm[i, j] > thresh else "black")

plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.autoscale()
plt.show()
Confusion matrix

Total running time of the script: ( 0 minutes 14.502 seconds)

Gallery generated by Sphinx-Gallery