NeMo TTS 配置指南:从数据集、预处理器到模型微调的完整 YAML 配置解析
【免费下载链接】SpeechA scalable generative AI framework built for researchers and developers working on Large Language Models, Multimodal, and Speech AI (Automatic Speech Recognition and Text-to-Speech)项目地址: https://gitcode.com/GitHub_Trending/nem/Speech
本指南以 NeMo(NVIDIA NeMo 语音生成框架,仓库根目录为GitHub_Trending/nem/Speech)TTS 集合的配置体系为主题,系统讲解 TTS 训练与微调过程中 YAML 配置文件的核心组成:数据集(model.train_ds/validation_ds/test_ds)、音频预处理器(preprocessor)、文本正则化(text_normalizer)、分词器(text_tokenizer)、模型架构模块(input_fft、duration_predictor等)以及三种预训练权重加载方式。读完本文,你将能够读懂并编写一份完整的 NeMo TTS 训练配置,并掌握通过命令行覆盖配置实现 HiFi-GAN、FastPitch 等模型微调的完整操作路径。
配置文件总览:一个 TTS 实验由哪些部分构成
NeMo 使用 Hydra + OmegaConf 管理实验配置,TTS 集合的配置文件围绕model根节点展开,一般需要描述以下信息:
- 数据集:训练 / 验证 / 测试数据集的 manifest 路径、采样率、补充数据(对齐先验、基频等);
- 音频预处理器:将原始音频信号转换为特征(如 mel 频谱)的模块;
- 文本正则化器:将书面文本转换为可发音的口语化文本;
- 文本分词器:将文本转换为整数 token 序列;
- 模型架构:各子模块(编码器、解码器、预测器等)的
_target_与初始化参数; - 优化器与调度器:
optim与optim.sched; - 训练器与实验管理:
trainer与exp_manager。
其中与所有 NeMo 模型通用的部分(如 PyTorch Lightning Trainer 参数、Experiment Manager)参见仓库中的 docs/source/core 文档;TTS 专属的配置细节则是本文的主体。仓库为所有 TTS 训练脚本提供了可直接使用的示例配置文件,位于 examples/tts/conf,覆盖 FastPitch(fastpitch/、fastpitch_align_44100.yaml)、HiFi-GAN(hifigan/)、声码器与编解码器(audio_codec/)、多语言(de/、es/、zh/)等多种场景,是学习和复用配置的最佳起点。
数据集配置:train_ds / validation_ds / test_ds
训练、验证、测试参数分别在model.train_ds、model.validation_ds、model.test_ds小节中指定。依据具体任务,这些小节可能包含音频采样率、补充数据(如语音/文本对齐先验、说话人 ID)、前后静音裁剪阈值、基频归一化参数等。你甚至可以将manifest_filepath留空,待运行时通过命令行指定。
TTSDataset 的典型训练与验证配置如下(完整继承自 docs/source/tts/configs.rst):
model: train_ds: dataset: _target_: nemo.collections.tts.data.dataset.TTSDataset manifest_filepath: ??? sample_rate: 44100 sup_data_path: ??? sup_data_types: ["align_prior_matrix", "pitch"] n_fft: 2048 win_length: 2048 hop_length: 512 window: hann n_mels: 80 lowfreq: 0 highfreq: null max_duration: null min_duration: 0.1 ignore_file: null trim: false pitch_fmin: 65.40639132514966 pitch_fmax: 2093.004522404789 pitch_norm: true pitch_mean: 212.35873413085938 pitch_std: 68.52806091308594 use_beta_binomial_interpolator: true dataloader_params: drop_last: false shuffle: true batch_size: 32 num_workers: 12 pin_memory: true任何TTSDataset类(nemo/collections/tts/data/dataset.py)构造函数可接受的初始化参数,都可以直接写进配置文件。各核心参数含义如下:
| 参数 | 默认值 | 说明 |
|---|---|---|
manifest_filepath | 必填 | 一个或多个.jsonmanifest 文件路径,每行一条合法 JSON 记录 |
sample_rate | 必填 | 音频采样率,所有音频将被重采样到该值 |
sup_data_path | 必填(按需) | 补充数据(如基频、对齐先验矩阵)的存放/读取目录,首次计算后会被缓存 |
sup_data_types | 无 | 补充数据类型列表,如align_prior_matrix、pitch、energy、speaker_id等 |
n_fft / win_length / hop_length | 1024 / None / None | STFT 参数,win_length缺省用n_fft,hop_length缺省用n_fft // 4 |
window | hann | 窗函数,可选hann、hamming、blackman、bartlett、none |
n_mels | 80 | mel 滤波器数量 |
lowfreq / highfreq | 0 / None | mel 滤波器组的频率范围 |
max_duration / min_duration | None / None | 按秒过滤样本(需要 manifest 含duration字段),不会加载音频来计算时长 |
ignore_file | None | 一个 JSON 格式的音频路径黑名单,训练前剔除对应样本 |
trim | false | 是否用librosa.effects.trim裁剪前后静音 |
trim_ref / trim_top_db / trim_frame_length / trim_hop_length | 峰值 / 60 / 2048 / 512 | 静音裁剪的参考幅度、阈值(dB)与分析窗参数 |
pitch_fmin / pitch_fmax | C2 / C7 | librosa.pyin提取基频的频率范围 |
pitch_norm | false | 是否归一化基频,开启时需提供pitch_stats_path或pitch_mean/pitch_std |
pitch_mean / pitch_std | 无 | 基频归一化使用的均值与标准差 |
use_beta_binomial_interpolator | false | 是否使用 beta-binomial 插值器计算对齐先验矩阵 |
从 TTSDataset 源码 可以看到,该数据集"加载主要数据类型(音频、文本)以及指定的补充数据类型(log mel、时长、对齐先验矩阵、基频、能量、说话人 ID)",部分补充数据会在首次运行时即时计算并保存到sup_data_path,后续训练直接复用。另外 manifest 支持以下字段(源码注释明确列出):
audio_filepath:wav 音频路径(必填);text:原始转录文本(必填);normalized_text:已归一化的文本(可选,缺省时由文本归一化器现场生成);mel_filepath:log-mel 张量路径(可选);duration:音频时长(秒,可选,用于时长过滤与日志统计);speaker:说话人 ID(可选,多说话人模型需要)。
值得注意的源码细节:若text_normalizer存在,dataset.py 会优先使用 manifest 中的normalized_text或text_normalized字段,否则对text现场执行归一化;dataloader_params中的drop_last、shuffle、batch_size、num_workers、pin_memory等直接透传给 PyTorch DataLoader,其中batch_size通常放在配置文件顶层通过${batch_size}引用,便于统一调整。
作为对照,当前仓库的 examples/tts/conf/fastpitch/fastpitch_44100.yaml 使用了新一代的TextToSpeechDataset(nemo.collections.tts.data.text_to_speech_dataset.TextToSpeechDataset),它通过dataset_meta、featurizers(MelSpectrogramFeaturizer、PitchFeaturizer、EnergyFeaturizer)和feature_processors(如MeanVarianceSpeakerNormalization)来组织数据管线,结构上更模块化,但其核心设计思想与TTSDataset一致:manifest 驱动、特征按需计算并缓存。
音频预处理器配置:从波形到特征
如果实验需要加载音频,通常要配置预处理器把原始音频信号转换为特征(如 mel 频谱或 MFCC)。model.preprocessor小节通过_target_字段指定预处理器类及其初始化参数:
model: preprocessor: _target_: nemo.collections.asr.modules.AudioToMelSpectrogramPreprocessor features: 80 lowfreq: 0 highfreq: null n_fft: 2048 n_window_size: 2048 window_size: false n_window_stride: 512 window_stride: false pad_to: 1 pad_value: 0 sample_rate: 44100 window: hann normalize: null preemph: null dither: 0.0 frame_splicing: 1 log: true log_zero_guard_type: add log_zero_guard_value: 1e-05 mag_power: 1.0各参数的作用与取值建议:
features:mel 频带数,需与数据集配置中的n_mels保持一致(FastPitch 常见为 80);lowfreq/highfreq:mel 滤波器组的频率下限 / 上限(null表示不加限制);n_fft/n_window_size:FFT 点数与窗长(对 44.1 kHz 音频通常为 2048);n_window_stride:帧移(44.1 kHz 下常为 512,即约 11.6 ms);window:窗函数,常用hann;pad_to/pad_value:帧对齐填充,pad_to: 1表示不强制对齐;normalize/preemph:特征归一化与预加重,null表示关闭;dither:抖动噪声强度,0.0 关闭;frame_splicing:帧拼接数,1 表示不拼接;log:是否对 mel 特征取对数;log_zero_guard_type/log_zero_guard_value:取对数时的零值保护策略(add表示加一个极小值,clamp表示截断),避免log(0);mag_power:幅度幂次(1.0 表示使用幅值而非能量)。
ASR 集合下所有预处理器选项、参数与默认值的完整列表,可参考 ASR API 文档中的 Audio Preprocessors 章节(docs/source/asr/api.rst),实现位于 nemo/collections/asr/modules。注意不同模型的预处理器存在差异:例如 examples/tts/conf/hifigan/hifigan_44100.yaml 中的 HiFi-GAN 使用nemo.collections.asr.parts.preprocessing.features.FilterbankFeatures,并设置log_zero_guard_type: clamp、pad_to: 0、pad_value: -11.52、use_grads: false、exact_pad: true。因此在迁移配置时,务必以目标模型仓库自带的示例配置为准。
文本正则化配置:书面文本 → 口语化文本
文本正则化(Text Normalization,TN)将书面文本转换为口语化形式,是 TTS 合成前不可或缺的预处理步骤,确保 TTS 能够处理所有输入文本而不跳过未知符号。例如$123会被转换为 "one hundred and twenty three dollars"。目前 NeMo 支持英语、德语、西班牙语和中文的文本归一化,具体实现在nemo_text_processing包中。英语归一化器配置示例如下:
model: text_normalizer: _target_: nemo_text_processing.text_normalization.normalize.Normalizer lang: en input_case: cased text_normalizer_call_kwargs: verbose: false punct_pre_process: true punct_post_process: true_target_:指向nemo_text_processing包中的Normalizer类;lang:目标语言(en、de、es、zh等);input_case:输入文本大小写策略,cased保留大小写;text_normalizer_call_kwargs:调用归一化函数时的关键字参数,verbose控制日志输出,punct_pre_process/punct_post_process控制在归一化前后对标点符号的处理。
从 TTSDataset 源码 可以看到,数据集加载时若配置了text_normalizer且 manifest 中缺少归一化文本,会调用self.text_normalizer_call(text, **self.text_normalizer_call_kwargs)现场完成归一化;同时,若nemo_text_processing未安装(PYNINI_AVAILABLE为 False),会直接抛出ImportError,提示移除 TTS YAML 中的text_normalizer段落或安装该包。换言之,文本归一化是一个可选的硬依赖模块——不想使用时删除配置中对应段落即可。
Tokenizer 配置:文本 → token 序列
分词(Tokenization)将文本字符串转换为整数 token 列表,并可能为字符串首尾补充空白。NeMo 的 TTS tokenizer 支持纯 grapheme(字素)输入、纯 phoneme(音素)输入,以及 grapheme 与 phoneme 混合输入,以消解英语、德语、西班牙语中异形同音词(heteronym)的发音歧义;同时利用字素到音素(G2P)工具转写词汇表外的词(OOV)。以下配置示例建立了一个EnglishPhonemesTokenizer,使用 grapheme 与 phoneme 混合输入,异形同音词列表中的每个词以 50% 概率被转写为 grapheme 或 phoneme:
model: text_tokenizer: _target_: nemo.collections.common.tokenizers.text_to_speech.tts_tokenizers.EnglishPhonemesTokenizer punct: true stresses: true chars: true apostrophe: true pad_with_space: true g2p: _target_: nemo.collections.tts.g2p.models.en_us_arpabet.EnglishG2p phoneme_dict: ${phoneme_dict_path} heteronyms: ${heteronyms_path} phoneme_probability: 0.5punct:是否为基本标点保留 token;stresses:是否使用带重音标记(0-2)的音素编码;chars:是否在音素之外同时使用字符(当phoneme_probability非空时会被强制启用);apostrophe:是否处理撇号;pad_with_space:是否在文本首尾补充空格;g2p:G2P 模块,phoneme_dict指向音素字典,heteronyms指向异形同音词列表;phoneme_probability:词被转写为音素的概率。
从 tts_tokenizers.py 的实现看,EnglishPhonemesTokenizer内部维护了固定的元音集(AA、AE…共 15 个)与辅音集(B、CH、D…共 24 个);开启stresses后,元音会扩展为带重音标记的形式(如AA0、AA1、AA2,共 45 个);当chars或phoneme_probability非空时追加 26 个小写字母作为字符 token。类内部还会从g2p模块读取phoneme_probability属性(tts_tokenizers.py),用于决定每个词走音素还是字素路径。更多 G2P 细节见仓库的 docs/source/tts/g2p.rst。原文档特别说明,G2P 与 NeMo TTS tokenizer 管线的完整集成即将推出,使用时需留意版本差异。
模型架构配置:以 FastPitch 为例
每个配置文件都应描述实验所用的模型架构。NeMo TTS 集合的模型由多个带_target_字段的模块小节组成,模块实现集中在 nemo/collections/tts/modules。下面是一个完整的 FastPitch 架构配置示例(对齐器 + 时长/基频预测器 + 优化器):
model: input_fft: #n_embed and padding_idx are added by the model _target_: nemo.collections.tts.modules.transformer.FFTransformerEncoder n_layer: 6 n_head: 1 d_model: 384 d_head: 64 d_inner: 1536 kernel_size: 3 dropout: 0.1 dropatt: 0.1 dropemb: 0.0 d_embed: 384 output_fft: _target_: nemo.collections.tts.modules.transformer.FFTransformerDecoder n_layer: 6 n_head: 1 d_model: 384 d_head: 64 d_inner: 1536 kernel_size: 3 dropout: 0.1 dropatt: 0.1 dropemb: 0.0 alignment_module: _target_: nemo.collections.tts.modules.aligner.AlignmentEncoder n_text_channels: 384 duration_predictor: _target_: nemo.collections.tts.modules.fastpitch.TemporalPredictor input_size: 384 kernel_size: 3 filter_size: 256 dropout: 0.1 n_layers: 2 pitch_predictor: _target_: nemo.collections.tts.modules.fastpitch.TemporalPredictor input_size: 384 kernel_size: 3 filter_size: 256 dropout: 0.1 n_layers: 2 optim: name: adamw lr: 1e-3 betas: [0.9, 0.999] weight_decay: 1e-6 sched: name: NoamAnnealing warmup_steps: 1000 last_epoch: -1 d_model: 1 # Disable scaling based on model dim各模块要点:
input_fft/output_fft:基于 Transformer 的 FFT 编码器 / 解码器(FFTransformerEncoder/FFTransformerDecoder)。注释说明n_embed与padding_idx会由模型自动补齐,无需在配置中显式给出;d_model为模型维度、d_head为注意力头维度、d_inner为前馈网络中间维度、kernel_size为卷积核大小、dropout/dropatt/dropemb分别控制整体、注意力与 embedding 的丢弃率;alignment_module:对齐编码器AlignmentEncoder,n_text_channels需与d_model一致,用于学习文本与 mel 帧之间的软对齐;duration_predictor/pitch_predictor:TemporalPredictor时序预测器,输入维度input_size对齐d_model,filter_size为隐藏层维度,n_layers为层数;optim:优化器采用 AdamW(lr: 1e-3,betas: [0.9, 0.999],weight_decay: 1e-6);sched使用 Noam 退火调度(NoamAnnealing),warmup_steps: 1000,d_model: 1关闭基于模型维度的缩放(配置注释明确说明)。
对照仓库中的真实配置 examples/tts/conf/fastpitch/fastpitch_44100.yaml 可以发现:模型参数(learn_alignment: true、n_mel_channels、min/max_token_duration、symbols_embedding_dim、各损失权重dur_loss_scale、pitch_loss_scale、energy_loss_scale、aligner_loss_scale等)位于model顶层;子模块通过${...}插值引用顶层变量(如d_model: ${model.symbols_embedding_dim}),并额外配置了energy_predictor、AlignmentEncoder的dist_type: cosine与temperature: 15.0。这种"顶层数据集参数 + 模块插值"的写法保证了数据集配置与模型架构配置的一致性,是编写新 TTS 配置时推荐的结构。
微调配置:三种预训练权重加载方式
所有 TTS 脚本都支持便捷微调:将预训练权重部分或完整地加载到当前实例化的模型中。前提是当前实例化模型的参数与预训练 checkpoint 匹配(权重才能正确加载)。预训练权重有三种提供方式:
- 提供一个 NeMo 模型文件的路径:
init_from_nemo_model; - 提供一个预训练 NeMo 模型的名称(将从云端下载):
init_from_pretrained_model; - 提供一个 PyTorch Lightning checkpoint 文件路径:
init_from_ptl_ckpt。
仓库中对应每种 TTS 模型都有微调脚本,位于 examples/tts,命名规律为<model>_finetune.py(如fastpitch_finetune.py、hifigan_finetune.py)。下面以 HiFi-GAN 为例,展示三种微调方式(命令中的--config-path指向配置文件目录、--config-name指定不含.yaml后缀的配置名,~model.optim.sched表示删除调度器,+init_from_*前缀的加号表示向配置新增该字段):
方式一:通过 NeMo 模型文件微调
python examples/tts/hifigan_finetune.py \ --config-path=<path to dir of configs> \ --config-name=<name of config without .yaml>) \ model/train_ds=train_ds_finetune \ model/validation_ds=val_ds_finetune \ train_dataset="<path to manifest file>" \ validation_dataset="<path to manifest file>" \ model.optim.lr=0.00001 \ ~model.optim.sched \ trainer.devices=-1 \ trainer.accelerator='gpu' \ trainer.max_epochs=50 \ +init_from_nemo_model="<path to .nemo model file>"方式二:通过预训练模型名称微调(自动从云端下载)
python examples/tts/hifigan_finetune.py \ --config-path=<path to dir of configs> \ --config-name=<name of config without .yaml>) \ model/train_ds=train_ds_finetune \ model/validation_ds=val_ds_finetune \ train_dataset="<path to manifest file>" \ validation_dataset="<path to manifest file>" \ model.optim.lr=0.00001 \ ~model.optim.sched \ trainer.devices=-1 \ trainer.accelerator='gpu' \ trainer.max_epochs=50 \ +init_from_pretrained_model="<name of pretrained checkpoint>"方式三:通过 PyTorch Lightning checkpoint 微调
python examples/tts/hifigan_finetune.py \ --config-path=<path to dir of configs> \ --config-name=<name of config without .yaml>) \ model/train_ds=train_ds_finetune \ model/validation_ds=val_ds_finetune \ train_dataset="<path to manifest file>" \ validation_dataset="<path to manifest file>" \ model.optim.lr=0.00001 \ ~model.optim.sched \ trainer.devices=-1 \ trainer.accelerator='gpu' \ trainer.max_epochs=50 \ +init_from_ptl_ckpt="<name of pytorch lightning checkpoint>"上述三条命令的关键点:model/train_ds与model/validation_ds覆盖为微调专用数据集配置(如train_ds_finetune);train_dataset/validation_dataset覆盖为实际的 manifest 路径;微调通常使用更小的学习率(示例中lr=0.00001)并删除学习率调度器(~model.optim.sched);trainer.devices=-1使用全部可用 GPU。
从脚本实现看,微调入口非常简洁。以 examples/tts/hifigan_finetune.py 为例,它通过@hydra_runner(config_path="conf/hifigan", config_name="hifigan_44100")声明配置,主函数依次构建pl.Trainer、调用exp_manager、实例化HifiGanModel(cfg=cfg.model, trainer=trainer),再调用model.maybe_init_from_pretrained_checkpoint(cfg=cfg)完成权重加载后进入trainer.fit(model)。类似地,examples/tts/fastpitch_finetune.py 会在检测到配置中仍带调度器时打印警告("You are using an optimizer scheduler while finetuning. Are you sure this is intended?"),并在学习率超出1e-5~1e-3范围时提示"微调推荐学习率为 2e-4",这些提示与上面命令行中~model.optim.sched和model.optim.lr=0.00001的操作相互印证。若需为新说话人微调 FastPitch,可参考仓库中的 examples/tts/fastpitch_finetune.py 以及 tutorials/tts 目录下的 TTS 教程。
小结:一份可落地的 TTS 配置编写清单
综合本文内容,编写或修改一份 NeMo TTS 配置文件时可遵循以下检查清单:
- 数据集:确认
manifest_filepath指向正确的 manifest,sample_rate、STFT 参数(n_fft/win_length/hop_length/n_mels)与预处理阶段保持一致,需要基频或对齐先验时正确设置sup_data_types与sup_data_path; - 预处理器:
features与数据集的n_mels对齐,n_window_size/n_window_stride与win_length/hop_length一致,44.1 kHz 场景下n_fft: 2048、n_window_stride: 512是常用取值; - 文本正则化:按语种设置
lang,未安装nemo_text_processing时删除该段配置; - 分词器:根据任务选择 grapheme-only / phoneme-only / 混合模式,混合模式用
phoneme_probability控制音素化概率,确保g2p的字典与异形同音词路径正确; - 模型架构:各子模块的维度参数(
d_model、input_size、n_text_channels等)必须相互匹配,建议使用${...}插值统一管理; - 微调:根据预训练权重的来源选择
init_from_nemo_model/init_from_pretrained_model/init_from_ptl_ckpt三者之一,搭配小学习率并删除调度器。
配置即实验蓝图,NeMo 将数据集、预处理、文本处理与模型架构统一纳入 YAML 管理体系,使得复现与微调都只需修改配置即可完成。本文所述配置的完整可运行示例,均可在仓库的 examples/tts/conf 目录中找到对应模型的参考文件。
【免费下载链接】SpeechA scalable generative AI framework built for researchers and developers working on Large Language Models, Multimodal, and Speech AI (Automatic Speech Recognition and Text-to-Speech)项目地址: https://gitcode.com/GitHub_Trending/nem/Speech
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考