目錄
前言
一、下載源碼
1.下載ollama源碼
2.下載llama.cpp源碼
3.復制項目文件
二、安裝python依賴
三、合并模型文件
1.以Chinese-Mistral-7B-Instruct-v0.1為例,將4個safetensors文件合并為一個模型文件
2.下載Chinese-Mistral-7B-Instruct-v0.1模型
2.1下載模型
2.2合并文件
2.3合并過程
四、量化模型
1.安裝cmake和編譯器
2.開始編譯
3.量化模型
五、制作ollama使用的模型
1.創建Modelfile 文件
2.創建模型
3.運行模型
使用ollama+open-webui可以輕松部署本地大模型,但是通過ollama下載的模型都是別人制作好的。我的模型部署思路是大模型為底座+lora微調,實現真正的個人大模型,后續將分享自己的lora微調經驗和ollama調用lora。本文主要介紹如何在windows系統下將Safetensors 模型制作成ollama使用的自定義模型,linux系統自定義模型制作方法可直接按照官方文檔執行。ollama官方文檔提供了如何將GGUF,Pytorch或Safetensors 文件制作為自定義模型的方法。官方文檔https://github.com/ollama/ollama/blob/main/docs/import.md
https://github.com/ollama/ollama/tree/main
https://github.com/ggerganov/llama.cpp
下載解壓縮后,形成2個項目的文件
3.1以ollama為主項目,用pycharm打開ollama文件夾,顯示如下:
3.2將之前下載的llama.cpp項目文件夾復制到圖上的llama.cpp位置。鼠標選中llm文件夾,按ctral+v即粘貼至llama.cpp文件夾。效果如下所示:
打開終端,確保自己的路徑如下所示。養成良好習慣,創建一個虛擬環境,然后再執行pip安裝命令,確保不與電腦上的其他項目環境發生沖突。
pip install ./llm/llama.cpp/requirements.txt
模型可以在https://huggingface.co/,或者huggingface鏡像網站https://hf-mirror.com/,或者魔搭社區進行下載,我用魔搭社區的python腳本進行下載,下載速度直接拉滿,執行前需要先運行pip install modelscope 。
- from modelscope import snapshot_download
- #模型存放路徑
- model_path = r'D:\huggingface'
- #模型名字
- name = 'itpossible/Chinese-Mistral-7B-Instruct-v0.1'
- model_dir = snapshot_download(name, cache_dir=model_path, revision='master')
- # python llm/llama.cpp/convert.py 剛才下載好的模型文件地址 --outtype f16 --outfile 保存的文件名.bin
- python llm/llama.cpp/convert.py D:\huggingface\itpossible\Chinese-Mistral-7B-Instruct-v0___1 --outtype f16 --outfile D:\huggingface\itpossible\converted.bin
llama.cpp項目有變動,新下載的llama.cpp源碼中已經沒有convert.py這個腳本了,現在使用convert_hf_to_gguf.py腳本來進行模型的合并操作。下面是官方發布的變動說明。
合并后產生的文件converted.bin大小約14G
接下來,需要將14G的bin文件量化為4G左右。這個步驟需要編譯文件,使用cmake工具來編譯。傳送門——cmake安裝教程。同時,還需要安裝編譯器,我用visual studio安裝的C++編譯器。傳送門——vs使用教程。
驗證cmake是否安裝成功,下圖表示安裝成功。
在 llm/llama.cpp文件夾下開始編譯
- # 進入到llm/llama.cpp目錄
- cd llm/llama.cpp
- #創建build文件夾
- mkdir build
- #進入build
- cd build
- # 構建
- cmake ..
- cmake --build . --config Release
編譯過程需要一些,耐心等待一下。編譯后生成的quantization.exe就是我們需要用到的工具。
- # bin/Release/quantize.exe 之前合并的14G大小文件.bin 量化后的文件.bin 量化大小
- bin/Release/quantize.exe D:\huggingface\itpossible\converted.bin D:\huggingface\itpossible\quantized.bin q4_0
官方文檔提供了多種量化格式,常用的就是q4_0。
量化過程如下:
壓縮量化完成后,生成一個新的文件quantized.bin,大約4G。之前14G的源文件可以刪除了。
需要將quantized.bin文件制作為ollama可以使用的模型
Modelfile
文件創建一個test.Modelfile
文件,添加的內容如下
- FROM D:\huggingface\itpossible\quantized.bin
- TEMPLATE "[INST] {{ .Prompt }} [/INST]"
2.1指定生成的模型路徑
設置模型文件保存位置,打開系統環境變量配置,添加一個環境變量OLLAMA_MODELS=D:\huggingface\ollama(自己指定任意一個文件夾路徑),然后點確定。
2.2打開一個CMD終端
- # ollama create 模型名字 -f Modelfile文件路徑
- ollama create panda -f C:\Users\Administrator\Desktop\ollama\test.Modelfile
2.3創建過程
2.4生成的模型
ollama run panda