🚤

Deepspeed & Google Colab で Phi-3.5-vision をFine tuningする。

2025/02/13に公開

DeepspeedでPhi-3.5-visionをFine tuningするコードベースが以下にあります。

https://github.com/2U1/Phi3-Vision-Finetune

本記事では、こちらの使い勝手を調整したものを共有します。
細かいコード差分は本記事では紹介しません。それらはコミット履歴をご参照ください。

https://github.com/akutsu-kei/Phi3-Vision-Finetune-Colab

調整点

  • 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

以下のデータセットの一部を使用します。

https://huggingface.co/datasets/flaviagiammarino/vqa-rad

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

https://github.com/akutsu-kei/Phi3-Vision-Finetune/blob/main/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を変更して学習層を決めている感じです。

https://github.com/akutsu-kei/Phi3-Vision-Finetune/blob/main/src/training/train.py#L57

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