README.md 15.3 KB
Newer Older
1
# DeepSpeech2 on PaddlePaddle
2

3 4 5 6 7 8 9 10 11 12 13
*DeepSpeech2 on PaddlePaddle* is an open-source implementation of end-to-end Automatic Speech Recognition (ASR) engine, based on [Baidu's Deep Speech 2 paper](http://proceedings.mlr.press/v48/amodei16.pdf), with [PaddlePaddle](https://github.com/PaddlePaddle/Paddle) platform. Our vision is to empower both industrial application and academic research on speech-to-text, via an easy-to-use, efficent and scalable integreted implementation, including training & inferencing module, distributed [PaddleCloud](https://github.com/PaddlePaddle/cloud) training, and demo deployment. Besides, several pre-trained models for both English and Mandarin speech are also released.

## Table of Contents
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Getting Started](#getting-started)
- [Data Preparation](#data-preparation)
- [Training a Model](#training-a-model)
- [Inference and Evaluation](#inference-and-evaluation)
- [Distributed Cloud Training](#distributed-cloud-training)
- [Hyper-parameters Tuning](#hyper-parameters-tuning)
14
- [Training for Mandarin Language](#training-for-mandarin-language)
15 16 17 18 19 20 21
- [Trying Live Demo with Your Own Voice](#trying-live-demo-with-your-own-voice)
- [Experiments and Benchmarks](#experiments-and-benchmarks)
- [Questions and Help](#questions-and-help)

## Prerequisites
- Only support Python 2.7
- PaddlePaddle the latest version (please refer to the [Installation Guide](https://github.com/PaddlePaddle/Paddle#installation))
22

23
## Installation
24

25
Please install the [prerequisites](#prerequisites) above before moving onto this quick installation.
26

27
```
28 29
git clone https://github.com/PaddlePaddle/models.git
cd models/deep_speech_2
Y
yangyaming 已提交
30
sh setup.sh
31
```
32

33
## Getting Started
34

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
Several shell scripts provided in `./examples` will help us to quickly give it a try, including training, inferencing, evaluation and demo deployment.

Most of the scripts in `./examples` are configured with 8 GPUs. If you don't have 8 GPUs available, please modify `CUDA_VISIBLE_DEVICE` and `--trainer_count`. If you don't have any GPU available, please set `--use_gpu` to False.

Let's take a tiny sampled subset of [LibriSpeech dataset](http://www.openslr.org/12/) for instance.

- Go to directory

    ```
    cd examples/librispeech_tiny
    ```

    Notice that this is only a toy example with a tiny sampled set of LibriSpeech. If we would like to try with the complete LibriSpeech (would take much a longer time for training), please go to `examples/librispeech` instead.
- Prepare the libripseech data

    ```
    sh preprare_data.sh
    ```

    `prepare_data.sh` downloads dataset, generates file manifests, collects normalizer' statitics and builds vocabulary for us. Once the running is done, we'll find our LibriSpeech data (not full in this "tiny" example) downloaded in `~/.cache/paddle/dataset/speech/Libri` and several manifest files as well as one mean stddev file generated in `./data/librispeech_tiny`, for the further model training. It needs to be run for only once.
- Train your own ASR model

    ```
    sh run_train.sh
    ```

    `run_train.sh` starts a training job, with training logs printed to stdout and model checkpoint of every pass/epoch saved to `./checkpoints`. We can resume the training from these checkpoints, or use them for inference, evalutiaton and deployment.
- Case inference with an existing model

    ```
    sh run_infer.sh
    ```

    `run_infer.sh` will quickly show us speech-to-text decoding results for several (default: 10) audio samples with an existing model. Since the model is only trained on a subset of LibriSpeech, the performance might not be very good. We can download a well-trained model and then do the inference:

    ```
    sh download_model_run_infer.sh
    ```
- Evaluate an existing model

    ```
    sh run_test.sh
    ```

    `run_test.sh` evaluates the model with Word Error Rate (or Character Error Rate) measurement. Similarly, we can also download a well-trained model and test its performance:

    ```
    sh download_model_run_test.sh
    ```
- Try out a live demo with your own voice

    Until now, we have trained and tested an ASR model quantitively and qualitatively with existing audios. But we haven't try the model with our own speech. `demo_server.sh` and `demo_client.sh` helps quickly build up a demo ASR engine with the trained model, enabling us to test and play around with the demo with our own voice.

    We start the server in one console by entering:

    ```
    sh run_demo_server.sh
    ```

    and start the client in another console by entering:

    ```
    sh run_demo_client.sh
    ```

    Then, in the client console, press the `whitespace` key, hold, and start speaking. Until we finish our ulterance, we release the key to let the speech-to-text results show in the console.

    Notice that `run_demo_client.sh` must be run in a machine with a microphone device, while `run_demo_server.sh` could be run in one without any audio recording device, e.g. any remote server. Just be careful to update `run_demo_server.sh` and `run_demo_client.sh` with the actual accessable IP address and port, if the server and client are running with two seperate machines. Nothing has to be done if running in one single machine.

    This demo will first download a pre-trained Mandarin model (trained with 3000 hours of internal speech data). If we would like to try some other model, just update `model_path` argument in the script.  
    
More detailed information are provided in the following sections.

Wish you a happy journey with the DeepSpeech2 ASR engine!

110

111
## Data Preparation
112

113 114 115 116
#### Generate Manifest

*DeepSpeech2 on PaddlePaddle* accepts a textual **manifest** file as its data set interface. A manifest file summarizes a set of speech data, with each line containing the meta data (e.g. filepath, transcription, duration) of one audio clip, in [JSON](http://www.json.org/) format, just as:

117
```
118 119
{"audio_filepath": "/home/work/.cache/paddle/Libri/134686/1089-134686-0001.flac", "duration": 3.275, "text": "stuff it into you his belly counselled him"}
{"audio_filepath": "/home/work/.cache/paddle/Libri/134686/1089-134686-0007.flac", "duration": 4.275, "text": "a cold lucid indifference reigned in his soul"}
120
```
121

122
To use any custom data, we only need to generate such manifest files to summarize the dataset. Given such summarized manifests, training, inference and all other modules can be aware of where to access the audio files, as well as their meta data including the transcription labels.
123

124
For example script to generate such manifest files, please refer to `data/librispeech/librispeech.py`, which download and generate manifests for LibriSpeech dataset.
X
Xinghai Sun 已提交
125

126
#### Compute Mean & Stddev for Normalizer
X
Xinghai Sun 已提交
127

128
To perform z-score normalization (zero-mean, unit stddev) upon audio features, we have to estimate in advance the mean and standard deviation of the features, with sampled training audios:
X
Xinghai Sun 已提交
129 130

```
131 132 133 134 135
python tools/compute_mean_std.py \
--num_samples 2000 \
--specgram_type linear \
--manifest_paths data/librispeech/manifest.train \
--output_path data/librispeech/mean_std.npz
X
Xinghai Sun 已提交
136 137
```

138
It will compute the mean and standard deviation of power spectgram feature with 2000 random sampled audio clips listed in `data/librispeech/manifest.train` and save the results to `data/librispeech/mean_std.npz` for further usage.
139

X
Xinghai Sun 已提交
140

141
#### Build Vocabulary
X
Xinghai Sun 已提交
142

143
A list of possible characters is required to convert the target transcription into list of token indices for training and in docoders convert from them back to text. Such a character-based vocabulary can be build with `tools/build_vocab.py`.
Y
Yibing Liu 已提交
144 145

```
146 147 148 149
python tools/build_vocab.py \
--count_threshold 0 \
--vocab_path data/librispeech/eng_vocab.txt \
--manifest_paths data/librispeech/manifest.train
Y
Yibing Liu 已提交
150
```
151

152 153 154
It will build a vocabuary file of `data/librispeeech/eng_vocab.txt` with all transcription text in `data/librispeech/manifest.train`, without character truncation.

#### More Help
155

156
For more help on arguments:
157 158

```
159
python data/librispeech/librispeech.py --help
160
python tools/compute_mean_std.py --help
161
python tools/build_vocab.py --help
162 163
```

164
## Training a model
165

166
`train.py` is the main caller of the training module. We list several usage below.
167

168
- Start training from scratch with 8 GPUs:
169

170 171 172
    ```
    CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python train.py --trainer_count 8
    ```
173

174 175 176 177 178 179 180 181 182 183 184
- Start training from scratch with 16 CPUs:

    ```
    python train.py --use_gpu False --trainer_count 16
    ```
- Resume training from a checkpoint (an existing model):

    ```
    CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python train.py \
    --init_model_path CHECKPOINT_PATH_TO_RESUME_FROM
    ```
185

186
For more help on arguments:
187 188 189 190

```
python train.py --help
```
191
or refer to `example/librispeech/run_train.sh.
192

193
#### Augment the Dataset for Training
Y
Yibing Liu 已提交
194

195 196 197 198 199 200 201 202 203 204 205 206
Data augmentation has often been a highly effective technique to boost the deep learning performance. We augment our speech data by synthesizing new audios with small random perterbation (label-invariant transformation) added upon raw audios. We don't have to do the syntheses by ourselves, as it is already embeded into the data provider and is done on the fly, randomly for each epoch.

Six optional augmentation components are provided for us to configured and inserted into the processing pipeline.

  - Volume Perturbation
  - Speed Perturbation
  - Shifting Perturbation
  - Online Beyesian normalization
  - Noise Perturbation (need background noise audio files)
  - Impulse Response (need impulse audio files)

In order to inform the trainer of what augmentation components we need and what their processing orders are, we are required to prepare a *augmentation configuration file* in JSON format. For example:
Y
Yibing Liu 已提交
207 208

```
209 210 211 212 213 214 215 216 217 218 219 220
[{
    "type": "speed",
    "params": {"min_speed_rate": 0.95,
               "max_speed_rate": 1.05},
    "prob": 0.6
},
{
    "type": "shift",
    "params": {"min_shift_ms": -5,
               "max_shift_ms": 5},
    "prob": 0.8
}]
Y
Yibing Liu 已提交
221 222
```

223
When the `--augment_conf_file` argument of `trainer.py` is set to the path of the above example configuration file, each audio clip in each epoch will be processed: with 60% of chance, it will first be speed perturbed with a uniformly random sampled speed-rate between 0.95 and 1.05, and then with 80% of chance it will be shifted in time with a random sampled offset between -5 ms and 5 ms. Finally this newly synthesized audio clip will be feed into the feature extractor for further training.
224

225
For configuration examples, please refer to `conf/augmenatation.config.example`.
Y
Yibing Liu 已提交
226

227
Be careful when we are utilizing the data augmentation technique, as improper augmentation will instead do harm to the training, due to the enlarged train-test gap.
228

229
## Inference and Evaluation
230

231
#### Prepare Language Model
Y
Yibing Liu 已提交
232

233 234 235 236 237 238 239 240 241 242 243 244 245
A language model is required to improve the decoder's performance. We have prepared two language models (with lossy compression) for users to download and try. One is for English and the other is for Mandarin. Please refer to `examples/librispeech/download_model.sh` and `examples/mandarin_demo/download_model.sh` for their urls. If you wish to train your own better language model, please refer to [KenLM](https://github.com/kpu/kenlm) for tutorials.

TODO: any other requirements or tips to add?

#### Speech-to-text Inference

We provide a inference module `infer.py` to infer, decode and visualize speech-to-text results for several given audio clips, which might help to have a intuitive and qualitative evaluation of the ASR model performance.

- Inference with GPU:

    ```
    CUDA_VISIBLE_DEVICES=0 python infer.py --trainer_count 1
    ```
Y
Yibing Liu 已提交
246

247 248 249 250 251 252 253 254 255
- Inference with CPU:

    ```
    python infer.py --use_gpu False
    ```

We provide two CTC decoders: *CTC greedy decoder* and *CTC beam search decoder*. The *CTC greedy decoder* is an implementation of the simple best-path decoding algorithm, selecting at each timestep the most likely token, thus being greedy and locally optimal. The [*CTC beam search decoder*](https://arxiv.org/abs/1408.2873) otherwise utilzied a heuristic breadth-first gragh search for arriving at a near global optimality; it requires a pre-trained KenLM language model for better scoring and ranking sentences. The decoder type can be set with argument `--decoding_method`.

For more help on arguments:
256 257 258 259

```
python infer.py --help
```
260
or refer to `example/librispeech/run_infer.sh.
Y
Yibing Liu 已提交
261

262
#### Evaluate a Model
Y
Yibing Liu 已提交
263

264 265 266 267 268 269 270 271 272
To evaluate a model quantitively, we can run:

- Evaluation with GPU:

    ```
    CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python test.py --trainer_count 8
    ```

- Evaluation with CPU:
Y
Yibing Liu 已提交
273

274 275 276 277 278 279 280
    ```
    python test.py --use_gpu False
    ```

The error rate (default: word error rate, can be set with `--error_rate_type`) will be printed.

For more help on arguments:
Y
Yibing Liu 已提交
281 282

```
283
python test.py --help
Y
Yibing Liu 已提交
284
```
285
or refer to `example/librispeech/run_test.sh.
Y
Yibing Liu 已提交
286

287
## Hyper-parameters Tuning
Y
Yibing Liu 已提交
288

289
The hyper-parameters $\alpha$ (coefficient for language model scorer) and $\beta$ (coefficient for word count scorer) for the [*CTC beam search decoder*](https://arxiv.org/abs/1408.2873) often have a significant impact on the decoder's performance. It'd be better to re-tune them on validation samples after the accustic model is renewed.
Y
Yibing Liu 已提交
290

291
`tools/tune.py` performs a 2-D grid search over the hyper-parameter $\alpha$ and $\beta$. We have to provide the range of $\alpha$ and $\beta$, as well as the number of attempts.
Y
Yibing Liu 已提交
292

293
- Tuning with GPU:
Y
Yibing Liu 已提交
294

295 296 297 298 299 300 301 302 303 304
    ```
    CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python tools/tune.py \
    --trainer_count 8 \
    --alpha_from 0.1 \
    --alpha_to 0.36 \
    --num_alphas 14 \
    --beta_from 0.05 \
    --beta_to 1.0 \
    --num_betas 20
    ```
Y
Yibing Liu 已提交
305

306
- Tuning with CPU:
Y
Yibing Liu 已提交
307

308 309 310 311 312
    ```
    python tools/tune.py --use_gpu False
    ```

After tuning, we can reset $\alpha$ and $\beta$ in the inference and evaluation modules to see if they can really improve the ASR performance.
Y
Yibing Liu 已提交
313 314 315 316

```
python tune.py --help
```
317
or refer to `example/librispeech/run_tune.sh.
Y
Yibing Liu 已提交
318

319
TODO: add figure.
320

321 322 323 324 325
## Distributed Cloud Training

If you wish to train DeepSpeech2 on PaddleCloud, please refer to
[Train DeepSpeech2 on PaddleCloud](https://github.com/PaddlePaddle/models/tree/develop/deep_speech_2/cloud).

326 327
## Training for Mandarin Language

328
## Trying Live Demo with Your Own Voice
329

330 331 332 333 334 335 336 337 338 339
A real-time ASR demo is built for users to try out the ASR model with their own voice. Please do the following installation on the machine you'd like to run the demo's client (no need for the machine running the demo's server).

For example, on MAC OS X:

```
brew install portaudio
pip install pyaudio
pip install pynput
```
After a model and language model is prepared, we can first start the demo's server:
340 341 342 343

```
CUDA_VISIBLE_DEVICES=0 python demo_server.py
```
344
And then in another console, start the demo's client:
345 346 347 348

```
python demo_client.py
```
349
On the client console, press and hold the "white-space" key on the keyboard to start talking, until you finish your speech and then release the "white-space" key. The decoding results (infered transcription) will be displayed.
350

351
It could be possible to start the server and the client in two seperate machines, e.g. `demo_client.py` is usually started in a machine with a microphone hardware, while `demo_server.py` is usually started in a remote server with powerful GPUs. Please first make sure that these two machines have network access to each other, and then use `--host_ip` and `--host_port` to indicate the server machine's actual IP address (instead of the `localhost` as default) and TCP port, in both `demo_server.py` and `demo_client.py`.
352

353
## Experiments and Benchmarks
354

355
## Questions and Help