前文回溯,之前一篇:含辞未吐,声若幽兰,史上最强免费人工智能AI语音合成TTS服务微软Azure(Python3.10接入),利用AI技术将文本合成语音,现在反过来,利用开源库Whisper再将语音转回文字,所谓闻其声而知雅意。

Whisper 是一个开源的语音识别库,它是由Facebook AI Research (FAIR)开发的,支持多种语言的语音识别。它使用了双向循环神经网络(bi-directional RNNs)来识别语音并将其转换为文本。 Whisper支持自定义模型,可以用于实现在线语音识别,并且具有高级的语音识别功能,支持语音识别中的语音活动检测和语音识别中的语音转文本。它是使用PyTorch进行开发,可以使用Python API来调用语音识别,并且提供了一系列的预训练模型和数据集来帮助用户开始使用。

PyTorch基于MPS的安装

我们知道PyTorch一直以来在M芯片的MacOs系统中都不支持cuda模式,而现在,新的MPS后端扩展了PyTorch生态系统并提供了现有的脚本功能来在 GPU上设置和运行操作。

截止本文发布,PyTorch与Python 3.11不兼容,所以我们将使用最新的 3.10.x 版本。

确保安装Python3.10最新版:

➜  transformers git:(stable) python3
Python 3.10.9 (main, Dec 15 2022, 17:11:09) [Clang 14.0.0 (clang-1400.0.29.202)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

随后运行安装命令:

pip3 install --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cpu

安装成功后,在终端里验证PyTorch-MPS的状态:

➜  transformers git:(stable) python3
Python 3.10.9 (main, Dec 15 2022, 17:11:09) [Clang 14.0.0 (clang-1400.0.29.202)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.backends.mps.is_available()
True
>>>

返回True即可。

PyTorch MPS (Multi-Process Service)性能测试

PyTorch MPS (Multi-Process Service)是 PyTorch 中的一种分布式训练方式。它是基于Apple的MPS(Metal Performance Shaders) 框架开发的。MPS可以在多核的苹果设备上加速tensor的运算。MPS使用了多个设备上的多个核心来加速模型的训练。它可以将模型的计算过程分配到多个核心上,并且可以在多个设备上进行训练,从而提高训练速度。

PyTorch MPS 可以在 Apple 的设备(如 iPhone 和 iPad)上加速模型训练,也可以在 Mac 上使用。可以使用MPS来加速卷积神经网络(CNNs)、循环神经网络(RNNs)和其他类型的神经网络。使用MPS可以在不改变模型结构的情况下,通过分布式训练来加速模型的训练速度。

现在我们来做一个简单测试:

import torch
import timeit
import random x = torch.ones(50000000,device='cpu')
print(timeit.timeit(lambda:x*random.randint(0,100),number=1))

首先创建一个大小为 50000000 的全为1的张量 x,并将其设置为在cpu上运算。最后使用 timeit.timeit 函数来测量在 CPU 上执行 x 乘以一个随机整数的时间。 number=1表示只运行一次。这段代码的作用是在cpu上测量运算一个张量的时间。

运行结果:

➜  nlp_chinese /opt/homebrew/bin/python3.10 "/Users/liuyue/wodfan/work/nlp_chinese/mps_test.py"
0.020812375005334616

在10核M1pro的cpu芯片加持下,运行时间为:0.020812375005334616

随后换成MPS模式:

import torch
import timeit
import random x = torch.ones(50000000,device='mps')
print(timeit.timeit(lambda:x*random.randint(0,100),number=1))

程序返回:

➜  nlp_chinese /opt/homebrew/bin/python3.10 "/Users/liuyue/wodfan/work/nlp_chinese/mps_test.py"
0.003058041911572218

16核的GPU仅用时:0.003058041911572218

也就是说MPS的运行速度比CPU提升了7倍左右。

Whisper语音识别

安装好了PyTorch,我们安装Whisper:

pip install --upgrade --no-deps --force-reinstall git+https://github.com/openai/whisper.git

安装好之后进行验证:

➜  transformers git:(stable) whisper
usage: whisper [-h] [--model {tiny.en,tiny,base.en,base,small.en,small,medium.en,medium,large}] [--model_dir MODEL_DIR]
[--device DEVICE] [--output_dir OUTPUT_DIR] [--verbose VERBOSE] [--task {transcribe,translate}]
[--language {af,am,ar,as,az,ba,be,bg,bn,bo,br,bs,ca,cs,cy,da,de,el,en,es,et,eu,fa,fi,fo,fr,gl,gu,ha,haw,hi,hr,ht,hu,hy,id,is,it,iw,ja,jw,ka,kk,km,kn,ko,la,lb,ln,lo,lt,lv,mg,mi,mk,ml,mn,mr,ms,mt,my,ne,nl,nn,no,oc,pa,pl,ps,pt,ro,ru,sa,sd,si,sk,sl,sn,so,sq,sr,su,sv,sw,ta,te,tg,th,tk,tl,tr,tt,uk,ur,uz,vi,yi,yo,zh,Afrikaans,Albanian,Amharic,Arabic,Armenian,Assamese,Azerbaijani,Bashkir,Basque,Belarusian,Bengali,Bosnian,Breton,Bulgarian,Burmese,Castilian,Catalan,Chinese,Croatian,Czech,Danish,Dutch,English,Estonian,Faroese,Finnish,Flemish,French,Galician,Georgian,German,Greek,Gujarati,Haitian,Haitian Creole,Hausa,Hawaiian,Hebrew,Hindi,Hungarian,Icelandic,Indonesian,Italian,Japanese,Javanese,Kannada,Kazakh,Khmer,Korean,Lao,Latin,Latvian,Letzeburgesch,Lingala,Lithuanian,Luxembourgish,Macedonian,Malagasy,Malay,Malayalam,Maltese,Maori,Marathi,Moldavian,Moldovan,Mongolian,Myanmar,Nepali,Norwegian,Nynorsk,Occitan,Panjabi,Pashto,Persian,Polish,Portuguese,Punjabi,Pushto,Romanian,Russian,Sanskrit,Serbian,Shona,Sindhi,Sinhala,Sinhalese,Slovak,Slovenian,Somali,Spanish,Sundanese,Swahili,Swedish,Tagalog,Tajik,Tamil,Tatar,Telugu,Thai,Tibetan,Turkish,Turkmen,Ukrainian,Urdu,Uzbek,Valencian,Vietnamese,Welsh,Yiddish,Yoruba}]

随后安装ffmpeg:

brew install ffmpeg

然后编写语音识别代码:

import whisper  

model = whisper.load_model("small")  

# load audio and pad/trim it to fit 30 seconds
audio = whisper.load_audio("/Users/liuyue/wodfan/work/mydemo/b1.wav")
audio = whisper.pad_or_trim(audio) # make log-Mel spectrogram and move to the same device as the model mel = whisper.log_mel_spectrogram(audio).to("cpu") # detect the spoken language
_, probs = model.detect_language(mel)
print(f"Detected language: {max(probs, key=probs.get)}") # decode the audio
options = whisper.DecodingOptions(fp16 = False)
result = whisper.decode(model, mel, options) # print the recognized text
print(result.text)

这里导入音频后,通过whisper.log_mel_spectrogram方法自动检测语言,然后输出文本:

➜  minGPT git:(master) ✗ /opt/homebrew/bin/python3.10 "/Users/liuyue/wodfan/work/minGPT/wisper_test.py"
Detected language: zh
Hello大家好,这里是刘悦的技术博客,众神殿内,高朋满座,圣有如云,VMware,Virtual Box,UPM等虚拟机大神群英汇翠,指见位于C位王座上的Parallels唱网抬头,缓缓群寻,屁腻群小,目光到处,无人敢抬头对视。是的,如果说虚拟机领域有一位王者,非Parallels不能领袖群伦,毕竟大厂背书,功能满格,美中不足之处就是价格略高,

这里使用的small模型,也可以用更大的模型比如:medium、large。模型越大,效果越好。

如果想使用MPS的方式,需要改写一下Whisper源码,将load_model方法的参数改为mps即可:

def load_model(name: str, device: Optional[Union[str, torch.device]] = None, download_root: str = None, in_memory: bool = False) -> Whisper:
"""
Load a Whisper ASR model Parameters
----------
name : str
one of the official model names listed by `whisper.available_models()`, or
path to a model checkpoint containing the model dimensions and the model state_dict.
device : Union[str, torch.device]
the PyTorch device to put the model into
download_root: str
path to download the model files; by default, it uses "~/.cache/whisper"
in_memory: bool
whether to preload the model weights into host memory Returns
-------
model : Whisper
The Whisper ASR model instance
""" if device is None:
device = "cuda" if torch.cuda.is_available() else "mps"

代码在第18行。

随后运行脚本也改成mps:

import whisper  

model = whisper.load_model("medium")  

# load audio and pad/trim it to fit 30 seconds
audio = whisper.load_audio("/Users/liuyue/wodfan/work/mydemo/b1.wav")
audio = whisper.pad_or_trim(audio) # make log-Mel spectrogram and move to the same device as the model mel = whisper.log_mel_spectrogram(audio).to("mps") # detect the spoken language
_, probs = model.detect_language(mel)
print(f"Detected language: {max(probs, key=probs.get)}") # decode the audio
options = whisper.DecodingOptions(fp16 = False)
result = whisper.decode(model, mel, options) # print the recognized text
print(result.text)

这回切换为medium模型,程序返回:

➜  minGPT git:(master) ✗ /opt/homebrew/bin/python3.10 "/Users/liuyue/wodfan/work/minGPT/wisper_test.py"
100%|█████████████████████████████████████| 1.42G/1.42G [02:34<00:00, 9.90MiB/s]
Detected language: zh
Hello 大家好,这里是刘悦的技术博客,众神殿内,高朋满座,圣有如云,VMware,Virtualbox,UTM等虚拟机大神群音惠翠,只见位于C位王座上的Parallels唱往抬头,缓缓轻寻,屁逆群小,目光到处,无人敢抬头对视。

效率和精准度提升了不少,但medium模型的体积也更大,达到了1.42g。

结语

Whisper作为一个开源的语音识别库,支持多种语言,并且使用双向循环神经网络(bi-directional RNNs)来识别语音并将其转换为文本,支持自定义模型,可以用于实现在线语音识别,并且具有高级的语音识别功能,支持语音识别中的语音活动检测和语音识别中的语音转文本,在PyTorch的MPS加成下,更是猛虎添翼,绝世好库,值得拥有。

闻其声而知雅意,基于Pytorch(mps/cpu/cuda)的人工智能AI本地语音识别库Whisper(Python3.10)的更多相关文章

  1. 实践torch.fx第一篇——基于Pytorch的模型优化量化神器

    第一篇--什么是torch.fx 今天聊一下比较重要的torch.fx,也趁着这次机会把之前的torch.fx笔记整理下,笔记大概拆成三份,分别对应三篇: 什么是torch.fx 基于torch.fx ...

  2. 基于pytorch实现HighWay Networks之Highway Networks详解

    (一)简述---承接上文---基于pytorch实现HighWay Networks之Train Deep Networks 上文已经介绍过Highway Netwotrks提出的目的就是解决深层神经 ...

  3. 白瑜庆:知乎基于Kubernetes的kafka平台的设计和实现

    欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 本文首发在云+社区,未经许可,不得转载. 自我介绍 我是知乎的技术中台工程师,现在是负责知乎的存储相关组件.我的分享主要基于三个,一个是简单 ...

  4. 基于pytorch的电影推荐系统

    本文介绍一个基于pytorch的电影推荐系统. 代码移植自https://github.com/chengstone/movie_recommender. 原作者用了tf1.0实现了这个基于movie ...

  5. 目标检测-基于Pytorch实现Yolov3(1)- 搭建模型

    原文地址:https://www.cnblogs.com/jacklu/p/9853599.html 本人前段时间在T厂做了目标检测的项目,对一些目标检测框架也有了一定理解.其中Yolov3速度非常快 ...

  6. 基于Pytorch的简单小案例

    神经网络的理论知识不是本文讨论的重点,假设读者们都是已经了解RNN的基本概念,并希望能用一些框架做一些简单的实现.这里推荐神经网络必读书目:邱锡鹏<神经网络与深度学习>.本文基于Pytor ...

  7. 基于 PyTorch 和神经网络给 GirlFriend 制作漫画风头像

    摘要:本文中我们介绍的 AnimeGAN 就是 GitHub 上一款爆火的二次元漫画风格迁移工具,可以实现快速的动画风格迁移. 本文分享自华为云社区<AnimeGANv2 照片动漫化:如何基于 ...

  8. 使用LabVIEW实现基于pytorch的DeepLabv3图像语义分割

    前言 今天我们一起来看一下如何使用LabVIEW实现语义分割. 一.什么是语义分割 图像语义分割(semantic segmentation),从字面意思上理解就是让计算机根据图像的语义来进行分割,例 ...

  9. 解读 --- 基于微软企业商务应用平台 (Microsoft Dynamics 365) 之上的人工智能 (AI) 解决方案

    9月25日微软今年一年一度的Ignite 2017在佛罗里达州奥兰多市还是如期开幕了.为啥这么说?因为9月初五级飓风厄玛(Hurricane Irma) 在佛罗里达州登陆,在当地造成了挺大的麻烦.在这 ...

  10. 做游戏长知识------基于行为树与状态机的游戏AI(一)

    孙广东 2014.6.30 AI. 我们的第一印象可能是机器人,如今主要说在游戏中的应用. 现代的计算机游戏中已经大量融入了AI元素,平时我们进行游戏时产生的交互都是由AI来完毕的.比方在RPG游戏中 ...

随机推荐

  1. Hugging Face发布diffuser模型AI绘画库初尝鲜!

    作者:韩信子@ShowMeAI 深度学习实战系列:https://www.showmeai.tech/tutorials/42 TensorFlow 实战系列:https://www.showmeai ...

  2. python(牛客)试题解析1 - 入门级

    导航: 一.NC103 反转字符串 二.NC141 判断是否为回文字符串 三.NC151 最大公约数 四.NC65 斐波那契数列 - - - - - - - - - - 分-割-线 - - - - - ...

  3. PyCharm配置远程Docker环境

    1. docker 配置 使用-p参数暴露一个端口用于ssh连接. docker run -itd --name wangchao_paddle --gpus all -p 8899:8888 -p ...

  4. 记录因Sharding Jdbc批量操作引发的一次fullGC

    周五晚上告警群突然收到了一条告警消息,点开一看,应用 fullGC 了. 于是赶紧联系运维下载堆内存快照,进行分析. 内存分析 使用 MemoryAnalyzer 打开堆文件 mat 下载地址:htt ...

  5. 第2-3-1章 文件存储服务系统-nginx/fastDFS/minio/阿里云oss/七牛云oss

    目录 文件存储服务 1. 需求背景 2. 核心功能 3. 存储策略 3.1 本地存储 3.2 FastDFS存储 3.3 云存储 3.4 minio 4. 技术设计 文件存储服务 全套代码及资料全部完 ...

  6. 基于python的数学建模---非线性规划

    凸函数的非线性规划 minimize 求解的是局部最优解 简单的函数,无所谓 复杂的函数 初始值的设定很重要 scipy.optimize.minimize(fun,x0,args=(),method ...

  7. lambda、map、reduce、filter、sorted函数

    # lambda 函数from functools import reducea = lambda x: x ** 2print(a(3))def power(func, l=[]): return ...

  8. MIT6.828学习笔记1

    Lab 1: Booting a PC Part 1: PC Bootstrap The PC's Physical Address Space 早期的PC机基于Intel的8088处理器,能够寻址1 ...

  9. dfs 序

    dfs序可以\(O(1)\)判断书上两个点的从属关系 Tree Queries 题面翻译 给你一个以\(1\)为根的有根树. 每回询问\(k\)个节点\({v_1, v_2 \cdots v_k}\) ...

  10. 大前端html基础学习03-定位锚点透明

    一.position 定位属性和属性值position 定位属性,检索对象的定位方式:语法:position:static /absolute/relative/fixed/sticky/unset/ ...