文:紅蘋果3d模型 - 食物廚房3d模型下載 蠻蝸網(wǎng) https://www.3dsnail.com/thread-85404-1-1.html
色智能手表 蘋果公司 Apple Watch Ultra 戶外手表 電子表 - 機械電器3d模型 蠻蝸網(wǎng)
調(diào)大語言模型是常見的需求,由于模型參數(shù)量大,即使用 Lora/Qlora 進行微調(diào)也需要 GPU 顯卡,Mac M系是蘋果自己的 GPU,目前主流的框架還在建立在 CUDA 的顯卡架構(gòu),也就是主要的卡還是來自英偉達。如果要用 Mac 來做訓(xùn)練和推理,需要用MLX,MLX 類似于 Pytorch,對蘋果芯片做了支持,從而使得蘋果電腦也可以進行深度學(xué)習(xí)。本文將介紹如何用 MLX 訓(xùn)練 Phi3 大語言模型,
pip install mlx-lm
這里需要訪問 HuggingFace 下載,可以使用國內(nèi)鏡像
國內(nèi)鏡像
https://hf-mirror.com/
export HF_ENDPOINT=https://hf-mirror.com
python -m mlx_lm.generate --model microsoft/Phi-3-mini-4k-instruct --max-token 2048 --prompt "<|user|>\nCan you introduce yourself<|end|>\n<|assistant|>"
mlx 的命令都有一些默認(rèn)值,-h 中沒有具體說明, 只能去源碼里看。
例如,轉(zhuǎn)換完成的模型會保存到 mlx_model 目錄下。
python -m mlx_lm.convert --hf-path microsoft/Phi-3-mini-4k-instruct
首先準(zhǔn)備數(shù)據(jù),MLX 使用 jsonl 數(shù)據(jù)格式進行訓(xùn)練,從 github 下載數(shù)據(jù)集并存放到 data 目錄下,一共三個文件,test、train 和 valid,文件下載好之后我們就可以開始訓(xùn)練了。
https://github.com/microsoft/Phi-3CookBook/tree/main/code/04.Finetuning/mlx/data
消耗資源比較多,M2 風(fēng)扇又開始轉(zhuǎn)了。
python -m mlx_lm.lora --model microsoft/Phi-3-mini-4k-instruct --train --data ./data --iters 1000
python -m mlx_lm.generate --model microsoft/Phi-3-mini-4k-instruct --adapter-path ./adapters --max-token 2048 --prompt "Why do chameleons change colors? " --eos-token "<|end|>"
python -m mlx_lm.generate --model microsoft/Phi-3-mini-4k-instruct --max-token 2048 --prompt "Why do chameleons change colors? " --eos-token "<|end|>"
可以看到,訓(xùn)練之后的模型結(jié)果更加精簡。
將原 Lora 的 adapter 合并到原始模型中。
python -m mlx_lm.fuse --model microsoft/Phi-3-mini-4k-instruct
通過 llama.cpp 生成 GGUF,量化參數(shù)支持 'f32', 'f16', 'bf16', 'q8_0',根據(jù)需要自行修改。Phi3 模型默認(rèn)沒有 tokenizer.model,需要從 HF 下載 https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/tree/main
將 tokenizer.model 復(fù)制到 /lora_fused_model/ 目錄下,完成運行生成GGUF 的轉(zhuǎn)換命令。
git clone https://github.com/ggerganov/llama.cpp.git
cd llama.cpp
pip install -r requirements.txt
python convert-hf-to-gguf.py ../lora_fused_model --outfile ../phi-3-mini-ft.gguf --outtype q8_0
首先創(chuàng)建 Ollama 的模型文件 ModelFile,和上一步生成的 gguf 文件放到同一個目錄下
FROM ./phi-3-mini-ft.gguf
PARAMETER stop "<|end|>"
創(chuàng)建模型
ollama create phi3ft -f Modelfile
Ollama 啟動模型并進行推理
ollama run phi3ft
MLX 模型推理非常簡單,數(shù)據(jù)準(zhǔn)備好就可以訓(xùn)練和推理,本次使用的是 phi3 模型,中文支持的不好,以后可以試試 Qwen2 怎么樣。