10G顯存,使用Unsloth微調(diào)Qwen2并使用Ollama推理

本文主要使用Unsloth基于Qwen2基礎(chǔ)模型微調(diào)對話機(jī)器人以及在Ollama上運(yùn)行。

在魔搭社區(qū)免費(fèi)算力上,僅需要10G顯存,使用Unsloth來微調(diào)Qwen2創(chuàng)建自定義聊天機(jī)器人,并創(chuàng)建GGUF文件,可以在PC端本地運(yùn)行。

參考鏈接

Unsloth是什么?

Unsloth是一個預(yù)訓(xùn)練模型微調(diào)框架,專注于提高訓(xùn)練速度和減少顯存占用。針對現(xiàn)在主流模型,如Llama-3,Qwen2,Mistral等LLM的微調(diào)速度可提升2倍,內(nèi)存使用量減少70%,而且準(zhǔn)確度并不會降低!

  • 所有內(nèi)核均用OpenAI 的 Triton語言編寫
  • 準(zhǔn)確度損失為 0%
  • 通過bitsandbytes支持 4 位和 16 位 QLoRA / LoRA 微調(diào)。
  • 開源訓(xùn)練速度提高 5 倍
  • 擁有一張很酷的貼紙!所有基于Unsloth的模型都可以用這張貼紙


    image.png

在本教程中,使用魔搭社區(qū)的免費(fèi)GPU,使用10G顯存微調(diào)Qwen2-7B

image.png

Ollama是什么?

Ollama 是一款極其簡單的基于命令行的工具,用于運(yùn)行 LLM,極易上手,可用于構(gòu)建 AI 應(yīng)用程序。本文使用Ollama作為我們的推理引擎。


image.png

環(huán)境安裝

選擇魔搭社區(qū)鏡像版本:


image.png

安裝Unsloth:

!pip install "unsloth[cu121-torch230] @ git+https://github.com/unslothai/unsloth.git"

選擇需要微調(diào)的模型

本文選擇Qwen2-7B,Qwen2 是 Qwen 大型語言模型的新系列。與最先進(jìn)的開源語言模型(包括之前發(fā)布的 Qwen1.5)相比,Qwen2 總體上超越了大多數(shù)開源模型,并在一系列針對語言理解、語言生成、多語言能力、編碼、數(shù)學(xué)、推理等的基準(zhǔn)測試中展現(xiàn)出與專有模型的競爭力。

  
from unsloth import FastLanguageModel
import torch
from modelscope import snapshot_download
max_seq_length = 2048 
dtype = torch.bfloat16
load_in_4bit = True 


model_dir=snapshot_download("qwen/Qwen2-7B")
model, tokenizer = FastLanguageModel.from_pretrained(
model_name = model_dir, 
max_seq_length = max_seq_length,
dtype = dtype,
load_in_4bit = load_in_4bit,
)

其中三個參數(shù)的設(shè)置:

max_seq_length = 2048

這決定了模型的上下文窗口長度,比如Qwen2-7B的上下文長度為32K,并可以通過yarn拓展到128K。本文從測試的角度,設(shè)置上下文長度為2048。

dtype = torch.bfloat16

根據(jù)A10的GPU選擇torch.bfloat16

load_in_4bit = True

本文采用 4 位量化進(jìn)行微調(diào)。這樣可將內(nèi)存使用量減少 4 倍。4 位量化本質(zhì)上將權(quán)重轉(zhuǎn)換為一組有限的數(shù)字以減少內(nèi)存使用量。這樣做的缺點(diǎn)是準(zhǔn)確度會下降 1-2%。

微調(diào)參數(shù)

model = FastLanguageModel.get_peft_model(
    model,
    r = 16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
    target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
                      "gate_proj", "up_proj", "down_proj",],
    lora_alpha = 16,
    lora_dropout = 0, # Supports any, but = 0 is optimized
    bias = "none",    # Supports any, but = "none" is optimized
    # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes!
    use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context
    random_state = 3407,
    use_rslora = False,  # We support rank stabilized LoRA
    loftq_config = None, # And LoftQ
)

微調(diào)參數(shù)的設(shè)置目標(biāo)是改變這些微調(diào)參數(shù)以提高微調(diào)的準(zhǔn)確性,同時也不希望發(fā)生過擬合。過度擬合是指讓語言模型記住數(shù)據(jù)集,而無法回答新穎的新問題。本文希望最終模型能夠回答從未見過的問題,而不是進(jìn)行記憶。

r = 16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128

微調(diào)過程的rank。數(shù)值越大,占用的內(nèi)存越多,速度越慢,但可以提高復(fù)雜任務(wù)的準(zhǔn)確性。通常建議數(shù)值為 8(用于快速微調(diào)),最高可達(dá) 128。數(shù)值過大可能會導(dǎo)致過度擬合,從而損害模型的質(zhì)量。

target_modules = ["q_proj", "k_proj", "v_proj", "o_proj","gate_proj", "up_proj", "down_proj",],

微調(diào)的縮放因子。較大的數(shù)字將使微調(diào)更多地了解您的數(shù)據(jù)集,但可能會導(dǎo)致過度擬合。建議將其等于等級r,或?qū)⑵浼颖丁?/p>

lora_dropout = 0, # Supports any, but = 0 is optimized

將其保留為 0 以加快訓(xùn)練速度!可以減少過度擬合,但效果不大。

bias = "none",# Supports any, but = "none" is optimized

將其保留為 none,以實(shí)現(xiàn)更快、更少的過度擬合訓(xùn)練!

use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context

選項包括<b>True</b>、<b>False</b> 和"unsloth"。本文建議這樣做"unsloth",因?yàn)閡nsloth將內(nèi)存使用量減少了 30%,并支持極長的上下文微調(diào)。

random_state = 3407,

確定確定性運(yùn)行的次數(shù)。訓(xùn)練和微調(diào)需要隨機(jī)數(shù),因此設(shè)置此數(shù)字可使實(shí)驗(yàn)可重復(fù)。

use_rslora = False,# We support rank stabilized LoRA

高級功能可自動設(shè)置 <b>lora_alpha = 16。</b>

高級功能可將 LoRA 矩陣初始化為權(quán)重的前 r 個奇異向量??梢栽谝欢ǔ潭壬咸岣邷?zhǔn)確度,但一開始會使內(nèi)存使用量激增。

Prompt模板和數(shù)據(jù)集

現(xiàn)在使用 Qwen-2 的chatml格式進(jìn)行對話風(fēng)格微調(diào)。數(shù)據(jù)集使用 ShareGPT 風(fēng)格的 Open Assistant 對話數(shù)據(jù)集。
數(shù)據(jù)集鏈接
使用 get_chat_template 函數(shù)來獲取正確的聊天模板。get_chat_template 函數(shù)目前支持 zephyr、chatml、mistral、llama、alpaca、vicuna、vicuna_old 等模板。

注意 ShareGPT 使用 {"from": "human", "value" : "Hi"} 而不是 {"role": "user", "content" : "Hi"},因此使用mapping做一輪映射。


from unsloth.chat_templates import get_chat_template

tokenizer = get_chat_template(
tokenizer,
chat_template = "chatml", # Supports zephyr, chatml, mistral, llama, alpaca, vicuna, vicuna_old, unsloth
mapping = {"role" : "from", "content" : "value", "user" : "human", "assistant" : "gpt"}, # ShareGPT style
)

def formatting_prompts_func(examples):
convos = examples["conversations"]
texts = [tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = False) for convo in convos]
return { "text" : texts, }
pass

from modelscope.msdatasets import MsDataset
dataset =MsDataset.load('OmniData/guanaco-sharegpt-style', split = "train")
dataset = dataset.map(formatting_prompts_func, batched = True,)

可以看到mapping前后的數(shù)據(jù)集的具體樣式:


image.png

訓(xùn)練模型

下面開始訓(xùn)練模型,使用huggingface的trl庫


from trl import SFTTrainer
from transformers import TrainingArguments
from unsloth import is_bfloat16_supported

trainer = SFTTrainer(
    model = model,
    tokenizer = tokenizer,
    train_dataset = dataset,
    dataset_text_field = "text",
    max_seq_length = max_seq_length,
    dataset_num_proc = 2,
    packing = False, # Can make training 5x faster for short sequences.
    args = TrainingArguments(
    per_device_train_batch_size = 2,
    gradient_accumulation_steps = 4,
    warmup_steps = 5,
    max_steps = 60,
    learning_rate = 2e-4,
    fp16 = not is_bfloat16_supported(),
    bf16 = is_bfloat16_supported(),
    logging_steps = 1,
    optim = "adamw_8bit",
    weight_decay = 0.01,
    lr_scheduler_type = "linear",
    seed = 3407,
    output_dir = "outputs",
    ),
)

通常不建議更改上述參數(shù),但需要詳細(xì)說明其中一些參數(shù):

per_device_train_batch_size = 2,

如果想更多地利用 GPU 的內(nèi)存,請增加批處理大小。同時增加批處理大小可以使訓(xùn)練更加流暢,并使過程不會過度擬合。

