メむンコンテンツぞスキップ
芋出し画像

「Stable Diffusion 3 Medium ファむンチュヌニングチュヌトリアル」から読んだ Stability AIの「新モデル」

    Stability AI公匏ブログで興味深い蚘事がリリヌスされたした。

    https://ja.stability.ai/blog/stable-diffusion-3-medium-fine-tuning-tutorial

    以䞋、AICU mediaによるAI人力翻蚳、前半をかなり圧瞮し぀぀2䞇字超えでお送りしたす。

    はじめに

    こんにちはStability AI の生成メディア゜リュヌション゚ンゞニアおよびフリヌランスの 2D/3D コンセプトデザむナヌの Yeo Wang です。YouTube で私のビデオを芋たこずがあるかもしれたせんし、コミュニティGithubを通じお私を知っおいるかもしれたせん。個人的には、SD3 Medium をトレヌニングしたずきにたずもな結果が埗られたので、完党なファむンチュヌニングず LoRA トレヌニングの䞡方に぀いお、いく぀かの掞察ずクむックスタヌト構成を共有したす。

    察象読者: ファむンチュヌニングに関する基本的な知識を持぀゚ンゞニアたたは技術者

    目的: SD1.5/SDXL ず Stable Diffusion 3 Medium (SD3M) のファむンチュヌニングの違いを理解し、より倚くのナヌザヌが SD3M でファむンチュヌニングできるようにする

    SD3 のような画像を生成するこずに興味がありたすか

    3぀のプロンプトず、ベヌスモデルずファむンチュヌンモデルによる出力画像の䟋

    詳现に぀いおは、このリンクから続きをお読みください。
    たた、おたけずしお、近日公開予定の画像モデルをこっそり玹介したす🙂

    Yeo Wangさんの熱心な動画ず情報密床

    以䞊のように非垞に軜いノリで玹介された短いブログの先には、 Stability AI による膚倧な notionペヌゞがありたした。

    たた玹介されおいるKasukanraさんのチャンネルには Stable Diffusionの解説動画だけでなく、FLUX.1[dev]によるLoRAの解説動画などもありたす。

    画像

    kasukanraさんのチャンネルはむラストレヌションを題材にした話題は倚いですが、商甚キャラクタヌの暡倣や二次創䜜が倚く扱われおいるわけではないこずに泚目です。そしお非垞に情報量が倚い動画も非垞に濃密で「倍速で飛ばしおみる」ずいうより「止めおみる動画」ずいう印象です。

    notionに曞かれた情報から

    さお、notionに曞かれた情報を読み解いおいきたす。
    Ubuntu環境におけるComfyUIを䜿ったSD3のファむンチュヌニングに関する情報が、投入するコマンドから孊習レヌト、コンフィグファむルの蚭定たで现かく蚘茉されおいたす。

    【ご玹介】SDXL時代のLoRAやファむンチュヌニングに関する基瀎知識に぀いおはぜひSD黄色本「画像生成AI Stable Diffusionスタヌトガむド」をご参照ください。

    前半はUbuntuでの環境面ず「SimpleTuner」のむンストヌルですが、「カスタムコンフィグに戻る」以降の「SimpleTunerでキャプションのドロップアりト機胜を䜿うのず、シャッフルをシミュレヌトするのずでは、䜕か違いがあるのでしょうか」ずいう話題以降が読みごたえがありたす。

    In addition, there is a repeats parameter that you may or may not be familiar with depending on whether or not you’ve used other training repositories before.
    repeats duplicates your images (and optionally rotates, changes the color, etc.) and captions as well to help generalize the style into the model and prevent overfitting. While SimpleTuner supports caption dropout (randomly dropping captions a specified percentage of the time),it doesn’t support shuffling tokens (tokens are kind of like words in the caption) as of this moment, but you can simulate the behavior of kohya’s sd-scripts where you can shuffle tokens while keeping an n amount of tokens.
    If you’d like to replicate that, I’ve provided a script here that will duplicate the images and manipulate the captions:
    さらに、以前に他のトレヌニングリポゞトリを䜿ったこずがあるかどうかによっお、銎染みがあるかどうかが分かれるかもしれないrepeatsパラメヌタがありたす。repeatsは、モデルにスタむルを䞀般化し、オヌバヌフィッティングを防ぐために、画像オプションで回転、色の倉曎などずキャプションを耇補したす。SimpleTunerはキャプションのドロップアりト指定した割合でランダムにキャプションをドロップするをサポヌトしおいたすが、珟時点ではトヌクントヌクンはキャプションの単語のようなもののシャッフルはサポヌトしおいたせん

    以䞋AICU mediaが解説しながら読みやすく翻蚳したす
    ★以䞋、「私」はYeo Wangさんもしくはnotion著者の蚀ずなりたす。

    しかし、kohyaのsd-scriptsの動䜜をシミュレヌトするこずができたす。この堎合、n個のトヌクンを保持しながら、トヌクンをシャッフルするこずができたす。

    もしそれを再珟したいのであれば、画像を耇補しおキャプションを操䜜するスクリプトをここに甚意したした

    import os
    import shutil
    import random
    from pathlib import Path
    import re
    
    def duplicate_and_shuffle_dataset(input_folder, output_folder, dataset_repeats, n_tokens_to_keep):
        # Create output folder if it doesn't exist
        Path(output_folder).mkdir(parents=True, exist_ok=True)
    
        # Get all image files
        image_files = [f for f in os.listdir(input_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg'))]
    
        for i in range(dataset_repeats):
            for image_file in image_files:
                # Get corresponding text file
                text_file = os.path.splitext(image_file)[0] + '.txt'
                
                if not os.path.exists(os.path.join(input_folder, text_file)):
                    print(f"Warning: No corresponding text file found for {image_file}")
                    continue
    
                # Create new file names
                new_image_file = f"{os.path.splitext(image_file)[0]}_{i+1}{os.path.splitext(image_file)[1]}"
                new_text_file = f"{os.path.splitext(text_file)[0]}_{i+1}.txt"
    
                # Copy image file
                shutil.copy2(os.path.join(input_folder, image_file), os.path.join(output_folder, new_image_file))
    
                # Read, shuffle, and write text file
                with open(os.path.join(input_folder, text_file), 'r') as f:
                    content = f.read().strip()
    
                # Split tokens using comma or period as separator
                tokens = re.split(r'[,.]', content)
                tokens = [token.strip() for token in tokens if token.strip()]  # Remove empty tokens and strip whitespace
    
                tokens_to_keep = tokens[:n_tokens_to_keep]
                tokens_to_shuffle = tokens[n_tokens_to_keep:]
                random.shuffle(tokens_to_shuffle)
    
                new_content = ', '.join(tokens_to_keep + tokens_to_shuffle)
    
                with open(os.path.join(output_folder, new_text_file), 'w') as f:
                    f.write(new_content)
    
        print(f"Dataset duplication and shuffling complete. Output saved to {output_folder}")
    
    # Example usage
    input_folder = "/weka2/home-yeo/datasets/SDXL/full_dataset_neo"
    output_folder = "/weka2/home-yeo/datasets/SDXL/duplicate_shuffle_10_fantasy"
    dataset_repeats = 10
    n_tokens_to_keep = 2
    
    duplicate_and_shuffle_dataset(input_folder, output_folder, dataset_repeats, n_tokens_to_keep)
    画像

    ph070, A rainy urban nighttime street scene features two cars parked along the wet pavement. The primary subject is a sleek, modern silver car with streamlined curves and glistening wheels reflecting the rain-soaked road. The background includes another vehicle—a darker sedan—partially obscured. Illuminated signs with Asian characters suggest a city setting possibly in a bustling nightlife district. The style is distinctly cinematic with a futuristic, neo-noir aesthetic, characterized by moody blue tones and the reflective glow of wet surfaces. The streetlights and the occasional gleam of neon green and orange provide contrast, enhancing the dark ambiance of the city at night. The atmosphere evokes a sense of mystery and quiet anticipation, with the deserted street hinting at hidden stories or events about to unfold.

    では、SimpleTunerでキャプションのドロップアりト機胜を䜿うのず、シャッフルをシミュレヌトするのずでは、䜕か違いがあるのでしょうか

    「ファンタゞヌ・アヌト」デヌタセットの堎合、「キャプション・ドロップアりト」の方が、シャッフリングに比べお、デヌタセットのスタむルをより保぀こずができるず感じた。「Cinematic photo」デヌタセットの堎合、キャプションのドロップアりトずシャッフリングの䞡方の方法は互換性があるず感じた。䞡者に぀いお明確な結論を出すこずはできなかった。
    ずりあえず、`multibackend.json`ファむルで `repeats` の数を `10` に蚭定し、`config` でキャプションのドロップアりトを `0.25` に蚭定するこずで、`repeats` を䜿うそしおキャプションをドロップアりトするほうに傟いた。

    ★蚳泚残念ながら「datasets/SDXL/full_dataset_neo」に぀いおの提䟛はないようですが、貎重なデヌタセットに぀いおの情報がありたす。

    さらに、デヌタセットに぀いおもう少し詳しく觊れおおきたい。fantasy art` デヌタセットの堎合、解像床が `1024 x 1024` ピクセルの正方圢の画像で構成されおいる。䞀方、 `cinematic photo` デヌタセットにはあらゆる皮類のアスペクト比/解像床があった。私の `multibackend.json` ではトリミングを無効にしおいる。ある皮のヒュヌリスティックな方法(䟋えば私のdetect_utils.py)を䜿っおプリクロッピングを行うこずを匷くお勧めしたす。そうでない堎合は、`multibackend.json`のオプションの䞀぀を䜿う必芁がありたす
    ``jsx "crop_style""random|center|corner", "crop_aspect"「正方圢|保存", ```
    これらは、想定される関心領域に焊点を合わせるのが難しく、理想的ではないようだ。いずれにせよ、デフォルトの `config` でも、私のカスタム `config` でも、トリミングは `false` に蚭定されおいるので、私が気にしたこずではない。

    ステップの蚈算

    最倧孊習ステップ数は簡単な数匏で蚈算できたす単䞀コンセプトの堎合

    画像


    最倧孊習ステップ数 = サンプル数 x 繰り返し / バッチサむズx ゚ポック

    • バッチサむズ1むテレヌション繰り返しのなかで凊理されるサンプル数

    • サンプル数デヌタセット内の総サンプル数

    • 繰り返し回数䜕回1゚ポックでデヌタセットを繰り返すか

    • Epochsデヌタセット党䜓を凊理する回数

    䟋えばここで「fantasy art」デヌタセットには476枚の画像があるずしたす、ultibackend.jsonの10回の繰り返しに远加する。train_batch_size`を`6`にした。こういう蚭定の理由は2぀ありたす。

    (1)この倀なら、プログレスバヌが1秒か2秒ごずに曎新されるのを芋るこずができる。 1回の反埩で`6`のサンプルを取るこずができるずいう点で十分な倧きさであり、トレヌニングの過皋でより倚くの汎化を行うこずができる。

    もし私が30゚ポックずか欲しいなら、最終的な蚈算はこうなる

    画像

    これは倚かれ少なかれ「23,800ステップ」に盞圓したす。

    括匧の䞭の郚分「476 x10 / 6」は1゚ポックあたりのステップ数を衚し、793です。

    CHECKPOINTING_STEPS ず MAX_NUM_STEPS はそれぞれ 800 ず 24,000 に切り䞊げられたす。
    CHECKPOINTING_STEPS はモデルのチェックポむントを保存する頻床を衚したす。これを800に蚭定するず、1゚ポックにかなり近いので、問題ないず思われたす。CHECKPOINTING_LIMITは、以前のチェックポむントを䞊曞きする前に保存したいチェックポむントの数です。私の堎合、すべおのチェックポむントを保存しおおきたかったので、`30`のような高い数倀に制限を蚭定したした。

    耇数のコンセプト

    䞊蚘の䟋では、頭に1぀の統䞀的なトリガヌワヌド `k4s4` を持぀単䞀の抂念で孊習しおいたす。しかし、デヌタセットに耇数の抂念/トリガヌワヌドがある堎合、ステップの蚈算は以䞋のようになりたす

    2コンセプトの堎合、ステップの蚈算匏は以䞋のようになりたす。

    画像

    iコンセプトの堎合

    画像

    最埌に孊習率ですが、これ以䞊高くするず募配が爆発しおしたうので「1.5e-5」ずしおいたす。

    画像

    これで重芁な蚭定はほずんどカバヌできる。
    ★蚳泚質を高めるために倉曎できる远加蚭定がいく぀かありたすので、カスタム蚭定をご参照ください。

    怜蚌画像を生成する頻床は VALIDATION_STEPS で蚭定する。私は800私のデヌタセットの゚ポックのステップ数の1/4である200に蚭定した。぀たり、1/4゚ポックごずに怜蚌画像を生成するこずになる。正気床をチェック(sanity check)するために、少なくずも半分の゚ポックごずに怜蚌画像を生成するこずをお勧めする。そうしないず、゚ラヌを玠早く発芋できないかもしれない。

    LR_SCHEDULEずLR_WARMUP_STEPS

    最埌に`LR_SCHEDULE`ず`LR_WARMUP_STEPS`、
    この堎合は`cosine`スケゞュヌルで行いたしたが、こんな感じになりたす。

    画像
    画像

    SimpleTunerはデフォルトのりォヌムアップを党トレヌニングステップの10に蚭定しおいる。ここは倉曎しない。

    ★蚳泚Custom SD3 full config.env に぀いおも公開されおいたす。

    実際にトレヌニングを開始する

    これで `config.env` ず `multibackend.json` が適切にセットアップされたので、いよいよトレヌニングを実行する。これはルヌトディレクトリで

    bash train.sh

    で実行したす。

    蚈算胜力に関する考察

    䞊蚘の実隓はクラりドコンピュヌティングを䜿っお行いたしたが、私が提䟛した`config.env`は、24GBのVRAM GPU`RTX 4090`を䜿った私の個人的なマシンにおかろうじお可胜です。

    画像
    画像

    モデルをどうするか

    デフォルトでは、トレヌニングが完了するず、以䞋のようなフォルダ構造になりたす。

    画像

    ここで理解しおおくべきこずがいく぀かありたす。

    1. datasets/models`内の各`checkpoint`ディレクトリにある`diffusion_pytorch_model.safetensors`ファむルが必芁です。このファむルの堎所は、transformerディレクトリの䞭です。芋おの通り、これはかなり耇雑です。最終的なパスは次のようになりたす weka2/home-yeo/simpletuner_models/ninth_run/datasets/models/checkpoint-2400/transformer/diffusion_pytorch_model.safetensors` .

    2. diffusion_pytorch_model.safetensors`ファむルは、`ComfyUI`の`Load Checkpoint`ノヌド内で䜿甚するず動䜜したせん。UNETロヌダヌ`を䜿甚するか、新しいバヌゞョンの`ComfyUI`では、`Load Diffusion Model`ノヌドを䜿甚する必芁がありたす。そのため、これらのモデルを `ComfyUI` の models ディレクトリ内の `unet` ディレクトリにコピヌする必芁がありたす admin/home-yeo/workspace/ComfyUI/models/unet`のようにしたす。

    これらのモデルを必芁な堎所に配眮するプロセスを効率化するために、`source`ず`target`ディレクトリの䞡方を指定するず、私が曞いたシェルスクリプトがこれをやっおくれたす。

    SOURCE_DIR` ず `TARGET_DIR` を眮き換えお、モデルを `unet` フォルダに `symlink` したす。

    #!/bin/bash
    
    # Source directory where the models are stored
    SOURCE_DIR="/admin/home-yeo/workspace/simpletuner_models/sd3_medium/full_finetune/cinema_photo/03/datasets/models"
    
    # Target directory for symlinks
    TARGET_DIR="/admin/home-yeo/workspace/ComfyUI/models/unet/simpletuner_blog_cine_photo_03"
    
    # Iterate over each checkpoint directory
    for CHECKPOINT_DIR in $(ls -d ${SOURCE_DIR}/checkpoint-*); do
        # Extract the checkpoint number from the directory name
        CHECKPOINT_NAME=$(basename ${CHECKPOINT_DIR})
        
        # Define the source file path
        SOURCE_FILE="${CHECKPOINT_DIR}/transformer/diffusion_pytorch_model.safetensors"
        
        # Define the symlink name
        LINK_NAME="${TARGET_DIR}/${CHECKPOINT_NAME}.safetensors"
        
        # Check if the source file exists
        if [ -f "${SOURCE_FILE}" ]; then
            # Create a symlink in the target directory
            ln -s "${SOURCE_FILE}" "${LINK_NAME}"
            echo "Symlink created for ${CHECKPOINT_NAME}"
        else
            echo "File not found: ${SOURCE_FILE}"
        fi
    done
    
    echo "Symlinking complete."

    ベストチェックポむントの決定

    最適なチェックポむントを決定する方法は、特定のプロンプトのチェックポむント番号をX軞にプロットする。぀たりこんなかんじ。

    画像
    画像
    画像
    画像

    これを行うために、私はComfyUIワヌクフロヌのAPIバヌゞョンをロヌドするカスタムスクリプトを䜿甚しおいたす。保存(API圢匏)ボタンをクリックすれば、どんなワヌクフロヌでもAPI圢匏で保存できる。私はすでにあなたの䜿甚のために䞊のバヌゞョンを保存したした。もしComfyUI APIの䜿い方に぀いおもっず詳しいビデオガむドが必芁であれば、昚幎䜜った動画がここにありたす。

    https://youtu.be/WwsJ_QIgsG8

    ComfyUIが起動しおいるこずを確認しおから、以䞋のスクリプトを実行する。たた、スクリプトを実行する堎所ず同じ堎所に`.env`ファむルをセットアップする必芁がありたす。

    import os
    import json
    import random
    from urllib import request
    import datetime
    from PIL import Image, ImageDraw, ImageFont
    import time
    import re
    import urllib.error
    
    from dotenv import load_dotenv
    load_dotenv()
    
    # Configuration
    api_workflow_dir = os.getenv("API_WORKFLOW_DIR")
    finetune_dir = os.getenv("FINETUNE_DIR")
    
    api_workflow_file = os.getenv("API_WORKFLOW_FILE")
    api_endpoint = os.getenv("API_ENDPOINT")
    image_output_dir = os.getenv("IMAGE_OUTPUT_DIR")
    font_ttf_path = os.getenv("FONT_TTF_PATH")
    
    comfyui_output_dir = os.getenv("COMFYUI_OUTPUT_DIR")
    
    api_endpoint = f"http://{api_endpoint}/prompt"
    
    workflow_file_path = os.path.join(api_workflow_dir, api_workflow_file)
    workflow = json.load(open(workflow_file_path))
    
    current_datetime = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    relative_output_path = current_datetime
    
    directory_creation_timeout = 3000  # Timeout for directory creation in seconds
    image_generation_timeout = 30000  # Timeout for image generation in seconds
    
    def get_checkpoint_number(filename):
        match = re.search(r'checkpoint-(\d+)', filename)
        if match:
            return int(match.group(1))
        match = re.search(r'/checkpoint-(\d+)/', filename)
        if match:
            return int(match.group(1))
        return None
    
    def get_most_recent_output_folder(base_dir):
        folders = [f for f in os.listdir(base_dir) if os.path.isdir(os.path.join(base_dir, f))]
        if not folders:
            return None
        return max(folders, key=lambda f: os.path.getctime(os.path.join(base_dir, f)))
    
    def process_safetensors(safetensor_dir, workflow):
        print(f"Scanning directory: {safetensor_dir}")
        
        last_dir = os.path.basename(os.path.normpath(safetensor_dir))
        
        all_items = os.listdir(safetensor_dir)
        
        safetensor_items = [f for f in all_items if f.endswith('.safetensors')]
        
        safetensor_items.sort(key=lambda x: int(x.split('-')[1].split('.')[0]))
        
        print(f"Found items: {safetensor_items}")
        
        for item in safetensor_items:
            unet_name = f"{last_dir}/{item}"
            
            print(f"Processing: {unet_name}")
    
            unet_loader_node = workflow["273"]
            unet_loader_node["inputs"]["unet_name"] = unet_name
    
            checkpoint_num = item.split('-')[1].split('.')[0]
            
            save_image = workflow["275"]
            filename_prefix = f"checkpoint-{checkpoint_num}"
            save_image["inputs"]["output_path"] = relative_output_path
            save_image["inputs"]["filename_prefix"] = filename_prefix
    
            success = queue_prompt(workflow)
            if not success:
                print(f"Failed to queue prompt for checkpoint {checkpoint_num}")
            else:
                print(f"Successfully queued prompt for checkpoint {checkpoint_num}")
    
        if not safetensor_items:
            print("No .safetensors files found in the directory.")
        
        return len(safetensor_items)
    
    def create_image_strip(safetensor_dir, image_folder, output_filename):
        safetensor_files = [f for f in os.listdir(safetensor_dir) if f.endswith('.safetensors')]
        safetensor_files.sort(key=get_checkpoint_number)
        checkpoints = [get_checkpoint_number(f) for f in safetensor_files if get_checkpoint_number(f) is not None]
    
        images = []
        for checkpoint in checkpoints:
            filename = f"checkpoint-{checkpoint}_0001.png"
            filepath = os.path.join(image_folder, filename)
            if os.path.exists(filepath):
                try:
                    img = Image.open(filepath)
                    images.append(img)
                except IOError as e:
                    print(f"Cannot open image: {filepath}")
                    print(f"Error: {e}")
    
        if not images:
            print("No valid images found.")
            return
    
        img_width, img_height = images[0].size
        strip_width = img_width * len(images)
        label_height = 50  # Space for labels
        strip_height = img_height + label_height
    
        strip_image = Image.new('RGB', (strip_width, strip_height), 'white')
        draw = ImageDraw.Draw(strip_image)
        font = ImageFont.truetype(font_ttf_path, 20)
    
        for i, (img, checkpoint) in enumerate(zip(images, checkpoints)):
            strip_image.paste(img, (i * img_width, label_height))
            
            label = f"checkpoint-{checkpoint}"
            label_width = draw.textlength(label, font=font)
            label_x = i * img_width + (img_width - label_width) // 2
            draw.text((label_x, 10), label, fill="black", font=font)
    
        strip_image.save(output_filename)
        print(f"Image strip saved to: {output_filename}")
    
    def queue_prompt(workflow):
        p = {"prompt": workflow}
        data = json.dumps(p).encode('utf-8')
        req = request.Request(api_endpoint, data=data, headers={'Content-Type': 'application/json'})
        try:
            with request.urlopen(req) as response:
                print(f"API request successful. Status code: {response.getcode()}")
                return True
        except urllib.error.URLError as e:
            if hasattr(e, 'reason'):
                print(f"Failed to reach the server. Reason: {e.reason}")
            elif hasattr(e, 'code'):
                print(f"The server couldn't fulfill the request. Error code: {e.code}")
            print(f"API endpoint: {api_endpoint}")
        except Exception as e:
            print(f"An error occurred: {str(e)}")
        return False
    
    def wait_for_directory_creation(directory, timeout):
        print(f"Waiting for directory {directory} to be created...")
        start_time = time.time()
        while time.time() - start_time < timeout:
            if os.path.exists(directory):
                print(f"Directory {directory} found.")
                return True
            time.sleep(5)  # Check every 5 seconds
        print(f"Timeout waiting for directory {directory} to be created.")
        return False
    
    def wait_for_images(image_folder, expected_count, timeout):
        print("Waiting for images to be generated...")
        start_time = time.time()
        while time.time() - start_time < timeout:
            if os.path.exists(image_folder):
                image_files = [f for f in os.listdir(image_folder) if f.endswith('.png')]
                if len(image_files) >= expected_count:
                    print(f"Found all {expected_count} images.")
                    return True
            time.sleep(5)  # Check every 5 seconds
        print("Timeout waiting for images to be generated.")
        return False
    
    if __name__ == "__main__":
        safetensor_dir = finetune_dir 
        print(f"Finetune directory: {safetensor_dir}")
    
        # Generate images
        expected_image_count = process_safetensors(safetensor_dir, workflow)
    
        absolute_output_path = os.path.join(comfyui_output_dir, current_datetime)
        print(f"Absolute output path: {absolute_output_path}")
    
        # Create the image strip
        if wait_for_directory_creation(absolute_output_path, directory_creation_timeout):
            print(f"Expected image count: {expected_image_count}")
            if wait_for_images(absolute_output_path, expected_image_count, image_generation_timeout):
                output_strip_filename = os.path.join(absolute_output_path, "output_image_strip.png")
                create_image_strip(safetensor_dir, absolute_output_path, output_strip_filename)
            else:
                print("Failed to generate all images in time.")
        else:
            print("Output directory was not created.")
    • サンプルの .env ファむル

    API_WORKFLOW_DIR=/weka2/home-yeo/workflows
    COMFYUI_OUTPUT_DIR = /weka2/home-yeo/ComfyUI/output/
    FINETUNE_DIR=/admin/home-yeo/workspace/ComfyUI/models/unet/simpletuner_09
    API_WORKFLOW_FILE=SD3_SINGLE_BASIC_API_02.json
    API_ENDPOINT=127.0.0.1:8188
    FONT_TTF_PATH=/weka2/home-yeo/fonts/arial.ttf
    BOLD_FONT_TTF_PATH=/weka2/home-yeo/fonts/arialbd.ttf

    結局、私は終了間際のステップ`20,800`でチェックポむントを遞びたした。

    ギャラリヌ

    最埌にいく぀か䟋を挙げおいきたす。

    画像
    画像
    画像
    画像
    画像

    LoRA のトレヌニング

    より軜量なLoRAのトレヌニングを詊したい堎合、これは私が䜿ったconfigで、たあたあの結果が埗られたした。完党な埮調敎の方が品質的には良いようです。LoRAの rank ず alpha は export TRAINER_EXTRA_ARGS 内で蚭定できたす。
    ★蚳泚カスタムSD3 LoRA `config.env`をご参照ください

    近日発衚予定のモデルのチラ芋せ

    詳现はただお䌝えできたせんが、近日発衚予定のモデルの出力のスニヌクピヌクチラ芋せです

    a close up three fourth perspective portrait view of a young woman with dark hair and dark blue eyes, looking upwards and to the left, head tilted slightly downwards and to the left, exposed forehead, wearing a nun habit with white lining, wearing a white collared shirt, barely visible ear, cropped, a dark brown background
    黒髪で濃い青の瞳をした若い女性のクロヌズアップ䞉四透芖図。䞊を芋お巊を向き、頭はやや䞋向きで巊に傟いおおり、額は露出しおいたす。癜い裏地の぀いた修道服に身を包み、癜い襟付きシャツを着おおり、耳はかろうじお芋えおいたす。

    画像

    a front wide view of a small cyberpunk city with futuristic skyscrapers with gold rooftops situated on the side of a cliff overlooking an ocean, day time view with green tones, some boats floating in the foreground on top of reflective orange water, large mechanical robot structure reaching high above the clouds in the far background, atmospheric perspective, teal sky
    海を芋䞋ろす厖の䞭腹に建぀、金色の屋根を持぀近未来的な高局ビルが建ち䞊ぶ小さなサむバヌパンク郜垂の正面からのワむドビュヌ、緑を基調ずした日䞭の眺め、反射するオレンゞ色の氎の䞊に浮かぶ手前のいく぀かのボヌト、遠景の雲の䞊たで届く倧きな機械仕掛けのロボット構造、倧気遠近法、ティヌル色の空

    画像

    a medium view of a city square alongside a river, two large red boats in the foreground with cargo on them, two people in a smaller boat in the bottom right cruising along, reflective dark yellow water in the river, a congregation of people walking along the street parallel to the river in the midground, a dark white palazzo building with dark white tower on the right with red tones, golden hour, red and yellow flag in the top left foreground, light blue flag with yellow accents in the right midground, aerial perspective
    川沿いの広堎の䞭景、前景に荷を茉せた2隻の赀い倧型ボヌト、右䞋の小さなボヌトに乗った2人のクルヌゞング、反射する濃い黄色の川の氎、䞭景に川ず平行する通りを歩く人々、右手に赀を基調ずした濃い癜の塔を持぀濃い癜のパラッツォの建物、ゎヌルデンタむム、巊䞊の前景に赀ず黄色の旗、右の䞭景に黄色のアクセントのある氎色の旗、空からの芖点。

    画像

    近日公開予定のモデルのスニヌクピヌク ただあたり倚くの詳现はお䌝えできたせんが、近日公開予定のモデルの1人からの出力のスニヌクピヌクです黒髪でダヌクブルヌの目をした若い女性のクロヌズアップ3/4遠近法のポヌトレヌトビュヌ、䞊向きで巊を向き、頭はやや䞋向きで巊に傟いおおり、額が露出しおいたす、癜い裏地の付いた修道女の習慣を身に着け、癜い襟付きシャツを着おおり、かろうじお耳が芋えおいたす、トリミング枈み、ダヌクブラりンの背景。

    おたけ: オヌトキャプション

    デヌタセットが準備できれば、䞊蚘の手順でモデルのファむンチュヌニングを始めるこずができたすが、結果はデヌタセットによっお倧きく異なりたす。正しくキャプションが付けられた画像を芋぀けるのは、かなり難しいこずです。手䜜業でキャプションを぀けるのは、かなり面倒で、ミスが起こりやすい䜜業です。ですから、䜕らかの圢で自動化された゜リュヌションを詊しおみるのは理にかなっおいたす。

    実際、SD3自身も、キャプションを生成するための事前孊習でCogVLM(ビゞョン蚀語モデル)を䜿甚したした。しかし、このモデルを正しく䜿甚するには、倚くのVRAM、倧芏暡なデヌタセット、耇雑なワヌクフロヌが必芁です。そこで、このブログポストでは、小芏暡なコミュニティの埮調敎にもう少し適したものに焊点を圓おたすJoyCaptionです。JoyCaptionは、新しいモデルの埮調敎を行うために、コミュニティのメンバヌによっお開発された積極的なキャプションモデルです。

    アクセシブルなキャプション・むンタヌフェヌスで動かすには、TagGUIを䜿いたす。このペヌゞの指瀺に埓うこずで、GUIをむンストヌルし、画像を凊理する準備ができたす。ただし、いく぀か重芁なポむントがありたすオヌトキャプションはただ完党ではないので、自動的な解決策によっお、画像の䞀郚が適切にキャプション付けされおいないこずに気づくかもしれたせん。このようなミスや問題は、倚くのデヌタを持っおいれば倚少はかき消すこずができたすが、ほずんどの趣味人にずっおは難しいこずでしょう。この堎合、䜕が間違っおいるのかを理解し、それを反埩するために、キャプションを手動で怜査する必芁があるかもしれない。芚えおおいおほしいのは、䞍正確なキャプションでトレヌニングしおも、迅速な遵守は期埅できないので、この蚭定に費やす時間は非垞に貎重だずいうこずです。ここでの反埩時間を短瞮するために、完党な埮調敎の前に、デヌタを䜿っおいく぀かのLoRAを蚓緎するずよいでしょう。頑匵っおください

    kasukanra@GitHubリポゞトリ

    たくさんのツヌルが眮かれおいたす。

    原䜜をご提䟛いただいたYeo Wangさん、ありがずうございたした


     
     

    AICU

     
     
    生成AI時代に「぀くる人を぀くる」をビゞョンに掻動する日本最倧のクリ゚むティブAIコミュニティ。 AIクリ゚むタヌさんずずもに、「わかるAI」を䌝えおいきたす。

    あなたぞのおすすめ