fl0wikus

train_network_old.ps1

Jan 12th, 2023 (edited)
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PowerShell 10.31 KB | Source Code | 0 0
  1. # https://github.com/cloneofsimo/lora
  2. # https://github.com/kohya-ss/sd-scripts
  3. # https://rentry.org/2chAI_LoRA_Dreambooth_guide
  4.  
  5. ##### Начало конфига #####
  6.  
  7. $sd_scripts_dir = "X:\git-repos\sd-scripts\" # Путь к папке с репозиторием kohya-ss/sd-scripts
  8.  
  9. $ckpt = "X:\SD-models\checkpoint.safetensors" # Путь к чекпоинту (ckpt / safetensors)
  10. $is_sd_v2_ckpt = 0 # Поставь '1' если загружаешь SD 2.x чекпоинт
  11. $is_sd_v2_768_ckpt = 0 # Также поставь здесь значение '1', если загружаешь SD 2.x-768 чекпоинт
  12. $image_dir = "X:\training_data\img\" # Путь к папке с изображениями
  13. $reg_dir = "X:\training_data\img_reg\" # Путь к папке с регуляризационными изображениями (можно указать на пустую папку, но путь обязательно должен быть указан)
  14. $output_dir = "X:\LoRA\" # Директория сохранения LoRA чекпоинтов
  15. $output_name = "my_LoRA_network_v1" # Название файла (расширение не нужно)
  16.  
  17. $train_batch_size = 1 # Сколько изображений тренировать одновременно. Чем больше значение, тем быстрее тренировка, но больше потребление видеопамяти
  18. $resolution = 512 # Разрешение тренировки
  19. $num_epochs = 10 # Число эпох
  20. $save_every_n_epochs = 1 # Сохранять чекпоинт каждые n эпох
  21. $save_last_n_epochs = 999 # Сохранить только последние n эпох
  22. $max_token_length = 75 # Максимальная длина токена. Возможные значения: 75 / 150 / 225
  23. $clip_skip = 1 # https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features#ignore-last-layers-of-clip-model
  24.  
  25. # Дополнительные настройки, можно оставить по умолчанию
  26.  
  27. $learning_rate = 1e-4 # Скорость обучения
  28. $unet_lr = $learning_rate # Скорость обучения U-Net
  29. $text_encoder_lr = $learning_rate # Скорость обучения текстового энкодера
  30. $scheduler = "cosine_with_restarts" # linear, cosine, cosine_with_restarts, polynomial, constant (по умолчанию), constant_with_warmup
  31. $network_dim = 128 # Размер нетворка. Чем больше значение, тем больше точность и размер выходного файла
  32. $save_precision = "fp16" # None, float, fp16, bf16
  33. $mixed_precision = "fp16" # no, fp16, bf16
  34. $is_random_seed = 1 # 1 -- рандомный сид, 0 -- статичный
  35. $shuffle_caption = 1 # Перемешивать файлы описания, затеганные через запятую
  36. $keep_tokens = 1 # Не перемешивать первые N токенов когда перемешивается описание
  37. $use_vae = 0 # Использовать VAE
  38. $vae_path = "X:\SD-models\checkpoint.vae.pt" # Путь к VAE
  39.  
  40. # Логгирование
  41.  
  42. $logging_enabled = 0
  43. $logging_dir = "X:\LoRA\logs\"
  44. $log_prefix = $output_name
  45.  
  46. ##### Конец конфига #####
  47.  
  48. function Is-Numeric ($value) { return $value -match "^[\d\.]+$" }
  49.  
  50. function Write-ColorOutput($ForegroundColor)
  51. {
  52.     $fc = $host.UI.RawUI.ForegroundColor
  53.     $host.UI.RawUI.ForegroundColor = $ForegroundColor
  54.     if ($args) { Write-Output $args }
  55.     else { $input | Write-Output }
  56.     $host.UI.RawUI.ForegroundColor = $fc
  57. }
  58.  
  59. function Word-Ending($value)
  60. {
  61.     $ending = $value.ToString()
  62.     if ($ending -ge "11" -and $ending -le "19") { return "й" }
  63.     $ending = $ending.Substring([Math]::Max($ending.Length, 0) - 1)
  64.     if ($ending -eq "1") { return "е" }
  65.     if ($ending -ge "2" -and $ending -le "4") { return "я" }
  66.     if (($ending -ge "5" -and $ending -le "9") -or $ending -eq "0") { return "й" }
  67. }
  68.  
  69. Write-Output "Подсчет количества изображений в папках"
  70. $total = 0
  71. $is_structure_wrong = 0
  72. $abort_script = 0
  73. $iter = 0
  74.  
  75. Get-ChildItem -Path $image_dir -Directory | ForEach-Object {
  76.     $parts = $_.Name.Split("_")
  77.     if (!(Is-Numeric $parts[0]))
  78.     {
  79.         Write-ColorOutput red "Ошибка в $($_):`n`t$($parts[0]) не является числом"
  80.         $is_structure_wrong = 1
  81.         return
  82.     }
  83.     if ([int]$parts[0] -le 0)
  84.     {
  85.         Write-ColorOutput red "Ошибка в $($_):`nПовторения в имени папки с изображениями должно быть >0"
  86.         $is_structure_wrong = 1
  87.         return
  88.     }
  89.     $repeats = [int]$parts[0]
  90.     $imgs = Get-ChildItem $_.FullName -Depth 0 -File -Include *.jpg, *.png, *.webp | Measure-Object | ForEach-Object { $_.Count }
  91.     if ($iter -eq 0) { Write-Output "Обучающие изображения:" }
  92.     $img_repeats = ($repeats * $imgs)
  93.     Write-Output "`t$($parts[1]): $repeats повторени$(Word-Ending $repeats) * $imgs изображени$(Word-Ending $imgs) = $($img_repeats)"
  94.     $total += $img_repeats
  95.     $iter += 1
  96. }
  97.  
  98. $iter = 0
  99.  
  100. if ($is_structure_wrong -eq 0) { Get-ChildItem -Path $reg_dir -Directory | % { if ($abort_script -ne "n") { ForEach-Object {
  101.     $parts = $_.Name.Split("_")
  102.     if (!(Is-Numeric $parts[0]))
  103.     {
  104.         Write-ColorOutput red "Ошибка в $($_):`n`t$($parts[0]) не является числом"
  105.         $is_structure_wrong = 1
  106.         return
  107.     }
  108.     if ([int]$parts[0] -le 0)
  109.     {
  110.         Write-ColorOutput red "Ошибка в $($_):`nПовторения в имени папки с изображениями должно быть >0"
  111.         $is_structure_wrong = 1
  112.         return
  113.     }
  114.     $repeats = [int]$parts[0]
  115.     $reg_imgs = Get-ChildItem $_.FullName -Depth 0 -File -Include *.jpg, *.png, *.webp | Measure-Object | ForEach-Object { $_.Count }
  116.     if ($iter -eq 0) { Write-Output "Регуляризационные изображения:" }
  117.     if ($reg_imgs -eq 0)
  118.     {
  119.         Write-ColorOutput darkyellow "Внимание: папка для регуляризационных изображений присутствует, но в ней ничего нет"
  120.         do { $abort_script = Read-Host "Прервать выполнение скрипта? (y/N)" }
  121.         until (($abort_script -eq "y") -or ($abort_script -ceq "N"))
  122.         return
  123.     }
  124.     else
  125.     {
  126.         $img_repeats = ($repeats * $reg_imgs)
  127.         Write-Output "`t$($parts[1]): $repeats повторени$(Word-Ending $repeats) * $reg_imgs изображени$(Word-Ending $reg_imgs) = $($img_repeats)"
  128.         $iter += 1
  129.     }
  130. } } } }
  131.  
  132. if ($is_structure_wrong -eq 0 -and ($abort_script -eq "n" -or $abort_script -eq 0))
  133. {
  134.     if ($reg_imgs -gt 0)
  135.     {
  136.         $total *= 2
  137.         Write-Output "Количество шагов увеличено вдвое: количество регуляризационных изображений больше 0"
  138.     }
  139.    
  140.     Write-Output "Количество изображений с повторениями: $total"
  141.     Write-Output "Размер обучающей партии (train_batch_size): $train_batch_size"
  142.     Write-Output "Количество эпох: $num_epochs"
  143.     $max_training_steps = [int]($total / $train_batch_size * $num_epochs)
  144.     Write-Output "Количество шагов: $total / $train_batch_size * $num_epochs = $max_training_steps"
  145.    
  146.     if ($is_random_seed -le 0) { $seed = 1337 }
  147.     else { $seed = Get-Random }
  148.    
  149.     $image_dir = $image_dir.TrimEnd("\", "/")
  150.     $reg_dir = $reg_dir.TrimEnd("\", "/")
  151.     $output_dir = $output_dir.TrimEnd("\", "/")
  152.     $logging_dir = $logging_dir.TrimEnd("\", "/")
  153.    
  154.     $run_parameters = "--network_module=networks.lora --pretrained_model_name_or_path=`"$ckpt`" --train_data_dir=`"$image_dir`" --reg_data_dir=`"$reg_dir`" --output_dir=`"$output_dir`" --output_name=`"$output_name`" --caption_extension=`".txt`" --resolution=$resolution --prior_loss_weight=1 --enable_bucket --min_bucket_reso=256 --max_bucket_reso=1024 --train_batch_size=$train_batch_size --learning_rate=$learning_rate --unet_lr=$unet_lr --text_encoder_lr=$text_encoder_lr --max_train_steps=$max_training_steps --use_8bit_adam --xformers --save_every_n_epochs=$save_every_n_epochs --save_last_n_epochs=$save_last_n_epochs --save_model_as=safetensors --keep_tokens=$keep_tokens --clip_skip=$clip_skip --seed=$seed --network_dim=$network_dim --cache_latents --lr_scheduler=$scheduler --mixed_precision=$mixed_precision --save_precision=$save_precision"
  155.    
  156.     if ($max_token_length -eq 75) { }
  157.     else
  158.     {
  159.         if ($max_token_length -eq 150 -or $max_token_length -eq 225) { $run_parameters += " --max_token_length=$($max_token_length)" }
  160.         else { Write-ColorOutput darkyellow "Неверно указан max_token_length! Используем значение 75" }
  161.     }
  162.    
  163.     if ($is_sd_v2_ckpt -le 0) { Write-Output "Stable Diffusion 1.x чекпоинт" }
  164.     if ($is_sd_v2_ckpt -ge 1)
  165.     {
  166.         if ($is_sd_v2_768_ckpt -ge 1)
  167.         {
  168.             $v2_resolution = "768"
  169.             $run_parameters += " --v_parameterization"
  170.         }
  171.         else { $v2_resolution = "512" }
  172.         Write-Output "Stable Diffusion 2.x ($v2_resolution) чекпоинт"
  173.         $run_parameters += " --v2"
  174.         if ($clip_skip -eq -not 1)
  175.         {
  176.             Write-ColorOutput darkyellow "Внимание: результаты тренировки SD 2.x чекпоинта с clip_skip отличным от 1 могут быть непредсказуемые"
  177.             do { $abort_script = Read-Host "Прервать выполнение скрипта? (y/N)" }
  178.             until (($abort_script -eq "y") -or ($abort_script -ceq "N"))
  179.         }
  180.     }
  181.    
  182.     if ($shuffle_caption -ge 1) { $run_parameters += " --shuffle_caption" }
  183.    
  184.     if ($logging_enabled -ge 1) { $run_parameters += " --logging_dir=`"$logging_dir`" --log_prefix=`"$output_name`""}
  185.    
  186.     if ($use_vae -ge 1) { $run_parameters += " --vae=`"$vae_path`"" }
  187.    
  188.     sleep -s 1
  189.    
  190.     if ($abort_script -eq "n" -or $abort_script -eq 0)
  191.     {
  192.         Write-ColorOutput green "Выполнение скрипта с параметрами:"
  193.         sleep -s 1
  194.         Write-Output "$($run_parameters -split '--' | foreach { if ($_ -ceq '') { Write-Output '' } else { Write-Output --`"$_`n`" } } | foreach { $_ -replace '=', ' = ' })"
  195.         $script_origin = (get-location).path
  196.         cd $sd_scripts_dir
  197.         .\venv\Scripts\activate
  198.         powershell accelerate launch --num_cpu_threads_per_process 12 train_network.py $run_parameters
  199.         deactivate
  200.         cd $script_origin
  201.     }
  202. }
  203.  
  204. # 13.01.23 by anon
Advertisement
Add Comment
Please, Sign In to add comment