Commit ·
561e1e6
0
Parent(s):
Super-squash branch 'main' using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +62 -0
- BaseSDTrainProcess.py +2561 -0
- anime_style_flux2k_9b_000000024.safetensors +3 -0
- anime_style_flux2k_9b_000000048.safetensors +3 -0
- anime_style_flux2k_9b_000000072.safetensors +3 -0
- anime_style_flux2k_9b_000000096.safetensors +3 -0
- anime_style_flux2k_9b_000000120.safetensors +3 -0
- anime_style_flux2k_9b_000000144.safetensors +3 -0
- anime_style_flux2k_9b_000000168.safetensors +3 -0
- anime_style_flux2k_9b_000000192.safetensors +3 -0
- anime_style_flux2k_9b_000000216.safetensors +3 -0
- anime_style_flux2k_9b_000000240.safetensors +3 -0
- anime_style_flux2k_9b_000000264.safetensors +3 -0
- anime_style_flux2k_9b_000000288.safetensors +3 -0
- anime_style_flux2k_9b_000000312.safetensors +3 -0
- anime_style_flux2k_9b_000000336.safetensors +3 -0
- anime_style_flux2k_9b_000000360.safetensors +3 -0
- anime_style_flux2k_9b_000000384.safetensors +3 -0
- anime_style_flux2k_9b_000000408.safetensors +3 -0
- anime_style_flux2k_9b_000000432.safetensors +3 -0
- anime_style_flux2k_9b_000000456.safetensors +3 -0
- anime_style_flux2k_9b_000000480.safetensors +3 -0
- anime_style_flux2k_9b_000000504.safetensors +3 -0
- anime_style_flux2k_9b_000000528.safetensors +3 -0
- anime_style_flux2k_9b_000000552.safetensors +3 -0
- anime_style_flux2k_9b_000000576.safetensors +3 -0
- anime_style_flux2k_9b_000000600.safetensors +3 -0
- anime_style_flux2k_9b_000000624.safetensors +3 -0
- anime_style_flux2k_9b_000000648.safetensors +3 -0
- anime_style_flux2k_9b_000000672.safetensors +3 -0
- anime_style_flux2k_9b_000000696.safetensors +3 -0
- anime_style_flux2k_9b_000000720.safetensors +3 -0
- anime_style_flux2k_9b_000000744.safetensors +3 -0
- anime_style_flux2k_9b_000000768.safetensors +3 -0
- anime_style_flux2k_9b_000001464.safetensors +3 -0
- anime_style_flux2k_9b_000001488.safetensors +3 -0
- anime_style_flux2k_9b_000001512.safetensors +3 -0
- anime_style_flux2k_9b_000001536.safetensors +3 -0
- anime_style_flux2k_9b_000001560.safetensors +3 -0
- anime_style_flux2k_9b_000001584.safetensors +3 -0
- anime_style_flux2k_9b_000001608.safetensors +3 -0
- anime_style_flux2k_9b_000001632.safetensors +3 -0
- anime_style_flux2k_9b_000001656.safetensors +3 -0
- anime_style_flux2k_9b_000001680.safetensors +3 -0
- anime_style_flux2k_9b_000001704.safetensors +3 -0
- anime_style_flux2k_9b_000001728.safetensors +3 -0
- anime_style_flux2k_9b_000001752.safetensors +3 -0
- anime_style_flux2k_9b_000001776.safetensors +3 -0
- anime_style_flux2k_9b_000001800.safetensors +3 -0
- anime_style_flux2k_9b_000001824.safetensors +3 -0
.gitattributes
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.avro filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.lz4 filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.mds filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
# Audio files - uncompressed
|
| 40 |
+
*.pcm filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
*.sam filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
*.raw filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
# Audio files - compressed
|
| 44 |
+
*.aac filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
*.flac filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
*.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
*.ogg filter=lfs diff=lfs merge=lfs -text
|
| 48 |
+
*.wav filter=lfs diff=lfs merge=lfs -text
|
| 49 |
+
# Image files - uncompressed
|
| 50 |
+
*.bmp filter=lfs diff=lfs merge=lfs -text
|
| 51 |
+
*.gif filter=lfs diff=lfs merge=lfs -text
|
| 52 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
| 53 |
+
*.tiff filter=lfs diff=lfs merge=lfs -text
|
| 54 |
+
# Image files - compressed
|
| 55 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 56 |
+
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
| 57 |
+
*.webp filter=lfs diff=lfs merge=lfs -text
|
| 58 |
+
# Video files - compressed
|
| 59 |
+
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
+
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
nsfw_aio_v2/loss_log.db filter=lfs diff=lfs merge=lfs -text
|
| 62 |
+
nsfw_aio_v2/loss_log.db-wal filter=lfs diff=lfs merge=lfs -text
|
BaseSDTrainProcess.py
ADDED
|
@@ -0,0 +1,2561 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 2 |
+
import glob
|
| 3 |
+
import inspect
|
| 4 |
+
import json
|
| 5 |
+
import random
|
| 6 |
+
import shutil
|
| 7 |
+
from collections import OrderedDict
|
| 8 |
+
import os
|
| 9 |
+
import re
|
| 10 |
+
import traceback
|
| 11 |
+
from typing import Union, List, Optional
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import yaml
|
| 15 |
+
from diffusers import T2IAdapter, ControlNetModel
|
| 16 |
+
from diffusers.training_utils import compute_density_for_timestep_sampling
|
| 17 |
+
from safetensors.torch import save_file, load_file
|
| 18 |
+
# from lycoris.config import PRESET
|
| 19 |
+
from torch.utils.data import DataLoader
|
| 20 |
+
import torch
|
| 21 |
+
import torch.backends.cuda
|
| 22 |
+
from huggingface_hub import HfApi, interpreter_login
|
| 23 |
+
from toolkit.memory_management import MemoryManager
|
| 24 |
+
|
| 25 |
+
from toolkit.basic import value_map
|
| 26 |
+
from toolkit.clip_vision_adapter import ClipVisionAdapter
|
| 27 |
+
from toolkit.custom_adapter import CustomAdapter
|
| 28 |
+
from toolkit.data_loader import get_dataloader_from_datasets, trigger_dataloader_setup_epoch
|
| 29 |
+
from toolkit.data_transfer_object.data_loader import FileItemDTO, DataLoaderBatchDTO
|
| 30 |
+
from toolkit.ema import ExponentialMovingAverage
|
| 31 |
+
from toolkit.embedding import Embedding
|
| 32 |
+
from toolkit.image_utils import show_tensors, show_latents, reduce_contrast
|
| 33 |
+
from toolkit.ip_adapter import IPAdapter
|
| 34 |
+
from toolkit.lora_special import LoRASpecialNetwork
|
| 35 |
+
from toolkit.lorm import convert_diffusers_unet_to_lorm, count_parameters, print_lorm_extract_details, \
|
| 36 |
+
lorm_ignore_if_contains, lorm_parameter_threshold, LORM_TARGET_REPLACE_MODULE
|
| 37 |
+
from toolkit.lycoris_special import LycorisSpecialNetwork
|
| 38 |
+
from toolkit.models.decorator import Decorator
|
| 39 |
+
from toolkit.network_mixins import Network
|
| 40 |
+
from toolkit.optimizer import get_optimizer
|
| 41 |
+
from toolkit.paths import CONFIG_ROOT
|
| 42 |
+
from toolkit.progress_bar import ToolkitProgressBar
|
| 43 |
+
from toolkit.reference_adapter import ReferenceAdapter
|
| 44 |
+
from toolkit.sampler import get_sampler
|
| 45 |
+
from toolkit.saving import save_t2i_from_diffusers, load_t2i_model, save_ip_adapter_from_diffusers, \
|
| 46 |
+
load_ip_adapter_model, load_custom_adapter_model
|
| 47 |
+
|
| 48 |
+
from toolkit.scheduler import get_lr_scheduler
|
| 49 |
+
from toolkit.sd_device_states_presets import get_train_sd_device_state_preset
|
| 50 |
+
from toolkit.stable_diffusion_model import StableDiffusion
|
| 51 |
+
|
| 52 |
+
from jobs.process import BaseTrainProcess
|
| 53 |
+
from toolkit.metadata import get_meta_for_safetensors, load_metadata_from_safetensors, add_base_model_info_to_meta, \
|
| 54 |
+
parse_metadata_from_safetensors
|
| 55 |
+
from toolkit.train_tools import get_torch_dtype, LearnableSNRGamma, apply_learnable_snr_gos, apply_snr_weight
|
| 56 |
+
import gc
|
| 57 |
+
|
| 58 |
+
from tqdm import tqdm
|
| 59 |
+
|
| 60 |
+
from toolkit.config_modules import SaveConfig, LoggingConfig, SampleConfig, NetworkConfig, TrainConfig, ModelConfig, \
|
| 61 |
+
GenerateImageConfig, EmbeddingConfig, DatasetConfig, preprocess_dataset_raw_config, AdapterConfig, GuidanceConfig, validate_configs, \
|
| 62 |
+
DecoratorConfig
|
| 63 |
+
from toolkit.logging_aitk import create_logger
|
| 64 |
+
from diffusers import FluxTransformer2DModel
|
| 65 |
+
from toolkit.accelerator import get_accelerator, unwrap_model
|
| 66 |
+
from toolkit.print import print_acc
|
| 67 |
+
from accelerate import Accelerator
|
| 68 |
+
import transformers
|
| 69 |
+
import diffusers
|
| 70 |
+
import hashlib
|
| 71 |
+
|
| 72 |
+
from toolkit.util.blended_blur_noise import get_blended_blur_noise
|
| 73 |
+
from toolkit.util.get_model import get_model_class
|
| 74 |
+
from toolkit.basic import flush
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class BaseSDTrainProcess(BaseTrainProcess):
|
| 78 |
+
|
| 79 |
+
def __init__(self, process_id: int, job, config: OrderedDict, custom_pipeline=None):
|
| 80 |
+
super().__init__(process_id, job, config)
|
| 81 |
+
self.accelerator: Accelerator = get_accelerator()
|
| 82 |
+
if self.accelerator.is_local_main_process:
|
| 83 |
+
transformers.utils.logging.set_verbosity_warning()
|
| 84 |
+
diffusers.utils.logging.set_verbosity_error()
|
| 85 |
+
else:
|
| 86 |
+
transformers.utils.logging.set_verbosity_error()
|
| 87 |
+
diffusers.utils.logging.set_verbosity_error()
|
| 88 |
+
|
| 89 |
+
self.sd: StableDiffusion
|
| 90 |
+
self.embedding: Union[Embedding, None] = None
|
| 91 |
+
|
| 92 |
+
self.custom_pipeline = custom_pipeline
|
| 93 |
+
self.step_num = 0
|
| 94 |
+
self.start_step = 0
|
| 95 |
+
self.epoch_num = 0
|
| 96 |
+
self.last_save_step = 0
|
| 97 |
+
# start at 1 so we can do a sample at the start
|
| 98 |
+
self.grad_accumulation_step = 1
|
| 99 |
+
# if true, then we do not do an optimizer step. We are accumulating gradients
|
| 100 |
+
self.is_grad_accumulation_step = False
|
| 101 |
+
self.device = str(self.accelerator.device)
|
| 102 |
+
self.device_torch = self.accelerator.device
|
| 103 |
+
network_config = self.get_conf('network', None)
|
| 104 |
+
if network_config is not None:
|
| 105 |
+
self.network_config = NetworkConfig(**network_config)
|
| 106 |
+
else:
|
| 107 |
+
self.network_config = None
|
| 108 |
+
self.train_config = TrainConfig(**self.get_conf('train', {}))
|
| 109 |
+
model_config = self.get_conf('model', {})
|
| 110 |
+
self.modules_being_trained: List[torch.nn.Module] = []
|
| 111 |
+
|
| 112 |
+
# update modelconfig dtype to match train
|
| 113 |
+
model_config['dtype'] = self.train_config.dtype
|
| 114 |
+
self.model_config = ModelConfig(**model_config)
|
| 115 |
+
|
| 116 |
+
self.save_config = SaveConfig(**self.get_conf('save', {}))
|
| 117 |
+
self.sample_config = SampleConfig(**self.get_conf('sample', {}))
|
| 118 |
+
first_sample_config = self.get_conf('first_sample', None)
|
| 119 |
+
if first_sample_config is not None:
|
| 120 |
+
self.has_first_sample_requested = True
|
| 121 |
+
self.first_sample_config = SampleConfig(**first_sample_config)
|
| 122 |
+
else:
|
| 123 |
+
self.has_first_sample_requested = False
|
| 124 |
+
self.first_sample_config = self.sample_config
|
| 125 |
+
self.logging_config = LoggingConfig(**self.get_conf('logging', {}))
|
| 126 |
+
self.logger = create_logger(self.logging_config, config, self.save_root)
|
| 127 |
+
self.optimizer: torch.optim.Optimizer = None
|
| 128 |
+
self.lr_scheduler = None
|
| 129 |
+
self.data_loader: Union[DataLoader, None] = None
|
| 130 |
+
self.data_loader_reg: Union[DataLoader, None] = None
|
| 131 |
+
self.trigger_word = self.get_conf('trigger_word', None)
|
| 132 |
+
|
| 133 |
+
self.guidance_config: Union[GuidanceConfig, None] = None
|
| 134 |
+
guidance_config_raw = self.get_conf('guidance', None)
|
| 135 |
+
if guidance_config_raw is not None:
|
| 136 |
+
self.guidance_config = GuidanceConfig(**guidance_config_raw)
|
| 137 |
+
|
| 138 |
+
# store is all are cached. Allows us to not load vae if we don't need to
|
| 139 |
+
self.is_latents_cached = True
|
| 140 |
+
raw_datasets = self.get_conf('datasets', None)
|
| 141 |
+
if raw_datasets is not None and len(raw_datasets) > 0:
|
| 142 |
+
raw_datasets = preprocess_dataset_raw_config(raw_datasets)
|
| 143 |
+
self.datasets = None
|
| 144 |
+
self.datasets_reg = None
|
| 145 |
+
self.dataset_configs: List[DatasetConfig] = []
|
| 146 |
+
self.params = []
|
| 147 |
+
|
| 148 |
+
# add dataset text embedding cache to their config
|
| 149 |
+
if self.train_config.cache_text_embeddings:
|
| 150 |
+
for raw_dataset in raw_datasets:
|
| 151 |
+
raw_dataset['cache_text_embeddings'] = True
|
| 152 |
+
|
| 153 |
+
if raw_datasets is not None and len(raw_datasets) > 0:
|
| 154 |
+
for raw_dataset in raw_datasets:
|
| 155 |
+
dataset = DatasetConfig(**raw_dataset)
|
| 156 |
+
# handle trigger word per dataset
|
| 157 |
+
if dataset.trigger_word is None and self.trigger_word is not None:
|
| 158 |
+
dataset.trigger_word = self.trigger_word
|
| 159 |
+
is_caching = dataset.cache_latents or dataset.cache_latents_to_disk
|
| 160 |
+
if not is_caching:
|
| 161 |
+
self.is_latents_cached = False
|
| 162 |
+
if dataset.is_reg:
|
| 163 |
+
if self.datasets_reg is None:
|
| 164 |
+
self.datasets_reg = []
|
| 165 |
+
self.datasets_reg.append(dataset)
|
| 166 |
+
else:
|
| 167 |
+
if self.datasets is None:
|
| 168 |
+
self.datasets = []
|
| 169 |
+
self.datasets.append(dataset)
|
| 170 |
+
self.dataset_configs.append(dataset)
|
| 171 |
+
|
| 172 |
+
self.is_caching_text_embeddings = any(
|
| 173 |
+
dataset.cache_text_embeddings for dataset in self.dataset_configs
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
self.embed_config = None
|
| 177 |
+
embedding_raw = self.get_conf('embedding', None)
|
| 178 |
+
if embedding_raw is not None:
|
| 179 |
+
self.embed_config = EmbeddingConfig(**embedding_raw)
|
| 180 |
+
|
| 181 |
+
self.decorator_config: DecoratorConfig = None
|
| 182 |
+
decorator_raw = self.get_conf('decorator', None)
|
| 183 |
+
if decorator_raw is not None:
|
| 184 |
+
if not self.model_config.is_flux:
|
| 185 |
+
raise ValueError("Decorators are only supported for Flux models currently")
|
| 186 |
+
self.decorator_config = DecoratorConfig(**decorator_raw)
|
| 187 |
+
|
| 188 |
+
# t2i adapter
|
| 189 |
+
self.adapter_config = None
|
| 190 |
+
adapter_raw = self.get_conf('adapter', None)
|
| 191 |
+
if adapter_raw is not None:
|
| 192 |
+
self.adapter_config = AdapterConfig(**adapter_raw)
|
| 193 |
+
# sdxl adapters end in _xl. Only full_adapter_xl for now
|
| 194 |
+
if self.model_config.is_xl and not self.adapter_config.adapter_type.endswith('_xl'):
|
| 195 |
+
self.adapter_config.adapter_type += '_xl'
|
| 196 |
+
|
| 197 |
+
# to hold network if there is one
|
| 198 |
+
self.network: Union[Network, None] = None
|
| 199 |
+
self.adapter: Union[T2IAdapter, IPAdapter, ClipVisionAdapter, ReferenceAdapter, CustomAdapter, ControlNetModel, None] = None
|
| 200 |
+
self.embedding: Union[Embedding, None] = None
|
| 201 |
+
self.decorator: Union[Decorator, None] = None
|
| 202 |
+
|
| 203 |
+
is_training_adapter = self.adapter_config is not None and self.adapter_config.train
|
| 204 |
+
|
| 205 |
+
self.do_lorm = self.get_conf('do_lorm', False)
|
| 206 |
+
self.lorm_extract_mode = self.get_conf('lorm_extract_mode', 'ratio')
|
| 207 |
+
self.lorm_extract_mode_param = self.get_conf('lorm_extract_mode_param', 0.25)
|
| 208 |
+
# 'ratio', 0.25)
|
| 209 |
+
|
| 210 |
+
# get the device state preset based on what we are training
|
| 211 |
+
self.train_device_state_preset = get_train_sd_device_state_preset(
|
| 212 |
+
device=self.device_torch,
|
| 213 |
+
train_unet=self.train_config.train_unet,
|
| 214 |
+
train_text_encoder=self.train_config.train_text_encoder,
|
| 215 |
+
cached_latents=self.is_latents_cached,
|
| 216 |
+
train_lora=self.network_config is not None,
|
| 217 |
+
train_adapter=is_training_adapter,
|
| 218 |
+
train_embedding=self.embed_config is not None,
|
| 219 |
+
train_decorator=self.decorator_config is not None,
|
| 220 |
+
train_refiner=self.train_config.train_refiner,
|
| 221 |
+
unload_text_encoder=self.train_config.unload_text_encoder or self.is_caching_text_embeddings,
|
| 222 |
+
require_grads=False # we ensure them later
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
self.get_params_device_state_preset = get_train_sd_device_state_preset(
|
| 226 |
+
device=self.device_torch,
|
| 227 |
+
train_unet=self.train_config.train_unet,
|
| 228 |
+
train_text_encoder=self.train_config.train_text_encoder,
|
| 229 |
+
cached_latents=self.is_latents_cached,
|
| 230 |
+
train_lora=self.network_config is not None,
|
| 231 |
+
train_adapter=is_training_adapter,
|
| 232 |
+
train_embedding=self.embed_config is not None,
|
| 233 |
+
train_decorator=self.decorator_config is not None,
|
| 234 |
+
train_refiner=self.train_config.train_refiner,
|
| 235 |
+
unload_text_encoder=self.train_config.unload_text_encoder or self.is_caching_text_embeddings,
|
| 236 |
+
require_grads=True # We check for grads when getting params
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
# fine_tuning here is for training actual SD network, not LoRA, embeddings, etc. it is (Dreambooth, etc)
|
| 240 |
+
self.is_fine_tuning = True
|
| 241 |
+
if self.network_config is not None or is_training_adapter or self.embed_config is not None or self.decorator_config is not None:
|
| 242 |
+
self.is_fine_tuning = False
|
| 243 |
+
|
| 244 |
+
self.named_lora = False
|
| 245 |
+
if self.embed_config is not None or is_training_adapter:
|
| 246 |
+
self.named_lora = True
|
| 247 |
+
self.snr_gos: Union[LearnableSNRGamma, None] = None
|
| 248 |
+
self.ema: ExponentialMovingAverage = None
|
| 249 |
+
|
| 250 |
+
validate_configs(self.train_config, self.model_config, self.save_config, self.dataset_configs)
|
| 251 |
+
|
| 252 |
+
do_profiler = self.get_conf('torch_profiler', False)
|
| 253 |
+
self.torch_profiler = None if not do_profiler else torch.profiler.profile(
|
| 254 |
+
activities=[
|
| 255 |
+
torch.profiler.ProfilerActivity.CPU,
|
| 256 |
+
torch.profiler.ProfilerActivity.CUDA,
|
| 257 |
+
],
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
self.current_boundary_index = 0
|
| 261 |
+
self.steps_this_boundary = 0
|
| 262 |
+
self.num_consecutive_oom = 0
|
| 263 |
+
|
| 264 |
+
def post_process_generate_image_config_list(self, generate_image_config_list: List[GenerateImageConfig]):
|
| 265 |
+
# override in subclass
|
| 266 |
+
return generate_image_config_list
|
| 267 |
+
|
| 268 |
+
def sample(self, step=None, is_first=False):
|
| 269 |
+
if not self.accelerator.is_main_process:
|
| 270 |
+
return
|
| 271 |
+
flush()
|
| 272 |
+
sample_folder = os.path.join(self.save_root, 'samples')
|
| 273 |
+
gen_img_config_list = []
|
| 274 |
+
|
| 275 |
+
sample_config = self.first_sample_config if is_first else self.sample_config
|
| 276 |
+
start_seed = sample_config.seed
|
| 277 |
+
current_seed = start_seed
|
| 278 |
+
|
| 279 |
+
test_image_paths = []
|
| 280 |
+
if self.adapter_config is not None and self.adapter_config.test_img_path is not None:
|
| 281 |
+
test_image_path_list = self.adapter_config.test_img_path
|
| 282 |
+
# divide up images so they are evenly distributed across prompts
|
| 283 |
+
for i in range(len(sample_config.prompts)):
|
| 284 |
+
test_image_paths.append(test_image_path_list[i % len(test_image_path_list)])
|
| 285 |
+
|
| 286 |
+
for i in range(len(sample_config.prompts)):
|
| 287 |
+
if sample_config.walk_seed:
|
| 288 |
+
current_seed = start_seed + i
|
| 289 |
+
|
| 290 |
+
step_num = ''
|
| 291 |
+
if step is not None:
|
| 292 |
+
# zero-pad 9 digits
|
| 293 |
+
step_num = f"_{str(step).zfill(9)}"
|
| 294 |
+
|
| 295 |
+
filename = f"[time]_{step_num}_[count].{self.sample_config.ext}"
|
| 296 |
+
|
| 297 |
+
output_path = os.path.join(sample_folder, filename)
|
| 298 |
+
|
| 299 |
+
prompt = sample_config.prompts[i]
|
| 300 |
+
|
| 301 |
+
# add embedding if there is one
|
| 302 |
+
# note: diffusers will automatically expand the trigger to the number of added tokens
|
| 303 |
+
# ie test123 will become test123 test123_1 test123_2 etc. Do not add this yourself here
|
| 304 |
+
if self.embedding is not None:
|
| 305 |
+
prompt = self.embedding.inject_embedding_to_prompt(
|
| 306 |
+
prompt, expand_token=True, add_if_not_present=False
|
| 307 |
+
)
|
| 308 |
+
if self.adapter is not None and isinstance(self.adapter, ClipVisionAdapter):
|
| 309 |
+
prompt = self.adapter.inject_trigger_into_prompt(
|
| 310 |
+
prompt, expand_token=True, add_if_not_present=False
|
| 311 |
+
)
|
| 312 |
+
if self.trigger_word is not None:
|
| 313 |
+
prompt = self.sd.inject_trigger_into_prompt(
|
| 314 |
+
prompt, self.trigger_word, add_if_not_present=False
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
extra_args = {}
|
| 318 |
+
if self.adapter_config is not None and self.adapter_config.test_img_path is not None:
|
| 319 |
+
extra_args['adapter_image_path'] = test_image_paths[i]
|
| 320 |
+
|
| 321 |
+
sample_item = sample_config.samples[i]
|
| 322 |
+
if sample_item.seed is not None:
|
| 323 |
+
current_seed = sample_item.seed
|
| 324 |
+
|
| 325 |
+
gen_img_config_list.append(GenerateImageConfig(
|
| 326 |
+
prompt=prompt, # it will autoparse the prompt
|
| 327 |
+
width=sample_item.width,
|
| 328 |
+
height=sample_item.height,
|
| 329 |
+
negative_prompt=sample_item.neg,
|
| 330 |
+
seed=current_seed,
|
| 331 |
+
guidance_scale=sample_item.guidance_scale,
|
| 332 |
+
guidance_rescale=sample_config.guidance_rescale,
|
| 333 |
+
num_inference_steps=sample_item.sample_steps,
|
| 334 |
+
network_multiplier=sample_item.network_multiplier,
|
| 335 |
+
output_path=output_path,
|
| 336 |
+
output_ext=sample_config.ext,
|
| 337 |
+
adapter_conditioning_scale=sample_config.adapter_conditioning_scale,
|
| 338 |
+
refiner_start_at=sample_config.refiner_start_at,
|
| 339 |
+
extra_values=sample_config.extra_values,
|
| 340 |
+
logger=self.logger,
|
| 341 |
+
num_frames=sample_item.num_frames,
|
| 342 |
+
fps=sample_item.fps,
|
| 343 |
+
ctrl_img=sample_item.ctrl_img,
|
| 344 |
+
ctrl_idx=sample_item.ctrl_idx,
|
| 345 |
+
ctrl_img_1=sample_item.ctrl_img_1,
|
| 346 |
+
ctrl_img_2=sample_item.ctrl_img_2,
|
| 347 |
+
ctrl_img_3=sample_item.ctrl_img_3,
|
| 348 |
+
do_cfg_norm=sample_config.do_cfg_norm,
|
| 349 |
+
**extra_args
|
| 350 |
+
))
|
| 351 |
+
|
| 352 |
+
# post process
|
| 353 |
+
gen_img_config_list = self.post_process_generate_image_config_list(gen_img_config_list)
|
| 354 |
+
|
| 355 |
+
# if we have an ema, set it to validation mode
|
| 356 |
+
if self.ema is not None:
|
| 357 |
+
self.ema.eval()
|
| 358 |
+
|
| 359 |
+
# let adapter know we are sampling
|
| 360 |
+
if self.adapter is not None and isinstance(self.adapter, CustomAdapter):
|
| 361 |
+
self.adapter.is_sampling = True
|
| 362 |
+
|
| 363 |
+
# send to be generated
|
| 364 |
+
self.sd.generate_images(gen_img_config_list, sampler=sample_config.sampler)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
if self.adapter is not None and isinstance(self.adapter, CustomAdapter):
|
| 368 |
+
self.adapter.is_sampling = False
|
| 369 |
+
|
| 370 |
+
if self.ema is not None:
|
| 371 |
+
self.ema.train()
|
| 372 |
+
|
| 373 |
+
def update_training_metadata(self):
|
| 374 |
+
o_dict = OrderedDict({
|
| 375 |
+
"training_info": self.get_training_info()
|
| 376 |
+
})
|
| 377 |
+
o_dict['ss_base_model_version'] = self.sd.get_base_model_version()
|
| 378 |
+
|
| 379 |
+
# o_dict = add_base_model_info_to_meta(
|
| 380 |
+
# o_dict,
|
| 381 |
+
# is_v2=self.model_config.is_v2,
|
| 382 |
+
# is_xl=self.model_config.is_xl,
|
| 383 |
+
# )
|
| 384 |
+
o_dict['ss_output_name'] = self.job.name
|
| 385 |
+
|
| 386 |
+
if self.trigger_word is not None:
|
| 387 |
+
# just so auto1111 will pick it up
|
| 388 |
+
o_dict['ss_tag_frequency'] = {
|
| 389 |
+
f"1_{self.trigger_word}": {
|
| 390 |
+
f"{self.trigger_word}": 1
|
| 391 |
+
}
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
self.add_meta(o_dict)
|
| 395 |
+
|
| 396 |
+
def get_training_info(self):
|
| 397 |
+
info = OrderedDict({
|
| 398 |
+
'step': self.step_num,
|
| 399 |
+
'epoch': self.epoch_num,
|
| 400 |
+
})
|
| 401 |
+
return info
|
| 402 |
+
|
| 403 |
+
def clean_up_saves(self):
|
| 404 |
+
if not self.accelerator.is_main_process:
|
| 405 |
+
return
|
| 406 |
+
# remove old saves
|
| 407 |
+
# get latest saved step
|
| 408 |
+
latest_item = None
|
| 409 |
+
if os.path.exists(self.save_root):
|
| 410 |
+
# pattern is {job_name}_{zero_filled_step} for both files and directories
|
| 411 |
+
pattern = f"{self.job.name}_*"
|
| 412 |
+
items = glob.glob(os.path.join(self.save_root, pattern))
|
| 413 |
+
# Separate files and directories
|
| 414 |
+
safetensors_files = [f for f in items if f.endswith('.safetensors')]
|
| 415 |
+
pt_files = [f for f in items if f.endswith('.pt')]
|
| 416 |
+
directories = [d for d in items if os.path.isdir(d) and not d.endswith('.safetensors')]
|
| 417 |
+
embed_files = []
|
| 418 |
+
# do embedding files
|
| 419 |
+
if self.embed_config is not None:
|
| 420 |
+
embed_pattern = f"{self.embed_config.trigger}_*"
|
| 421 |
+
embed_items = glob.glob(os.path.join(self.save_root, embed_pattern))
|
| 422 |
+
# will end in safetensors or pt
|
| 423 |
+
embed_files = [f for f in embed_items if f.endswith('.safetensors') or f.endswith('.pt')]
|
| 424 |
+
|
| 425 |
+
# check for critic files
|
| 426 |
+
critic_pattern = f"CRITIC_{self.job.name}_*"
|
| 427 |
+
critic_items = glob.glob(os.path.join(self.save_root, critic_pattern))
|
| 428 |
+
|
| 429 |
+
# Sort the lists by creation time if they are not empty
|
| 430 |
+
if safetensors_files:
|
| 431 |
+
safetensors_files.sort(key=os.path.getctime)
|
| 432 |
+
if pt_files:
|
| 433 |
+
pt_files.sort(key=os.path.getctime)
|
| 434 |
+
if directories:
|
| 435 |
+
directories.sort(key=os.path.getctime)
|
| 436 |
+
if embed_files:
|
| 437 |
+
embed_files.sort(key=os.path.getctime)
|
| 438 |
+
if critic_items:
|
| 439 |
+
critic_items.sort(key=os.path.getctime)
|
| 440 |
+
|
| 441 |
+
# Combine and sort the lists
|
| 442 |
+
combined_items = safetensors_files + directories + pt_files
|
| 443 |
+
combined_items.sort(key=os.path.getctime)
|
| 444 |
+
|
| 445 |
+
num_saves_to_keep = self.save_config.max_step_saves_to_keep
|
| 446 |
+
|
| 447 |
+
if hasattr(self.sd, 'max_step_saves_to_keep_multiplier'):
|
| 448 |
+
num_saves_to_keep *= self.sd.max_step_saves_to_keep_multiplier
|
| 449 |
+
|
| 450 |
+
# Use slicing with a check to avoid 'NoneType' error
|
| 451 |
+
safetensors_to_remove = safetensors_files[
|
| 452 |
+
:-num_saves_to_keep] if safetensors_files else []
|
| 453 |
+
pt_files_to_remove = pt_files[:-num_saves_to_keep] if pt_files else []
|
| 454 |
+
directories_to_remove = directories[:-num_saves_to_keep] if directories else []
|
| 455 |
+
embeddings_to_remove = embed_files[:-num_saves_to_keep] if embed_files else []
|
| 456 |
+
critic_to_remove = critic_items[:-num_saves_to_keep] if critic_items else []
|
| 457 |
+
|
| 458 |
+
items_to_remove = safetensors_to_remove + pt_files_to_remove + directories_to_remove + embeddings_to_remove + critic_to_remove
|
| 459 |
+
|
| 460 |
+
# remove all but the latest max_step_saves_to_keep
|
| 461 |
+
# items_to_remove = combined_items[:-num_saves_to_keep]
|
| 462 |
+
|
| 463 |
+
# remove duplicates
|
| 464 |
+
items_to_remove = list(dict.fromkeys(items_to_remove))
|
| 465 |
+
|
| 466 |
+
for item in items_to_remove:
|
| 467 |
+
print_acc(f"Removing old save: {item}")
|
| 468 |
+
if os.path.isdir(item):
|
| 469 |
+
shutil.rmtree(item)
|
| 470 |
+
else:
|
| 471 |
+
os.remove(item)
|
| 472 |
+
# see if a yaml file with same name exists
|
| 473 |
+
yaml_file = os.path.splitext(item)[0] + ".yaml"
|
| 474 |
+
if os.path.exists(yaml_file):
|
| 475 |
+
os.remove(yaml_file)
|
| 476 |
+
if combined_items:
|
| 477 |
+
latest_item = combined_items[-1]
|
| 478 |
+
return latest_item
|
| 479 |
+
|
| 480 |
+
def post_save_hook(self, save_path):
|
| 481 |
+
# override in subclass
|
| 482 |
+
pass
|
| 483 |
+
|
| 484 |
+
def done_hook(self):
|
| 485 |
+
pass
|
| 486 |
+
|
| 487 |
+
def end_step_hook(self):
|
| 488 |
+
pass
|
| 489 |
+
|
| 490 |
+
def save(self, step=None):
|
| 491 |
+
if not self.accelerator.is_main_process:
|
| 492 |
+
return
|
| 493 |
+
flush()
|
| 494 |
+
if self.ema is not None:
|
| 495 |
+
# always save params as ema
|
| 496 |
+
self.ema.eval()
|
| 497 |
+
|
| 498 |
+
if not os.path.exists(self.save_root):
|
| 499 |
+
os.makedirs(self.save_root, exist_ok=True)
|
| 500 |
+
|
| 501 |
+
step_num = ''
|
| 502 |
+
if step is not None:
|
| 503 |
+
self.last_save_step = step
|
| 504 |
+
# zeropad 9 digits
|
| 505 |
+
step_num = f"_{str(step).zfill(9)}"
|
| 506 |
+
|
| 507 |
+
self.update_training_metadata()
|
| 508 |
+
filename = f'{self.job.name}{step_num}.safetensors'
|
| 509 |
+
file_path = os.path.join(self.save_root, filename)
|
| 510 |
+
|
| 511 |
+
save_meta = copy.deepcopy(self.meta)
|
| 512 |
+
# get extra meta
|
| 513 |
+
if self.adapter is not None and isinstance(self.adapter, CustomAdapter):
|
| 514 |
+
additional_save_meta = self.adapter.get_additional_save_metadata()
|
| 515 |
+
if additional_save_meta is not None:
|
| 516 |
+
for key, value in additional_save_meta.items():
|
| 517 |
+
save_meta[key] = value
|
| 518 |
+
|
| 519 |
+
# prepare meta
|
| 520 |
+
save_meta = get_meta_for_safetensors(save_meta, self.job.name)
|
| 521 |
+
if not self.is_fine_tuning and not self.train_config.merge_network_on_save:
|
| 522 |
+
if self.network is not None:
|
| 523 |
+
lora_name = self.job.name
|
| 524 |
+
if self.named_lora:
|
| 525 |
+
# add _lora to name
|
| 526 |
+
lora_name += '_LoRA'
|
| 527 |
+
|
| 528 |
+
filename = f'{lora_name}{step_num}.safetensors'
|
| 529 |
+
file_path = os.path.join(self.save_root, filename)
|
| 530 |
+
prev_multiplier = self.network.multiplier
|
| 531 |
+
self.network.multiplier = 1.0
|
| 532 |
+
|
| 533 |
+
# if we are doing embedding training as well, add that
|
| 534 |
+
embedding_dict = self.embedding.state_dict() if self.embedding else None
|
| 535 |
+
self.network.save_weights(
|
| 536 |
+
file_path,
|
| 537 |
+
dtype=get_torch_dtype(self.save_config.dtype),
|
| 538 |
+
metadata=save_meta,
|
| 539 |
+
extra_state_dict=embedding_dict
|
| 540 |
+
)
|
| 541 |
+
self.network.multiplier = prev_multiplier
|
| 542 |
+
# if we have an embedding as well, pair it with the network
|
| 543 |
+
|
| 544 |
+
# even if added to lora, still save the trigger version
|
| 545 |
+
if self.embedding is not None:
|
| 546 |
+
emb_filename = f'{self.embed_config.trigger}{step_num}.safetensors'
|
| 547 |
+
emb_file_path = os.path.join(self.save_root, emb_filename)
|
| 548 |
+
# for combo, above will get it
|
| 549 |
+
# set current step
|
| 550 |
+
self.embedding.step = self.step_num
|
| 551 |
+
# change filename to pt if that is set
|
| 552 |
+
if self.embed_config.save_format == "pt":
|
| 553 |
+
# replace extension
|
| 554 |
+
emb_file_path = os.path.splitext(emb_file_path)[0] + ".pt"
|
| 555 |
+
self.embedding.save(emb_file_path)
|
| 556 |
+
|
| 557 |
+
if self.decorator is not None:
|
| 558 |
+
dec_filename = f'{self.job.name}{step_num}.safetensors'
|
| 559 |
+
dec_file_path = os.path.join(self.save_root, dec_filename)
|
| 560 |
+
decorator_state_dict = self.decorator.state_dict()
|
| 561 |
+
for key, value in decorator_state_dict.items():
|
| 562 |
+
if isinstance(value, torch.Tensor):
|
| 563 |
+
decorator_state_dict[key] = value.clone().to('cpu', dtype=get_torch_dtype(self.save_config.dtype))
|
| 564 |
+
save_file(
|
| 565 |
+
decorator_state_dict,
|
| 566 |
+
dec_file_path,
|
| 567 |
+
metadata=save_meta,
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
if self.adapter is not None and self.adapter_config.train:
|
| 571 |
+
adapter_name = self.job.name
|
| 572 |
+
if self.network_config is not None or self.embedding is not None:
|
| 573 |
+
# add _lora to name
|
| 574 |
+
if self.adapter_config.type == 't2i':
|
| 575 |
+
adapter_name += '_t2i'
|
| 576 |
+
elif self.adapter_config.type == 'control_net':
|
| 577 |
+
adapter_name += '_cn'
|
| 578 |
+
elif self.adapter_config.type == 'clip':
|
| 579 |
+
adapter_name += '_clip'
|
| 580 |
+
elif self.adapter_config.type.startswith('ip'):
|
| 581 |
+
adapter_name += '_ip'
|
| 582 |
+
else:
|
| 583 |
+
adapter_name += '_adapter'
|
| 584 |
+
|
| 585 |
+
filename = f'{adapter_name}{step_num}.safetensors'
|
| 586 |
+
file_path = os.path.join(self.save_root, filename)
|
| 587 |
+
# save adapter
|
| 588 |
+
state_dict = self.adapter.state_dict()
|
| 589 |
+
if self.adapter_config.type == 't2i':
|
| 590 |
+
save_t2i_from_diffusers(
|
| 591 |
+
state_dict,
|
| 592 |
+
output_file=file_path,
|
| 593 |
+
meta=save_meta,
|
| 594 |
+
dtype=get_torch_dtype(self.save_config.dtype)
|
| 595 |
+
)
|
| 596 |
+
elif self.adapter_config.type == 'control_net':
|
| 597 |
+
# save in diffusers format
|
| 598 |
+
name_or_path = file_path.replace('.safetensors', '')
|
| 599 |
+
# move it to the new dtype and cpu
|
| 600 |
+
orig_device = self.adapter.device
|
| 601 |
+
orig_dtype = self.adapter.dtype
|
| 602 |
+
self.adapter = self.adapter.to(torch.device('cpu'), dtype=get_torch_dtype(self.save_config.dtype))
|
| 603 |
+
self.adapter.save_pretrained(
|
| 604 |
+
name_or_path,
|
| 605 |
+
dtype=get_torch_dtype(self.save_config.dtype),
|
| 606 |
+
safe_serialization=True
|
| 607 |
+
)
|
| 608 |
+
meta_path = os.path.join(name_or_path, 'aitk_meta.yaml')
|
| 609 |
+
with open(meta_path, 'w') as f:
|
| 610 |
+
yaml.dump(self.meta, f)
|
| 611 |
+
# move it back
|
| 612 |
+
self.adapter = self.adapter.to(orig_device, dtype=orig_dtype)
|
| 613 |
+
else:
|
| 614 |
+
direct_save = False
|
| 615 |
+
if self.adapter_config.train_only_image_encoder:
|
| 616 |
+
direct_save = True
|
| 617 |
+
elif isinstance(self.adapter, CustomAdapter):
|
| 618 |
+
direct_save = self.adapter.do_direct_save
|
| 619 |
+
save_ip_adapter_from_diffusers(
|
| 620 |
+
state_dict,
|
| 621 |
+
output_file=file_path,
|
| 622 |
+
meta=save_meta,
|
| 623 |
+
dtype=get_torch_dtype(self.save_config.dtype),
|
| 624 |
+
direct_save=direct_save
|
| 625 |
+
)
|
| 626 |
+
else:
|
| 627 |
+
if self.network is not None and self.train_config.merge_network_on_save:
|
| 628 |
+
# merge the network weights into a full model and save that
|
| 629 |
+
if not self.network.can_merge_in:
|
| 630 |
+
raise ValueError("Network cannot merge in weights. Cannot save full model.")
|
| 631 |
+
|
| 632 |
+
print_acc("Merging network weights into full model for saving...")
|
| 633 |
+
|
| 634 |
+
self.network.merge_in(merge_weight=self.train_config.merge_network_on_save_strength)
|
| 635 |
+
# reset weights to zero
|
| 636 |
+
self.network.reset_weights()
|
| 637 |
+
self.network.is_merged_in = False
|
| 638 |
+
|
| 639 |
+
print_acc("Done merging network weights.")
|
| 640 |
+
|
| 641 |
+
if self.save_config.save_format == "diffusers":
|
| 642 |
+
# saving as a folder path
|
| 643 |
+
file_path = file_path.replace('.safetensors', '')
|
| 644 |
+
# convert it back to normal object
|
| 645 |
+
save_meta = parse_metadata_from_safetensors(save_meta)
|
| 646 |
+
|
| 647 |
+
if self.sd.refiner_unet and self.train_config.train_refiner:
|
| 648 |
+
# save refiner
|
| 649 |
+
refiner_name = self.job.name + '_refiner'
|
| 650 |
+
filename = f'{refiner_name}{step_num}.safetensors'
|
| 651 |
+
file_path = os.path.join(self.save_root, filename)
|
| 652 |
+
self.sd.save_refiner(
|
| 653 |
+
file_path,
|
| 654 |
+
save_meta,
|
| 655 |
+
get_torch_dtype(self.save_config.dtype)
|
| 656 |
+
)
|
| 657 |
+
if self.train_config.train_unet or self.train_config.train_text_encoder:
|
| 658 |
+
self.sd.save(
|
| 659 |
+
file_path,
|
| 660 |
+
save_meta,
|
| 661 |
+
get_torch_dtype(self.save_config.dtype)
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
# save learnable params as json if we have thim
|
| 665 |
+
if self.snr_gos:
|
| 666 |
+
json_data = {
|
| 667 |
+
'offset_1': self.snr_gos.offset_1.item(),
|
| 668 |
+
'offset_2': self.snr_gos.offset_2.item(),
|
| 669 |
+
'scale': self.snr_gos.scale.item(),
|
| 670 |
+
'gamma': self.snr_gos.gamma.item(),
|
| 671 |
+
}
|
| 672 |
+
path_to_save = file_path = os.path.join(self.save_root, 'learnable_snr.json')
|
| 673 |
+
with open(path_to_save, 'w') as f:
|
| 674 |
+
json.dump(json_data, f, indent=4)
|
| 675 |
+
|
| 676 |
+
print_acc(f"Saved checkpoint to {file_path}")
|
| 677 |
+
|
| 678 |
+
# save optimizer
|
| 679 |
+
if self.optimizer is not None:
|
| 680 |
+
try:
|
| 681 |
+
filename = f'optimizer.pt'
|
| 682 |
+
file_path = os.path.join(self.save_root, filename)
|
| 683 |
+
try:
|
| 684 |
+
state_dict = unwrap_model(self.optimizer).state_dict()
|
| 685 |
+
except Exception as e:
|
| 686 |
+
state_dict = self.optimizer.state_dict()
|
| 687 |
+
torch.save(state_dict, file_path)
|
| 688 |
+
print_acc(f"Saved optimizer to {file_path}")
|
| 689 |
+
except Exception as e:
|
| 690 |
+
print_acc(e)
|
| 691 |
+
print_acc("Could not save optimizer")
|
| 692 |
+
|
| 693 |
+
self.clean_up_saves()
|
| 694 |
+
self.post_save_hook(file_path)
|
| 695 |
+
|
| 696 |
+
if self.ema is not None:
|
| 697 |
+
self.ema.train()
|
| 698 |
+
flush()
|
| 699 |
+
|
| 700 |
+
# Called before the model is loaded
|
| 701 |
+
def hook_before_model_load(self):
|
| 702 |
+
# override in subclass
|
| 703 |
+
pass
|
| 704 |
+
|
| 705 |
+
def hook_after_model_load(self):
|
| 706 |
+
# override in subclass
|
| 707 |
+
pass
|
| 708 |
+
|
| 709 |
+
def hook_add_extra_train_params(self, params):
|
| 710 |
+
# override in subclass
|
| 711 |
+
return params
|
| 712 |
+
|
| 713 |
+
def hook_before_train_loop(self):
|
| 714 |
+
if self.accelerator.is_main_process:
|
| 715 |
+
self.logger.start()
|
| 716 |
+
self.prepare_accelerator()
|
| 717 |
+
|
| 718 |
+
def sample_step_hook(self, img_num, total_imgs):
|
| 719 |
+
pass
|
| 720 |
+
|
| 721 |
+
def prepare_accelerator(self):
|
| 722 |
+
# set some config
|
| 723 |
+
self.accelerator.even_batches=False
|
| 724 |
+
|
| 725 |
+
# # prepare all the models stuff for accelerator (hopefully we dont miss any)
|
| 726 |
+
self.sd.vae = self.accelerator.prepare(self.sd.vae)
|
| 727 |
+
if self.sd.unet is not None:
|
| 728 |
+
self.sd.unet = self.accelerator.prepare(self.sd.unet)
|
| 729 |
+
# todo always tdo it?
|
| 730 |
+
self.modules_being_trained.append(self.sd.unet)
|
| 731 |
+
if self.sd.text_encoder is not None and self.train_config.train_text_encoder:
|
| 732 |
+
if isinstance(self.sd.text_encoder, list):
|
| 733 |
+
self.sd.text_encoder = [self.accelerator.prepare(model) for model in self.sd.text_encoder]
|
| 734 |
+
self.modules_being_trained.extend(self.sd.text_encoder)
|
| 735 |
+
else:
|
| 736 |
+
self.sd.text_encoder = self.accelerator.prepare(self.sd.text_encoder)
|
| 737 |
+
self.modules_being_trained.append(self.sd.text_encoder)
|
| 738 |
+
if self.sd.refiner_unet is not None and self.train_config.train_refiner:
|
| 739 |
+
self.sd.refiner_unet = self.accelerator.prepare(self.sd.refiner_unet)
|
| 740 |
+
self.modules_being_trained.append(self.sd.refiner_unet)
|
| 741 |
+
# todo, do we need to do the network or will "unet" get it?
|
| 742 |
+
if self.sd.network is not None:
|
| 743 |
+
self.sd.network = self.accelerator.prepare(self.sd.network)
|
| 744 |
+
self.modules_being_trained.append(self.sd.network)
|
| 745 |
+
if self.adapter is not None and self.adapter_config.train:
|
| 746 |
+
# todo adapters may not be a module. need to check
|
| 747 |
+
self.adapter = self.accelerator.prepare(self.adapter)
|
| 748 |
+
self.modules_being_trained.append(self.adapter)
|
| 749 |
+
|
| 750 |
+
# prepare other things
|
| 751 |
+
self.optimizer = self.accelerator.prepare(self.optimizer)
|
| 752 |
+
if self.lr_scheduler is not None:
|
| 753 |
+
self.lr_scheduler = self.accelerator.prepare(self.lr_scheduler)
|
| 754 |
+
# self.data_loader = self.accelerator.prepare(self.data_loader)
|
| 755 |
+
# if self.data_loader_reg is not None:
|
| 756 |
+
# self.data_loader_reg = self.accelerator.prepare(self.data_loader_reg)
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
def ensure_params_requires_grad(self, force=False):
|
| 760 |
+
if self.train_config.do_paramiter_swapping and not force:
|
| 761 |
+
# the optimizer will handle this if we are not forcing
|
| 762 |
+
return
|
| 763 |
+
for group in self.params:
|
| 764 |
+
for param in group['params']:
|
| 765 |
+
if isinstance(param, torch.nn.Parameter): # Ensure it's a proper parameter
|
| 766 |
+
param.requires_grad_(True)
|
| 767 |
+
|
| 768 |
+
def setup_ema(self):
|
| 769 |
+
if self.train_config.ema_config.use_ema:
|
| 770 |
+
# our params are in groups. We need them as a single iterable
|
| 771 |
+
params = []
|
| 772 |
+
for group in self.optimizer.param_groups:
|
| 773 |
+
for param in group['params']:
|
| 774 |
+
params.append(param)
|
| 775 |
+
self.ema = ExponentialMovingAverage(
|
| 776 |
+
params,
|
| 777 |
+
decay=self.train_config.ema_config.ema_decay,
|
| 778 |
+
use_feedback=self.train_config.ema_config.use_feedback,
|
| 779 |
+
param_multiplier=self.train_config.ema_config.param_multiplier,
|
| 780 |
+
)
|
| 781 |
+
|
| 782 |
+
def before_dataset_load(self):
|
| 783 |
+
pass
|
| 784 |
+
|
| 785 |
+
def get_params(self):
|
| 786 |
+
# you can extend this in subclass to get params
|
| 787 |
+
# otherwise params will be gathered through normal means
|
| 788 |
+
return None
|
| 789 |
+
|
| 790 |
+
def hook_train_loop(self, batch):
|
| 791 |
+
# return loss
|
| 792 |
+
return 0.0
|
| 793 |
+
|
| 794 |
+
def hook_after_sd_init_before_load(self):
|
| 795 |
+
pass
|
| 796 |
+
|
| 797 |
+
def get_latest_save_path(self, name=None, post=''):
|
| 798 |
+
if name == None:
|
| 799 |
+
name = self.job.name
|
| 800 |
+
# get latest saved step
|
| 801 |
+
latest_path = None
|
| 802 |
+
if os.path.exists(self.save_root):
|
| 803 |
+
# Define patterns for both files and directories
|
| 804 |
+
patterns = [
|
| 805 |
+
f"{name}*{post}.safetensors",
|
| 806 |
+
f"{name}*{post}.pt",
|
| 807 |
+
f"{name}*{post}"
|
| 808 |
+
]
|
| 809 |
+
# Search for both files and directories
|
| 810 |
+
paths = []
|
| 811 |
+
for pattern in patterns:
|
| 812 |
+
paths.extend(glob.glob(os.path.join(self.save_root, pattern)))
|
| 813 |
+
|
| 814 |
+
# Filter out non-existent paths and sort by creation time
|
| 815 |
+
if paths:
|
| 816 |
+
paths = [p for p in paths if os.path.exists(p)]
|
| 817 |
+
# remove false positives
|
| 818 |
+
if '_LoRA' not in name:
|
| 819 |
+
paths = [p for p in paths if '_LoRA' not in p]
|
| 820 |
+
if '_refiner' not in name:
|
| 821 |
+
paths = [p for p in paths if '_refiner' not in p]
|
| 822 |
+
if '_t2i' not in name:
|
| 823 |
+
paths = [p for p in paths if '_t2i' not in p]
|
| 824 |
+
if '_cn' not in name:
|
| 825 |
+
paths = [p for p in paths if '_cn' not in p]
|
| 826 |
+
|
| 827 |
+
if len(paths) > 0:
|
| 828 |
+
latest_path = max(paths, key=os.path.getctime)
|
| 829 |
+
|
| 830 |
+
if latest_path is None and self.network_config is not None and self.network_config.pretrained_lora_path is not None:
|
| 831 |
+
# set pretrained lora path as load path if we do not have a checkpoint to resume from
|
| 832 |
+
if os.path.exists(self.network_config.pretrained_lora_path):
|
| 833 |
+
latest_path = self.network_config.pretrained_lora_path
|
| 834 |
+
print_acc(f"Using pretrained lora path from config: {latest_path}")
|
| 835 |
+
else:
|
| 836 |
+
# no pretrained lora found
|
| 837 |
+
print_acc(f"Pretrained lora path from config does not exist: {self.network_config.pretrained_lora_path}")
|
| 838 |
+
|
| 839 |
+
return latest_path
|
| 840 |
+
|
| 841 |
+
def load_training_state_from_metadata(self, path):
|
| 842 |
+
if not self.accelerator.is_main_process:
|
| 843 |
+
return
|
| 844 |
+
if path is not None and self.network_config is not None and path == self.network_config.pretrained_lora_path:
|
| 845 |
+
# dont load metadata from pretrained lora
|
| 846 |
+
return
|
| 847 |
+
meta = None
|
| 848 |
+
# if path is folder, then it is diffusers
|
| 849 |
+
if os.path.isdir(path):
|
| 850 |
+
meta_path = os.path.join(path, 'aitk_meta.yaml')
|
| 851 |
+
# load it
|
| 852 |
+
if os.path.exists(meta_path):
|
| 853 |
+
with open(meta_path, 'r') as f:
|
| 854 |
+
meta = yaml.load(f, Loader=yaml.FullLoader)
|
| 855 |
+
else:
|
| 856 |
+
meta = load_metadata_from_safetensors(path)
|
| 857 |
+
# if 'training_info' in Orderdict keys
|
| 858 |
+
if meta is not None and 'training_info' in meta and 'step' in meta['training_info'] and self.train_config.start_step is None:
|
| 859 |
+
self.step_num = meta['training_info']['step']
|
| 860 |
+
if 'epoch' in meta['training_info']:
|
| 861 |
+
self.epoch_num = meta['training_info']['epoch']
|
| 862 |
+
self.start_step = self.step_num
|
| 863 |
+
print_acc(f"Found step {self.step_num} in metadata, starting from there")
|
| 864 |
+
|
| 865 |
+
def load_weights(self, path):
|
| 866 |
+
if self.network is not None:
|
| 867 |
+
extra_weights = self.network.load_weights(path)
|
| 868 |
+
self.load_training_state_from_metadata(path)
|
| 869 |
+
return extra_weights
|
| 870 |
+
else:
|
| 871 |
+
print_acc("load_weights not implemented for non-network models")
|
| 872 |
+
return None
|
| 873 |
+
|
| 874 |
+
def apply_snr(self, seperated_loss, timesteps):
|
| 875 |
+
if self.train_config.learnable_snr_gos:
|
| 876 |
+
# add snr_gamma
|
| 877 |
+
seperated_loss = apply_learnable_snr_gos(seperated_loss, timesteps, self.snr_gos)
|
| 878 |
+
elif self.train_config.snr_gamma is not None and self.train_config.snr_gamma > 0.000001:
|
| 879 |
+
# add snr_gamma
|
| 880 |
+
seperated_loss = apply_snr_weight(seperated_loss, timesteps, self.sd.noise_scheduler, self.train_config.snr_gamma, fixed=True)
|
| 881 |
+
elif self.train_config.min_snr_gamma is not None and self.train_config.min_snr_gamma > 0.000001:
|
| 882 |
+
# add min_snr_gamma
|
| 883 |
+
seperated_loss = apply_snr_weight(seperated_loss, timesteps, self.sd.noise_scheduler, self.train_config.min_snr_gamma)
|
| 884 |
+
|
| 885 |
+
return seperated_loss
|
| 886 |
+
|
| 887 |
+
def load_lorm(self):
|
| 888 |
+
latest_save_path = self.get_latest_save_path()
|
| 889 |
+
if latest_save_path is not None:
|
| 890 |
+
# hacky way to reload weights for now
|
| 891 |
+
# todo, do this
|
| 892 |
+
state_dict = load_file(latest_save_path, device=self.device)
|
| 893 |
+
self.sd.unet.load_state_dict(state_dict)
|
| 894 |
+
|
| 895 |
+
meta = load_metadata_from_safetensors(latest_save_path)
|
| 896 |
+
# if 'training_info' in Orderdict keys
|
| 897 |
+
if 'training_info' in meta and 'step' in meta['training_info']:
|
| 898 |
+
self.step_num = meta['training_info']['step']
|
| 899 |
+
if 'epoch' in meta['training_info']:
|
| 900 |
+
self.epoch_num = meta['training_info']['epoch']
|
| 901 |
+
self.start_step = self.step_num
|
| 902 |
+
print_acc(f"Found step {self.step_num} in metadata, starting from there")
|
| 903 |
+
|
| 904 |
+
# def get_sigmas(self, timesteps, n_dim=4, dtype=torch.float32):
|
| 905 |
+
# self.sd.noise_scheduler.set_timesteps(1000, device=self.device_torch)
|
| 906 |
+
# sigmas = self.sd.noise_scheduler.sigmas.to(device=self.device_torch, dtype=dtype)
|
| 907 |
+
# schedule_timesteps = self.sd.noise_scheduler.timesteps.to(self.device_torch, )
|
| 908 |
+
# timesteps = timesteps.to(self.device_torch, )
|
| 909 |
+
#
|
| 910 |
+
# # step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps]
|
| 911 |
+
# step_indices = [t for t in timesteps]
|
| 912 |
+
#
|
| 913 |
+
# sigma = sigmas[step_indices].flatten()
|
| 914 |
+
# while len(sigma.shape) < n_dim:
|
| 915 |
+
# sigma = sigma.unsqueeze(-1)
|
| 916 |
+
# return sigma
|
| 917 |
+
|
| 918 |
+
def load_additional_training_modules(self, params):
|
| 919 |
+
# override in subclass
|
| 920 |
+
return params
|
| 921 |
+
|
| 922 |
+
def get_sigmas(self, timesteps, n_dim=4, dtype=torch.float32):
|
| 923 |
+
sigmas = self.sd.noise_scheduler.sigmas.to(device=self.device, dtype=dtype)
|
| 924 |
+
schedule_timesteps = self.sd.noise_scheduler.timesteps.to(self.device)
|
| 925 |
+
timesteps = timesteps.to(self.device)
|
| 926 |
+
|
| 927 |
+
step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps]
|
| 928 |
+
|
| 929 |
+
sigma = sigmas[step_indices].flatten()
|
| 930 |
+
while len(sigma.shape) < n_dim:
|
| 931 |
+
sigma = sigma.unsqueeze(-1)
|
| 932 |
+
return sigma
|
| 933 |
+
|
| 934 |
+
def get_optimal_noise(self, latents, dtype=torch.float32):
|
| 935 |
+
batch_num = latents.shape[0]
|
| 936 |
+
chunks = torch.chunk(latents, batch_num, dim=0)
|
| 937 |
+
noise_chunks = []
|
| 938 |
+
for chunk in chunks:
|
| 939 |
+
noise_samples = [torch.randn_like(chunk, device=chunk.device, dtype=dtype) for _ in range(self.train_config.optimal_noise_pairing_samples)]
|
| 940 |
+
# find the one most similar to the chunk
|
| 941 |
+
lowest_loss = 999999999999
|
| 942 |
+
best_noise = None
|
| 943 |
+
for noise in noise_samples:
|
| 944 |
+
loss = torch.nn.functional.mse_loss(chunk, noise)
|
| 945 |
+
if loss < lowest_loss:
|
| 946 |
+
lowest_loss = loss
|
| 947 |
+
best_noise = noise
|
| 948 |
+
noise_chunks.append(best_noise)
|
| 949 |
+
noise = torch.cat(noise_chunks, dim=0)
|
| 950 |
+
return noise
|
| 951 |
+
|
| 952 |
+
def get_consistent_noise(self, latents, batch: 'DataLoaderBatchDTO', dtype=torch.float32):
|
| 953 |
+
batch_num = latents.shape[0]
|
| 954 |
+
chunks = torch.chunk(latents, batch_num, dim=0)
|
| 955 |
+
noise_chunks = []
|
| 956 |
+
for idx, chunk in enumerate(chunks):
|
| 957 |
+
# get seed from path
|
| 958 |
+
file_item = batch.file_items[idx]
|
| 959 |
+
img_path = file_item.path
|
| 960 |
+
# add augmentors
|
| 961 |
+
if file_item.flip_x:
|
| 962 |
+
img_path += '_fx'
|
| 963 |
+
if file_item.flip_y:
|
| 964 |
+
img_path += '_fy'
|
| 965 |
+
seed = int(hashlib.md5(img_path.encode()).hexdigest(), 16) & 0xffffffff
|
| 966 |
+
generator = torch.Generator("cpu").manual_seed(seed)
|
| 967 |
+
noise_chunk = torch.randn(chunk.shape, generator=generator).to(chunk.device, dtype=dtype)
|
| 968 |
+
noise_chunks.append(noise_chunk)
|
| 969 |
+
noise = torch.cat(noise_chunks, dim=0).to(dtype=dtype)
|
| 970 |
+
return noise
|
| 971 |
+
|
| 972 |
+
|
| 973 |
+
def get_noise(
|
| 974 |
+
self,
|
| 975 |
+
latents,
|
| 976 |
+
batch_size,
|
| 977 |
+
dtype=torch.float32,
|
| 978 |
+
batch: 'DataLoaderBatchDTO' = None,
|
| 979 |
+
timestep=None,
|
| 980 |
+
):
|
| 981 |
+
if self.train_config.optimal_noise_pairing_samples > 1:
|
| 982 |
+
noise = self.get_optimal_noise(latents, dtype=dtype)
|
| 983 |
+
elif self.train_config.force_consistent_noise:
|
| 984 |
+
if batch is None:
|
| 985 |
+
raise ValueError("Batch must be provided for consistent noise")
|
| 986 |
+
noise = self.get_consistent_noise(latents, batch, dtype=dtype)
|
| 987 |
+
else:
|
| 988 |
+
if hasattr(self.sd, 'get_latent_noise_from_latents'):
|
| 989 |
+
noise = self.sd.get_latent_noise_from_latents(
|
| 990 |
+
latents,
|
| 991 |
+
noise_offset=self.train_config.noise_offset
|
| 992 |
+
).to(self.device_torch, dtype=dtype)
|
| 993 |
+
else:
|
| 994 |
+
# get noise
|
| 995 |
+
noise = self.sd.get_latent_noise(
|
| 996 |
+
height=latents.shape[2],
|
| 997 |
+
width=latents.shape[3],
|
| 998 |
+
num_channels=latents.shape[1],
|
| 999 |
+
batch_size=batch_size,
|
| 1000 |
+
noise_offset=self.train_config.noise_offset,
|
| 1001 |
+
).to(self.device_torch, dtype=dtype)
|
| 1002 |
+
|
| 1003 |
+
if self.train_config.blended_blur_noise:
|
| 1004 |
+
noise = get_blended_blur_noise(
|
| 1005 |
+
latents, noise, timestep
|
| 1006 |
+
)
|
| 1007 |
+
|
| 1008 |
+
return noise
|
| 1009 |
+
|
| 1010 |
+
def process_general_training_batch(self, batch: 'DataLoaderBatchDTO'):
|
| 1011 |
+
with torch.no_grad():
|
| 1012 |
+
with self.timer('prepare_prompt'):
|
| 1013 |
+
prompts = batch.get_caption_list()
|
| 1014 |
+
is_reg_list = batch.get_is_reg_list()
|
| 1015 |
+
|
| 1016 |
+
is_any_reg = any([is_reg for is_reg in is_reg_list])
|
| 1017 |
+
|
| 1018 |
+
do_double = self.train_config.short_and_long_captions and not is_any_reg
|
| 1019 |
+
|
| 1020 |
+
if self.train_config.short_and_long_captions and do_double:
|
| 1021 |
+
# dont do this with regs. No point
|
| 1022 |
+
|
| 1023 |
+
# double batch and add short captions to the end
|
| 1024 |
+
prompts = prompts + batch.get_caption_short_list()
|
| 1025 |
+
is_reg_list = is_reg_list + is_reg_list
|
| 1026 |
+
if self.model_config.refiner_name_or_path is not None and self.train_config.train_unet:
|
| 1027 |
+
prompts = prompts + prompts
|
| 1028 |
+
is_reg_list = is_reg_list + is_reg_list
|
| 1029 |
+
|
| 1030 |
+
conditioned_prompts = []
|
| 1031 |
+
|
| 1032 |
+
for prompt, is_reg in zip(prompts, is_reg_list):
|
| 1033 |
+
|
| 1034 |
+
# make sure the embedding is in the prompts
|
| 1035 |
+
if self.embedding is not None:
|
| 1036 |
+
prompt = self.embedding.inject_embedding_to_prompt(
|
| 1037 |
+
prompt,
|
| 1038 |
+
expand_token=True,
|
| 1039 |
+
add_if_not_present=not is_reg,
|
| 1040 |
+
)
|
| 1041 |
+
|
| 1042 |
+
if self.adapter and isinstance(self.adapter, ClipVisionAdapter):
|
| 1043 |
+
prompt = self.adapter.inject_trigger_into_prompt(
|
| 1044 |
+
prompt,
|
| 1045 |
+
expand_token=True,
|
| 1046 |
+
add_if_not_present=not is_reg,
|
| 1047 |
+
)
|
| 1048 |
+
|
| 1049 |
+
# make sure trigger is in the prompts if not a regularization run
|
| 1050 |
+
if self.trigger_word is not None:
|
| 1051 |
+
prompt = self.sd.inject_trigger_into_prompt(
|
| 1052 |
+
prompt,
|
| 1053 |
+
trigger=self.trigger_word,
|
| 1054 |
+
add_if_not_present=not is_reg,
|
| 1055 |
+
)
|
| 1056 |
+
|
| 1057 |
+
if not is_reg and self.train_config.prompt_saturation_chance > 0.0:
|
| 1058 |
+
# do random prompt saturation by expanding the prompt to hit at least 77 tokens
|
| 1059 |
+
if random.random() < self.train_config.prompt_saturation_chance:
|
| 1060 |
+
est_num_tokens = len(prompt.split(' '))
|
| 1061 |
+
if est_num_tokens < 77:
|
| 1062 |
+
num_repeats = int(77 / est_num_tokens) + 1
|
| 1063 |
+
prompt = ', '.join([prompt] * num_repeats)
|
| 1064 |
+
|
| 1065 |
+
|
| 1066 |
+
conditioned_prompts.append(prompt)
|
| 1067 |
+
|
| 1068 |
+
with self.timer('prepare_latents'):
|
| 1069 |
+
dtype = get_torch_dtype(self.train_config.dtype)
|
| 1070 |
+
imgs = None
|
| 1071 |
+
is_reg = any(batch.get_is_reg_list())
|
| 1072 |
+
if batch.tensor is not None:
|
| 1073 |
+
imgs = batch.tensor
|
| 1074 |
+
imgs = imgs.to(self.device_torch, dtype=dtype)
|
| 1075 |
+
# dont adjust for regs.
|
| 1076 |
+
if self.train_config.img_multiplier is not None and not is_reg:
|
| 1077 |
+
# do it ad contrast
|
| 1078 |
+
imgs = reduce_contrast(imgs, self.train_config.img_multiplier)
|
| 1079 |
+
if batch.latents is not None:
|
| 1080 |
+
latents = batch.latents.to(self.device_torch, dtype=dtype)
|
| 1081 |
+
batch.latents = latents
|
| 1082 |
+
else:
|
| 1083 |
+
# normalize to
|
| 1084 |
+
if self.train_config.standardize_images:
|
| 1085 |
+
if self.sd.is_xl or self.sd.is_vega or self.sd.is_ssd:
|
| 1086 |
+
target_mean_list = [0.0002, -0.1034, -0.1879]
|
| 1087 |
+
target_std_list = [0.5436, 0.5116, 0.5033]
|
| 1088 |
+
else:
|
| 1089 |
+
target_mean_list = [-0.0739, -0.1597, -0.2380]
|
| 1090 |
+
target_std_list = [0.5623, 0.5295, 0.5347]
|
| 1091 |
+
# Mean: tensor([-0.0739, -0.1597, -0.2380])
|
| 1092 |
+
# Standard Deviation: tensor([0.5623, 0.5295, 0.5347])
|
| 1093 |
+
imgs_channel_mean = imgs.mean(dim=(2, 3), keepdim=True)
|
| 1094 |
+
imgs_channel_std = imgs.std(dim=(2, 3), keepdim=True)
|
| 1095 |
+
imgs = (imgs - imgs_channel_mean) / imgs_channel_std
|
| 1096 |
+
target_mean = torch.tensor(target_mean_list, device=self.device_torch, dtype=dtype)
|
| 1097 |
+
target_std = torch.tensor(target_std_list, device=self.device_torch, dtype=dtype)
|
| 1098 |
+
# expand them to match dim
|
| 1099 |
+
target_mean = target_mean.unsqueeze(0).unsqueeze(2).unsqueeze(3)
|
| 1100 |
+
target_std = target_std.unsqueeze(0).unsqueeze(2).unsqueeze(3)
|
| 1101 |
+
|
| 1102 |
+
imgs = imgs * target_std + target_mean
|
| 1103 |
+
batch.tensor = imgs
|
| 1104 |
+
|
| 1105 |
+
# show_tensors(imgs, 'imgs')
|
| 1106 |
+
|
| 1107 |
+
latents = self.sd.encode_images(imgs)
|
| 1108 |
+
batch.latents = latents
|
| 1109 |
+
|
| 1110 |
+
if self.train_config.standardize_latents:
|
| 1111 |
+
if self.sd.is_xl or self.sd.is_vega or self.sd.is_ssd:
|
| 1112 |
+
target_mean_list = [-0.1075, 0.0231, -0.0135, 0.2164]
|
| 1113 |
+
target_std_list = [0.8979, 0.7505, 0.9150, 0.7451]
|
| 1114 |
+
else:
|
| 1115 |
+
target_mean_list = [0.2949, -0.3188, 0.0807, 0.1929]
|
| 1116 |
+
target_std_list = [0.8560, 0.9629, 0.7778, 0.6719]
|
| 1117 |
+
|
| 1118 |
+
latents_channel_mean = latents.mean(dim=(2, 3), keepdim=True)
|
| 1119 |
+
latents_channel_std = latents.std(dim=(2, 3), keepdim=True)
|
| 1120 |
+
latents = (latents - latents_channel_mean) / latents_channel_std
|
| 1121 |
+
target_mean = torch.tensor(target_mean_list, device=self.device_torch, dtype=dtype)
|
| 1122 |
+
target_std = torch.tensor(target_std_list, device=self.device_torch, dtype=dtype)
|
| 1123 |
+
# expand them to match dim
|
| 1124 |
+
target_mean = target_mean.unsqueeze(0).unsqueeze(2).unsqueeze(3)
|
| 1125 |
+
target_std = target_std.unsqueeze(0).unsqueeze(2).unsqueeze(3)
|
| 1126 |
+
|
| 1127 |
+
latents = latents * target_std + target_mean
|
| 1128 |
+
batch.latents = latents
|
| 1129 |
+
|
| 1130 |
+
# show_latents(latents, self.sd.vae, 'latents')
|
| 1131 |
+
|
| 1132 |
+
|
| 1133 |
+
if batch.unconditional_tensor is not None and batch.unconditional_latents is None:
|
| 1134 |
+
unconditional_imgs = batch.unconditional_tensor
|
| 1135 |
+
unconditional_imgs = unconditional_imgs.to(self.device_torch, dtype=dtype)
|
| 1136 |
+
unconditional_latents = self.sd.encode_images(unconditional_imgs)
|
| 1137 |
+
batch.unconditional_latents = unconditional_latents * self.train_config.latent_multiplier
|
| 1138 |
+
|
| 1139 |
+
unaugmented_latents = None
|
| 1140 |
+
if self.train_config.loss_target == 'differential_noise':
|
| 1141 |
+
# we determine noise from the differential of the latents
|
| 1142 |
+
unaugmented_latents = self.sd.encode_images(batch.unaugmented_tensor)
|
| 1143 |
+
|
| 1144 |
+
with self.timer('prepare_scheduler'):
|
| 1145 |
+
|
| 1146 |
+
batch_size = len(batch.file_items)
|
| 1147 |
+
min_noise_steps = self.train_config.min_denoising_steps
|
| 1148 |
+
max_noise_steps = self.train_config.max_denoising_steps
|
| 1149 |
+
if self.model_config.refiner_name_or_path is not None:
|
| 1150 |
+
# if we are not training the unet, then we are only doing refiner and do not need to double up
|
| 1151 |
+
if self.train_config.train_unet:
|
| 1152 |
+
max_noise_steps = round(self.train_config.max_denoising_steps * self.model_config.refiner_start_at)
|
| 1153 |
+
do_double = True
|
| 1154 |
+
else:
|
| 1155 |
+
min_noise_steps = round(self.train_config.max_denoising_steps * self.model_config.refiner_start_at)
|
| 1156 |
+
do_double = False
|
| 1157 |
+
|
| 1158 |
+
num_train_timesteps = self.train_config.num_train_timesteps
|
| 1159 |
+
|
| 1160 |
+
if self.train_config.noise_scheduler in ['custom_lcm']:
|
| 1161 |
+
# we store this value on our custom one
|
| 1162 |
+
self.sd.noise_scheduler.set_timesteps(
|
| 1163 |
+
self.sd.noise_scheduler.train_timesteps, device=self.device_torch
|
| 1164 |
+
)
|
| 1165 |
+
elif self.train_config.noise_scheduler in ['lcm']:
|
| 1166 |
+
self.sd.noise_scheduler.set_timesteps(
|
| 1167 |
+
num_train_timesteps, device=self.device_torch, original_inference_steps=num_train_timesteps
|
| 1168 |
+
)
|
| 1169 |
+
elif self.train_config.noise_scheduler == 'flowmatch':
|
| 1170 |
+
linear_timesteps = any([
|
| 1171 |
+
self.train_config.linear_timesteps,
|
| 1172 |
+
self.train_config.linear_timesteps2,
|
| 1173 |
+
self.train_config.timestep_type == 'linear',
|
| 1174 |
+
self.train_config.timestep_type == 'one_step',
|
| 1175 |
+
])
|
| 1176 |
+
|
| 1177 |
+
timestep_type = 'linear' if linear_timesteps else None
|
| 1178 |
+
if timestep_type is None:
|
| 1179 |
+
timestep_type = self.train_config.timestep_type
|
| 1180 |
+
|
| 1181 |
+
if self.train_config.timestep_type == 'next_sample':
|
| 1182 |
+
# simulate a sample
|
| 1183 |
+
num_train_timesteps = self.train_config.next_sample_timesteps
|
| 1184 |
+
timestep_type = 'shift'
|
| 1185 |
+
|
| 1186 |
+
patch_size = 1
|
| 1187 |
+
if self.sd.is_flux or 'flex' in self.sd.arch:
|
| 1188 |
+
# flux is a patch size of 1, but latents are divided by 2, so we need to double it
|
| 1189 |
+
patch_size = 2
|
| 1190 |
+
elif hasattr(self.sd.unet, 'config') and hasattr(self.sd.unet.config, 'patch_size'):
|
| 1191 |
+
patch_size = self.sd.unet.config.patch_size
|
| 1192 |
+
|
| 1193 |
+
self.sd.noise_scheduler.set_train_timesteps(
|
| 1194 |
+
num_train_timesteps,
|
| 1195 |
+
device=self.device_torch,
|
| 1196 |
+
timestep_type=timestep_type,
|
| 1197 |
+
latents=latents,
|
| 1198 |
+
patch_size=patch_size,
|
| 1199 |
+
)
|
| 1200 |
+
else:
|
| 1201 |
+
self.sd.noise_scheduler.set_timesteps(
|
| 1202 |
+
num_train_timesteps, device=self.device_torch
|
| 1203 |
+
)
|
| 1204 |
+
if self.sd.is_multistage:
|
| 1205 |
+
with self.timer('adjust_multistage_timesteps'):
|
| 1206 |
+
# get our current sample range
|
| 1207 |
+
boundaries = [1] + self.sd.multistage_boundaries
|
| 1208 |
+
boundary_max, boundary_min = boundaries[self.current_boundary_index], boundaries[self.current_boundary_index + 1]
|
| 1209 |
+
asc_timesteps = torch.flip(self.sd.noise_scheduler.timesteps, dims=[0])
|
| 1210 |
+
lo = len(asc_timesteps) - torch.searchsorted(asc_timesteps, torch.tensor(boundary_max * 1000, device=asc_timesteps.device), right=False)
|
| 1211 |
+
hi = len(asc_timesteps) - torch.searchsorted(asc_timesteps, torch.tensor(boundary_min * 1000, device=asc_timesteps.device), right=True)
|
| 1212 |
+
first_idx = (lo - 1).item() if hi > lo else 0
|
| 1213 |
+
last_idx = (hi - 1).item() if hi > lo else 999
|
| 1214 |
+
min_noise_steps = first_idx
|
| 1215 |
+
max_noise_steps = last_idx
|
| 1216 |
+
|
| 1217 |
+
# clip min max indicies
|
| 1218 |
+
min_noise_steps = max(min_noise_steps, 0)
|
| 1219 |
+
max_noise_steps = min(max_noise_steps, num_train_timesteps - 1)
|
| 1220 |
+
|
| 1221 |
+
|
| 1222 |
+
with self.timer('prepare_timesteps_indices'):
|
| 1223 |
+
|
| 1224 |
+
content_or_style = self.train_config.content_or_style
|
| 1225 |
+
if is_reg:
|
| 1226 |
+
content_or_style = self.train_config.content_or_style_reg
|
| 1227 |
+
|
| 1228 |
+
# if self.train_config.timestep_sampling == 'style' or self.train_config.timestep_sampling == 'content':
|
| 1229 |
+
if self.train_config.timestep_type == 'next_sample':
|
| 1230 |
+
timestep_indices = torch.randint(
|
| 1231 |
+
0,
|
| 1232 |
+
num_train_timesteps - 2, # -1 for 0 idx, -1 so we can step
|
| 1233 |
+
(batch_size,),
|
| 1234 |
+
device=self.device_torch
|
| 1235 |
+
)
|
| 1236 |
+
timestep_indices = timestep_indices.long()
|
| 1237 |
+
elif self.train_config.timestep_type == 'one_step':
|
| 1238 |
+
timestep_indices = torch.zeros((batch_size,), device=self.device_torch, dtype=torch.long)
|
| 1239 |
+
elif content_or_style in ['style', 'content']:
|
| 1240 |
+
# this is from diffusers training code
|
| 1241 |
+
# Cubic sampling for favoring later or earlier timesteps
|
| 1242 |
+
# For more details about why cubic sampling is used for content / structure,
|
| 1243 |
+
# refer to section 3.4 of https://arxiv.org/abs/2302.08453
|
| 1244 |
+
|
| 1245 |
+
# for content / structure, it is best to favor earlier timesteps
|
| 1246 |
+
# for style, it is best to favor later timesteps
|
| 1247 |
+
|
| 1248 |
+
orig_timesteps = torch.rand((batch_size,), device=latents.device)
|
| 1249 |
+
|
| 1250 |
+
if content_or_style == 'content':
|
| 1251 |
+
timestep_indices = orig_timesteps ** 3 * self.train_config.num_train_timesteps
|
| 1252 |
+
elif content_or_style == 'style':
|
| 1253 |
+
timestep_indices = (1 - orig_timesteps ** 3) * self.train_config.num_train_timesteps
|
| 1254 |
+
|
| 1255 |
+
timestep_indices = value_map(
|
| 1256 |
+
timestep_indices,
|
| 1257 |
+
0,
|
| 1258 |
+
self.train_config.num_train_timesteps - 1,
|
| 1259 |
+
min_noise_steps,
|
| 1260 |
+
max_noise_steps
|
| 1261 |
+
)
|
| 1262 |
+
timestep_indices = timestep_indices.long().clamp(
|
| 1263 |
+
min_noise_steps,
|
| 1264 |
+
max_noise_steps
|
| 1265 |
+
)
|
| 1266 |
+
|
| 1267 |
+
elif content_or_style == 'balanced':
|
| 1268 |
+
if min_noise_steps == max_noise_steps:
|
| 1269 |
+
timestep_indices = torch.ones((batch_size,), device=self.device_torch) * min_noise_steps
|
| 1270 |
+
else:
|
| 1271 |
+
# todo, some schedulers use indices, otheres use timesteps. Not sure what to do here
|
| 1272 |
+
min_idx = min_noise_steps + 1
|
| 1273 |
+
max_idx = max_noise_steps - 1
|
| 1274 |
+
if self.train_config.noise_scheduler == 'flowmatch':
|
| 1275 |
+
# flowmatch uses indices, so we need to use indices
|
| 1276 |
+
min_idx = min_noise_steps
|
| 1277 |
+
max_idx = max_noise_steps
|
| 1278 |
+
timestep_indices = torch.randint(
|
| 1279 |
+
min_idx,
|
| 1280 |
+
max_idx,
|
| 1281 |
+
(batch_size,),
|
| 1282 |
+
device=self.device_torch
|
| 1283 |
+
)
|
| 1284 |
+
timestep_indices = timestep_indices.long()
|
| 1285 |
+
else:
|
| 1286 |
+
raise ValueError(f"Unknown content_or_style {content_or_style}")
|
| 1287 |
+
with self.timer('convert_timestep_indices_to_timesteps'):
|
| 1288 |
+
# convert the timestep_indices to a timestep
|
| 1289 |
+
timesteps = self.sd.noise_scheduler.timesteps[timestep_indices.long()]
|
| 1290 |
+
|
| 1291 |
+
with self.timer('prepare_noise'):
|
| 1292 |
+
# get noise
|
| 1293 |
+
noise = self.get_noise(latents, batch_size, dtype=dtype, batch=batch, timestep=timesteps)
|
| 1294 |
+
|
| 1295 |
+
# add dynamic noise offset. Dynamic noise is offsetting the noise to the same channelwise mean as the latents
|
| 1296 |
+
# this will negate any noise offsets
|
| 1297 |
+
if self.train_config.dynamic_noise_offset and not is_reg:
|
| 1298 |
+
latents_channel_mean = latents.mean(dim=(2, 3), keepdim=True) / 2
|
| 1299 |
+
# subtract channel mean to that we compensate for the mean of the latents on the noise offset per channel
|
| 1300 |
+
noise = noise + latents_channel_mean
|
| 1301 |
+
|
| 1302 |
+
if self.train_config.loss_target == 'differential_noise':
|
| 1303 |
+
differential = latents - unaugmented_latents
|
| 1304 |
+
# add noise to differential
|
| 1305 |
+
# noise = noise + differential
|
| 1306 |
+
noise = noise + (differential * 0.5)
|
| 1307 |
+
# noise = value_map(differential, 0, torch.abs(differential).max(), 0, torch.abs(noise).max())
|
| 1308 |
+
latents = unaugmented_latents
|
| 1309 |
+
|
| 1310 |
+
noise_multiplier = self.train_config.noise_multiplier
|
| 1311 |
+
|
| 1312 |
+
s = (noise.shape[0], noise.shape[1], 1, 1)
|
| 1313 |
+
if len(noise.shape) == 5:
|
| 1314 |
+
# if we have a 5d tensor, then we need to do it on a per batch item, per channel basis, per frame
|
| 1315 |
+
s = (noise.shape[0], noise.shape[1], noise.shape[2], 1, 1)
|
| 1316 |
+
|
| 1317 |
+
noise = noise * noise_multiplier
|
| 1318 |
+
|
| 1319 |
+
if self.train_config.do_signal_correction_noise:
|
| 1320 |
+
batch_noise = latents.clone().to(noise.device, dtype=noise.dtype)
|
| 1321 |
+
scn_scale = torch.randn(
|
| 1322 |
+
batch_noise.shape[0], batch_noise.shape[1], 1, 1,
|
| 1323 |
+
device=batch_noise.device,
|
| 1324 |
+
dtype=batch_noise.dtype
|
| 1325 |
+
) * self.train_config.signal_correction_noise_scale
|
| 1326 |
+
batch_noise = batch_noise * scn_scale
|
| 1327 |
+
noise = noise + batch_noise
|
| 1328 |
+
|
| 1329 |
+
if self.train_config.do_batch_noise_correction:
|
| 1330 |
+
if latents.shape[0] == 1:
|
| 1331 |
+
# if we only have a batch size of 1, then we cant do batch noise correction, so we skip it
|
| 1332 |
+
print_acc("Skipping batch noise correction because batch size is 1, increase batch size and num_repeats to use this feature")
|
| 1333 |
+
else:
|
| 1334 |
+
# shuffle tensors ensuring that no tensor is in the same position as before
|
| 1335 |
+
batch_noise = latents.clone().roll(shifts=torch.randint(1, latents.shape[0], (1,)).item(), dims=0).to(noise.device, dtype=noise.dtype)
|
| 1336 |
+
batch_noise_scale = torch.randn(
|
| 1337 |
+
batch_noise.shape[0], batch_noise.shape[1], 1, 1,
|
| 1338 |
+
device=batch_noise.device,
|
| 1339 |
+
dtype=batch_noise.dtype
|
| 1340 |
+
) * self.train_config.batch_noise_correction_scale
|
| 1341 |
+
batch_noise = batch_noise * batch_noise_scale
|
| 1342 |
+
noise = noise + batch_noise
|
| 1343 |
+
|
| 1344 |
+
if self.train_config.random_noise_shift > 0.0:
|
| 1345 |
+
# get random noise -1 to 1
|
| 1346 |
+
noise_shift = torch.randn(
|
| 1347 |
+
batch_size, latents.shape[1], 1, 1,
|
| 1348 |
+
device=noise.device,
|
| 1349 |
+
dtype=noise.dtype
|
| 1350 |
+
) * self.train_config.random_noise_shift
|
| 1351 |
+
# add to noise
|
| 1352 |
+
noise += noise_shift
|
| 1353 |
+
|
| 1354 |
+
if self.train_config.random_noise_multiplier > 0.0:
|
| 1355 |
+
sigma = self.train_config.random_noise_multiplier
|
| 1356 |
+
noise_multiplier = torch.exp(torch.randn(s, device=noise.device, dtype=noise.dtype) * sigma)
|
| 1357 |
+
noise = noise * noise_multiplier
|
| 1358 |
+
with self.timer('make_noisy_latents'):
|
| 1359 |
+
|
| 1360 |
+
latent_multiplier = self.train_config.latent_multiplier
|
| 1361 |
+
|
| 1362 |
+
# handle adaptive scaling mased on std
|
| 1363 |
+
if self.train_config.adaptive_scaling_factor:
|
| 1364 |
+
std = latents.std(dim=(2, 3), keepdim=True)
|
| 1365 |
+
normalizer = 1 / (std + 1e-6)
|
| 1366 |
+
latent_multiplier = normalizer
|
| 1367 |
+
|
| 1368 |
+
latents = latents * latent_multiplier
|
| 1369 |
+
|
| 1370 |
+
if self.train_config.do_blank_stabilization:
|
| 1371 |
+
# zero out latents with blank prompts
|
| 1372 |
+
blank_latent = torch.zeros_like(latents)
|
| 1373 |
+
for i, prompt in enumerate(conditioned_prompts):
|
| 1374 |
+
if prompt.strip() == '':
|
| 1375 |
+
latents[i] = blank_latent[i]
|
| 1376 |
+
|
| 1377 |
+
batch.latents = latents
|
| 1378 |
+
|
| 1379 |
+
# normalize latents to a mean of 0 and an std of 1
|
| 1380 |
+
# mean_zero_latents = latents - latents.mean()
|
| 1381 |
+
# latents = mean_zero_latents / mean_zero_latents.std()
|
| 1382 |
+
|
| 1383 |
+
if batch.unconditional_latents is not None:
|
| 1384 |
+
batch.unconditional_latents = batch.unconditional_latents * self.train_config.latent_multiplier
|
| 1385 |
+
|
| 1386 |
+
|
| 1387 |
+
noisy_latents = self.sd.add_noise(latents, noise, timesteps)
|
| 1388 |
+
|
| 1389 |
+
# determine scaled noise
|
| 1390 |
+
# todo do we need to scale this or does it always predict full intensity
|
| 1391 |
+
# noise = noisy_latents - latents
|
| 1392 |
+
|
| 1393 |
+
# https://github.com/huggingface/diffusers/blob/324d18fba23f6c9d7475b0ff7c777685f7128d40/examples/t2i_adapter/train_t2i_adapter_sdxl.py#L1170C17-L1171C77
|
| 1394 |
+
if self.train_config.loss_target == 'source' or self.train_config.loss_target == 'unaugmented':
|
| 1395 |
+
sigmas = self.get_sigmas(timesteps, len(noisy_latents.shape), noisy_latents.dtype)
|
| 1396 |
+
# add it to the batch
|
| 1397 |
+
batch.sigmas = sigmas
|
| 1398 |
+
# todo is this for sdxl? find out where this came from originally
|
| 1399 |
+
# noisy_latents = noisy_latents / ((sigmas ** 2 + 1) ** 0.5)
|
| 1400 |
+
|
| 1401 |
+
def double_up_tensor(tensor: torch.Tensor):
|
| 1402 |
+
if tensor is None:
|
| 1403 |
+
return None
|
| 1404 |
+
return torch.cat([tensor, tensor], dim=0)
|
| 1405 |
+
|
| 1406 |
+
if do_double:
|
| 1407 |
+
if self.model_config.refiner_name_or_path:
|
| 1408 |
+
# apply refiner double up
|
| 1409 |
+
refiner_timesteps = torch.randint(
|
| 1410 |
+
max_noise_steps,
|
| 1411 |
+
self.train_config.max_denoising_steps,
|
| 1412 |
+
(batch_size,),
|
| 1413 |
+
device=self.device_torch
|
| 1414 |
+
)
|
| 1415 |
+
refiner_timesteps = refiner_timesteps.long()
|
| 1416 |
+
# add our new timesteps on to end
|
| 1417 |
+
timesteps = torch.cat([timesteps, refiner_timesteps], dim=0)
|
| 1418 |
+
|
| 1419 |
+
refiner_noisy_latents = self.sd.noise_scheduler.add_noise(latents, noise, refiner_timesteps)
|
| 1420 |
+
noisy_latents = torch.cat([noisy_latents, refiner_noisy_latents], dim=0)
|
| 1421 |
+
|
| 1422 |
+
else:
|
| 1423 |
+
# just double it
|
| 1424 |
+
noisy_latents = double_up_tensor(noisy_latents)
|
| 1425 |
+
timesteps = double_up_tensor(timesteps)
|
| 1426 |
+
|
| 1427 |
+
noise = double_up_tensor(noise)
|
| 1428 |
+
# prompts are already updated above
|
| 1429 |
+
imgs = double_up_tensor(imgs)
|
| 1430 |
+
batch.mask_tensor = double_up_tensor(batch.mask_tensor)
|
| 1431 |
+
batch.control_tensor = double_up_tensor(batch.control_tensor)
|
| 1432 |
+
|
| 1433 |
+
noisy_latent_multiplier = self.train_config.noisy_latent_multiplier
|
| 1434 |
+
|
| 1435 |
+
if noisy_latent_multiplier != 1.0:
|
| 1436 |
+
noisy_latents = noisy_latents * noisy_latent_multiplier
|
| 1437 |
+
|
| 1438 |
+
# remove grads for these
|
| 1439 |
+
noisy_latents.requires_grad = False
|
| 1440 |
+
noisy_latents = noisy_latents.detach()
|
| 1441 |
+
noise.requires_grad = False
|
| 1442 |
+
noise = noise.detach()
|
| 1443 |
+
|
| 1444 |
+
return noisy_latents, noise, timesteps, conditioned_prompts, imgs
|
| 1445 |
+
|
| 1446 |
+
def setup_adapter(self):
|
| 1447 |
+
# t2i adapter
|
| 1448 |
+
is_t2i = self.adapter_config.type == 't2i'
|
| 1449 |
+
is_control_net = self.adapter_config.type == 'control_net'
|
| 1450 |
+
if self.adapter_config.type == 't2i':
|
| 1451 |
+
suffix = 't2i'
|
| 1452 |
+
elif self.adapter_config.type == 'control_net':
|
| 1453 |
+
suffix = 'cn'
|
| 1454 |
+
elif self.adapter_config.type == 'clip':
|
| 1455 |
+
suffix = 'clip'
|
| 1456 |
+
elif self.adapter_config.type == 'reference':
|
| 1457 |
+
suffix = 'ref'
|
| 1458 |
+
elif self.adapter_config.type.startswith('ip'):
|
| 1459 |
+
suffix = 'ip'
|
| 1460 |
+
else:
|
| 1461 |
+
suffix = 'adapter'
|
| 1462 |
+
adapter_name = self.name
|
| 1463 |
+
if self.network_config is not None:
|
| 1464 |
+
adapter_name = f"{adapter_name}_{suffix}"
|
| 1465 |
+
latest_save_path = self.get_latest_save_path(adapter_name)
|
| 1466 |
+
|
| 1467 |
+
if latest_save_path is not None and not self.adapter_config.train:
|
| 1468 |
+
# the save path is for something else since we are not training
|
| 1469 |
+
latest_save_path = self.adapter_config.name_or_path
|
| 1470 |
+
|
| 1471 |
+
dtype = get_torch_dtype(self.train_config.dtype)
|
| 1472 |
+
if is_t2i:
|
| 1473 |
+
# if we do not have a last save path and we have a name_or_path,
|
| 1474 |
+
# load from that
|
| 1475 |
+
if latest_save_path is None and self.adapter_config.name_or_path is not None:
|
| 1476 |
+
self.adapter = T2IAdapter.from_pretrained(
|
| 1477 |
+
self.adapter_config.name_or_path,
|
| 1478 |
+
torch_dtype=get_torch_dtype(self.train_config.dtype),
|
| 1479 |
+
varient="fp16",
|
| 1480 |
+
# use_safetensors=True,
|
| 1481 |
+
)
|
| 1482 |
+
else:
|
| 1483 |
+
self.adapter = T2IAdapter(
|
| 1484 |
+
in_channels=self.adapter_config.in_channels,
|
| 1485 |
+
channels=self.adapter_config.channels,
|
| 1486 |
+
num_res_blocks=self.adapter_config.num_res_blocks,
|
| 1487 |
+
downscale_factor=self.adapter_config.downscale_factor,
|
| 1488 |
+
adapter_type=self.adapter_config.adapter_type,
|
| 1489 |
+
)
|
| 1490 |
+
elif is_control_net:
|
| 1491 |
+
if self.adapter_config.name_or_path is None:
|
| 1492 |
+
raise ValueError("ControlNet requires a name_or_path to load from currently")
|
| 1493 |
+
load_from_path = self.adapter_config.name_or_path
|
| 1494 |
+
if latest_save_path is not None:
|
| 1495 |
+
load_from_path = latest_save_path
|
| 1496 |
+
self.adapter = ControlNetModel.from_pretrained(
|
| 1497 |
+
load_from_path,
|
| 1498 |
+
torch_dtype=get_torch_dtype(self.train_config.dtype),
|
| 1499 |
+
)
|
| 1500 |
+
elif self.adapter_config.type == 'clip':
|
| 1501 |
+
self.adapter = ClipVisionAdapter(
|
| 1502 |
+
sd=self.sd,
|
| 1503 |
+
adapter_config=self.adapter_config,
|
| 1504 |
+
)
|
| 1505 |
+
elif self.adapter_config.type == 'reference':
|
| 1506 |
+
self.adapter = ReferenceAdapter(
|
| 1507 |
+
sd=self.sd,
|
| 1508 |
+
adapter_config=self.adapter_config,
|
| 1509 |
+
)
|
| 1510 |
+
elif self.adapter_config.type.startswith('ip'):
|
| 1511 |
+
self.adapter = IPAdapter(
|
| 1512 |
+
sd=self.sd,
|
| 1513 |
+
adapter_config=self.adapter_config,
|
| 1514 |
+
)
|
| 1515 |
+
if self.train_config.gradient_checkpointing:
|
| 1516 |
+
self.adapter.enable_gradient_checkpointing()
|
| 1517 |
+
else:
|
| 1518 |
+
self.adapter = CustomAdapter(
|
| 1519 |
+
sd=self.sd,
|
| 1520 |
+
adapter_config=self.adapter_config,
|
| 1521 |
+
train_config=self.train_config,
|
| 1522 |
+
)
|
| 1523 |
+
self.adapter.to(self.device_torch, dtype=dtype)
|
| 1524 |
+
if latest_save_path is not None and not is_control_net:
|
| 1525 |
+
# load adapter from path
|
| 1526 |
+
print_acc(f"Loading adapter from {latest_save_path}")
|
| 1527 |
+
if is_t2i:
|
| 1528 |
+
loaded_state_dict = load_t2i_model(
|
| 1529 |
+
latest_save_path,
|
| 1530 |
+
self.device,
|
| 1531 |
+
dtype=dtype
|
| 1532 |
+
)
|
| 1533 |
+
self.adapter.load_state_dict(loaded_state_dict)
|
| 1534 |
+
elif self.adapter_config.type.startswith('ip'):
|
| 1535 |
+
# ip adapter
|
| 1536 |
+
loaded_state_dict = load_ip_adapter_model(
|
| 1537 |
+
latest_save_path,
|
| 1538 |
+
self.device,
|
| 1539 |
+
dtype=dtype,
|
| 1540 |
+
direct_load=self.adapter_config.train_only_image_encoder
|
| 1541 |
+
)
|
| 1542 |
+
self.adapter.load_state_dict(loaded_state_dict)
|
| 1543 |
+
else:
|
| 1544 |
+
# custom adapter
|
| 1545 |
+
loaded_state_dict = load_custom_adapter_model(
|
| 1546 |
+
latest_save_path,
|
| 1547 |
+
self.device,
|
| 1548 |
+
dtype=dtype
|
| 1549 |
+
)
|
| 1550 |
+
self.adapter.load_state_dict(loaded_state_dict)
|
| 1551 |
+
if latest_save_path is not None and self.adapter_config.train:
|
| 1552 |
+
self.load_training_state_from_metadata(latest_save_path)
|
| 1553 |
+
# set trainable params
|
| 1554 |
+
self.sd.adapter = self.adapter
|
| 1555 |
+
|
| 1556 |
+
def run(self):
|
| 1557 |
+
# torch.autograd.set_detect_anomaly(True)
|
| 1558 |
+
# run base process run
|
| 1559 |
+
BaseTrainProcess.run(self)
|
| 1560 |
+
params = []
|
| 1561 |
+
|
| 1562 |
+
### HOOK ###
|
| 1563 |
+
self.hook_before_model_load()
|
| 1564 |
+
model_config_to_load = copy.deepcopy(self.model_config)
|
| 1565 |
+
|
| 1566 |
+
if self.is_fine_tuning or self.train_config.merge_network_on_save:
|
| 1567 |
+
# get the latest checkpoint
|
| 1568 |
+
# check to see if we have a latest save
|
| 1569 |
+
latest_save_path = self.get_latest_save_path()
|
| 1570 |
+
|
| 1571 |
+
if latest_save_path is not None:
|
| 1572 |
+
print_acc(f"#### IMPORTANT RESUMING FROM {latest_save_path} ####")
|
| 1573 |
+
model_config_to_load.name_or_path = latest_save_path
|
| 1574 |
+
self.load_training_state_from_metadata(latest_save_path)
|
| 1575 |
+
|
| 1576 |
+
ModelClass = get_model_class(self.model_config)
|
| 1577 |
+
# if the model class has get_train_scheduler static method
|
| 1578 |
+
if hasattr(ModelClass, 'get_train_scheduler'):
|
| 1579 |
+
sampler = ModelClass.get_train_scheduler()
|
| 1580 |
+
else:
|
| 1581 |
+
# get the noise scheduler
|
| 1582 |
+
arch = 'sd'
|
| 1583 |
+
if self.model_config.is_pixart:
|
| 1584 |
+
arch = 'pixart'
|
| 1585 |
+
if self.model_config.is_flux:
|
| 1586 |
+
arch = 'flux'
|
| 1587 |
+
if self.model_config.is_lumina2:
|
| 1588 |
+
arch = 'lumina2'
|
| 1589 |
+
sampler = get_sampler(
|
| 1590 |
+
self.train_config.noise_scheduler,
|
| 1591 |
+
{
|
| 1592 |
+
"prediction_type": "v_prediction" if self.model_config.is_v_pred else "epsilon",
|
| 1593 |
+
},
|
| 1594 |
+
arch=arch,
|
| 1595 |
+
)
|
| 1596 |
+
|
| 1597 |
+
if self.train_config.train_refiner and self.model_config.refiner_name_or_path is not None and self.network_config is None:
|
| 1598 |
+
previous_refiner_save = self.get_latest_save_path(self.job.name + '_refiner')
|
| 1599 |
+
if previous_refiner_save is not None:
|
| 1600 |
+
model_config_to_load.refiner_name_or_path = previous_refiner_save
|
| 1601 |
+
self.load_training_state_from_metadata(previous_refiner_save)
|
| 1602 |
+
|
| 1603 |
+
self.sd = ModelClass(
|
| 1604 |
+
# todo handle single gpu and multi gpu here
|
| 1605 |
+
# device=self.device,
|
| 1606 |
+
device=self.accelerator.device,
|
| 1607 |
+
model_config=model_config_to_load,
|
| 1608 |
+
dtype=self.train_config.dtype,
|
| 1609 |
+
custom_pipeline=self.custom_pipeline,
|
| 1610 |
+
noise_scheduler=sampler,
|
| 1611 |
+
)
|
| 1612 |
+
|
| 1613 |
+
self.hook_after_sd_init_before_load()
|
| 1614 |
+
# run base sd process run
|
| 1615 |
+
self.sd.load_model()
|
| 1616 |
+
|
| 1617 |
+
self.sd.add_after_sample_image_hook(self.sample_step_hook)
|
| 1618 |
+
|
| 1619 |
+
dtype = get_torch_dtype(self.train_config.dtype)
|
| 1620 |
+
|
| 1621 |
+
# model is loaded from BaseSDProcess
|
| 1622 |
+
unet = self.sd.unet
|
| 1623 |
+
vae = self.sd.vae
|
| 1624 |
+
tokenizer = self.sd.tokenizer
|
| 1625 |
+
text_encoder = self.sd.text_encoder
|
| 1626 |
+
noise_scheduler = self.sd.noise_scheduler
|
| 1627 |
+
|
| 1628 |
+
if self.train_config.xformers:
|
| 1629 |
+
vae.enable_xformers_memory_efficient_attention()
|
| 1630 |
+
unet.enable_xformers_memory_efficient_attention()
|
| 1631 |
+
if isinstance(text_encoder, list):
|
| 1632 |
+
for te in text_encoder:
|
| 1633 |
+
# if it has it
|
| 1634 |
+
if hasattr(te, 'enable_xformers_memory_efficient_attention'):
|
| 1635 |
+
te.enable_xformers_memory_efficient_attention()
|
| 1636 |
+
|
| 1637 |
+
if self.train_config.attention_backend != 'native':
|
| 1638 |
+
if hasattr(vae, 'set_attention_backend'):
|
| 1639 |
+
vae.set_attention_backend(self.train_config.attention_backend)
|
| 1640 |
+
if hasattr(unet, 'set_attention_backend'):
|
| 1641 |
+
unet.set_attention_backend(self.train_config.attention_backend)
|
| 1642 |
+
if isinstance(text_encoder, list):
|
| 1643 |
+
for te in text_encoder:
|
| 1644 |
+
if hasattr(te, 'set_attention_backend'):
|
| 1645 |
+
te.set_attention_backend(self.train_config.attention_backend)
|
| 1646 |
+
else:
|
| 1647 |
+
if hasattr(text_encoder, 'set_attention_backend'):
|
| 1648 |
+
text_encoder.set_attention_backend(self.train_config.attention_backend)
|
| 1649 |
+
if self.train_config.sdp:
|
| 1650 |
+
torch.backends.cuda.enable_math_sdp(True)
|
| 1651 |
+
torch.backends.cuda.enable_flash_sdp(True)
|
| 1652 |
+
torch.backends.cuda.enable_mem_efficient_sdp(True)
|
| 1653 |
+
|
| 1654 |
+
# # check if we have sage and is flux
|
| 1655 |
+
# if self.sd.is_flux:
|
| 1656 |
+
# # try_to_activate_sage_attn()
|
| 1657 |
+
# try:
|
| 1658 |
+
# from sageattention import sageattn
|
| 1659 |
+
# from toolkit.models.flux_sage_attn import FluxSageAttnProcessor2_0
|
| 1660 |
+
# model: FluxTransformer2DModel = self.sd.unet
|
| 1661 |
+
# # enable sage attention on each block
|
| 1662 |
+
# for block in model.transformer_blocks:
|
| 1663 |
+
# processor = FluxSageAttnProcessor2_0()
|
| 1664 |
+
# block.attn.set_processor(processor)
|
| 1665 |
+
# for block in model.single_transformer_blocks:
|
| 1666 |
+
# processor = FluxSageAttnProcessor2_0()
|
| 1667 |
+
# block.attn.set_processor(processor)
|
| 1668 |
+
|
| 1669 |
+
# except ImportError:
|
| 1670 |
+
# print_acc("sage attention is not installed. Using SDP instead")
|
| 1671 |
+
|
| 1672 |
+
if self.train_config.gradient_checkpointing:
|
| 1673 |
+
# if has method enable_gradient_checkpointing
|
| 1674 |
+
if hasattr(unet, 'enable_gradient_checkpointing'):
|
| 1675 |
+
unet.enable_gradient_checkpointing()
|
| 1676 |
+
elif hasattr(unet, 'gradient_checkpointing'):
|
| 1677 |
+
unet.gradient_checkpointing = True
|
| 1678 |
+
else:
|
| 1679 |
+
print("Gradient checkpointing not supported on this model")
|
| 1680 |
+
if isinstance(text_encoder, list):
|
| 1681 |
+
for te in text_encoder:
|
| 1682 |
+
if hasattr(te, 'enable_gradient_checkpointing'):
|
| 1683 |
+
te.enable_gradient_checkpointing()
|
| 1684 |
+
if hasattr(te, "gradient_checkpointing_enable"):
|
| 1685 |
+
te.gradient_checkpointing_enable()
|
| 1686 |
+
else:
|
| 1687 |
+
if hasattr(text_encoder, 'enable_gradient_checkpointing'):
|
| 1688 |
+
text_encoder.enable_gradient_checkpointing()
|
| 1689 |
+
if hasattr(text_encoder, "gradient_checkpointing_enable"):
|
| 1690 |
+
text_encoder.gradient_checkpointing_enable()
|
| 1691 |
+
|
| 1692 |
+
if self.sd.refiner_unet is not None:
|
| 1693 |
+
self.sd.refiner_unet.to(self.device_torch, dtype=dtype)
|
| 1694 |
+
self.sd.refiner_unet.requires_grad_(False)
|
| 1695 |
+
self.sd.refiner_unet.eval()
|
| 1696 |
+
if self.train_config.xformers:
|
| 1697 |
+
self.sd.refiner_unet.enable_xformers_memory_efficient_attention()
|
| 1698 |
+
if self.train_config.gradient_checkpointing:
|
| 1699 |
+
self.sd.refiner_unet.enable_gradient_checkpointing()
|
| 1700 |
+
|
| 1701 |
+
if isinstance(text_encoder, list):
|
| 1702 |
+
for te in text_encoder:
|
| 1703 |
+
te.requires_grad_(False)
|
| 1704 |
+
te.eval()
|
| 1705 |
+
else:
|
| 1706 |
+
text_encoder.requires_grad_(False)
|
| 1707 |
+
text_encoder.eval()
|
| 1708 |
+
unet.to(self.device_torch, dtype=dtype)
|
| 1709 |
+
unet.requires_grad_(False)
|
| 1710 |
+
unet.eval()
|
| 1711 |
+
vae = vae.to(torch.device('cpu'), dtype=dtype)
|
| 1712 |
+
vae.requires_grad_(False)
|
| 1713 |
+
vae.eval()
|
| 1714 |
+
if self.train_config.learnable_snr_gos:
|
| 1715 |
+
self.snr_gos = LearnableSNRGamma(
|
| 1716 |
+
self.sd.noise_scheduler, device=self.device_torch
|
| 1717 |
+
)
|
| 1718 |
+
# check to see if previous settings exist
|
| 1719 |
+
path_to_load = os.path.join(self.save_root, 'learnable_snr.json')
|
| 1720 |
+
if os.path.exists(path_to_load):
|
| 1721 |
+
with open(path_to_load, 'r') as f:
|
| 1722 |
+
json_data = json.load(f)
|
| 1723 |
+
if 'offset' in json_data:
|
| 1724 |
+
# legacy
|
| 1725 |
+
self.snr_gos.offset_2.data = torch.tensor(json_data['offset'], device=self.device_torch)
|
| 1726 |
+
else:
|
| 1727 |
+
self.snr_gos.offset_1.data = torch.tensor(json_data['offset_1'], device=self.device_torch)
|
| 1728 |
+
self.snr_gos.offset_2.data = torch.tensor(json_data['offset_2'], device=self.device_torch)
|
| 1729 |
+
self.snr_gos.scale.data = torch.tensor(json_data['scale'], device=self.device_torch)
|
| 1730 |
+
self.snr_gos.gamma.data = torch.tensor(json_data['gamma'], device=self.device_torch)
|
| 1731 |
+
|
| 1732 |
+
self.hook_after_model_load()
|
| 1733 |
+
flush()
|
| 1734 |
+
if not self.is_fine_tuning:
|
| 1735 |
+
if self.network_config is not None:
|
| 1736 |
+
# TODO should we completely switch to LycorisSpecialNetwork?
|
| 1737 |
+
network_kwargs = self.network_config.network_kwargs
|
| 1738 |
+
is_lycoris = False
|
| 1739 |
+
is_lorm = self.network_config.type.lower() == 'lorm'
|
| 1740 |
+
# default to LoCON if there are any conv layers or if it is named
|
| 1741 |
+
NetworkClass = LoRASpecialNetwork
|
| 1742 |
+
if self.network_config.type.lower() == 'locon' or self.network_config.type.lower() == 'lycoris':
|
| 1743 |
+
NetworkClass = LycorisSpecialNetwork
|
| 1744 |
+
is_lycoris = True
|
| 1745 |
+
|
| 1746 |
+
if is_lorm:
|
| 1747 |
+
network_kwargs['ignore_if_contains'] = lorm_ignore_if_contains
|
| 1748 |
+
network_kwargs['parameter_threshold'] = lorm_parameter_threshold
|
| 1749 |
+
network_kwargs['target_lin_modules'] = LORM_TARGET_REPLACE_MODULE
|
| 1750 |
+
|
| 1751 |
+
# if is_lycoris:
|
| 1752 |
+
# preset = PRESET['full']
|
| 1753 |
+
# NetworkClass.apply_preset(preset)
|
| 1754 |
+
|
| 1755 |
+
if hasattr(self.sd, 'target_lora_modules'):
|
| 1756 |
+
network_kwargs['target_lin_modules'] = self.sd.target_lora_modules
|
| 1757 |
+
|
| 1758 |
+
self.network = NetworkClass(
|
| 1759 |
+
text_encoder=text_encoder,
|
| 1760 |
+
unet=self.sd.get_model_to_train(),
|
| 1761 |
+
lora_dim=self.network_config.linear,
|
| 1762 |
+
multiplier=1.0,
|
| 1763 |
+
alpha=self.network_config.linear_alpha,
|
| 1764 |
+
train_unet=self.train_config.train_unet,
|
| 1765 |
+
train_text_encoder=self.train_config.train_text_encoder,
|
| 1766 |
+
conv_lora_dim=self.network_config.conv,
|
| 1767 |
+
conv_alpha=self.network_config.conv_alpha,
|
| 1768 |
+
is_sdxl=self.model_config.is_xl or self.model_config.is_ssd,
|
| 1769 |
+
is_v2=self.model_config.is_v2,
|
| 1770 |
+
is_v3=self.model_config.is_v3,
|
| 1771 |
+
is_pixart=self.model_config.is_pixart,
|
| 1772 |
+
is_auraflow=self.model_config.is_auraflow,
|
| 1773 |
+
is_flux=self.model_config.is_flux,
|
| 1774 |
+
is_lumina2=self.model_config.is_lumina2,
|
| 1775 |
+
is_ssd=self.model_config.is_ssd,
|
| 1776 |
+
is_vega=self.model_config.is_vega,
|
| 1777 |
+
dropout=self.network_config.dropout,
|
| 1778 |
+
use_text_encoder_1=self.model_config.use_text_encoder_1,
|
| 1779 |
+
use_text_encoder_2=self.model_config.use_text_encoder_2,
|
| 1780 |
+
use_bias=is_lorm,
|
| 1781 |
+
is_lorm=is_lorm,
|
| 1782 |
+
network_config=self.network_config,
|
| 1783 |
+
network_type=self.network_config.type,
|
| 1784 |
+
transformer_only=self.network_config.transformer_only,
|
| 1785 |
+
is_transformer=self.sd.is_transformer,
|
| 1786 |
+
base_model=self.sd,
|
| 1787 |
+
**network_kwargs
|
| 1788 |
+
)
|
| 1789 |
+
|
| 1790 |
+
|
| 1791 |
+
# todo switch everything to proper mixed precision like this
|
| 1792 |
+
self.network.force_to(self.device_torch, dtype=torch.float32)
|
| 1793 |
+
# give network to sd so it can use it
|
| 1794 |
+
self.sd.network = self.network
|
| 1795 |
+
self.network._update_torch_multiplier()
|
| 1796 |
+
|
| 1797 |
+
self.network.apply_to(
|
| 1798 |
+
text_encoder,
|
| 1799 |
+
unet,
|
| 1800 |
+
self.train_config.train_text_encoder,
|
| 1801 |
+
self.train_config.train_unet
|
| 1802 |
+
)
|
| 1803 |
+
|
| 1804 |
+
# we cannot merge in if quantized
|
| 1805 |
+
if self.model_config.quantize or self.model_config.layer_offloading:
|
| 1806 |
+
# todo find a way around this
|
| 1807 |
+
self.network.can_merge_in = False
|
| 1808 |
+
|
| 1809 |
+
if is_lorm:
|
| 1810 |
+
self.network.is_lorm = True
|
| 1811 |
+
# make sure it is on the right device
|
| 1812 |
+
self.sd.unet.to(self.sd.device, dtype=dtype)
|
| 1813 |
+
original_unet_param_count = count_parameters(self.sd.unet)
|
| 1814 |
+
self.network.setup_lorm()
|
| 1815 |
+
new_unet_param_count = original_unet_param_count - self.network.calculate_lorem_parameter_reduction()
|
| 1816 |
+
|
| 1817 |
+
print_lorm_extract_details(
|
| 1818 |
+
start_num_params=original_unet_param_count,
|
| 1819 |
+
end_num_params=new_unet_param_count,
|
| 1820 |
+
num_replaced=len(self.network.get_all_modules()),
|
| 1821 |
+
)
|
| 1822 |
+
|
| 1823 |
+
self.network.prepare_grad_etc(text_encoder, unet)
|
| 1824 |
+
flush()
|
| 1825 |
+
|
| 1826 |
+
# LyCORIS doesnt have default_lr
|
| 1827 |
+
config = {
|
| 1828 |
+
'text_encoder_lr': self.train_config.lr,
|
| 1829 |
+
'unet_lr': self.train_config.lr,
|
| 1830 |
+
}
|
| 1831 |
+
sig = inspect.signature(self.network.prepare_optimizer_params)
|
| 1832 |
+
if 'default_lr' in sig.parameters:
|
| 1833 |
+
config['default_lr'] = self.train_config.lr
|
| 1834 |
+
if 'learning_rate' in sig.parameters:
|
| 1835 |
+
config['learning_rate'] = self.train_config.lr
|
| 1836 |
+
params_net = self.network.prepare_optimizer_params(
|
| 1837 |
+
**config
|
| 1838 |
+
)
|
| 1839 |
+
|
| 1840 |
+
params += params_net
|
| 1841 |
+
|
| 1842 |
+
if self.train_config.gradient_checkpointing:
|
| 1843 |
+
self.network.enable_gradient_checkpointing()
|
| 1844 |
+
|
| 1845 |
+
lora_name = self.name
|
| 1846 |
+
# need to adapt name so they are not mixed up
|
| 1847 |
+
if self.named_lora:
|
| 1848 |
+
lora_name = f"{lora_name}_LoRA"
|
| 1849 |
+
|
| 1850 |
+
latest_save_path = self.get_latest_save_path(lora_name)
|
| 1851 |
+
extra_weights = None
|
| 1852 |
+
if latest_save_path is not None and not self.train_config.merge_network_on_save:
|
| 1853 |
+
print_acc(f"#### IMPORTANT RESUMING FROM {latest_save_path} ####")
|
| 1854 |
+
print_acc(f"Loading from {latest_save_path}")
|
| 1855 |
+
extra_weights = self.load_weights(latest_save_path)
|
| 1856 |
+
self.network.multiplier = 1.0
|
| 1857 |
+
|
| 1858 |
+
if self.network_config.layer_offloading:
|
| 1859 |
+
MemoryManager.attach(
|
| 1860 |
+
self.network,
|
| 1861 |
+
self.device_torch
|
| 1862 |
+
)
|
| 1863 |
+
|
| 1864 |
+
if self.embed_config is not None:
|
| 1865 |
+
# we are doing embedding training as well
|
| 1866 |
+
self.embedding = Embedding(
|
| 1867 |
+
sd=self.sd,
|
| 1868 |
+
embed_config=self.embed_config
|
| 1869 |
+
)
|
| 1870 |
+
latest_save_path = self.get_latest_save_path(self.embed_config.trigger)
|
| 1871 |
+
# load last saved weights
|
| 1872 |
+
if latest_save_path is not None:
|
| 1873 |
+
self.embedding.load_embedding_from_file(latest_save_path, self.device_torch)
|
| 1874 |
+
if self.embedding.step > 1:
|
| 1875 |
+
self.step_num = self.embedding.step
|
| 1876 |
+
self.start_step = self.step_num
|
| 1877 |
+
|
| 1878 |
+
# self.step_num = self.embedding.step
|
| 1879 |
+
# self.start_step = self.step_num
|
| 1880 |
+
params.append({
|
| 1881 |
+
'params': list(self.embedding.get_trainable_params()),
|
| 1882 |
+
'lr': self.train_config.embedding_lr
|
| 1883 |
+
})
|
| 1884 |
+
|
| 1885 |
+
flush()
|
| 1886 |
+
|
| 1887 |
+
if self.decorator_config is not None:
|
| 1888 |
+
self.decorator = Decorator(
|
| 1889 |
+
num_tokens=self.decorator_config.num_tokens,
|
| 1890 |
+
token_size=4096 # t5xxl hidden size for flux
|
| 1891 |
+
)
|
| 1892 |
+
latest_save_path = self.get_latest_save_path()
|
| 1893 |
+
# load last saved weights
|
| 1894 |
+
if latest_save_path is not None:
|
| 1895 |
+
state_dict = load_file(latest_save_path)
|
| 1896 |
+
self.decorator.load_state_dict(state_dict)
|
| 1897 |
+
self.load_training_state_from_metadata(latest_save_path)
|
| 1898 |
+
|
| 1899 |
+
params.append({
|
| 1900 |
+
'params': list(self.decorator.parameters()),
|
| 1901 |
+
'lr': self.train_config.lr
|
| 1902 |
+
})
|
| 1903 |
+
|
| 1904 |
+
# give it to the sd network
|
| 1905 |
+
self.sd.decorator = self.decorator
|
| 1906 |
+
self.decorator.to(self.device_torch, dtype=torch.float32)
|
| 1907 |
+
self.decorator.train()
|
| 1908 |
+
|
| 1909 |
+
flush()
|
| 1910 |
+
|
| 1911 |
+
if self.adapter_config is not None:
|
| 1912 |
+
self.setup_adapter()
|
| 1913 |
+
if self.adapter_config.train:
|
| 1914 |
+
|
| 1915 |
+
if isinstance(self.adapter, IPAdapter):
|
| 1916 |
+
# we have custom LR groups for IPAdapter
|
| 1917 |
+
adapter_param_groups = self.adapter.get_parameter_groups(self.train_config.adapter_lr)
|
| 1918 |
+
for group in adapter_param_groups:
|
| 1919 |
+
params.append(group)
|
| 1920 |
+
else:
|
| 1921 |
+
# set trainable params
|
| 1922 |
+
params.append({
|
| 1923 |
+
'params': list(self.adapter.parameters()),
|
| 1924 |
+
'lr': self.train_config.adapter_lr
|
| 1925 |
+
})
|
| 1926 |
+
|
| 1927 |
+
if self.train_config.gradient_checkpointing:
|
| 1928 |
+
self.adapter.enable_gradient_checkpointing()
|
| 1929 |
+
flush()
|
| 1930 |
+
|
| 1931 |
+
params = self.load_additional_training_modules(params)
|
| 1932 |
+
|
| 1933 |
+
else: # no network, embedding or adapter
|
| 1934 |
+
# set the device state preset before getting params
|
| 1935 |
+
self.sd.set_device_state(self.get_params_device_state_preset)
|
| 1936 |
+
|
| 1937 |
+
# params = self.get_params()
|
| 1938 |
+
if len(params) == 0:
|
| 1939 |
+
# will only return savable weights and ones with grad
|
| 1940 |
+
params = self.sd.prepare_optimizer_params(
|
| 1941 |
+
unet=self.train_config.train_unet,
|
| 1942 |
+
text_encoder=self.train_config.train_text_encoder,
|
| 1943 |
+
text_encoder_lr=self.train_config.lr,
|
| 1944 |
+
unet_lr=self.train_config.lr,
|
| 1945 |
+
default_lr=self.train_config.lr,
|
| 1946 |
+
refiner=self.train_config.train_refiner and self.sd.refiner_unet is not None,
|
| 1947 |
+
refiner_lr=self.train_config.refiner_lr,
|
| 1948 |
+
)
|
| 1949 |
+
# we may be using it for prompt injections
|
| 1950 |
+
if self.adapter_config is not None and self.adapter is None:
|
| 1951 |
+
self.setup_adapter()
|
| 1952 |
+
flush()
|
| 1953 |
+
|
| 1954 |
+
### HOOK ###
|
| 1955 |
+
params = self.hook_add_extra_train_params(params)
|
| 1956 |
+
self.params = params
|
| 1957 |
+
# self.params = []
|
| 1958 |
+
|
| 1959 |
+
# for param in params:
|
| 1960 |
+
# if isinstance(param, dict):
|
| 1961 |
+
# self.params += param['params']
|
| 1962 |
+
# else:
|
| 1963 |
+
# self.params.append(param)
|
| 1964 |
+
|
| 1965 |
+
if self.train_config.start_step is not None:
|
| 1966 |
+
self.step_num = self.train_config.start_step
|
| 1967 |
+
self.start_step = self.step_num
|
| 1968 |
+
|
| 1969 |
+
optimizer_type = self.train_config.optimizer.lower()
|
| 1970 |
+
|
| 1971 |
+
# esure params require grad
|
| 1972 |
+
self.ensure_params_requires_grad(force=True)
|
| 1973 |
+
optimizer = get_optimizer(self.params, optimizer_type, learning_rate=self.train_config.lr,
|
| 1974 |
+
optimizer_params=self.train_config.optimizer_params)
|
| 1975 |
+
self.optimizer = optimizer
|
| 1976 |
+
|
| 1977 |
+
# set it to do paramiter swapping
|
| 1978 |
+
if self.train_config.do_paramiter_swapping:
|
| 1979 |
+
# only works for adafactor, but it should have thrown an error prior to this otherwise
|
| 1980 |
+
self.optimizer.enable_paramiter_swapping(self.train_config.paramiter_swapping_factor)
|
| 1981 |
+
|
| 1982 |
+
# check if it exists
|
| 1983 |
+
optimizer_state_filename = f'optimizer.pt'
|
| 1984 |
+
optimizer_state_file_path = os.path.join(self.save_root, optimizer_state_filename)
|
| 1985 |
+
if os.path.exists(optimizer_state_file_path):
|
| 1986 |
+
# try to load
|
| 1987 |
+
# previous param groups
|
| 1988 |
+
# previous_params = copy.deepcopy(optimizer.param_groups)
|
| 1989 |
+
previous_lrs = []
|
| 1990 |
+
for group in optimizer.param_groups:
|
| 1991 |
+
previous_lrs.append(group['lr'])
|
| 1992 |
+
|
| 1993 |
+
load_optimizer = True
|
| 1994 |
+
if self.network is not None:
|
| 1995 |
+
if self.network.did_change_weights:
|
| 1996 |
+
# do not load optimizer if the network changed, it will result in
|
| 1997 |
+
# a double state that will oom.
|
| 1998 |
+
load_optimizer = False
|
| 1999 |
+
|
| 2000 |
+
if load_optimizer:
|
| 2001 |
+
try:
|
| 2002 |
+
print_acc(f"Loading optimizer state from {optimizer_state_file_path}")
|
| 2003 |
+
optimizer_state_dict = torch.load(optimizer_state_file_path, weights_only=False)
|
| 2004 |
+
optimizer.load_state_dict(optimizer_state_dict)
|
| 2005 |
+
del optimizer_state_dict
|
| 2006 |
+
flush()
|
| 2007 |
+
except Exception as e:
|
| 2008 |
+
print_acc(f"Failed to load optimizer state from {optimizer_state_file_path}")
|
| 2009 |
+
print_acc(e)
|
| 2010 |
+
|
| 2011 |
+
# update the optimizer LR from the params
|
| 2012 |
+
print_acc(f"Updating optimizer LR from params")
|
| 2013 |
+
if len(previous_lrs) > 0:
|
| 2014 |
+
for i, group in enumerate(optimizer.param_groups):
|
| 2015 |
+
group['lr'] = previous_lrs[i]
|
| 2016 |
+
group['initial_lr'] = previous_lrs[i]
|
| 2017 |
+
|
| 2018 |
+
# Update the learning rates if they changed
|
| 2019 |
+
# optimizer.param_groups = previous_params
|
| 2020 |
+
|
| 2021 |
+
lr_scheduler_params = self.train_config.lr_scheduler_params
|
| 2022 |
+
|
| 2023 |
+
# make sure it had bare minimum
|
| 2024 |
+
if 'max_iterations' not in lr_scheduler_params:
|
| 2025 |
+
lr_scheduler_params['total_iters'] = self.train_config.steps
|
| 2026 |
+
|
| 2027 |
+
lr_scheduler = get_lr_scheduler(
|
| 2028 |
+
self.train_config.lr_scheduler,
|
| 2029 |
+
optimizer,
|
| 2030 |
+
**lr_scheduler_params
|
| 2031 |
+
)
|
| 2032 |
+
self.lr_scheduler = lr_scheduler
|
| 2033 |
+
|
| 2034 |
+
### HOOk ###
|
| 2035 |
+
self.before_dataset_load()
|
| 2036 |
+
# load datasets if passed in the root process
|
| 2037 |
+
if self.datasets is not None:
|
| 2038 |
+
self.data_loader = get_dataloader_from_datasets(self.datasets, self.train_config.batch_size, self.sd)
|
| 2039 |
+
if self.datasets_reg is not None:
|
| 2040 |
+
self.data_loader_reg = get_dataloader_from_datasets(self.datasets_reg, self.train_config.batch_size,
|
| 2041 |
+
self.sd)
|
| 2042 |
+
|
| 2043 |
+
flush()
|
| 2044 |
+
self.last_save_step = self.step_num
|
| 2045 |
+
### HOOK ###
|
| 2046 |
+
self.hook_before_train_loop()
|
| 2047 |
+
|
| 2048 |
+
# compile the model if needed (must be after LoRA/adapter injection AND accelerator.prepare)
|
| 2049 |
+
if self.model_config.compile:
|
| 2050 |
+
try:
|
| 2051 |
+
# make sure it is on the gpu
|
| 2052 |
+
self.sd.unet.to(self.device_torch)
|
| 2053 |
+
print_acc("Compiling model with torch.compile. The first forward will hang for a while using this. This is normal.")
|
| 2054 |
+
self.sd.unet = torch.compile(self.sd.unet)
|
| 2055 |
+
except Exception as e:
|
| 2056 |
+
print_acc(f"Failed to compile model: {e}")
|
| 2057 |
+
print_acc("Continuing without compilation")
|
| 2058 |
+
|
| 2059 |
+
if self.has_first_sample_requested and self.step_num <= 1 and not self.train_config.disable_sampling:
|
| 2060 |
+
print_acc("Generating first sample from first sample config")
|
| 2061 |
+
self.sample(0, is_first=True)
|
| 2062 |
+
|
| 2063 |
+
# sample first
|
| 2064 |
+
if self.train_config.skip_first_sample or self.train_config.disable_sampling:
|
| 2065 |
+
print_acc("Skipping first sample due to config setting")
|
| 2066 |
+
elif self.step_num <= 1 or self.train_config.force_first_sample:
|
| 2067 |
+
print_acc("Generating baseline samples before training")
|
| 2068 |
+
self.sample(self.step_num)
|
| 2069 |
+
|
| 2070 |
+
if self.accelerator.is_local_main_process:
|
| 2071 |
+
self.progress_bar = ToolkitProgressBar(
|
| 2072 |
+
total=self.train_config.steps,
|
| 2073 |
+
desc=self.job.name,
|
| 2074 |
+
leave=True,
|
| 2075 |
+
initial=self.step_num,
|
| 2076 |
+
iterable=range(0, self.train_config.steps),
|
| 2077 |
+
)
|
| 2078 |
+
self.progress_bar.pause()
|
| 2079 |
+
else:
|
| 2080 |
+
self.progress_bar = None
|
| 2081 |
+
|
| 2082 |
+
if self.data_loader is not None:
|
| 2083 |
+
dataloader = self.data_loader
|
| 2084 |
+
dataloader_iterator = iter(dataloader)
|
| 2085 |
+
else:
|
| 2086 |
+
dataloader = None
|
| 2087 |
+
dataloader_iterator = None
|
| 2088 |
+
|
| 2089 |
+
if self.data_loader_reg is not None:
|
| 2090 |
+
dataloader_reg = self.data_loader_reg
|
| 2091 |
+
dataloader_iterator_reg = iter(dataloader_reg)
|
| 2092 |
+
else:
|
| 2093 |
+
dataloader_reg = None
|
| 2094 |
+
dataloader_iterator_reg = None
|
| 2095 |
+
|
| 2096 |
+
# zero any gradients
|
| 2097 |
+
optimizer.zero_grad()
|
| 2098 |
+
|
| 2099 |
+
self.lr_scheduler.step(self.step_num)
|
| 2100 |
+
|
| 2101 |
+
self.sd.set_device_state(self.train_device_state_preset)
|
| 2102 |
+
flush()
|
| 2103 |
+
# self.step_num = 0
|
| 2104 |
+
|
| 2105 |
+
# print_acc(f"Compiling Model")
|
| 2106 |
+
# torch.compile(self.sd.unet, dynamic=True)
|
| 2107 |
+
|
| 2108 |
+
# make sure all params require grad
|
| 2109 |
+
self.ensure_params_requires_grad(force=True)
|
| 2110 |
+
|
| 2111 |
+
|
| 2112 |
+
###################################################################
|
| 2113 |
+
# TRAIN LOOP
|
| 2114 |
+
###################################################################
|
| 2115 |
+
|
| 2116 |
+
|
| 2117 |
+
start_step_num = self.step_num
|
| 2118 |
+
did_first_flush = False
|
| 2119 |
+
flush_next = False
|
| 2120 |
+
for step in range(start_step_num, self.train_config.steps):
|
| 2121 |
+
if self.train_config.do_paramiter_swapping:
|
| 2122 |
+
self.optimizer.optimizer.swap_paramiters()
|
| 2123 |
+
self.timer.start('train_loop')
|
| 2124 |
+
if flush_next:
|
| 2125 |
+
flush()
|
| 2126 |
+
flush_next = False
|
| 2127 |
+
if self.train_config.do_random_cfg:
|
| 2128 |
+
self.train_config.do_cfg = True
|
| 2129 |
+
self.train_config.cfg_scale = value_map(random.random(), 0, 1, 1.0, self.train_config.max_cfg_scale)
|
| 2130 |
+
self.step_num = step
|
| 2131 |
+
# default to true so various things can turn it off
|
| 2132 |
+
self.is_grad_accumulation_step = True
|
| 2133 |
+
if self.train_config.free_u:
|
| 2134 |
+
self.sd.pipeline.enable_freeu(s1=0.9, s2=0.2, b1=1.1, b2=1.2)
|
| 2135 |
+
if self.progress_bar is not None:
|
| 2136 |
+
self.progress_bar.unpause()
|
| 2137 |
+
with torch.no_grad():
|
| 2138 |
+
# if is even step and we have a reg dataset, use that
|
| 2139 |
+
# todo improve this logic to send one of each through if we can buckets and batch size might be an issue
|
| 2140 |
+
is_reg_step = False
|
| 2141 |
+
is_save_step = self.save_config.save_every and self.step_num % self.save_config.save_every == 0
|
| 2142 |
+
is_sample_step = self.sample_config.sample_every and self.step_num % self.sample_config.sample_every == 0
|
| 2143 |
+
if self.train_config.disable_sampling:
|
| 2144 |
+
is_sample_step = False
|
| 2145 |
+
|
| 2146 |
+
batch_list = []
|
| 2147 |
+
|
| 2148 |
+
for b in range(self.train_config.gradient_accumulation):
|
| 2149 |
+
# keep track to alternate on an accumulation step for reg
|
| 2150 |
+
batch_step = step
|
| 2151 |
+
# don't do a reg step on sample or save steps as we dont want to normalize on those
|
| 2152 |
+
if batch_step % 2 == 0 and dataloader_reg is not None and not is_save_step and not is_sample_step:
|
| 2153 |
+
try:
|
| 2154 |
+
with self.timer('get_batch:reg'):
|
| 2155 |
+
batch = next(dataloader_iterator_reg)
|
| 2156 |
+
except StopIteration:
|
| 2157 |
+
with self.timer('reset_batch:reg'):
|
| 2158 |
+
# hit the end of an epoch, reset
|
| 2159 |
+
if self.progress_bar is not None:
|
| 2160 |
+
self.progress_bar.pause()
|
| 2161 |
+
dataloader_iterator_reg = iter(dataloader_reg)
|
| 2162 |
+
trigger_dataloader_setup_epoch(dataloader_reg)
|
| 2163 |
+
|
| 2164 |
+
with self.timer('get_batch:reg'):
|
| 2165 |
+
batch = next(dataloader_iterator_reg)
|
| 2166 |
+
if self.progress_bar is not None:
|
| 2167 |
+
self.progress_bar.unpause()
|
| 2168 |
+
is_reg_step = True
|
| 2169 |
+
elif dataloader is not None:
|
| 2170 |
+
try:
|
| 2171 |
+
with self.timer('get_batch'):
|
| 2172 |
+
batch = next(dataloader_iterator)
|
| 2173 |
+
except StopIteration:
|
| 2174 |
+
with self.timer('reset_batch'):
|
| 2175 |
+
# hit the end of an epoch, reset
|
| 2176 |
+
if self.progress_bar is not None:
|
| 2177 |
+
self.progress_bar.pause()
|
| 2178 |
+
dataloader_iterator = iter(dataloader)
|
| 2179 |
+
trigger_dataloader_setup_epoch(dataloader)
|
| 2180 |
+
self.epoch_num += 1
|
| 2181 |
+
if self.train_config.gradient_accumulation_steps == -1:
|
| 2182 |
+
# if we are accumulating for an entire epoch, trigger a step
|
| 2183 |
+
self.is_grad_accumulation_step = False
|
| 2184 |
+
self.grad_accumulation_step = 0
|
| 2185 |
+
with self.timer('get_batch'):
|
| 2186 |
+
batch = next(dataloader_iterator)
|
| 2187 |
+
if self.progress_bar is not None:
|
| 2188 |
+
self.progress_bar.unpause()
|
| 2189 |
+
else:
|
| 2190 |
+
batch = None
|
| 2191 |
+
batch_list.append(batch)
|
| 2192 |
+
batch_step += 1
|
| 2193 |
+
|
| 2194 |
+
# setup accumulation
|
| 2195 |
+
if self.train_config.gradient_accumulation_steps == -1:
|
| 2196 |
+
# epoch is handling the accumulation, dont touch it
|
| 2197 |
+
pass
|
| 2198 |
+
else:
|
| 2199 |
+
# determine if we are accumulating or not
|
| 2200 |
+
# since optimizer step happens in the loop, we trigger it a step early
|
| 2201 |
+
# since we cannot reprocess it before them
|
| 2202 |
+
optimizer_step_at = self.train_config.gradient_accumulation_steps
|
| 2203 |
+
is_optimizer_step = self.grad_accumulation_step >= optimizer_step_at
|
| 2204 |
+
self.is_grad_accumulation_step = not is_optimizer_step
|
| 2205 |
+
if is_optimizer_step:
|
| 2206 |
+
self.grad_accumulation_step = 0
|
| 2207 |
+
|
| 2208 |
+
# flush()
|
| 2209 |
+
### HOOK ###
|
| 2210 |
+
if self.torch_profiler is not None:
|
| 2211 |
+
self.torch_profiler.start()
|
| 2212 |
+
did_oom = False
|
| 2213 |
+
loss_dict = None
|
| 2214 |
+
try:
|
| 2215 |
+
with self.accelerator.accumulate(self.modules_being_trained):
|
| 2216 |
+
loss_dict = self.hook_train_loop(batch_list)
|
| 2217 |
+
except torch.cuda.OutOfMemoryError:
|
| 2218 |
+
did_oom = True
|
| 2219 |
+
except RuntimeError as e:
|
| 2220 |
+
if "CUDA out of memory" in str(e):
|
| 2221 |
+
did_oom = True
|
| 2222 |
+
else:
|
| 2223 |
+
raise # not an OOM; surface real errors
|
| 2224 |
+
if did_oom:
|
| 2225 |
+
self.num_consecutive_oom += 1
|
| 2226 |
+
if self.num_consecutive_oom > 3:
|
| 2227 |
+
raise RuntimeError("OOM during training step 3 times in a row, aborting training")
|
| 2228 |
+
optimizer.zero_grad(set_to_none=True)
|
| 2229 |
+
flush()
|
| 2230 |
+
torch.cuda.ipc_collect()
|
| 2231 |
+
# skip this step and keep going
|
| 2232 |
+
print_acc("")
|
| 2233 |
+
print_acc("################################################")
|
| 2234 |
+
print_acc(f"# OOM during training step, skipping batch {self.num_consecutive_oom}/3 #")
|
| 2235 |
+
print_acc("################################################")
|
| 2236 |
+
print_acc("")
|
| 2237 |
+
else:
|
| 2238 |
+
self.num_consecutive_oom = 0
|
| 2239 |
+
if self.torch_profiler is not None:
|
| 2240 |
+
torch.cuda.synchronize() # Make sure all CUDA ops are done
|
| 2241 |
+
self.torch_profiler.stop()
|
| 2242 |
+
|
| 2243 |
+
print("\n==== Profile Results ====")
|
| 2244 |
+
print(self.torch_profiler.key_averages().table(sort_by="cpu_time_total", row_limit=1000))
|
| 2245 |
+
self.timer.stop('train_loop')
|
| 2246 |
+
if not did_first_flush:
|
| 2247 |
+
flush()
|
| 2248 |
+
did_first_flush = True
|
| 2249 |
+
# flush()
|
| 2250 |
+
# setup the networks to gradient checkpointing and everything works
|
| 2251 |
+
if self.adapter is not None and isinstance(self.adapter, ReferenceAdapter):
|
| 2252 |
+
self.adapter.clear_memory()
|
| 2253 |
+
|
| 2254 |
+
with torch.no_grad():
|
| 2255 |
+
# torch.cuda.empty_cache()
|
| 2256 |
+
# if optimizer has get_lrs method, then use it
|
| 2257 |
+
learning_rate = 0.0
|
| 2258 |
+
if not did_oom and loss_dict is not None:
|
| 2259 |
+
if hasattr(optimizer, 'get_avg_learning_rate'):
|
| 2260 |
+
learning_rate = optimizer.get_avg_learning_rate()
|
| 2261 |
+
elif hasattr(optimizer, 'get_learning_rates'):
|
| 2262 |
+
learning_rate = optimizer.get_learning_rates()[0]
|
| 2263 |
+
elif self.train_config.optimizer.lower().startswith('dadaptation') or \
|
| 2264 |
+
self.train_config.optimizer.lower().startswith('prodigy'):
|
| 2265 |
+
learning_rate = (
|
| 2266 |
+
optimizer.param_groups[0]["d"] *
|
| 2267 |
+
optimizer.param_groups[0]["lr"]
|
| 2268 |
+
)
|
| 2269 |
+
else:
|
| 2270 |
+
learning_rate = optimizer.param_groups[0]['lr']
|
| 2271 |
+
|
| 2272 |
+
prog_bar_string = f"lr: {learning_rate:.1e}"
|
| 2273 |
+
for key, value in loss_dict.items():
|
| 2274 |
+
prog_bar_string += f" {key}: {value:.3e}"
|
| 2275 |
+
|
| 2276 |
+
if self.progress_bar is not None:
|
| 2277 |
+
self.progress_bar.set_postfix_str(prog_bar_string)
|
| 2278 |
+
|
| 2279 |
+
# if the batch is a DataLoaderBatchDTO, then we need to clean it up
|
| 2280 |
+
if isinstance(batch, DataLoaderBatchDTO):
|
| 2281 |
+
with self.timer('batch_cleanup'):
|
| 2282 |
+
batch.cleanup()
|
| 2283 |
+
|
| 2284 |
+
# don't do on first step
|
| 2285 |
+
if self.step_num != self.start_step:
|
| 2286 |
+
if is_sample_step or is_save_step:
|
| 2287 |
+
self.accelerator.wait_for_everyone()
|
| 2288 |
+
|
| 2289 |
+
if is_save_step:
|
| 2290 |
+
self.accelerator
|
| 2291 |
+
# print above the progress bar
|
| 2292 |
+
if self.progress_bar is not None:
|
| 2293 |
+
self.progress_bar.pause()
|
| 2294 |
+
print_acc(f"\nSaving at step {self.step_num}")
|
| 2295 |
+
self.save(self.step_num)
|
| 2296 |
+
self.ensure_params_requires_grad()
|
| 2297 |
+
# clear any grads
|
| 2298 |
+
optimizer.zero_grad()
|
| 2299 |
+
flush()
|
| 2300 |
+
flush_next = True
|
| 2301 |
+
if self.progress_bar is not None:
|
| 2302 |
+
self.progress_bar.unpause()
|
| 2303 |
+
|
| 2304 |
+
if is_sample_step:
|
| 2305 |
+
if self.progress_bar is not None:
|
| 2306 |
+
self.progress_bar.pause()
|
| 2307 |
+
flush()
|
| 2308 |
+
# print above the progress bar
|
| 2309 |
+
if self.train_config.free_u:
|
| 2310 |
+
self.sd.pipeline.disable_freeu()
|
| 2311 |
+
self.sample(self.step_num)
|
| 2312 |
+
if self.train_config.unload_text_encoder:
|
| 2313 |
+
# make sure the text encoder is unloaded
|
| 2314 |
+
self.sd.text_encoder_to('cpu')
|
| 2315 |
+
flush()
|
| 2316 |
+
|
| 2317 |
+
self.ensure_params_requires_grad()
|
| 2318 |
+
if self.progress_bar is not None:
|
| 2319 |
+
self.progress_bar.unpause()
|
| 2320 |
+
|
| 2321 |
+
if self.logging_config.log_every and self.step_num % self.logging_config.log_every == 0:
|
| 2322 |
+
if self.progress_bar is not None:
|
| 2323 |
+
self.progress_bar.pause()
|
| 2324 |
+
with self.timer('log_to_tensorboard'):
|
| 2325 |
+
# log to tensorboard
|
| 2326 |
+
if self.accelerator.is_main_process:
|
| 2327 |
+
if self.writer is not None:
|
| 2328 |
+
if loss_dict is not None:
|
| 2329 |
+
for key, value in loss_dict.items():
|
| 2330 |
+
self.writer.add_scalar(f"{key}", value, self.step_num)
|
| 2331 |
+
self.writer.add_scalar(f"lr", learning_rate, self.step_num)
|
| 2332 |
+
if self.progress_bar is not None:
|
| 2333 |
+
self.progress_bar.unpause()
|
| 2334 |
+
|
| 2335 |
+
if self.accelerator.is_main_process:
|
| 2336 |
+
# log to logger
|
| 2337 |
+
self.logger.log({
|
| 2338 |
+
'learning_rate': learning_rate,
|
| 2339 |
+
})
|
| 2340 |
+
if loss_dict is not None:
|
| 2341 |
+
for key, value in loss_dict.items():
|
| 2342 |
+
self.logger.log({
|
| 2343 |
+
f'loss/{key}': value,
|
| 2344 |
+
})
|
| 2345 |
+
elif self.logging_config.log_every is None:
|
| 2346 |
+
if self.accelerator.is_main_process:
|
| 2347 |
+
# log every step
|
| 2348 |
+
self.logger.log({
|
| 2349 |
+
'learning_rate': learning_rate,
|
| 2350 |
+
})
|
| 2351 |
+
for key, value in loss_dict.items():
|
| 2352 |
+
self.logger.log({
|
| 2353 |
+
f'loss/{key}': value,
|
| 2354 |
+
})
|
| 2355 |
+
|
| 2356 |
+
|
| 2357 |
+
if self.performance_log_every > 0 and self.step_num % self.performance_log_every == 0:
|
| 2358 |
+
if self.progress_bar is not None:
|
| 2359 |
+
self.progress_bar.pause()
|
| 2360 |
+
# print the timers and clear them
|
| 2361 |
+
self.timer.print()
|
| 2362 |
+
self.timer.reset()
|
| 2363 |
+
if self.progress_bar is not None:
|
| 2364 |
+
self.progress_bar.unpause()
|
| 2365 |
+
|
| 2366 |
+
# commit log
|
| 2367 |
+
if self.accelerator.is_main_process:
|
| 2368 |
+
with self.timer('commit_logger'):
|
| 2369 |
+
self.logger.commit(step=self.step_num)
|
| 2370 |
+
|
| 2371 |
+
# sets progress bar to match out step
|
| 2372 |
+
if self.progress_bar is not None:
|
| 2373 |
+
self.progress_bar.update(step - self.progress_bar.n)
|
| 2374 |
+
|
| 2375 |
+
#############################
|
| 2376 |
+
# End of step
|
| 2377 |
+
#############################
|
| 2378 |
+
|
| 2379 |
+
# update various steps
|
| 2380 |
+
self.step_num = step + 1
|
| 2381 |
+
self.grad_accumulation_step += 1
|
| 2382 |
+
self.end_step_hook()
|
| 2383 |
+
|
| 2384 |
+
|
| 2385 |
+
###################################################################
|
| 2386 |
+
## END TRAIN LOOP
|
| 2387 |
+
###################################################################
|
| 2388 |
+
self.accelerator.wait_for_everyone()
|
| 2389 |
+
if self.progress_bar is not None:
|
| 2390 |
+
self.progress_bar.close()
|
| 2391 |
+
if self.train_config.free_u:
|
| 2392 |
+
self.sd.pipeline.disable_freeu()
|
| 2393 |
+
if not self.train_config.disable_sampling:
|
| 2394 |
+
self.sample(self.step_num)
|
| 2395 |
+
self.logger.commit(step=self.step_num)
|
| 2396 |
+
print_acc("")
|
| 2397 |
+
if self.accelerator.is_main_process:
|
| 2398 |
+
self.save()
|
| 2399 |
+
self.logger.finish()
|
| 2400 |
+
self.accelerator.end_training()
|
| 2401 |
+
|
| 2402 |
+
if self.accelerator.is_main_process:
|
| 2403 |
+
# push to hub
|
| 2404 |
+
if self.save_config.push_to_hub:
|
| 2405 |
+
if("HF_TOKEN" not in os.environ):
|
| 2406 |
+
interpreter_login(new_session=False, write_permission=True)
|
| 2407 |
+
self.push_to_hub(
|
| 2408 |
+
repo_id=self.save_config.hf_repo_id,
|
| 2409 |
+
private=self.save_config.hf_private
|
| 2410 |
+
)
|
| 2411 |
+
del (
|
| 2412 |
+
self.sd,
|
| 2413 |
+
unet,
|
| 2414 |
+
noise_scheduler,
|
| 2415 |
+
optimizer,
|
| 2416 |
+
self.network,
|
| 2417 |
+
tokenizer,
|
| 2418 |
+
text_encoder,
|
| 2419 |
+
)
|
| 2420 |
+
|
| 2421 |
+
flush()
|
| 2422 |
+
self.done_hook()
|
| 2423 |
+
|
| 2424 |
+
def push_to_hub(
|
| 2425 |
+
self,
|
| 2426 |
+
repo_id: str,
|
| 2427 |
+
private: bool = False,
|
| 2428 |
+
):
|
| 2429 |
+
if not self.accelerator.is_main_process:
|
| 2430 |
+
return
|
| 2431 |
+
readme_content = self._generate_readme(repo_id)
|
| 2432 |
+
readme_path = os.path.join(self.save_root, "README.md")
|
| 2433 |
+
with open(readme_path, "w", encoding="utf-8") as f:
|
| 2434 |
+
f.write(readme_content)
|
| 2435 |
+
|
| 2436 |
+
api = HfApi()
|
| 2437 |
+
|
| 2438 |
+
api.create_repo(
|
| 2439 |
+
repo_id,
|
| 2440 |
+
private=private,
|
| 2441 |
+
exist_ok=True
|
| 2442 |
+
)
|
| 2443 |
+
|
| 2444 |
+
api.upload_folder(
|
| 2445 |
+
repo_id=repo_id,
|
| 2446 |
+
folder_path=self.save_root,
|
| 2447 |
+
ignore_patterns=["*.yaml", "*.pt"],
|
| 2448 |
+
repo_type="model",
|
| 2449 |
+
)
|
| 2450 |
+
|
| 2451 |
+
|
| 2452 |
+
def _generate_readme(self, repo_id: str) -> str:
|
| 2453 |
+
"""Generates the content of the README.md file."""
|
| 2454 |
+
|
| 2455 |
+
# Gather model info
|
| 2456 |
+
base_model = self.model_config.name_or_path
|
| 2457 |
+
instance_prompt = self.trigger_word if hasattr(self, "trigger_word") else None
|
| 2458 |
+
if base_model == "black-forest-labs/FLUX.1-schnell":
|
| 2459 |
+
license = "apache-2.0"
|
| 2460 |
+
elif base_model == "black-forest-labs/FLUX.1-dev":
|
| 2461 |
+
license = "other"
|
| 2462 |
+
license_name = "flux-1-dev-non-commercial-license"
|
| 2463 |
+
license_link = "https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/LICENSE.md"
|
| 2464 |
+
else:
|
| 2465 |
+
license = "creativeml-openrail-m"
|
| 2466 |
+
tags = [
|
| 2467 |
+
"text-to-image",
|
| 2468 |
+
]
|
| 2469 |
+
if self.model_config.is_xl:
|
| 2470 |
+
tags.append("stable-diffusion-xl")
|
| 2471 |
+
if self.model_config.is_flux:
|
| 2472 |
+
tags.append("flux")
|
| 2473 |
+
if self.model_config.is_lumina2:
|
| 2474 |
+
tags.append("lumina2")
|
| 2475 |
+
if self.model_config.is_v3:
|
| 2476 |
+
tags.append("sd3")
|
| 2477 |
+
if self.network_config:
|
| 2478 |
+
tags.extend(
|
| 2479 |
+
[
|
| 2480 |
+
"lora",
|
| 2481 |
+
"diffusers",
|
| 2482 |
+
"template:sd-lora",
|
| 2483 |
+
"ai-toolkit",
|
| 2484 |
+
]
|
| 2485 |
+
)
|
| 2486 |
+
|
| 2487 |
+
# Generate the widget section
|
| 2488 |
+
widgets = []
|
| 2489 |
+
sample_image_paths = []
|
| 2490 |
+
samples_dir = os.path.join(self.save_root, "samples")
|
| 2491 |
+
if os.path.isdir(samples_dir):
|
| 2492 |
+
for filename in os.listdir(samples_dir):
|
| 2493 |
+
#The filenames are structured as 1724085406830__00000500_0.jpg
|
| 2494 |
+
#So here we capture the 2nd part (steps) and 3rd (index the matches the prompt)
|
| 2495 |
+
match = re.search(r"__(\d+)_(\d+)\.jpg$", filename)
|
| 2496 |
+
if match:
|
| 2497 |
+
steps, index = int(match.group(1)), int(match.group(2))
|
| 2498 |
+
#Here we only care about uploading the latest samples, the match with the # of steps
|
| 2499 |
+
if steps == self.train_config.steps:
|
| 2500 |
+
sample_image_paths.append((index, f"samples/{filename}"))
|
| 2501 |
+
|
| 2502 |
+
# Sort by numeric index
|
| 2503 |
+
sample_image_paths.sort(key=lambda x: x[0])
|
| 2504 |
+
|
| 2505 |
+
# Create widgets matching prompt with the index
|
| 2506 |
+
for i, prompt in enumerate(self.sample_config.prompts):
|
| 2507 |
+
if i < len(sample_image_paths):
|
| 2508 |
+
# Associate prompts with sample image paths based on the extracted index
|
| 2509 |
+
_, image_path = sample_image_paths[i]
|
| 2510 |
+
widgets.append(
|
| 2511 |
+
{
|
| 2512 |
+
"text": prompt,
|
| 2513 |
+
"output": {
|
| 2514 |
+
"url": image_path
|
| 2515 |
+
},
|
| 2516 |
+
}
|
| 2517 |
+
)
|
| 2518 |
+
dtype = "torch.bfloat16" if self.model_config.is_flux else "torch.float16"
|
| 2519 |
+
# Construct the README content
|
| 2520 |
+
readme_content = f"""---
|
| 2521 |
+
tags:
|
| 2522 |
+
{yaml.dump(tags, indent=4).strip()}
|
| 2523 |
+
{"widget:" if os.path.isdir(samples_dir) else ""}
|
| 2524 |
+
{yaml.dump(widgets, indent=4).strip() if widgets else ""}
|
| 2525 |
+
base_model: {base_model}
|
| 2526 |
+
{"instance_prompt: " + instance_prompt if instance_prompt else ""}
|
| 2527 |
+
license: {license}
|
| 2528 |
+
{'license_name: ' + license_name if license == "other" else ""}
|
| 2529 |
+
{'license_link: ' + license_link if license == "other" else ""}
|
| 2530 |
+
---
|
| 2531 |
+
|
| 2532 |
+
# {self.job.name}
|
| 2533 |
+
Model trained with [AI Toolkit by Ostris](https://github.com/ostris/ai-toolkit)
|
| 2534 |
+
<Gallery />
|
| 2535 |
+
|
| 2536 |
+
## Trigger words
|
| 2537 |
+
|
| 2538 |
+
{"You should use `" + instance_prompt + "` to trigger the image generation." if instance_prompt else "No trigger words defined."}
|
| 2539 |
+
|
| 2540 |
+
## Download model and use it with ComfyUI, AUTOMATIC1111, SD.Next, Invoke AI, etc.
|
| 2541 |
+
|
| 2542 |
+
Weights for this model are available in Safetensors format.
|
| 2543 |
+
|
| 2544 |
+
[Download](/{repo_id}/tree/main) them in the Files & versions tab.
|
| 2545 |
+
|
| 2546 |
+
## Use it with the [🧨 diffusers library](https://github.com/huggingface/diffusers)
|
| 2547 |
+
|
| 2548 |
+
```py
|
| 2549 |
+
from diffusers import AutoPipelineForText2Image
|
| 2550 |
+
import torch
|
| 2551 |
+
|
| 2552 |
+
pipeline = AutoPipelineForText2Image.from_pretrained('{base_model}', torch_dtype={dtype}).to('cuda')
|
| 2553 |
+
pipeline.load_lora_weights('{repo_id}', weight_name='{self.job.name}.safetensors')
|
| 2554 |
+
image = pipeline('{instance_prompt if not widgets else self.sample_config.prompts[0]}').images[0]
|
| 2555 |
+
image.save("my_image.png")
|
| 2556 |
+
```
|
| 2557 |
+
|
| 2558 |
+
For more details, including weighting, merging and fusing LoRAs, check the [documentation on loading LoRAs in diffusers](https://huggingface.co/docs/diffusers/main/en/using-diffusers/loading_adapters)
|
| 2559 |
+
|
| 2560 |
+
"""
|
| 2561 |
+
return readme_content
|
anime_style_flux2k_9b_000000024.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:68cb16a3cd0c5f57bd0ca3caa883beb584546e5517715c54bdfc2ae286538cba
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000048.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0b038a43c6d94c17788f7917587ab23b76d10750b6c272976292d36dd162dec5
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000072.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:877c46ae9e1bc6eac122f3d730edf61a0cbf5f3ee618cea1ea79d2783908f208
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000096.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:01990e2a557b624cde36fcea66e74990b0e7c62da87d91b082d76219639f2750
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000120.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:374670449e2c9d47eeae0a8d07ce1776725aba78404fef82c06e63005c48d2c7
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000144.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:647b17f3fa67596b1ca2a2d58cb0d3974c3640e81f6cda34bf1b73d7361665f9
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000168.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f2d1baa73b5d99f12b84e02d78524e4251d3b5eba4d079e1e791c09d2f704beb
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000192.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2f39c1b41baf2f0d85f006057ea08be494900fa97ea7c76e78fd7516dd662c60
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000216.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e294a707d6cc4cb8dbb0dadcd2b6c6c5ceb40fb37f5f5052dae2fe617c345d59
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000240.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2e2afddf58a47097527e26960b90bac05f14a9ae30e12d79bfdeb812033a88e6
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000264.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:85bfd0b6d216c7d369f8c790c143148c98aba4e2e59afb242bc76c19a9a97426
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000288.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a593293208e48bda07a4d10f61c2705a9b59d5c89a35ab06962bac5514b68d8a
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000312.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:38ba8926b16fecced8e3efc9b710903cb80816670bea7c0560948412b8eab58e
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000336.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3cd95fe4943de51c7a78ecac6849128acfcf0cd314902be2c51abb744353dbb6
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000360.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:188d1ec06425ea54eeea05ab667db1d4abec460d2d022e9c1a69e3cdd9fc3afc
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000384.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1383a463e3fcd1bc22770b69ce95085a668583eaf56fd55cc2d67e3e23babc6b
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000408.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:661922b210be2281b6e17cc32da4168913306984d010ef006c8802655c017b5b
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000432.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1465704dea374c3a9f91d19c512a07d2fb66ebfc16477c073e7cbc1253d5fc9e
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000456.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e545990bc42ce240657adec32707f02004edc8f1e77da82548623434fb4a1ed0
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000480.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1723c3d4956c054cafbc7c5327c9466747f131e2ceb4665d6c468f071902a18b
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000504.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a0b06bc1c842323377e8971c0076b5a6c269e1f0a0a7aa397e8bc029cbbf4749
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000000528.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6a73343bd78d6641378c185f6f00551af4ed99570f3c89424a6635ac859a6dff
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000000552.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0fb6e43d13526bbf4877413a4af3da6063112e78c67d275605506691973d1e3f
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000000576.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:72e050be25380b3c7c6d31424731d07ed2093fcfa0df9e2c679ac7dec48748dd
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000000600.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:814c6543bb03b43345100585af40d617bfc8df4fb2dd61a1622ae3fed85e87f5
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000000624.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2691efe6fb2b3192b470bb03dea946ea43797d1a963da7984c0593ffa7e8c487
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000000648.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a1e876433bcc28aeffff9ea2dcb25c8a03622478399a8f29b7ac768c3c01fe3e
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000672.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3f3b62d976234d03d3488a5805a660c347d55538b6d8be567ce3aaa137b00f4a
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000696.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:97b93eaf36680d0856cc3f0ed49fc1b94d5806b5328e26876b535c0176ac8d14
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000720.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9d4fca1a405332efb5a3905dbe040255f21bd941817703ff9843f14123cf5634
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000744.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ebbbdde3a89db1944eb18c993e4ee979d5e23f7851a2fc7ad4bfecc09a65c2cf
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000000768.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:661744599b2e8fac372d0e2cac40c9fd0fc6362cb8d74a61b9b4e897ae2e5683
|
| 3 |
+
size 82866720
|
anime_style_flux2k_9b_000001464.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a8ee8a769a195be233e9e95fa921591bcb2c810fa302663bfd7a6f525ddf3012
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000001488.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:75d5437fc1cb40d8decdfe87c9a8b4f78000cf5939467bcc07bfb67ccd04cbf4
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000001512.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:aa366300ee3911d818f29c8cfbb1fac967d3b73ce817675dd26058910067b9d0
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000001536.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:334784987b16dadb3504a30c666a0ea304c0e1eba87a063cc19093a8dfc6260f
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000001560.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4249beb63b612ac161d9c1985889f4012ea30ee55ef5351af35af12209e27c89
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000001584.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7091ddd2aea40fabb92086d322fee308fca5749ca5bb347e9578e712464d4341
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000001608.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d9207ff431feb32f2e627d255f389a31147d3c40d8842312043711cfdaec4e49
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000001632.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7f93947a4c42a68441d918fba271edbf3c48e17a94eb6f0c47418d0fc73f08bc
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000001656.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:136a5dce2a7032d41f82ebd565ed3ee837ba7ff9d17fa9a52a3639c650ae5ba8
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000001680.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:279e93d00b431262dc3336b46e11b232cfcabb0d67834820b59d3b1d7e041822
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000001704.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:437f7f8b60868a32b5f7df6018341c55210dfbdb0b4e20b6ce1f7212b71bc78a
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000001728.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:39fb2396996493dc2f73cd40ab5a890bfb2a21f335fd545e8d9c1924973bb91a
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000001752.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8e23d1fd01ca174ab534383ee120b5a0253013121d06371d1c087cc7fe1bff5e
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000001776.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:516ccca7c4892f9fc7aa0cf2bbbf42e450130e97c39ed2fa46ae82a6c1a401aa
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000001800.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7bbbad9cbc511e4be1aa55aa554f2ded85d7e45225db6f95dd7b22ce2f2ec6d8
|
| 3 |
+
size 165704464
|
anime_style_flux2k_9b_000001824.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cc6c3a567c57ad1ed02f29adc7208011bc1f32a61ff702d323d49ca403f30883
|
| 3 |
+
size 165704464
|