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

本文涉及的产品
模型在线服务 PAI-EAS,A10/V100等 500元 1个月
交互式建模 PAI-DSW,5000CU*H 3个月
模型训练 PAI-DLC,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,搭建一个在线教育视频课程分享网站。
相关文章
|
1月前
|
人工智能 开发者
通义千问三款主力模型再降价,最高降幅85%
通义千问三款主力模型再降价,最高降幅85%
424 11
通义千问三款主力模型再降价,最高降幅85%
|
1月前
|
编解码 JSON 自然语言处理
通义千问重磅开源Qwen2.5,性能超越Llama
击败Meta,阿里Qwen2.5再登全球开源大模型王座
1651 17
|
1月前
|
API 云栖大会
通义千问升级旗舰模型Qwen-Max,性能接近GPT-4o
通义旗舰模型Qwen-Max全方位升级,性能接近GPT-4o
525 10
|
1月前
|
存储 关系型数据库 分布式数据库
GraphRAG:基于PolarDB+通义千问+LangChain的知识图谱+大模型最佳实践
本文介绍了如何使用PolarDB、通义千问和LangChain搭建GraphRAG系统,结合知识图谱和向量检索提升问答质量。通过实例展示了单独使用向量检索和图检索的局限性,并通过图+向量联合搜索增强了问答准确性。PolarDB支持AGE图引擎和pgvector插件,实现图数据和向量数据的统一存储与检索,提升了RAG系统的性能和效果。
|
1月前
|
编解码 自然语言处理 机器人
通义千问Qwen2-VL开源,API可直接调用!
通义千问宣布开源第二代视觉语言模型Qwen2-VL,并推出2B、7B两个尺寸及其量化版本模型。同时,旗舰模型Qwen2-VL-72B的API已上线阿里云百炼平台,用户可直接调用。
335 8
|
18天前
|
存储 关系型数据库 分布式数据库
GraphRAG:基于PolarDB+通义千问+LangChain的知识图谱+大模型最佳实践
本文介绍了一种结合知识图谱与大型语言模型(LLM)的GraphRAG系统,利用PolarDB、通义千问及LangChain实现。知识图谱通过结构化信息、语义理解和推理等功能,增强了信息检索与自然语言处理效果。PolarDB具备图引擎与向量检索能力,适配知识图谱存储与查询。通义千问处理自然语言,LangChain则整合模型与应用。实战步骤包括环境准备、数据库配置与数据导入,并通过实例展示了图谱与向量联合检索的优越性,提升了问答系统的准确性和实用性。
|
2月前
|
自然语言处理 开发者
通义千问继续开源!阿里云38篇论文被顶会ACL 2024录用
通义千问继续开源!阿里云38篇论文被顶会ACL 2024录用
90 8
|
3月前
|
JSON API 定位技术
AppFlow:让通义千问大模型调用你的任意API
在阿里云AppFlow中,通过自定义插件连接器可使通义千问获取特定功能,如旅游规划或投资辅助。登录AppFlow控制台,选择“自定义连接器”,上传图标,设定基本信息,选“插件连接器”。支持Basic、Bearer Token、AppCode等鉴权。精确配置API名称、描述及请求参数,确保模型调用准确。参考示例curl命令调整参数结构,填写响应体帮助模型解析。发布后,在模型Agent搭建中选用自定义连接器增强功能。
|
3月前
|
人工智能
|
5月前
|
并行计算 PyTorch 算法框架/工具
社区供稿 | 本地部署通义千问大模型做RAG验证
这篇文章中,我们通过将模搭社区开源的大模型部署到本地,并实现简单的对话和RAG。