通义千问72B、1.8B、Audio模型开源!魔搭社区最佳实践来啦!

本文涉及的产品
交互式建模 PAI-DSW,5000CU*H 3个月
简介: 通义千问再次重磅开源!

引言

今天,通义千问再次重磅开源!

阿里云开源通义千问720亿参数模型Qwen-72B、18亿参数模型Qwen-1.8B 及 音频大模型Qwen-Audio,魔搭社区已首发上线!本次开源的模型中除预训练模型外,还同步推出了对应的对话模型,面向72B、1.8B对话模型提供了4bit/8bit 量化版模型,便于开发者们推理训练。

目前,魔搭社区提供一站式体验、下载、推理、微调、部署服务及教程,欢迎开发者小伙伴们体验!

模型效果体验

通义千问团队对Qwen-72B的指令遵循、工具使用等技能作了技术优化,使Qwen-72B能够更好地被下游应用集成,比如,Qwen-72B搭载了强大的系统指令(System Prompt)能力,用户只用一句提示词就可定制自己的AI助手,要求大模型扮演某个角色,或者执行特定的回复任务。

创空间体验链接:

https://modelscope.cn/studios/qwen/Qwen-72B-Chat-Demo

通义千问音频大模型效果体验:


创空间体验链接:

https://modelscope.cn/studios/qwen/Qwen-Audio-Chat-Demo

通义千问1.8B模型效果体验:

创空间体验链接:

https://www.modelscope.cn/studios/qwen/Qwen-1_8B-Chat-Demo

模型下载

模型链接:

通义千问-72B-预训练:

https://modelscope.cn/models/qwen/Qwen-72B

通义千问-72B-Chat:

https://modelscope.cn/models/qwen/Qwen-72B-Chat

通义千问-72B-Chat-Int8:https://www.modelscope.cn/models/qwen/Qwen-72B-Chat-Int8

通义千问-72B-Chat-Int4:

https://www.modelscope.cn/models/qwen/Qwen-72B-Chat-Int4

通义千问-1.8B-预训练:

https://modelscope.cn/models/qwen/Qwen-1_8B

通义千问-1.8B-Chat:

https://modelscope.cn/models/qwen/Qwen-1_8B-Chat

通义千问-1_8B-Chat-Int8:

https://www.modelscope.cn/models/qwen/Qwen-1_8B-Chat-Int8

通义千问-1_8B-Chat-Int4:

https://www.modelscope.cn/models/qwen/Qwen-1_8B-Chat-Int4

通义千问-Audio-预训练:

https://modelscope.cn/models/qwen/Qwen-Audio

通义千问-Audio-Chat:

https://modelscope.cn/models/qwen/Qwen-Audio-Chat

模型下载(以通义千问-72B-Chat-Int4为例):

from modelscope import snapshot_download
model_dir = snapshot_download("qwen/Qwen-72B-Chat-Int4")

模型推理

模型推理 以通义千问-72B-Chat-Int4、通义千问-1_8B-Chat-Int4和通义千问-Audio-Chat为例:

通义千问-72B-Chat-Int4推理代码:

from modelscope import AutoTokenizer, AutoModelForCausalLM, snapshot_download
model_dir = snapshot_download("qwen/Qwen-72B-Chat-Int4")
# Note: The default behavior now has injection attack prevention off.
tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    model_dir,
    device_map="auto",
    trust_remote_code=True
).eval()
response, history = model.chat(tokenizer, "你好呀", history=None, system="You are a helpful assistant.")
print(response)
# 你好!很高兴为你提供帮助。
# 第二轮对话 2nd dialogue turn
response, history = model.chat(tokenizer, "给我讲一个年轻人奋斗创业最终取得成功的故事。", history=history,system="You are a helpful assistant.")
print(response)
# 这是一个关于一个年轻人奋斗创业最终取得成功的故事。
# 故事的主人公叫李明,他来自一个普通的家庭,父母都是普通的工人。从小,李明就立下了一个目标:要成为一名成功的企业家。
# 为了实现这个目标,李明勤奋学习,考上了大学。在大学期间,他积极参加各种创业比赛,获得了不少奖项。他还利用课余时间去实习,积累了宝贵的经验。
# 毕业后,李明决定开始自己的创业之路。他开始寻找投资机会,但多次都被拒绝了。然而,他并没有放弃。他继续努力,不断改进自己的创业计划,并寻找新的投资机会。
# 最终,李明成功地获得了一笔投资,开始了自己的创业之路。他成立了一家科技公司,专注于开发新型软件。在他的领导下,公司迅速发展起来,成为了一家成功的科技企业。
# 李明的成功并不是偶然的。他勤奋、坚韧、勇于冒险,不断学习和改进自己。他的成功也证明了,只要努力奋斗,任何人都有可能取得成功。
# 第三轮对话 3rd dialogue turn
response, history = model.chat(tokenizer, "给这个故事起一个标题", history=history,system="You are a helpful assistant.")
print(response)
# 《奋斗创业:一个年轻人的成功之路》

