微调 Whisper 语音大模型

打印 上一主题 下一主题

主题 2080|帖子 2080|积分 6240

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
1.预备环境

#创建环境
   conda create -n whisper python=3.10 -y  
  source activate whisper
   #安装环境
   conda install pytorch==2.1.0 torchvision==0.16.0 torchaudio==2.1.0 pytorch-cuda=11.8 -c pytorch -c nvidia 
  #下载github微调文件
   git clone https://github.com/yeyupiaoling/Whisper-Finetune.git
  #安装依赖
   cd /root/autodl-tmp/Whisper-Finetune
  python -m pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
  2.加载数据集

导入所有wav文件

计算所有wav时长
  1. import os
  2. import wave
  3. import contextlib
  4. def get_wav_duration(file_path):
  5.     with contextlib.closing(wave.open(file_path, 'r')) as f:
  6.         frames = f.getnframes()
  7.         rate = f.getframerate()
  8.         duration = frames / float(rate)
  9.         return duration
  10. def print_wav_durations(folder_path):
  11.     for root, dirs, files in os.walk(folder_path):
  12.         for file in files:
  13.             if file.endswith('.wav'):
  14.                 file_path = os.path.join(root, file)
  15.                 duration = get_wav_duration(file_path)
  16.                 print(f"File: {file} - Duration: {duration:.2f} seconds")
  17. # 指定包含 .wav 文件的文件夹路径
  18. folder_path = '/root/autodl-tmp/data'
  19. print_wav_durations(folder_path)
复制代码


生成json文件:一个jsonlines的数据列表,也就是每一行都是一个JSON数据
   

  3.微调模型

#修改读取json的地方
在Whisper-Finetune/utils/reader.py修改_load_data_list 函数
  1. # 从数据列表里面获取音频数据、采样率和文本
  2.     def _get_list_data(self, idx):
  3.         if self.data_list_path.endswith(".header"):
  4.             data_list = self.dataset_reader.get_data(self.data_list[idx])
  5.         else:
  6.             data_list = self.data_list[idx]
  7.         # 分割音频路径和标签
  8.         audio_file = data_list["audio"]['path']
  9.         transcript = data_list["sentences"] if self.timestamps else data_list["sentence"]
  10.         language = data_list["language"] if 'language' in data_list.keys() else None
  11.         if 'start_time' not in data_list["audio"].keys():
  12.             sample, sample_rate = soundfile.read(audio_file, dtype='float32')
  13.         else:
  14.             start_time, end_time = data_list["audio"]["start_time"], data_list["audio"]["end_time"]
  15.             # 分割读取音频
  16.             sample, sample_rate = self.slice_from_file(audio_file, start=start_time, end=end_time)
  17.         sample = sample.T
  18.         # 转成单通道
  19.         if self.mono:
  20.             sample = librosa.to_mono(sample)
  21.         # 数据增强
  22.         if self.augment_configs:
  23.             sample, sample_rate = self.augment(sample, sample_rate)
  24.         # 重采样
  25.         if self.sample_rate != sample_rate:
  26.             sample = self.resample(sample, orig_sr=sample_rate, target_sr=self.sample_rate)
  27.         return sample, sample_rate, transcript, language
复制代码
修改Whisper-Finetune/utils/callback.py的SavePeftModelCallback函数
  1. class SavePeftModelCallback(TrainerCallback):
  2.     def on_save(self,
  3.                 args: TrainingArguments,
  4.                 state: TrainerState,
  5.                 control: TrainerControl,
  6.                 **kwargs):
  7.         if args.local_rank == 0 or args.local_rank == -1:
  8.             # 保存效果最好的模型
  9.             best_checkpoint_folder = os.path.join(args.output_dir, f"{PREFIX_CHECKPOINT_DIR}-best")
  10.             # 确保 state.best_model_checkpoint 不是 NoneType
  11.             if state.best_model_checkpoint is not None:
  12.                 # 因为只保存最新5个检查点,所以要确保不是之前的检查点
  13.                 if os.path.exists(state.best_model_checkpoint):
  14.                     if os.path.exists(best_checkpoint_folder):
  15.                         shutil.rmtree(best_checkpoint_folder)
  16.                     shutil.copytree(state.best_model_checkpoint, best_checkpoint_folder)
  17.                     print(f"效果最好的检查点为:{state.best_model_checkpoint},评估结果为:{state.best_metric}")
  18.         return control
复制代码
#下载基础模型
   git clone https://gitee.com/hf-models/whisper-tiny.git
  微调
   cd Whisper-Finetune 
  CUDA_VISIBLE_DEVICES=0 python finetune.py --train_data /root/autodl-tmp/data/data_list_lines.json --test_data /root/autodl-tmp/data/data_list_lines.json --base_model=/root/autodl-tmp/whisper-tiny --output_dir=output/
  

4.合并



  • --lora_model 是训练结束后保存的 Lora 模型路径,就是查抄点文件夹路径
  • --output_dir 是合并后模型的保存目录
   python merge_lora.py --lora_model=/root/autodl-tmp/Whisper-Finetune/output/whisper-tiny/checkpoint-3/ --output_dir=models/
  

5.验证

   python infer.py --audio_path=/root/autodl-tmp/data/0.wav --model_path=models/whisper-
tiny-finetune
  


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

钜形不锈钢水箱

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表