SafetensorsをGGUFに変換する方法

2024.06.14
SafetensorsをGGUFに変換する方法の紹介。SafetensorsのArrowPro-7B-KillerWhaleをggufに変換してOllamaで動かしてみます。
ArrowPro-7B-KillerWhaleのgguf版すでにあった。
https://huggingface.co/mmnga/ArrowPro-7B-KillerWhale-gguf/tree/main
必要なものをインストール
git-lfsとcmakeをインストール。
$ sudo apt install git-lfs cmake
GGUF化したいモデルをクローン
次のコマンドで対象のモデル「https://huggingface.co/DataPilot/ArrowPro-7B-KillerWhale」をクローンします。
$ git clone https://huggingface.co/DataPilot/ArrowPro-7B-KillerWhale
llama.cppをクローン
llama.cppをクローンします。
$ git clone https://github.com/ggerganov/llama.cpp.git
$ cd llama.cpp/
必要なものをインストール
$ pip install -r requirements.txt
モデルをGGUFにコンバート
llama.cppに含まれるconvert-hf-to-gguf.pyを使用してggufにコンバートします。
$ llama.cpp/convert-hf-to-gguf.py ArrowPro-7B-KillerWhale/
INFO:hf-to-gguf:Model successfully exported to 'ArrowPro-7B-KillerWhale/ggml-model-f16.gguf'

ArrowPro-7B-KillerWhale/ggml-model-f16.ggufに作成されました。容量は14.5GBです。
q8_0に量子化する
量子化するためにllama.cppに含まれる「llama-quantize」を使いたいのでビルドします。
$ cd ~/llama.cpp/
$ mkdir build
$ cd build
$ cmake ..
$ cmake --build . --config Release
llama-quantizeを使ってモデルをq8_0に量子化
$ cd bin/
$ ./llama-quantize ~/ArrowPro-7B-KillerWhale/ggml-model-f16.gguf ~/ArrowPro-7B-KillerWhale/arrowpro-7b-killerwhale-q8_0.gguf q8_0

モデルのサイズが14.5GB→7.7GBまで小さくなりました。
これより小さくなる量子化方式がありますが、精度悪化が酷くて使い物になりません。
q8_0がバランスが良い気がします。
ollamaで実行
modelfileを作成
$ cd ~
$ vi modelfile.txt
FROM ./ArrowPro-7B-KillerWhale/arrowpro-7b-killerwhale-q8_0.gguf
読み込み
$ ollama create killerwhale -f modelfile.txt
実行
$ ollama run killerwhale

自作のpythonでパラメーターを調整して実行:
