dlxj commited on
Commit ·
31a7185
1
Parent(s): af9c3d5
训练中文数字识别
Browse files- .gitignore +1 -0
- examples/asr/asr_eou/speech_to_text_rnnt_eou_train_number.py +377 -0
- readme.txt +3 -0
.gitignore
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
# log and data files
|
| 2 |
# common_voice_11_0/
|
| 3 |
# nemo/
|
|
|
|
| 4 |
nemotron-speech-streaming-en-0.6b/
|
| 5 |
common_voice_11_0/audio/
|
| 6 |
common_voice_11_0/ja/
|
|
|
|
| 1 |
# log and data files
|
| 2 |
# common_voice_11_0/
|
| 3 |
# nemo/
|
| 4 |
+
data/tts_dataset
|
| 5 |
nemotron-speech-streaming-en-0.6b/
|
| 6 |
common_voice_11_0/audio/
|
| 7 |
common_voice_11_0/ja/
|
examples/asr/asr_eou/speech_to_text_rnnt_eou_train_number.py
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# huggingface_echodict/NeMo_RNNT_EOU/gen_tts_dataset.py
|
| 3 |
+
# huggingface_echodict\asr_rnnt_eou_from_scratch\papers\arXiv-1211.3711v1\training_number.py
|
| 4 |
+
# 训练中文数字识别
|
| 5 |
+
|
| 6 |
+
"""
|
| 7 |
+
Example usage:
|
| 8 |
+
|
| 9 |
+
1. Prepare dataset based on <NeMo Root>/nemo/collections/asr/data/audio_to_eou_label_lhotse.py
|
| 10 |
+
Specifically, each sample in the jsonl manifest should have the following fields:
|
| 11 |
+
{
|
| 12 |
+
"audio_filepath": "/path/to/audio.wav",
|
| 13 |
+
"text": "The text of the audio."
|
| 14 |
+
"offset": 0.0, # offset of the audio, in seconds
|
| 15 |
+
"duration": 3.0, # duration of the audio, in seconds
|
| 16 |
+
"sou_time": 0.2, # start of utterance time, in seconds
|
| 17 |
+
"eou_time": 1.5, # end of utterance time, in seconds
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
2. If using a normal ASR model as initialization:
|
| 21 |
+
- Add special tokens <EOU> and <EOB> to the tokenizer of pretrained model, by refering to the script
|
| 22 |
+
<NeMo Root>/scripts/asr_eou/tokenizers/add_special_tokens_to_sentencepiece.py
|
| 23 |
+
- If pretrained model is HybridRNNTCTCBPEModel, convert it to RNNT using the script
|
| 24 |
+
<NeMo Root>/examples/asr/asr_hybrid_transducer_ctc/helpers/convert_nemo_asr_hybrid_to_ctc.py
|
| 25 |
+
|
| 26 |
+
3. Run the following command to train the ASR-EOU model:
|
| 27 |
+
```bash
|
| 28 |
+
#!/bin/bash
|
| 29 |
+
|
| 30 |
+
TRAIN_MANIFEST=/path/to/train_manifest.json
|
| 31 |
+
VAL_MANIFEST=/path/to/val_manifest.json
|
| 32 |
+
NOISE_MANIFEST=/path/to/noise_manifest.json
|
| 33 |
+
|
| 34 |
+
PRETRAINED_NEMO=/path/to/pretrained_model.nemo
|
| 35 |
+
TOKENIZER_DIR=/path/to/tokenizer_dir
|
| 36 |
+
|
| 37 |
+
BATCH_SIZE=16
|
| 38 |
+
NUM_WORKERS=8
|
| 39 |
+
LIMIT_TRAIN_BATCHES=1000
|
| 40 |
+
VAL_CHECK_INTERVAL=1000
|
| 41 |
+
MAX_STEPS=1000000
|
| 42 |
+
|
| 43 |
+
EXP_NAME=fastconformer_transducer_bpe_streaming_eou
|
| 44 |
+
SCRIPT=${NEMO_PATH}/examples/asr/asr_eou/speech_to_text_rnnt_eou_train.py
|
| 45 |
+
CONFIG_PATH=${NEMO_PATH}/examples/asr/conf/asr_eou
|
| 46 |
+
CONFIG_NAME=fastconformer_transducer_bpe_streaming
|
| 47 |
+
|
| 48 |
+
CUDA_VISIBLE_DEVICES=0 python $SCRIPT \
|
| 49 |
+
--config-path $CONFIG_PATH \
|
| 50 |
+
--config-name $CONFIG_NAME \
|
| 51 |
+
++init_from_nemo_model=$PRETRAINED_NEMO \
|
| 52 |
+
model.encoder.att_context_size="[70,1]" \
|
| 53 |
+
model.tokenizer.dir=$TOKENIZER_DIR \
|
| 54 |
+
model.train_ds.manifest_filepath=$TRAIN_MANIFEST \
|
| 55 |
+
model.train_ds.augmentor.noise.manifest_path=$NOISE_MANIFEST \
|
| 56 |
+
model.validation_ds.manifest_filepath=$VAL_MANIFEST \
|
| 57 |
+
model.train_ds.batch_size=$BATCH_SIZE \
|
| 58 |
+
model.train_ds.num_workers=$NUM_WORKERS \
|
| 59 |
+
model.validation_ds.batch_size=$BATCH_SIZE \
|
| 60 |
+
model.validation_ds.num_workers=$NUM_WORKERS \
|
| 61 |
+
~model.test_ds \
|
| 62 |
+
trainer.limit_train_batches=$LIMIT_TRAIN_BATCHES \
|
| 63 |
+
trainer.val_check_interval=$VAL_CHECK_INTERVAL \
|
| 64 |
+
trainer.max_steps=$MAX_STEPS \
|
| 65 |
+
exp_manager.name=$EXP_NAME
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
import os
|
| 71 |
+
import sys
|
| 72 |
+
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..')))
|
| 73 |
+
|
| 74 |
+
from dataclasses import is_dataclass
|
| 75 |
+
from typing import Optional
|
| 76 |
+
|
| 77 |
+
import lightning.pytorch as pl
|
| 78 |
+
from omegaconf import DictConfig, OmegaConf, open_dict
|
| 79 |
+
|
| 80 |
+
from nemo.collections.asr.models import ASRModel, EncDecHybridRNNTCTCBPEModel, EncDecRNNTBPEModel
|
| 81 |
+
from nemo.collections.asr.models.asr_eou_models import EncDecRNNTBPEEOUModel
|
| 82 |
+
from nemo.collections.asr.modules.rnnt import RNNTDecoder, RNNTJoint
|
| 83 |
+
from nemo.core import adapter_mixins
|
| 84 |
+
from nemo.core.config import hydra_runner
|
| 85 |
+
from nemo.utils import logging
|
| 86 |
+
from nemo.utils.exp_manager import exp_manager
|
| 87 |
+
from nemo.utils.trainer_utils import resolve_trainer_cfg
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def add_global_adapter_cfg(model, global_adapter_cfg):
|
| 91 |
+
# Convert to DictConfig from dict or Dataclass
|
| 92 |
+
if is_dataclass(global_adapter_cfg):
|
| 93 |
+
global_adapter_cfg = OmegaConf.structured(global_adapter_cfg)
|
| 94 |
+
|
| 95 |
+
if not isinstance(global_adapter_cfg, DictConfig):
|
| 96 |
+
global_adapter_cfg = DictConfig(global_adapter_cfg)
|
| 97 |
+
|
| 98 |
+
# Update the model.cfg with information about the new adapter global cfg
|
| 99 |
+
with open_dict(global_adapter_cfg), open_dict(model.cfg):
|
| 100 |
+
if 'adapters' not in model.cfg:
|
| 101 |
+
model.cfg.adapters = OmegaConf.create({})
|
| 102 |
+
|
| 103 |
+
# Add the global config for adapters to the model's internal config
|
| 104 |
+
model.cfg.adapters[model.adapter_global_cfg_key] = global_adapter_cfg
|
| 105 |
+
|
| 106 |
+
# Update all adapter modules (that already exist) with this global adapter config
|
| 107 |
+
model.update_adapter_cfg(model.cfg.adapters)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def update_model_config_to_support_adapter(model_cfg):
|
| 111 |
+
with open_dict(model_cfg):
|
| 112 |
+
# Update encoder adapter compatible config
|
| 113 |
+
adapter_metadata = adapter_mixins.get_registered_adapter(model_cfg.encoder._target_)
|
| 114 |
+
if adapter_metadata is not None:
|
| 115 |
+
model_cfg.encoder._target_ = adapter_metadata.adapter_class_path
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def setup_adapters(cfg: DictConfig, model: ASRModel):
|
| 119 |
+
# Setup adapters
|
| 120 |
+
with open_dict(cfg.model.adapter):
|
| 121 |
+
# Extract the name of the adapter (must be give for training)
|
| 122 |
+
adapter_name = cfg.model.adapter.pop("adapter_name")
|
| 123 |
+
adapter_type = cfg.model.adapter.pop("adapter_type")
|
| 124 |
+
adapter_module_name = cfg.model.adapter.pop("adapter_module_name", None)
|
| 125 |
+
|
| 126 |
+
# Resolve the config of the specified `adapter_type`
|
| 127 |
+
if adapter_type not in cfg.model.adapter.keys():
|
| 128 |
+
raise ValueError(
|
| 129 |
+
f"Adapter type ({adapter_type}) config could not be found. Adapter setup config - \n"
|
| 130 |
+
f"{OmegaConf.to_yaml(cfg.model.adapter)}"
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
adapter_type_cfg = cfg.model.adapter[adapter_type]
|
| 134 |
+
print(f"Found `{adapter_type}` config :\n" f"{OmegaConf.to_yaml(adapter_type_cfg)}")
|
| 135 |
+
|
| 136 |
+
# Augment adapter name with module name, if not provided by user
|
| 137 |
+
if adapter_module_name is not None and ':' not in adapter_name:
|
| 138 |
+
adapter_name = f'{adapter_module_name}:{adapter_name}'
|
| 139 |
+
|
| 140 |
+
# Extract the global adapter config, if provided
|
| 141 |
+
adapter_global_cfg = cfg.model.adapter.pop(model.adapter_global_cfg_key, None)
|
| 142 |
+
if adapter_global_cfg is not None:
|
| 143 |
+
add_global_adapter_cfg(model, adapter_global_cfg)
|
| 144 |
+
|
| 145 |
+
model.add_adapter(adapter_name, cfg=adapter_type_cfg)
|
| 146 |
+
assert model.is_adapter_available()
|
| 147 |
+
|
| 148 |
+
# Disable all other adapters, enable just the current adapter.
|
| 149 |
+
model.set_enabled_adapters(enabled=False) # disable all adapters prior to training
|
| 150 |
+
model.set_enabled_adapters(adapter_name, enabled=True) # enable just one adapter by name
|
| 151 |
+
|
| 152 |
+
model.freeze() # freeze whole model by default
|
| 153 |
+
if not cfg.model.get("freeze_decoder", True):
|
| 154 |
+
logging.info("Unfreezing decoder weights.")
|
| 155 |
+
model.decoder.unfreeze()
|
| 156 |
+
if hasattr(model, 'joint') and not cfg.model.get(f"freeze_joint", True):
|
| 157 |
+
logging.info("Unfreezing joint network weights.")
|
| 158 |
+
model.joint.unfreeze()
|
| 159 |
+
|
| 160 |
+
# Activate dropout() and other modules that depend on train mode.
|
| 161 |
+
model = model.train()
|
| 162 |
+
# Then, Unfreeze just the adapter weights that were enabled above (no part of encoder/decoder/joint/etc)
|
| 163 |
+
model.unfreeze_enabled_adapters()
|
| 164 |
+
return model
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def get_pretrained_model_name(cfg: DictConfig) -> Optional[str]:
|
| 168 |
+
if hasattr(cfg, 'init_from_ptl_ckpt') and cfg.init_from_ptl_ckpt is not None:
|
| 169 |
+
raise NotImplementedError(
|
| 170 |
+
"Currently for simplicity of single script for all model types, we only support `init_from_nemo_model` and `init_from_pretrained_model`"
|
| 171 |
+
)
|
| 172 |
+
nemo_model_path = cfg.get('init_from_nemo_model', None)
|
| 173 |
+
pretrained_name = cfg.get('init_from_pretrained_model', None)
|
| 174 |
+
if nemo_model_path is not None and pretrained_name is not None:
|
| 175 |
+
raise ValueError("Only pass `init_from_nemo_model` or `init_from_pretrained_model` but not both")
|
| 176 |
+
elif nemo_model_path is None and pretrained_name is None:
|
| 177 |
+
return None
|
| 178 |
+
|
| 179 |
+
if nemo_model_path:
|
| 180 |
+
return nemo_model_path
|
| 181 |
+
if pretrained_name:
|
| 182 |
+
return pretrained_name
|
| 183 |
+
return None
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def init_from_pretrained_nemo(model: EncDecRNNTBPEEOUModel, pretrained_model_path: str, cfg: DictConfig):
|
| 187 |
+
"""
|
| 188 |
+
Load the pretrained model from a .nemo file or remote checkpoint. If the pretrained model has exactly
|
| 189 |
+
the same vocabulary size as the current model, the whole model will be loaded directly. Otherwise,
|
| 190 |
+
the encoder and decoder weights will be loaded separately and the EOU/EOB classes will be handled separately.
|
| 191 |
+
"""
|
| 192 |
+
if pretrained_model_path.endswith('.nemo'):
|
| 193 |
+
pretrained_model = ASRModel.restore_from(restore_path=pretrained_model_path) # type: EncDecRNNTBPEModel
|
| 194 |
+
else:
|
| 195 |
+
pretrained_model = ASRModel.from_pretrained(pretrained_model_path) # type: EncDecRNNTBPEModel
|
| 196 |
+
|
| 197 |
+
if not isinstance(pretrained_model, (EncDecRNNTBPEModel, EncDecHybridRNNTCTCBPEModel)):
|
| 198 |
+
raise TypeError(
|
| 199 |
+
f"Pretrained model {pretrained_model.__class__} is not EncDecRNNTBPEModel or EncDecHybridRNNTCTCBPEModel."
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
try:
|
| 203 |
+
model.load_state_dict(pretrained_model.state_dict(), strict=True)
|
| 204 |
+
logging.info(
|
| 205 |
+
f"Pretrained model from {pretrained_model_path} has exactly the same model structure, skip further loading."
|
| 206 |
+
)
|
| 207 |
+
return
|
| 208 |
+
except Exception:
|
| 209 |
+
logging.warning(
|
| 210 |
+
f"Pretrained model {pretrained_model_path} has different model structure, try loading weights separately and add EOU/EOB classes."
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
# Load encoder state dict into the model
|
| 214 |
+
model.encoder.load_state_dict(pretrained_model.encoder.state_dict(), strict=True)
|
| 215 |
+
logging.info(f"Encoder weights loaded from {pretrained_model_path}.")
|
| 216 |
+
|
| 217 |
+
# Load decoder state dict into the model
|
| 218 |
+
decoder = model.decoder # type: RNNTDecoder
|
| 219 |
+
pretrained_decoder = pretrained_model.decoder # type: RNNTDecoder
|
| 220 |
+
if not isinstance(decoder, RNNTDecoder) or not isinstance(pretrained_decoder, RNNTDecoder):
|
| 221 |
+
raise TypeError(
|
| 222 |
+
f"Decoder {decoder.__class__} is not RNNTDecoder or pretrained decoder {pretrained_decoder.__class__} is not RNNTDecoder."
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
decoder.prediction["dec_rnn"].load_state_dict(pretrained_decoder.prediction["dec_rnn"].state_dict(), strict=True)
|
| 226 |
+
|
| 227 |
+
decoder_embed_states = decoder.prediction["embed"].state_dict()['weight'] # shape: [num_classes+2, hid_dim]
|
| 228 |
+
pretrained_decoder_embed_states = pretrained_decoder.prediction["embed"].state_dict()[
|
| 229 |
+
'weight'
|
| 230 |
+
] # shape: [num_classes, hid_dim]
|
| 231 |
+
if decoder_embed_states.shape[0] != pretrained_decoder_embed_states.shape[0] + 2:
|
| 232 |
+
raise ValueError(
|
| 233 |
+
f"Size mismatched between pretrained ({pretrained_decoder_embed_states.shape[0]}+2) and current model ({decoder_embed_states.shape[0]}), skip loading decoder embedding."
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
decoder_embed_states[:-3, :] = pretrained_decoder_embed_states[:-1, :] # everything except EOU, EOB and blank
|
| 237 |
+
decoder_embed_states[-1, :] = pretrained_decoder_embed_states[-1, :] # blank class
|
| 238 |
+
decoder.prediction["embed"].load_state_dict({"weight": decoder_embed_states}, strict=True)
|
| 239 |
+
logging.info(f"Decoder weights loaded from {pretrained_model_path}.")
|
| 240 |
+
|
| 241 |
+
# Load joint network weights if new model's joint network has two more classes than the pretrained model
|
| 242 |
+
joint_network = model.joint # type: RNNTJoint
|
| 243 |
+
pretrained_joint_network = pretrained_model.joint # type: RNNTJoint
|
| 244 |
+
assert isinstance(joint_network, RNNTJoint), f"Joint network {joint_network.__class__} is not RNNTJoint."
|
| 245 |
+
assert isinstance(
|
| 246 |
+
pretrained_joint_network, RNNTJoint
|
| 247 |
+
), f"Pretrained joint network {pretrained_joint_network.__class__} is not RNNTJoint."
|
| 248 |
+
joint_network.pred.load_state_dict(pretrained_joint_network.pred.state_dict(), strict=True)
|
| 249 |
+
joint_network.enc.load_state_dict(pretrained_joint_network.enc.state_dict(), strict=True)
|
| 250 |
+
|
| 251 |
+
if joint_network.num_classes_with_blank != pretrained_joint_network.num_classes_with_blank + 2:
|
| 252 |
+
raise ValueError(
|
| 253 |
+
f"Size mismatched between pretrained ({pretrained_joint_network.num_classes_with_blank}+2) and current model ({joint_network.num_classes_with_blank}), skip loading joint network."
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
# Load the joint network weights
|
| 257 |
+
pretrained_joint_state = pretrained_joint_network.joint_net.state_dict()
|
| 258 |
+
joint_state = joint_network.joint_net.state_dict()
|
| 259 |
+
pretrained_joint_clf_weight = pretrained_joint_state['2.weight'] # shape: [num_classes, hid_dim]
|
| 260 |
+
pretrained_joint_clf_bias = pretrained_joint_state['2.bias'] if '2.bias' in pretrained_joint_state else None
|
| 261 |
+
|
| 262 |
+
token_init_method = cfg.model.get('token_init_method', 'constant')
|
| 263 |
+
# Copy the weights and biases from the pretrained model to the new model
|
| 264 |
+
# shape: [num_classes+2, hid_dim]
|
| 265 |
+
joint_state['2.weight'][:-3, :] = pretrained_joint_clf_weight[:-1, :] # everything except EOU, EOB and blank
|
| 266 |
+
joint_state['2.weight'][-1, :] = pretrained_joint_clf_weight[-1, :] # blank class
|
| 267 |
+
|
| 268 |
+
value = None
|
| 269 |
+
if token_init_method == 'min':
|
| 270 |
+
# set the EOU and EOB class to the minimum value of the pretrained model
|
| 271 |
+
value = pretrained_joint_clf_weight.min(dim=0)[0]
|
| 272 |
+
elif token_init_method == 'max':
|
| 273 |
+
# set the EOU and EOB class to the maximum value of the pretrained model
|
| 274 |
+
value = pretrained_joint_clf_weight.max(dim=0)[0]
|
| 275 |
+
elif token_init_method == 'mean':
|
| 276 |
+
# set the EOU and EOB class to the mean value of the pretrained model
|
| 277 |
+
value = pretrained_joint_clf_weight.mean(dim=0)
|
| 278 |
+
elif token_init_method == 'constant':
|
| 279 |
+
value = cfg.model.get('token_init_weight_value', None)
|
| 280 |
+
elif token_init_method:
|
| 281 |
+
raise ValueError(f"Unknown token_init_method: {token_init_method}.")
|
| 282 |
+
|
| 283 |
+
if value is not None:
|
| 284 |
+
joint_state['2.weight'][-2, :] = value # EOB class
|
| 285 |
+
joint_state['2.weight'][-3, :] = value # EOU class
|
| 286 |
+
|
| 287 |
+
if pretrained_joint_clf_bias is not None and '2.bias' in joint_state:
|
| 288 |
+
joint_state['2.bias'][:-3] = pretrained_joint_clf_bias[:-1] # everything except EOU, EOB and blank
|
| 289 |
+
joint_state['2.bias'][-1] = pretrained_joint_clf_bias[-1] # blank class
|
| 290 |
+
value = None
|
| 291 |
+
if token_init_method == 'constant':
|
| 292 |
+
value = cfg.model.get('token_init_bias_value', None)
|
| 293 |
+
elif token_init_method == 'min':
|
| 294 |
+
# set the EOU and EOB class to the minimum value of the pretrained model
|
| 295 |
+
value = pretrained_joint_clf_bias.min()
|
| 296 |
+
elif token_init_method == 'max':
|
| 297 |
+
# set the EOU and EOB class to the maximum value of the pretrained model
|
| 298 |
+
value = pretrained_joint_clf_bias.max()
|
| 299 |
+
elif token_init_method == 'mean':
|
| 300 |
+
# set the EOU and EOB class to the mean value of the pretrained model
|
| 301 |
+
value = pretrained_joint_clf_bias.mean()
|
| 302 |
+
elif token_init_method:
|
| 303 |
+
raise ValueError(f"Unknown token_init_method: {token_init_method}.")
|
| 304 |
+
|
| 305 |
+
if value is not None:
|
| 306 |
+
joint_state['2.bias'][-2] = value # EOB class
|
| 307 |
+
joint_state['2.bias'][-3] = value # EOU class
|
| 308 |
+
|
| 309 |
+
# Load the joint network weights
|
| 310 |
+
joint_network.joint_net.load_state_dict(joint_state, strict=True)
|
| 311 |
+
logging.info(f"Joint network weights loaded from {pretrained_model_path}.")
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
@hydra_runner(config_path="../conf/asr_eou", config_name="fastconformer_transducer_bpe_streaming")
|
| 315 |
+
def main(cfg):
|
| 316 |
+
logging.info(f'Hydra config: {OmegaConf.to_yaml(cfg)}')
|
| 317 |
+
|
| 318 |
+
trainer = pl.Trainer(**resolve_trainer_cfg(cfg.trainer))
|
| 319 |
+
exp_manager(trainer, cfg.get("exp_manager", None))
|
| 320 |
+
|
| 321 |
+
if cfg.model.get("adapter", None) is not None:
|
| 322 |
+
update_model_config_to_support_adapter(cfg.model)
|
| 323 |
+
|
| 324 |
+
asr_model = EncDecRNNTBPEEOUModel(cfg=cfg.model, trainer=trainer)
|
| 325 |
+
|
| 326 |
+
init_from_model = get_pretrained_model_name(cfg)
|
| 327 |
+
if init_from_model:
|
| 328 |
+
init_from_pretrained_nemo(asr_model, init_from_model, cfg)
|
| 329 |
+
|
| 330 |
+
if cfg.model.get("freeze_encoder", False):
|
| 331 |
+
logging.info("Freezing encoder weights.")
|
| 332 |
+
asr_model.encoder.freeze()
|
| 333 |
+
|
| 334 |
+
if cfg.model.get("adapter", None) is not None:
|
| 335 |
+
asr_model = setup_adapters(cfg, asr_model)
|
| 336 |
+
|
| 337 |
+
trainer.fit(asr_model)
|
| 338 |
+
|
| 339 |
+
if hasattr(cfg.model, 'test_ds') and cfg.model.test_ds.manifest_filepath is not None:
|
| 340 |
+
if asr_model.prepare_test(trainer):
|
| 341 |
+
trainer.test(asr_model)
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
if __name__ == '__main__':
|
| 345 |
+
import sys
|
| 346 |
+
sys.argv.extend([
|
| 347 |
+
'--config-path', '../conf/asr_eou/',
|
| 348 |
+
'--config-name', 'fastconformer_transducer_bpe_streaming_large',
|
| 349 |
+
'exp_manager.name=NeMo_Ja_FastConformer_Transducer_RNNT_EOU',
|
| 350 |
+
'exp_manager.resume_if_exists=true',
|
| 351 |
+
'exp_manager.resume_ignore_no_checkpoint=true',
|
| 352 |
+
'exp_manager.exp_dir=results/',
|
| 353 |
+
'exp_manager.checkpoint_callback_params.save_top_k=1',
|
| 354 |
+
'++trainer.check_val_every_n_epoch=1',
|
| 355 |
+
'++model.encoder.conv_norm_type=layer_norm',
|
| 356 |
+
'model.tokenizer.dir=data/common_voice_11_0/ja/tokenizers/tokenizer_spe_bpe_v2491_eou',
|
| 357 |
+
'model.train_ds.tarred_audio_filepaths=data/common_voice_11_0/ja/train_tarred_1bk/audio__OP_0..1023_CL_.tar',
|
| 358 |
+
'++model.train_ds.is_tarred=true',
|
| 359 |
+
'++model.train_ds.tarred_dataset_resolve_paths=false',
|
| 360 |
+
'++model.train_ds.is_tarred_audio=true',
|
| 361 |
+
'model.train_ds.manifest_filepath=data/common_voice_11_0/ja/train_tarred_1bk/tarred_audio_manifest.json',
|
| 362 |
+
'~model.train_ds.augmentor.noise',
|
| 363 |
+
'model.validation_ds.manifest_filepath=data/common_voice_11_0/ja/validation_tarred_1bk/tarred_audio_manifest.json',
|
| 364 |
+
'model.test_ds.manifest_filepath=data/common_voice_11_0/ja/test_tarred_1bk/tarred_audio_manifest.json',
|
| 365 |
+
'trainer.max_epochs=1',
|
| 366 |
+
'trainer.devices=1',
|
| 367 |
+
'trainer.accelerator=gpu',
|
| 368 |
+
'trainer.strategy=auto',
|
| 369 |
+
'trainer.log_every_n_steps=1',
|
| 370 |
+
'model.train_ds.batch_size=1', # Reduced batch size for transducer/EOU as it consumes more memory
|
| 371 |
+
'model.validation_ds.batch_size=1',
|
| 372 |
+
'model.test_ds.batch_size=1',
|
| 373 |
+
'model.train_ds.num_workers=0',
|
| 374 |
+
'model.validation_ds.num_workers=0',
|
| 375 |
+
'model.test_ds.num_workers=0',
|
| 376 |
+
])
|
| 377 |
+
main() # noqa pylint: disable=no-value-for-parameter
|
readme.txt
CHANGED
|
@@ -13,6 +13,9 @@ see https://github.com/NVIDIA-NeMo/NeMo/discussions/8473
|
|
| 13 |
see https://huggingface.co/reazon-research/reazonspeech-nemo-v2
|
| 14 |
reazonspeech 已经训练出日语模型了
|
| 15 |
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
CTC 能正常训练的 nemo 版本是 2.2.1
|
| 18 |
common_voice_11_0 需要的版本是 datasets==3.6.0
|
|
|
|
| 13 |
see https://huggingface.co/reazon-research/reazonspeech-nemo-v2
|
| 14 |
reazonspeech 已经训练出日语模型了
|
| 15 |
|
| 16 |
+
see huggingface_echodict/NeMo_RNNT_EOU/gen_tts_dataset.py
|
| 17 |
+
see huggingface_echodict\asr_rnnt_eou_from_scratch\papers\arXiv-1211.3711v1\training_number.py
|
| 18 |
+
训练中文数字识别
|
| 19 |
|
| 20 |
CTC 能正常训练的 nemo 版本是 2.2.1
|
| 21 |
common_voice_11_0 需要的版本是 datasets==3.6.0
|