speechbrain
PyTorch
Chinese
CTC
wav2vec2
Adel-Moumen yingzhi commited on
Commit
5be032d
1 Parent(s): 44947f4

- initial upload (232893bd8f2f89de25ac9dc4df0b62bb9d4a4404)
- Update custom_interface.py (42c29e0a9b45031ff4171bc947cc205e5898f00f)


Co-authored-by: Yingzhi Wang <yingzhi@users.noreply.huggingface.co>

Files changed (7) hide show
  1. .gitattributes +2 -0
  2. README.md +114 -1
  3. custom_interface.py +130 -0
  4. example.wav +0 -0
  5. hyperparams.yaml +78 -0
  6. model.ckpt +3 -0
  7. wav2vec2.ckpt +3 -0
.gitattributes CHANGED
@@ -30,3 +30,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
30
  *.zip filter=lfs diff=lfs merge=lfs -text
31
  *.zst filter=lfs diff=lfs merge=lfs -text
32
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
30
  *.zip filter=lfs diff=lfs merge=lfs -text
31
  *.zst filter=lfs diff=lfs merge=lfs -text
32
  *tfevents* filter=lfs diff=lfs merge=lfs -text
33
+ model.ckpt filter=lfs diff=lfs merge=lfs -text
34
+ wav2vec2.ckpt filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,3 +1,116 @@
1
  ---
2
- license: apache-2.0
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ language: zh
3
+ thumbnail:
4
+ tags:
5
+ - automatic-speech-recognition
6
+ - CTC
7
+ - wav2vec2
8
+ - pytorch
9
+ - speechbrain
10
+ license: "apache-2.0"
11
+ datasets:
12
+ - aishell
13
+ metrics:
14
+ - cer
15
  ---
