colab 上接續訓練的步驟

如果要接續訓練(Resume Training),你需要確保以下幾點:

  1. 之前訓練的權重檔已儲存(通常會在 OUTPUT_DIR 內)。
  2. 載入最新的 checkpoint(上次訓練時的最後一步)。
  3. 繼續 Trainer 訓練,而不是從頭開始

🔹 接續訓練的完整步驟

1️⃣ 掛載 Google Drive 並確認已訓練的模型

from google.colab import drive
import os

drive.mount('/content/drive')

# 設定 Google Drive 內的數據集與輸出目錄
OUTPUT_DIR = "/content/drive/MyDrive/AI/output/zenmaru_finetune"

# 檢查上次訓練的 checkpoint 是否存在
checkpoint_path = os.path.join(OUTPUT_DIR, "checkpoint-last")

if os.path.exists(checkpoint_path):
    print(f"✅ 找到上次訓練的 checkpoint: {checkpoint_path}")
else:
    print("❌ 沒有找到 checkpoint,請確認上次訓練是否有儲存!")

2️⃣ 重新載入 Stable Diffusion 2.1 模型

from diffusers import StableDiffusionPipeline, UNet2DConditionModel

PRETRAINED_MODEL_NAME = "stabilityai/stable-diffusion-2-1"

# 載入上次訓練的 checkpoint,而不是從頭開始
unet = UNet2DConditionModel.from_pretrained(
    checkpoint_path,  # 這裡載入上次訓練的 checkpoint
    torch_dtype=torch.float16
).to("cuda")

3️⃣ 設定接續訓練的參數

from transformers import TrainingArguments, Trainer
from datasets import load_dataset

# 設定訓練參數
training_args = TrainingArguments(
    output_dir=OUTPUT_DIR,  # 繼續存放到同一個目錄
    per_device_train_batch_size=1,
    gradient_accumulation_steps=4,  
    learning_rate=5e-6,
    max_steps=20000,  # 這裡設定新總步數(包括上次訓練的步數)
    save_strategy="steps",
    save_steps=1000,
    resume_from_checkpoint=True  # ✅ 啟用接續訓練
)

# 重新載入數據集
DATASET_DIR = "/content/drive/MyDrive/AI/datasets/zenmaru_dataset"
dataset = load_dataset("imagefolder", data_dir=DATASET_DIR, split="train")

# 設定 Trainer
trainer = Trainer(
    model=unet,
    args=training_args,
    train_dataset=dataset
)

4️⃣ 繼續訓練

trainer.train(resume_from_checkpoint=True)  # ✅ 這行確保會從 checkpoint 繼續訓練

🔹 確保訓練結果不會遺失

建議在 Google Drive 上手動檢查 /AI/output/zenmaru_finetune 內是否有:

  • checkpoint-last/ 目錄(裡面有 .bin.json 檔案)。
  • pytorch_model.bin.safetensors(訓練後的模型)。

如果你想手動儲存最新的模型:

trainer.save_model(OUTPUT_DIR)

🔹 總結

  • 載入上次訓練的 checkpoint(確保 checkpoint-last 存在)。
  • 設定 resume_from_checkpoint=True 讓訓練從中斷的地方繼續。
  • 開始訓練 trainer.train(resume_from_checkpoint=True)

這樣就能在 Colab 繼續 Fine-tuning 了!🚀
你上次訓練到幾步呢? 😃

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *