-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy pathcmd_args.py
More file actions
1319 lines (1109 loc) · 55.5 KB
/
Copy pathcmd_args.py
File metadata and controls
1319 lines (1109 loc) · 55.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import ast
import json
import logging
import os
import random
import re
import sys
import time
from collections.abc import Mapping
from datetime import timedelta
from pathlib import Path
from typing import Any, Dict, List, Optional
import torch
from accelerate import InitProcessGroupKwargs
from accelerate.utils import ProjectConfiguration
from simpletuner.helpers.configuration.cli_utils import mapping_to_cli_args, normalize_lr_scheduler_value
from simpletuner.helpers.logging import get_logger
from simpletuner.helpers.training.attention_backend import (
AttentionBackendMode,
is_sageattention_available,
xformers_compute_capability_error,
)
from simpletuner.helpers.training.multi_process import should_log
from simpletuner.helpers.training.optimizer_param import is_optimizer_deprecated, is_optimizer_grad_fp32
from simpletuner.helpers.training.quantisation import MANUAL_QUANTIZATION_PRESETS, PIPELINE_QUANTIZATION_PRESETS
from simpletuner.helpers.training.state_tracker import StateTracker
from simpletuner.simpletuner_sdk.server.services.field_registry.types import (
ConfigField,
FieldType,
ParserType,
ValidationRuleType,
)
from simpletuner.simpletuner_sdk.server.utils.paths import resolve_config_path
logger = get_logger("ArgsParser")
if torch.cuda.is_available():
os.environ["NCCL_SOCKET_NTIMEO"] = "2000000"
def print_on_main_thread(message):
if should_log():
print(message)
def info_log(message):
if should_log():
logger.info(message)
def warning_log(message):
if should_log():
logger.warning(message)
def error_log(message):
if should_log():
logger.error(message)
def _configure_tf32(disable_tf32: bool) -> None:
"""Configure TF32/FP32 behavior for CUDA backends."""
if not torch.cuda.is_available():
return
backend_root = getattr(torch, "backends", None)
if backend_root is None:
return
cuda_backend = getattr(backend_root, "cuda", None)
cudnn_backend = getattr(backend_root, "cudnn", None)
matmul_backend = getattr(cuda_backend, "matmul", None)
cudnn_conv_backend = getattr(cudnn_backend, "conv", None)
cudnn_rnn_backend = getattr(cudnn_backend, "rnn", None)
supports_precision_overrides = any(
(
hasattr(torch, "set_float32_matmul_precision"),
hasattr(backend_root, "fp32_precision"),
matmul_backend is not None and hasattr(matmul_backend, "fp32_precision"),
cudnn_backend is not None and hasattr(cudnn_backend, "fp32_precision"),
)
)
def _set_tf32(enabled: bool) -> None:
if supports_precision_overrides:
precision = "tf32" if enabled else "ieee"
if hasattr(torch, "set_float32_matmul_precision"):
torch.set_float32_matmul_precision("high" if enabled else "highest")
if hasattr(backend_root, "fp32_precision"):
backend_root.fp32_precision = precision
if matmul_backend is not None and hasattr(matmul_backend, "fp32_precision"):
matmul_backend.fp32_precision = precision
if cudnn_backend is not None and hasattr(cudnn_backend, "fp32_precision"):
cudnn_backend.fp32_precision = precision
for cudnn_op_backend in (cudnn_conv_backend, cudnn_rnn_backend):
if cudnn_op_backend is not None and hasattr(cudnn_op_backend, "fp32_precision"):
cudnn_op_backend.fp32_precision = precision
if (
cudnn_backend is not None
and hasattr(cudnn_backend, "allow_tf32")
and not hasattr(cudnn_backend, "fp32_precision")
):
cudnn_backend.allow_tf32 = enabled
else:
if matmul_backend is not None and hasattr(matmul_backend, "allow_tf32"):
matmul_backend.allow_tf32 = enabled
if cudnn_backend is not None and hasattr(cudnn_backend, "allow_tf32"):
cudnn_backend.allow_tf32 = enabled
if disable_tf32:
warning_log("--disable_tf32 is provided, not enabling. Training will potentially be much slower.")
_set_tf32(False)
else:
_set_tf32(True)
info_log("Enabled NVIDIA TF32 for faster training on Ampere GPUs. Use --disable_tf32 if this causes any problems.")
def _configure_rocm_environment() -> None:
"""Enable ROCm-specific acceleration toggles when running on HIP builds."""
if not torch.cuda.is_available():
return
hip_version = getattr(getattr(torch, "version", None), "hip", None)
if not hip_version:
return
os.environ.setdefault("PYTORCH_TUNABLEOP_ENABLED", "1")
if "HIPBLASLT_ALLOW_TF32" in os.environ:
return
if not _has_mi300_gpu():
return
os.environ["HIPBLASLT_ALLOW_TF32"] = "1"
def _has_mi300_gpu() -> bool:
"""Return True when at least one visible device exposes an MI300 (gfx94x) architecture."""
try:
device_count = torch.cuda.device_count()
except Exception:
device_count = 0
for index in range(device_count):
try:
props = torch.cuda.get_device_properties(index)
except Exception:
continue
if _device_is_mi300(props):
return True
return False
def _device_is_mi300(props: Any) -> bool:
mi300_tokens = ("mi300", "gfx940", "gfx941", "gfx942", "gfx943", "gfx944", "gfx94")
candidates = (
str(getattr(props, "gcnArchName", "") or "").lower(),
str(getattr(props, "name", "") or "").lower(),
)
return any(token in candidate for token in mi300_tokens for candidate in candidates)
_ARG_PARSER_CACHE: Optional[argparse.ArgumentParser] = None
BOOL_TRUE_STRINGS = {"1", "true", "yes", "y", "on"}
BOOL_FALSE_STRINGS = {"0", "false", "no", "n", "off"}
def _parse_json_like_option(raw_value, option_name: str):
"""
Normalize config options that accept rich JSON structures or file references.
"""
if raw_value in (None, "", "None"):
return None
if isinstance(raw_value, (dict, list)):
return raw_value
if isinstance(raw_value, str):
candidate = raw_value.strip()
if not candidate:
return None
if candidate.startswith("{") or candidate.startswith("["):
try:
return json.loads(candidate)
except json.JSONDecodeError as json_error:
try:
return ast.literal_eval(candidate)
except (ValueError, SyntaxError) as ast_error:
raise ValueError(
f"Could not parse {option_name} as JSON."
f" json.loads error: {json_error}; ast.literal_eval error: {ast_error}"
) from ast_error
expanded_path = os.path.expanduser(candidate)
if os.path.isfile(expanded_path):
try:
with open(expanded_path, "r", encoding="utf-8") as handle:
return json.load(handle)
except json.JSONDecodeError as file_error:
raise ValueError(f"Could not load {option_name} from {expanded_path}: {file_error}") from file_error
return candidate
return raw_value
def _process_modelspec_comment(value) -> str | None:
"""Process modelspec_comment: handle array, env placeholders."""
if value is None:
return None
if isinstance(value, list):
value = "\n".join(str(item) for item in value)
elif not isinstance(value, str):
value = str(value)
value = value.strip()
if not value:
return None
def replace_env(match):
var_name = match.group(1)
return os.environ.get(var_name, "")
value = re.sub(r"\{env:([^}]+)\}", replace_env, value)
return value or None
def _contains_ast_markers(candidate: str) -> bool:
lowered = candidate.lower()
return (
"ast." in candidate
or "<ast." in candidate
or "ast object at" in lowered
or (candidate.strip().startswith("<") and candidate.strip().endswith(">"))
)
def _normalize_structured_config_option(raw_value, option_name: str):
"""
Normalize structured CLI options such as webhook_config and publishing_config.
Returns a list (preserving order) or raises ValueError with a descriptive message.
"""
if raw_value is None:
return None
logger.debug("%s at start = %s (type: %s)", option_name, raw_value, type(raw_value))
if isinstance(raw_value, (ast.AST, ast.Name, ast.Call, ast.Dict, ast.List, ast.Constant)) or (
hasattr(raw_value, "__class__") and "ast" in str(type(raw_value))
):
ast_repr = repr(raw_value)
raise ValueError(
f"{option_name} is an AST object ({ast_repr}) instead of a JSON string or file path. "
f"Please check your configuration format."
)
if isinstance(raw_value, str):
import os
config_str = os.path.expanduser(str(raw_value))
if config_str.startswith("{") or config_str.startswith("["):
if _contains_ast_markers(config_str):
raise ValueError(f"{option_name} contains AST object patterns instead of valid JSON. Received: {config_str}")
try:
parsed_config = json.loads(config_str)
except json.JSONDecodeError as exc:
raise ValueError(f"Could not load {option_name} (invalid JSON): {exc}") from exc
if isinstance(parsed_config, dict):
return [parsed_config]
if isinstance(parsed_config, list):
return parsed_config
raise ValueError(f"Invalid {option_name} type: {type(parsed_config)}")
if os.path.isfile(config_str):
try:
with open(config_str, "r") as handle:
loaded_config = json.load(handle)
except Exception as exc:
raise ValueError(f"Could not load {option_name} from file: {exc}") from exc
if isinstance(loaded_config, dict):
return [loaded_config]
if isinstance(loaded_config, list):
return loaded_config
raise ValueError(f"Invalid {option_name} type: {type(loaded_config)}")
raise ValueError(f"Could not find {option_name} file: {config_str}")
def _normalize_lora_target_modules(raw_value, option_name: str):
"""Normalize PEFT LoRA target modules supplied as JSON or JSON file."""
if raw_value is None:
return None
if isinstance(raw_value, (ast.AST, ast.Name, ast.Call, ast.Dict, ast.List, ast.Constant)) or (
hasattr(raw_value, "__class__") and "ast" in str(type(raw_value))
):
ast_repr = repr(raw_value)
raise ValueError(
f"{option_name} is an AST object ({ast_repr}) instead of a JSON string or file path. "
f"Please check your configuration format."
)
def _normalize_list(value):
if isinstance(value, dict):
raise ValueError(f"{option_name} must be a JSON array of strings, got {type(value)}")
if not isinstance(value, (list, tuple)):
raise ValueError(f"{option_name} must be a JSON array of strings, got {type(value)}")
normalized = []
for entry in value:
if entry in (None, "", "None"):
continue
if not isinstance(entry, str):
raise ValueError(f"{option_name} entries must be strings, got {type(entry)}")
candidate = entry.strip()
if candidate:
normalized.append(candidate)
return normalized or None
if isinstance(raw_value, str):
config_str = os.path.expanduser(str(raw_value))
if config_str in ("", "None"):
return None
if config_str.startswith("{") or config_str.startswith("["):
if _contains_ast_markers(config_str):
raise ValueError(f"{option_name} contains AST object patterns instead of valid JSON. Received: {config_str}")
try:
parsed_config = json.loads(config_str)
except json.JSONDecodeError as exc:
raise ValueError(f"Could not load {option_name} (invalid JSON): {exc}") from exc
return _normalize_list(parsed_config)
if os.path.isfile(config_str):
try:
with open(config_str, "r", encoding="utf-8") as handle:
loaded_config = json.load(handle)
except Exception as exc:
raise ValueError(f"Could not load {option_name} from file: {exc}") from exc
return _normalize_list(loaded_config)
raise ValueError(f"Could not find {option_name} file: {config_str}")
return _normalize_list(raw_value)
if isinstance(raw_value, dict):
return [raw_value]
if isinstance(raw_value, list):
return raw_value
raise ValueError(f"{option_name} must be string, dict, or list, got {type(raw_value)}")
def _normalize_sana_complex_instruction(raw_value):
"""
Normalize the Sana complex human instruction value so downstream code always receives a list of strings.
"""
if raw_value in (None, "", "None"):
return None
if isinstance(raw_value, (list, tuple)):
normalized = []
for entry in raw_value:
if entry in (None, "", "None"):
continue
entry_str = str(entry).strip()
if entry_str:
normalized.append(entry_str)
return normalized or None
if not isinstance(raw_value, str):
raise ValueError(f"Unsupported type for sana_complex_human_instruction: {type(raw_value).__name__}")
candidate = raw_value.strip()
if not candidate or candidate == "None":
return None
expanded_path = os.path.expanduser(candidate)
if os.path.isfile(expanded_path):
with open(expanded_path, "r", encoding="utf-8") as handle:
file_contents = handle.read()
return _normalize_sana_complex_instruction(file_contents)
if candidate.startswith("{") or candidate.startswith("["):
try:
parsed = json.loads(candidate)
except json.JSONDecodeError as json_error:
logger.error(f"Could not parse sana_complex_human_instruction as JSON: {json_error}")
raise
return _normalize_sana_complex_instruction(parsed)
instructions = [line.strip() for line in candidate.splitlines() if line.strip()]
return instructions or [candidate]
def _parse_bool_flag(value):
if isinstance(value, bool):
return value
if value is None:
return True
text_value = str(value).strip().lower()
if text_value in BOOL_TRUE_STRINGS:
return True
if text_value in BOOL_FALSE_STRINGS:
return False
raise argparse.ArgumentTypeError(f"Expected a boolean value, got {value!r}")
def _extract_choice_values(field: ConfigField) -> List[Any]:
if not field.choices or field.dynamic_choices:
return []
values: List[Any] = []
for choice in field.choices:
if isinstance(choice, Mapping):
values.append(choice.get("value"))
else:
values.append(choice)
return values
def _infer_numeric_type(field: ConfigField, choice_values: List[Any]):
candidates: List[Any] = []
default = field.default_value
if default not in (None, "==SUPPRESS=="):
candidates.append(default)
candidates.extend(choice_values)
for rule in field.validation_rules:
value = getattr(rule, "value", None)
if value is not None:
candidates.append(value)
for candidate in candidates:
if isinstance(candidate, float):
return float
if isinstance(candidate, str):
try:
numeric_value = float(candidate)
except ValueError:
continue
if "." in candidate or "e" in candidate.lower() or not numeric_value.is_integer():
return float
return int
def _determine_cli_type(field: ConfigField, choice_values: List[Any]):
if field.parser_type is not None:
parser_type_map = {
ParserType.STRING: str,
ParserType.INTEGER: int,
ParserType.FLOAT: float,
ParserType.BOOLEAN: _parse_bool_flag,
}
try:
return parser_type_map[field.parser_type]
except KeyError as exc:
raise ValueError(f"Unsupported parser type override: {field.parser_type}") from exc
if field.field_type == FieldType.NUMBER:
return _infer_numeric_type(field, choice_values)
return str
def _is_required(field: ConfigField) -> bool:
return any(rule.rule_type == ValidationRuleType.REQUIRED for rule in field.validation_rules)
def _add_argument_from_field(parser: argparse.ArgumentParser, field: ConfigField) -> None:
choice_values = _extract_choice_values(field)
cli_choices = [value for value in choice_values if value is not None]
help_text = field.help_text or getattr(field, "cmd_args_help", "") or field.tooltip
kwargs: Dict[str, Any] = {}
option_strings: List[str] = []
if isinstance(field.arg_name, str):
option_strings.append(field.arg_name)
elif isinstance(field.arg_name, (list, tuple)):
option_strings.extend(field.arg_name)
else:
option_strings.append(str(field.arg_name))
if field.aliases:
option_strings.extend(field.aliases)
# Deduplicate while preserving order
seen_opts = set()
option_strings = [opt for opt in option_strings if not (opt in seen_opts or seen_opts.add(opt))]
if help_text:
kwargs["help"] = help_text
if _is_required(field):
kwargs["required"] = True
if field.field_type == FieldType.CHECKBOX:
default = field.default_value
if default == "==SUPPRESS==":
return
if default is None:
default_bool = None
else:
default_bool = _parse_bool_flag(default)
kwargs.update(
{
"nargs": "?",
"const": True,
"type": _parse_bool_flag,
"default": default_bool,
}
)
parser.add_argument(*option_strings, **kwargs)
return
if field.field_type == FieldType.SELECT:
cli_choices = [str(value) for value in cli_choices]
if cli_choices and not field.dynamic_choices:
kwargs["choices"] = cli_choices
default = field.default_value
if field.field_type == FieldType.SELECT and default is not None:
default = str(default)
if default is not None:
kwargs["default"] = default
kwargs["type"] = _determine_cli_type(field, cli_choices)
parser.add_argument(*option_strings, **kwargs)
def _populate_parser_from_field_registry(parser: argparse.ArgumentParser) -> None:
from simpletuner.simpletuner_sdk.server.services.field_registry.registry import field_registry
seen: set[str] = set()
for field in field_registry._fields.values():
arg_name = field.arg_name
if not arg_name or not arg_name.startswith("--") or arg_name == "--help":
continue
if field.default_value == "==SUPPRESS==":
continue
if arg_name in seen:
continue
seen.add(arg_name)
_add_argument_from_field(parser, field)
def get_argument_parser():
global _ARG_PARSER_CACHE
if _ARG_PARSER_CACHE is not None:
return _ARG_PARSER_CACHE
parser = argparse.ArgumentParser(
description="The following SimpleTuner command-line options are available:",
exit_on_error=False,
)
_populate_parser_from_field_registry(parser)
_ARG_PARSER_CACHE = parser
return parser
def get_default_config():
parser = get_argument_parser()
default_config = {}
for action in parser.__dict__["_actions"]:
if action.dest:
default_config[action.dest] = action.default
return default_config
def parse_cmdline_args(input_args=None, exit_on_error: bool = False):
parser = get_argument_parser()
args = None
from simpletuner.helpers.training.state_tracker import StateTracker
parser_error = None
def _normalize_model_family(value: str) -> str:
normalized = (value or "").strip().lower()
if not normalized:
return normalized
try:
from simpletuner.helpers.models.registry import ModelRegistry
families = list(ModelRegistry.model_families().keys())
except Exception:
return normalized
if normalized in families:
return normalized
return normalized
def _normalize_input_args(raw_args):
if raw_args is None:
return None
normalized_args = []
skip_next = False
for idx, arg in enumerate(raw_args):
if skip_next:
skip_next = False
continue
if arg.startswith(("--lr_scheduler=", "--lr-scheduler=")):
prefix, value = arg.split("=", 1)
normalized_value = normalize_lr_scheduler_value(value)
normalized_args.append(f"{prefix}={normalized_value}")
continue
if arg in ("--lr_scheduler", "--lr-scheduler") and idx + 1 < len(raw_args):
normalized_args.append(arg)
normalized_args.append(normalize_lr_scheduler_value(raw_args[idx + 1]))
skip_next = True
continue
if arg.startswith(("--model_family=", "--model-family=")):
prefix, value = arg.split("=", 1)
normalized_args.append(f"{prefix}={_normalize_model_family(value)}")
continue
if arg in ("--model_family", "--model-family") and idx + 1 < len(raw_args):
normalized_args.append(arg)
normalized_args.append(_normalize_model_family(raw_args[idx + 1]))
skip_next = True
continue
normalized_args.append(arg)
return normalized_args
parser_error_traceback = None
try:
normalized_args = _normalize_input_args(input_args)
args = parser.parse_args(normalized_args)
except Exception: # pragma: no cover - parser handles errors consistently
parser_error = sys.exc_info()[1]
import traceback
parser_error_traceback = traceback.format_exc()
logger.error(f"Could not parse input: {input_args}")
logger.error(parser_error_traceback)
webhook_handler = StateTracker.get_webhook_handler()
if webhook_handler is not None:
try:
logger.info(f"Sending error message to webhook: {webhook_handler.webhook_url}")
# Sanitize error message - don't expose raw args in webhook
webhook_handler.send(
message="Command Line Argument Error: Failed to parse command line arguments. Please check the server logs for details.",
message_level="error",
)
except Exception as exc:
logger.error(f"Failed to send webhook error message: {exc}")
logger.error(f"Argument parsing failed for input: {input_args}")
else:
logger.error("No webhook handler available to send error message.")
if args is None and exit_on_error:
error_detail = parser_error_traceback or str(parser_error) if parser_error else "unknown parsing error"
raise ValueError(f"Could not parse command line arguments:\n{error_detail}")
if args is None:
return None
if hasattr(args, "lr_scheduler"):
normalized_lr_scheduler = normalize_lr_scheduler_value(
getattr(args, "lr_scheduler", None),
getattr(args, "lr_warmup_steps", None),
)
if normalized_lr_scheduler != getattr(args, "lr_scheduler", None):
args.lr_scheduler = normalized_lr_scheduler
if args.controlnet_custom_config is not None and type(args.controlnet_custom_config) is str:
if args.controlnet_custom_config.startswith("{"):
try:
args.controlnet_custom_config = ast.literal_eval(args.controlnet_custom_config)
except Exception as e:
logger.error(f"Could not load controlnet_custom_config: {e}")
raise
if args.webhook_config is not None:
try:
args.webhook_config = _normalize_structured_config_option(args.webhook_config, "webhook_config")
except ValueError as exc:
logger.error(str(exc))
raise
if getattr(args, "publishing_config", None) is not None:
try:
args.publishing_config = _normalize_structured_config_option(args.publishing_config, "publishing_config")
except ValueError as exc:
logger.error(str(exc))
raise
if isinstance(getattr(args, "post_checkpoint_script", None), str):
candidate = args.post_checkpoint_script.strip()
args.post_checkpoint_script = candidate or None
if isinstance(getattr(args, "post_upload_script", None), str):
candidate = args.post_upload_script.strip()
args.post_upload_script = candidate or None
if hasattr(args, "modelspec_comment"):
args.modelspec_comment = _process_modelspec_comment(args.modelspec_comment)
if args.tread_config is not None and type(args.tread_config) is str:
if args.tread_config.startswith("{"):
try:
args.tread_config = ast.literal_eval(args.tread_config)
except Exception as e:
logger.error(f"Could not load tread_config: {e}")
raise
if args.sla_config is not None and isinstance(args.sla_config, str):
candidate = args.sla_config.strip()
if candidate.startswith("{"):
try:
args.sla_config = ast.literal_eval(candidate)
except Exception as e:
logger.error(f"Could not load sla_config: {e}")
raise
if args.optimizer == "adam_bfloat16" and args.mixed_precision != "bf16":
if not torch.backends.mps.is_available():
raise ValueError("You cannot use --adam_bfloat16 without --mixed_precision=bf16.")
if args.mixed_precision == "fp8" and not torch.cuda.is_available():
raise ValueError("You cannot use --mixed_precision=fp8 without a CUDA device. Please use bf16 instead.")
if hasattr(args, "quantization_config"):
try:
args.quantization_config = _parse_json_like_option(args.quantization_config, "quantization_config")
except ValueError as exc:
logger.error(str(exc))
raise
if isinstance(args.quantization_config, list):
raise ValueError("quantization_config must be a JSON object, not a list.")
if isinstance(args.quantization_config, str) and args.quantization_config not in (None, ""):
raise ValueError(
"quantization_config must be JSON or a file path to a JSON object. "
f"Received a raw string instead: {args.quantization_config}"
)
manual_quant_precisions = set(MANUAL_QUANTIZATION_PRESETS)
pipeline_quant_precisions = set(PIPELINE_QUANTIZATION_PRESETS)
manual_only_precisions = manual_quant_precisions - pipeline_quant_precisions
quantization_precisions = manual_quant_precisions | pipeline_quant_precisions
base_precision = getattr(args, "base_model_precision", "no_change")
model_path = str(getattr(args, "pretrained_model_name_or_path", "") or "")
is_gguf_checkpoint = model_path.endswith(".gguf")
quantize_via_pipeline = getattr(args, "quantize_via", "accelerator") == "pipeline"
if args.quantization_config is not None and args.model_type != "lora":
raise ValueError("quantization_config is only supported for LoRA training.")
if quantize_via_pipeline and base_precision in manual_only_precisions:
raise ValueError(
f"quantize_via=pipeline cannot be combined with base_model_precision '{base_precision}'. "
"Use a Diffusers-compatible preset such as nf4-bnb or int4-torchao, or provide a pipeline quantization_config."
)
if quantize_via_pipeline:
for idx in range(1, 5):
te_precision = getattr(args, f"text_encoder_{idx}_precision", None)
if te_precision in manual_only_precisions:
raise ValueError(
f"quantize_via=pipeline cannot be combined with manual text encoder quantization ({te_precision}). "
"Provide a pipeline quantization_config entry for text encoders instead."
)
if quantize_via_pipeline and not (
base_precision in pipeline_quant_precisions
or base_precision == "no_change"
or args.quantization_config is not None
or is_gguf_checkpoint
):
raise ValueError(
"quantize_via=pipeline requires a pipeline-capable base_model_precision, a quantization_config, or a GGUF checkpoint."
)
if base_precision in pipeline_quant_precisions:
for idx in range(1, 5):
te_precision = getattr(args, f"text_encoder_{idx}_precision", None)
if te_precision in manual_only_precisions:
raise ValueError(
f"base_model_precision '{base_precision}' cannot be combined with manual text encoder quantization ({te_precision}). "
"Use pipeline presets for text encoders or disable manual quantization."
)
if (
args.quantization_config is not None
and base_precision not in pipeline_quant_precisions
and base_precision != "no_change"
):
raise ValueError(
"quantization_config is intended for pipeline-backed quantization. "
f"Set base_model_precision to a pipeline preset ({', '.join(sorted(pipeline_quant_precisions))}) or 'no_change'."
)
if args.quantization_config is not None:
for idx in range(1, 5):
te_precision = getattr(args, f"text_encoder_{idx}_precision", None)
if te_precision in quantization_precisions:
raise ValueError(
"quantization_config should include any text encoder quantization settings. "
f"Text encoder precision '{te_precision}' is not supported alongside quantization_config."
)
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
if env_local_rank != -1 and env_local_rank != args.local_rank:
args.local_rank = env_local_rank
if args.seed is not None:
if args.seed == 0:
# the current time should be used if value is zero, providing a rolling seed.
args.seed = int(time.time())
elif args.seed == -1:
# more random seed if value is -1, it will be very different on each startup.
args.seed = int(random.randint(0, 2**30))
if args.cache_dir is None or args.cache_dir == "":
args.cache_dir = os.path.join(args.output_dir, "cache")
if args.maximum_image_size is not None and not args.target_downsample_size:
raise ValueError("When providing --maximum_image_size, you must also provide a value for --target_downsample_size.")
if (
args.maximum_image_size is not None
and args.resolution_type == "area"
and args.maximum_image_size > 5
and not os.environ.get("SIMPLETUNER_MAXIMUM_IMAGE_SIZE_OVERRIDE", False)
):
raise ValueError(
f"When using --resolution_type=area, --maximum_image_size must be less than 5 megapixels. You may have accidentally entered {args.maximum_image_size} pixels, instead of megapixels."
)
elif args.maximum_image_size is not None and args.resolution_type == "pixel" and args.maximum_image_size < 512:
raise ValueError(
f"When using --resolution_type=pixel, --maximum_image_size must be at least 512 pixels. You may have accidentally entered {args.maximum_image_size} megapixels, instead of pixels."
)
if (
args.target_downsample_size is not None
and args.resolution_type == "area"
and args.target_downsample_size > 5
and not os.environ.get("SIMPLETUNER_MAXIMUM_IMAGE_SIZE_OVERRIDE", False)
):
raise ValueError(
f"When using --resolution_type=area, --target_downsample_size must be less than 5 megapixels. You may have accidentally entered {args.target_downsample_size} pixels, instead of megapixels."
)
elif args.target_downsample_size is not None and args.resolution_type == "pixel" and args.target_downsample_size < 512:
raise ValueError(
f"When using --resolution_type=pixel, --target_downsample_size must be at least 512 pixels. You may have accidentally entered {args.target_downsample_size} megapixels, instead of pixels."
)
model_is_bf16 = (
base_precision == "no_change" and (args.mixed_precision == "bf16" or torch.backends.mps.is_available())
) or (base_precision != "no_change" and args.base_model_default_dtype == "bf16")
model_is_quantized = base_precision != "no_change" or args.quantization_config is not None or is_gguf_checkpoint
if model_is_quantized and args.mixed_precision == "fp8" and base_precision != "fp8-torchao":
raise ValueError(
"You cannot use --mixed_precision=fp8 with a quantized base model. Please use bf16 or remove base_model_precision option from your configuration."
)
# check optimiser validity
chosen_optimizer = args.optimizer
is_optimizer_deprecated(chosen_optimizer)
from simpletuner.helpers.training.optimizer_param import optimizer_parameters
optimizer_cls, optimizer_details = optimizer_parameters(chosen_optimizer, args)
using_bf16_optimizer = optimizer_details.get("default_settings", {}).get("precision") in ["any", "bf16"]
if using_bf16_optimizer and not model_is_bf16:
raise ValueError(f"Model is not using bf16 precision, but the optimizer {chosen_optimizer} requires it.")
if is_optimizer_grad_fp32(args.optimizer):
warning_log("Using an optimizer that requires fp32 gradients. Training will potentially run more slowly.")
if args.gradient_precision != "fp32":
args.gradient_precision = "fp32"
else:
if args.gradient_precision == "fp32":
args.gradient_precision = "unmodified"
if torch.backends.mps.is_available():
if args.model_family.lower() not in ["sd3", "flux", "legacy"] and not args.unet_attention_slice:
warning_log("MPS may benefit from the use of --unet_attention_slice for memory savings at the cost of speed.")
if args.train_batch_size > 16:
raise ValueError(
"An M3 Max 128G will use 12 seconds per step at a batch size of 1 and 65 seconds per step at a batch size of 12."
" Any higher values will result in NDArray size errors or other unstable training results and crashes."
"\nPlease reduce the batch size to 12 or lower."
)
if args.quantize_via == "accelerator":
args.quantize_via = "cpu"
if args.max_train_steps is not None and args.max_train_steps > 0 and args.num_train_epochs > 0:
raise ValueError("When using --max_train_steps (MAX_NUM_STEPS), you must set --num_train_epochs (NUM_EPOCHS) to 0.")
if (
args.pretrained_vae_model_name_or_path is not None
# currently these are the only models we have using the SDXL VAE.
and args.model_family not in ["sdxl", "pixart_sigma", "kolors"]
and "sdxl" in args.pretrained_vae_model_name_or_path
and "deepfloyd" not in args.model_type
):
warning_log(
f"The VAE model {args.pretrained_vae_model_name_or_path} is not compatible. Please use a compatible VAE to eliminate this warning. The baked-in VAE will be used, instead."
)
args.pretrained_vae_model_name_or_path = None
if args.pretrained_vae_model_name_or_path == "" or args.pretrained_vae_model_name_or_path == "''":
args.pretrained_vae_model_name_or_path = None
if "deepfloyd" not in args.model_type:
info_log(f"VAE Model: {args.pretrained_vae_model_name_or_path or args.pretrained_model_name_or_path}")
info_log(f"Default VAE Cache location: {args.cache_dir_vae}")
info_log(f"Text Cache location: {args.cache_dir_text}")
elif "deepfloyd" in args.model_type:
deepfloyd_pixel_alignment = 8
if args.aspect_bucket_alignment != deepfloyd_pixel_alignment:
warning_log(
f"Overriding aspect bucket alignment pixel interval to {deepfloyd_pixel_alignment}px instead of {args.aspect_bucket_alignment}px."
)
args.aspect_bucket_alignment = deepfloyd_pixel_alignment
if "deepfloyd-stage2" in args.model_type and args.resolution < 256:
warning_log("DeepFloyd Stage II requires a resolution of at least 256. Setting to 256.")
args.resolution = 256
args.aspect_bucket_alignment = 64
args.resolution_type = "pixel"
validation_resolution_is_float = False
if "." in str(args.validation_resolution):
try:
# this makes handling for int() conversion easier later.
args.validation_resolution = float(args.validation_resolution)
validation_resolution_is_float = True
except ValueError:
pass
validation_resolution_is_digit = False
try:
int(args.validation_resolution)
validation_resolution_is_digit = True
except ValueError:
pass
if (
(validation_resolution_is_digit or validation_resolution_is_float)
and int(args.validation_resolution) < 128
and "deepfloyd" not in args.model_type
):
# Convert from megapixels to pixels:
log_msg = f"It seems that --validation_resolution was given in megapixels ({args.validation_resolution}). Converting to pixel measurement:"
if int(args.validation_resolution) == 1:
args.validation_resolution = 1024
else:
args.validation_resolution = int(int(args.validation_resolution) * 1e3)
# Make it divisible by 8:
args.validation_resolution = int(int(args.validation_resolution) / 8) * 8
info_log(f"{log_msg} {int(args.validation_resolution)}px")
if args.timestep_bias_portion < 0.0 or args.timestep_bias_portion > 1.0:
raise ValueError("Timestep bias portion must be between 0.0 and 1.0.")
if args.metadata_update_interval < 60:
raise ValueError("Metadata update interval must be at least 60 seconds.")
args.vae_path = (
args.pretrained_model_name_or_path
if args.pretrained_vae_model_name_or_path is None
else args.pretrained_vae_model_name_or_path
)
if args.use_ema and args.ema_cpu_only:
args.ema_device = "cpu"
if (args.optimizer_beta1 is not None and args.optimizer_beta2 is None) or (
args.optimizer_beta1 is None and args.optimizer_beta2 is not None
):
raise ValueError("Both --optimizer_beta1 and --optimizer_beta2 should be provided.")
if args.gradient_checkpointing:
# enable torch compile w/ activation checkpointing :[ slows us down.
torch._dynamo.config.optimize_ddp = False
args.logging_dir = os.path.join(args.output_dir, args.logging_dir)
args.accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=args.logging_dir)
# Create the custom configuration
args.process_group_kwargs = InitProcessGroupKwargs(timeout=timedelta(seconds=5400)) # 1.5 hours
# Enable TF32 for faster training on Ampere GPUs,
# cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
_configure_tf32(disable_tf32=args.disable_tf32)
_configure_rocm_environment()
args.is_quantized = bool(model_is_quantized and "lora" in str(args.model_type))
args.weight_dtype = (
torch.bfloat16
if (args.mixed_precision == "bf16" or (args.base_model_default_dtype == "bf16" and args.is_quantized))
else torch.float16 if args.mixed_precision == "fp16" else torch.float32
)
args.disable_accelerator = os.environ.get("SIMPLETUNER_DISABLE_ACCELERATOR", False)