gradient_accumulation_steps = 4,

相當(dāng)于將批量大小增加到自身之上,但不會影響內(nèi)存消耗!如果您想要更平滑的訓(xùn)練損失曲線,通常建議增加這個值。

max_steps = 60, # num_train_epochs = 1,

我們將步驟設(shè)置為 60 以加快訓(xùn)練速度。對于可能需要數(shù)小時的完整訓(xùn)練運(yùn)行,請注釋掉max_steps,并將其替換為<b>num_train_epochs = 1</b>。將其設(shè)置為 1 表示對數(shù)據(jù)集進(jìn)行 1 次完整傳遞。通常建議傳遞 1 到 3 次,不要更多,否則您的微調(diào)會過度擬合。

learning_rate = 2e-4,

如果您想讓微調(diào)過程變慢,但同時又最有可能收斂到更高精度的結(jié)果,請降低學(xué)習(xí)率。我們通常建議嘗試 2e-4、1e-4、5e-5、2e-5 作為數(shù)字。

trainer_stats = trainer.train()
image.png

顯存占用(使用Unsloth):


image.png

推理/運(yùn)行模型

完成訓(xùn)練過程后運(yùn)行模型!


from unsloth.chat_templates import get_chat_template

tokenizer = get_chat_template(
tokenizer,
chat_template = "chatml", # Supports zephyr, chatml, mistral, llama, alpaca, vicuna, vicuna_old, unsloth
mapping = {"role" : "from", "content" : "value", "user" : "human", "assistant" : "gpt"}, # ShareGPT style
)

FastLanguageModel.for_inference(model) # Enable native 2x faster inference

messages = [
{"from": "human", "value": "杭州的省會在哪里?"},
]
inputs = tokenizer.apply_chat_template(
messages,
tokenize = True,
add_generation_prompt = True, # Must add for generation
return_tensors = "pt",
).to("cuda")

outputs = model.generate(input_ids = inputs, max_new_tokens = 64, use_cache = True)
tokenizer.batch_decode(outputs)

也支持流式輸出:


FastLanguageModel.for_inference(model) # Enable native 2x faster inference

messages = [
{"from": "human", "value": "杭州的省會在哪里?"},
]
inputs = tokenizer.apply_chat_template(
messages,
tokenize = True,
add_generation_prompt = True, # Must add for generation
return_tensors = "pt",
).to("cuda")

from transformers import TextStreamer
text_streamer = TextStreamer(tokenizer, skip_prompt = True)
_ = model.generate(input_ids = inputs, streamer = text_streamer, max_new_tokens = 128, use_cache = True)

保存模型

我們將微調(diào)后的模型保存到一個名叫LoRA的100MB小文件。

model.save_pretrained("lora_model") # Local savingtokenizer.save_pretrained("lora_model")

導(dǎo)出至Ollama

最后,可以將經(jīng)過微調(diào)的模型導(dǎo)出為GGUF格式!本文選擇的量化方法是q4_k_m格式??梢郧巴?a target="_blank">https://github.com/ggerganov/llama.cpp了解有關(guān) GGUF 的更多信息。

if True: model.save_pretrained_gguf("model", tokenizer, quantization_method = "q4_k_m")
image.png

自動創(chuàng)建Modelfile

Unsloth 在轉(zhuǎn)化模型為GGUF格式的時候,自動生成Ollama所需的Modelfile文件,其中包括模型的路徑和我們用于微調(diào)過程的聊天模板!可以打印Modelfile生成的模板,如下所示:

print(tokenizer._ollama_modelfile)
image.png

使用Ollama創(chuàng)建和推理模型

Linux環(huán)境使用

Liunx用戶可使用魔搭鏡像環(huán)境安裝【推薦】

git clone https://www.modelscope.cn/modelscope/ollama-linux.gitcd ollama-linuxsudo chmod 777 ./ollama-modelscope-install.sh./ollama-modelscope-install.sh

啟動Ollama服務(wù)

ollama serve

創(chuàng)建自定義模型

使用ollama create命令創(chuàng)建自定義模型

!ollama create unsloth_qwen2 -f /mnt/workspace/model/Modelfile

多輪對話測試

在terminal中運(yùn)行g(shù)guf模型

ollama run unsloth_qwen2

測試模型多輪對話效果:


image.png

至此,您已經(jīng)成功使用Unsloth微調(diào)了Qwen2基礎(chǔ)模型,使之具備多輪對話能力,并導(dǎo)出Ollama支持本地運(yùn)行,顯存使用10G以內(nèi),可以在魔搭社區(qū)的免費(fèi)算力中完成。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容