FunASR 微调 Whisper 全流程指南:数据准备、参数配置与源码级原理解析
2026/9/13 16:27:17 网站建设 项目流程

FunASR 微调 Whisper 全流程指南:数据准备、参数配置与源码级原理解析

【免费下载链接】FunASROpen-source speech recognition toolkit for training, inference, streaming ASR, VAD, punctuation, speaker diarization pipelines, and OpenAI-compatible/MCP serving.项目地址: https://gitcode.com/GitHub_Trending/fun/FunASR

本文以 FunASR 开源仓库中 examples/industrial_data_pretraining/whisper/README.md 为骨架,系统讲解如何在 FunASR 训练框架下对 OpenAI Whisper 系列模型(tiny 到 large-v3-turbo)进行领域数据微调与推理部署。你将掌握 JSONL 数据集的构造规范、funasr.bin.train训练命令的完整参数语义、关键超参数(学习率、batch size、warmup、冻结编码器)的调优策略,以及微调后通过 AutoModel 一键加载与多路径推理的实战方法,同时深入理解 FunASR 中WhisperWarp模型封装(funasr/models/whisper/model.py)的训练与推理底层实现。

一、为什么在 FunASR 中微调 Whisper

OpenAI Whisper 是业界广泛使用的多语言语音识别基础模型,但其通用能力在垂直领域(如金融、医疗、工业术语、方言口音)往往表现不佳。FunASR 将 Whisper 无缝纳入其统一的训练与推理框架:同一套AutoModel接口、同一套 JSONL 数据管线、同一套funasr.bin.train训练入口,即可完成从数据准备到模型微调再到推理部署的完整闭环。

从源码看,FunASR 通过 funasr/models/whisper/model.py 中的WhisperWarp类对 Whisper 做了包装,并注册了从Whisper-tiny.enWhisper-large-v3-turbo的全系列模型名(见 funasr/register.py 对应的注册表)。这意味着训练脚本中只需通过++model="Whisper-large-v3"字符串即可指定模型,训练框架会自动解析并实例化对应结构。

二、支持微调的模型列表

根据 examples/industrial_data_pretraining/whisper/README.md 及finetune.sh脚本中的说明,FunASR 支持以下 Whisper 变体:

模型名称说明
whisper-tiny / whisper-tiny.en最小规模,适合快速验证流程
whisper-base / whisper-base.en轻量级基线
whisper-small / whisper-small.en速度与精度均衡
whisper-medium / whisper-medium.en中等规模
whisper-large-v1 / whisper-large-v2 / whisper-large-v3大规模高精度
whisper-large-v3-turbov3 的加速蒸馏版本,推理更快

对应到 FunASR 模型名(在++model中使用时需遵循注册名,如Whisper-large-v3),全部由 funasr/models/whisper/model.py 中的@tables.register("model_classes", ...)装饰器注册。.en后缀的模型为纯英文模型,若目标领域主要为中文,应优先选择多语言版本(无.en后缀)。

三、数据准备:JSONL 格式规范

Whisper 微调使用 JSONL(JSON Lines)格式的数据集,每行一个 JSON 对象,包含三个字段:

  • key:样本唯一标识(字符串);
  • source:音频文件路径(本地绝对/相对路径或 URL);
  • target:对应的转写文本。
{"key": "utt001", "source": "/path/to/audio1.wav", "target": "the transcription text"} {"key": "utt002", "source": "/path/to/audio2.wav", "target": "another transcription"}

仓库中已提供了可直接参考的真实样例数据 data/list/train.jsonl,其完整字段形式如下:

{"key": "BAC009S0764W0121", "source": "https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/test_audio/BAC009S0764W0121.wav", "source_len": 90, "target": "甚至出现交易几乎停滞的情况", "target_len": 13}

可以看到除key/source/target外,还可附带source_lentarget_len等元信息字段(非必需,训练框架按需读取)。验证集val.jsonl与训练集格式完全一致,分别通过++train_data_set_list++valid_data_set_list指定。

四、发起微调训练

4.1 一键脚本

仓库提供了开箱即用的训练脚本 finetune.sh,直接执行:

bash finetune.sh

脚本内容如下(完整继承,含全部参数):

#!/bin/bash # Whisper Fine-tuning with FunASR # Data format: JSONL with "audio" and "text" fields # {"key": "utt1", "source": "/path/to/audio.wav", "target": "transcription text"} export CUDA_VISIBLE_DEVICES=0,1 model_name="Whisper-large-v3" train_data="data/train.jsonl" val_data="data/val.jsonl" output_dir="exp/whisper_finetune" python -m funasr.bin.train \ ++model="${model_name}" \ ++model_conf.hub="openai" \ ++train_data_set_list="${train_data}" \ ++valid_data_set_list="${val_data}" \ ++dataset_conf.batch_size=4 \ ++dataset_conf.num_workers=4 \ ++train_conf.output_dir="${output_dir}" \ ++train_conf.max_epoch=10 \ ++train_conf.lr=1e-5 \ ++train_conf.warmup_steps=500 \ ++optim="adam" \ ++optim_conf.lr=1e-5 \ ++scheduler="warmuplr" \ ++scheduler_conf.warmup_steps=500

