Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 67 additions & 8 deletions src/audio/mfcc/tune/setup_mfcc.m
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,17 @@ function setup_mfcc()
setup.num_mel_bins = 40;
setup.low_freq = 125;
setup.high_freq = 7500;
setup.mel_log = 'log10';
setup.top_db = 8.0;
setup.mmax_coef = 0;
setup.dynamic_mmax = true;
setup.remove_dc_offset = false;
setup.enable_vad = true;
setup.update_controls = true;
setup.pcan_strength = 0;
setup.pcan_offset = 0;
setup.pcan_gain_bits = 0;
setup.pcan_smoothing_coef = 0;
setup.tplg_fn = 'mel40_10ms.conf';
export_mfcc_setup(gen_cfg, setup);

Expand All @@ -77,6 +88,7 @@ function setup_mfcc()
setup.enable_dtx = false;
setup.dtx_trailing_silence_hops = 0;
setup.dtx_silence_hops_interval = 0;
setup.comment = 'enable_vad=0 enable_dtx=0: streaming MWW must see every hop, and VAD is not run.';
setup.tplg_fn = 'mel40_10ms_compress.conf';
export_mfcc_setup(gen_cfg, setup);

Expand Down Expand Up @@ -126,13 +138,43 @@ function setup_mfcc()
setup.pcan_smoothing_coef = 819;
setup.compress_output = true;
setup.update_controls = false;
setup.enable_vad = false;
setup.enable_vad = true;
setup.enable_dtx = false;
setup.dtx_trailing_silence_hops = 0;
setup.dtx_silence_hops_interval = 0;
setup.comment = ['enable_vad=1 enable_dtx=0 update_controls=0: VAD runs to populate energy/vad_flag\n' ...
'# for MWW gating; DTX off so every hop is still emitted; no kcontrol notifications.'];
setup.tplg_fn = 'mel40_10ms_pcan_compress.conf';
export_mfcc_setup(gen_cfg, setup);

% 40 mel bins, 10 ms hop with soft AGC int8 output for microWakeWord, a
% light alternative to PCAN. The int8 range -1.0 .. +1.0 covers 50 dB of
% log10 Mel power below the AGC normalized peak.
setup = get_mel_spectrogram_config();
setup.frame_length = 30.0;
setup.frame_shift = 10.0;
setup.num_mel_bins = 40;
setup.low_freq = 125;
setup.high_freq = 7500;
setup.mel_log = 'log10';
setup.mel_offset = 0;
setup.mel_scale = 0.4; % 1.0 is 25 dB
setup.enable_agc8 = true;
setup.agc_target = 3.0; % allows +75 dB boost for quiet input
setup.agc_floor = -1.0;
setup.agc_release = 10066; % 3 dB/s at 100 hops/s
setup.agc_release_speech = 335; % 0.1 dB/s
setup.compress_output = true;
setup.update_controls = false;
setup.enable_vad = true; % slower AGC release in speech, vad_flag for MWW
setup.enable_dtx = false;
setup.dtx_trailing_silence_hops = 0;
setup.dtx_silence_hops_interval = 0;
setup.comment = ['enable_vad=1 enable_dtx=0 update_controls=0: VAD runs to populate energy/vad_flag\n' ...
'# for the AGC release and MWW gating; DTX off so every hop is still emitted.'];
setup.tplg_fn = 'mel40_10ms_agc8_compress.conf';
export_mfcc_setup(gen_cfg, setup);

end

function cfg = get_mfcc_default_config()
Expand Down Expand Up @@ -181,6 +223,11 @@ function setup_mfcc()
cfg.pcan_offset = 80.0;
cfg.pcan_gain_bits = 21;
cfg.pcan_smoothing_coef = 819;
cfg.enable_agc8 = false;
cfg.agc_target = 0; % 0 = default 0.25
cfg.agc_floor = 0; % 0 = default -2.0
cfg.agc_release = 0; % Q9.23 per hop, 0 = default 4194
cfg.agc_release_speech = 0; % Q9.23 per hop, 0 = default 419
end

