yingzhi commited on
Commit
232893b
1 Parent(s): 44947f4

initial upload

Browse files
Files changed (7) hide show
  1. .gitattributes +2 -0
  2. README.md +114 -1
  3. custom_interface.py +122 -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,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from speechbrain.pretrained import Pretrained
3
+
4
+
5
+ class CustomEncoderDecoderASR(Pretrained):
6
+ """A ready-to-use Encoder-Decoder ASR model
7
+ The class can be used either to run only the encoder (encode()) to extract
8
+ features or to run the entire encoder-decoder model
9
+ (transcribe()) to transcribe speech. The given YAML must contains the fields
10
+ specified in the *_NEEDED[] lists.
11
+ Example
12
+ -------
13
+ >>> from speechbrain.pretrained import EncoderDecoderASR
14
+ >>> tmpdir = getfixture("tmpdir")
15
+ >>> asr_model = EncoderDecoderASR.from_hparams(
16
+ ... source="speechbrain/asr-crdnn-rnnlm-librispeech",
17
+ ... savedir=tmpdir,
18
+ ... )
19
+ >>> asr_model.transcribe_file("tests/samples/single-mic/example2.flac")
20
+ "MY FATHER HAS REVEALED THE CULPRIT'S NAME"
21
+ """
22
+
23
+ def __init__(self, *args, **kwargs):
24
+ super().__init__(*args, **kwargs)
25
+ self.tokenizer = self.hparams.tokenizer
26
+
27
+ def transcribe_file(self, path):
28
+ """Transcribes the given audiofile into a sequence of words.
29
+ Arguments
30
+ ---------
31
+ path : str
32
+ Path to audio file which to transcribe.
33
+ Returns
34
+ -------
35
+ str
36
+ The audiofile transcription produced by this ASR system.
37
+ """
38
+ waveform = self.load_audio(path)
39
+ # Fake a batch:
40
+ batch = waveform.unsqueeze(0)
41
+ rel_length = torch.tensor([1.0])
42
+ predicted_words = self.transcribe_batch(
43
+ batch, rel_length
44
+ )
45
+ return predicted_words[0]
46
+
47
+ def encode_batch(self, wavs):
48
+ """Encodes the input audio into a sequence of hidden states
49
+ The waveforms should already be in the model's desired format.
50
+ You can call:
51
+ ``normalized = EncoderDecoderASR.normalizer(signal, sample_rate)``
52
+ to get a correctly converted signal in most cases.
53
+ Arguments
54
+ ---------
55
+ wavs : torch.tensor
56
+ Batch of waveforms [batch, time, channels] or [batch, time]
57
+ depending on the model.
58
+ wav_lens : torch.tensor
59
+ Lengths of the waveforms relative to the longest one in the
60
+ batch, tensor of shape [batch]. The longest one should have
61
+ relative length 1.0 and others len(waveform) / max_length.
62
+ Used for ignoring padding.
63
+ Returns
64
+ -------
65
+ torch.tensor
66
+ The encoded batch
67
+ """
68
+ wavs = wavs.float()
69
+ wavs = wavs.to(self.device)
70
+ outputs = self.mods.wav2vec2(wavs)
71
+ outputs = self.mods.enc(outputs)
72
+ outputs = self.mods.ctc_lin(outputs)
73
+ return outputs
74
+
75
+ def transcribe_batch(self, wavs, wav_lens):
76
+ """Transcribes the input audio into a sequence of words
77
+ The waveforms should already be in the model's desired format.
78
+ You can call:
79
+ ``normalized = EncoderDecoderASR.normalizer(signal, sample_rate)``
80
+ to get a correctly converted signal in most cases.
81
+ Arguments
82
+ ---------
83
+ wavs : torch.tensor
84
+ Batch of waveforms [batch, time, channels] or [batch, time]
85
+ depending on the model.
86
+ wav_lens : torch.tensor
87
+ Lengths of the waveforms relative to the longest one in the
88
+ batch, tensor of shape [batch]. The longest one should have
89
+ relative length 1.0 and others len(waveform) / max_length.
90
+ Used for ignoring padding.
91
+ Returns
92
+ -------
93
+ list
94
+ Each waveform in the batch transcribed.
95
+ tensor
96
+ Each predicted token id.
97
+ """
98
+ with torch.no_grad():
99
+ wav_lens = wav_lens.to(self.device)
100
+ encoder_out = self.encode_batch(wavs)
101
+ p_ctc = self.hparams.log_softmax(encoder_out)
102
+ sequences = self.hparams.decoder(p_ctc, wav_lens)
103
+ predicted_words_list = []
104
+ for sequence in sequences:
105
+ predicted_tokens = self.tokenizer.convert_ids_to_tokens(
106
+ sequence
107
+ )
108
+ predicted_words = []
109
+ for c in predicted_tokens:
110
+ if c == "[CLS]":
111
+ continue
112
+ elif c == "[SEP]" or c == "[PAD]":
113
+ break
114
+ else:
115
+ predicted_words.append(c)
116
+ predicted_words_list.append(predicted_words)
117
+
118
+ return predicted_words_list
119
+
120
+ def forward(self, wavs, wav_lens):
121
+ """Runs full transcription - note: no gradients through decoding"""
122
+ 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