16
+
17
+ <iframe src="https://ghbtns.com/github-btn.html?user=speechbrain&repo=speechbrain&type=star&count=true&size=large&v=2" frameborder="0" scrolling="0" width="170" height="30" title="GitHub"></iframe>
18
+ <br/><br/>
19
+
20
+ # Wav2vec2-CTC for AISHELL (Mandarin Chinese)
21
+
22
+ This repository provides all the necessary tools to perform automatic speech
23
+ recognition from an end-to-end system pretrained on AISHELL (Mandarin Chinese)
24
+ within SpeechBrain. For a better experience, we encourage you to learn more about
25
+ [SpeechBrain](https://speechbrain.github.io).
26
+
27
+ The performance of the model is the following:
28
+
29
+ | Release | Dev CER | Test CER | GPUs | Full Results |
30
+ |:-------------:|:--------------:|:--------------:|:--------:|:--------:|
31
+ | 20-09-22 | 4.48 | 5.02 | 1xRTX8000 48GB | [Google Drive](https://drive.google.com/drive/folders/1GTB5IzQPl57j-0I1IpmvKg722Ti4ahLz?usp=sharing)|
32
+
33
+
34
+
35
+ ## Pipeline description
36
+
37
+ This ASR system is composed of 2 different but linked blocks:
38
+ - Tokenizer (from huggingface) that transforms words into chars and trained with
39
+ the training transcriptions of AISHELL-1.
40
+ - Acoustic model made of a wav2vec2 encoder and fully-connected layers
41
+
42
+ To Train this system from scratch, [see our SpeechBrain recipe](https://github.com/speechbrain/speechbrain/tree/develop/recipes/AISHELL-1/ASR/CTC).
43
+
44
+ The system is trained with recordings sampled at 16kHz (single channel).
45
+
46
+ ## Install SpeechBrain
47
+
48
+ First of all, please install SpeechBrain with the following command:
49
+
50
+ ```
51
+ pip install speechbrain
52
+ ```
53
+
54
+ Please notice that we encourage you to read our tutorials and learn more about
55
+ [SpeechBrain](https://speechbrain.github.io).
56
+
57
+ ### Transcribing your own audio files (in English)
58
+
59
+ ```python
60
+ from speechbrain.pretrained.interfaces import foreign_class
61
+ asr_model = foreign_class(source="speechbrain/asr-wav2vec2-ctc-aishell", pymodule_file="custom_interface.py", classname="CustomEncoderDecoderASR")
62
+ asr_model.transcribe_file("speechbrain/asr-wav2vec2-ctc-aishell/example.wav")
63
+ ```
64
+
65
+ ### Inference on GPU
66
+ To perform inference on the GPU, add `run_opts={"device":"cuda"}` when calling the `from_hparams` method.
67
+
68
+ ## Parallel Inference on a Batch
69
+ Please, [see this Colab notebook](https://colab.research.google.com/drive/1hX5ZI9S4jHIjahFCZnhwwQmFoGAi3tmu?usp=sharing) to figure out how to transcribe in parallel a batch of input sentences using a pre-trained model.
70
+
71
+ ### Training
72
+ The model was trained with SpeechBrain (Commit hash: '480dde87').
73
+ To train it from scratch follow these steps:
74
+ 1. Clone SpeechBrain:
75
+ ```bash
76
+ git clone https://github.com/speechbrain/speechbrain/git
77
+ ```
78
+ 2. Install it:
79
+ ```bash
80
+ cd speechbrain
81
+ pip install -r requirements.txt
82
+ pip install -e .
83
+ ```
84
+
85
+ 3. Run Training:
86
+ ```bash
87
+ cd recipes/AISHELL-1/ASR/CTC/
88
+ python train_with_wav2vec.py hparams/train_with_wav2vec.yaml --data_folder=your_data_folder
89
+ ```
90
+
91
+ You can find our training results (models, logs, etc) [here](https://drive.google.com/drive/folders/1GTB5IzQPl57j-0I1IpmvKg722Ti4ahLz?usp=sharing).
92
+
93
+ ### Limitations
94
+ The SpeechBrain team does not provide any warranty on the performance achieved by this model when used on other datasets.
95
+
96
+
97
+ # **About SpeechBrain**
98
+ - Website: https://speechbrain.github.io/
99
+ - Code: https://github.com/speechbrain/speechbrain/
100
+ - HuggingFace: https://huggingface.co/speechbrain/
101
+
102
+
103
+ # **Citing SpeechBrain**
104
+ Please, cite SpeechBrain if you use it for your research or business.
105
+
106
+ ```bibtex
107
+ @misc{speechbrain,
108
+ title={{SpeechBrain}: A General-Purpose Speech Toolkit},
109
+ author={Mirco Ravanelli and Titouan Parcollet and Peter Plantinga and Aku Rouhe and Samuele Cornell and Loren Lugosch and Cem Subakan and Nauman Dawalatabad and Abdelwahab Heba and Jianyuan Zhong and Ju-Chieh Chou and Sung-Lin Yeh and Szu-Wei Fu and Chien-Feng Liao and Elena Rastorgueva and François Grondin and William Aris and Hwidong Na and Yan Gao and Renato De Mori and Yoshua Bengio},
110
+ year={2021},
111
+ eprint={2106.04624},
112
+ archivePrefix={arXiv},
113
+ primaryClass={eess.AS},
114
+ note={arXiv:2106.04624}
115
+ }
116
+ ```
custom_interface.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Custom Interface for AISHELL-1 CTC inference
2
+ An external tokenizer is used so some special tokens
3
+ need to be specified during decoding
4
+
5
+ Authors
6
+ * Yingzhi Wang 2022
7
+ """
8
+
9
+ import torch
10
+ from speechbrain.pretrained import Pretrained
11
+
12
+
13
+ class CustomEncoderDecoderASR(Pretrained):
14
+ """A ready-to-use Encoder-Decoder ASR model
15
+ The class can be used either to run only the encoder (encode()) to extract
16
+ features or to run the entire encoder-decoder model
17
+ (transcribe()) to transcribe speech. The given YAML must contains the fields
18
+ specified in the *_NEEDED[] lists.
19
+ Example
20
+ -------
21
+ >>> from speechbrain.pretrained import EncoderDecoderASR
22
+ >>> tmpdir = getfixture("tmpdir")
23
+ >>> asr_model = EncoderDecoderASR.from_hparams(
24
+ ... source="speechbrain/asr-crdnn-rnnlm-librispeech",
25
+ ... savedir=tmpdir,
26
+ ... )
27
+ >>> asr_model.transcribe_file("tests/samples/single-mic/example2.flac")
28
+ "MY FATHER HAS REVEALED THE CULPRIT'S NAME"
29
+ """
30
+
31
+ def __init__(self, *args, **kwargs):
32
+ super().__init__(*args, **kwargs)
33
+ self.tokenizer = self.hparams.tokenizer
34
+
35
+ def transcribe_file(self, path):
36
+ """Transcribes the given audiofile into a sequence of words.
37
+ Arguments
38
+ ---------
39
+ path : str
40
+ Path to audio file which to transcribe.
41
+ Returns
42
+ -------
43
+ str
44
+ The audiofile transcription produced by this ASR system.
45
+ """
46
+ waveform = self.load_audio(path)
47
+ # Fake a batch:
48
+ batch = waveform.unsqueeze(0)
49
+ rel_length = torch.tensor([1.0])
50
+ predicted_words = self.transcribe_batch(
51
+ batch, rel_length
52
+ )
53
+ return predicted_words[0]
54
+
55
+ def encode_batch(self, wavs):
56
+ """Encodes the input audio into a sequence of hidden states
57
+ The waveforms should already be in the model's desired format.
58
+ You can call:
59
+ ``normalized = EncoderDecoderASR.normalizer(signal, sample_rate)``
60
+ to get a correctly converted signal in most cases.
61
+ Arguments
62
+ ---------
63
+ wavs : torch.tensor
64
+ Batch of waveforms [batch, time, channels] or [batch, time]
65
+ depending on the model.
66
+ wav_lens : torch.tensor
67
+ Lengths of the waveforms relative to the longest one in the
68
+ batch, tensor of shape [batch]. The longest one should have
69
+ relative length 1.0 and others len(waveform) / max_length.
70
+ Used for ignoring padding.
71
+ Returns
72
+ -------
73
+ torch.tensor
74
+ The encoded batch
75
+ """
76
+ wavs = wavs.float()
77
+ wavs = wavs.to(self.device)
78
+ outputs = self.mods.wav2vec2(wavs)
79
+ outputs = self.mods.enc(outputs)
80
+ outputs = self.mods.ctc_lin(outputs)
81
+ return outputs
82
+
83
+ def transcribe_batch(self, wavs, wav_lens):
84
+ """Transcribes the input audio into a sequence of words
85
+ The waveforms should already be in the model's desired format.
86
+ You can call:
87
+ ``normalized = EncoderDecoderASR.normalizer(signal, sample_rate)``
88
+ to get a correctly converted signal in most cases.
89
+ Arguments
90
+ ---------
91
+ wavs : torch.tensor
92
+ Batch of waveforms [batch, time, channels] or [batch, time]
93
+ depending on the model.
94
+ wav_lens : torch.tensor
95
+ Lengths of the waveforms relative to the longest one in the
96
+ batch, tensor of shape [batch]. The longest one should have
97
+ relative length 1.0 and others len(waveform) / max_length.
98
+ Used for ignoring padding.
99
+ Returns
100
+ -------
101
+ list
102
+ Each waveform in the batch transcribed.
103
+ tensor
104
+ Each predicted token id.
105
+ """
106
+ with torch.no_grad():
107
+ wav_lens = wav_lens.to(self.device)
108
+ encoder_out = self.encode_batch(wavs)
109
+ p_ctc = self.hparams.log_softmax(encoder_out)
110
+ sequences = self.hparams.decoder(p_ctc, wav_lens)
111
+ predicted_words_list = []
112
+ for sequence in sequences:
113
+ predicted_tokens = self.tokenizer.convert_ids_to_tokens(
114
+ sequence
115
+ )
116
+ predicted_words = []
117
+ for c in predicted_tokens:
118
+ if c == "[CLS]":
119
+ continue
120
+ elif c == "[SEP]" or c == "[PAD]":
121
+ break
122
+ else:
123
+ predicted_words.append(c)
124
+ predicted_words_list.append(predicted_words)
125
+
126
+ return predicted_words_list
127
+
128
+ def forward(self, wavs, wav_lens):
129
+ """Runs full transcription - note: no gradients through decoding"""
130
+ return self.transcribe_batch(wavs, wav_lens)
example.wav ADDED
Binary file (165 kB). View file
 
hyperparams.yaml ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ############################################################################
2
+ # Model: CTC-wav2vec2
3
+ # Encoder: wav2vec2
4
+ # Decoder: -
5
+ # Tokens: Char
6
+ # losses: CTC
7
+ # Training: AISHELL-1
8
+ # Authors: Yingzhi WANG 2022
9
+ # ############################################################################
10
+
11
+ wav2vec2_hub: TencentGameMate/chinese-wav2vec2-large
12
+ sample_rate: 16000
13
+
14
+ wav2vec_output_dim: 1024
15
+ dnn_neurons: 1024
16
+ freeze_wav2vec: False
17
+ dropout: 0.15
18
+
19
+ tokenizer: !apply:transformers.BertTokenizer.from_pretrained
20
+ pretrained_model_name_or_path: bert-base-chinese
21
+
22
+ output_neurons: 21128
23
+
24
+ # Decoding parameters
25
+ # Be sure that the bos and eos index match with the BPEs ones
26
+ blank_index: 0
27
+
28
+ enc: !new:speechbrain.nnet.containers.Sequential
29
+ input_shape: [null, null, !ref <wav2vec_output_dim>]
30
+ linear1: !name:speechbrain.nnet.linear.Linear
31
+ n_neurons: !ref <dnn_neurons>
32
+ bias: True
33
+ bn1: !name:speechbrain.nnet.normalization.BatchNorm1d
34
+ activation: !new:torch.nn.LeakyReLU
35
+ drop: !new:torch.nn.Dropout
36
+ p: !ref <dropout>
37
+ linear2: !name:speechbrain.nnet.linear.Linear
38
+ n_neurons: !ref <dnn_neurons>
39
+ bias: True
40
+ bn2: !name:speechbrain.nnet.normalization.BatchNorm1d
41
+ activation2: !new:torch.nn.LeakyReLU
42
+ drop2: !new:torch.nn.Dropout
43
+ p: !ref <dropout>
44
+ linear3: !name:speechbrain.nnet.linear.Linear
45
+ n_neurons: !ref <dnn_neurons>
46
+ bias: True
47
+ bn3: !name:speechbrain.nnet.normalization.BatchNorm1d
48
+ activation3: !new:torch.nn.LeakyReLU
49
+
50
+ wav2vec2: !new:speechbrain.lobes.models.huggingface_wav2vec.HuggingFaceWav2Vec2
51
+ source: !ref <wav2vec2_hub>
52
+ output_norm: True
53
+ freeze: !ref <freeze_wav2vec>
54
+ save_path: model_checkpoints
55
+
56
+ ctc_lin: !new:speechbrain.nnet.linear.Linear
57
+ input_size: !ref <dnn_neurons>
58
+ n_neurons: !ref <output_neurons>
59
+
60
+ log_softmax: !new:speechbrain.nnet.activations.Softmax
61
+ apply_log: True
62
+
63
+ decoder: !name:speechbrain.decoders.ctc_greedy_decode
64
+ blank_id: !ref <blank_index>
65
+
66
+ model: !new:torch.nn.ModuleList
67
+ - [!ref <enc>, !ref <ctc_lin>]
68
+
69
+ modules:
70
+ wav2vec2: !ref <wav2vec2>
71
+ enc: !ref <enc>
72
+ ctc_lin: !ref <ctc_lin>
73
+
74
+ pretrainer: !new:speechbrain.utils.parameter_transfer.Pretrainer
75
+ loadables:
76
+ wav2vec2: !ref <wav2vec2>
77
+ model: !ref <model>
78
+
model.ckpt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d793d99305f11da0a3c058e03e1fd370b5d93de512c008c0709e8b91dee608ea
3
+ size 99276064
wav2vec2.ckpt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1e4c8a9b2ab99c2c20d7b0d9c970615033faf51794cfce3e59edc214c92df65
3
+ size 1261923125