function cfg = get_mel_spectrogram_config()
Expand Down Expand Up @@ -229,6 +276,11 @@ function setup_mfcc()
cfg.pcan_offset = 80.0;
cfg.pcan_gain_bits = 21;
cfg.pcan_smoothing_coef = 819;
cfg.enable_agc8 = false;
cfg.agc_target = 0; % 0 = default 0.25
cfg.agc_floor = 0; % 0 = default -2.0
cfg.agc_release = 0; % Q9.23 per hop, 0 = default 4194
cfg.agc_release_speech = 0; % Q9.23 per hop, 0 = default 419
end

function export_mfcc_setup(gen_cfg, cfg)
Expand Down Expand Up @@ -266,8 +318,12 @@ function export_mfcc_setup(gen_cfg, cfg)
v = cfg.dtx_trailing_silence_hops; [b8, j] = add_w16b(v, b8, j); % DTX trailing silence hops
v = cfg.dtx_silence_hops_interval; [b8, j] = add_w16b(v, b8, j); % DTX silence frame interval
v = cfg.pcan_smoothing_coef; [b8, j] = add_w32b(v, b8, j); % PCAN smoothing coef in Q14
v = q_convert(cfg.agc_target, 7); [b8, j] = add_w16b(v, b8, j); % AGC8 target in Q8.7
v = q_convert(cfg.agc_floor, 7); [b8, j] = add_w16b(v, b8, j); % AGC8 floor in Q8.7
v = cfg.agc_release; [b8, j] = add_w16b(v, b8, j); % AGC8 release in Q9.23
v = cfg.agc_release_speech; [b8, j] = add_w16b(v, b8, j); % AGC8 speech release in Q9.23
% Reserved
for i = 1:4
for i = 1:2
[b8, j] = add_w32b(0, b8, j);
end

Expand Down Expand Up @@ -309,22 +365,25 @@ function export_mfcc_setup(gen_cfg, cfg)
v = cfg.update_controls; [b8, j] = add_w8b(v, b8, j); % bool
v = cfg.compress_output; [b8, j] = add_w8b(v, b8, j); % bool
v = cfg.enable_pcan; [b8, j] = add_w8b(v, b8, j); % bool
% reserved_bool[3]
for i = 1:3
v = cfg.enable_agc8; [b8, j] = add_w8b(v, b8, j); % bool
% reserved_bool[2]
for i = 1:2
[b8, j] = add_w8b(0, b8, j);
end

