以 Llama-3-8B-Instruct 为例,演示在 DSW 中对 Llama3 模型进行参数微调训练,使模型更好地适应特定任务。
背景信息
Llama3是Meta于2024年4月开放的Llama系列的最新模型。基于超过15万亿tokens的训练,相当于Llama2数据集的7倍之多。该模型不仅支持8K长文本,还配备了经过改进的Tokenizer,其词汇量高达128K token,确保在处理复杂语境和专业术语时实现更精准高效的性能表现。
Llama3提供8B和70B两个版本以满足不同场景的需求,每个版本都包括基础和指令调优两种形式:
8B版本
适合消费级GPU环境,确保在有限计算资源下实现快速部署与开发工作,适用于对模型响应速度与成本效益要求较高的应用场景。
Meta-Llama-3-8b:8B基础模型
Meta-Llama-3-8b-instruct:8B基础模型的指令调优版
70B版本
面向大规模AI应用定制,凭借其庞大的参数规模,适合处理高复杂度任务和追求更优模型性能的高端项目。
Meta-Llama-3-70b:70B基础模型
Meta-Llama-3-70b-instruct:70B基础模型的指令调优版
前提条件
创建工作空间,详情请参见创建及管理工作空间。
创建DSW实例,关键参数配置如下。具体操作,请参见创建DSW实例。
实例规格选择:推荐使用V100(16GB)或更高显存的GPU。
Python环境:建议使用Python3.9及以上版本。
镜像选择:本方案在镜像URL中输入
dsw-registry-vpc.REGION.cr.aliyuncs.com/pai-training-algorithm/llm_deepspeed_peft:v0.0.3,REGION需替换为DSW实例所属地域对应的代号,例如cn-hangzhou、cn-shanghai等,更多地域和REGION对应关系请参见下表。地域
REGION代号
杭州
cn-hangzhou
上海
cn-shanghai
北京
cn-beijing
深圳
cn-shenzhen
使用Llama3大模型前请阅读Meta官方许可证。
说明如果无法访问,您可能需要设置代理后再尝试重新访问。
步骤一、下载模型
方式一:在DSW下载模型
进入DSW开发环境。
登录PAI控制台。
在页面左上方,选择DSW实例所在的地域。
在左侧导航栏单击工作空间列表,在工作空间列表页面中单击默认工作空间名称,进入对应工作空间内。
在左侧导航栏,选择模型开发与训练>交互式建模(DSW)。
单击需要打开的实例操作列下的打开,进入DSW实例开发环境。
在Launcher页面中,单击快速开始区域Notebook下的Python3。
在Notebook中执行以下代码下载模型文件。代码自动选择下载地址,并将模型文件下载至当前目录。
! pip install modelscope==1.32.0 transformers==4.37.0from modelscope.hub.snapshot_download import snapshot_download snapshot_download('LLM-Research/Meta-Llama-3-8B-Instruct', cache_dir='.', revision='master')
方式二:在Meta下载模型
如果无法访问,您可能需要设置代理后再尝试重新访问。
步骤二、准备数据集
本案例提供了英文诗歌数据集,用于微调 Llama 3 模型,提高诗歌生成能力。在 Notebook 中执行以下命令下载训练数据。
!wget https://atp-modelzoo-sh.oss-cn-shanghai.aliyuncs.com/tutorial/llm_instruct/en_poetry_train.json也可参考该数据集格式,根据实际场景准备数据。微调可提高大语言模型在特定任务上的回答准确性。
步骤三、微调模型
LoRA轻量化训练
基于训练脚本/ml/code/sft.py对模型进行LoRA轻量化训练。训练结束后,量化模型参数,以减少推理时的显存占用。
当运行accelerate launch命令时,会使用这些参数启动指定的Python脚本,并且根据multi_gpu.yaml配置文件中的设置,在计算资源允许的范围内进行训练。
! accelerate launch --num_processes 1 --config_file /ml/code/multi_gpu.yaml /ml/code/sft.py \
--model_name ./LLM-Research/Meta-Llama-3-8B-Instruct/ \
--model_type llama \
--train_dataset_name en_poetry_train.json \
--num_train_epochs 3 \
--batch_size 8 \
--seq_length 128 \
--learning_rate 5e-4 \
--lr_scheduler_type linear \
--target_modules k_proj o_proj q_proj v_proj \
--output_dir lora_model/ \
--apply_chat_template \
--use_peft \
--load_in_4bit \
--peft_lora_r 32 \
--peft_lora_alpha 32 示例使用的参数说明如下,请根据实际情况修改:
accelerate launch命令行工具用于在多GPU中启动和管理深度学习训练脚本。num_processes 1:设置并行处理的进程数量为1,即不进行多进程并行处理。config_file/ml/code/multi_gpu.yaml:指定配置文件的路径。/ml/code/sft.py:指定要运行的Python脚本的路径。
脚本
/ml/code/sft.py接受的参数:--model_name./LLM-Research/Meta-Llama-3-8B-Instruct/:指定预训练模型的路径。--model_type llama:指定模型的类型,此处为Llama。--train_dataset_namechinese_medical_train_sampled.json:指定训练数据集的路径。--num_train_epochs 3:设置训练的轮次为3。--batch_size 8:设置批处理的大小为8。--seq_length 128:设置序列的长度为128。--learning_rate 5e-4:设置学习率为0.0005。--lr_scheduler_type linear:设置学习率调度器类型为线性。--target_modules k_proj o_proj q_proj v_proj:指定在微调中需要特别关注的模型模块。--output_dir lora_model/:指定输出目录路径,微调后的模型将被保存在这里。--apply_chat_template:指定训练时应用聊天模板。--use_peft:在训练过程中使用参数有效调优PEFT(Parameter-Efficient Fine-Tuning)方法。--load_in_4bit:指示模型权重载入时使用4位精度,减少内存消耗。--peft_lora_r 32:如果使用了LoRA(Low-Rank Adaptation)作为参数有效调优方法的一部分,这会指定LoRA的值为32。--peft_lora_alpha 32:设置LoRA参数的另一部分,alpha的大小为32。
将LoRA权重与基础模型融合
执行以下命令,将LoRA权重与基础模型融合。
! RANK=0 python /ml/code/convert.py \
--model_name ./LLM-Research/Meta-Llama-3-8B-Instruct/ \
--model_type llama \
--output_dir trained_model/ \
--adapter_dir lora_model/示例使用的参数说明如下:
RANK=0:环境变量RANK用于分布式训练中,表示当前进程在所有进程中的序号。设为0表明它是单进程或者是分布式训练中的主进程。python /ml/code/convert.py:执行convert.py脚本,用于权重转换或其他转换工作。--model_name ./LLM-Research/Meta-Llama-3-8B-Instruct/:指定基础模型的路径。--model_type llama:指定模型类型,此处为Llama。--output_dir trained_model/:指定转换后的模型和权重应该输出保存的目录。--adapter_dir lora_model/:指定包含LoRA适配器权重的目录。
步骤四、推理模型
执行以下命令推理模型,验证微调效果。这里让模型写一首关于春天的诗歌:
import torch, transformers
# model_id = "./LLM-Research/Meta-Llama-3-8B-Instruct/"
model_id = "./trained_model/"
pipeline = transformers.pipeline(
"text-generation",
model=model_id,
model_kwargs={"torch_dtype": torch.bfloat16},
device="cuda",
)
messages = [
{"role": "user", "content": "Write a poem on a topic 'spring' "},
]
prompt = pipeline.tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
terminators = [
pipeline.tokenizer.eos_token_id,
pipeline.tokenizer.convert_tokens_to_ids("<|eot_id|>")
]
outputs = pipeline(
prompt,
max_new_tokens=1024,
eos_token_id=terminators,
do_sample=True,
temperature=0.6,
top_p=0.9,
)
print(outputs[0]["generated_text"][len(prompt):])以下是模型生成的回答,可以看出微调后的模型在诗歌写作方面表现很好:
Here's a poem on the topic of "Spring":
As winter's chill begins to fade,
The earth awakens from its shade,
And spring's sweet breath begins to blow,
Bringing life to all that's cold and slow.
The trees regain their vibrant hue,
And flowers bloom, both old and new,
Their petals dancing in the breeze,
As sunshine warms the world with ease.
The air is filled with sweet perfume,
As blossoms burst forth in their room,
And robins sing their morning song,
As spring's awakening is strong.
The world is fresh, and new, and bright,
As spring's warm light begins to take flight,
And all around, new life unfolds,
As winter's grip begins to grow old.
So let us bask in spring's warm rays,
And let our spirits soar and sway,
For in this season, we're reborn,
And all around, new life is sworn.
I hope you enjoy it!步骤五、部署模型
将微调后的模型权重上传至OSS,使用EAS ChatLLM部署Llama3模型服务。具体操作,请参见5分钟使用EAS一键部署LLM大语言模型应用。
附录:从DSW Gallery中运行Llama3
DSW Gallery 内置 Llama3 Notebook 案例,可在 DSW 实例中一键运行或按需修改。具体操作,请参见Notebook Gallery。
常见问题
Q:下载模型时报错:FileDownloadError: File config.json download imcomlete,content_length: None but the ......
请在Terminal中执行pip install -U modelscope升级modelscope包,并在Notebook页面上方单击
图标,重新加载Python Kernel,然后再重新执行下载模型代码。
相关文档
若要了解ChatLLM-WebUI的重要版本发布信息,请参见ChatLLM-WebUI版本发布详情。