4.2 命令行参数逐项解读

训练统一通过python -m funasr.bin.train启动,使用++前缀的 Hydra 覆盖语法传参。各参数含义如下:

参数取值示例作用
modelWhisper-large-v3指定模型注册名,决定模型结构
model_conf.hubopenai权重来源;openai表示直接调用whisper.load_model从 OpenAI 加载官方权重(需pip install openai-whisper),funasr/modelscope则从模型仓库加载
train_data_set_listdata/train.jsonl训练集 JSONL 路径
valid_data_set_listdata/val.jsonl验证集 JSONL 路径
dataset_conf.batch_size4每张 GPU 的 batch size,需根据显存调整
dataset_conf.num_workers4DataLoader 数据加载进程数
train_conf.output_direxp/whisper_finetune模型 checkpoint 与日志输出目录
train_conf.max_epoch10最大训练轮数
train_conf.lr1e-5学习率(大模型建议更小)
train_conf.warmup_steps500学习率 warmup 步数
optimadam优化器类型
optim_conf.lr1e-5优化器侧学习率(与train_conf.lr保持一致)
schedulerwarmuplr学习率调度器类型
scheduler_conf.warmup_steps500调度器 warmup 步数

4.3 训练底层原理:交叉熵损失与教师强制

funasr/models/whisper/model.py 中的forward()实现了微调的核心逻辑,其数据流为:

  1. 编码器前向audio_features = self.model.encoder(speech),输入为(B, T, D)的 mel 频谱特征;
  2. 教师强制(Teacher Forcing):训练时文本序列格式为[SOT, lang, task, ..., tokens, EOT],代码通过text[:, :-1]作为解码器输入、text[:, 1:]作为目标,逐 token 右移一位,避免模型在训练阶段看到未来 token;
  3. 解码器前向logits = self.model.decoder(decoder_input, audio_features)
  4. 交叉熵损失F.cross_entropy(logits, decoder_target, ignore_index=-100),pad 位置通过ignore_index=-100屏蔽。

forward()返回{"loss": loss, "stats": {...}}字典,其中stats记录了当前 loss 与 batch size,供训练框架打印与监控。这也解释了 README 中"Training uses the forward() method which computes cross-entropy loss on (mel-spectrogram, token_ids) pairs"的说明。

4.4 模型加载机制:hub 参数的分流逻辑

WhisperWarp.__init__(funasr/models/whisper/model.py)根据hub参数走两条加载路径:

  • hub == "openai":将Whisper-large-v3等模型名去掉Whisper-前缀后,直接调用whisper.load_model("large-v3")加载 OpenAI 官方预训练权重;
  • 其他 hub(默认funasr):通过whisper.model.ModelDimensionswhisper.model.Whisper(dims=dims)从模型仓库(如 ModelScope)的配置与权重重建模型。

因此微调时++model_conf.hub="openai"意味着从 OpenAI 官方权重开始微调;若需基于已有 FunASR/ModelScope 格式权重,可切换 hub 并配合本地模型目录。

五、关键超参数与实战调优 Tips

原文档给出的核心参数表(examples/industrial_data_pretraining/whisper/README.md):

参数默认值说明
modelWhisper-large-v3模型规模
lr1e-5学习率(模型越大取值越小)
max_epoch10训练轮数
batch_size4每张 GPU 的 batch size
warmup_steps500学习率预热步数

结合 README 的 Tips 与训练框架机制,给出以下实战建议:

  1. 中文场景首选whisper-large-v3:它是多语言模型中中文支持最好的版本,作为领域微调基座能保留最强的多语言泛化能力。
  2. 冻结编码器加速训练:在训练命令末尾追加++train_conf.freeze_param="model.encoder",可冻结 Whisper 编码器仅训练解码器部分,显著减少显存占用与训练时间。对于数据量有限或只需适配领域文本分布的场景,这是性价比很高的策略。
  3. 使用更小的学习率(1e-5 ~ 5e-6):Whisper 预训练权重非常成熟,过大的学习率会导致灾难性遗忘(catastrophic forgetting)。finetune.shlr=1e-5是通用起点,大规模模型建议降至 5e-6。
  4. 数据量建议:README 建议目标领域音频100 小时以上才能获得有意义的提升;数据不足时可结合冻结编码器 + 低学习率避免过拟合。
  5. 显存不足时的调整dataset_conf.batch_size=4为每 GPU 的 batch size,出现 OOM 时可降至 1~2,并同步降低lr或延长max_epoch以保持等效训练量。

六、微调后的推理与部署

6.1 加载微调 checkpoint 推理

微调完成后,checkpoint 保存在output_dir(默认exp/whisper_finetune)。通过AutoModel直接指定本地模型路径即可加载:

from funasr import AutoModel # Load fine-tuned model model = AutoModel(model="/path/to/exp/whisper_finetune") result = model.generate(input="test.wav") print(result[0]["text"])

