Replicate ファインチューニングチュートリアル

このノートブックでは、Replicate の API を使用して画像モデル(FLUX.1、SDXL)をファインチューニングする手順を説明します。以下を行います。

  • .env から API キーを安全に読み込む
  • トレーニングデータ(画像の zip)を準備する
  • Python クライアント経由でファインチューニングジョブを開始する
  • トレーニングの進捗を監視し、サンプルを生成する

核心コンセプト:

  • ファインチューニングを使用すると、わずか数枚の画像(FLUX.1 の場合 2〜10 枚)で、事前学習済み画像生成モデルを新しい被写体やスタイルに適応させることができます
  • Replicate は API と Web を介して FLUX.1 と SDXL をサポートします。FLUX.1 は LoRA(軽量、高速、パラメーター効率が良い)を使用します
  • トレーニングパイプラインには前処理が含まれます(SDXL の場合は SwinIR、BLIP、CLIPSeg など)
import os
from dotenv import load_dotenv
import replicate

# Load API key
load_dotenv()
REPLICATE_API_TOKEN = os.getenv("REPLICATE_API_TOKEN")
assert REPLICATE_API_TOKEN, "Set REPLICATE_API_TOKEN in .env file"
replicate_client = replicate.Client(api_token=REPLICATE_API_TOKEN)

1. トレーニングデータの準備

  • 被写体/スタイルを表す 5〜20 枚の画像を収集します(高品質で、さまざまな角度と照明)
  • zip 圧縮します: zip -r training_images.zip your_folder/
# Example: Ensure training_images.zip exists
ZIP_PATH = "training_images.zip"
assert os.path.isfile(ZIP_PATH), f"Place your zip at {ZIP_PATH}"

2. FLUX.1 ファインチューニングの開始

Replicate API を介して LoRA を使用します。

  • trigger_word(意味のない単語または固有のトークン)を選択または作成します。
  • トレーニングジョブを開始します。
try:
    # Try to get current user info through endpoint
    import requests
    headers = {"Authorization": f"Token {REPLICATE_API_TOKEN}"}
    response = requests.get("https://api.replicate.com/v1/account", headers=headers)
    if response.status_code == 200:
        user_data = response.json()
        username = user_data.get("username", user_data.get("name"))
    else:
        print(f"\n API request failed with status: {response.status_code}")
        username = "your_username"  # Set a fallback username
except Exception as e:
    print(f"Error: {e}")
    username = "your_username"  # Set a fallback username

# Set up destination name with your username
flux_destination = f"{username}/flux-my-finetune-v2"

print(f"\n📋 FLUX destination will be: {flux_destination}")
📋 FLUX destination will be: devonsunml/flux-my-finetune-v2
# Create the destination model first if it doesn't exist
try:
    print(f"Creating model: {flux_destination}")
    model = replicate_client.models.create(
        owner=username,
        name="flux-my-finetune-v2",
        visibility="private",
        description="Fine-tuned FLUX model",
        hardware="gpu-t4" 
    )
    print(f"✅ Model created: {model.name}")
except Exception as e:
    print(f"Error: {e}")

独自のデータセットでモデルをファインチューニングする

try:
    training = replicate_client.trainings.create(
        version="replicate/fast-flux-trainer:f463fbfc97389e10a2f443a8a84b6953b1058eafbf0c9af4d84457ff07cb04db",
        input={
            "input_images": open(ZIP_PATH, "rb"), 
            "trigger_word": "MYTOK",
            "steps": 1000
        },
        destination=flux_destination
    )
    print("✅ Training started successfully!")
    print("Training ID:", training.id)
    print("You can monitor training at:", training.urls.get)
    
except Exception as e:
    print(f"Error {e}")
✅ Training started successfully!
Training ID: 7v0r4sswjxrm80crhmd92axe2m
You can monitor training at: <built-in method get of dict object at 0x117a1a9c0>

3. 進捗の監視とサンプルの生成

training.status または training.logs を使用して監視します。完了後、ファインチューニング済みモデルを他の Replicate モデルと同様に呼び出します。

# Polling loop (example)
import time

# Store training job
training_jobs = []
if 'training' in locals():
    training_jobs.append(training)

for job in training_jobs:
    print(f"Polling {job.id}...")
    while True:
        job = replicate_client.trainings.get(job.id)
        print(f"Status: {job.status}")
        if job.status in ["succeeded", "failed", "canceled"]:
            break
        time.sleep(30)  # Check every 30 seconds
    print(f"Job {job.id} finished with status {job.status}")
    
    if job.status == "succeeded":
        print(f"Training completed! View results at: {job.urls.get}")
        print("Note: To use the trained model, you'll need to:")
        print("1. Go to the training URL above")
        print("2. Create a model from the training results")
        print("3. Use the new model ID for generation")
    else:
        print(f"Training failed or was canceled")
Polling 7v0r4sswjxrm80crhmd92axe2m...
Status: succeeded
Job 7v0r4sswjxrm80crhmd92axe2m finished with status succeeded
Training completed! View results at: <built-in method get of dict object at 0x117a1f800>
Note: To use the trained model, you'll need to:
1. Go to the training URL above
2. Create a model from the training results
3. Use the new model ID for generation
# Generate an image of yourself wearing a space suit using your fine-tuned model
prompt = "A realistic photo of Devon wearing a space suit on Mars, cinematic lighting, astronaut helmet, NASA patch, high detail"
output = replicate.run(
    "devonsunml/flux-my-finetune-v2:1c68fbecae650b8a0dd9e4ea7f38f9c18cba1b9fc4af1077d0a0c9fe403db98a",
    input={
        "prompt": prompt,
        "model": "dev",
        "go_fast": False,
        "lora_scale": 1,
        "megapixels": "1",
        "num_outputs": 1,
        "aspect_ratio": "1:1",
        "output_format": "webp",
        "guidance_scale": 3,
        "output_quality": 80,
        "prompt_strength": 0.8,
        "extra_lora_scale": 1,
        "num_inference_steps": 28
    }
)

# To access the file URL:
img_url = output[0]
print("Image URL:", img_url)

import requests
from IPython.display import Image, display
img_data = requests.get(img_url).content
display(Image(data=img_data, width=512, height=512))
Image URL: https://replicate.delivery/xezq/dd4p70uV5X4TL1mJCmFyPdcr5MLlUZzYOzbwYOIf7vwuJkkKA/out-0.webp
<IPython.core.display.Image object>

4. ヒントと次のステップ

  • 誤った発動を避けるために、一般的でないトリガーワードを選択してください。
  • 必要に応じて steps、batch size、resolution を調整してください。
  • ファインチューニング済みモデルは起動が速く(コールドスタート 1 秒未満)、複数のファインチューン間でスタイルや被写体を混ぜて試すこともできます。

クリエイティブなモデルのファインチューニングをお楽しみください!