microWakeWord Documentation

repository·main·Indexed 21 days ago

https://github.com/ohf-voice/micro-wake-word

A TensorFlow-based wake word detection training framework designed for low-power microcontrollers. It produces models compatible with TensorFlow Lite for Microcontrollers using synthetic sample generation, MixConv neural networks, and a two-stage detection process involving feature extraction and streaming inference. The library includes tools for SpecAugment, spectrogram length adjustment, and data management via FeatureHandler for training custom wake words.

Tokens
13.6K
Snippets
34
Records
45
Agent score
74%

What's inside microWakeWord

  1. Overview of microWakeWord

    main

    microWakeWord is an open-source library designed for detecting custom wake words on low-power devices. It produces models optimized for TensorFlow Lite for Microcontrollers, aiming for low false accept and false reject rates in real-world environments.

    Note: The project is currently in early release. Training high-quality models is an advanced task that requires significant experimentation with hyperparameters and sample generation.

  2. How model training works

    main

    Training is a complex process intended for advanced users. Key aspects include:

    • Augmentation: Uses techniques like SpecAugment to mask time and frequency features.
    • Weight Selection: A two-step process where the priority is minimizing a specific metric (e.g., false accepts per hour on ambient noise) before maximizing accuracy.
    • Validation Strategy: Uses both standard sets (positive/negative samples) and ambient sets (real-world background sounds like music or household noise).
    • Training Mode: Models are trained in non-streaming mode (on the entire spectrogram) and then converted to a streaming model. This ensures prediction behaviors remain nearly identical.
    • Quantization: Models are quantized to improve performance on low-power hardware with minimal accuracy loss.
  3. How the detection process works

    main

    Detection occurs in two stages using a streaming inference approach:

    1. Feature Extraction (Preprocessing): Raw mono audio at a 16 kHz sample rate is processed into 40 spectrogram features every 10 ms. This uses a process similar to a Mel spectrogram but includes noise suppression and automatic gain control (AGC) to suit low-power devices. The window duration is 30 ms, with a 10 ms stride.
    2. Streaming Inference: A neural network using MixConv (mixed depthwise convolutions) performs inferences every 30 ms. The model uses the newest slice of feature data as input and returns a probability. A wake word is predicted only if the model consistently predicts it over multiple windows.
  4. Validation and testing procedures for wake words

    main

    Validation and testing sets are generated using the same augmentation pipeline as the training data.

    Dataset Splitting

    • Background Datasets: FSD50K, FMA, and WHAM! are split 90/10 between training and testing sets. Note that these datasets are not used in the validation set.

    Performance Metrics

    • False Accepts per Hour (Training): Estimated during the training phase using the VOiCES validation set and the DiPCo (Dinner Party Corpus).
    • False Accepts per Hour (Post-Training): Tested in streaming mode after training is complete using the DiPCo set.
  5. Data sources for training wake words

    main

    To train a wake word model, micro-wake-word utilizes a combination of synthetic speech, adversarial phrases, and various audio augmentations.

    Positive Samples (Wake Word Audio)

    • Generated Samples: Uses Piper sample generator for text-to-speech generation and openWakeWord for generating adversarial phrase samples.
    • Augmentations: Generated samples are augmented using background audio from FSD50K, FMA, and WHAM!, and reverberated using room impulse responses from the BIRD dataset.

    Negative Samples (Ambient Noise)

    To reduce false positives, the training process uses ambient noise as negative samples, categorized into:

    • Ambient Speech: Derived from the VOICES corpus and Common Voice.
    • Ambient Background: Derived from FSD50K, FMA (reverberated), and WHAM!.
  6. Generate wake word samples using piper-sample-generator

    main

    Use piper-sample-generator to create synthetic audio samples of your target wake word. You can generate a single sample for manual verification or a large batch for training.

    Tips for improvement:

    • Use phonetic spellings for the target_word to potentially improve sample quality.
    • Experiment with noise-scales and noise-scale-ws parameters.
    • Generate negative samples that are phonetically similar to the wake word.
    • Generate a high volume of samples with different pronunciations.
    # Generate 1 sample for verification
    !python3 piper-sample-generator/generate_samples.py "khum_puter" \
    --max-samples 1 \
    --batch-size 1 \
    --output-dir generated_samples
    
    # Generate a large batch for training
    !python3 piper-sample-generator/generate_samples.py "khum_puter" \
    --max-samples 1000 \
    --batch-size 100 \
    --output-dir generated_samples
  7. Train and evaluate microWakeWord models via CLI

    main

    The model_train_eval.py script provides a command-line interface to train neural network models (Inception or MixedNet) and evaluate them across different formats (TensorFlow SavedModel, TFLite non-streaming, and TFLite streaming/quantized).

    Usage Pattern

    1. Train a model: Set --train 1 and specify a model type (inception or mixednet).
    2. Evaluate a model: Set --train 0 and enable specific testing flags like --test_tflite_streaming or --test_tflite_nonstreaming_quantized.
    3. Resume training: Use --restore_checkpoint 1 to initialize weights and optimizer from an existing checkpoint.

    Key CLI Flags

    • --training_config: Path to the YAML configuration file.
    • --train: Set to 1 to run training, 0 to run only evaluation.
    • --restore_checkpoint: Set to 1 to resume interrupted training (requires adjusting learning rate and steps).
    • --use_weights: Which weight set to load for evaluation (best_weights or last_weights).
    • --verbosity: Log level (INFO, DEBUG, ERROR, FATAL, or WARN).

    Model Subcommands

    You must provide a model name as a subcommand:

    • inception: Uses Inception architecture (parameters defined via inception.model_parameters).
    • mixednet: Uses MixedNet architecture (parameters defined via mixednet.model_parameters).
    # Example: Train an inception model
    python microwakeword/model_train_eval.py --training_config my_config.yaml --train 1 inception
    
    # Example: Evaluate a quantized streaming TFLite model
    python microwakeword/model_train_eval.py --training_config my_config.yaml --train 0 --test_tflite_streaming_quantized 1 mixednet
  8. Install microWakeWord and dependencies

    main

    To set up the microWakeWord training environment, install the package and its specific dependencies. Note that certain packages are installed from forks to ensure compatibility with macOS and Jupyter environments.

    Important: Restart your Python session after installation is complete.

    # For macOS users, install the specific fork for pymicro-features
    if platform.system() == "Darwin":
        pip install 'git+https://github.com/puddly/pymicro-features@puddly/minimum-cpp-version'
    
    # Install audio-metadata from a fork to prevent breaking Jupyter
    pip install 'git+https://github.com/whatsnowplaying/audio-metadata@d4ebb238e6a401bb1a5aaaac60c9e2b3cb30929f'
    
    # Clone and install microWakeWord in editable mode
    git clone https://github.com/kahrendt/microWakeWord
    pip install -e ./microWakeWord
    import platform
    
    if platform.system() == "Darwin":
        !pip install 'git+https://github.com/puddly/pymicro-features@puddly/minimum-cpp-version'
    
    !pip install 'git+https://github.com/whatsnowplaying/audio-metadata@d4ebb238e6a401bb1a5aaaac60c9e2b3cb30929f'
    
    !git clone https://github.com/kahrendt/microWakeWord
    !pip install -e ./microWakeWord
  9. Start training a model with the basic training notebook

    main

    For advanced users looking to start training, the repository includes a basic_training_notebook.ipynb.

    Warning: This notebook is intended as a starting point only. While it will produce a model, it is unlikely to be usable for real-world applications without significant experimentation with hyperparameters and sample generation.

  10. Configure training hyperparameters in the config dictionary

    main

    The train function expects a config dictionary. If the following keys are missing, they are assigned default values. Note that many of these keys expect lists to allow for scheduled changes over training steps:

    KeyDefault ValueDescription
    training_steps[20000]List of steps for each training phase
    learning_rates[0.001]List of learning rates per phase
    mix_up_augmentation_prob[0.0]List of mix-up probabilities
    freq_mix_augmentation_prob[0.0]List of frequency mix probabilities
    time_mask_max_size[5]Max size for time masking
    time_mask_count[2]Number of time masks
    freq_mask_max_size[5]Max size for frequency masking
    freq_mask_count[2]Number of frequency masks
    positive_class_weight[1.0]Weight for the positive class
    negative_class_weight[1.0]Weight for the negative class
    train_dirRequiredDirectory for saving weights and checkpoints
    summaries_dirRequiredDirectory for TensorBoard summaries
    eval_step_intervalRequiredInterval of steps between evaluations
    minimization_metricOptionalMetric to minimize (e.g., for FAPH)
    maximization_metricOptionalMetric to maximize (e.g., accuracy)
    target_minimizationOptionalTarget value for the minimization metric

    Note: If you provide a list with length $N$, the training loop will iterate through $N$ phases, where each phase lasts for the number of steps specified in training_steps[i].

  11. Configure training parameters in YAML

    main

    The training process is controlled by a YAML configuration file. This file defines feature sets, training steps, and optimization hyperparameters.

    Feature Set Configuration

    Each entry in the features list defines a dataset used during training:

    • features_dir: Path to the feature directory.
    • sampling_weight: Weight for choosing a sample from this set in a batch.
    • penalty_weight: Weight used to penalize incorrect predictions from this set.
    • truth: True if the set contains positive (wake word) samples, False if it contains negative (ambient/speech) samples.
    • truncation_strategy: How to handle long spectrograms:
      • random: Choose a random portion.
      • truncate_start: Remove the start.
      • truncate_end: Remove the end.
      • split: Split into multiple spectrograms offset by 100ms (recommended for ambient sets).
    • type: The data format (e.g., mmap).

    Optimization Hyperparameters

    • training_steps: Total number of training steps.
    • positive_class_weight / negative_class_weight: Lists of weights corresponding to training steps.
    • learning_rates: List of learning rates for the Adam optimizer.
    • batch_size: Number of samples per batch.
    • target_minimization: The target value for the minimization_metric.
    • minimization_metric: The metric to minimize (e.g., loss, accuracy, recall, precision, false_positive_rate, false_negative_rate, ambient_false_positives). If set to None, the process only maximizes the maximization_metric.
    • maximization_metric: The metric to maximize (e.g., average_viable_recall).