Skip to content

Commit 888f4e5

Browse files
lrgirdwosingalsu
andcommitted
audio: microwakeword: add model training and mtrace tuning scripts
Add dataset generation, Piper TTS synthesis, PCAN/MFCC training, model verification, and mtrace feature plotting utilities under src/audio/microwakeword/tune/. Signed-off-by: Liam Girdwood <liam.r.girdwood@linux.intel.com> Co-authored-by: Seppo Ingalsuo <seppo.ingalsuo@linux.intel.com> Signed-off-by: Seppo Ingalsuo <seppo.ingalsuo@linux.intel.com>
1 parent 6ebce4d commit 888f4e5

12 files changed

Lines changed: 4983 additions & 0 deletions
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
# microWakeWord (MWW) Training & Tuning Toolchain
2+
3+
This directory contains offline scripts to train, quantize, verify, and export streaming keyword-spotting models for the SOF `microwakeword` (MWW) module using real SOF MFCC features extracted via `sof-testbench4`.
4+
5+
---
6+
7+
## Toolchain Overview
8+
9+
1. **Keyword Dataset Generation & Ingestion:**
10+
- [sof_mww_generate_keyword_dataset_from_dir.sh](sof_mww_generate_keyword_dataset_from_dir.sh): Ingests recorded real speech WAV samples from a directory, preserves clean reference clips, and complements them with Room Impulse Response (RIR) reverberation, additive background noise (at varying SNRs), tempo/pitch perturbations, and Gaussian gain jitter.
11+
- [sof_mww_generate_keyword_dataset_piper_tts.sh](sof_mww_generate_keyword_dataset_piper_tts.sh): Synthesizes positive keyword WAVs with single-speaker Piper TTS voices, pitch/tempo perturbation (via `sox`), Gaussian gain jitter, and Room Impulse Response (RIR) reverberation.
12+
- [sof_mww_generate_keyword_dataset.sh](sof_mww_generate_keyword_dataset.sh): Multi-speaker generation with `piper-sample-generator` (LibriTTS-R).
13+
- [sof_mww_prepare_silence_unknown.sh](sof_mww_prepare_silence_unknown.sh): Prepares negative dataset classes (`silence` and `unknown`) by slicing background noise and non-target words from Google Speech Commands v2.
14+
15+
2. **DSP Feature Extraction:**
16+
- [sof_mfcc_extract_features.sh](sof_mfcc_extract_features.sh): Emits 184-byte hop records ($24\text{-byte } \texttt{struct mfcc\_data\_header} + 40 \times \text{int32\_t}$ Q9.23 mel values) by running the SOF host testbench with 10 ms mel-40 topology.
17+
18+
3. **Model Training & Export:**
19+
- [sof_mww_dataset.py](sof_mww_dataset.py): Parses testbench `.raw` feature files, applies soft mel-log AGC ($0\text{ dB}$ target, $0.5\text{ dB/s}$ release recovery), and builds training slices.
20+
- [sof_mww_train.py](sof_mww_train.py): Trains a streaming Keras model, quantizes to `int8` with TFLite Micro resource variables, packages behind SOF IPC4 ABI headers, and emits:
21+
- `mww_model_data_<name>.h`: Built-in model header selected by Kconfig.
22+
- `<name>.conf`: ALSA Topology v2 configuration blob for `Object.Base.data`.
23+
- `<name>.txt`: Runtime `sof-ctl` binary control file.
24+
- `sof_mww_train_pipeline.sh --hard-negative-keyword <phrase>`: Synthesizes
25+
Piper TTS competing wake phrases into `unknown/` as hard negatives before
26+
feature extraction. Set `PIPER_VOICE` and optionally
27+
`HARD_NEGATIVE_SAMPLES` (default: 200 per phrase).
28+
29+
For a `Hi Intel` model, useful phrases include `hey siri`, `hey google`,
30+
`ok google`, `alexa`, `hey copilot`, and `hey jarvis`.
31+
32+
4. **Off-Device Verification & Automation:**
33+
- [sof_mww_verify.py](sof_mww_verify.py): Feeds 3-hop streaming slices through the quantized TFLite model to verify detection rates and false alarm rates.
34+
- [sof_mww_train_pipeline.sh](sof_mww_train_pipeline.sh): End-to-end automation runner.
35+
36+
---
37+
38+
## Quickstart
39+
40+
### Environment Setup
41+
42+
#### Setup Piper Virtual Environment (for Dataset Generation)
43+
```bash
44+
python3 -m venv ~/venvs/piper
45+
source ~/venvs/piper/bin/activate
46+
pip install --upgrade pip
47+
pip install piper-sample-generator
48+
```
49+
50+
#### Setup `piper-sample-generator` and Model Checkpoint
51+
```bash
52+
git clone https://github.com/rhasspy/piper-sample-generator ~/git/piper-sample-generator
53+
mkdir -p ~/git/piper-sample-generator/models
54+
wget -O ~/git/piper-sample-generator/models/en_US-libritts_r-medium.pt \
55+
https://github.com/rhasspy/piper-sample-generator/releases/download/v2.0.0/en_US-libritts_r-medium.pt
56+
```
57+
58+
#### Setup Model Training Virtual Environment (Python 3.10 via `uv`)
59+
For systems with newer default Python versions (such as Ubuntu 24.04/26.04), install `uv` to manage a Python 3.10 environment required by TensorFlow 2.16:
60+
```bash
61+
curl -LsSf https://astral.sh/uv/install.sh | sh
62+
uv venv ~/venvs/mww-train --python 3.10
63+
source ~/venvs/mww-train/bin/activate
64+
uv pip install --upgrade pip
65+
uv pip install "tensorflow==2.16.1" "tf-keras==2.16.0"
66+
```
67+
68+
### 1. Generate Synthetic Keyword Data
69+
70+
#### Option A: Multi-speaker dataset with `piper-sample-generator` (PyTorch `.pt` model)
71+
```bash
72+
./sof_mww_generate_keyword_dataset.sh \
73+
--keyword "hey jarvis" \
74+
--label hey_jarvis \
75+
--venv ~/venvs/piper \
76+
~/wov/wavs
77+
```
78+
By default, the script automatically uses:
79+
- `PIPER_MODEL="$HOME/git/piper-sample-generator/models/en_US-libritts_r-medium.pt"` (auto-detected)
80+
- `MAX_SAMPLES=1000` (clips synthesized per speaking-rate variation)
81+
- `MAX_SPEAKERS=200` (cap on LibriTTS-R speaker indices for diverse, high-quality voices)
82+
- `GAIN_AUG=1` (Gaussian level jitter enabled: peak target -10 dBFS, sigma 5 dB)
83+
84+
These can be overridden via environment variables if desired (e.g., `MAX_SAMPLES=1500 MAX_SPEAKERS=300 ./sof_mww_generate_keyword_dataset.sh ...`).
85+
86+
#### Option B: Single-speaker dataset with `piper-tts` (ONNX `.onnx` model)
87+
```bash
88+
./sof_mww_generate_keyword_dataset_piper_tts.sh \
89+
--keyword "hey jarvis" \
90+
--label hey_jarvis \
91+
--voice ~/.local/share/piper-voices/en_US-lessac-medium.onnx \
92+
~/wov/wavs
93+
```
94+
95+
#### Option C: Real speech dataset from a directory of recorded WAV samples
96+
To use recorded human speech recordings instead of synthetic TTS:
97+
```bash
98+
./sof_mww_generate_keyword_dataset_from_dir.sh \
99+
--src-dir /path/to/recorded/audio \
100+
--label hi_intel \
101+
~/wov/wavs
102+
```
103+
This converts the input audio to 16 kHz 16-bit mono, keeps the clean unperturbed samples, and automatically complements them with RIR convolution, background noise mixing (10–30 dB SNR), pitch/tempo shifts, and Gaussian level jitter to reach a full training set size (`MAX_SAMPLES=1000` by default).
104+
105+
You can also pass `--keyword-dir <label>:<path>` directly to `sof_mww_train_pipeline.sh`:
106+
```bash
107+
./sof_mww_train_pipeline.sh \
108+
--keyword-dir hi_intel:/path/to/recorded/audio \
109+
--name hi_intel \
110+
~/wov/wavs ~/wov/feats ~/wov/model
111+
```
112+
113+
### 2. Run End-to-End Retraining Pipeline
114+
With the `mww-train` virtual environment activated:
115+
```bash
116+
source ~/venvs/mww-train/bin/activate
117+
./sof_mww_train_pipeline.sh \
118+
--keyword hey_jarvis \
119+
--name hey_jarvis \
120+
~/wov/wavs ~/wov/feats ~/wov/model
121+
```
122+
123+
---
124+
125+
### Training Multiple Keyword Variants into the Same Model
126+
127+
You can train a single wake-word model to trigger on multiple spoken variants (such as `"hey jarvis"` and `"hi jarvis"`) with **no increase in model size or DSP RAM**:
128+
129+
#### 1. Generate Datasets for Both Phrases
130+
```bash
131+
./sof_mww_generate_keyword_dataset.sh \
132+
--keyword "hey jarvis" --label hey_jarvis \
133+
--keyword "hi jarvis" --label hi_jarvis \
134+
--venv ~/venvs/piper \
135+
~/wov/wavs
136+
```
137+
138+
#### 2. Train with Multiple `--keyword` Arguments
139+
Pass both directory labels to the training pipeline and specify `--name hey_jarvis`:
140+
```bash
141+
source ~/venvs/mww-train/bin/activate
142+
./sof_mww_train_pipeline.sh \
143+
--keyword hey_jarvis \
144+
--keyword hi_jarvis \
145+
--name hey_jarvis \
146+
~/wov/wavs ~/wov/feats ~/wov/model
147+
```
148+
149+
Both phrase directories are pooled as the positive target class ($y = 1$). The streaming verification report provides individual detection recall for each phrase, and the exported `mww_model_data_<name>.h` model triggers when either phrase is spoken.
150+
151+
---
152+
153+
### Visualizing Streaming Diagnostics from mtrace
154+
155+
You can visualize real-time hop metrics, energy/noise floor, int8 feature quantization, and detection probability curves captured from device `mtrace` logs:
156+
157+
```bash
158+
# Capture mtrace output from device:
159+
sof-mtrace-reader > /tmp/mtrace.txt
160+
161+
# Plot streaming diagnostics:
162+
./sof_mww_plot_mtrace.py /tmp/mtrace.txt -o /tmp/mww_diag.png
163+
```
Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
#!/bin/bash
2+
# SPDX-License-Identifier: BSD-3-Clause
3+
# Copyright(c) 2026 Intel Corporation. All rights reserved.
4+
#
5+
# Batch-emit SOF mel40 MFCC feature files for a labelled WAV dataset using the
6+
# SOF host testbench. Used for training microWakeWord (MWW) models against real
7+
# SOF DSP frontend features.
8+
#
9+
# Expected input layout:
10+
# <wav_root>/<label>/<file>.wav # any sample rate/channels; auto-converted
11+
#
12+
# Output layout:
13+
# <feat_root>/<label>/<file>.raw # SOF mel40 hop records
14+
#
15+
# Each hop record is:
16+
# Non-PCAN mode (184 bytes):
17+
# 24 bytes struct mfcc_data_header (magic, frame_number, reserved,
18+
# energy, noise_energy, vad_flag)
19+
# 40 x int32_t Q9.23 mel-log values
20+
# PCAN mode (64 bytes):
21+
# 24 bytes struct mfcc_data_header
22+
# 40 x int8_t PCAN normalized values
23+
#
24+
# Requirements:
25+
# - $SOF_WORKSPACE points at the parent of the sof tree (or workspace root)
26+
# - sof-testbench4 built at tools/testbench/build_testbench/install/bin/
27+
# - sof-hda-benchmark-mfccmel40_10ms{16,24,32}.tplg or
28+
# sof-hda-benchmark-mfccmel40_10ms_pcan{16,24,32}.tplg built
29+
# - sox on PATH
30+
31+
set -e
32+
33+
usage() {
34+
cat >&2 <<EOF
35+
Usage: $0 <wav_root> <feat_root> [--format S16|S24|S32] [--pcan] [--tplg <path>]
36+
37+
wav_root Directory containing <label>/*.wav (recursed one level).
38+
feat_root Output root; <label>/ subdirs are created as needed.
39+
--format Testbench sample container (S16, S24, S32). Default S32.
40+
--pcan Extract 8-bit PCAN normalized features (64-byte hops).
41+
--tplg Explicit path to benchmark topology file.
42+
EOF
43+
exit 1
44+
}
45+
46+
[ $# -ge 2 ] || usage
47+
48+
WAV_ROOT="$1"
49+
FEAT_ROOT="$2"
50+
FORMAT="S32"
51+
CUSTOM_TPLG=""
52+
PCAN_MODE=0
53+
54+
shift 2
55+
while [ $# -gt 0 ]; do
56+
case "$1" in
57+
--format)
58+
FORMAT="$2"
59+
shift 2
60+
;;
61+
--pcan)
62+
PCAN_MODE=1
63+
shift 1
64+
;;
65+
--tplg)
66+
CUSTOM_TPLG="$2"
67+
shift 2
68+
;;
69+
*)
70+
usage
71+
;;
72+
esac
73+
done
74+
75+
case "$FORMAT" in
76+
S16) SF="16" ;;
77+
S24) SF="24" ;;
78+
S32) SF="32" ;;
79+
*) usage ;;
80+
esac
81+
82+
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
83+
SOF_ROOT="$(cd "$SCRIPT_DIR/../../../../" 2>/dev/null && pwd || true)"
84+
85+
if [[ -z "$SOF_WORKSPACE" ]]; then
86+
if [[ -d "$SOF_ROOT/tools/testbench" ]]; then
87+
SOF_WORKSPACE="$(cd "$SOF_ROOT/.." && pwd)"
88+
fi
89+
fi
90+
91+
: "${SOF_WORKSPACE:?SOF_WORKSPACE must point at the parent of the sof tree}"
92+
93+
TESTBENCH="${SOF_WORKSPACE}/sof/tools/testbench/build_testbench/install/bin/sof-testbench4"
94+
if [[ -n "$CUSTOM_TPLG" ]]; then
95+
TPLG="$CUSTOM_TPLG"
96+
elif [[ "$PCAN_MODE" -eq 1 ]]; then
97+
TPLG="${SOF_WORKSPACE}/sof/tools/build_tools/topology/topology2/development/sof-hda-benchmark-mfccmel40_10ms_pcan${SF}.tplg"
98+
else
99+
TPLG="${SOF_WORKSPACE}/sof/tools/build_tools/topology/topology2/development/sof-hda-benchmark-mfccmel40_10ms${SF}.tplg"
100+
fi
101+
102+
[ -x "$TESTBENCH" ] || { echo "Missing testbench: $TESTBENCH" >&2; exit 2; }
103+
[ -f "$TPLG" ] || { echo "Missing topology: $TPLG" >&2; exit 2; }
104+
[ -d "$WAV_ROOT" ] || { echo "Missing wav_root: $WAV_ROOT" >&2; exit 2; }
105+
command -v sox >/dev/null || { echo "sox not on PATH" >&2; exit 2; }
106+
107+
TMPDIR_LOCAL=$(mktemp -d -t sof_mfcc_mww.XXXXXX)
108+
trap 'rm -rf "$TMPDIR_LOCAL"' EXIT
109+
110+
convert_wav() {
111+
local src="$1"
112+
local dst="$2"
113+
114+
# Duplicate utterance with 100ms silence gap to warm up MFCC VAD noise floor
115+
case "$FORMAT" in
116+
S16) sox "$src" -p pad 0 0.10 | sox - "$src" -R --encoding signed-integer \
117+
-L -r 16000 -c 2 -b 16 "$dst" ;;
118+
S24) sox "$src" -p pad 0 0.10 | sox - "$src" -R --no-dither --encoding signed-integer \
119+
-L -r 16000 -c 2 -b 32 "$dst" vol 0.003906250000 ;;
120+
S32) sox "$src" -p pad 0 0.10 | sox - "$src" -R --no-dither --encoding signed-integer \
121+
-L -r 16000 -c 2 -b 32 "$dst" ;;
122+
esac
123+
}
124+
125+
process_wav() {
126+
local wav="$1"
127+
local out_dir="$2"
128+
local base
129+
base=$(basename "$wav" .wav)
130+
131+
local raw_in="${TMPDIR_LOCAL}/in.raw"
132+
local raw_out="${out_dir}/${base}.raw"
133+
local tb_log="${TMPDIR_LOCAL}/tb.log"
134+
135+
# Calculate expected hop count for the single (original) utterance
136+
local orig_samples
137+
orig_samples=$(soxi -s "$wav" 2>/dev/null || echo 0)
138+
local orig_sr
139+
orig_sr=$(soxi -r "$wav" 2>/dev/null || echo 16000)
140+
local orig_hops=$(( (orig_samples * 16000 / orig_sr) / 160 ))
141+
142+
mkdir -p "$out_dir"
143+
convert_wav "$wav" "$raw_in"
144+
echo " extracting: ${base}.raw"
145+
146+
if ! "$TESTBENCH" -d 0 \
147+
-r 16000 -c 2 -b "${FORMAT}_LE" -p 3,4 \
148+
-t "$TPLG" -i "$raw_in" -o "$raw_out" > "$tb_log" 2>&1; then
149+
cat "$tb_log" >&2
150+
echo "Error: testbench failed for $wav" >&2
151+
return 1
152+
fi
153+
154+
# Retain only the trailing second-half hops where VAD noise floor is fully settled
155+
if [[ "$orig_hops" -gt 0 ]]; then
156+
python3 - "$raw_out" "$orig_hops" "$PCAN_MODE" <<'PYEOF'
157+
import sys
158+
import numpy as np
159+
160+
raw_path = sys.argv[1]
161+
orig_hops = int(sys.argv[2])
162+
pcan_mode = int(sys.argv[3])
163+
164+
hop_size = 64 if pcan_mode else 184
165+
data = np.fromfile(raw_path, dtype=np.uint8)
166+
if data.size >= hop_size:
167+
u32 = data[: (data.size // 4) * 4].view(np.uint32)
168+
pos = np.flatnonzero(u32 == 0x6D666363) * 4
169+
if len(pos) > orig_hops:
170+
start_byte = pos[-orig_hops]
171+
data[start_byte:].tofile(raw_path)
172+
PYEOF
173+
fi
174+
}
175+
176+
total=0
177+
for label_dir in "$WAV_ROOT"/*/; do
178+
[ -d "$label_dir" ] || continue
179+
label=$(basename "$label_dir")
180+
case "$label" in _*) continue ;; esac
181+
out_dir="${FEAT_ROOT}/${label}"
182+
183+
echo "[label=${label}]"
184+
count=0
185+
for wav in "$label_dir"*.wav; do
186+
[ -f "$wav" ] || continue
187+
process_wav "$wav" "$out_dir"
188+
count=$((count + 1))
189+
done
190+
echo " wrote ${count} feature files to ${out_dir}"
191+
total=$((total + count))
192+
done
193+
194+
echo "-----------------------------------------------------------------"
195+
echo "Emitted ${total} mel40 feature files under ${FEAT_ROOT}"
196+
if [[ "$PCAN_MODE" -eq 1 ]]; then
197+
echo "Format per hop: 24-byte mfcc_data_header + 40 x int8 PCAN = 64 bytes"
198+
else
199+
echo "Format per hop: 24-byte mfcc_data_header + 40 x int32 Q9.23 = 184 bytes"
200+
fi
201+
echo "-----------------------------------------------------------------"

0 commit comments

Comments
 (0)