资源消耗:

通义千问-1_8B-Chat-Int4推理代码:

from modelscope import GenerationConfig# Note: The default behavior now has injection attack prevention off.model_dir = snapshot_download("qwen/Qwen-1_8B-Chat-Int4")tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)# use bf16# model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True, bf16=True).eval()# use fp16# model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True, fp16=True).eval()# use cpu only# model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="cpu", trust_remote_code=True).eval()# use auto mode, automatically select precision based on the device.model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True).eval()# Specify hyperparameters for generationmodel.generation_config = GenerationConfig.from_pretrained(model_dir, trust_remote_code=True) # 可指定不同的生成长度、top_p等相关超参# 第一轮对话 1st dialogue turnresponse, history = model.chat(tokenizer, "你好呀", history=None, system="You are a helpful assistant.")print(response)# 你好!很高兴为你提供帮助。# 第二轮对话 2nd dialogue turnresponse, history = model.chat(tokenizer, "给我讲一个年轻人奋斗创业最终取得成功的故事。", history=history,system="You are a helpful assistant.")print(response)# 这是一个关于一个年轻人奋斗创业最终取得成功的故事。# 故事的主人公叫李明,他来自一个普通的家庭,父母都是普通的工人。从小,李明就立下了一个目标:要成为一名成功的企业家。# 为了实现这个目标,李明勤奋学习,考上了大学。在大学期间,他积极参加各种创业比赛,获得了不少奖项。他还利用课余时间去实习,积累了宝贵的经验。# 毕业后,李明决定开始自己的创业之路。他开始寻找投资机会,但多次都被拒绝了。然而,他并没有放弃。他继续努力,不断改进自己的创业计划,并寻找新的投资机会。# 最终,李明成功地获得了一笔投资,开始了自己的创业之路。他成立了一家科技公司,专注于开发新型软件。在他的领导下,公司迅速发展起来,成为了一家成功的科技企业。# 李明的成功并不是偶然的。他勤奋、坚韧、勇于冒险,不断学习和改进自己。他的成功也证明了,只要努力奋斗,任何人都有可能取得成功。# 第三轮对话 3rd dialogue turnresponse, history = model.chat(tokenizer, "给这个故事起一个标题", history=history,system="You are a helpful assistant.")print(response)# 《奋斗创业:一个年轻人的成功之路》
from modelscope import GenerationConfig
# Note: The default behavior now has injection attack prevention off.
model_dir = snapshot_download("qwen/Qwen-1_8B-Chat-Int4")
tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)
# use bf16
# model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True, bf16=True).eval()
# use fp16
# model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True, fp16=True).eval()
# use cpu only
# model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="cpu", trust_remote_code=True).eval()
# use auto mode, automatically select precision based on the device.
model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True).eval()
# Specify hyperparameters for generation
model.generation_config = GenerationConfig.from_pretrained(model_dir, trust_remote_code=True) # 可指定不同的生成长度、top_p等相关超参
# 第一轮对话 1st dialogue turn
response, history = model.chat(tokenizer, "你好呀", history=None, system="You are a helpful assistant.")
print(response)
# 你好!很高兴为你提供帮助。
# 第二轮对话 2nd dialogue turn
response, history = model.chat(tokenizer, "给我讲一个年轻人奋斗创业最终取得成功的故事。", history=history,system="You are a helpful assistant.")
print(response)
# 这是一个关于一个年轻人奋斗创业最终取得成功的故事。
# 故事的主人公叫李明,他来自一个普通的家庭,父母都是普通的工人。从小,李明就立下了一个目标:要成为一名成功的企业家。
# 为了实现这个目标,李明勤奋学习,考上了大学。在大学期间,他积极参加各种创业比赛,获得了不少奖项。他还利用课余时间去实习,积累了宝贵的经验。
# 毕业后,李明决定开始自己的创业之路。他开始寻找投资机会,但多次都被拒绝了。然而,他并没有放弃。他继续努力,不断改进自己的创业计划,并寻找新的投资机会。
# 最终,李明成功地获得了一笔投资,开始了自己的创业之路。他成立了一家科技公司,专注于开发新型软件。在他的领导下,公司迅速发展起来,成为了一家成功的科技企业。
# 李明的成功并不是偶然的。他勤奋、坚韧、勇于冒险,不断学习和改进自己。他的成功也证明了,只要努力奋斗,任何人都有可能取得成功。
# 第三轮对话 3rd dialogue turn
response, history = model.chat(tokenizer, "给这个故事起一个标题", history=history,system="You are a helpful assistant.")
print(response)
# 《奋斗创业:一个年轻人的成功之路》

