文章目录
引言
你是否还在为在colab微调大模型训练时GPU资源受限和空间不足,或者模型文件过大导出费时又费力而发愁?那么这篇文章将教你如何在自己的服务器上部署,用unsloth 去微调训练llama3.1大模型 ,打破colab的局限性!
1. 创建unsloth所需的conda虚拟环境
- 这里以要求
python3.10
,pytorch2.3
,cuda12.1
为例。
1.1 创建python3.10版本的conda虚拟环境
conda create -n unsloth python=3.10
1.1.1 补充:conda的一些常用命令
环境管理(最常用)
-
创建新环境:
conda create --name env_name python=3.10
-
激活环境:
conda activate env_name
-
停用当前环境:
conda deactivate
-
列出所有环境:
conda env list
-
删除环境:
conda remove --name env_name --all
包管理
-
安装包:
conda install package_name
-
更新包:
conda update package_name
-
卸载包:
conda remove package_name
-
列出已安装的包:
conda list
-
查找包:
conda search package_name
其他命令
-
更新 conda 本身:
conda update conda
-
导出环境配置:
conda env export > environment.yml
-
从环境配置文件创建环境:
conda env create -f environment.yml
-
清理未使用的包和缓存:
conda clean --all
1.2 激活创建的虚拟环境,并安装cuda12.1版本的pytorch2.3
- 激活环境:
conda activate unsloth
- 进入pytorch官网,找寻对应的版本
- 命令如下
conda install pytorch==2.3.0 torchvision==0.18.0 torchaudio==2.3.0 pytorch-cuda=12.1 -c pytorch -c nvidia
注意:环境中如果没有TensorFlow,记得安装,因为pytorch
和tensorflow
具有关联性
2. 安装unsloth及其所需的包
pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
pip install --no-deps "xformers==0.0.27" trl peft accelerate bitsandbytes
3. 执行训练所需的相关代码
- 执行训练代码之前,需要先执行这三条代码。
python程序默认使用的是0号GPU,所以可以先参考GPU的情况(nvidia-smi
),然后选择要用的GPU
export CUDA_VISIBLE_DEVICES="4"
export NCCL_P2P_DISABLE="1"
export NCCL_IB_DISABLE="1"
- 补充:如果没开科学上网,需要打开,命令如下(没sudo权限,找管理员)
sudo systemctl start v2raya.service
- 训练所需的代码比如叫
run.py
- 运行run.py
python run.py
- 运行run.py
# 帅小柏
import os
import torch
from unsloth import FastLanguageModel, is_bfloat16_supported
from transformers import TextStreamer, TrainingArguments
from datasets import load_dataset
from trl import SFTTrainer
# 1. Configuration
max_seq_length = 2048
dtype = None
load_in_4bit = True
alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{}
### Input:
{}
### Response:
{}"""
instruction = "以下是一首唐詩的第一句話,請用你的知識判斷並完成整首詩。" # instruction
input = "长风破浪会有时,直挂云帆济沧海。"
# huggingface_model_name = "poem"
# 2. Before Training
model, tokenizer = FastLanguageModel.from_pretrained(
# model_name = "unsloth/Meta-Llama-3.1-8B",
# model_name = "unsloth/llama-3-8b-bnb-4bit",
model_name = "unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit",
max_seq_length = max_seq_length,
dtype = dtype,
load_in_4bit = load_in_4bit,
# token = os.getenv("HF_TOKEN")
)
FastLanguageModel.for_