0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LoRAモデルのマージとGGUF量子化手順

0
Posted at

LoRAモデルのマージとGGUF量子化手順

はじめに

備忘もかねて、
ファインチューニングで作成した LoRA アダプターをベースモデルにマージし、
LM-Studio 上で実行できるように GGUF 形式へ変換・量子化する手順を紹介する。


使用環境・ライブラリ


手順

1. ベースモデルと LoRA のマージ

ベースモデルを読み込み、PeftModel として LoRA アダプターを適用したのち、
merge_and_unload() でマージ、
マージしたモデルとトークナイザーを保存する。

from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer

# パス
base_path = "meta-llama/Llama-3.2-1B-Instruct" #ベースモデルパス(LoRAアダプターのconfig.jsonのbase_model_name_or_pathの値をそのまま記載)
adapter_path = /path/to/your/LoRA-adapter #LoRAアダプターパス(config.jsonが入っているフォルダを指定)

# マージ
base_model = AutoModelForCausalLM.from_pretrained(base_path)
model = PeftModel.from_pretrained(base_model, adapter_path)
merged_model = model.merge_and_unload()

# 保存
merged_model.save_pretrained("merged-model/")
tokenizer = AutoTokenizer.from_pretrained(base_path, use_fast=False)
tokenizer.save_pretrained("merged-model/")

2. llama.cpp の取得

GGUF 形式への変換には llama.cpp を使用する。以下のコマンドでリポジトリを取得し、必要なパッケージをインストールする。

git clone https://github.com/ggml-org/llama.cpp.git
cd llama.cpp
pip install -r requirements.txt

6. 量子化ツールのビルド

量子化ツール(llama-quantize)を、以下のコマンドでビルドする。

cmake -B build
cmake --build build --config Release

7. GGUF 形式への変換

convert_hf_to_gguf.py を使用し、マージ済みモデルを GGUF 形式(f16)に変換する。

python convert_hf_to_gguf.py \
  path/to/your/merged-model \
  --outfile merged-model.gguf \
  --outtype f16

8. 量子化

変換した GGUF ファイルを今回は Q4_K_M 形式に量子化する。

./build/bin/llama-quantize merged-model-model.gguf merged-model-Q4_K_M.gguf Q4_K_M

まとめ

以上の手順により、LoRA でファインチューニングしたモデルをベースモデルにマージし、
LM-Studio で実行可能な GGUF 形式(Q4_K_M 量子化)に変換することができる。

作成したファイルは LM-Studio に配置し、モデルを選択することで実行可能となる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?