%% Export
tplg_fn = [gen_cfg.mfcc_conf_path cfg.tplg_fn];
howto = 'cd src/audio/mfcc/tune; octave setup_mfcc.m';
if isfield(cfg, 'comment')
howto = sprintf('%s\n# %s', howto, sprintf(cfg.comment));
end
switch gen_cfg.tplg_ver
case 1
sof_tplg_write(tplg_fn, b8, "DEF_MFCC_PRIV", ...
"Exported with script setup_mfcc.m", ...
"cd src/audio/mfcc/tune; octave setup_mfcc.m");
"Exported with script setup_mfcc.m", howto);
case 2
sof_tplg2_write(tplg_fn, b8, "mfcc_config", ...
"Exported MFCC configuration", ...
"cd src/audio/mfcc/tune; octave setup_mfcc.m");
"Exported MFCC configuration", howto);
otherwise
error("Illegal tplg_ver, use 1 for topology v1 or 2 topology v2.");
end
Expand Down
2 changes: 1 addition & 1 deletion src/audio/microwakeword/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ The built-in models and the bytes control use the same model blob: `struct sof_m
- the trigger threshold (Q0.8) and the number of averaged probabilities, so each model carries its own trigger tuning,
- reserved words.

A bare TFLite flatbuffer without the header is still accepted and uses the default trigger settings `MWW_DETECT_THRESHOLD_Q8` and `MWW_DETECT_AVG_LEN`.
A bare TFLite flatbuffer without the header is still accepted and uses the default trigger settings `MWW_DETECT_THRESHOLD_Q8` and `MWW_DETECT_AVG_LEN`. The tune scripts `sof_mww_train_pcan.py` and `sof_mww_int8_state.py` emit the blobs with the header.

---

Expand Down
123 changes: 79 additions & 44 deletions src/audio/microwakeword/tune/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,21 @@ This directory contains offline scripts to train, quantize, verify, and export s
- [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.
- [sof_mww_generate_keyword_dataset.sh](sof_mww_generate_keyword_dataset.sh): Multi-speaker generation with `piper-sample-generator` (LibriTTS-R).
- [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.
- [sof_mww_prepare_common_voice.py](sof_mww_prepare_common_voice.py): Selects a repeatable set of Mozilla Common Voice (CC0) sentence clips from extracted language releases into a `speech` class of continuous speech negatives, with a per-speaker limit and a transcript exclusion regex for the keyword. Common Voice is downloaded from Mozilla Data Collective.
- [sof_mww_split_utterances.py](sof_mww_split_utterances.py): Splits recordings of a repeated keyword into one 48 kHz mono WAV per utterance. Speech is detected from the 100 - 7000 Hz band energy of 20 ms frames, and the room noise before and after each utterance is kept up to `--max-pad` and `--max-pad-after` seconds. Needs `scipy`.
- [sof_mww_anonymize_clips.py](sof_mww_anonymize_clips.py): Copies keyword clips to `<label>_NNN.wav` names in a fixed-seed shuffled order, so the names do not reveal the speakers.
- [sof_mww_asr_transcribe.py](sof_mww_asr_transcribe.py): Transcribes a directory of WAVs with an OpenVINO Whisper model (e.g. `whisper-medium-int4-ov`) into a `file,text` CSV, to find generated keyword clips that are not recognizable. Needs `openvino`, `transformers` and `soundfile`.
- [sof_mww_asr_filter.py](sof_mww_asr_filter.py): Deletes the WAVs listed in a `sof_mww_asr_transcribe.py` CSV whose transcription does not match any `--pass` string, compared case-insensitively without punctuation. E.g. `python3 sof_mww_asr_filter.py --pass banana banana_asr.csv ~/train/mww_wov2/wavs/banana`. Use `--dry-run` to only report.

2. **DSP Feature Extraction:**
- [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.
- [sof_mfcc_extract_features.sh](sof_mfcc_extract_features.sh): Emits SOF MFCC hop records for a labelled WAV dataset by running the SOF host testbench with a 10 ms mel-40 topology: 184-byte hops ($24\text{-byte } \texttt{struct mfcc\_data\_header} + 40 \times \text{int32\_t}$ Q9.23 mel values) or with `--pcan` 64-byte hops ($24\text{-byte header} + 40 \times \text{int8\_t}$).

3. **Model Training & Export:**
- [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.
- [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:
- `mww_model_data_<name>.h`: Built-in model header selected by Kconfig.
- `<name>.conf`: ALSA Topology v2 configuration blob for `Object.Base.data`.
- `<name>.txt`: Runtime `sof-ctl` binary control file.
- `sof_mww_train_pipeline.sh --hard-negative-keyword <phrase>`: Synthesizes
Piper TTS competing wake phrases into `unknown/` as hard negatives before
feature extraction. Set `PIPER_VOICE` and optionally
`HARD_NEGATIVE_SAMPLES` (default: 200 per phrase).

For a `Hi Intel` model, useful phrases include `hey siri`, `hey google`,
`ok google`, `alexa`, `hey copilot`, and `hey jarvis`.

4. **Off-Device Verification & Automation:**
- [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.
- [sof_mww_train_pipeline.sh](sof_mww_train_pipeline.sh): End-to-end automation runner.
- [sof_mww_train_pcan.py](sof_mww_train_pcan.py): All-in-one PCAN (int8 feature) trainer working directly from WAVs. Features come from the SOF MFCC component run in `sof-testbench4` with `sof-hda-benchmark-mfccmel40_10ms_pcan32.tplg` (`--frontend sof`, default) or from TensorFlow `audio_microfrontend` (`--frontend tf`). Each clip is embedded in 2 s of continuous background from the ambient classes at 5..35 dB SNR with a random 0..29 ms phase, and the mixture is peak-normalized to a random level in `--level-min-dbfs`..`--level-max-dbfs` (default -45..-6 dBFS). Training windows are 160 hops so they cover the streaming model's 149-hop receptive field, and the evaluation streams each clip after background as on the device. The model input quantization is pinned to the firmware int8 PCAN scale (666/256, zero point -128). Digital silence (all-zero PCM, e.g. a muted or not yet started capture) is a hard negative (`--digital-silence N` streams, default 300): zeros only, background followed by zeros, and zeros followed by background. Windows from these streams are also trained from stream start, where the streaming model state is still zero, and the evaluation report includes a `digital_silence` class streamed from a state reset. The network is described in [model_architecture.md](model_architecture.md).
- [sof_mww_int8_state.py](sof_mww_int8_state.py): Converts the float32 streaming state of a model (`.tflite` or `mww_model_data_<name>.h`) to int8 without changing any output, removing the per-inference DEQUANTIZE/QUANTIZE operations, and emits the header and the sof-ctl blob. `sof_mww_train_pcan.py` applies it to the models it exports; use it directly for older models. It also wraps a model in the old format without the `struct sof_mww_model_hdr` model header into the current format, and `--features`, `--threshold` and `--avg-len` change the header settings of a model.

4. **Automation:**
- [sof_mww_pcan_train_fruits.sh](sof_mww_pcan_train_fruits.sh): Trains the strawberry, banana and orange PCAN models for the 3-keyword topology. Positives can optionally be ASR screened (`ASR_SCREEN=true`) on the clean TTS output before noise augmentation, and each fruit model gets the other fruits as `unknown` negatives since all detectors run at the same time. Real recordings of a keyword in `REAL_SAMPLES_ROOT/<label>/` are trimmed to the speech with 1 s of room noise before and 0.25 s after it, augmented with `sof_mww_generate_keyword_dataset_from_dir.sh` and added to the TTS positives. The trainer labels the keyword at the last detected speech of a clip, so a long pause after the word would teach the model to trigger late. `TRAIN_<FRUIT>=false` only generates the positives of a fruit for the cross-fruit negatives.

---

Expand Down Expand Up @@ -102,31 +96,14 @@ To use recorded human speech recordings instead of synthetic TTS:
```
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).

You can also pass `--keyword-dir <label>:<path>` directly to `sof_mww_train_pipeline.sh`:
```bash
./sof_mww_train_pipeline.sh \
--keyword-dir hi_intel:/path/to/recorded/audio \
--name hi_intel \
~/wov/wavs ~/wov/feats ~/wov/model
```

### 2. Run End-to-End Retraining Pipeline
With the `mww-train` virtual environment activated:
```bash
source ~/venvs/mww-train/bin/activate
./sof_mww_train_pipeline.sh \
--keyword hey_jarvis \
--name hey_jarvis \
~/wov/wavs ~/wov/feats ~/wov/model
```

---

### Training Multiple Keyword Variants into the Same Model

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**:

#### 1. Generate Datasets for Both Phrases
Generate datasets for both phrases, then pass both labels to `sof_mww_train_pcan.py` with repeated `--keyword` arguments (e.g. `--keyword hey_jarvis --keyword hi_jarvis --name hey_jarvis`). Both phrase directories are pooled as the positive class, and the exported model triggers when either phrase is spoken.

```bash
./sof_mww_generate_keyword_dataset.sh \
--keyword "hey jarvis" --label hey_jarvis \
Expand All @@ -135,18 +112,76 @@ You can train a single wake-word model to trigger on multiple spoken variants (s
~/wov/wavs
```

#### 2. Train with Multiple `--keyword` Arguments
Pass both directory labels to the training pipeline and specify `--name hey_jarvis`:
---

### Training 8-bit PCAN Models with SOF Testbench Features

The firmware MWW models (`banana`, `hi_intel`, `orange`, `strawberry`) take int8 PCAN features from the `mel40_10ms_pcan_compress` MFCC profile. Train them with `sof_mww_train_pcan.py`, which computes the features with the SOF MFCC component in `sof-testbench4` so they are bit-exact with the firmware.

MFCC can alternatively produce int8 features with its soft AGC (AGC8, `mel40_10ms_agc8_compress` profile), a lighter frontend without PCAN. Train such models with `--features agc8`, which uses `sof-hda-benchmark-mfccmel40_10ms_agc832.tplg`, and build the WoV topology with `MWW_FEATURES=agc8`. A model works only with the feature type it was trained with.

