{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rmCPmqFL6hCQ"
      },
      "source": [
        "# 🌟 XL Lora Trainer by Hollowstrawberry\n",
        "\n",
        "❗ **Colab Premium is recommended.** Ideally you'd be changing the runtime to an A100 and use the maximum batch size.  \n",
        "However you can still train for free if you load a diffusers model, it will just take much longer.  \n",
        "\n",
        "\n",
        "This colab is based on the work of [Kohya-ss](https://github.com/kohya-ss/sd-scripts) and [Linaqruf](https://github.com/Linaqruf/kohya-trainer). Thank you!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vJ8clWTZEu-g"
      },
      "source": [
        "### ⭕ Disclaimer\n",
        "The purpose of this document is to research bleeding-edge technologies in the field of machine learning inference.  \n",
        "Please read and follow the [Google Colab guidelines](https://research.google.com/colaboratory/faq.html) and its [Terms of Service](https://research.google.com/colaboratory/tos_v3.html)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dPQlB4djNm3C"
      },
      "source": [
        "| |GitHub|🇬🇧 English|🇪🇸 Spanish|\n",
        "|:--|:-:|:-:|:-:|\n",
        "| 🏠 **Homepage** | [![GitHub](https://raw.githubusercontent.com/hollowstrawberry/kohya-colab/main/assets/github.svg)](https://github.com/hollowstrawberry/kohya-colab) | | |\n",
        "| 📊 **Dataset Maker** | [![GitHub](https://raw.githubusercontent.com/hollowstrawberry/kohya-colab/main/assets/github.svg)](https://github.com/hollowstrawberry/kohya-colab/blob/main/Dataset_Maker.ipynb) | [![Open in Colab](https://raw.githubusercontent.com/hollowstrawberry/kohya-colab/main/assets/colab-badge.svg)](https://colab.research.google.com/github/hollowstrawberry/kohya-colab/blob/main/Dataset_Maker.ipynb) | [![Abrir en Colab](https://raw.githubusercontent.com/hollowstrawberry/kohya-colab/main/assets/colab-badge-spanish.svg)](https://colab.research.google.com/github/hollowstrawberry/kohya-colab/blob/main/Spanish_Dataset_Maker.ipynb) |\n",
        "| ⭐ **Lora Trainer** | [![GitHub](https://raw.githubusercontent.com/hollowstrawberry/kohya-colab/main/assets/github.svg)](https://github.com/hollowstrawberry/kohya-colab/blob/main/Lora_Trainer.ipynb) | [![Open in Colab](https://raw.githubusercontent.com/hollowstrawberry/kohya-colab/main/assets/colab-badge.svg)](https://colab.research.google.com/github/hollowstrawberry/kohya-colab/blob/main/Lora_Trainer.ipynb) | [![Abrir en Colab](https://raw.githubusercontent.com/hollowstrawberry/kohya-colab/main/assets/colab-badge-spanish.svg)](https://colab.research.google.com/github/hollowstrawberry/kohya-colab/blob/main/Spanish_Lora_Trainer.ipynb) |\n",
        "| 🌟 **XL Lora Trainer** | [![GitHub](https://raw.githubusercontent.com/hollowstrawberry/kohya-colab/main/assets/github.svg)](https://github.com/hollowstrawberry/kohya-colab/blob/main/Lora_Trainer_XL.ipynb) | [![Open in Colab](https://raw.githubusercontent.com/hollowstrawberry/kohya-colab/main/assets/colab-badge.svg)](https://colab.research.google.com/github/hollowstrawberry/kohya-colab/blob/main/Lora_Trainer_XL.ipynb) |  |"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Wd4916Eu1tb9"
      },
      "source": [
        "### 📚 Multiple folders in dataset\n",
        "Below is a template allowing you to define multiple folders in your dataset. You must include the location of each folder and you can set different number of repeats for each one. To add more folders simply copy and paste the sections starting with `[[datasets.subsets]]`.\n",
        "\n",
        "When enabling this, the number of repeats set in the main cell will be ignored, and the main folder set by the project name will also be ignored.\n",
        "\n",
        "You can make one of them a regularization folder by adding `is_reg = true`  \n",
        "You can also set different `keep_tokens`, `flip_aug`, etc."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WDjkp4scvPgE"
      },
      "outputs": [],
      "source": [
        "#@markdown ### 📂 Unzip dataset\n",
        "#@markdown It's much slower to upload individual files to your Drive, so you may want to upload a zip if you have your dataset in your computer.\n",
        "zip = \"/content/drive/MyDrive/bludwingdata.zip\" #@param {type:\"string\"}\n",
        "extract_to = \"/content/Loras/bludwingdata/dataset\" #@param {type:\"string\"}\n",
        "\n",
        "import os, zipfile\n",
        "\n",
        "if not os.path.exists('/content/drive'):\n",
        "  from google.colab import drive\n",
        "  print(\"📂 Connecting to Google Drive...\")\n",
        "  drive.mount('/content/drive')\n",
        "\n",
        "os.makedirs(extract_to, exist_ok=True)\n",
        "\n",
        "with zipfile.ZipFile(zip, 'r') as f:\n",
        "  f.extractall(extract_to)\n",
        "\n",
        "print(\"✅ Done\")\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Y037lagnJWmn"
      },
      "outputs": [],
      "source": [
        "custom_dataset = \"\"\"\n",
        "[[datasets]]\n",
        "\n",
        "[[datasets.subsets]]\n",
        "flip_aug=true\n",
        "image_dir = \"/content/Loras/bludwingdata/dataset\"\n",
        "num_repeats = 1\n",
        "\n",
        "\"\"\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "aKWlpsG0jrX3"
      },
      "outputs": [],
      "source": [
        "#@markdown ### 🔢 Count datasets\n",
        "#@markdown Google Drive makes it impossible to count the files in a folder, so this will show you the file counts in all folders and subfolders.\n",
        "folder = \"/content/Loras\" #@param {type:\"string\"}\n",
        "\n",
        "import os\n",
        "from google.colab import drive\n",
        "\n",
        "if not os.path.exists('/content/drive'):\n",
        "    print(\"📂 Connecting to Google Drive...\\n\")\n",
        "    drive.mount('/content/drive')\n",
        "\n",
        "tree = {}\n",
        "exclude = (\"_logs\", \"/output\")\n",
        "for i, (root, dirs, files) in enumerate(os.walk(folder, topdown=True)):\n",
        "  dirs[:] = [d for d in dirs if all(ex not in d for ex in exclude)]\n",
        "  images = len([f for f in files if f.lower().endswith((\".png\", \".jpg\", \".jpeg\"))])\n",
        "  captions = len([f for f in files if f.lower().endswith(\".txt\")])\n",
        "  others = len(files) - images - captions\n",
        "  path = root[folder.rfind(\"/\")+1:]\n",
        "  tree[path] = None if not images else f\"{images:>4} images | {captions:>4} captions |\"\n",
        "  if tree[path] and others:\n",
        "    tree[path] += f\" {others:>4} other files\"\n",
        "\n",
        "pad = max(len(k) for k in tree)\n",
        "print(\"\\n\".join(f\"📁{k.ljust(pad)} | {v}\" for k, v in tree.items() if v))\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "OglZzI_ujZq-"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "import re\n",
        "import toml\n",
        "from time import time\n",
        "from huggingface_hub import HfFileSystem\n",
        "from IPython.display import Markdown, display\n",
        "\n",
        "# These carry information from past executions\n",
        "if \"model_url\" in globals():\n",
        "  old_model_url = model_url\n",
        "else:\n",
        "  old_model_url = None\n",
        "if \"dependencies_installed\" not in globals():\n",
        "  dependencies_installed = False\n",
        "if \"model_file\" not in globals():\n",
        "  model_file = None\n",
        "\n",
        "# These may be set by other cells, some are legacy\n",
        "if \"custom_dataset\" not in globals():\n",
        "  custom_dataset = None\n",
        "if \"override_dataset_config_file\" not in globals():\n",
        "  override_dataset_config_file = None\n",
        "if \"override_config_file\" not in globals():\n",
        "  override_config_file = None\n",
        "\n",
        "COLAB = True\n",
        "COMMIT = None\n",
        "BETTER_EPOCH_NAMES = True\n",
        "LOAD_TRUNCATED_IMAGES = True\n",
        "try:\n",
        "  LOWRAM = int(next(line.split()[1] for line in open('/proc/meminfo') if \"MemTotal\" in line)) / (1024**2) < 15\n",
        "except:\n",
        "  LOWRAM = False\n",
        "\n",
        "#@title ## 🚩 Start Here\n",
        "\n",
        "#@markdown ### ▶️ Setup\n",
        "#@markdown Your project name will be the same as the folder containing your images. Spaces aren't allowed.\n",
        "project_name = \"bludwing\" #@param {type:\"string\"}\n",
        "#@markdown The folder structure doesn't matter and is purely for comfort. Make sure to always pick the same one. I like organizing by project.\n",
        "folder_structure = \"Organize by project (MyDrive/Loras/project_name/dataset)\" #@param [\"Organize by category (MyDrive/lora_training/datasets/project_name)\", \"Organize by project (MyDrive/Loras/project_name/dataset)\"]\n",
        "#@markdown Decide the model that will be downloaded and used for training. You can also choose your own by pasting its download link.\n",
        "training_model = \"Pony Diffusion V6 XL\" #@param [\"Pony Diffusion V6 XL\", \"Animagine XL V3\", \"Stable Diffusion XL 1.0 base\"]\n",
        "optional_custom_training_model_url = \"\" #@param {type:\"string\"}\n",
        "#@markdown Using a diffusers model utilizes less resources. The 3 options above will work with or without diffusers.\n",
        "load_diffusers = True #@param {type:\"boolean\"}\n",
        "\n",
        "if optional_custom_training_model_url:\n",
        "  model_url = optional_custom_training_model_url\n",
        "elif \"Pony\" in training_model:\n",
        "  if load_diffusers:\n",
        "    model_url = \"https://huggingface.co/stablediffusionapi/pony-diffusion-v6-xl/\"\n",
        "  else:\n",
        "    model_url = \"https://civitai.com/api/download/models/290640\"\n",
        "  model_file = \"/content/ponyDiffusionV6XL.safetensors\"\n",
        "elif \"Animagine\" in training_model:\n",
        "  if load_diffusers:\n",
        "    model_url = \"https://huggingface.co/cagliostrolab/animagine-xl-3.0\"\n",
        "  else:\n",
        "    model_url = \"https://civitai.com/api/download/models/293564\"\n",
        "  model_file = \"/content/animagineXLV3.safetensors\"\n",
        "else:\n",
        "  if load_diffusers:\n",
        "    model_url = \"https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/\"\n",
        "  else:\n",
        "    model_url = \"https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_base_1.0.safetensors\"\n",
        "\n",
        "if load_diffusers:\n",
        "  vae_file= \"stabilityai/sdxl-vae\"\n",
        "else:\n",
        "  vae_url = \"https://huggingface.co/stabilityai/sdxl-vae/resolve/main/sdxl_vae.safetensors\"\n",
        "  vae_file = \"/content/sdxl_vae.safetensors\"\n",
        "\n",
        "\n",
        "#@markdown ### ▶️ Processing\n",
        "resolution = 1024 #param {type:\"slider\", min:768, max:1536, step:128}\n",
        "caption_extension = \".txt\" #param {type:\"string\"}\n",
        "#@markdown Shuffling anime tags in place improves learning and prompting. An activation tag goes at the start of every text file and will not be shuffled.<p>\n",
        "shuffle_tags = True #@param {type:\"boolean\"}\n",
        "shuffle_caption = shuffle_tags\n",
        "activation_tags = \"0\" #@param [0,1,2,3]\n",
        "keep_tokens = int(activation_tags)\n",
        "\n",
        "#@markdown ### ▶️ Steps <p>\n",
        "#@markdown Your images will repeat this number of times during training. I recommend that your images multiplied by their repeats is between 200 and 400.\n",
        "num_repeats = 1 #@param {type:\"number\"}\n",
        "#@markdown Choose how long you want to train for. A good starting point is around 10 epochs or around 2000 steps.<p>\n",
        "#@markdown One epoch is a number of steps equal to: your number of images multiplied by their repeats, divided by batch size. <p>\n",
        "preferred_unit = \"Epochs\" #@param [\"Epochs\", \"Steps\"]\n",
        "how_many = 15 #@param {type:\"number\"}\n",
        "max_train_epochs = how_many if preferred_unit == \"Epochs\" else None\n",
        "max_train_steps = how_many if preferred_unit == \"Steps\" else None\n",
        "#@markdown Saving more epochs will let you compare your Lora's progress better.\n",
        "save_every_n_epochs = 2 #@param {type:\"number\"}\n",
        "keep_only_last_n_epochs = 999 #@param {type:\"number\"}\n",
        "if not save_every_n_epochs:\n",
        "  save_every_n_epochs = max_train_epochs\n",
        "if not keep_only_last_n_epochs:\n",
        "  keep_only_last_n_epochs = max_train_epochs\n",
        "\n",
        "#@markdown ### ▶️ Learning\n",
        "#@markdown The learning rate is the most important for your results. If you want to train slower with lots of images, or if your dim and alpha are high, move the unet to 2e-4 or lower. <p>\n",
        "#@markdown The text encoder helps your Lora learn concepts slightly better. It is recommended to make it half or a fifth of the unet. If you're training a style you can even set it to 0.\n",
        "unet_lr = 1 #@param {type:\"number\"}\n",
        "text_encoder_lr = 0 #@param {type:\"number\"}\n",
        "#@markdown The scheduler is the algorithm that guides the learning rate. If you're not sure, pick `constant` and ignore the number. I personally recommend `cosine_with_restarts` with 3 restarts.\n",
        "lr_scheduler = \"constant\" #@param [\"constant\", \"cosine\", \"cosine_with_restarts\", \"constant_with_warmup\", \"linear\", \"polynomial\"]\n",
        "lr_scheduler_number = 1 #@param {type:\"number\"}\n",
        "lr_scheduler_num_cycles = lr_scheduler_number if lr_scheduler == \"cosine_with_restarts\" else 0\n",
        "lr_scheduler_power = lr_scheduler_number if lr_scheduler == \"polynomial\" else 0\n",
        "#@markdown Steps spent \"warming up\" the learning rate during training for efficiency. I recommend leaving it at 5%.\n",
        "lr_warmup_ratio = 0 #@param {type:\"slider\", min:0.0, max:0.2, step:0.01}\n",
        "lr_warmup_steps = 0\n",
        "#@markdown Adjusts loss over time, makes learning much more efficient. The paper recommends 5.0, I recommend 8.0 for anime. Higher value makes it less strict. Set to 0 to disable.\n",
        "min_snr_gamma = 6.5 #@param {type:\"slider\", min:4.0, max:16.0, step:0.5}\n",
        "\n",
        "#@markdown ### ▶️ Structure\n",
        "#@markdown LoRA is the classic type and good for a variety of purposes. LoCon is good with artstyles as it has more layers to learn more aspects of the dataset.\n",
        "lora_type = \"LoRA\" #@param [\"LoRA\", \"LoCon\"]\n",
        "\n",
        "#@markdown Below are some recommended XL values for the following settings:\n",
        "\n",
        "#@markdown | type | network_dim | network_alpha | conv_dim | conv_alpha |\n",
        "#@markdown | :---: | :---: | :---: | :---: | :---: |\n",
        "#@markdown | Regular LoRA | 8 | 4 |   |   |\n",
        "#@markdown | Style LoCon | 16 | 8 | 16 | 8 |\n",
        "\n",
        "#@markdown More dim means larger Lora, it can hold more information but more isn't always better.\n",
        "network_dim = 16 #@param {type:\"slider\", min:1, max:32, step:1}\n",
        "network_alpha = 8 #@param {type:\"slider\", min:1, max:32, step:1}\n",
        "#@markdown The following two values only apply to the additional layers of LoCon.\n",
        "conv_dim = 4 #@param {type:\"slider\", min:1, max:32, step:1}\n",
        "conv_alpha = 1 #@param {type:\"slider\", min:1, max:32, step:1}\n",
        "\n",
        "network_module = \"networks.lora\"\n",
        "network_args = None\n",
        "if lora_type.lower() == \"locon\":\n",
        "  network_args = [f\"conv_dim={conv_dim}\", f\"conv_alpha={conv_alpha}\"]\n",
        "\n",
        "#@markdown ### ▶️ Training\n",
        "#@markdown Adjust these parameters depending on your colab configuration.\n",
        "#@markdown If you're using the free tier you should select a diffusers model at the top of this cell.\n",
        "#@markdown\n",
        "#@markdown Higher batch size is often faster but uses more memory.\n",
        "train_batch_size = 4 #@param {type:\"slider\", min:1, max:16, step:1}\n",
        "#@markdown I have found no substantial difference between sdpa and xformers.\n",
        "cross_attention = \"sdpa\" #@param [\"sdpa\", \"xformers\"]\n",
        "#@markdown If you're on an A100 you should enable bf16.\n",
        "mixed_precision = \"fp16\" #@param [\"bf16\", \"fp16\"]\n",
        "#@markdown Caching latents to drive will add a 250KB file next to each image but will use considerably less memory.\n",
        "cache_latents = False #@param {type:\"boolean\"}\n",
        "#@markdown The following option will turn off shuffle_tags and disable text encoder training.\n",
        "cache_text_encoder_outputs  = True  # @param {type:\"boolean\"}\n",
        "\n",
        "#@markdown ### ▶️ Advanced\n",
        "#@markdown The optimizer is the algorithm used for training. AdanW8Bit is the default and works great, while Prodigy manages learning rate automatically and may have several advantages such as training faster due to needing less steps as well as working better for small datasets.\n",
        "optimizer = \"Prodigy\" #@param [\"AdamW8bit\", \"Prodigy\", \"DAdaptation\", \"DadaptAdam\", \"DadaptLion\", \"AdamW\", \"Lion\", \"SGDNesterov\", \"SGDNesterov8bit\", \"AdaFactor\"]\n",
        "#@markdown Recommended args for AdamW8bit: `weight_decay=0.1 betas=[0.9,0.99]`<p>\n",
        "#@markdown Recommended args for Prodigy: `decouple=True weight_decay=0.01 betas=[0.9,0.999] d_coef=2 use_bias_correction=True safeguard_warmup=True`\n",
        "optimizer_args = \"decouple=True weight_decay=0.05 d_coef=0.8 use_bias_correction=True betas=0.9,0.99\" #@param {type:\"string\"}\n",
        "optimizer_args = [a.strip() for a in optimizer_args.split(' ') if a]\n",
        "#@markdown If Dadapt or Prodigy are selected and this box is checked, the following recommended values will override any previous settings:<p>\n",
        "#@markdown `unet_lr=0.75`, `text_encoder_lr=0.75`, `network_alpha=network_dim`\n",
        "recommended_values_for_prodigy = False #@param {type:\"boolean\"}\n",
        "\n",
        "if any(opt in optimizer.lower() for opt in [\"dadapt\", \"prodigy\"]):\n",
        "  if recommended_values_for_prodigy:\n",
        "    unet_lr = 0.75\n",
        "    text_encoder_lr = 0.75\n",
        "    network_alpha = network_dim\n",
        "\n",
        "#@markdown ### ▶️ Ready\n",
        "#@markdown You can now run this cell to cook your Lora. Good luck! <p>\n",
        "\n",
        "\n",
        "# 👩‍💻 Cool code goes here\n",
        "\n",
        "root_dir = \"/content\" if COLAB else \"~/Loras\"\n",
        "deps_dir = os.path.join(root_dir, \"deps\")\n",
        "repo_dir = os.path.join(root_dir, \"kohya-trainer\")\n",
        "\n",
        "if \"/Loras\" in folder_structure:\n",
        "  main_dir      = os.path.join(root_dir, \"drive/MyDrive/Loras\") if COLAB else root_dir\n",
        "  log_folder    = os.path.join(main_dir, \"_logs\")\n",
        "  config_folder = os.path.join(main_dir, project_name)\n",
        "  images_folder = os.path.join(main_dir, project_name, \"dataset\")\n",
        "  output_folder = os.path.join(main_dir, project_name, \"output\")\n",
        "else:\n",
        "  main_dir      = os.path.join(root_dir, \"drive/MyDrive/lora_training\") if COLAB else root_dir\n",
        "  images_folder = os.path.join(main_dir, \"datasets\", project_name)\n",
        "  output_folder = os.path.join(main_dir, \"output\", project_name)\n",
        "  config_folder = os.path.join(main_dir, \"config\", project_name)\n",
        "  log_folder    = os.path.join(main_dir, \"log\")\n",
        "\n",
        "config_file = os.path.join(config_folder, \"training_config.toml\")\n",
        "dataset_config_file = os.path.join(config_folder, \"dataset_config.toml\")\n",
        "accelerate_config_file = os.path.join(repo_dir, \"accelerate_config/config.yaml\")\n",
        "\n",
        "def clone_repo():\n",
        "  os.chdir(root_dir)\n",
        "  !git clone https://github.com/qaneel/kohya-trainer {repo_dir}\n",
        "  os.chdir(repo_dir)\n",
        "  if COMMIT:\n",
        "    !git reset --hard {COMMIT}\n",
        "  !wget https://raw.githubusercontent.com/hollowstrawberry/kohya-colab/main/requirementsXL.txt -q -O requirements.txt\n",
        "\n",
        "def install_dependencies():\n",
        "  clone_repo()\n",
        "  !apt -y update -qq\n",
        "  !apt -y install aria2 -qq\n",
        "  !pip install --upgrade -r requirements.txt\n",
        "\n",
        "  if cross_attention == \"xformers\":\n",
        "    !pip install -q xformers==0.0.22.post7\n",
        "\n",
        "  # patch kohya for minor stuff\n",
        "  if LOWRAM:\n",
        "    !sed -i \"s@cpu@cuda@\" library/model_util.py\n",
        "  if LOAD_TRUNCATED_IMAGES:\n",
        "    !sed -i 's/from PIL import Image/from PIL import Image, ImageFile\\nImageFile.LOAD_TRUNCATED_IMAGES=True/g' library/train_util.py # fix truncated jpegs error\n",
        "  if BETTER_EPOCH_NAMES:\n",
        "    !sed -i 's/{:06d}/{:02d}/g' library/train_util.py # make epoch names shorter\n",
        "    !sed -i 's/\".\" + args.save_model_as)/\"-{:02d}.\".format(num_train_epochs) + args.save_model_as)/g' train_network.py # name of the last epoch will match the rest\n",
        "\n",
        "  from accelerate.utils import write_basic_config\n",
        "  if not os.path.exists(accelerate_config_file):\n",
        "    write_basic_config(save_location=accelerate_config_file)\n",
        "\n",
        "  os.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\"\n",
        "  os.environ[\"BITSANDBYTES_NOWELCOME\"] = \"1\"\n",
        "  os.environ[\"SAFETENSORS_FAST_GPU\"] = \"1\"\n",
        "\n",
        "def validate_dataset():\n",
        "  global lr_warmup_steps, lr_warmup_ratio, caption_extension, keep_tokens\n",
        "  supported_types = (\".png\", \".jpg\", \".jpeg\", \".webp\", \".bmp\")\n",
        "\n",
        "  print(\"\\n💿 Checking dataset...\")\n",
        "  if not project_name.strip() or any(c in project_name for c in \" .()\\\"'\\\\/\"):\n",
        "    print(\"💥 Error: Please choose a valid project name.\")\n",
        "    return\n",
        "\n",
        "  if custom_dataset:\n",
        "    try:\n",
        "      datconf = toml.loads(custom_dataset)\n",
        "      datasets = [d for d in datconf[\"datasets\"][0][\"subsets\"]]\n",
        "    except:\n",
        "      print(f\"💥 Error: Your custom dataset is invalid or contains an error! Please check the original template.\")\n",
        "      return\n",
        "    reg = [d.get(\"image_dir\") for d in datasets if d.get(\"is_reg\", False)]\n",
        "    datasets_dict = {d[\"image_dir\"]: d[\"num_repeats\"] for d in datasets}\n",
        "    folders = datasets_dict.keys()\n",
        "    files = [f for folder in folders for f in os.listdir(folder)]\n",
        "    images_repeats = {folder: (len([f for f in os.listdir(folder) if f.lower().endswith(supported_types)]), datasets_dict[folder]) for folder in folders}\n",
        "  else:\n",
        "    reg = []\n",
        "    folders = [images_folder]\n",
        "    files = os.listdir(images_folder)\n",
        "    images_repeats = {images_folder: (len([f for f in files if f.lower().endswith(supported_types)]), num_repeats)}\n",
        "\n",
        "  for folder in folders:\n",
        "    if not os.path.exists(folder):\n",
        "      print(f\"💥 Error: The folder {folder.replace('/content/drive/', '')} doesn't exist.\")\n",
        "      return\n",
        "  for folder, (img, rep) in images_repeats.items():\n",
        "    if not img:\n",
        "      print(f\"💥 Error: Your {folder.replace('/content/drive/', '')} folder is empty.\")\n",
        "      return\n",
        "  for f in files:\n",
        "    if not f.lower().endswith((\".txt\", \".npz\")) and not f.lower().endswith(supported_types):\n",
        "      print(f\"💥 Error: Invalid file in dataset: \\\"{f}\\\". Aborting.\")\n",
        "      return\n",
        "\n",
        "  if not [txt for txt in files if txt.lower().endswith(\".txt\")]:\n",
        "    caption_extension = \"\"\n",
        "\n",
        "  pre_steps_per_epoch = sum(img*rep for (img, rep) in images_repeats.values())\n",
        "  steps_per_epoch = pre_steps_per_epoch/train_batch_size\n",
        "  total_steps = max_train_steps or int(max_train_epochs*steps_per_epoch)\n",
        "  estimated_epochs = int(total_steps/steps_per_epoch)\n",
        "  lr_warmup_steps = int(total_steps*lr_warmup_ratio)\n",
        "\n",
        "  for folder, (img, rep) in images_repeats.items():\n",
        "    print(\"📁\"+folder.replace(\"/content/drive/\", \"\") + (\" (Regularization)\" if folder in reg else \"\"))\n",
        "    print(f\"📈 Found {img} images with {rep} repeats, equaling {img*rep} steps.\")\n",
        "  print(f\"📉 Divide {pre_steps_per_epoch} steps by {train_batch_size} batch size to get {steps_per_epoch} steps per epoch.\")\n",
        "  if max_train_epochs:\n",
        "    print(f\"🔮 There will be {max_train_epochs} epochs, for around {total_steps} total training steps.\")\n",
        "  else:\n",
        "    print(f\"🔮 There will be {total_steps} steps, divided into {estimated_epochs} epochs and then some.\")\n",
        "\n",
        "  if total_steps > 100000000000:\n",
        "    print(\"💥 Error: Your total steps are too high. You probably made a mistake. Aborting...\")\n",
        "    return\n",
        "\n",
        "  return True\n",
        "\n",
        "def create_config():\n",
        "  global dataset_config_file, config_file, model_file\n",
        "\n",
        "  if override_config_file:\n",
        "    config_file = override_config_file\n",
        "    print(f\"\\n⭕ Using custom config file {config_file}\")\n",
        "  else:\n",
        "    config_dict = {\n",
        "      \"network_arguments\": {\n",
        "        \"unet_lr\": unet_lr,\n",
        "        \"text_encoder_lr\": text_encoder_lr if not cache_text_encoder_outputs else 0,\n",
        "        \"network_dim\": network_dim,\n",
        "        \"network_alpha\": network_alpha,\n",
        "        \"network_module\": network_module,\n",
        "        \"network_args\": network_args,\n",
        "        \"network_train_unet_only\": text_encoder_lr == 0 or cache_text_encoder_outputs,\n",
        "      },\n",
        "      \"optimizer_arguments\": {\n",
        "        \"learning_rate\": unet_lr,\n",
        "        \"lr_scheduler\": lr_scheduler,\n",
        "        \"lr_scheduler_num_cycles\": lr_scheduler_num_cycles if lr_scheduler == \"cosine_with_restarts\" else None,\n",
        "        \"lr_scheduler_power\": lr_scheduler_power if lr_scheduler == \"polynomial\" else None,\n",
        "        \"lr_warmup_steps\": lr_warmup_steps if lr_scheduler != \"constant\" else None,\n",
        "        \"optimizer_type\": optimizer,\n",
        "        \"optimizer_args\": optimizer_args if optimizer_args else None,\n",
        "      },\n",
        "      \"training_arguments\": {\n",
        "        \"pretrained_model_name_or_path\": model_file,\n",
        "        \"vae\": vae_file,\n",
        "        \"max_train_steps\": max_train_steps,\n",
        "        \"max_train_epochs\": max_train_epochs,\n",
        "        \"train_batch_size\": train_batch_size,\n",
        "        \"seed\": 42,\n",
        "        \"max_token_length\": 225,\n",
        "        \"xformers\": cross_attention == \"xformers\",\n",
        "        \"sdpa\": cross_attention == \"sdpa\",\n",
        "        \"min_snr_gamma\": min_snr_gamma if min_snr_gamma > 0 else None,\n",
        "        \"lowram\": LOWRAM,\n",
        "        \"no_half_vae\": True,\n",
        "        \"gradient_checkpointing\": True,\n",
        "        \"gradient_accumulation_steps\": 1,\n",
        "        \"max_data_loader_n_workers\": 8,\n",
        "        \"persistent_data_loader_workers\": True,\n",
        "        \"mixed_precision\": mixed_precision,\n",
        "        \"full_bf16\": mixed_precision == \"bf16\",\n",
        "        \"cache_latents\": True,\n",
        "        \"cache_latents_to_disk\": True,\n",
        "        \"cache_text_encoder_outputs\": cache_text_encoder_outputs,\n",
        "        \"min_timestep\": 0,\n",
        "        \"max_timestep\": 1000,\n",
        "        \"prior_loss_weight\": 1.0,\n",
        "      },\n",
        "      \"saving_arguments\": {\n",
        "        \"save_precision\": \"fp16\",\n",
        "        \"save_model_as\": \"safetensors\",\n",
        "        \"save_every_n_epochs\": save_every_n_epochs,\n",
        "        \"save_last_n_epochs\": keep_only_last_n_epochs,\n",
        "        \"output_name\": project_name,\n",
        "        \"output_dir\": output_folder,\n",
        "        \"log_prefix\": project_name,\n",
        "        \"logging_dir\": log_folder,\n",
        "      }\n",
        "    }\n",
        "\n",
        "    for key in config_dict:\n",
        "      if isinstance(config_dict[key], dict):\n",
        "        config_dict[key] = {k: v for k, v in config_dict[key].items() if v is not None}\n",
        "\n",
        "    with open(config_file, \"w\") as f:\n",
        "      f.write(toml.dumps(config_dict))\n",
        "    print(f\"\\n📄 Config saved to {config_file}\")\n",
        "\n",
        "  if override_dataset_config_file:\n",
        "    dataset_config_file = override_dataset_config_file\n",
        "    print(f\"⭕ Using custom dataset config file {dataset_config_file}\")\n",
        "  else:\n",
        "    dataset_config_dict = {\n",
        "      \"general\": {\n",
        "        \"resolution\": resolution,\n",
        "        \"shuffle_caption\": shuffle_caption and not cache_text_encoder_outputs,\n",
        "        \"keep_tokens\": keep_tokens,\n",
        "        \"flip_aug\": False,\n",
        "        \"caption_extension\": caption_extension,\n",
        "        \"enable_bucket\": True,\n",
        "        \"bucket_no_upscale\": False,\n",
        "        \"bucket_reso_steps\": 64,\n",
        "        \"min_bucket_reso\": 256,\n",
        "        \"max_bucket_reso\": 1024,\n",
        "      },\n",
        "      \"datasets\": toml.loads(custom_dataset)[\"datasets\"] if custom_dataset else [\n",
        "        {\n",
        "          \"subsets\": [\n",
        "            {\n",
        "              \"num_repeats\": num_repeats,\n",
        "              \"image_dir\": images_folder,\n",
        "              \"class_tokens\": None if caption_extension else project_name\n",
        "            }\n",
        "          ]\n",
        "        }\n",
        "      ]\n",
        "    }\n",
        "\n",
        "    for key in dataset_config_dict:\n",
        "      if isinstance(dataset_config_dict[key], dict):\n",
        "        dataset_config_dict[key] = {k: v for k, v in dataset_config_dict[key].items() if v is not None}\n",
        "\n",
        "    with open(dataset_config_file, \"w\") as f:\n",
        "      f.write(toml.dumps(dataset_config_dict))\n",
        "    print(f\"📄 Dataset config saved to {dataset_config_file}\")\n",
        "\n",
        "def download_model():\n",
        "  global old_model_url, model_url, model_file, vae_url, vae_file\n",
        "  real_model_url = model_url.strip()\n",
        "\n",
        "  if load_diffusers:\n",
        "    if 'huggingface.co' in real_model_url:\n",
        "        match = re.search(r'huggingface\\.co/([^/]+)/([^/]+)', real_model_url)\n",
        "        if match:\n",
        "            username = match.group(1)\n",
        "            model_name = match.group(2)\n",
        "            model_file = f\"{username}/{model_name}\"\n",
        "            fs = HfFileSystem()\n",
        "            existing_folders = set(fs.ls(model_file, detail=False))\n",
        "            necessary_folders = [ \"scheduler\", \"text_encoder\", \"text_encoder_2\", \"tokenizer\", \"tokenizer_2\", \"unet\", \"vae\" ]\n",
        "            if all(f\"{model_file}/{folder}\" in existing_folders for folder in necessary_folders):\n",
        "              print(\"🍃 Diffusers model identified.\")\n",
        "              return True\n",
        "    print(\"🍃 Failed to load Diffusers model.\")\n",
        "\n",
        "  if not model_file:\n",
        "    if real_model_url.lower().endswith((\".ckpt\", \".safetensors\")):\n",
        "      model_file = f\"/content{real_model_url[real_model_url.rfind('/'):]}\"\n",
        "    else:\n",
        "      model_file = \"/content/downloaded_model.safetensors\"\n",
        "      if os.path.exists(model_file):\n",
        "        !rm \"{model_file}\"\n",
        "\n",
        "  if m := re.search(r\"(?:https?://)?(?:www\\.)?huggingface\\.co/[^/]+/[^/]+/blob\", model_url):\n",
        "    real_model_url = real_model_url.replace(\"blob\", \"resolve\")\n",
        "  elif m := re.search(r\"(?:https?://)?(?:www\\\\.)?civitai\\.com/models/([0-9]+)(/[A-Za-z0-9-_]+)?\", model_url):\n",
        "    if m.group(2):\n",
        "      model_file = f\"/content{m.group(2)}.safetensors\"\n",
        "    if m := re.search(r\"modelVersionId=([0-9]+)\", model_url):\n",
        "      real_model_url = f\"https://civitai.com/api/download/models/{m.group(1)}\"\n",
        "    else:\n",
        "      raise ValueError(\"optional_custom_training_model_url contains a civitai link, but the link doesn't include a modelVersionId. You can also right click the download button to copy the direct download link.\")\n",
        "\n",
        "  !aria2c \"{real_model_url}\" --console-log-level=warn -c -s 16 -x 16 -k 10M -d / -o \"{model_file}\"\n",
        "\n",
        "  if not os.path.exists(vae_file):\n",
        "    !aria2c \"{vae_url}\" --console-log-level=warn -c -s 16 -x 16 -k 10M -d / -o \"{vae_file}\"\n",
        "\n",
        "  if model_file.lower().endswith(\".safetensors\"):\n",
        "    from safetensors.torch import load_file as load_safetensors\n",
        "    try:\n",
        "      test = load_safetensors(model_file)\n",
        "      del test\n",
        "    except:\n",
        "      #if \"HeaderTooLarge\" in str(e):\n",
        "      new_model_file = os.path.splitext(model_file)[0]+\".ckpt\"\n",
        "      !mv \"{model_file}\" \"{new_model_file}\"\n",
        "      model_file = new_model_file\n",
        "      print(f\"Renamed model to {os.path.splitext(model_file)[0]}.ckpt\")\n",
        "\n",
        "  if model_file.lower().endswith(\".ckpt\"):\n",
        "    from torch import load as load_ckpt\n",
        "    try:\n",
        "      test = load_ckpt(model_file)\n",
        "      del test\n",
        "    except:\n",
        "      return False\n",
        "\n",
        "  return True\n",
        "\n",
        "def main():\n",
        "  global dependencies_installed\n",
        "\n",
        "  if COLAB and not os.path.exists('/content/drive'):\n",
        "    from google.colab import drive\n",
        "    print(\"📂 Connecting to Google Drive...\")\n",
        "    drive.mount('/content/drive')\n",
        "\n",
        "  for dir in (main_dir, deps_dir, repo_dir, log_folder, images_folder, output_folder, config_folder):\n",
        "    os.makedirs(dir, exist_ok=True)\n",
        "\n",
        "  if not validate_dataset():\n",
        "    return\n",
        "\n",
        "  if not dependencies_installed:\n",
        "    print(\"\\n🏭 Installing dependencies...\\n\")\n",
        "    t0 = time()\n",
        "    install_dependencies()\n",
        "    t1 = time()\n",
        "    dependencies_installed = True\n",
        "    print(f\"\\n✅ Installation finished in {int(t1-t0)} seconds.\")\n",
        "  else:\n",
        "    print(\"\\n✅ Dependencies already installed.\")\n",
        "\n",
        "  if old_model_url != model_url or not model_file or not os.path.exists(model_file):\n",
        "    print(\"\\n🔄 Downloading model...\")\n",
        "    if not download_model():\n",
        "      print(\"\\n💥 Error: The model you selected is invalid or corrupted, or couldn't be downloaded. You can use a civitai or huggingface link, or any direct download link.\")\n",
        "      return\n",
        "    print()\n",
        "  else:\n",
        "    print(\"\\n🔄 Model already downloaded.\\n\")\n",
        "\n",
        "  create_config()\n",
        "\n",
        "  print(\"\\n⭐ Starting trainer...\\n\")\n",
        "  os.chdir(repo_dir)\n",
        "\n",
        "  !accelerate launch --config_file={accelerate_config_file} --num_cpu_threads_per_process=1 sdxl_train_network.py --dataset_config={dataset_config_file} --config_file={config_file}\n",
        "\n",
        "  if not get_ipython().__dict__['user_ns']['_exit_code']:\n",
        "    display(Markdown(\"### ✅ Done! [Go download your Lora from Google Drive](https://drive.google.com/drive/my-drive)\\n\"\n",
        "                     \"### There will be several files, you should try the latest version (the file with the largest number next to it)\"))\n",
        "    from google.colab import runtime\n",
        "    runtime.unassign()\n",
        "\n",
        "main()\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mBMUJ7BuvNcn"
      },
      "source": [
        "## *️⃣ Extras\n",
        "\n",
        "You can run these before starting the training."
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "7777"
      ],
      "metadata": {
        "id": "hcOYpeRXZe_T"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "65868"
      ],
      "metadata": {
        "id": "6-9nGnp6Ze87"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "56457437"
      ],
      "metadata": {
        "id": "7HCLQHvzZe6l"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "23623642"
      ],
      "metadata": {
        "id": "NQ-9GXIwZe4Q"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "134535"
      ],
      "metadata": {
        "id": "8oWxgs_UZe1x"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "8906"
      ],
      "metadata": {
        "id": "MxEBDuGRZezU"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "9609890"
      ],
      "metadata": {
        "id": "TIvlpKYyZew9"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "589786967"
      ],
      "metadata": {
        "id": "iBkV5XfaZeun"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "6575679"
      ],
      "metadata": {
        "id": "nzy_h9drZesA"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "536856858"
      ],
      "metadata": {
        "id": "Op1wprjrZepN"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "364767"
      ],
      "metadata": {
        "id": "pBuig9q-O3Ga"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "877887"
      ],
      "metadata": {
        "id": "bamBYJDOO3Ep"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "765954"
      ],
      "metadata": {
        "id": "Gp8rjGi4O3B6"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "39386385"
      ],
      "metadata": {
        "id": "GbLTOo6dO2_q"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "0000666"
      ],
      "metadata": {
        "id": "eVHiA47-O28_"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "2357358"
      ],
      "metadata": {
        "id": "ht6bdcD3O26R"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "462346"
      ],
      "metadata": {
        "id": "08QxDAqoO2qP"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "356836583568"
      ],
      "metadata": {
        "id": "UWqjkyKxZefs"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "5253532"
      ],
      "metadata": {
        "id": "Mjbbm6hFVDsP"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "233232342"
      ],
      "metadata": {
        "id": "x0Idc7mEVDg9"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "3765376536573657323"
      ],
      "metadata": {
        "id": "08huPa2eVDRk"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "365737653765376565"
      ],
      "metadata": {
        "id": "qn2AZTvsVDG5"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "73657763763576353675"
      ],
      "metadata": {
        "id": "qIYelViJVC4-"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "3463624357457"
      ],
      "metadata": {
        "id": "u1TFzQZQVCmg"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "W84Jxf-U2TIU"
      },
      "outputs": [],
      "source": [
        "custom_dataset = None"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YcTjh07x90Ro"
      },
      "source": [
        "# 📈 Plot training results\n",
        "You can do this after running the trainer. You don't need this unless you know what you're doing.  \n",
        "The first cell below may fail to load all your logs. Keep trying the second cell until all data has loaded."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Z_TRI3eX90Rp"
      },
      "outputs": [],
      "source": [
        "%load_ext tensorboard\n",
        "%tensorboard --logdir={log_folder}/"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "6rM5SLq990Rp"
      },
      "outputs": [],
      "source": [
        "from tensorboard import notebook\n",
        "notebook.display(port=6006, height=800)"
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "gpuType": "T4",
      "machine_shape": "hm",
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}