{"cells":[{"cell_type":"markdown","metadata":{"id":"rmCPmqFL6hCQ"},"source":["# š Anima Lora Trainer\n","\n","ā **Colab Premium is not needed** but recommended for larger datasets. Ideally you'd be changing the runtime to an A100 and use the maximum batch size. \n","\n","\n","\n","This colab is based on the work of [Kohya-ss](https://github.com/kohya-ss/sd-scripts) and [Hollowstrawberry](https://github.com/hollowstrawberry/kohya-colab). 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** | [](https://github.com/uYouUs/kohya-colab) | | |\n","| ā **Lora Trainer** | [](https://github.com/uYouUs/kohya-colab/blob/main/Lora_Trainer.ipynb) | [](https://colab.research.google.com/github/uYouUs/kohya-colab/blob/main/Lora_Trainer.ipynb) | [](https://colab.research.google.com/github/uYouUs/kohya-colab/blob/main/Spanish_Lora_Trainer.ipynb) |\n","| š **Simple XL Trainer** | [](https://github.com/uYouUs/kohya-colab/blob/main/Simple_XL_Trainer.ipynb) | [](https://colab.research.google.com/github/uYouUs/kohya-colab/blob/main/Simple_XL_Trainer.ipynb) | [](https://colab.research.google.com/github/uYouUs/kohya-colab/blob/main/Spanish_Simple_XL_Trainer.ipynb) |\n","| š **XL Lora Trainer** | [](https://github.com/uYouUs/kohya-colab/blob/main/Lora_Trainer_XL.ipynb) | [](https://colab.research.google.com/github/uYouUs/kohya-colab/blob/main/Lora_Trainer_XL.ipynb) | [](https://colab.research.google.com/github/uYouUs/kohya-colab/blob/main/Spanish_Lora_Trainer_XL.ipynb) |\n","| š **Advanced XL Trainer** | [](https://github.com/uYouUs/kohya-colab/blob/main/Advanced_Trainer_XL.ipynb) | [](https://colab.research.google.com/github/uYouUs/kohya-colab/blob/main/Advanced_Trainer_XL.ipynb) | [](https://colab.research.google.com/github/uYouUs/kohya-colab/blob/main/Spanish_Advanced_Trainer_XL.ipynb) |\n","| š **Anima Lora Trainer** | [](https://github.com/uYouUs/kohya-colab/blob/main/Lora_Trainer_Anima.ipynb) | [](https://colab.research.google.com/github/uYouUs/kohya-colab/blob/main/Lora_Trainer_Anima.ipynb) | |"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","id":"OglZzI_ujZq-"},"outputs":[],"source":["import os\n","import re\n","import toml\n","import pathlib\n","import threading\n","import zipfile\n","from time import time\n","from IPython.display import Markdown, display\n","\n","# These carry information from past executions\n","if \"old_model_url\" not in globals():\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","if \"model_cached\" not in globals():\n"," model_cached = False\n","if \"diffusers_model\" not in globals():\n"," diffusers_model = 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 \"continue_from_lora\" not in globals():\n"," continue_from_lora = \"\"\n","if \"override_config_file\" not in globals():\n"," override_config_file = None\n","\n","COLAB = True\n","SOURCE = \"https://github.com/uYouUs/sd-scripts\"\n","BRANCH = \"dev\"\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 = \"\" #@param {type:\"string\"}\n","project_name = project_name.strip()\n","\n","#@markdown ### š 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/my_dataset.zip\" #@param {type:\"string\"}\n","unzip = True #@param {type:\"boolean\"}\n","\n","#@markdown Only check this if dataset is ready in your google drive and not a zip file. Ignore this otherwise.\n","use_drive_dataset = False #@param {type:\"boolean\"}\n","drive_dataset = \"/content/drive/MyDrive/Loras/example/dataset\" #@param {type:\"string\"}\n","\n","#@markdown The output loras will be saved to this directory + `project_name`. Leave like this for them to go to a folder titled Loras in google drive.
\n","#@markdown This setting is not used when `use_drive_dataset` is enabled. Will instead save to a folder, `output`, outside of `drive_dataset` location.\n","output_location = \"/content/drive/MyDrive/Loras/\" #@param {type:\"string\"}\n","#@markdown Decide the model that will be downloaded and used for training. You can also choose your own by pasting its download link, or a file in your Google Drive starting with /`content/drive/MyDrive`.\n","training_model = \"Anima Base v1.0\" #@param [\"Anima Base v1.0\", \"Anima Preview\", \"Anima Preview2\", \"Anima Preview3\"]\n","optional_custom_training_model = \"\" #param {type:\"string\"}\n","#markdown Using a diffusers model utilizes less resources. The options above will work with or without diffusers.\n","load_diffusers = True #param {type:\"boolean\"}\n","force_dif = False if optional_custom_training_model and not load_diffusers else True # Built in models will force use diffuser versions as they handle caching between swapping models\n","#@markdown Civitai API token for models that require login.\n","civitoken = \"\" #@param {type:\"string\"}\n","#@markdown Use wandb if you want to visualize the progress of your training over time.\n","wandb_key = \"\" #@param {type:\"string\"}\n","model_url = None\n","if optional_custom_training_model:\n"," model_url = optional_custom_training_model\n"," model_url = model_url.strip()\n"," model_file = \"/content/custom_model.safetensors\"\n","elif \"Anima Base v1.0\" in training_model:\n"," anima_model = \"base-v1.0\"\n","elif \"Anima Preview3\" in training_model:\n"," anima_model = \"preview3-base\"\n","elif \"Anima Preview2\" in training_model:\n"," anima_model =\"preview2\"\n","else:\n"," anima_model = \"preview\"\n","\n","\n","#@markdown ### ā¶ļø Processing\n","resolution = 1024 #param {type:\"slider\", min:768, max:1536, step:128}\n","caption_extension = \".txt\" #@param [\".txt\", \".caption\"]\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.
\n","shuffle_tags = True #@param {type:\"boolean\"}\n","activation_tags = \"1\" #@param [0,1,2,3]\n","keep_tokens = int(activation_tags)\n","\n","#@markdown ### ā¶ļø Steps
\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 = 2 #@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.
\n","#@markdown One epoch is a number of steps equal to: your number of images multiplied by their repeats, divided by batch size.
\n","preferred_unit = \"Epochs\" #@param [\"Epochs\", \"Steps\"]\n","how_many = 10 #@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 = 1 #@param {type:\"number\"}\n","keep_only_last_n_epochs = 10 #@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 your Lora produces black images, lower the unet and text encoder to 1e-4 and 1e-5 respectively, or even lower.
\n","#markdown If you're training a style you can choose to set the text encoder to 0.\n","unet_lr = 15e-5 #@param {type:\"number\"}\n","text_encoder_lr = 6e-5 #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 3 restarts.\n","lr_scheduler = \"cosine\" #@param [\"constant\", \"cosine\", \"cosine_with_restarts\", \"constant_with_warmup\", \"linear\", \"polynomial\"]\n","lr_scheduler_number = 3 #@param {type:\"number\"}\n","#@markdown Steps spent \"warming up\" the learning rate during training for efficiency. I recommend leaving it at 5%.\n","lr_warmup_ratio = 0.05 #@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 = 8.0 #@param {type:\"slider\", min:0.0, max:16.0, step:0.5}\n","#@markdown Multinoise may help with color balance (darker darks, lighter lights).\n","multinoise = True #@param {type:\"boolean\"}\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 Anima values for the following settings:\n","\n","#@markdown | type | network_dim | network_alpha | conv_dim | conv_alpha |\n","#@markdown | :---: | :---: | :---: | :---: | :---: |\n","#@markdown | Regular LoRA | 32 | 16 | | |\n","\n","\n","#@markdown More dim means larger Lora, it can hold more information but more isn't always better.\n","network_dim = 32 #@param {type:\"slider\", min:1, max:64, step:1}\n","network_alpha = 16 #@param {type:\"slider\", min:1, max:64, 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:64, step:1}\n","conv_alpha = 1 #@param {type:\"slider\", min:1, max:64, step:1}\n","\n","network_module = \"networks.lora_anima\"\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 = 2 #@param {type:\"slider\", min:1, max:16, step:1}\n","#@markdown Use torch on the free tier as flash is not supported by T4. Otherwise use flash.\n","cross_attention = \"torch\" #@param [\"torch\", \"flash\"]\n","#@markdown If you're on an A100 or supported hardware you should enable bf16. If you are running out of memory on the free tier, try `full_fp16`.\n","mixed_precision = \"full_fp16\" #@param [\"bf16\", \"full_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 = True #@param {type:\"boolean\"}\n","cache_latents_to_drive = True #@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 = \"AdamW8bit\" #@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]`
\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 = \"weight_decay=0.1 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 the recommended box is checked, the following recommended values will override any previous settings:
\n","#@markdown `unet_lr=1`, `network_alpha=network_dim`\n","recommended_values = True #@param {type:\"boolean\"}\n","\n","if any(opt in optimizer.lower() for opt in [\"dadapt\", \"prodigy\"]):\n"," if recommended_values:\n"," unet_lr = 1\n"," network_alpha = network_dim\n","\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","\n","#@markdown ### ā¶ļø Generate Sample Image\n","#@markdown Generate a sample image using the lora after every saved epoch using the following prompt:
\n","#@markdown Add optional generation settings at the end by using `--w {width} --h {height} --d {seed} --s {steps} --l {cfg}`
\n","#@markdown Example prompt: `1girl, blonde hair, smiling --w 1024 --h 1024 --d 173371316 --s 20 --l 5`
\n","#@markdown This setting requires more VRAM at generation. Training may slow down slightly after generating an image as things are shifted in and out of vram. Don't use this if you are trying to maximize training time.\n","sample_prompt = \"\" #@param {type:\"string\"}\n","\n","#@markdown ### ā¶ļø Ready\n","#@markdown You can now run this cell to cook your Lora. Good luck!
\n","\n","\n","# š©āš» Cool code goes here\n","\n","root_dir = \"/content\" if COLAB else pathlib.Path.home() / \"Loras\"\n","deps_dir = os.path.join(root_dir, \"deps\")\n","repo_dir = os.path.join(root_dir, \"kohya-trainer\")\n","model_dir = os.path.join(repo_dir, \"model\")\n","\n","main_dir = os.path.join(root_dir, \"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(output_location, project_name, \"output\")\n","if use_drive_dataset:\n"," images_folder = drive_dataset\n"," output_folder = os.path.abspath(os.path.join(drive_dataset, os.pardir, \"output\"))\n","\n","\n","config_file = os.path.join(output_location, project_name, \"training_config.toml\")\n","dataset_config_file = os.path.join(output_location, project_name, \"dataset_config.toml\")\n","accelerate_config_file = os.path.join(repo_dir, \"accelerate_config/config.yaml\")\n","\n","anima = \"anima-\"+anima_model+\".safetensors\"\n","if not optional_custom_training_model:\n"," model_file = os.path.join(model_dir, \"split_files/diffusion_models/\"+anima)\n","qwen3_file = os.path.join(model_dir, \"split_files/text_encoders/qwen_3_06b_base.safetensors\")\n","vae_file = os.path.join(model_dir, \"split_files/vae/qwen_image_vae.safetensors\")\n","\n","def install_dependencies():\n"," print(\"Cloning Kohya\")\n"," os.chdir(root_dir)\n"," !git clone {SOURCE} {repo_dir}\n"," os.chdir(repo_dir)\n"," if BRANCH:\n"," !git checkout {BRANCH}\n"," if COMMIT:\n"," !git reset --hard {COMMIT}\n"," !wget https://raw.githubusercontent.com/uYouUs/kohya-colab/main/train_network_xl_wrapper.py -q -O train_network_xl_wrapper.py\n"," !wget https://raw.githubusercontent.com//uYouUs/kohya-colab/main/dracula.py -q -O dracula.py\n","\n"," #!apt -y update -qq\n"," !pip install uv\n"," #!pip install accelerate==1.2.1 opencv-python==4.10.0.84 einops==0.8.0 \\ #debug, slows down startup if active\n"," !uv pip install diffusers==0.36.0 transformers==4.57.6 bitsandbytes==0.49.1 pytorch-lightning==1.9.0 voluptuous==0.13.1 \\\n"," invisible-watermark==0.2.0 prodigyopt==1.0.0 \\\n"," dadaptation==3.1 lion-pytorch==0.1.2 ftfy==6.1.1 --no-progress\n"," # toml==0.10.2 safetensors pygments wandb imagesize==1.4.1 #debug\n"," !uv pip install -e . --no-progress\n"," if cross_attention == \"flash\":\n"," !uv pip install -q flash-attn\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, model_url\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"," # Find the folders and files\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"," # Validation\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"," test_files = []\n"," for f in files:\n"," if not f.lower().endswith((caption_extension, \".npz\")) and not f.lower().endswith(supported_types):\n"," print(f\"š„ Error: Invalid file in dataset: \\\"{f}\\\". Aborting.\")\n"," return\n"," for ff in test_files:\n"," if f.endswith(supported_types) and ff.endswith(supported_types) \\\n"," and os.path.splitext(f)[0] == os.path.splitext(ff)[0]:\n"," print(f\"š„ Error: The files {f} and {ff} cannot have the same name. Aborting.\")\n"," return\n"," test_files.append(f)\n","\n"," if caption_extension and not [txt for txt in files if txt.lower().endswith(caption_extension)]:\n"," caption_extension = \"\"\n"," if continue_from_lora and not (continue_from_lora.endswith(\".safetensors\") and os.path.exists(continue_from_lora)):\n"," print(f\"š„ Error: Invalid path to existing Lora. Example: /content/drive/MyDrive/Loras/example.safetensors\")\n"," return\n","\n"," # Pretty stuff\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 > 10000:\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\": 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"," \"network_weights\": continue_from_lora if continue_from_lora else None\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"," \"qwen3\": qwen3_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"," \"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\": 3,\n"," \"persistent_data_loader_workers\": True,\n"," \"mixed_precision\": \"fp16\" if mixed_precision == \"full_fp16\" else mixed_precision,\n"," \"full_bf16\": mixed_precision == \"bf16\",\n"," \"full_fp16\": mixed_precision == \"full_fp16\",\n"," \"cache_latents\": cache_latents,\n"," \"cache_latents_to_disk\": cache_latents_to_drive,\n"," \"cache_text_encoder_outputs\": cache_text_encoder_outputs,\n"," \"min_timestep\": 0,\n"," \"max_timestep\": 1000,\n"," \"prior_loss_weight\": 1.0,\n"," \"multires_noise_iterations\": 6 if multinoise else None,\n"," \"multires_noise_discount\": 0.3 if multinoise else None,\n"," },\n"," \"saving_arguments\": {\n"," \"save_precision\": \"bf16\",\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"," \"wandb_api_key\": wandb_key if wandb_key else None,\n"," \"log_with\": \"wandb\" if wandb_key else None,\n"," \"sample_prompts\": prompt_file if sample_prompt else None,\n"," \"sample_every_n_epochs\": save_every_n_epochs if sample_prompt else None,\n"," \"sample_sampler\": \"euler_a\" if sample_prompt else None,\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_tags 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\": 4096,\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\n"," real_model_url = model_url # Keep model url intact to compare against old model url to detect a change.\n","\n"," # Test for google drive model\n"," if real_model_url.startswith(\"/content/drive/\"):\n"," model_file = real_model_url\n"," if model_file.lower().endswith(\".safetensors\") or model_file.lower().endswith(\".ckpt\"):\n"," print(f\"\\nTraing will be done with drive model at {model_file}, check it is valid if you recieve errors\\n\")\n"," return True\n"," return False\n","\n"," else:\n"," # Define local filename\n"," if not model_file or not model_file.endswith((\".ckpt\", \".safetensors\")):\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"," # HuggingFace\n"," if m := re.search(r\"(?:https?://)?(?:www\\.)?huggingface\\.co/[^/]+/[^/]+/blob\", real_model_url):\n"," real_model_url = real_model_url.replace(\"blob\", \"resolve\")\n"," # Civitai\n"," elif m := re.search(r\"(?:https?://)?(?:www\\\\.)?civitai\\.com/models/([0-9]+)(/[A-Za-z0-9-_]+)?\", real_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]+)\", real_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 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"," if civitoken:\n"," real_model_url = real_model_url+\"?token=\"+civitoken\n"," # Download checkpoint\n"," !apt -y install aria2 -qq\n"," !aria2c \"{real_model_url}\" --console-log-level=warn -c -s 16 -x 16 -k 10M -d / -o \"{model_file}\"\n","\n"," # Validation\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"," 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 getModel():\n"," global diffusers_model, model_url, model_file, old_model_url\n"," #!pip install transformers==4.47.1 diffusers==0.32.2 jax==0.4.33 jaxlib==0.4.33 huggingface_hub==0.27.1 flax==0.10.2\n"," from huggingface_hub import snapshot_download\n"," from huggingface_hub.utils import disable_progress_bars\n"," disable_progress_bars() # Disable model download progress bars to clean up output from threading mess\n"," #snapshot_download(repo_id=vae_file, allow_patterns=[\"*model.safetensors\", \"*.json\"]) # Download Vae\n"," if not optional_custom_training_model:\n"," snapshot_download(repo_id=\"circlestone-labs/Anima\", allow_patterns=[\"*qwen_image_vae.safetensors\", \"*qwen_3_06b_base.safetensors\", f\"*{anima}\"], local_dir=f\"{repo_dir}/model\")\n"," elif old_model_url != model_url or not model_file or not os.path.exists(model_file):\n"," print(\"\\nš Getting model...\")\n"," if not download_model():\n"," print(\"\\nš„ Error: The model you specified is invalid or corrupted.\"\n"," \"\\nIf you're using an URL, please check that the model is accessible without being logged in.\"\n"," \"\\nYou can try civitai or huggingface URLs, or a path in your Google Drive starting with /content/drive/MyDrive\")\n"," return\n"," snapshot_download(repo_id=\"circlestone-labs/Anima\", allow_patterns=[\"*qwen_image_vae.safetensors\", \"*qwen_3_06b_base.safetensors\"], local_dir=f\"{repo_dir}/model\")\n"," print()\n"," else:\n"," print(\"\\nš Model already downloaded.\\n\")\n"," old_model_url = model_url # only update old model url if we successfully downloaded it to prevent not downloading model if it previously failed on a change.\n","\n","def unzipset():\n"," if COLAB and not os.path.exists('/content/drive'):\n"," from google.colab import drive\n"," print(\"\\nš Connecting to Google Drive...\")\n"," drive.mount('/content/drive')\n","\n"," print(\"\\nUnzipping\")\n"," os.makedirs(images_folder, exist_ok=True)\n"," with zipfile.ZipFile(zip, 'r') as f:\n"," f.extractall(images_folder)\n"," print(\"\\nā Done unzipping\")\n","\n","def generateSample(): # Generate required files for sample generation\n"," global output_folder, sample_prompt, prompt_file\n"," if sample_prompt:\n"," prompt_file = os.path.abspath(os.path.join(output_folder, \"sample\"))\n"," if not os.path.exists(prompt_file): # Make sample directory so prompt file creation does not fail.\n"," os.mkdir(prompt_file)\n"," prompt_file = os.path.join(prompt_file, \"prompt.txt\")\n"," with open(prompt_file, \"w\") as f:\n"," f.write(sample_prompt)\n","\n","def thInstallDep():\n"," global 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. \\nWaiting on Model...\\n\")\n","\n","def main():\n"," global dependencies_installed, unzip, sample_prompt\n"," threadList = []\n"," # Download model with a thread\n"," thr1 = threading.Thread(target = getModel)\n"," threadList.append(thr1)\n"," thr1.start()\n","\n"," if not dependencies_installed: # Begin installing dependencies while user gives gdrive permissions\n"," thr2 = threading.Thread(target = thInstallDep)\n"," threadList.append(thr2)\n"," thr2.start()\n"," else:\n"," print(\"\\nā Dependencies already installed.\")\n","\n"," if unzip and not use_drive_dataset: # Unzip dataset with a thread\n"," thr3 = threading.Thread(target = unzipset)\n"," threadList.append(thr3)\n"," thr3.start()\n","\n"," elif COLAB and not os.path.exists('/content/drive'): # Request drive access for dataset validatation if we did not unzip it\n"," from google.colab import drive\n"," print(\"\\nš Connecting to Google Drive...\")\n"," drive.mount('/content/drive')\n","\n"," for th in threadList: # Make sure model and or set are done before continuing\n"," th.join()\n","\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"," generateSample() # Make sure sample file exists prior to creating config file\n"," create_config()\n","\n"," print(\"\\nā Starting trainer...\\n\")\n"," os.chdir(repo_dir)\n","\n"," !accelerate launch --quiet --config_file={accelerate_config_file} --num_cpu_threads_per_process=2 --num_processes=2 anima_train_network.py --dataset_config={dataset_config_file} --config_file={config_file} --attn_mode={cross_attention}\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","\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":["#@markdown ### Continue\n","\n","#@markdown Here you can write a path in your Google Drive to load an existing Lora file to continue training on.
\n","#@markdown **Warning:** It's not the same as one long training session. The epochs start from scratch, and it may have worse results.\n","continue_from_lora = \"\" #@param {type:\"string\"}\n","if continue_from_lora and not continue_from_lora.startswith(\"/content/drive/MyDrive\"):\n"," import os\n"," continue_from_lora = os.path.join(\"/content/drive/MyDrive\", continue_from_lora)\n"],"metadata":{"cellView":"form","id":"-cnM6xM_E6Jx"},"execution_count":null,"outputs":[]},{"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.\n","\n","When using google drive for datasets, the default format is:\n","`content/drive/MyDrive/Loras/example/dataset/normal_images`\n","\n","For in-drive unzipping if dataset, the default location is:\n","`content/Loras/example/dataset/normal_images`\n"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"Y037lagnJWmn"},"outputs":[],"source":["custom_dataset = \"\"\"\n","[[datasets]]\n","\n","[[datasets.subsets]]\n","image_dir = \"/content/drive/MyDrive/Loras/example/dataset/good_images\"\n","num_repeats = 3\n","\n","[[datasets.subsets]]\n","image_dir = \"/content/drive/MyDrive/Loras/example/dataset/normal_images\"\n","num_repeats = 1\n","\n","\"\"\""]},{"cell_type":"code","execution_count":null,"metadata":{"id":"W84Jxf-U2TIU"},"outputs":[],"source":["custom_dataset = None"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","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/my_dataset.zip\" #@param {type:\"string\"}\n","extract_to = \"/content/drive/MyDrive/Loras/example/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":{"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/drive/MyDrive/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":"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","provenance":[{"file_id":"https://github.com/uYouUs/kohya-colab/blob/main/Lora_Trainer_Anima.ipynb","timestamp":1780676399434}]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0}