#### 1. Build the Testbench and the PCAN Benchmark Topology
```bash
cd $SOF_WORKSPACE/sof
scripts/build-tools.sh
scripts/rebuild-testbench.sh
```
This provides:
- `tools/testbench/build_testbench/install/bin/sof-testbench4`
- `tools/build_tools/topology/topology2/development/sof-hda-benchmark-mfccmel40_10ms_pcan32.tplg`
- `tools/build_tools/topology/topology2/development/sof-hda-benchmark-mfccmel40_10ms_agc832.tplg`

#### 2. Prepare the Dataset
The trainer expects one WAV directory per class under the dataset root: the positive class named by `--keyword`, `unknown/` for non-target speech, and `ambient/` for silence, noise and babble. The ambient clips are also used as continuous background for every training clip.

```bash
cd src/audio/microwakeword/tune

# Positives from synthetic multi-speaker TTS (piper venv active) ...
MAX_SAMPLES=1000 ./sof_mww_generate_keyword_dataset.sh \
--keyword banana --label banana ~/train/mww_banana/wavs

# ... or from recorded speech, one --src-dir per recording set
MAX_SAMPLES=3500 ./sof_mww_generate_keyword_dataset_from_dir.sh \
--src-dir ~/rec/set1 --label hi_intel \
--src-dir ~/rec/set2 --label hi_intel \
~/train/mww_hi_intel/wavs

# Negatives from Speech Commands v2, silence slices moved to ambient/
N_UNKNOWN=5000 N_SILENCE=1500 ./sof_mww_prepare_silence_unknown.sh ~/train/mww_banana/wavs
mkdir -p ~/train/mww_banana/wavs/ambient
mv ~/train/mww_banana/wavs/silence/*.wav ~/train/mww_banana/wavs/ambient/
rmdir ~/train/mww_banana/wavs/silence
```

Optional additions that improved the models:
- Multi-speaker cafeteria babble from the DEMAND `PCAFETER_16k` set (CC-BY-4.0) sliced into 5 s clips in `ambient/`. This reduced random false positives.
- For synthetic keywords, a few hundred clips per single-speaker Piper voice with `sof_mww_generate_keyword_dataset_piper_tts.sh --voice <model.onnx>`. Keep them around 20-30 % of the positives so the model does not learn the voices instead of the word.
- Competing wake phrases (`hey siri`, `ok google`, `alexa`, ...) synthesized with `sof_mww_generate_keyword_dataset_piper_tts.sh` into `unknown/` as hard negatives.
- Continuous sentence speech in `speech/`, e.g. 3000 Common Voice clips with `sof_mww_prepare_common_voice.py --out-dir ~/train/mww_hi_intel/wavs/speech ~/Music/CommonVoice/*/`. The `unknown/` clips are single words and only get windows near their start and end, while `speech/` clips are windowed over their whole length.

#### 3. Train
```bash
source ~/venvs/mww-train/bin/activate
./sof_mww_train_pipeline.sh \
--keyword hey_jarvis \
--keyword hi_jarvis \
--name hey_jarvis \
~/wov/wavs ~/wov/feats ~/wov/model
python3 sof_mww_train_pcan.py \
--wav-root ~/train/mww_banana/wavs \
--keyword banana --name banana \
--out-dir ~/train/mww_banana/model_pcan \
--frontend sof \
--level-min-dbfs -45 --level-max-dbfs -6 \
--pos-level-copies 2 \
--class-weight-neg 3.0 \
--threshold 0.5 --avg-len 4 \
--epochs 30
```
`--testbench` and `--tplg` default to the paths above under `$SOF_WORKSPACE`. `--threshold` and `--avg-len` are stored in the model blob header and used by the firmware trigger: it triggers when the mean of the last `--avg-len` probabilities reaches the threshold, and the streaming evaluation report uses the same rule.

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.
#### 4. Deploy
```bash
cp ~/train/mww_banana/model_pcan/mww_model_data_banana.h $SOF_WORKSPACE/sof/src/audio/microwakeword/
cp ~/train/mww_banana/model_pcan/banana.txt $SOF_WORKSPACE/sof/tools/ctl/ipc4/mww/
```
The header is the built-in model selected by Kconfig. The `.txt` blob can be loaded at runtime with `sof-ctl`. Both contain the model with the `struct sof_mww_model_hdr` header, which carries the `--features`, `--threshold` and `--avg-len` settings of the training to the firmware trigger.

---

Expand Down
Loading
Loading