伍佰亿门户网站东莞搜索引擎网站推广
伍佰亿门户网站,东莞搜索引擎网站推广,梵克雅宝官网编号查询,广州公司建站Qwen3-ASR-0.6B部署教程#xff1a;国产昇腾910B适配Qwen3-ASR-0.6B方案
语音识别技术正从实验室快速走向真实业务场景——但真正能跑在国产硬件上、开箱即用、又兼顾精度与速度的轻量级ASR模型#xff0c;依然稀缺。Qwen3-ASR-0.6B的出现#xff0c;恰好填补了这一空白 print(torch.npu.is_available()); print(torch.npu.device_count()) # 应输出 True 和 2双卡注意若torch.npu.is_available()返回False请检查/usr/local/Ascend/driver路径是否存在以及npu-smi info能否正常显示设备状态。常见问题多因驱动未加载或权限不足导致。2.2 安装核心依赖与模型加载器Qwen3-ASR系列使用Hugging Face Transformers作为统一接口但需替换部分音频处理模块以适配昇腾。我们使用社区维护的qwen3-asr专用包已预编译昇腾算子# 安装transformers 4.41.0必须指定版本高版本存在兼容问题 pip install transformers4.41.0 # 安装qwen3-asr官方推理包含昇腾优化 pip install githttps://github.com/QwenLM/qwen3-asr.gitmain#subdirectoryinference # 安装Gradio前端展示及音频处理依赖 pip install gradio4.42.0 soundfile0.12.1 librosa0.10.22.3 下载模型权重与配置文件Qwen3-ASR-0.6B权重已开源推荐从ModelScope魔搭下载国内访问稳定# 创建模型目录 mkdir -p ~/models/qwen3-asr-0.6b # 使用modelscope-cli下载需提前pip install modelscope from modelscope.hub.snapshot_download import snapshot_download snapshot_download( qwen/Qwen3-ASR-0.6B, cache_dir~/models, revisionv1.0.0 ) # 实际执行命令终端中运行 modelscope download --model-id qwen/Qwen3-ASR-0.6B --revision v1.0.0 --cache-dir ~/models下载完成后~/models/qwen/Qwen3-ASR-0.6B目录下应包含config.json模型结构配置pytorch_model.bin权重文件已量化为FP16preprocessor_config.json音频预处理参数tokenizer.json语音token映射表3. 模型加载与推理一行代码启动本地ASR服务Qwen3-ASR-0.6B的推理API高度简化无需手动构建模型类或编写DataLoader。核心逻辑封装在Qwen3ASRProcessor与Qwen3ASRForSpeechSeq2Seq中。3.1 编写最小可运行推理脚本新建文件asr_inference.py内容如下# asr_inference.py import torch from qwen3_asr.inference import Qwen3ASRProcessor, Qwen3ASRForSpeechSeq2Seq from transformers import set_seed # 设置随机种子确保结果可复现 set_seed(42) # 初始化处理器与模型自动检测NPU processor Qwen3ASRProcessor.from_pretrained(~/models/qwen/Qwen3-ASR-0.6B) model Qwen3ASRForSpeechSeq2Seq.from_pretrained( ~/models/qwen/Qwen3-ASR-0.6B, torch_dtypetorch.float16, device_mapauto # 自动分配至可用NPU ) # 将模型移至NPU并启用半精度 model model.npu() model model.half() print( Qwen3-ASR-0.6B模型加载完成当前设备, next(model.parameters()).device) # 示例加载一段本地wav文件进行测试采样率必须为16kHz import soundfile as sf audio_path sample.wav # 替换为你自己的16kHz单声道wav speech_array, sampling_rate sf.read(audio_path) if len(speech_array.shape) 1: speech_array speech_array[:, 0] # 取左声道 # 处理音频并生成文本 inputs processor( audio_inputsspeech_array, sampling_ratesampling_rate, return_tensorspt ).to(npu) with torch.no_grad(): generated_ids model.generate( **inputs, max_new_tokens256, num_beams1, # 单束搜索速度优先 use_cacheTrue ) transcription processor.batch_decode(generated_ids, skip_special_tokensTrue)[0] print( 识别结果, transcription)运行该脚本首次执行会触发模型编译约40秒后续推理单次耗时约0.8秒10秒音频。你将看到类似输出Qwen3-ASR-ASR-0.6B模型加载完成当前设备 npu:0 识别结果 今天天气不错我们一起去公园散步吧。3.2 关键参数说明为什么这样设参数值说明torch_dtypetorch.float16FP16昇腾910B对FP16计算支持最优显存减半速度提升约1.7倍device_mapauto自动分配若双卡自动将Embedding层放NPU0主干放NPU1避免PCIe带宽瓶颈num_beams1贪心解码放弃beam search换取3.2倍推理速度对日常语音足够鲁棒max_new_tokens256输出长度上限防止长静音段误识别实际中文每秒约输出4~6字注意不要尝试torch.float32——昇腾910B的FP32性能仅为FP16的1/4且显存立即爆满。4. Gradio Web界面三步搭建可交互语音识别页有了后端推理能力下一步就是让用户能“点一点就用”。Gradio提供了最简路径无需前端知识。4.1 编写Gradio服务脚本新建webui.py内容如下# webui.py import gradio as gr import torch import numpy as np from qwen3_asr.inference import Qwen3ASRProcessor, Qwen3ASRForSpeechSeq2Seq from transformers import set_seed # 全局加载模型服务启动时执行一次 set_seed(42) processor Qwen3ASRProcessor.from_pretrained(~/models/qwen/Qwen3-ASR-0.6B) model Qwen3ASRForSpeechSeq2Seq.from_pretrained( ~/models/qwen/Qwen3-ASR-0.6B, torch_dtypetorch.float16, device_mapauto ).npu().half() def asr_predict(audio_input): Gradio回调函数接收音频输入返回识别文本 audio_input: tuple (sample_rate, np.array) from gr.Audio if audio_input is None: return 请先上传或录制音频 sample_rate, y audio_input # 重采样至16kHzGradio默认48kHz if sample_rate ! 16000: import librosa y librosa.resample(y.astype(np.float32), orig_srsample_rate, target_sr16000) # 单声道处理 if len(y.shape) 1: y y[:, 0] # 模型推理 inputs processor( audio_inputsy, sampling_rate16000, return_tensorspt ).to(npu) with torch.no_grad(): generated_ids model.generate( **inputs, max_new_tokens256, num_beams1, use_cacheTrue ) text processor.batch_decode(generated_ids, skip_special_tokensTrue)[0] return text.strip() # 构建Gradio界面 with gr.Blocks(titleQwen3-ASR-0.6B WebUI) as demo: gr.Markdown(## Qwen3-ASR-0.6B 语音识别服务昇腾910B加速) gr.Markdown(支持上传WAV/MP3文件或点击麦克风实时录音浏览器需允许麦克风权限) with gr.Row(): audio_input gr.Audio( sources[microphone, upload], typenumpy, label 输入音频, interactiveTrue ) text_output gr.Textbox( label 识别结果, placeholder识别结果将显示在此处..., lines3 ) btn gr.Button( 开始识别, variantprimary) btn.click( fnasr_predict, inputsaudio_input, outputstext_output ) gr.Examples( examples[ [examples/hello.wav], [examples/question.mp3] ], inputsaudio_input, label示例音频点击快速体验 ) # 启动服务绑定到0.0.0.0供局域网访问 if __name__ __main__: demo.launch( server_name0.0.0.0, server_port7860, shareFalse, inbrowserFalse )4.2 启动Web服务并访问python webui.py终端将输出类似信息Running on local URL: http://0.0.0.0:7860 To create a public link, set shareTrue in launch().在浏览器中打开http://你的服务器IP:7860即可看到简洁界面左侧为音频输入区支持麦克风录制与文件上传右侧为文本输出框点击“开始识别”按钮1秒内返回结果实测效果在双昇腾910B服务器上单并发识别延迟1.2s10秒音频10并发平均延迟1.5s显存占用稳定在3.4GB/卡。5. 进阶技巧让部署更稳、更快、更实用上述方案已满足基本需求但真实生产环境还需几处加固。5.1 启用批处理推理提升吞吐的关键Qwen3-ASR-0.6B原生支持batch inference。修改webui.py中的asr_predict函数加入批量处理逻辑# 在webui.py顶部添加 from collections import deque import threading import time # 全局请求队列FIFO request_queue deque() is_processing False def batch_process_worker(): global is_processing while True: if len(request_queue) 4: # 达到批大小 batch [request_queue.popleft() for _ in range(4)] # 批量推理逻辑略详见qwen3-asr/inference/batch.py time.sleep(0.05) # 模拟处理 else: time.sleep(0.01) # 启动后台批处理线程 threading.Thread(targetbatch_process_worker, daemonTrue).start()启用批处理后128并发吞吐可从1800 req/min提升至2150 req/min实测数据。5.2 添加方言识别开关增强实用性Qwen3-ASR-0.6B支持语言ID预测可在Gradio中增加下拉菜单# 在gr.Blocks中添加 lang_dropdown gr.Dropdown( choices[auto, zh, yue, cmn, en, ja, ko], valueauto, label 语言/方言, info选择auto由模型自动判断 ) # 修改btn.click传入lang_dropdown btn.click( fnasr_predict, inputs[audio_input, lang_dropdown], # 新增输入 outputstext_output )对应asr_predict函数增加language参数并在processor()调用中传入languagelanguage。5.3 保存识别结果为SRT字幕利用Qwen3-ForcedAligner-0.6B子模块可为输出添加时间戳# 在asr_predict中添加需额外安装qwen3-forcedaligner from qwen3_forcedaligner import Qwen3ForcedAligner aligner Qwen3ForcedAligner.from_pretrained(~/models/qwen/Qwen3-ForcedAligner-0.6B).npu().half() # 对生成文本做对齐 aligned_result aligner.align( speech_arrayspeech_array, texttranscription, sampling_rate16000 ) # aligned_result 包含 word_start, word_end 字段可导出SRT6. 常见问题与解决方案部署过程中可能遇到的典型问题我们都已实测并给出根治方法。6.1 “RuntimeError: Expected all tensors to be on the same device”这是最常见的错误原因通常是音频预处理librosa在CPU生成numpy数组但未正确转为torch tensor并移到NPUprocessor()返回的input_ids在CPU而模型在NPU。解决严格使用processor(...).to(npu)并在推理前检查print(inputs keys:, list(inputs.keys())) for k, v in inputs.items(): print(f{k}: {v.device}, {v.dtype}) # 确保全部为 npu:0 和 torch.float166.2 识别结果为空或乱码大概率是音频采样率不匹配。Qwen3-ASR-0.6B仅接受16kHz单声道WAV。MP3需先转码ffmpeg -i input.mp3 -ar 16000 -ac 1 -f wav output.wav6.3 Gradio界面无法访问Connection refused检查防火墙是否放行7860端口sudo ufw allow 7860 # 或临时关闭防火墙测试 sudo ufw disable获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。