Deepspeed & Google Colab で Phi-3.5-vision をFine tuningする。
DeepspeedでPhi-3.5-visionをFine tuningするコードベースが以下にあります。
本記事では、こちらの使い勝手を調整したものを共有します。
細かいコード差分は本記事では紹介しません。それらはコミット履歴をご参照ください。
調整点
- Colabで動作できるようにライブラリ・コードベースの調整
- HF load_dataset() specデータセットを、Llava spec データセットにするスニペット追加
その他を注意点を本記事に記載しています。
Getting started
Clone
git clone https://github.com/akutsu-kei/Phi3-Vision-Finetune-Colab.git
Install dependency
cd Phi3-Vision-Finetune
pip install -r requirements_colab.txt
pip install flash-attn --no-build-isolation
pip install --upgrade huggingface_hub datasets
Create dataset
以下のデータセットの一部を使用します。
Fork元リポジトリの作法に従って、LLaVA Specに変換します。
cd Phi3-Vision-Finetune
python3 create_brain-vqa-rad.py
出力はPhi3-Vision-Finetune/brain-vqa-rad
ディレクトリです。
Fine tuning by Lora
Fine tuningを実行します。今回はDecoder層のみを対象にFine tuningを実行します。
cd Phi3-Vision-Finetune
bash scripts/finetune_lora.sh
Adapterの重みは、Phi3-Vision-Finetune/output/train_vqa_rad_llava_lora/runs/Feb13_11-24-15_hoge
へ保存されます。
また、finetune_lora_vision.sh
を使用することでEncoder層のFine tuningも可能です。
VRAM消費量
per_device_train_batch_size 3, gradient_accumulation_steps 3に対してVRAM消費量は以下の通りです。
Fine tuningの設定項目
scripts/finetune_lora.sh
の引数について、重要なものは以下のあたりかと思います。これらで学習層を決定しています。
lora_enable, tune_img_projector, freeze_vision_tower, freeze_llm
lora_enable
を有効にする場合には、freeze_llm
をする必要があるなど設定制約がありますが、色々といじってみると面白いかもしません。
内部動作としては、以下の辺りでpytorchのmodel
インスタンスに対して、1つ1つrequires_grad
を変更して学習層を決めている感じです。
def configure_llm(model, training_args):
lm_head_params = model.lm_head.parameters()
set_requires_grad(lm_head_params, not training_args.freeze_llm)
embed_token_params = model.model.embed_tokens.parameters()
set_requires_grad(embed_token_params, not training_args.freeze_llm)
for name, param in model.model.named_parameters():
if name.startswith('layers') or name.startswith('norm'):
param.requires_grad = not training_args.freeze_llm
他方、output_dir
には、lora
という文字列を入れる必要がある実装になっています。
ハマりました。意図は不明です。
Merge tuned weight
Adapterの重みをPhi-3.5-visionの本体と結合します。
cd Phi3-Vision-Finetune
bash scripts/merge_lora.sh
出力ディレクトリはPhi3-Vision-Finetune/output/train_vqa_rad_llava_lora_merged
です。
このディレクトリをAutoModelForCausalLM.from_pretrained
から呼び出すことで、Fine tuning版モデルを動作させることが可能です。
寝言
最近、A100のハイメモリが全然引けない気がする。。
Discussion