资源消耗:

通义千问-Audio-Chat推理代码:

from modelscope import AutoModelForCausalLM, AutoTokenizer
from modelscope import GenerationConfig
import torch
torch.manual_seed(1234)
model_dir = '/mnt/workspace/Qwen-Audio-Chat'
tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)
# 打开bf16精度,A100、H100、RTX3060、RTX3070等显卡建议启用以节省显存
# model = AutoModelForCausalLM.from_pretrained("/mnt/workspace/chatofa_audio/Qwen-VL-Chat/10302244_iter8000_final_slice", device_map="auto", trust_remote_code=True, bf16=True).eval()
# 打开fp16精度,V100、P100、T4等显卡建议启用以节省显存
model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True, bf16=True).eval()  ##
# 使用CPU进行推理,需要约32GB内存
# model = AutoModelForCausalLM.from_pretrained("/mnt/workspace/chatofa_audio/Qwen-VL-Chat/10302244_iter8000_final_slice", device_map="cpu", trust_remote_code=True).eval()
# 默认gpu进行推理,需要约24GB显存
# model = AutoModelForCausalLM.from_pretrained("/mnt/workspace/chatofa_audio/Qwen-VL-Chat/10302244_iter8000_final_slice", device_map="cuda", trust_remote_code=True).eval()
model.generation_config = GenerationConfig.from_pretrained(model_dir, trust_remote_code=True)
# 1st dialogue turn
query = tokenizer.from_list_format([
    {'audio': 'asr_example.wav'},
    {'text': '这句话的情绪是什么?'},
])
response, history = model.chat(tokenizer, query=query, history=None)
print(response)
# # That is the sound of typing on a keyboard.
# # 第二轮对话
response, history = model.chat(tokenizer, '这个人说的啥', history=history)
print(response)

资源消耗:

模型微调

微调代码开源地址:

https://github.com/modelscope/swift/tree/main/examples/pytorch/llm

微调环境准备

# 设置pip全局镜像和安装相关的python包
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
git clone https://github.com/modelscope/swift.git
cd swift
pip install -e .[llm]
pip install deepspeed -U
# 跑Qwen-72B-Chat-Int4需要安装对应cuda版本的auto_gptq
# 可以参考: https://github.com/PanQiWei/AutoGPTQ
pip install auto_gptq
# 下面的脚本需要在此目录下执行
cd examples/pytorch/llm

Qwen-72B-Chat-Int4为例:qlora+ddp+deepspeed

脚本地址:https://github.com/modelscope/swift/tree/main/examples/pytorch/llm/scripts/qwen_72b_chat_int4/qlora_ddp_ds

微调脚本:

# Experimental environment: 2 * A100
# 2 * 67GB GPU memory
nproc_per_node=2
PYTHONPATH=../../.. \
CUDA_VISIBLE_DEVICES=0,1 \
torchrun \
    --nproc_per_node=$nproc_per_node \
    --master_port 29500 \
    llm_sft.py \
    --model_id_or_path qwen/Qwen-72B-Chat-Int4 \
    --model_revision master \
    --sft_type lora \
    --tuner_backend swift \
    --template_type AUTO \
    --dtype AUTO \
    --output_dir output \
    --ddp_backend nccl \
    --dataset damo-agent-mini-zh \
    --train_dataset_sample 20000 \
    --num_train_epochs 1 \
    --max_length 4096 \
    --check_dataset_strategy warning \
    --lora_rank 8 \
    --lora_alpha 32 \
    --lora_dropout_p 0.05 \
    --lora_target_modules DEFAULT \
    --gradient_checkpointing true \
    --batch_size 1 \
    --weight_decay 0.01 \
    --learning_rate 1e-4 \
    --gradient_accumulation_steps $(expr 16 / $nproc_per_node) \
    --max_grad_norm 0.5 \
    --warmup_ratio 0.03 \
    --eval_steps 100 \
    --save_steps 100 \
    --save_total_limit 2 \
    --logging_steps 10 \
    --use_flash_attn true \
    --push_to_hub false \
    --push_hub_strategy end \
    --hub_model_id qwen-72b-chat-int4-qlora \
    --hub_private_repo true \
    --hub_token 'your-sdk-token' \
    --deepspeed_config_path 'ds_config/zero2.json' \
    --only_save_model true \

训练过程支持本地数据集,需要指定如下参数:

--custom_train_dataset_path xxx.jsonl \
--custom_val_dataset_path yyy.jsonl \

自定义数据集的格式可以参考:https://github.com/modelscope/swift/blob/main/docs/source/LLM/%E8%87%AA%E5%AE%9A%E4%B9%89%E4%B8%8E%E6%8B%93%E5%B1%95.md#-%E6%8E%A8%E8%8D%90%E5%91%BD%E4%BB%A4%E8%A1%8C%E5%8F%82%E6%95%B0%E7%9A%84%E5%BD%A2%E5%BC%8F

微调后推理脚本:

这里的ckpt_dir需要修改为训练生成的checkpoint文件夹

# Experimental environment: A100
PYTHONPATH=../../.. \
CUDA_VISIBLE_DEVICES=0 \
python llm_infer.py \
    --ckpt_dir "output/qwen-72b-chat-int4/vx_xxx/checkpoint-xxx" \
    --load_args_from_ckpt_dir true \
    --eval_human false \
    --max_length 4096 \
    --use_flash_attn true \
    --max_new_tokens 2048 \
    --temperature 0.1 \
    --top_p 0.7 \
    --repetition_penalty 1.05 \
    --do_sample true \
    --merge_lora_and_save false \

训练损失图:

训练后生成样例:

[PROMPT]<|im_start|>system
你是达摩院的ModelScopeGPT(魔搭助手),你是个大语言模型, 是2023年达摩院的工程师训练得到的。你有多种能力,可以通过插件集成魔搭社区的模型api来回复用户的问题,还能解答用户使用模型遇到的问题和模型知识相关问答。1. {"plugin_name": "modelscope_image-generation", "plugin_owner": "ModelScopeGPT", "plugin_type": "default", "plugin_schema_for_model": {"name": "modelscope_image-generation", "description": "针对文本输入,生成对应的图片", "url": "http://134.47.175.82:4975/", "paths": [{"name": "modelscope_image-generation", "model_id": "/damo/image_generation", "method": "post", "description": "针对文本输入,生成对应的图片", "parameters": [{"name": "text", "description": "用户输入的文本信息", "required": "True"}]}]}}
2. {"plugin_name": "modelscope_video-generation", "plugin_owner": "ModelScopeGPT", "plugin_type": "default", "plugin_schema_for_model": {"name": "modelscope_video-generation", "description": "针对文本输入,生成一段描述视频", "url": "http://0.111.1.69:6495/", "paths": [{"name": "modelscope_video-generation", "model_id": "/damo/text-to-video-synthesis", "method": "post", "description": "针对文本输入,生成一段描述视频", "parameters": [{"name": "text", "description": "用户输入的文本信息", "required": "True"}]}]}}
3. {"plugin_name": "modelscope_speech-generation", "plugin_owner": "ModelScopeGPT", "plugin_type": "default", "plugin_schema_for_model": {"name": "modelscope_speech-generation", "description": "针对回复的内容,用语音表示,同时可以选择是男声或者女声", "url": "http://72.191.72.28:2576/", "paths": [{"name": "modelscope_speech-generation", "model_id": "/damo/speech_sambert-hifigan_tts_zh-cn_16k", "method": "post", "description": "针对回复的内容,用语音表示,同时可以选择是男声或者女声", "parameters": [{"name": "text", "description": "要转成语音的文本", "required": "True"}, {"name": "gender", "description": "用户身份", "required": "True"}]}]}}
4. {"plugin_name": "modelscope_text-translation-zh2en", "plugin_owner": "ModelScopeGPT", "plugin_type": "default", "plugin_schema_for_model": {"name": "modelscope_text-translation-zh2en", "description": "将输入的中文文本翻译成英文", "url": "http://13.64.143.130:6242/", "paths": [{"name": "modelscope_text-translation-zh2en", "model_id": "/damo/nlp_csanmt_translation_zh2en", "method": "post", "description": "将输入的中文文本翻译成英文", "parameters": [{"name": "text", "description": "用户输入的中文文本", "required": "True"}]}]}}<|im_end|>
<|im_start|>user
给我写一首诗,形容绿树成荫,小河潺潺,女生诵读这首诗,生成个视频<|im_end|>
<|im_start|>assistant
[OUTPUT]绿树成荫小河流, 潺潺流水声悠悠。鸟儿啾啾鸣叫声, 花香四溢满园中。
<|startofthink|>```JSON
{"api_name": "modelscope_speech-generation", "url": "http://72.191.72.28:2576/damo/speech_sambert-hifigan_tts_zh-cn_16k", "parameters": {"text": "绿树成荫小河流, 潺潺流水声悠悠。鸟儿啾啾鸣叫声, 花香四溢满园中。", "gender": "woman"}}
```<|endofthink|>
<|startofexec|>```JSON
{"result": "<audio id="audio" controls="" preload="none"> <source id="wav" src="http://xdp-expriment.oss-cn-zhangjiakou.aliyuncs.com/modelscope/audio/6e6d6f7c3b2a4457.wav"> </audio>"}
```<|endofexec|>
<audio id="audio" controls=""preload="none"> <source id="wav" src="http://xdp-expriment.oss-cn-zhangjiakou.aliyuncs.com/modelscope/audio/6e6d6f7c3b2a4457.wav"> </audio>
目前ModelScope只有支持英文的视频生成模型,所以我将首先把您的问题利用ModelScope的中英翻译模型转化为英文,然后再调用英文的视频生成模型<|startofthink|>```JSON
{"api_name": "modelscope_text-translation-zh2en", "url": "http://13.64.143.130:6242/damo/nlp_csanmt_translation_zh2en", "parameters": {"text": "绿树成荫小河流, 潺潺流水声悠悠。鸟儿啾啾鸣叫声, 花香四溢满园中。"}}
```<|endofthink|>
<|startofexec|>```JSON
{"result": "A dog chasing a ball in the park."}
```<|endofexec|>
翻译后的指令:A dog chasing a ball in the park.
调用视频生成模型生成视频中......
<|startofthink|>```JSON
{"api_name": "modelscope_video-generation", "url": "http://0.111.1.69:6495/damo/text-to-video-synthesis", "parameters": {"text": "A dog chasing a ball in the park."}}
```<|endofthink|>
<|startofexec|>```JSON
{"result": "![IMAGEGEN](http://xdp-expriment.oss-cn-zhangjiakou.aliyuncs.com/modelscope/video/7442222973724275.gif"}
```<|endofexec|>
![IMAGEGEN](http://xdp-expriment.oss-cn-zhangjiakou.aliyuncs.com/modelscope/video/7442222973724275.gif)<|im_end|>
[LABELS]绿树成荫小河流, 潺潺流水悠悠留。鸟语花香风拂面, 桥上行人笑语喧。亭阁楼台风景好, 游人停步赏不够。画船轻摇水草舞, 天光云影映水流。
<|startofthink|>```JSON
{"api_name": "modelscope_speech-generation", "url": "http://72.191.72.28:2576/damo/speech_sambert-hifigan_tts_zh-cn_16k", "parameters": {"text": "绿树成荫小河流, 潺潺流水悠悠留。鸟语花香风拂面, 桥上行人笑语喧。亭阁楼台风景好, 游人停步赏不够。画船轻摇水草舞, 天光云影映水流。", "gender": "woman"}}
```<|endofthink|>
<|startofexec|>```JSON
{"result": "<audio id="audio" controls="" preload="none"> <source id="wav" src="http://xdp-expriment.oss-cn-zhangjiakou.aliyuncs.com/modelscope/audio/f4e6cc38253a4959.wav"> </audio>"}
```<|endofexec|>
<audio id="audio" controls=""preload="none"> <source id="wav" src="http://xdp-expriment.oss-cn-zhangjiakou.aliyuncs.com/modelscope/audio/f4e6cc38253a4959.wav"> </audio>
目前ModelScope只有支持英文的视频生成模型,所以我将首先把您的问题利用ModelScope的中英翻译模型转化为英文,然后再调用英文的视频生成模型<|startofthink|>```JSON
{"api_name": "modelscope_text-translation-zh2en", "url": "http://13.64.143.130:6242/damo/nlp_csanmt_translation_zh2en", "parameters": {"text": "绿树成荫小河流, 潺潺流水悠悠留。鸟语花香风拂面, 桥上行人笑语喧。亭阁楼台风景好, 游人停步赏不够。画船轻摇水草舞, 天光云影映水流。"}}
```<|endofthink|>
<|startofexec|>```JSON
{"result": "Butterfly dancing among flowers."}
```<|endofexec|>
翻译后的指令:Butterfly dancing among flowers.
调用视频生成模型生成视频中......
<|startofthink|>```JSON
{"api_name": "modelscope_video-generation", "url": "http://0.111.1.69:6495/damo/text-to-video-synthesis", "parameters": {"text": "Butterfly dancing among flowers."}}
```<|endofthink|>
<|startofexec|>```JSON
{"result": "![IMAGEGEN](http://xdp-expriment.oss-cn-zhangjiakou.aliyuncs.com/modelscope/video/84f90182535a475f.gif"}
```<|endofexec|>
![IMAGEGEN](http://xdp-expriment.oss-cn-zhangjiakou.aliyuncs.com/modelscope/video/84f90182535a475f.gif)

Qwen-Audio-Chat为例:lora (可以在ModelScope PAI-DSW上直接运行)

脚本地址:https://github.com/modelscope/swift/tree/main/examples/pytorch/llm/scripts/qwen_audio_chat/lora

微调脚本:

# Experimental environment: V100, A10, 3090
# 21GB GPU memory
PYTHONPATH=../../.. \
CUDA_VISIBLE_DEVICES=0 \
python llm_sft.py \
    --model_id_or_path qwen/Qwen-Audio-Chat \
    --model_revision master \
    --sft_type lora \
    --tuner_backend swift \
    --template_type AUTO \
    --dtype AUTO \
    --output_dir output \
    --dataset aishell1-mini-zh \
    --train_dataset_sample -1 \
    --num_train_epochs 1 \
    --max_length 2048 \
    --check_dataset_strategy warning \
    --lora_rank 8 \
    --lora_alpha 32 \
    --lora_dropout_p 0.05 \
    --lora_target_modules DEFAULT \
    --gradient_checkpointing true \
    --batch_size 1 \
    --weight_decay 0.01 \
    --learning_rate 1e-4 \
    --gradient_accumulation_steps 16 \
    --max_grad_norm 0.5 \
    --warmup_ratio 0.03 \
    --eval_steps 100 \
    --save_steps 100 \
    --save_total_limit 2 \
    --logging_steps 10 \
    --use_flash_attn false \
    --push_to_hub false \
    --hub_model_id qwen-audio-chat-lora \
    --hub_private_repo true \
    --hub_token 'your-sdk-token' \

微调后推理脚本:

# Experimental environment: V100, A10, 3090
PYTHONPATH=../../.. \
CUDA_VISIBLE_DEVICES=0 \
python llm_infer.py \
    --ckpt_dir "output/qwen-audio-chat/vx_xxx/checkpoint-xxx" \
    --load_args_from_ckpt_dir true \
    --eval_human false \
    --max_length 2048 \
    --use_flash_attn false \
    --max_new_tokens 2048 \
    --temperature 0.3 \
    --top_p 0.7 \
    --repetition_penalty 1.05 \
    --do_sample true \
    --merge_lora_and_save false \

训练损失图:

训练后生成样例:

[PROMPT]<|im_start|>system
You are a helpful assistant.<|im_end|>
<|im_start|>user
Audio 1:<audio>/root/.cache/modelscope/hub/datasets/speech_asr/speech_asr_aishell1_trainsets/master/data_files/extracted/037bf9a958c0e200c49ae900894ba0af40f592bb98f2dab81415c11e8ceac132/speech_asr_aishell_testsets/wav/test/S0764/BAC009S0764W0217.wav</audio>
语音转文本<|im_end|>
<|im_start|>assistant
[OUTPUT]营造良好的消费环境<|im_end|>
[LABELS]营造良好的消费环境
------------------------------------------------------------------------
[PROMPT]<|im_start|>system
You are a helpful assistant.<|im_end|>
<|im_start|>user
Audio 1:<audio>/root/.cache/modelscope/hub/datasets/speech_asr/speech_asr_aishell1_trainsets/master/data_files/extracted/037bf9a958c0e200c49ae900894ba0af40f592bb98f2dab81415c11e8ceac132/speech_asr_aishell_testsets/wav/test/S0764/BAC009S0764W0294.wav</audio>
语音转文本<|im_end|>
<|im_start|>assistant
[OUTPUT]解决小小芯片上的连线和物理问题需要大量昂贵设备<|im_end|>
[LABELS]解决小小芯片上的连线和物理问题需要大量昂贵设备
------------------------------------------------------------------------

模型部署

使用Vllm实现通义千问高效推理加速

魔搭社区和Vllm合作,为社区开发者提供更快更高效的通义千问推理服务

离线批量推理

预训练模型:

from vllm import LLM, SamplingParams
import os
# 设置环境变量,从魔搭下载模型
os.environ['VLLM_USE_MODELSCOPE'] = 'True'
llm = LLM(model="qwen/Qwen-1_8B", trust_remote_code=True)
prompts = [
    "Hello, my name is",
    "today is a sunny day,",
    "The capital of France is",
    "The future of AI is",
]
sampling_params = SamplingParams(temperature=0.8, top_p=0.95,stop=["<|endoftext|>"])
outputs = llm.generate(prompts, sampling_params,)
# print the output
for output in outputs:
    prompt = output.prompt
    generated_text = output.outputs[0].text
    print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")

对话模型:

import sys
from vllm import LLM, SamplingParams
import os
from modelscope import AutoTokenizer, snapshot_download
# 设置环境变量,从魔搭下载模型
model_dir = snapshot_download("qwen/Qwen-1_8b-Chat")
sys.path.insert(0, model_dir)
from qwen_generation_utils import (
    HistoryType,
    make_context,
    decode_tokens,
    get_stop_words_ids,
    StopWordsLogitsProcessor,
)
llm = LLM(model=model_dir, trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)
prompts = [
    "Hello, my name is Alia",
    "Today is a sunny day,",
    "The capital of France is",
    "Introduce YaoMing to me.",
]
sampling_params = SamplingParams(temperature=0.8, top_p=0.95, max_tokens=128, stop=['<|endoftext|>', '<|im_start|>'])
inputs = []
for prompt in prompts:
    raw_text, context_tokens = make_context(
        tokenizer,
        prompt,
        history=[],
        system="You are a helpful assistant.",
        chat_format='chatml',
    )
    inputs.append(context_tokens)
# call with prompt_token_ids, which has template information
outputs = llm.generate(prompt_token_ids=inputs, sampling_params=sampling_params,)
histories = []
for prompt, output in zip(prompts, outputs):
    history = []
    generated_text = output.outputs[0].text
    print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")
    history.append((prompt, generated_text))
    histories.append(history)
prompts_new = [
    'What is my name again?',
    'What is the weather I just said today?',
    'What is the city you mentioned just now?',
    'How tall is him?'
]
inputs = []
for prompt, history in zip(prompts_new, histories):
    raw_text, context_tokens = make_context(
        tokenizer,
        prompt,
        history=history,
        system="You are a helpful assistant.",
        chat_format='chatml',
    )
    inputs.append(context_tokens)
outputs = llm.generate(prompt_token_ids=inputs, sampling_params=sampling_params,)
# print the output
for prompt, output in zip(prompts_new, outputs):
    generated_text = output.outputs[0].text
    print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")

使用Qwen.cpp实现通义千问的多端部署:

多端部署以1.8B模型为例

第一步:使用qwen.cpp将pytorch格式的千问模型转为GGML格式

python3 qwen_cpp/convert.py -i qwen/Qwen-1_8-Chat -t q4_0 -o qwen-1_8b-ggml.bin

第二步:在Xinference上launch模型,并部署到Mac笔记本实现推理。

https://live.csdn.net/v/347883

点击直达72B对话模型创空间体验https://www.modelscope.cn/studios/qwen/Qwen-72B-Chat-Demo/summary

相关实践学习
借助OSS搭建在线教育视频课程分享网站
本教程介绍如何基于云服务器ECS和对象存储OSS,搭建一个在线教育视频课程分享网站。
相关文章
|
15天前
|
并行计算 PyTorch 算法框架/工具
社区供稿 | 本地部署通义千问大模型做RAG验证
这篇文章中,我们通过将模搭社区开源的大模型部署到本地,并实现简单的对话和RAG。
|
10天前
|
自然语言处理 Swift
千亿大模型来了!通义千问110B模型开源,魔搭社区推理、微调最佳实践
近期开源社区陆续出现了千亿参数规模以上的大模型,这些模型都在各项评测中取得杰出的成绩。今天,通义千问团队开源1100亿参数的Qwen1.5系列首个千亿参数模型Qwen1.5-110B,该模型在基础能力评估中与Meta-Llama3-70B相媲美,在Chat评估中表现出色,包括MT-Bench和AlpacaEval 2.0。
|
14天前
|
人工智能 算法 知识图谱
大模型首次接入天文望远镜!基于通义千问,“星语3.0”发布
大模型首次接入天文望远镜!基于通义千问,“星语3.0”发布
28 0
|
1月前
|
人工智能 架构师 搜索推荐
通义大模型使用指南之通义千问
本文介绍了如何注册并使用通义大模型,该平台提供了通义千问、通义万相和通义听悟三大功能。通义千问包含对话和百宝箱两个子功能。在对话中,用户需按照特定格式提问,如设定角色、背景等,但实际体验中,回复可能不够理想。百宝箱提供不同场景的应用,如健身教练和办公助理。通过示例展示了健身计划的生成,但与专业教练相比仍有差距。对于职场问题,通义千问的回答显得较为通用,难以满足个性化需求。
379 0
|
3月前
|
弹性计算 前端开发 Java
通义千问API:让大模型写代码和跑代码
基于前面三章的铺垫,本章我们将展示大模型Agent的强大能力。我们不仅要实现让大模型同时使用多种查询工具,还要实现让大模型能查询天气情况,最后让大模型自己写代码来查询天气情况。
59900 448
通义千问API:让大模型写代码和跑代码
|
3月前
|
自然语言处理 搜索推荐 API
通义千问API:用4行代码对话大模型
本章将通过一个简单的例子,让你快速进入到通义千问大模型应用开发的世界。
224364 105
通义千问API:用4行代码对话大模型
|
4月前
|
机器学习/深度学习 人工智能 算法
通义千问Qwen-72B-Chat大模型在PAI平台的微调实践
本文将以Qwen-72B-Chat为例,介绍如何在PAI平台的快速开始PAI-QuickStart和交互式建模工具PAI-DSW中高效微调千问大模型。
|
5月前
|
人工智能 API 异构计算
基于PAI-EAS一键部署通义千问模型
本教程中,您将学习如何在阿里云模型在线服务(PAI-EAS)一键部署基于开源模型通义千问的WebUI应用,以及使用WebUI和API进行模型推理。
|
5月前
|
人工智能 编解码 文字识别
通义千问720亿参数模型开源,适配企业级、科研级高性能应用
通义千问720亿参数模型开源,适配企业级、科研级高性能应用
1181 0
|
4月前
|
人工智能 自然语言处理 运维
NLP国内外大模型汇总列表[文心一言、智谱、百川、星火、通义千问、盘古等等]
NLP国内外大模型汇总列表[文心一言、智谱、百川、星火、通义千问、盘古等等]
NLP国内外大模型汇总列表[文心一言、智谱、百川、星火、通义千问、盘古等等]

热门文章

最新文章

http://www.vxiaotou.com