Guest User

train_network.ps1

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