Skip to content

Commit 536260d

Browse files
committed
update logging
1 parent 19b7b41 commit 536260d

7 files changed

+153
-32
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,4 @@ gui-user.bat
1111
gui-user.ps1
1212
.vscode
1313
wandb
14+
setup.log

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,7 @@ This will store a backup file with your current locally installed pip packages a
314314
- Not tested in multi-GPU environment. Please report any bugs.
315315
- `--cache_latents_to_disk` option automatically enables `--cache_latents` option when specified. [#438](https://github.com/kohya-ss/sd-scripts/issues/438)
316316
- Fixed a bug in `gen_img_diffusers.py` where latents upscaler would fail with a batch size of 2 or more.
317+
- Fix issue with using earlier version than python 3.10 in Linux. Thanks @Whyjsee
317318
* 2023/04/24 (v21.5.6)
318319
- Fix triton error
319320
- Fix issue with merge lora path with spaces

gui.bat

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ call .\venv\Scripts\activate.bat
55
set PATH=%PATH%;%~dp0venv\Lib\site-packages\torch\lib
66

77
:: Debug info about system
8-
python.exe .\tools\debug_info.py
8+
:: python.exe .\tools\debug_info.py
99

1010
:: Validate the requirements and store the exit code
1111
python.exe .\tools\validate_requirements.py

gui.ps1

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
$env:PATH += ";$($MyInvocation.MyCommand.Path)\venv\Lib\site-packages\torch\lib"
44

55
# Debug info about system
6-
python.exe .\tools\debug_info.py
6+
# python.exe .\tools\debug_info.py
77

88
# Validate the requirements and store the exit code
99
python.exe .\tools\validate_requirements.py
@@ -16,6 +16,6 @@ if ($LASTEXITCODE -eq 0) {
1616
$argsFromFile = Get-Content .\gui_parameters.txt -Encoding UTF8 | Where-Object { $_ -notmatch "^#" } | Foreach-Object { $_ -split " " }
1717
}
1818
$args_combo = $argsFromFile + $args
19-
Write-Host "The arguments passed to this script were: $args_combo"
19+
# Write-Host "The arguments passed to this script were: $args_combo"
2020
python.exe kohya_gui.py $args_combo
2121
}

kohya_gui.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ def UI(**kwargs):
8585

8686
if os.path.exists('./style.css'):
8787
with open(os.path.join('./style.css'), 'r', encoding='utf8') as file:
88-
print('Load CSS...')
88+
log.info('Load CSS...')
8989
css += file.read() + '\n'
9090

