{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [] }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "source": [ "#**PLAYGROUND V2.5 LORA CREATOR - Adapted from SD XL Lora training by linoytsaban*" ], "metadata": { "id": "RvbNnswz1Bwy" } }, { "cell_type": "markdown", "source": [ "# Install necessary libs." ], "metadata": { "id": "Pxl1NJ4ew_22" } }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "krdOGpbewX6D" }, "outputs": [], "source": [ "!pip install huggingface_hub datasets pillow xformers bitsandbytes transformers accelerate wandb dadaptation prodigyopt torch -q\n" ] }, { "cell_type": "code", "source": [ "!pip install peft -q" ], "metadata": { "id": "LmsPVnS8xpWB" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "!pip install git+https://github.com/huggingface/diffusers.git -q" ], "metadata": { "id": "yAKkbjNsxp4n" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "Downloading the script!" ], "metadata": { "id": "gYT0P8sMxtOE" } }, { "cell_type": "code", "source": [ "!wget https://raw.githubusercontent.com/huggingface/diffusers/main/examples/advanced_diffusion_training/train_dreambooth_lora_sdxl_advanced.py" ], "metadata": { "id": "ehtWgVcdxwJT" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "!wget https://gist.githubusercontent.com/artificialguybr/a1c58ad578d0446d493c9793093196e1/raw/b8cede5d9ad5f9911de70ac187c6b078eea693c8/sd-dataset-to-hf-dataset.py" ], "metadata": { "id": "rvrh-vLexwlI" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "!accelerate config default" ], "metadata": { "id": "cepNwXbXyBa-" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "Login with your HuggingFace Account!" ], "metadata": { "id": "PTJdDX4AxE2m" } }, { "cell_type": "code", "source": [ "from huggingface_hub import notebook_login\n", "notebook_login()" ], "metadata": { "id": "nKtKBrgVxGpb" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "Convert your currently SD XL (Kohya) style Dataset to HF Dataset." ], "metadata": { "id": "HLDTiVlJyI4g" } }, { "cell_type": "code", "source": [ "# Required imports\n", "import os\n", "from huggingface_hub import HfApi, login\n", "from datasets import Dataset, Features, Value, Image\n", "from PIL import Image as PILImage\n", "import io\n", "\n", "## Configuration\n", "# Define the directory where your images and texts are stored\n", "data_folder = \"\" # Example: \"/content/drive/MyDrive/dataset\"\n", "\n", "# Name your dataset as desired\n", "dataset_name = \"\" # Example: \"my-first-dataset\"\n", "dataset_repo_id = \"\" # Example: \"your_username/my-first-dataset\"\n", "hf_token = \"\" # Your Hugging Face token\n", "\n", "## Initialize the Hugging Face API\n", "api = HfApi()\n", "login(hf_token)\n", "\n", "## Define the dataset features\n", "features = Features({\n", " \"image\": Image(),\n", " \"text\": Value(\"string\"),\n", "})\n", "\n", "## Create a dictionary to store the corresponding images and texts\n", "data = {\"image\": [], \"text\": []}\n", "\n", "## Accepted image file extensions\n", "image_extensions = [\".png\", \".jpg\", \".jpeg\", \".gif\"]\n", "\n", "## Iterate through image files\n", "for filename in os.listdir(data_folder):\n", " # Check if the file has an accepted image extension\n", " if any(filename.lower().endswith(ext) for ext in image_extensions):\n", " image_path = os.path.join(data_folder, filename)\n", " txt_filename = os.path.splitext(filename)[0] + \".txt\"\n", " txt_path = os.path.join(data_folder, txt_filename)\n", "\n", " if os.path.exists(txt_path):\n", " # Read the content of the text file\n", " with open(txt_path, \"r\") as txt_file:\n", " text = txt_file.read()\n", "\n", " # Load the image using the pillow library\n", " with PILImage.open(image_path) as image:\n", " # Convert the image to the format expected by Hugging Face Datasets\n", " image_bytes = io.BytesIO()\n", " image.save(image_bytes, format='PNG')\n", " image_bytes = image_bytes.getvalue()\n", "\n", " # Add the image and text to the dictionary\n", " data[\"image\"].append(image_bytes)\n", " data[\"text\"].append(text)\n", "\n", "## Create the dataset on Hugging Face\n", "dataset = Dataset.from_dict(data, features=features)\n", "dataset.push_to_hub(dataset_repo_id, private=True) # Set private=False if you want the dataset to be public\n", "\n", "print(\"Dataset successfully uploaded to Hugging Face!\")\n" ], "metadata": { "id": "jYTgzfRwyDfL" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "!pip install python-slugify\n", "from slugify import slugify\n", "\n", "model_name = \"3d icon SDXL LoRA\" # @param\n", "output_dir = slugify(model_name)" ], "metadata": { "id": "I-EcR3g6zS7o" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Instance & Validation Prompt**\n", "* `instance_prompt` -\n", " * when custom captions are enabled this prompt is still used in case there are missing captions, as well as in the model's readme.\n", " * If custom captions are not used, this prompt will be used as the caption for all training images.\n", "* `validation_prompt` -\n", " * this prompt is used to generate images throught the training process, this way you can see the models learning curve during training.\n", " * you can also change `num_validation_images` (4 by default) and `validation_epochs` (50 by default) to control the amount images generated with the validation prompt, and the number of ephochs between each dreambooth validation. " ], "metadata": { "id": "LyuzvbWIzbXC" } }, { "cell_type": "code", "source": [ "instance_prompt = \"3d icon in the style of TOK\" # @param\n", "validation_prompt = \"a TOK icon of an astronaut riding a horse, in the style of TOK\" # @param" ], "metadata": { "id": "xIopxUKHzYcU" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "**Set your LoRA rank**\n", "The rank of your LoRA is linked to its expressiveness.\n", "The bigger the rank the closer we are to regular dreambooth, and in theory we have more expressive power (and heavier weights).\n", "\n", "For a very simple concept that you have a good high quality image set for (e.g. a pet, a generic object), a rank as low as 4 can be enough to get great results. We reccomend going between 8 and 64 depending on your concept and how much of a priortiy it is for you to keep the LoRA small or not. " ], "metadata": { "id": "sb0kvKjtzh9w" } }, { "cell_type": "code", "source": [ "rank = 8 # @param" ], "metadata": { "id": "58pTgSOIziw3" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "#Dataset Name/Local/HF" ], "metadata": { "id": "DviZbC9mz0RX" } }, { "cell_type": "code", "source": [ "dataset_name=./3d_icon # @param\n", "caption_column=prompt # @param" ], "metadata": { "id": "VZnq1H7fz2dM" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "#!/usr/bin/env bash\n", "!accelerate launch train_dreambooth_lora_sdxl_advanced.py \\\n", " --pretrained_model_name_or_path=\"playgroundai/playground-v2.5-1024px-aesthetic\" \\\n", " --dataset_name=\"$dataset_name\" \\\n", " --instance_prompt=\"$instance_prompt\" \\\n", " --validation_prompt=\"$validation_prompt\" \\\n", " --output_dir=\"$output_dir\" \\\n", " --caption_column=\"$caption_column\" \\\n", " --do_edm_style_training \\\n", " --mixed_precision=\"bf16\" \\\n", " --resolution=1024 \\\n", " --train_batch_size=3 \\\n", " --repeats=1 \\\n", " --report_to=\"wandb\"\\\n", " --gradient_accumulation_steps=1 \\\n", " --gradient_checkpointing \\\n", " --learning_rate=1e-5 \\\n", " --optimizer=\"AdamW\"\\\n", " --lr_scheduler=\"constant\" \\\n", " --rank=\"$rank\" \\\n", " --max_train_steps=2000 \\\n", " --checkpointing_steps=2000 \\\n", " --seed=\"0\" \\\n", " --push_to_hub" ], "metadata": { "id": "P3IAGgF9zmig" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "from huggingface_hub import whoami\n", "from pathlib import Path\n", "from IPython.display import display, Markdown\n", "\n", "username = whoami(token=Path(\"/root/.cache/huggingface/\"))[\"name\"]\n", "repo_id = f\"{username}/{output_dir}\"\n", "\n", "link_to_model = f\"https://huggingface.co/{repo_id}\"\n", "\n", "display(Markdown(\"### Your model has finished training.\\nAccess it here: {}\".format(link_to_model)))" ], "metadata": { "id": "NkY5Sviy0fHJ" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "#LOAD INFERENCE" ], "metadata": { "id": "t8gtC0kf0WX0" } }, { "cell_type": "code", "source": [ "import torch\n", "from huggingface_hub import hf_hub_download, upload_file\n", "from diffusers import DiffusionPipeline\n", "from diffusers.models import AutoencoderKL\n", "from safetensors.torch import load_file\n", "\n", "pipe = DiffusionPipeline.from_pretrained(\n", " \"playgroundai/playground-v2.5-1024px-aesthetic\",\n", " torch_dtype=torch.float16,\n", " variant=\"fp16\",\n", ").to(\"cuda\")\n", "\n", "pipe.load_lora_weights(repo_id, weight_name=\"pytorch_lora_weights.safetensors\")\n" ], "metadata": { "id": "Ib7aaWVQ0mdT" }, "execution_count": null, "outputs": [] } ] }