
Repositori ini berisi versi terakhir dari toolkit Pytorch-Kaldi (Pytorch-Kaldi-V1.0). Untuk melihat versi sebelumnya (Pytorch-Kaldi-V0.1), klik di sini.
Jika Anda menggunakan kode ini atau bagiannya, silakan kutip makalah berikut:
M. Ravanelli, T. Parcollet, Y. Bengio, "The Pytorch-Kaldi Toule Toolkit Pengenalan", Arxiv
@inproceedings{pytorch-kaldi,
title = {The PyTorch-Kaldi Speech Recognition Toolkit},
author = {M. Ravanelli and T. Parcollet and Y. Bengio},
booktitle = {In Proc. of ICASSP},
year = {2019}
}
Toolkit ini dirilis di bawah Lisensi Internasional Creative Commons Attribution 4.0 . Anda dapat menyalin, mendistribusikan, memodifikasi kode untuk tujuan penelitian, komersial dan non-komersial. Kami hanya meminta untuk mengutip makalah kami yang dirujuk di atas.
Untuk meningkatkan transparansi dan replikasi hasil pengenalan suara, kami memberi pengguna kemungkinan untuk melepaskan model Pytorch-Kaldi mereka dalam repositori ini. Jangan ragu untuk menghubungi kami (atau melakukan permintaan tarik) untuk itu. Selain itu, jika kertas Anda menggunakan Pytorch-Kaldi, juga dimungkinkan untuk mengiklankannya di repositori ini.
Lihat video pengantar pendek di pytorch-kaldi toolkit
Kami dengan senang hati mengumumkan bahwa Proyek Pidato (https://speechbrain.github.io/) sekarang publik! Kami sangat mendorong pengguna untuk bermigrasi ke PidatoBrain. Ini adalah proyek yang jauh lebih baik yang sudah mendukung beberapa tugas pemrosesan bicara, seperti pengenalan suara, pengenalan pembicara, SLU, peningkatan bicara, pemisahan bicara, pemrosesan sinyal multi-mikrofon dan banyak lainnya.
Tujuannya adalah untuk mengembangkan toolkit tunggal , fleksibel , dan ramah pengguna yang dapat digunakan untuk dengan mudah mengembangkan sistem ucapan canggih untuk pengenalan suara (baik ujung-ke-ujung dan HMM-DNN), pengenalan pembicara, pemisahan wicara, pemrosesan sinyal multi-mikrofon (misalnya, beamforming), pembelajaran swasembar Sandan, dan banyak lainnya.
Proyek ini akan dipimpin oleh Mila dan disponsori oleh Samsung, Nvidia, Dolby. SpeechBrain juga akan mendapat manfaat dari kolaborasi dan keahlian perusahaan lain seperti Facebook/Pytorch, IBMResearch, Fluentai.
Kami secara aktif mencari kolaborator. Jangan ragu untuk menghubungi kami di pidato [email protected] jika Anda tertarik untuk berkolaborasi.
Berkat sponsor kami, kami juga dapat menyewa pekerja magang yang bekerja di Mila di Proyek Pidato. Kandidat yang ideal adalah mahasiswa PhD dengan pengalaman di Pytorch dan Teknologi Bicara (kirim CV Anda ke pidatonya
Pengembangan PidatoBrain akan membutuhkan beberapa bulan sebelum memiliki repositori yang berfungsi. Sementara itu, kami akan terus memberikan dukungan untuk proyek Pytorch-Kaldi.
Pantau terus!
Proyek Pytorch-Kaldi bertujuan untuk menjembatani kesenjangan antara Kaldi dan toolkit Pytorch, mencoba mewarisi efisiensi Kaldi dan fleksibilitas Pytorch. Pytorch-Kaldi tidak hanya antarmuka sederhana antara toolkit ini, tetapi juga menanamkan beberapa fitur yang berguna untuk mengembangkan pengukur suara modern. Misalnya, kode ini dirancang khusus untuk secara alami model akustik yang ditentukan pengguna. Sebagai alternatif, pengguna dapat mengeksploitasi beberapa jaringan saraf yang telah diimplementasikan sebelumnya yang dapat disesuaikan menggunakan file konfigurasi intuitif. Pytorch-Kaldi mendukung berbagai fitur dan label aliran serta kombinasi jaringan saraf, memungkinkan penggunaan arsitektur saraf yang kompleks. Toolkit ini dirilis secara publik bersama dengan dokumentasi yang kaya dan dirancang untuk bekerja dengan baik secara lokal atau pada kelompok HPC.
Beberapa fitur dari versi baru toolkit Pytorch-Kaldi:
export KALDI_ROOT=/home/mirco/kaldi-trunk
PATH=$PATH:$KALDI_ROOT/tools/openfst
PATH=$PATH:$KALDI_ROOT/src/featbin
PATH=$PATH:$KALDI_ROOT/src/gmmbin
PATH=$PATH:$KALDI_ROOT/src/bin
PATH=$PATH:$KALDI_ROOT//src/nnetbin
export PATH
Ingatlah untuk mengubah variabel Kaldi_root menggunakan jalur Anda. Sebagai tes pertama untuk memeriksa instalasi, buka shell bash, ketik "copy-feats" atau "hmm-info" dan pastikan tidak ada kesalahan yang muncul.
Jika belum selesai, instal pytorch (http://pytorch.org/). Kami menguji kode kami di Pytorch 1.0 dan Pytorch 0.4. Versi Pytorch yang lebih lama cenderung meningkatkan kesalahan. Untuk memeriksa instalasi Anda, ketik "Python" dan, setelah dimasukkan ke dalam konsol, ketik "impor obor", dan pastikan tidak ada kesalahan yang muncul.
Kami sarankan menjalankan kode pada mesin GPU. Pastikan Perpustakaan CUDA (https://developer.nvidia.com/Cuda-Downloads) diinstal dan berfungsi dengan benar. Kami menguji sistem kami di CUDA 9.0, 9.1 dan 8.0. Pastikan Python diinstal (kode diuji dengan Python 2.7 dan Python 3.7). Meskipun tidak wajib, kami sarankan menggunakan Anaconda (https://anaconda.org/anaconda/python).
19 Februari 2019: Pembaruan:
batch_size_train = 128*12 | 64*10 | 32*2
Garis di atas berarti: lakukan 12 zaman dengan 128 batch, 10 zaman dengan 64 batch, dan 2 zaman dengan 32 batch. Formalisme serupa dapat digunakan untuk tingkat pembelajaran dan penjadwalan putus sekolah. Lihat bagian ini untuk informasi lebih lanjut.
5 Feb. 2019: Pembaruan:
Catatan pada versi berikutnya: Di versi berikutnya, kami berencana untuk lebih memperluas fungsi toolkit kami, mendukung lebih banyak model dan fitur fitur. Tujuannya adalah untuk membuat toolkit kami cocok untuk tugas-tugas terkait pidato lainnya seperti pengenalan ucapan end-to-end, identifikasi pembicara, bercak kata kunci, pemisahan bicara, deteksi aktivitas bicara, peningkatan bicara, dll. Jika Anda ingin mengusulkan beberapa fungsi baru, tolong beri kami umpan balik Anda dengan mengisi survei ini.
Untuk menginstal Pytorch-Kaldi, lakukan langkah-langkah berikut:
git clone https://github.com/mravanelli/pytorch-kaldi
pip install -r requirements.txt
Berikut ini, kami memberikan tutorial singkat dari toolkit Pytorch-Kaldi berdasarkan dataset Timit yang populer.
Pastikan Anda memiliki dataset Timit. Jika tidak, itu dapat diunduh dari situs web LDC (https://catalog.ldc.upenn.edu/ldc93s1).
Pastikan instalasi Kaldi dan Pytorch baik -baik saja. Pastikan juga bahwa jalur Kaldi Anda saat ini berfungsi (Anda harus menambahkan jalur Kaldi ke dalam .bashrc seperti yang dilaporkan dalam bagian "prasyarat"). Misalnya, ketik "copy-feats" dan "hmm-info" dan pastikan tidak ada kesalahan yang muncul.
Jalankan garis dasar Kaldi S5 dari Timit. Langkah ini diperlukan untuk menghitung fitur dan label yang kemudian digunakan untuk melatih jaringan saraf Pytorch. Kami sarankan menjalankan resep Timit S5 lengkap (termasuk pelatihan DNN):
cd kaldi/egs/timit/s5
./run.sh
./local/nnet/run_dnn.sh
Dengan cara ini semua file yang diperlukan dibuat dan pengguna dapat secara langsung membandingkan hasil yang diperoleh Kaldi dengan yang dicapai dengan toolkit kami.
steps/align_fmllr.sh --nj 4 data/dev data/lang exp/tri3 exp/tri3_ali_dev
steps/align_fmllr.sh --nj 4 data/test data/lang exp/tri3 exp/tri3_ali_test
Jika Anda ingin menggunakan keberpihakan DNN (seperti yang disarankan), ketik:
steps/nnet/align.sh --nj 4 data-fmllr-tri3/train data/lang exp/dnn4_pretrain-dbn_dnn exp/dnn4_pretrain-dbn_dnn_ali
steps/nnet/align.sh --nj 4 data-fmllr-tri3/dev data/lang exp/dnn4_pretrain-dbn_dnn exp/dnn4_pretrain-dbn_dnn_ali_dev
steps/nnet/align.sh --nj 4 data-fmllr-tri3/test data/lang exp/dnn4_pretrain-dbn_dnn exp/dnn4_pretrain-dbn_dnn_ali_test
Kami memulai tutorial ini dengan jaringan MLP yang sangat sederhana yang dilatih pada fitur MFCC. Sebelum meluncurkan percobaan, lihat file konfigurasi CFG/TIMIT_BASELINES/TIMIT_MLP_MFCC_BASIC.CFG . Lihat deskripsi file konfigurasi untuk deskripsi terperinci dari semua bidangnya.
Ubah file konfigurasi sesuai dengan jalur Anda. Secara khusus:
Untuk menghindari kesalahan, pastikan semua jalur dalam file CFG ada. Harap, hindari menggunakan jalur yang mengandung variabel bash karena jalur dibaca secara harfiah dan tidak diperluas secara otomatis (misalnya, penggunaan/home/mirco/Kaldi-trunk/eGS/timit/s5/exp/dnn4_prain-dbn_dn_ali bukan $ Kaldi_root/EGS/TIMIT/S5/S5/EXP, bukan $ KALDI_ROOT/EGS/TIMIT/S5/S5/EXP, bukan $ KALDI_ROOT/EGS/TIMIT/S5/S5/S5/EXP, bukannya $ KALDI_ROOT/EGS/TIGS/S5/S5/S5/S5/
python run_exp.py cfg/TIMIT_baselines/TIMIT_MLP_mfcc_basic.cfg
Script ini memulai percobaan ASR lengkap dan melakukan pelatihan, validasi, maju, dan langkah decoding. Bilah kemajuan menunjukkan evolusi semua fase yang disebutkan di atas. Script run_exp.py secara progresif membuat file berikut di direktori output:
Perhatikan bahwa Anda dapat menghentikan percobaan kapan saja. Jika Anda menjalankan lagi skrip itu akan secara otomatis dimulai dari potongan terakhir yang diproses dengan benar. Pelatihan bisa memakan waktu beberapa jam, tergantung pada GPU yang tersedia. Perhatikan juga bahwa jika Anda ingin mengubah beberapa parameter file konfigurasi (misalnya, n_chunks =, fea_lst =, batch_size_train =, ..) Anda harus menentukan folder output yang berbeda (output_folder =).
Debug: Jika Anda mengalami beberapa kesalahan, kami sarankan untuk melakukan pemeriksaan berikut:
Lihatlah output standar.
Jika tidak membantu, perhatikan file log.log.
Lihatlah fungsi run_nn ke dalam pustaka Core.py. Tambahkan beberapa cetakan di berbagai bagian fungsi untuk mengisolasi masalah dan cari tahu masalahnya.
Pada akhir pelatihan, tingkat kesalahan telepon (per%) ditambahkan ke dalam file res.res. Untuk melihat detail lebih lanjut tentang hasil decoding, Anda dapat masuk ke "decoding_test" di folder output dan melihat ke berbagai file yang dibuat. Untuk contoh khusus ini, kami memperoleh file res.res berikut:
ep=000 tr=['TIMIT_tr'] loss=3.398 err=0.721 valid=TIMIT_dev loss=2.268 err=0.591 lr_architecture1=0.080000 time(s)=86
ep=001 tr=['TIMIT_tr'] loss=2.137 err=0.570 valid=TIMIT_dev loss=1.990 err=0.541 lr_architecture1=0.080000 time(s)=87
ep=002 tr=['TIMIT_tr'] loss=1.896 err=0.524 valid=TIMIT_dev loss=1.874 err=0.516 lr_architecture1=0.080000 time(s)=87
ep=003 tr=['TIMIT_tr'] loss=1.751 err=0.494 valid=TIMIT_dev loss=1.819 err=0.504 lr_architecture1=0.080000 time(s)=88
ep=004 tr=['TIMIT_tr'] loss=1.645 err=0.472 valid=TIMIT_dev loss=1.775 err=0.494 lr_architecture1=0.080000 time(s)=89
ep=005 tr=['TIMIT_tr'] loss=1.560 err=0.453 valid=TIMIT_dev loss=1.773 err=0.493 lr_architecture1=0.080000 time(s)=88
.........
ep=020 tr=['TIMIT_tr'] loss=0.968 err=0.304 valid=TIMIT_dev loss=1.648 err=0.446 lr_architecture1=0.002500 time(s)=89
ep=021 tr=['TIMIT_tr'] loss=0.965 err=0.304 valid=TIMIT_dev loss=1.649 err=0.446 lr_architecture1=0.002500 time(s)=90
ep=022 tr=['TIMIT_tr'] loss=0.960 err=0.302 valid=TIMIT_dev loss=1.652 err=0.447 lr_architecture1=0.001250 time(s)=88
ep=023 tr=['TIMIT_tr'] loss=0.959 err=0.301 valid=TIMIT_dev loss=1.651 err=0.446 lr_architecture1=0.000625 time(s)=88
%WER 18.1 | 192 7215 | 84.0 11.9 4.2 2.1 18.1 99.5 | -0.583 | /home/mirco/pytorch-kaldi-new/exp/TIMIT_MLP_basic5/decode_TIMIT_test_out_dnn1/score_6/ctm_39phn.filt.sys
Yang dicapai per (%) adalah 18,1%. Perhatikan bahwa mungkin ada beberapa variabilitas dalam hasil, karena inisialisasi yang berbeda pada mesin yang berbeda. Kami percaya bahwa rata -rata kinerja yang diperoleh dengan benih inisialisasi yang berbeda (yaitu, mengubah benih lapangan dalam file konfigurasi) sangat penting untuk Timit karena variabilitas kinerja alami mungkin sepenuhnya menyembunyikan bukti eksperimental. Kami memperhatikan standar deviasi sekitar 0,2% untuk percobaan Timit.
Jika Anda ingin mengubah fitur, Anda harus menghitungnya terlebih dahulu dengan Kaldi Toolkit. Untuk menghitung fitur FBank, Anda harus membuka $ Kaldi_root/EGS/TIMIT/S5/RUN.SH dan menghitungnya dengan baris berikut:
feadir=fbank
for x in train dev test; do
steps/make_fbank.sh --cmd "$train_cmd" --nj $feats_nj data/$x exp/make_fbank/$x $feadir
steps/compute_cmvn_stats.sh data/$x exp/make_fbank/$x $feadir
done
Kemudian, ubah file konfigurasi yang disebutkan di atas dengan daftar fitur baru. Jika Anda sudah menjalankan resep Timit Kaldi lengkap, Anda dapat langsung menemukan fitur FMLLR di $ Kaldi_root/EGS/TIMIT/S5/Data-FMLLR-TRI3 . Jika Anda memberi makan jaringan saraf dengan fitur -fitur tersebut, Anda harus mengharapkan peningkatan kinerja yang substansial, karena adopsi adaptasi pembicara.
Di folder Timit_Baseline, kami mengusulkan beberapa contoh lain dari kemungkinan Timit Baselines. Demikian pula dengan contoh sebelumnya, Anda dapat menjalankannya hanya dengan mengetik:
python run_exp.py $cfg_file
Ada beberapa contoh dengan berulang (timit_rnn*, timit_lstm*, timit_gru*, timit_ligru*) dan arsitektur CNN (timit_cnn*). Kami juga mengusulkan model yang lebih canggih (TIMIT_DNN_LIGRU_DNN_MFCC+FBANK+FMLLR.CFG) di mana kami menggunakan kombinasi jaringan saraf feed-forward dan berulang yang diumpankan oleh fitur MFCC, FBank, dan FMLLR. Perhatikan bahwa file konfigurasi yang terakhir sesuai dengan arsitektur terbaik yang dijelaskan dalam makalah referensi. Seperti yang mungkin Anda lihat dari file konfigurasi yang disebutkan di atas, kami meningkatkan kinerja ASR dengan memasukkan beberapa trik seperti regularisasi monofon (yaitu, kami bersama-sama memperkirakan target konteks yang bergantung pada konteks dan independen konteks). Tabel berikut melaporkan hasil yang diperoleh dengan menjalankan sistem yang terakhir (rata -rata per%):
| Model | MFCC | fbank | fmllr |
|---|---|---|---|
| Baseline Kaldi DNN | ----- | ------ | 18.5 |
| MLP | 18.2 | 18.7 | 16.7 |
| Rnn | 17.7 | 17.2 | 15.9 |
| Sru | ----- | 16.6 | ----- |
| LSTM | 15.1 | 14.3 | 14.5 |
| Gru | 16.0 | 15.2 | 14.9 |
| Li-gru | 15.5 | 14.9 | 14.2 |
Hasil menunjukkan bahwa, seperti yang diharapkan, fitur FMLLR mengungguli MFCCS dan koefisien FBanks, berkat proses adaptasi speaker. Model berulang secara signifikan mengungguli MLP One standar, terutama saat menggunakan arsitektur LSTM, GRU, dan LI-Gru, yang secara efektif menangani gradien menghilang melalui gerbang multiplikasi. Hasil terbaik per = $ 14,2 $% diperoleh dengan model Li-gru [2,3], yang didasarkan pada gerbang tunggal dan dengan demikian menghemat 33% dari perhitungan atas GRU standar.
Hasil terbaik sebenarnya diperoleh dengan arsitektur yang lebih kompleks yang menggabungkan fitur MFCC, FBANK, dan FMLLR (lihat CFG/Timi_Baselines/Timit_MFCC_FBANK_FMLLR_LIGRU_BEST.cfg ). Sepengetahuan kami, per = 13,8% yang dicapai oleh sistem yang terakhir menghasilkan kinerja yang diterbitkan terbaik pada test-set Timit.
Unit berulang sederhana (SRU) adalah model berulang yang efisien dan sangat paralelisasi. Kinerja pada ASR lebih buruk daripada model LSTM, GRU, dan LI-Gru standar, tetapi secara signifikan lebih cepat. SRU diimplementasikan di sini dan dijelaskan dalam makalah berikut:
T. Lei, Y. Zhang, Si Wang, H. Dai, Y. Artzi, "Unit Berulang Sederhana untuk Rekurensi yang Sangat Paralelisasi, Proc. EMNLP 2018. Arxiv
Untuk melakukan eksperimen dengan model ini, gunakan file konfigurasi CFG/TIMIT_BASELINES/TIMIT_SRU_FBANK.cfg . Sebelum Anda harus menginstal model menggunakan pip install sru dan Anda harus membatalkan komentar "Impor SRU" di neural_networks.py .
Anda dapat secara langsung membandingkan hasil Anda dengan kami dengan pergi ke sini. Di repositori eksternal ini, Anda dapat menemukan semua folder yang berisi file yang dihasilkan.
Langkah-langkah untuk menjalankan Pytorch-Kaldi pada dataset Librispeech mirip dengan yang dilaporkan di atas untuk Timit. Tutorial berikut didasarkan pada sub-set 100h , tetapi dapat dengan mudah diperluas ke dataset lengkap (960H).
mkdir exp/tri4b/decode_tgsmall_train_clean_100 && cp exp/tri4b/trans.* exp/tri4b/decode_tgsmall_train_clean_100/
. ./cmd.sh ## You'll want to change cmd.sh to something that will work on your system.
. ./path.sh ## Source the tools/utils (import the queue.pl)
gmmdir=exp/tri4b
for chunk in train_clean_100 dev_clean test_clean; do
dir=fmllr/$chunk
steps/nnet/make_fmllr_feats.sh --nj 10 --cmd "$train_cmd"
--transform-dir $gmmdir/decode_tgsmall_$chunk
$dir data/$chunk $gmmdir $dir/log $dir/data || exit 1
compute-cmvn-stats --spk2utt=ark:data/$chunk/spk2utt scp:fmllr/$chunk/feats.scp ark:$dir/data/cmvn_speaker.ark
done
# aligments on dev_clean and test_clean
steps/align_fmllr.sh --nj 30 data/train_clean_100 data/lang exp/tri4b exp/tri4b_ali_clean_100
steps/align_fmllr.sh --nj 10 data/dev_clean data/lang exp/tri4b exp/tri4b_ali_dev_clean_100
steps/align_fmllr.sh --nj 10 data/test_clean data/lang exp/tri4b exp/tri4b_ali_test_clean_100
python run_exp.py cfg/Librispeech_baselines/libri_MLP_fmllr.cfg
Jika Anda ingin menggunakan model berulang, Anda dapat menggunakan libri_rnn_fmllr.cfg , libri_lstm_fmllr.cfg , libri_gru_fmllr.cfg , atau libri_ligru_fmllr.cfg . Pelatihan model berulang mungkin memakan waktu beberapa hari (tergantung pada GPU yang diadopsi). Kinerja yang diperoleh dengan grafik TGSMALL dilaporkan dalam tabel berikut:
| Model | Wer% |
|---|---|
| MLP | 9.6 |
| LSTM | 8.6 |
| Gru | 8.6 |
| Li-gru | 8.6 |
Hasil ini diperoleh tanpa menambahkan penyelamatan kisi (yaitu, hanya menggunakan grafik TGSmall ). Anda dapat meningkatkan kinerja dengan menambahkan penyelamatan kisi dengan cara ini (jalankan dari folder Kaldi_Decoding_Script dari Pytorch-Kaldi):
data_dir=/data/milatmp1/ravanelm/librispeech/s5/data/
dec_dir=/u/ravanelm/pytorch-Kaldi-new/exp/libri_fmllr/decode_test_clean_out_dnn1/
out_dir=/u/ravanelm/pytorch-kaldi-new/exp/libri_fmllr/
steps/lmrescore_const_arpa.sh $data_dir/lang_test_{tgsmall,fglarge}
$data_dir/test_clean $dec_dir $out_dir/decode_test_clean_fglarge || exit 1;
Hasil akhir yang diperoleh menggunakan rescoring ( fglarge ) dilaporkan dalam tabel berikut:
| Model | Wer% |
|---|---|
| MLP | 6.5 |
| LSTM | 6.4 |
| Gru | 6.3 |
| Li-gru | 6.2 |
Anda dapat melihat hasil yang diperoleh di sini.
Skrip utama untuk menjalankan percobaan ASR adalah run_exp.py . Skrip python ini melakukan pelatihan, validasi, maju, dan langkah -langkah decoding. Pelatihan dilakukan selama beberapa zaman, yang secara progresif memproses semua materi pelatihan dengan jaringan saraf yang dipertimbangkan. Setelah setiap zaman pelatihan, langkah validasi dilakukan untuk memantau kinerja sistem pada data yang ditahan . Pada akhir pelatihan, fase maju dilakukan dengan menghitung probabilitas posterior dari dataset uji yang ditentukan. Probabilitas posterior dinormalisasi oleh prior mereka (menggunakan file hitungan) dan disimpan ke dalam file Ark. Langkah decoding kemudian dilakukan untuk mengambil urutan terakhir dari kata -kata yang diucapkan oleh pembicara dalam kalimat pengujian.
Skrip run_exp.py mengambil input file konfigurasi global (misalnya, cfg/timit_mlp_mfcc.cfg ) yang menentukan semua opsi yang diperlukan untuk menjalankan percobaan lengkap. Kode run_exp.py memanggil fungsi lain run_nn (lihat Core.py Library) yang melakukan pelatihan, validasi, dan operasi maju pada setiap bagian data. Fungsi run_nn mengambil input file konfigurasi spesifik chunk (misalnya, exp/timit_mlp_mfcc/exp_files/train_timit_tr+timit_dev_ep000_ck00.cfg*) yang menentukan semua parameter yang diperlukan untuk menjalankan eksperimen satu-chunk. Fungsi run_nn menghasilkan beberapa info filles (mis., Exp/timit_mlp_mfcc/exp_files/train_timit_tr+timit_dev_ep000_ck00.info ) yang merangkum kerugian dan kesalahan chunk yang diproses.
Hasilnya dirangkum ke dalam file res.res , sementara kesalahan dan peringatan dialihkan ke file log.log .
Ada dua jenis file konfigurasi (file CFG global dan spesifik chunk). Keduanya dalam format INI dan dibaca, diproses, dan dimodifikasi dengan ConfigParser Library of Python. File global berisi beberapa bagian, yang menentukan semua langkah utama dari percobaan pengenalan suara (pelatihan, validasi, maju, dan decoding). Struktur file konfigurasi dijelaskan dalam file prototipe (lihat misalnya proto/global.proto ) yang tidak hanya mencantumkan semua bagian dan bidang yang diperlukan tetapi juga menentukan jenis setiap bidang yang memungkinkan. Misalnya, n_ep = int (1, INF) berarti bahwa bidang N_EP (yaitu, jumlah zaman pelatihan) harus berupa bilangan bulat mulai dari 1 hingga INF. Demikian pula, LR = float (0, INF) berarti bahwa bidang LR (yaitu, tingkat pembelajaran) harus mengapung mulai dari 0 hingga INF. Setiap upaya untuk menulis file konfigurasi yang tidak sesuai dengan spesifikasi ini akan menimbulkan kesalahan.
Sekarang mari kita coba buka file konfigurasi (misalnya, cfg/timit_baselines/timit_mlp_mfcc_basic.cfg ) dan mari kita jelaskan bagian utama:
[cfg_proto]
cfg_proto = proto/global.proto
cfg_proto_chunk = proto/global_chunk.proto
Versi saat ini dari file config pertama-tama menentukan jalur file prototipe global dan spesifik chunk di bagian [CFG_PROTO] .
[exp]
cmd =
run_nn_script = run_nn
out_folder = exp/TIMIT_MLP_basic5
seed = 1234
use_cuda = True
multi_gpu = False
save_gpumem = False
n_epochs_tr = 24
Bagian [exp] berisi beberapa bidang penting, seperti folder output ( out_folder ) dan jalur skrip pemrosesan spesifik chunk run_nn (secara default fungsi ini harus diimplementasikan di pustaka core.py). Bidang n_epochs_tr menentukan jumlah zaman pelatihan yang dipilih. Opsi lain tentang menggunakan_Cuda, multi_gpu, dan save_gpumem dapat diaktifkan oleh pengguna. CMD bidang dapat digunakan untuk menambahkan perintah untuk menjalankan skrip pada cluster HPC.
[dataset1]
data_name = TIMIT_tr
fea = fea_name=mfcc
fea_lst=quick_test/data/train/feats_mfcc.scp
fea_opts=apply-cmvn --utt2spk=ark:quick_test/data/train/utt2spk ark:quick_test/mfcc/train_cmvn_speaker.ark ark:- ark:- | add-deltas --delta-order=2 ark:- ark:- |
cw_left=5
cw_right=5
lab = lab_name=lab_cd
lab_folder=quick_test/dnn4_pretrain-dbn_dnn_ali
lab_opts=ali-to-pdf
lab_count_file=auto
lab_data_folder=quick_test/data/train/
lab_graph=quick_test/graph
n_chunks = 5
[dataset2]
data_name = TIMIT_dev
fea = fea_name=mfcc
fea_lst=quick_test/data/dev/feats_mfcc.scp
fea_opts=apply-cmvn --utt2spk=ark:quick_test/data/dev/utt2spk ark:quick_test/mfcc/dev_cmvn_speaker.ark ark:- ark:- | add-deltas --delta-order=2 ark:- ark:- |
cw_left=5
cw_right=5
lab = lab_name=lab_cd
lab_folder=quick_test/dnn4_pretrain-dbn_dnn_ali_dev
lab_opts=ali-to-pdf
lab_count_file=auto
lab_data_folder=quick_test/data/dev/
lab_graph=quick_test/graph
n_chunks = 1
[dataset3]
data_name = TIMIT_test
fea = fea_name=mfcc
fea_lst=quick_test/data/test/feats_mfcc.scp
fea_opts=apply-cmvn --utt2spk=ark:quick_test/data/test/utt2spk ark:quick_test/mfcc/test_cmvn_speaker.ark ark:- ark:- | add-deltas --delta-order=2 ark:- ark:- |
cw_left=5
cw_right=5
lab = lab_name=lab_cd
lab_folder=quick_test/dnn4_pretrain-dbn_dnn_ali_test
lab_opts=ali-to-pdf
lab_count_file=auto
lab_data_folder=quick_test/data/test/
lab_graph=quick_test/graph
n_chunks = 1
File konfigurasi berisi sejumlah bagian ( [Dataset1] , [Dataset2] , [Dataset3] , ...) yang menggambarkan semua korpora yang digunakan untuk percobaan ASR. Bidang pada bagian [Dataset*] menjelaskan semua fitur dan label yang dipertimbangkan dalam percobaan. The features, for instance, are specified in the field fea: , where fea_name contains the name given to the feature, fea_lst is the list of features (in the scp Kaldi format), fea_opts allows users to specify how to process the features (eg, doing CMVN or adding the derivatives), while cw_left and cw_right set the characteristics of the context window (ie, number of left and right frames to ditambahkan). Perhatikan bahwa versi saat ini dari toolkit Pytorch-Kaldi mendukung definisi beberapa fitur aliran. Memang, seperti yang ditunjukkan dalam cfg/timit_baselines/timit_mfcc_fbank_fmllr_ligru_best.cfg beberapa aliran fitur (misalnya, MFCC, FBank, FMLLR) digunakan.
Demikian pula, bagian lab berisi beberapa sub-bidang. Misalnya, lab_name mengacu pada nama yang diberikan ke label, sedangkan lab_folder berisi folder di mana keberpihakan yang dihasilkan oleh resep Kaldi disimpan. LAB_OPTS memungkinkan pengguna untuk menentukan beberapa opsi pada penyelarasan yang dipertimbangkan. Misalnya lab_opts = "Ali-to-PDF" mengekstrak label telepon-state yang bergantung pada konteks standar, sedangkan lab_opts = ali-to-phones --per-frame = true dapat digunakan untuk mengekstrak target monofon. lab_count_file digunakan untuk menentukan file yang berisi jumlah status telepon yang dipertimbangkan. Hitungan ini penting dalam fase depan, di mana probabilitas posterior yang dihitung oleh jaringan saraf dibagi oleh prior mereka. Pytorch-Kaldi memungkinkan pengguna untuk menentukan file hitungan eksternal atau untuk secara otomatis mengambilnya (menggunakan lab_count_file = auto ). Pengguna juga dapat menentukan lab_count_file = tidak ada jika file hitungan tidak diperlukan, misalnya, ketika label sesuai dengan output yang tidak digunakan untuk menghasilkan probabilitas posterior yang digunakan dalam fase maju (lihat misalnya target monofon di CFG/timit_baselines/timit_mlp_mfcc.cfg ). Lab_data_folder , sebagai gantinya, sesuai dengan folder data yang dibuat selama persiapan data Kaldi. Ini berisi beberapa file, termasuk file teks yang akhirnya digunakan untuk perhitungan final WER. Lab_graph sub-bidang terakhir adalah jalur grafik Kaldi yang digunakan untuk menghasilkan label.
Dataset lengkap biasanya besar dan tidak dapat sesuai dengan memori GPU/RAM. Dengan demikian itu harus dibagi menjadi beberapa potongan. Pytorch-Kaldi secara otomatis membagi dataset menjadi jumlah potongan yang ditentukan dalam n_chunks . Jumlah potongan mungkin tergantung pada dataset tertentu. Secara umum, kami menyarankan memproses potongan pidato sekitar 1 atau 2 jam (tergantung pada memori yang tersedia).
[data_use]
train_with = TIMIT_tr
valid_with = TIMIT_dev
forward_with = TIMIT_test
Bagian ini menceritakan bagaimana data yang tercantum ke dalam bagian [dataset*] digunakan dalam skrip run_exp.py . Baris pertama berarti bahwa kami melakukan pelatihan dengan data yang disebut TIMIT_TR . Perhatikan bahwa nama dataset ini harus muncul di salah satu bagian dataset, jika tidak, konfigurasi parser akan menimbulkan kesalahan. Demikian pula, baris kedua dan ketiga menentukan data yang digunakan untuk validasi dan fase maju, masing -masing.
[batches]
batch_size_train = 128
max_seq_length_train = 1000
increase_seq_length_train = False
start_seq_len_train = 100
multply_factor_seq_len_train = 2
batch_size_valid = 128
max_seq_length_valid = 1000
Batch_size_train digunakan untuk menentukan jumlah contoh pelatihan dalam mini-batch. Fields max_seq_length_train memotong kalimat lebih lama dari nilai yang ditentukan. Saat melatih model berulang pada kalimat yang sangat panjang, masalah di luar memori mungkin muncul. Dengan opsi ini, kami memungkinkan pengguna untuk mengurangi masalah memori seperti itu dengan memotong kalimat panjang. Selain itu, dimungkinkan untuk secara progresif menumbuhkan panjang kalimat maksimum selama pelatihan dengan mengatur peningkatan_seq_length_train = true . Jika diaktifkan, pelatihan dimulai dengan panjang kalimat maksimum yang ditentukan dalam start_seq_len_train (misalnya, start_seq_len_train = 100 ). Setelah setiap zaman, panjang kalimat maksimum dikalikan dengan multply_factor_seq_len_train (misalnya multply_factor_seq_len_train = 2 ). Kami telah mengamati bahwa strategi sederhana ini umumnya meningkatkan kinerja sistem karena mendorong model untuk terlebih dahulu fokus pada dependensi jangka pendek dan belajar yang jangka panjang hanya pada tahap selanjutnya.
Demikian pula, batch_size_valid dan max_seq_length_valid menentukan jumlah contoh dalam mini-batch dan panjang maksimum untuk dataset dev.
[architecture1]
arch_name = MLP_layers1
arch_proto = proto/MLP.proto
arch_library = neural_networks
arch_class = MLP
arch_pretrain_file = none
arch_freeze = False
arch_seq_model = False
dnn_lay = 1024,1024,1024,1024,N_out_lab_cd
dnn_drop = 0.15,0.15,0.15,0.15,0.0
dnn_use_laynorm_inp = False
dnn_use_batchnorm_inp = False
dnn_use_batchnorm = True,True,True,True,False
dnn_use_laynorm = False,False,False,False,False
dnn_act = relu,relu,relu,relu,softmax
arch_lr = 0.08
arch_halving_factor = 0.5
arch_improvement_threshold = 0.001
arch_opt = sgd
opt_momentum = 0.0
opt_weight_decay = 0.0
opt_dampening = 0.0
opt_nesterov = False
Bagian [arsitektur*] digunakan untuk menentukan arsitektur jaringan saraf yang terlibat dalam percobaan ASR. Field Arch_name menentukan nama arsitektur. Karena jaringan saraf yang berbeda dapat bergantung pada serangkaian hiperparameter yang berbeda, pengguna harus menambahkan jalur file proto yang berisi daftar hyperparameter ke dalam proto lapangan. Misalnya, file prototipe untuk model MLP standar berisi bidang -bidang berikut:
[proto]
library=path
class=MLP
dnn_lay=str_list
dnn_drop=float_list(0.0,1.0)
dnn_use_laynorm_inp=bool
dnn_use_batchnorm_inp=bool
dnn_use_batchnorm=bool_list
dnn_use_laynorm=bool_list
dnn_act=str_list
Demikian pula dengan file prototipe lainnya, setiap baris mendefinisikan hiperparameter dengan tipe nilai terkait. Semua hyperparameter yang ditentukan dalam file proto harus muncul ke file konfigurasi global di bawah bagian [Arsitektur*] yang sesuai. Field Arch_library menentukan di mana model diberi kode (misalnya neural_nets.py ), sedangkan Arch_Class menunjukkan nama kelas di mana arsitektur diimplementasikan (misalnya jika kita mengatur kelas = MLP yang akan kita lakukan dari neural_nets.py impor MLP ).
Field arch_prain_file dapat digunakan untuk melatih jaringan saraf dengan arsitektur yang sebelumnya terlatih, sedangkan arch_freeze dapat diatur ke false jika Anda ingin melatih parameter arsitektur selama pelatihan dan harus diatur ke true memang menjaga parameter tetap (yaitu, beku) selama pelatihan. Bagian arch_seq_model menunjukkan apakah arsitekturnya berurutan (misalnya RNNs) atau non-sekuensial (misalnya, feed-forward MLP atau CNN). Cara memproses Pytorch-Kaldi, batch input berbeda dalam dua kasus. Untuk jaringan saraf berulang ( ARCH_SEQ_MODEL = TRUE ) Urutan fitur tidak diacak (untuk melestarikan elemen urutan), sedangkan untuk model feedforward ( arch_seq_model = false ) kami mengacak fitur (ini biasanya membantu meningkatkan kinerja). Dalam kasus beberapa arsitektur, pemrosesan berurutan digunakan jika setidaknya salah satu arsitektur yang digunakan ditandai sebagai sekuensial ( arch_seq_model = true ).
Perhatikan bahwa hiperparameter yang dimulai dengan "Arch_" dan "OPT_" adalah wajib dan harus ada di semua arsitektur yang ditentukan dalam file konfigurasi. Hyperparameters lainnya (misalnya, DNN_*,) secara spesifik dari arsitektur yang dipertimbangkan (mereka bergantung pada bagaimana kelas MLP sebenarnya diimplementasikan oleh pengguna) dan dapat menentukan jumlah dan tipologi lapisan tersembunyi, normalisasi batch dan lapisan, dan parameter lainnya. Parameter penting lainnya terkait dengan optimalisasi arsitektur yang dipertimbangkan. Misalnya, ARCH_LR adalah tingkat pembelajaran, sedangkan arch_halving_factor digunakan untuk mengimplementasikan anil tingkat pembelajaran. Secara khusus, ketika peningkatan kinerja relatif pada set-set antara dua zaman berturut-turut lebih kecil dari yang ditentukan dalam arch_improvement_threshold (misalnya, arch_improvement_threshold) kami melipatgandakan tingkat pembelajaran dengan arch_halving_factor (EG, arch_halving_factor = 0,5 ). Field Arch_opt menentukan jenis algoritma optimasi. Kami saat ini mendukung SGD, Adam, dan RMSProp. Parameter lain khusus untuk algoritma optimasi yang dipertimbangkan (lihat dokumentasi Pytorch untuk makna yang tepat dari semua hiperparameter spesifik optimasi). Perhatikan bahwa arsitektur yang berbeda yang didefinisikan dalam [archictecture*] dapat memiliki hiperparameter optimasi yang berbeda dan mereka bahkan dapat menggunakan algoritma optimasi yang berbeda.
[model]
model_proto = proto/model.proto
model = out_dnn1=compute(MLP_layers1,mfcc)
loss_final=cost_nll(out_dnn1,lab_cd)
err_final=cost_err(out_dnn1,lab_cd)
Cara semua fitur dan arsitektur digabungkan ditentukan dalam bagian ini dengan meta-bahasa yang sangat sederhana dan intuitif. Model lapangan: Menjelaskan bagaimana fitur dan arsitektur terhubung untuk menghasilkan sebagai output satu set probabilitas posterior. Line out_dnn1 = compute (mlp_layers, mfcc) berarti " memberi makan arsitektur yang disebut mlp_layers1 dengan fitur yang disebut mfcc dan menyimpan output ke variabel out_dnn1 ". Dari output jaringan saraf out_dnn1 kesalahan dan fungsi kerugian dihitung menggunakan label yang disebut lab_cd , yang harus didefinisikan sebelumnya ke dalam bagian [dataset*] . Bidang err_final dan loss_final adalah subbidang wajib yang menentukan output akhir dari model.
Contoh yang jauh lebih kompleks (dibahas di sini hanya untuk menyoroti potensi toolkit) dilaporkan dalam cfg/timit_baselines/timit_mfcc_fbank_fmllr_ligru_best.cfg :
[model]
model_proto=proto/model.proto
model:conc1=concatenate(mfcc,fbank)
conc2=concatenate(conc1,fmllr)
out_dnn1=compute(MLP_layers_first,conc2)
out_dnn2=compute(liGRU_layers,out_dnn1)
out_dnn3=compute(MLP_layers_second,out_dnn2)
out_dnn4=compute(MLP_layers_last,out_dnn3)
out_dnn5=compute(MLP_layers_last2,out_dnn3)
loss_mono=cost_nll(out_dnn5,lab_mono)
loss_mono_w=mult_constant(loss_mono,1.0)
loss_cd=cost_nll(out_dnn4,lab_cd)
loss_final=sum(loss_cd,loss_mono_w)
err_final=cost_err(out_dnn4,lab_cd)
Dalam hal ini kami pertama kali menggabungkan fitur MFCC, FBank, dan FMLLR dan kami kemudian memberi makan MLP. Output MLP dimasukkan ke dalam jaringan saraf berulang (khususnya model Li-gru). Kami kemudian memiliki lapisan MLP lain ( MLP_LAYERS_SECOND ) diikuti oleh dua pengklasifikasi Softmax (yaitu, MLP_LAYERS_LAST , MLP_LAYERS_LAST2 ). Yang pertama memperkirakan status yang bergantung pada konteks standar, sedangkan target monofon memperkirakan kedua. Fungsi biaya akhir adalah jumlah tertimbang antara dua prediksi ini. Dengan cara ini kami menerapkan regularisasi monofon, itu ternyata berguna untuk meningkatkan kinerja ASR.
Model lengkap dapat dianggap sebagai grafik komputasi besar tunggal, di mana semua arsitektur dasar yang digunakan di bagian [model] dilatih bersama. Untuk setiap mini-batch, fitur input disebarkan melalui model lengkap dan cost_final dihitung menggunakan label yang ditentukan. Gradien fungsi biaya sehubungan dengan semua parameter arsitektur yang dapat dipelajari kemudian dihitung. Semua parameter arsitektur yang dipekerjakan kemudian diperbarui bersama dengan algoritma yang ditentukan di bagian [Arsitektur*] .
[forward]
forward_out = out_dnn1
normalize_posteriors = True
normalize_with_counts_from = lab_cd
save_out_file = True
require_decoding = True
Bagian Forward First mendefinisikan yang merupakan output untuk diteruskan (harus didefinisikan ke bagian model). Jika normalize_posteriors = true , posterior ini dinormalisasi oleh prior mereka (menggunakan file count). Jika save_out_file = true , file posterior (biasanya file bahtera yang sangat besar) disimpan, sedangkan jika save_out_file = false file ini dihapus jika tidak diperlukan lagi. Persyaratan_decoding adalah boolean yang menentukan jika kita perlu memecahkan kode output yang ditentukan. Bidang Normalize_with_counts_from set yang dihitung menggunakan untuk menormalkan probabilitas posterior.
[decoding]
decoding_script_folder = kaldi_decoding_scripts/
decoding_script = decode_dnn.sh
decoding_proto = proto/decoding.proto
min_active = 200
max_active = 7000
max_mem = 50000000
beam = 13.0
latbeam = 8.0
acwt = 0.2
max_arcs = -1
skip_scoring = false
scoring_script = local/score.sh
scoring_opts = "--min-lmwt 1 --max-lmwt 10"
norm_vars = False
Bagian decoding melaporkan parameter tentang decoding, yaitu langkah-langkah yang memungkinkan seseorang untuk lewat dari urutan probabilitas yang bergantung pada konteks yang disediakan oleh DNN ke dalam urutan kata. Field decoding_script_folder menentukan folder di mana skrip decoding disimpan. The decoding script field is the script used for decoding (eg, decode_dnn.sh ) that should be in the decoding_script_folder specified before. The field decoding_proto reports all the parameters needed for the considered decoding script.
To make the code more flexible, the config parameters can also be specified within the command line. For example, you can run:
python run_exp.py quick_test/example_newcode.cfg --optimization,lr=0.01 --batches,batch_size=4
The script will replace the learning rate in the specified cfg file with the specified lr value. The modified config file is then stored into out_folder/config.cfg .
The script run_exp.py automatically creates chunk-specific config files, that are used by the run_nn function to perform a single chunk training. The structure of chunk-specific cfg files is very similar to that of the global one. The main difference is a field to_do={train, valid, forward} that specifies the type of processing to on the features chunk specified in the field fea .
Why proto files? Different neural networks, optimization algorithms, and HMM decoders might depend on a different set of hyperparameters. To address this issue, our current solution is based on the definition of some prototype files (for global, chunk, architecture config files). In general, this approach allows a more transparent check of the fields specified into the global config file. Moreover, it allows users to easily add new parameters without changing any line of the python code. For instance, to add a user-defined model, a new proto file (eg, user-model.prot o) that specifies the hyperparameter must be written. Then, the user should only write a class (eg, user-model in neural_networks.py ) that implements the architecture).
The toolkit is designed to allow users to easily plug-in their own acoustic models. To add a customized neural model do the following steps:
[proto]
dnn_lay=str_list
dnn_drop=float_list(0.0,1.0)
dnn_use_laynorm_inp=bool
dnn_use_batchnorm_inp=bool
dnn_use_batchnorm=bool_list
dnn_use_laynorm=bool_list
dnn_act=str_list
The parameter dnn_lay must be a list of string, dnn_drop (ie, the dropout factors for each layer) is a list of float ranging from 0.0 and 1.0, dnn_use_laynorm_inp and dnn_use_batchnorm_inp are booleans that enable or disable batch or layer normalization of the input. dnn_use_batchnorm and dnn_use_laynorm are a list of boolean that decide layer by layer if batch/layer normalization has to be used. The parameter dnn_act is again a list of string that sets the activation function of each layer. Since every model is based on its own set of hyperparameters, different models have a different prototype file. For instance, you can take a look into GRU.proto and see that the hyperparameter list is different from that of a standard MLP. Similarly to the previous examples, you should add here your list of hyperparameters and save the file.
Write a PyTorch class implementing your model. Open the library neural_networks.py and look at some of the models already implemented. For simplicity, you can start taking a look into the class MLP. The classes have two mandatory methods: init and forward . The first one is used to initialize the architecture, the second specifies the list of computations to do. The method init takes in input two variables that are automatically computed within the run_nn function. inp_dim is simply the dimensionality of the neural network input, while options is a dictionary containing all the parameters specified into the section architecture of the configuration file.
For instance, you can access to the DNN activations of the various layers in this way: options['dnn_lay'].split(',') . As you might see from the MLP class, the initialization method defines and initializes all the parameters of the neural network. The forward method takes in input a tensor x (ie, the input data) and outputs another vector containing x. If your model is a sequence model (ie, if there is at least one architecture with arch_seq_model=true in the cfg file), x is a tensor with (time_steps, batches, N_in), otherwise is a (batches, N_in) matrix. The class forward defines the list of computations to transform the input tensor into a corresponding output tensor. The output must have the sequential format (time_steps, batches, N_out) for recurrent models and the non-sequential format (batches, N_out) for feed-forward models. Similarly to the already-implemented models the user should write a new class (eg, myDNN) that implements the customized model:
class myDNN(nn.Module):
def __init__(self, options,inp_dim):
super(myDNN, self).__init__()
// initialize the parameters
def forward(self, x):
// do some computations out=f(x)
return out
[architecture1]
arch_name= mynetwork (this is a name you would like to use to refer to this architecture within the following model section)
arch_proto=proto/myDNN.proto (here is the name of the proto file defined before)
arch_library=neural_networks (this is the name of the library where myDNN is implemented)
arch_class=myDNN (This must be the name of the class you have implemented)
arch_pretrain_file=none (With this you can specify if you want to pre-train your model)
arch_freeze=False (set False if you want to update the parameters of your model)
arch_seq_model=False (set False for feed-forward models, True for recurrent models)
Then, you have to specify proper values for all the hyperparameters specified in proto/myDNN.proto . For the MLP.proto , we have:
dnn_lay=1024,1024,1024,1024,1024,N_out_lab_cd
dnn_drop=0.15,0.15,0.15,0.15,0.15,0.0
dnn_use_laynorm_inp=False
dnn_use_batchnorm_inp=False
dnn_use_batchnorm=True,True,True,True,True,False
dnn_use_laynorm=False,False,False,False,False,False
dnn_act=relu,relu,relu,relu,relu,softmax
Then, add the following parameters related to the optimization of your own architecture. You can use here standard sdg, adam, or rmsprop (see cfg/TIMIT_baselines/TIMIT_LSTM_mfcc.cfg for an example with rmsprop):
arch_lr=0.08
arch_halving_factor=0.5
arch_improvement_threshold=0.001
arch_opt=sgd
opt_momentum=0.0
opt_weight_decay=0.0
opt_dampening=0.0
opt_nesterov=False
Save the configuration file into the cfg folder (eg, cfg/myDNN_exp.cfg ).
Run the experiment with:
python run_exp.py cfg/myDNN_exp.cfg
When implementing a new model, an important debug test consists of doing an overfitting experiment (to make sure that the model is able to overfit a tiny dataset). If the model is not able to overfit, it means that there is a major bug to solve.
A hyperparameter tuning is often needed in deep learning to search for proper neural architectures. To help tuning the hyperparameters within PyTorch-Kaldi, we have implemented a simple utility that implements a random search. In particular, the script tune_hyperparameters.py generates a set of random configuration files and can be run in this way:
python tune_hyperparameters.py cfg/TIMIT_MLP_mfcc.cfg exp/TIMIT_MLP_mfcc_tuning 10 arch_lr=randfloat(0.001,0.01) batch_size_train=randint(32,256) dnn_act=choose_str{relu,relu,relu,relu,softmax|tanh,tanh,tanh,tanh,softmax}
The first parameter is the reference cfg file that we would like to modify, while the second one is the folder where the random configuration files are saved. The third parameter is the number of the random config file that we would like to generate. There is then the list of all the hyperparameters that we want to change. For instance, arch_lr=randfloat(0.001,0.01) will replace the field arch_lr with a random float ranging from 0.001 to 0.01. batch_size_train=randint(32,256) will replace batch_size_train with a random integer between 32 and 256 and so on. Once the config files are created, they can be run sequentially or in parallel with:
python run_exp.py $cfg_file
PyTorch-Kaldi can be used with any speech dataset. To use your own dataset, the steps to take are similar to those discussed in the TIMIT/Librispeech tutorials. In general, what you have to do is the following:
python run_exp.py $cfg_file . The current version of PyTorch-Kaldi supports input features stored with the Kaldi ark format. If the user wants to perform experiments with customized features, the latter must be converted into the ark format. Take a look into the Kaldi-io-for-python git repository (https://github.com/vesis84/kaldi-io-for-python) for a detailed description about converting numpy arrays into ark files. Moreover, you can take a look into our utility called save_raw_fea.py. This script generates Kaldi ark files containing raw features, that are later used to train neural networks fed by the raw waveform directly (see the section about processing audio with SincNet).
The current version of Pytorch-Kaldi supports the standard production process of using a Pytorch-Kaldi pre-trained acoustic model to transcript one or multiples .wav files. It is important to understand that you must have a trained Pytorch-Kaldi model. While you don't need labels or alignments anymore, Pytorch-Kaldi still needs many files to transcript a new audio file:
Once you have all these files, you can start adding your dataset section to the global configuration file. The easiest way is to copy the cfg file used to train your acoustic model and just modify by adding a new [dataset] :
[dataset4]
data_name = myWavFile
fea = fea_name=fbank
fea_lst=myWavFilePath/data/feats.scp
fea_opts=apply-cmvn --utt2spk=ark:myWavFilePath/data//utt2spk ark:myWavFilePath/cmvn_test.ark ark:- ark:- | add-deltas --delta-order=0 ark:- ark:- |
cw_left=5
cw_right=5
lab = lab_name=none
lab_data_folder=myWavFilePath/data/
lab_graph=myWavFilePath/exp/tri3/graph
n_chunks=1
[data_use]
train_with = TIMIT_tr
valid_with = TIMIT_dev
forward_with = myWavFile
The key string for your audio file transcription is lab_name=none . The none tag asks Pytorch-Kaldi to enter a production mode that only does the forward propagation and decoding without any labels. You don't need TIMIT_tr and TIMIT_dev to be on your production server since Pytorch-Kaldi will skip this information to directly go to the forward phase of the dataset given in the forward_with field. As you can see, the global fea field requires the exact same parameters than standard training or testing dataset, while the lab field only requires two parameters. Please, note that lab_data_folder is nothing more than the same path as fea_lst . Finally, you still need to specify the number of chunks you want to create to process this file (1 hour = 1 chunk).
WARNINGS
In your standard .cfg, you might have used keywords such as N_out_lab_cd that can not be used anymore. Indeed, in a production scenario, you don't want to have the training data on your machine. Therefore, all the variables that were on your .cfg file must be replaced by their true values. To replace all the N_out_{mono,lab_cd} you can take a look at the output of:
hmm-info /path/to/the/final.mdl/used/to/generate/the/training/ali
Then, if you normalize posteriors as (check in your .cfg Section forward):
normalize_posteriors = True
normalize_with_counts_from = lab_cd
You must replace lab_cd by:
normalize_posteriors = True
normalize_with_counts_from = /path/to/ali_train_pdf.counts
This normalization step is crucial for HMM-DNN speech recognition. DNNs, in fact, provide posterior probabilities, while HMMs are generative models that work with likelihoods. To derive the required likelihoods, one can simply divide the posteriors by the prior probabilities. To create this ali_train_pdf.counts file you can follow:
alidir=/path/to/the/exp/tri_ali (change it with your path to the exp with the ali)
num_pdf=$(hmm-info $alidir/final.mdl | awk '/pdfs/{print $4}')
labels_tr_pdf="ark:ali-to-pdf $alidir/final.mdl "ark:gunzip -c $alidir/ali.*.gz |" ark:- |"
analyze-counts --verbose=1 --binary=false --counts-dim=$num_pdf "$labels_tr_pdf" ali_train_pdf.counts
et voilà ! In a production scenario, you might need to transcript a huge number of audio files, and you don't want to create as much as needed .cfg file. In this extent, and after creating this initial production .cfg file (you can leave the path blank), you can call the run_exp.py script with specific arguments referring to your different.wav features:
python run_exp.py cfg/TIMIT_baselines/TIMIT_MLP_fbank_prod.cfg --dataset4,fea,0,fea_lst="myWavFilePath/data/feats.scp" --dataset4,lab,0,lab_data_folder="myWavFilePath/data/" --dataset4,lab,0,lab_graph="myWavFilePath/exp/tri3/graph/"
This command will internally alter the configuration file with your specified paths, and run and your defined features! Note that passing long arguments to the run_exp.py script requires a specific notation. --dataset4 specifies the name of the created section, fea is the name of the higher level field, fea_lst or lab_graph are the name of the lowest level field you want to change. The 0 is here to indicate which lowest level field you want to alter, indeed some configuration files may contain multiple lab_graph per dataset! Therefore, 0 indicates the first occurrence, 1 the second ... Paths MUST be encapsulated by " " to be interpreted as full strings! Note that you need to alter the data_name and forward_with fields if you don't want different .wav files transcriptions to erase each other (decoding files are stored accordingly to the field data_name ). --dataset4,data_name=MyNewName --data_use,forward_with=MyNewName .
In order to give users more flexibility, the latest version of PyTorch-Kaldi supports scheduling of the batch size, max_seq_length_train, learning rate, and dropout factor. This means that it is now possible to change these values during training. To support this feature, we implemented the following formalisms within the config files:
batch_size_train = 128*12 | 64*10 | 32*2
In this case, our batch size will be 128 for the first 12 epochs, 64 for the following 10 epochs, and 32 for the last two epochs. By default "*" means "for N times", while "|" is used to indicate a change of the batch size. Note that if the user simply sets batch_size_train = 128 , the batch size is kept fixed during all the training epochs by default.
A similar formalism can be used to perform learning rate scheduling:
arch_lr = 0.08*10|0.04*5|0.02*3|0.01*2|0.005*2|0.0025*2
In this case, if the user simply sets arch_lr = 0.08 the learning rate is annealed with the new-bob procedure used in the previous version of the toolkit. In practice, we start from the specified learning rate and we multiply it by a halving factor every time that the improvement on the validation dataset is smaller than the threshold specified in the field arch_improvement_threshold .
Also the dropout factor can now be changed during training with the following formalism:
dnn_drop = 0.15*12|0.20*12,0.15,0.15*10|0.20*14,0.15,0.0
With the line before we can set a different dropout rate for different layers and for different epochs. For instance, the first hidden layer will have a dropout rate of 0.15 for the first 12 epochs, and 0.20 for the other 12. The dropout factor of the second layer, instead, will remain constant to 0.15 over all the training. The same formalism is used for all the layers. Note that "|" indicates a change in the dropout factor within the same layer, while "," indicates a different layer.
You can take a look here into a config file where batch sizes, learning rates, and dropout factors are changed here:
cfg/TIMIT_baselines/TIMIT_mfcc_basic_flex.cfg
or here:
cfg/TIMIT_baselines/TIMIT_liGRU_fmllr_lr_schedule.cfg
The project is still in its initial phase and we invite all potential contributors to participate. We hope to build a community of developers larger enough to progressively maintain, improve, and expand the functionalities of our current toolkit. For instance, it could be helpful to report any bug or any suggestion to improve the current version of the code. People can also contribute by adding additional neural models, that can eventually make richer the set of currently-implemented architectures.
Perhatikan Video kami Pengantar Sincnet
SincNet is a convolutional neural network recently proposed to process raw audio waveforms. In particular, SincNet encourages the first layer to discover more meaningful filters by exploiting parametrized sinc functions. In contrast to standard CNNs, which learn all the elements of each filter, only low and high cutoff frequencies of band-pass filters are directly learned from data. This inductive bias offers a very compact way to derive a customized filter-bank front-end, that only depends on some parameters with a clear physical meaning.
For a more detailed description of the SincNet model, please refer to the following papers:
M. Ravanelli, Y. Bengio, "Speaker Recognition from raw waveform with SincNet", in Proc. of SLT 2018 ArXiv
M. Ravanelli, Y.Bengio, "Interpretable Convolutional Filters with SincNet", in Proc. of NIPS@IRASL 2018 ArXiv
To use this model for speech recognition on TIMIT, to the following steps:
python ./run_exp.py cfg/TIMIT_baselines/TIMIT_SincNet_raw.cfg
In the following table, we compare the result of SincNet with other feed-forward neural network:
| Model | WER(%) |
|---|---|
| MLP -fbank | 18.7 |
| MLP -mfcc | 18.2 |
| CNN -raw | 18.1 |
| SincNet -raw | 17.2 |
In this section, we show how to use PyTorch-Kaldi to jointly train a cascade between a speech enhancement and a speech recognition neural networks. The speech enhancement has the goal of improving the quality of the speech signal by minimizing the MSE between clean and noisy features. The enhanced features then feed another neural network that predicts context-dependent phone states.
In the following, we report a toy-task example based on a reverberated version of TIMIT, that is only intended to show how users should set the config file to train such a combination of neural networks. Even though some implementation details (and the adopted datasets) are different, this tutorial is inspired by this paper:
To run the system do the following steps:
1- Make sure you have the standard clean version of TIMIT available.
2- Run the Kaldi s5 baseline of TIMIT. This step is necessary to compute the clean features (that will be the labels of the speech enhancement system) and the alignments (that will be the labels of the speech recognition system). We recommend running the full timit s5 recipe (including the DNN training).
3- The standard TIMIT recipe uses MFCCs features. In this tutorial, instead, we use FBANK features. To compute FBANK features run the following script in $KALDI_ROOT/egs/TIMIT/s5 :
feadir=fbank
for x in train dev test; do
steps/make_fbank.sh --cmd "$train_cmd" --nj $feats_nj data/$x exp/make_fbank/$x $feadir
steps/compute_cmvn_stats.sh data/$x exp/make_fbank/$x $feadir
done
Note that we use 40 FBANKS here, while Kaldi uses by default 23 FBANKs. To compute 40-dimensional features go into "$KALDI_ROOT/egs/TIMIT/conf/fbank.conf" and change the number of considered output filters.
4- Go to this external repository and follow the steps to generate a reverberated version of TIMIT starting from the clean one. Note that this is just a toy task that is only helpful to show how setting up a joint-training system.
5- Compute the FBANK features for the TIMIT_rev dataset. To do it, you can copy the scripts in $KALDI_ROOT/egs/TIMIT/ into $KALDI_ROOT/egs/TIMIT_rev/ . Please, copy also the data folder. Note that the audio files in the TIMIT_rev folders are saved with the standard WAV format, while TIMIT is released with the SPHERE format. To bypass this issue, open the files data/train/wav.scp , data/dev/wav.scp , data/test/wav.scp and delete the part about SPHERE reading (eg, /home/mirco/kaldi-trunk/tools/sph2pipe_v2.5/sph2pipe -f wav ). You also have to change the paths from the standard TIMIT to the reverberated one (eg replace /TIMIT/ with /TIMIT_rev/). Remind to remove the final pipeline symbol“ |”. Save the changes and run the computation of the fbank features in this way:
feadir=fbank
for x in train dev test; do
steps/make_fbank.sh --cmd "$train_cmd" --nj $feats_nj data/$x exp/make_fbank/$x $feadir
steps/compute_cmvn_stats.sh data/$x exp/make_fbank/$x $feadir
done
Remember to change the $KALDI_ROOT/egs/TIMIT_rev/conf/fbank.conf file in order to compute 40 features rather than the 23 FBANKS of the default configuration.
6- Once features are computed, open the following config file:
cfg/TIMIT_baselines/TIMIT_rev/TIMIT_joint_training_liGRU_fbank.cfg
Remember to change the paths according to where data are stored in your machine. As you can see, we consider two types of features. The fbank_rev features are computed from the TIMIT_rev dataset, while the fbank_clean features are derived from the standard TIMIT dataset and are used as targets for the speech enhancement neural network. As you can see in the [model] section of the config file, we have the cascade between networks doing speech enhancement and speech recognition. The speech recognition architecture jointly estimates both context-dependent and monophone targets (thus using the so-called monophone regularization). To run an experiment type the following command:
python run_exp.py cfg/TIMIT_baselines/TIMIT_rev/TIMIT_joint_training_liGRU_fbank.cfg
7- Results With this configuration file, you should obtain a Phone Error Rate (PER)=28.1% . Note that some oscillations around this performance are more than natural and are due to different initialization of the neural parameters.
You can take a closer look into our results here
In this tutorial, we use the DIRHA-English dataset to perform a distant speech recognition experiment. The DIRHA English Dataset is a multi-microphone speech corpus being developed under the EC project DIRHA. The corpus is composed of both real and simulated sequences recorded with 32 sample-synchronized microphones in a domestic environment. The database contains signals of different characteristics in terms of noise and reverberation making it suitable for various multi-microphone signal processing and distant speech recognition tasks. The part of the dataset currently released is composed of 6 native US speakers (3 Males, 3 Females) uttering 409 wall-street journal sentences. The training data have been created using a realistic data contamination approach, that is based on contaminating the clean speech wsj-5k sentences with high-quality multi-microphone impulse responses measured in the targeted environment. For more details on this dataset, please refer to the following papers:
M. Ravanelli, L. Cristoforetti, R. Gretter, M. Pellin, A. Sosi, M. Omologo, "The DIRHA-English corpus and related tasks for distant-speech recognition in domestic environments", in Proceedings of ASRU 2015. ArXiv
M. Ravanelli, P. Svaizer, M. Omologo, "Realistic Multi-Microphone Data Simulation for Distant Speech Recognition", in Proceedings of Interspeech 2016. ArXiv
In this tutorial, we use the aforementioned simulated data for training (using LA6 microphone), while test is performed using the real recordings (LA6). This task is very realistic, but also very challenging. The speech signals are characterized by a reverberation time of about 0.7 seconds. Non-stationary domestic noises (such as vacuum cleaner, steps, phone rings, etc.) are also present in the real recordings.
Let's start now with the practical tutorial.
1- If not available, download the DIRHA dataset from the LDC website. LDC releases the full dataset for a small fee.
2- Go this external reposotory. As reported in this repository, you have to generate the contaminated WSJ dataset with the provided MATLAB script. Then, you can run the proposed KALDI baseline to have features and labels ready for our pytorch-kaldi toolkit.
3- Open the following configuration file:
cfg/DIRHA_baselines/DIRHA_liGRU_fmllr.cfg
The latter configuration file implements a simple RNN model based on a Light Gated Recurrent Unit (Li-GRU). We used fMLLR as input features. Change the paths and run the following command:
python run_exp.py cfg/DIRHA_baselines/DIRHA_liGRU_fmllr.cfg
4- Results: The aforementioned system should provide Word Error Rate (WER%)=23.2% . You can find the results obtained by us here.
Using the other configuration files in the cfg/DIRHA_baselines folder you can perform experiments with different setups. With the provided configuration files you can obtain the following results:
| Model | WER(%) |
|---|---|
| MLP | 26.1 |
| Gru | 25.3 |
| Li-GRU | 23.8 |
The current version of the repository is mainly designed for speech recognition experiments. We are actively working a new version, which is much more flexible and can manage input/output different from Kaldi features/labels. Even with the current version, however, it is possible to implement other systems, such as an autoencoder.
An autoencoder is a neural network whose inputs and outputs are the same. The middle layer normally contains a bottleneck that forces our representations to compress the information of the input. In this tutorial, we provide a toy example based on the TIMIT dataset. For instance, see the following configuration file:
cfg/TIMIT_baselines/TIMIT_MLP_fbank_autoencoder.cfg
Our inputs are the standard 40-dimensional fbank coefficients that are gathered using a context windows of 11 frames (ie, the total dimensionality of our input is 440). A feed-forward neural network (called MLP_encoder) encodes our features into a 100-dimensional representation. The decoder (called MLP_decoder) is fed by the learned representations and tries to reconstruct the output. The system is trained with Mean Squared Error (MSE) metric. Note that in the [Model] section we added this line “err_final=cost_err(dec_out,lab_cd)” at the end. The current version of the model, in fact, by default needs that at least one label is specified (we will remove this limit in the next version).
You can train the system running the following command:
python run_exp.py cfg/TIMIT_baselines/TIMIT_MLP_fbank_autoencoder.cfg
The results should look like this:
ep=000 tr=['TIMIT_tr'] loss=0.139 err=0.999 valid=TIMIT_dev loss=0.076 err=1.000 lr_architecture1=0.080000 lr_architecture2=0.080000 time(s)=41
ep=001 tr=['TIMIT_tr'] loss=0.098 err=0.999 valid=TIMIT_dev loss=0.062 err=1.000 lr_architecture1=0.080000 lr_architecture2=0.080000 time(s)=39
ep=002 tr=['TIMIT_tr'] loss=0.091 err=0.999 valid=TIMIT_dev loss=0.058 err=1.000 lr_architecture1=0.040000 lr_architecture2=0.040000 time(s)=39
ep=003 tr=['TIMIT_tr'] loss=0.088 err=0.999 valid=TIMIT_dev loss=0.056 err=1.000 lr_architecture1=0.020000 lr_architecture2=0.020000 time(s)=38
ep=004 tr=['TIMIT_tr'] loss=0.087 err=0.999 valid=TIMIT_dev loss=0.055 err=0.999 lr_architecture1=0.010000 lr_architecture2=0.010000 time(s)=39
ep=005 tr=['TIMIT_tr'] loss=0.086 err=0.999 valid=TIMIT_dev loss=0.054 err=1.000 lr_architecture1=0.005000 lr_architecture2=0.005000 time(s)=39
ep=006 tr=['TIMIT_tr'] loss=0.086 err=0.999 valid=TIMIT_dev loss=0.054 err=1.000 lr_architecture1=0.002500 lr_architecture2=0.002500 time(s)=39
ep=007 tr=['TIMIT_tr'] loss=0.086 err=0.999 valid=TIMIT_dev loss=0.054 err=1.000 lr_architecture1=0.001250 lr_architecture2=0.001250 time(s)=39
ep=008 tr=['TIMIT_tr'] loss=0.086 err=0.999 valid=TIMIT_dev loss=0.054 err=0.999 lr_architecture1=0.000625 lr_architecture2=0.000625 time(s)=41
ep=009 tr=['TIMIT_tr'] loss=0.086 err=0.999 valid=TIMIT_dev loss=0.054 err=0.999 lr_architecture1=0.000313 lr_architecture2=0.000313 time(s)=38
You should only consider the field "loss=". The filed "err=" only contains not useuful information in this case (for the aforementioned reason). You can take a look into the generated features typing the following command:
copy-feats ark:exp/TIMIT_MLP_fbank_autoencoder/exp_files/forward_TIMIT_test_ep009_ck00_enc_out.ark ark,t:- | more
[1] M. Ravanelli, T. Parcollet, Y. Bengio, "The PyTorch-Kaldi Speech Recognition Toolkit", ArxIv
[2] M. Ravanelli, P. Brakel, M. Omologo, Y. Bengio, "Improving speech recognition by revising gated recurrent units", in Proceedings of Interspeech 2017. ArXiv
[3] M. Ravanelli, P. Brakel, M. Omologo, Y. Bengio, "Light Gated Recurrent Units for Speech Recognition", in IEEE Transactions on Emerging Topics in Computational Intelligence. ArXiv
[4] M. Ravanelli, "Deep Learning for Distant Speech Recognition", PhD Thesis, Unitn 2017. ArXiv
[5] T. Parcollet, M. Ravanelli, M. Morchid, G. Linarès, C. Trabelsi, R. De Mori, Y. Bengio, "Quaternion Recurrent Neural Networks", in Proceedings of ICLR 2019 ArXiv
[6] T. Parcollet, M. Morchid, G. Linarès, R. De Mori, "Bidirectional Quaternion Long-Short Term Memory Recurrent Neural Networks for Speech Recognition", in Proceedings of ICASSP 2019 ArXiv