9191
interface = gr.Blocks(

lora_gui.py

+79-21
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
# v3.1: Adding captionning of images to utilities
55

66
import gradio as gr
7-
import easygui
7+
import logging
8+
import time
89
import json
910
import math
1011
import os
@@ -51,7 +52,63 @@
5152
save_style_symbol = '\U0001f4be' # 💾
5253
document_symbol = '\U0001F4C4' # 📄
5354
path_of_this_folder = os.getcwd()
54-
55+
log = logging.getLogger('sd')
56+
57+
# setup console and file logging
58+
# def setup_logging(clean=False):
59+
# try:
60+
# if clean and os.path.isfile('setup.log'):
61+
# os.remove('setup.log')
62+
# time.sleep(0.1) # prevent race condition
63+
# except:
64+
# pass
65+
# logging.basicConfig(
66+
# level=logging.DEBUG,
67+
# format='%(asctime)s | %(levelname)s | %(pathname)s | %(message)s',
68+
# filename='setup.log',
69+
# filemode='a',
70+
# encoding='utf-8',
71+
# force=True,
72+
# )
73+
# from rich.theme import Theme
74+
# from rich.logging import RichHandler
75+
# from rich.console import Console
76+
# from rich.pretty import install as pretty_install
77+
# from rich.traceback import install as traceback_install
78+
79+
# console = Console(
80+
# log_time=True,
81+
# log_time_format='%H:%M:%S-%f',
82+
# theme=Theme(
83+
# {
84+
# 'traceback.border': 'black',
85+
# 'traceback.border.syntax_error': 'black',
86+
# 'inspect.value.border': 'black',
87+
# }
88+
# ),
89+
# )
90+
# pretty_install(console=console)
91+
# traceback_install(
92+
# console=console,
93+
# extra_lines=1,
94+
# width=console.width,
95+
# word_wrap=False,
96+
# indent_guides=False,
97+
# suppress=[],
98+
# )
99+
# rh = RichHandler(
100+
# show_time=True,
101+
# omit_repeated_times=False,
102+
# show_level=True,
103+
# show_path=False,
104+
# markup=False,
105+
# rich_tracebacks=True,
106+
# log_time_format='%H:%M:%S-%f',
107+
# level=logging.DEBUG if args.debug else logging.INFO,
108+
# console=console,
109+
# )
110+
# rh.set_name(logging.DEBUG if args.debug else logging.INFO)
111+
# log.addHandler(rh)
55112

56113
def save_configuration(
57114
save_as,
@@ -148,14 +205,14 @@ def save_configuration(
148205
save_as_bool = True if save_as.get('label') == 'True' else False
149206

150207
if save_as_bool:
151-
print('Save as...')
208+
log.info('Save as...')
152209
file_path = get_saveasfile_path(file_path)
153210
else:
154-
print('Save...')
211+
log.info('Save...')
155212
if file_path == None or file_path == '':
156213
file_path = get_saveasfile_path(file_path)
157214

158-
# print(file_path)
215+
# log.info(file_path)
159216

160217
if file_path == None or file_path == '':
161218
return original_file_path # In case a file_path was provided and the user decide to cancel the open action
@@ -286,7 +343,7 @@ def open_configuration(
286343
# load variables from JSON file
287344
with open(file_path, 'r') as f:
288345
my_data = json.load(f)
289-
print('Loading config...')
346+
log.info('Loading config...')
290347

291348
# Update values to fix deprecated use_8bit_adam checkbox, set appropriate optimizer if it is set to True, etc.
292349
my_data = update_my_data(my_data)
@@ -396,6 +453,7 @@ def train_model(
396453
save_last_n_steps_state,
397454
):
398455
print_only_bool = True if print_only.get('label') == 'True' else False
456+
log.info(f'Start training LoRA {LoRA_type} ...')
399457

400458
if pretrained_model_name_or_path == '':
401459
msgbox('Source model information is missing')
@@ -482,19 +540,19 @@ def train_model(
482540
]
483541
)
484542

485-
print(f'Folder {folder}: {num_images} images found')
543+
log.info(f'Folder {folder}: {num_images} images found')
486544

487545
# Calculate the total number of steps for this folder
488546
steps = repeats * num_images
489547

490-
# Print the result
491-
print(f'Folder {folder}: {steps} steps')
548+
# log.info the result
549+
log.info(f'Folder {folder}: {steps} steps')
492550

493551
total_steps += steps
494552

495553
except ValueError:
496554
# Handle the case where the folder name does not contain an underscore
497-
print(
555+
log.info(
498556
f"Error: '{folder}' does not contain an underscore, skipping..."
499557
)
500558

@@ -507,7 +565,7 @@ def train_model(
507565
# * int(reg_factor)
508566
)
509567
)
510-
print(f'max_train_steps = {max_train_steps}')
568+
log.info(f'max_train_steps = {max_train_steps}')
511569

512570
# calculate stop encoder training
513571
if stop_text_encoder_training_pct == None:
@@ -516,10 +574,10 @@ def train_model(
516574
stop_text_encoder_training = math.ceil(
517575
float(max_train_steps) / 100 * int(stop_text_encoder_training_pct)
518576
)
519-
print(f'stop_text_encoder_training = {stop_text_encoder_training}')
577+
log.info(f'stop_text_encoder_training = {stop_text_encoder_training}')
520578

521579
lr_warmup_steps = round(float(int(lr_warmup) * int(max_train_steps) / 100))
522-
print(f'lr_warmup_steps = {lr_warmup_steps}')
580+
log.info(f'lr_warmup_steps = {lr_warmup_steps}')
523581

524582
run_cmd = f'accelerate launch --num_cpu_threads_per_process={num_cpu_threads_per_process} "train_network.py"'
525583

@@ -557,7 +615,7 @@ def train_model(
557615
try:
558616
import lycoris
559617
except ModuleNotFoundError:
560-
print(
618+
log.info(
561619
"\033[1;31mError:\033[0m The required module 'lycoris_lora' is not installed. Please install by running \033[33mupgrade.ps1\033[0m before running this program."
562620
)
563621
return
@@ -567,7 +625,7 @@ def train_model(
567625
try:
568626
import lycoris
569627
except ModuleNotFoundError:
570-
print(
628+
log.info(
571629
"\033[1;31mError:\033[0m The required module 'lycoris_lora' is not installed. Please install by running \033[33mupgrade.ps1\033[0m before running this program."
572630
)
573631
return
@@ -738,12 +796,12 @@ def train_model(
738796
# run_cmd += f' --conv_alphas="{conv_alphas}"'
739797

740798
if print_only_bool:
741-
print(
799+
log.info(
742800
'\033[93m\nHere is the trainer command as a reference. It will not be executed:\033[0m\n'
743801
)
744-
print('\033[96m' + run_cmd + '\033[0m\n')
802+
log.info('\033[96m' + run_cmd + '\033[0m\n')
745803
else:
746-
print(run_cmd)
804+
log.info(run_cmd)
747805
# Run the command
748806
if os.name == 'posix':
749807
os.system(run_cmd)
@@ -973,7 +1031,7 @@ def lora_tab(
9731031
# Show of hide LoCon conv settings depending on LoRA type selection
9741032
def update_LoRA_settings(LoRA_type):
9751033
# Print a message when LoRA type is changed
976-
print('LoRA type changed...')
1034+
log.info('LoRA type changed...')
9771035

9781036
# Determine if LoCon_row should be visible based on LoRA_type
9791037
LoCon_row = LoRA_type in {
@@ -1317,7 +1375,7 @@ def UI(**kwargs):
13171375

13181376
if os.path.exists('./style.css'):
13191377
with open(os.path.join('./style.css'), 'r', encoding='utf8') as file:
1320-
print('Load CSS...')
1378+
log.info('Load CSS...')
13211379
css += file.read() + '\n'
13221380

13231381
interface = gr.Blocks(css=css)
@@ -1352,7 +1410,7 @@ def UI(**kwargs):
13521410
launch_kwargs['inbrowser'] = kwargs.get('inbrowser', False)
13531411
if kwargs.get('listen', True):
13541412
launch_kwargs['server_name'] = '0.0.0.0'
1355-
print(launch_kwargs)
1413+
log.info(launch_kwargs)
13561414
interface.launch(**launch_kwargs)
13571415

13581416

tools/validate_requirements.py

+68-7
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,74 @@
22
import sys
33
import pkg_resources
44
import argparse
5+
import shutil
6+
import logging
7+
import time
8+
9+
log = logging.getLogger("sd")
10+
11+
# setup console and file logging
12+
def setup_logging(clean=False):
13+
try:
14+
if clean and os.path.isfile('setup.log'):
15+
os.remove('setup.log')
16+
time.sleep(0.1) # prevent race condition
17+
except:
18+
pass
19+
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s | %(levelname)s | %(pathname)s | %(message)s', filename='setup.log', filemode='a', encoding='utf-8', force=True)
20+
from rich.theme import Theme
21+
from rich.logging import RichHandler
22+
from rich.console import Console
23+
from rich.pretty import install as pretty_install
24+
from rich.traceback import install as traceback_install
25+
console = Console(log_time=True, log_time_format='%H:%M:%S-%f', theme=Theme({
26+
"traceback.border": "black",
27+
"traceback.border.syntax_error": "black",
28+
"inspect.value.border": "black",
29+
}))
30+
pretty_install(console=console)
31+
traceback_install(console=console, extra_lines=1, width=console.width, word_wrap=False, indent_guides=False, suppress=[])
32+
rh = RichHandler(show_time=True, omit_repeated_times=False, show_level=True, show_path=False, markup=False, rich_tracebacks=True, log_time_format='%H:%M:%S-%f', level=logging.DEBUG if args.debug else logging.INFO, console=console)
33+
rh.set_name(logging.DEBUG if args.debug else logging.INFO)
34+
log.addHandler(rh)
35+
36+
def check_torch():
37+
if shutil.which('nvidia-smi') is not None or os.path.exists(os.path.join(os.environ.get('SystemRoot') or r'C:\Windows', 'System32', 'nvidia-smi.exe')):
38+
log.info('nVidia toolkit detected')
39+
elif shutil.which('rocminfo') is not None or os.path.exists('/opt/rocm/bin/rocminfo'):
40+
log.info('AMD toolkit detected')
41+
else:
42+
log.info('Using CPU-only Torch')
43+
try:
44+
import torch
45+
log.info(f'Torch {torch.__version__}')
46+
if not torch.cuda.is_available():
47+
log.warning("Torch repoorts CUDA not available")
48+
else:
49+
if torch.version.cuda:
50+
log.info(f'Torch backend: nVidia CUDA {torch.version.cuda} cuDNN {torch.backends.cudnn.version() if torch.backends.cudnn.is_available() else "N/A"}')
51+
elif torch.version.hip:
52+
log.info(f'Torch backend: AMD ROCm HIP {torch.version.hip}')
53+
else:
54+
log.warning('Unknown Torch backend')
55+
for device in [torch.cuda.device(i) for i in range(torch.cuda.device_count())]:
56+
log.info(f'Torch detected GPU: {torch.cuda.get_device_name(device)} VRAM {round(torch.cuda.get_device_properties(device).total_memory / 1024 / 1024)} Arch {torch.cuda.get_device_capability(device)} Cores {torch.cuda.get_device_properties(device).multi_processor_count}')
57+
except Exception as e:
58+
log.error(f'Could not load torch: {e}')
59+
exit(1)
560

661
# Parse command line arguments
762
parser = argparse.ArgumentParser(description="Validate that requirements are satisfied.")
863
parser.add_argument('-r', '--requirements', type=str, default='requirements.txt', help="Path to the requirements file.")
64+
parser.add_argument(
65+
'--debug', action='store_true', help='Debug on'
66+
)
967
args = parser.parse_args()
1068

11-
print("Validating that requirements are satisfied.")
69+
setup_logging()
70+
check_torch()
71+
72+
log.info("Validating that requirements are satisfied.")
1273

1374
# Load the requirements from the specified requirements file
1475
with open(args.requirements) as f:
@@ -44,18 +105,18 @@
44105
# If there are any missing or wrong version requirements, print an error message and exit with a non-zero exit code
45106
if missing_requirements or wrong_version_requirements:
46107
if missing_requirements:
47-
print("Error: The following packages are missing:")
108+
log.info("Error: The following packages are missing:")
48109
for requirement in missing_requirements:
49-
print(f" - {requirement}")
110+
log.info(f" - {requirement}")
50111
if wrong_version_requirements:
51-
print("Error: The following packages have the wrong version:")
112+
log.info("Error: The following packages have the wrong version:")
52113
for requirement, expected_version, actual_version in wrong_version_requirements:
53-
print(f" - {requirement} (expected version {expected_version}, found version {actual_version})")
114+
log.info(f" - {requirement} (expected version {expected_version}, found version {actual_version})")
54115
upgrade_script = "upgrade.ps1" if os.name == "nt" else "upgrade.sh"
55-
print(f"\nRun \033[33m{upgrade_script}\033[0m or \033[33mpip install -U -r {args.requirements}\033[0m to resolve the missing requirements listed above...")
116+
log.info(f"\nRun \033[33m{upgrade_script}\033[0m or \033[33mpip install -U -r {args.requirements}\033[0m to resolve the missing requirements listed above...")
56117

57118
sys.exit(1)
58119

59120
# All requirements satisfied
60-
print("All requirements satisfied.")
121+
log.info("All requirements satisfied.")
61122
sys.exit(0)

0 commit comments

Comments
 (0)