推理返回结果列表,每个元素形如{"key": ..., "text": ...},与 funasr/models/whisper/model.py 中inference()返回结构一致。

6.2 从 OpenAI 权重直接推理(未微调场景)

仓库提供 demo_from_openai.py,演示如何从 OpenAI 官方权重加载 Whisper-large-v3-turbo 并配合 FunASR 的 VAD 模型做长音频切分推理:

from funasr import AutoModel model = AutoModel( model="Whisper-large-v3-turbo", vad_model="iic/speech_fsmn_vad_zh-cn-16k-common-pytorch", vad_kwargs={"max_single_segment_time": 30000}, hub="openai", ) DecodingOptions = { "task": "transcribe", "language": None, "beam_size": None, "fp16": True, "without_timestamps": False, "prompt": None, } res = model.generate( DecodingOptions=DecodingOptions, batch_size_s=0, input="https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/test_audio/asr_example_zh.wav", ) print(res)

要点说明:

  • hub="openai"对应WhisperWarp的 OpenAI 加载路径(需pip3 install -U openai-whisper);
  • vad_model指定 FunASR 的流式 VAD 模型,max_single_segment_time=30000将超过 30 秒的音频自动切段,规避 Whisper 长音频性能衰减;
  • DecodingOptions直接透传给 OpenAI Whisper 的whisper.DecodingOptions(对应源码 funasr/models/whisper/model.py 中的whisper.DecodingOptions(**kwargs.get("DecodingOptions", {}))),支持task(transcribe/translate)、languagebeam_sizefp16without_timestampsprompt(提示词热词)等完整解码控制。

6.3 命令行推理(三种方式)

仓库提供三种命令行推理脚本,均通过python -m funasr.bin.inference启动:

方式一:从模型仓库推理(infer.sh)

input="https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/test_audio/asr_example_zh.wav" output_dir="./outputs/debug" model="iic/speech_whisper-large_asr_multilingual" device="cuda:0" # "cuda:0" for gpu0, "cuda:1" for gpu1, "cpu" python -m funasr.bin.inference \ ++model=${model} \ ++input="${input}" \ ++output_dir="${output_dir}" \ ++device="${device}"

方式二:从本地模型推理(infer_from_local.sh)——先从 ModelScope 克隆模型到本地,再用--config-path/--config-name指向本地目录:

local_path_root=${workspace}/modelscope_models mkdir -p ${local_path_root} local_path=${local_path_root}/Whisper-large-v3 git clone https://www.modelscope.cn/iic/Whisper-large-v3.git ${local_path} init_param="${local_path}/large-v3.pt" config="config.yaml" python -m funasr.bin.inference \ --config-path "${local_path}" \ --config-name "${config}" \ ++init_param="${init_param}" \ ++input="${input}" \ ++output_dir="${output_dir}" \ ++device="${device}"

方式三:从 OpenAI hub 推理(infer_from_openai.sh)

model="Whisper-large-v2" # 也支持 Whisper-small / Whisper-medium / Whisper-large-v3 hub="openai" device="cuda:0" python -m funasr.bin.inference \ ++model=${model} \ ++hub=${hub} \ ++input="${input}" \ ++output_dir="${output_dir}" \ ++device="${device}"

其中方式二与微调后的本地 checkpoint 推理路径一致:--config-path指向模型目录、++init_param指定权重文件(微调后即output_dir下的模型文件),适合离线部署环境;input支持本地音频路径、URL 等输入形式(详见 infer.sh 注释)。

七、总结:从微调到落地的完整链路

本文基于 examples/industrial_data_pretraining/whisper/ 目录,完整覆盖了 FunASR 微调 Whisper 的五个环节:

  1. 模型选型:根据语言(中/英)与算力选择 tiny 至 large-v3-turbo 系列,通过++model注册名指定;
  2. 数据构造:按{"key", "source", "target"}的 JSONL 规范准备训练集与验证集(参考 data/list/train.jsonl);
  3. 训练启动bash finetune.sh或自定义python -m funasr.bin.train,核心参数包括model_conf.hubdataset_conf.batch_sizetrain_conf.lr/max_epoch/warmup_steps
  4. 调优策略:中文用 large-v3、小学习率 1e-5~5e-6、freeze_param冻结编码器加速、100+ 小时领域数据保障效果;
  5. 推理部署:AutoModel 加载本地 checkpoint 一键推理,或通过python -m funasr.bin.inference支持模型仓库、本地目录、OpenAI 权重三种来源。

源码层面,funasr/models/whisper/model.py 的WhisperWarp封装清晰展示了训练(教师强制 + 交叉熵)与推理(whisper.decode+DecodingOptions透传)的完整实现,微调者既可以把它当作黑盒使用,也可以在需要定制损失函数或解码策略时以此为切入点深入改造。

【免费下载链接】FunASROpen-source speech recognition toolkit for training, inference, streaming ASR, VAD, punctuation, speaker diarization pipelines, and OpenAI-compatible/MCP serving.项目地址: https://gitcode.com/GitHub_Trending/fun/FunASR

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询