nanaj commited on
Commit
aa69dc8
·
verified ·
1 Parent(s): 8c468cf

Upload folder using huggingface_hub (part 3)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +15 -0
  2. SECourses_Musubi_Trainer/musubi_tuner_gui.log +0 -0
  3. SECourses_Musubi_Trainer/musubi_tuner_gui/zimage_lora_gui.py +2219 -0
  4. SECourses_Musubi_Trainer/pytest.ini +2 -0
  5. SECourses_Musubi_Trainer/qwen_image_defaults.toml +252 -0
  6. SECourses_Musubi_Trainer/sitecustomize.py +3 -0
  7. SECourses_Musubi_Trainer/tests/test_automagic_gui.py +75 -0
  8. SECourses_Musubi_Trainer/tests/test_full_finetune_gui.py +875 -0
  9. SECourses_Musubi_Trainer/tests/test_model_quantizer_gui.py +232 -0
  10. SECourses_Musubi_Trainer/tmp_quantizer_expected.json +2066 -0
  11. SECourses_Musubi_Trainer/venv/bin/python +3 -0
  12. SECourses_Musubi_Trainer/venv/bin/python3 +3 -0
  13. SECourses_Musubi_Trainer/venv/bin/python3.10 +3 -0
  14. SECourses_Musubi_Trainer/venv/pyvenv.cfg +3 -0
  15. SECourses_Musubi_Trainer/wan_defaults.toml +238 -0
  16. SECourses_Musubi_Trainer/zimage_defaults.toml +152 -0
  17. gradio/frpc/frpc_linux_amd64_v0.3 +3 -0
  18. hub/models--Qwen--Qwen-Image/.no_exist/75e0b4be04f60ec59a75f475837eced720f823b6/tokenizer/tokenizer.json +0 -0
  19. hub/models--Qwen--Qwen-Image/blobs/28028c056af412405debd878cdda0171e35fa5d1 +54 -0
  20. hub/models--Qwen--Qwen-Image/blobs/31349551d90c7606f325fe0f11bbb8bd5fa0d7c7 +0 -0
  21. hub/models--Qwen--Qwen-Image/blobs/482ced4679301bf287ebb310bdd1790eb4514232 +24 -0
  22. hub/models--Qwen--Qwen-Image/blobs/6bce3a0a3866c4791a74d83d78f6824c3af64ec3 +0 -0
  23. hub/models--Qwen--Qwen-Image/blobs/ac23c0aaa2434523c494330aeb79c58395378103 +31 -0
  24. hub/models--Qwen--Qwen-Image/blobs/eaed590d62aaf0ba31e284b66ddcb18222f066c2 +207 -0
  25. hub/models--Qwen--Qwen-Image/refs/main +1 -0
  26. hub/models--Qwen--Qwen-Image/snapshots/75e0b4be04f60ec59a75f475837eced720f823b6/tokenizer/added_tokens.json +24 -0
  27. hub/models--Qwen--Qwen-Image/snapshots/75e0b4be04f60ec59a75f475837eced720f823b6/tokenizer/chat_template.jinja +54 -0
  28. hub/models--Qwen--Qwen-Image/snapshots/75e0b4be04f60ec59a75f475837eced720f823b6/tokenizer/merges.txt +0 -0
  29. hub/models--Qwen--Qwen-Image/snapshots/75e0b4be04f60ec59a75f475837eced720f823b6/tokenizer/special_tokens_map.json +31 -0
  30. hub/models--Qwen--Qwen-Image/snapshots/75e0b4be04f60ec59a75f475837eced720f823b6/tokenizer/tokenizer_config.json +207 -0
  31. hub/models--Qwen--Qwen-Image/snapshots/75e0b4be04f60ec59a75f475837eced720f823b6/tokenizer/vocab.json +0 -0
  32. hub/version_diffusers_cache.txt +1 -0
  33. venv/.lock +0 -0
  34. venv/bin/Activate.ps1 +247 -0
  35. venv/bin/accelerate +10 -0
  36. venv/bin/accelerate-config +10 -0
  37. venv/bin/accelerate-estimate-memory +10 -0
  38. venv/bin/accelerate-launch +10 -0
  39. venv/bin/accelerate-merge-weights +10 -0
  40. venv/bin/activate +63 -0
  41. venv/bin/activate.csh +26 -0
  42. venv/bin/activate.fish +69 -0
  43. venv/bin/convert-to-quant +10 -0
  44. venv/bin/convert_to_quant +10 -0
  45. venv/bin/ctq +10 -0
  46. venv/bin/diffusers-cli +10 -0
  47. venv/bin/f2py +6 -0
  48. venv/bin/fastapi +6 -0
  49. venv/bin/ftfy +10 -0
  50. venv/bin/gradio +6 -0
.gitattributes CHANGED
@@ -36,3 +36,18 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
36
  SECourses_Musubi_Trainer/musubi-tuner/docs/kisekaeichi_ref.png filter=lfs diff=lfs merge=lfs -text
37
  SECourses_Musubi_Trainer/musubi-tuner/docs/kisekaeichi_result.png filter=lfs diff=lfs merge=lfs -text
38
  SECourses_Musubi_Trainer/musubi-tuner/docs/kisekaeichi_start.png filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  SECourses_Musubi_Trainer/musubi-tuner/docs/kisekaeichi_ref.png filter=lfs diff=lfs merge=lfs -text
37
  SECourses_Musubi_Trainer/musubi-tuner/docs/kisekaeichi_result.png filter=lfs diff=lfs merge=lfs -text
38
  SECourses_Musubi_Trainer/musubi-tuner/docs/kisekaeichi_start.png filter=lfs diff=lfs merge=lfs -text
39
+ SECourses_Musubi_Trainer/venv/bin/python filter=lfs diff=lfs merge=lfs -text
40
+ SECourses_Musubi_Trainer/venv/bin/python3 filter=lfs diff=lfs merge=lfs -text
41
+ SECourses_Musubi_Trainer/venv/bin/python3.10 filter=lfs diff=lfs merge=lfs -text
42
+ gradio/frpc/frpc_linux_amd64_v0.3 filter=lfs diff=lfs merge=lfs -text
43
+ venv/bin/python filter=lfs diff=lfs merge=lfs -text
44
+ venv/bin/python3 filter=lfs diff=lfs merge=lfs -text
45
+ venv/bin/python3.11 filter=lfs diff=lfs merge=lfs -text
46
+ venv/bin/uv filter=lfs diff=lfs merge=lfs -text
47
+ venv/bin/uvx filter=lfs diff=lfs merge=lfs -text
48
+ venv/lib/python3.11/site-packages/PIL/_imaging.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
49
+ venv/lib/python3.11/site-packages/PIL/_imagingcms.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
50
+ venv/lib/python3.11/site-packages/PIL/_imagingft.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
51
+ venv/lib/python3.11/site-packages/PIL/_imagingmath.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
52
+ venv/lib/python3.11/site-packages/PIL/_webp.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
53
+ venv/lib/python3.11/site-packages/_brotli.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
SECourses_Musubi_Trainer/musubi_tuner_gui.log ADDED
The diff for this file is too large to render. See raw diff
 
SECourses_Musubi_Trainer/musubi_tuner_gui/zimage_lora_gui.py ADDED
@@ -0,0 +1,2219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import shlex
4
+ import shutil
5
+ import sys
6
+ import time
7
+ from datetime import datetime
8
+
9
+ import gradio as gr
10
+ import toml
11
+
12
+ from .class_accelerate_launch import AccelerateLaunch
13
+ from .class_advanced_training import AdvancedTraining
14
+ from .class_command_executor import CommandExecutor
15
+ from .class_configuration_file import ConfigurationFile
16
+ from .class_gui_config import GUIConfig
17
+ from .class_huggingface import HuggingFace
18
+ from .class_metadata import MetaData
19
+ from .class_network import Network
20
+ from .class_optimizer_and_scheduler import OptimizerAndScheduler
21
+ from .class_save_load import SaveLoadSettings
22
+ from .class_training import TrainingSettings
23
+ from .full_finetune_gui import normalize_image_training_parameters, training_mode_runtime_exclusions
24
+ from .common_gui import (
25
+ SaveConfigFile,
26
+ SaveConfigFileToRun,
27
+ generate_script_content,
28
+ get_file_path,
29
+ get_file_path_or_save_as,
30
+ get_folder_path,
31
+ print_command_and_toml,
32
+ resolve_portable_model_value,
33
+ run_cmd_advanced_training,
34
+ save_executed_script,
35
+ save_training_preview_config,
36
+ scriptdir,
37
+ requires_native_compile_toolchain,
38
+ setup_environment,
39
+ validate_block_swap_options,
40
+ )
41
+ from .custom_logging import setup_logging
42
+ from .dataset_config_generator import generate_dataset_config_from_folders, save_dataset_config, validate_dataset_config
43
+
44
+ log = setup_logging()
45
+
46
+ executor = None
47
+ train_state_value = time.time()
48
+
49
+
50
+ def _find_accelerate_launch(python_cmd: str) -> list[str]:
51
+ python_dir = os.path.dirname(python_cmd)
52
+ accelerate_fallback = os.path.join(python_dir, "accelerate.exe" if sys.platform == "win32" else "accelerate")
53
+ if os.path.exists(accelerate_fallback) and os.access(accelerate_fallback, os.X_OK):
54
+ return [rf"{accelerate_fallback}", "launch"]
55
+
56
+ accelerate_path = shutil.which("accelerate")
57
+ if accelerate_path:
58
+ return [rf"{accelerate_path}", "launch"]
59
+
60
+ log.warning("Accelerate binary not found, using Python module fallback")
61
+ return [python_cmd, "-m", "accelerate.commands.launch"]
62
+
63
+
64
+ def _get_debug_parameters_for_mode(debug_mode: str) -> str:
65
+ debug_params = {
66
+ "Show Timesteps (Image)": "--show_timesteps image",
67
+ "Show Timesteps (Console)": "--show_timesteps console",
68
+ "RCM Debug Save": "--rcm_debug_save",
69
+ "Enable Logging (TensorBoard)": "--log_with tensorboard",
70
+ "Enable Logging (WandB)": "--log_with wandb",
71
+ "Enable Logging (All)": "--log_with all",
72
+ }
73
+ return debug_params.get(debug_mode, "")
74
+
75
+
76
+ def _generate_zimage_dataset_toml(
77
+ parent_folder_path: str,
78
+ dataset_resolution_width: int,
79
+ dataset_resolution_height: int,
80
+ dataset_caption_extension: str,
81
+ create_missing_captions: bool,
82
+ caption_strategy: str,
83
+ dataset_batch_size: int,
84
+ dataset_enable_bucket: bool,
85
+ dataset_bucket_no_upscale: bool,
86
+ dataset_cache_directory: str,
87
+ output_dir: str,
88
+ ):
89
+ try:
90
+ parent_folder_path = (parent_folder_path or "").strip()
91
+ if not parent_folder_path:
92
+ raise ValueError("Parent folder path is required.")
93
+ if not os.path.isdir(parent_folder_path):
94
+ raise ValueError(f"Parent folder does not exist: {parent_folder_path}")
95
+
96
+ save_dir = (output_dir or "").strip() or parent_folder_path
97
+ os.makedirs(save_dir, exist_ok=True)
98
+
99
+ cfg, msgs = generate_dataset_config_from_folders(
100
+ parent_folder=parent_folder_path,
101
+ resolution=(int(dataset_resolution_width), int(dataset_resolution_height)),
102
+ caption_extension=(dataset_caption_extension or ".txt"),
103
+ create_missing_captions=bool(create_missing_captions),
104
+ caption_strategy=caption_strategy or "folder_name",
105
+ batch_size=int(dataset_batch_size),
106
+ enable_bucket=bool(dataset_enable_bucket),
107
+ bucket_no_upscale=bool(dataset_bucket_no_upscale),
108
+ cache_directory_name=dataset_cache_directory or "cache_dir",
109
+ # Z-Image does not support control images; avoid adding control_directory entries.
110
+ control_directory_name="__zimage_no_control__",
111
+ )
112
+
113
+ ts = datetime.now().strftime("%Y%m%d-%H%M%S")
114
+ out_path = os.path.join(save_dir, f"zimage_dataset_{ts}.toml")
115
+ save_dataset_config(cfg, out_path)
116
+
117
+ is_valid, v_msgs = validate_dataset_config(out_path)
118
+ status_lines = []
119
+ status_lines.extend(msgs)
120
+ status_lines.extend(v_msgs)
121
+ if not is_valid:
122
+ status_lines.append("[ERROR] Dataset TOML validation failed. Please review warnings/errors above.")
123
+ else:
124
+ status_lines.append(f"[OK] Saved dataset TOML: {out_path}")
125
+
126
+ return out_path, out_path, "\n".join(status_lines)
127
+ except Exception as e:
128
+ err = f"[ERROR] Failed to generate dataset TOML: {e}"
129
+ log.error(err)
130
+ return "", "", err
131
+
132
+
133
+ def save_zimage_configuration(save_as_bool, file_path, parameters):
134
+ original_file_path = file_path
135
+
136
+ if save_as_bool or not file_path:
137
+ file_path = get_file_path_or_save_as(file_path, default_extension=".toml", extension_name="TOML files")
138
+
139
+ if not file_path:
140
+ return original_file_path, gr.update(value="No file selected.", visible=True)
141
+
142
+ try:
143
+ SaveConfigFile(
144
+ parameters=parameters,
145
+ file_path=file_path,
146
+ exclusion=["file_path", "save_as", "save_as_bool", "headless", "print_only"],
147
+ )
148
+ msg = f"Configuration saved: {os.path.basename(file_path)}"
149
+ gr.Info(msg)
150
+ return file_path, gr.update(value=msg, visible=True)
151
+ except Exception as e:
152
+ msg = f"Failed to save configuration: {e}"
153
+ log.error(msg)
154
+ gr.Error(msg)
155
+ return original_file_path, gr.update(value=msg, visible=True)
156
+
157
+
158
+ def open_zimage_configuration(ask_for_file, file_path, parameters):
159
+ original_file_path = file_path
160
+
161
+ if ask_for_file:
162
+ file_path = get_file_path_or_save_as(file_path, default_extension=".toml", extension_name="TOML files")
163
+
164
+ if not file_path:
165
+ values = [original_file_path, gr.update(value="", visible=False)]
166
+ values.extend([v for _, v in parameters])
167
+ return tuple(values)
168
+
169
+ if ask_for_file and not os.path.isfile(file_path):
170
+ msg = f"New configuration file will be created at: {os.path.basename(file_path)}"
171
+ gr.Info(msg)
172
+ values = [file_path, gr.update(value=msg, visible=True)]
173
+ values.extend([v for _, v in parameters])
174
+ return tuple(values)
175
+
176
+ if not os.path.isfile(file_path):
177
+ msg = f"Config file does not exist: {file_path}"
178
+ gr.Error(msg)
179
+ values = [original_file_path, gr.update(value=msg, visible=True)]
180
+ values.extend([v for _, v in parameters])
181
+ return tuple(values)
182
+
183
+ try:
184
+ with open(file_path, "r", encoding="utf-8") as f:
185
+ data = toml.load(f)
186
+ except Exception as e:
187
+ msg = f"Failed to load configuration: {e}"
188
+ log.error(msg)
189
+ gr.Error(msg)
190
+ values = [original_file_path, gr.update(value=msg, visible=True)]
191
+ values.extend([v for _, v in parameters])
192
+ return tuple(values)
193
+
194
+ numeric_fields = {
195
+ "dataset_resolution_width",
196
+ "dataset_resolution_height",
197
+ "dataset_batch_size",
198
+ "num_cpu_threads_per_process",
199
+ "num_processes",
200
+ "num_machines",
201
+ "main_process_port",
202
+ "blocks_to_swap",
203
+ "max_train_steps",
204
+ "max_train_epochs",
205
+ "max_data_loader_n_workers",
206
+ "seed",
207
+ "gradient_accumulation_steps",
208
+ "discrete_flow_shift",
209
+ "sigmoid_scale",
210
+ "min_timestep",
211
+ "max_timestep",
212
+ "learning_rate",
213
+ "max_grad_norm",
214
+ "lr_warmup_steps",
215
+ "lr_decay_steps",
216
+ "lr_scheduler_num_cycles",
217
+ "lr_scheduler_power",
218
+ "lr_scheduler_timescale",
219
+ "lr_scheduler_min_lr_ratio",
220
+ "network_dim",
221
+ "network_alpha",
222
+ "network_dropout",
223
+ "scale_weight_norms",
224
+ "sample_every_n_steps",
225
+ "sample_every_n_epochs",
226
+ "sample_width",
227
+ "sample_height",
228
+ "sample_steps",
229
+ "sample_guidance_scale",
230
+ "sample_seed",
231
+ "sample_cfg_scale",
232
+ "save_every_n_epochs",
233
+ "save_every_n_steps",
234
+ "save_last_n_epochs",
235
+ "save_last_n_steps",
236
+ "save_last_n_epochs_state",
237
+ "save_last_n_steps_state",
238
+ "ddp_timeout",
239
+ "compile_cache_size_limit",
240
+ "caching_latent_batch_size",
241
+ "caching_latent_num_workers",
242
+ "caching_teo_batch_size",
243
+ "caching_teo_num_workers",
244
+ "training_adapter_multiplier",
245
+ }
246
+
247
+ list_to_str_fields = {"optimizer_args", "lr_scheduler_args", "network_args", "base_weights", "base_weights_multiplier"}
248
+
249
+ def _quote_if_needed(s: str) -> str:
250
+ s = str(s)
251
+ if not s:
252
+ return s
253
+ if any(ch.isspace() for ch in s):
254
+ return f"\"{s}\""
255
+ return s
256
+
257
+ loaded_values = []
258
+ for key, default_value in parameters:
259
+ if key in data:
260
+ v = resolve_portable_model_value(key, data[key])
261
+ if isinstance(v, list) and key in numeric_fields:
262
+ v = v[0] if v else None
263
+ elif isinstance(v, list) and key in list_to_str_fields:
264
+ if key == "base_weights":
265
+ v = " ".join(_quote_if_needed(str(x)) for x in v)
266
+ else:
267
+ v = " ".join(str(x) for x in v)
268
+ loaded_values.append(v)
269
+ else:
270
+ loaded_values.append(resolve_portable_model_value(key, default_value))
271
+
272
+ msg = f"Loaded configuration: {os.path.basename(file_path)}"
273
+ gr.Info(msg)
274
+ return tuple([file_path, gr.update(value=msg, visible=True)] + loaded_values)
275
+
276
+
277
+ def _maybe_create_enhanced_sample_prompts_zimage(param_dict: dict, parameters: list[tuple[str, object]]) -> tuple[dict, list[tuple[str, object]]]:
278
+ sample_prompts = (param_dict.get("sample_prompts") or "").strip()
279
+ if not sample_prompts or not sample_prompts.lower().endswith(".txt"):
280
+ return param_dict, parameters
281
+ if not os.path.isfile(sample_prompts):
282
+ return param_dict, parameters
283
+ if bool(param_dict.get("disable_prompt_enhancement", False)):
284
+ log.info("Z-Image prompt enhancement disabled; using original sample prompt file.")
285
+ return param_dict, parameters
286
+
287
+ output_dir = (param_dict.get("output_dir") or "").strip()
288
+ if not output_dir:
289
+ return param_dict, parameters
290
+
291
+ sample_out_dir = (param_dict.get("sample_output_dir") or "").strip() or output_dir
292
+ os.makedirs(sample_out_dir, exist_ok=True)
293
+
294
+ width = int(param_dict.get("sample_width") or 1024)
295
+ height = int(param_dict.get("sample_height") or 1024)
296
+ steps = int(param_dict.get("sample_steps") or 25)
297
+ seed = param_dict.get("sample_seed", None)
298
+ neg = (param_dict.get("sample_negative_prompt") or "").strip()
299
+ cfg_scale = float(param_dict.get("sample_cfg_scale") or 4.0)
300
+
301
+ def has_flag(s: str, flag: str) -> bool:
302
+ return re.search(rf"(?<!\S)--{re.escape(flag)}(?:\s+|=)", s, flags=re.IGNORECASE) is not None
303
+ def get_flag_value(s: str, flag: str):
304
+ m = re.search(rf"(?<!\S)--{re.escape(flag)}(?:\s+|=)([^\s]+)", s, flags=re.IGNORECASE)
305
+ return m.group(1) if m else None
306
+
307
+ enhanced_lines = []
308
+ with open(sample_prompts, "r", encoding="utf-8") as f:
309
+ for raw in f.readlines():
310
+ line = raw.rstrip("\n")
311
+ stripped = line.strip()
312
+ if not stripped or stripped.startswith("#"):
313
+ enhanced_lines.append(line)
314
+ continue
315
+
316
+ s = stripped
317
+ # Normalize common short/equals forms to canonical Kohya-style options that musubi parses.
318
+ s = re.sub(r"(?<!\S)-(?P<flag>fs|w|h|s|d|l|n|g)(?=\s|=)", r"--\g<flag>", s, flags=re.IGNORECASE)
319
+ s = re.sub(r"(?<!\S)--(?P<flag>fs|w|h|s|d|l|n|g)=(?P<value>[^\s]+)", r"--\g<flag> \g<value>", s, flags=re.IGNORECASE)
320
+ if not has_flag(s, "w"):
321
+ s += f" --w {width}"
322
+ if not has_flag(s, "h"):
323
+ s += f" --h {height}"
324
+ if not has_flag(s, "s"):
325
+ s += f" --s {steps}"
326
+ if seed is not None and int(seed) >= 0 and not has_flag(s, "d"):
327
+ s += f" --d {int(seed)}"
328
+
329
+ # Z-Image training samples are controlled by cfg_scale (`--l`).
330
+ # Mirror legacy `--g` into `--l` when `--l` is missing.
331
+ has_cfg_scale = has_flag(s, "l")
332
+ has_guidance = has_flag(s, "g")
333
+ if has_guidance and not has_cfg_scale:
334
+ g_val = get_flag_value(s, "g")
335
+ if g_val is not None:
336
+ s += f" --l {g_val}"
337
+ has_cfg_scale = True
338
+
339
+ if not has_cfg_scale:
340
+ s += f" --l {cfg_scale}"
341
+ if neg and not has_flag(s, "n"):
342
+ s += f" --n {neg}"
343
+
344
+ enhanced_lines.append(s)
345
+
346
+ ts = datetime.now().strftime("%Y%m%d-%H%M%S")
347
+ out_name = (param_dict.get("output_name") or "zimage").strip() or "zimage"
348
+ enhanced_path = os.path.join(sample_out_dir, f"{out_name}_enhanced_prompts_{ts}.txt")
349
+ with open(enhanced_path, "w", encoding="utf-8") as f:
350
+ f.write("# Enhanced prompt file generated by SECourses Musubi Trainer\n")
351
+ f.write(f"# Original file: {sample_prompts}\n\n")
352
+ for l in enhanced_lines:
353
+ f.write(l + "\n")
354
+
355
+ param_dict["sample_prompts"] = enhanced_path
356
+ parameters = [(k, (enhanced_path if k == "sample_prompts" else v)) for k, v in parameters]
357
+ return param_dict, parameters
358
+
359
+
360
+ def train_zimage_model(headless: bool, print_only: bool, parameters):
361
+ global train_state_value
362
+
363
+ python_cmd = sys.executable
364
+ run_cmd = _find_accelerate_launch(python_cmd)
365
+
366
+ param_dict, parameters, full_finetune = normalize_image_training_parameters(parameters)
367
+
368
+ def _strip_matching_quotes(s: str) -> str:
369
+ if len(s) >= 2 and ((s[0] == s[-1] == '"') or (s[0] == s[-1] == "'")):
370
+ return s[1:-1]
371
+ return s
372
+
373
+ def _split_cli_args_windows(value: str) -> list[str]:
374
+ if not value or not value.strip():
375
+ return []
376
+ try:
377
+ parts = shlex.split(value, posix=False)
378
+ except Exception:
379
+ parts = value.replace(",", " ").split()
380
+ cleaned: list[str] = []
381
+ for p in parts:
382
+ p = _strip_matching_quotes(p.strip().strip(",").strip())
383
+ if p:
384
+ cleaned.append(p)
385
+ return cleaned
386
+
387
+ def _coerce_str_list(value: object) -> list[str]:
388
+ if value is None:
389
+ return []
390
+ if isinstance(value, list):
391
+ return [str(v) for v in value if v is not None and str(v).strip()]
392
+ if isinstance(value, str):
393
+ return _split_cli_args_windows(value)
394
+ return [str(value)]
395
+
396
+ def _coerce_float_list(value: object) -> list[float]:
397
+ if value is None:
398
+ return []
399
+ if isinstance(value, list):
400
+ out: list[float] = []
401
+ for v in value:
402
+ if v is None:
403
+ continue
404
+ try:
405
+ out.append(float(v))
406
+ except Exception:
407
+ continue
408
+ return out
409
+ if isinstance(value, (int, float)):
410
+ return [float(value)]
411
+ if isinstance(value, str):
412
+ out: list[float] = []
413
+ for tok in _split_cli_args_windows(value):
414
+ try:
415
+ out.append(float(tok))
416
+ except Exception:
417
+ continue
418
+ return out
419
+ return []
420
+
421
+ training_mode = (param_dict.get("training_mode") or "LoRA Training").strip()
422
+ validate_block_swap_options(param_dict, lora_training=not full_finetune)
423
+
424
+ # Prefer generated dataset config when using folder mode.
425
+ dataset_config_mode = (param_dict.get("dataset_config_mode") or "").strip()
426
+ if dataset_config_mode == "Generate from Folder Structure":
427
+ gen_path = (param_dict.get("generated_toml_path") or "").strip()
428
+ if gen_path:
429
+ param_dict["dataset_config"] = gen_path
430
+ parameters = [(k, (gen_path if k == "dataset_config" else v)) for k, v in parameters]
431
+
432
+ dataset_config = (param_dict.get("dataset_config") or "").strip()
433
+ if not dataset_config:
434
+ raise ValueError("[ERROR] Dataset config is required. Generate a dataset TOML or set dataset_config.")
435
+ if not os.path.exists(dataset_config):
436
+ raise ValueError(f"[ERROR] Dataset config file does not exist: {dataset_config}")
437
+
438
+ dit_path = (param_dict.get("dit") or "").strip()
439
+ vae_path = (param_dict.get("vae") or "").strip()
440
+ te_path = (param_dict.get("text_encoder") or "").strip()
441
+
442
+ if not dit_path or not os.path.exists(dit_path):
443
+ raise ValueError("[ERROR] DiT checkpoint path is required and must exist.")
444
+ if not vae_path or not os.path.exists(vae_path):
445
+ raise ValueError("[ERROR] VAE checkpoint path is required and must exist.")
446
+ if not te_path or not os.path.exists(te_path):
447
+ raise ValueError("[ERROR] Text Encoder checkpoint path is required and must exist.")
448
+
449
+ output_dir = (param_dict.get("output_dir") or "").strip()
450
+ output_name = (param_dict.get("output_name") or "").strip()
451
+ if not output_dir:
452
+ raise ValueError("[ERROR] Output directory is required.")
453
+ if not output_name:
454
+ raise ValueError("[ERROR] Output name is required.")
455
+
456
+ # Z-Image Turbo training adapter / LoRA adapter support:
457
+ # - Use the GUI field to populate base_weights (+ multiplier) so musubi-tuner receives --base_weights correctly.
458
+ # - Also normalize any user-entered base_weights/base_weights_multiplier to lists (argparse expects nargs='*').
459
+ base_weights_list = _coerce_str_list(param_dict.get("base_weights"))
460
+ base_weights_multiplier_list = _coerce_float_list(param_dict.get("base_weights_multiplier"))
461
+
462
+ training_adapter_path = (param_dict.get("training_adapter_path") or "").strip()
463
+ training_adapter_multiplier = float(param_dict.get("training_adapter_multiplier") or 1.0)
464
+ if training_adapter_path:
465
+ if not os.path.exists(training_adapter_path):
466
+ raise ValueError(f"[ERROR] Training adapter path does not exist: {training_adapter_path}")
467
+ if training_adapter_path not in base_weights_list:
468
+ base_weights_list.append(training_adapter_path)
469
+ adapter_idx = base_weights_list.index(training_adapter_path)
470
+ if len(base_weights_multiplier_list) <= adapter_idx:
471
+ base_weights_multiplier_list.extend([1.0] * (adapter_idx + 1 - len(base_weights_multiplier_list)))
472
+ base_weights_multiplier_list[adapter_idx] = training_adapter_multiplier
473
+
474
+ # Update parameter list with normalized values (lists), so config TOML is compatible with nargs='*'.
475
+ if base_weights_list:
476
+ param_dict["base_weights"] = base_weights_list
477
+ parameters = [(k, (base_weights_list if k == "base_weights" else v)) for k, v in parameters]
478
+ else:
479
+ param_dict["base_weights"] = None
480
+ parameters = [(k, (None if k == "base_weights" else v)) for k, v in parameters]
481
+
482
+ if base_weights_multiplier_list:
483
+ param_dict["base_weights_multiplier"] = base_weights_multiplier_list
484
+ parameters = [(k, (base_weights_multiplier_list if k == "base_weights_multiplier" else v)) for k, v in parameters]
485
+ else:
486
+ param_dict["base_weights_multiplier"] = None
487
+ parameters = [(k, (None if k == "base_weights_multiplier" else v)) for k, v in parameters]
488
+
489
+ # Enforce correct LoRA module for LoRA training only.
490
+ if not full_finetune:
491
+ required_network_module = "networks.lora_zimage"
492
+ if (param_dict.get("network_module") or "").strip() != required_network_module:
493
+ param_dict["network_module"] = required_network_module
494
+ parameters = [(k, (required_network_module if k == "network_module" else v)) for k, v in parameters]
495
+
496
+ # Optional pre-steps
497
+ latent_cache_cmd = None
498
+ teo_cache_cmd = None
499
+
500
+ # Match WAN tab behavior: run caching unless explicitly disabled.
501
+ if param_dict.get("caching_latent_skip_existing") is not False:
502
+ latent_cache_cmd = [
503
+ python_cmd,
504
+ f"{scriptdir}/musubi-tuner/src/musubi_tuner/zimage_cache_latents.py",
505
+ "--dataset_config",
506
+ dataset_config,
507
+ "--vae",
508
+ vae_path,
509
+ ]
510
+
511
+ caching_device = (param_dict.get("caching_latent_device") or "cuda").strip()
512
+ if caching_device == "cuda":
513
+ if (param_dict.get("gpu_ids") or "").strip():
514
+ gpu_ids = str(param_dict.get("gpu_ids")).split(",")
515
+ caching_device = f"cuda:{gpu_ids[0].strip()}"
516
+ else:
517
+ caching_device = "cuda:0"
518
+ latent_cache_cmd.extend(["--device", caching_device])
519
+
520
+ if param_dict.get("caching_latent_batch_size") is not None:
521
+ latent_cache_cmd.extend(["--batch_size", str(int(param_dict.get("caching_latent_batch_size")))])
522
+ if param_dict.get("caching_latent_num_workers") is not None:
523
+ latent_cache_cmd.extend(["--num_workers", str(int(param_dict.get("caching_latent_num_workers")))])
524
+
525
+ if bool(param_dict.get("caching_latent_skip_existing")):
526
+ latent_cache_cmd.append("--skip_existing")
527
+ if bool(param_dict.get("caching_latent_keep_cache", False)):
528
+ latent_cache_cmd.append("--keep_cache")
529
+
530
+ if param_dict.get("caching_teo_skip_existing") is not False:
531
+ teo_cache_cmd = [
532
+ python_cmd,
533
+ f"{scriptdir}/musubi-tuner/src/musubi_tuner/zimage_cache_text_encoder_outputs.py",
534
+ "--dataset_config",
535
+ dataset_config,
536
+ "--text_encoder",
537
+ te_path,
538
+ ]
539
+
540
+ if bool(param_dict.get("caching_teo_fp8_llm", False)):
541
+ teo_cache_cmd.append("--fp8_llm")
542
+
543
+ teo_device = (param_dict.get("caching_teo_device") or "cuda").strip()
544
+ if teo_device == "cuda":
545
+ if (param_dict.get("gpu_ids") or "").strip():
546
+ gpu_ids = str(param_dict.get("gpu_ids")).split(",")
547
+ teo_device = f"cuda:{gpu_ids[0].strip()}"
548
+ else:
549
+ teo_device = "cuda:0"
550
+ teo_cache_cmd.extend(["--device", teo_device])
551
+
552
+ if param_dict.get("caching_teo_batch_size") is not None:
553
+ teo_cache_cmd.extend(["--batch_size", str(int(param_dict.get("caching_teo_batch_size")))])
554
+ if param_dict.get("caching_teo_num_workers") is not None:
555
+ teo_cache_cmd.extend(["--num_workers", str(int(param_dict.get("caching_teo_num_workers")))])
556
+
557
+ if bool(param_dict.get("caching_teo_skip_existing")):
558
+ teo_cache_cmd.append("--skip_existing")
559
+ if bool(param_dict.get("caching_teo_keep_cache", False)):
560
+ teo_cache_cmd.append("--keep_cache")
561
+
562
+ # Accelerate launch flags
563
+ run_cmd = AccelerateLaunch.run_cmd(
564
+ run_cmd=run_cmd,
565
+ dynamo_backend=param_dict.get("dynamo_backend"),
566
+ dynamo_mode=param_dict.get("dynamo_mode"),
567
+ dynamo_use_fullgraph=param_dict.get("dynamo_use_fullgraph"),
568
+ dynamo_use_dynamic=param_dict.get("dynamo_use_dynamic"),
569
+ num_processes=param_dict.get("num_processes"),
570
+ num_machines=param_dict.get("num_machines"),
571
+ multi_gpu=param_dict.get("multi_gpu"),
572
+ gpu_ids=param_dict.get("gpu_ids"),
573
+ main_process_port=param_dict.get("main_process_port"),
574
+ num_cpu_threads_per_process=param_dict.get("num_cpu_threads_per_process"),
575
+ mixed_precision=param_dict.get("mixed_precision"),
576
+ extra_accelerate_launch_args=param_dict.get("extra_accelerate_launch_args"),
577
+ )
578
+
579
+ if full_finetune:
580
+ run_cmd.append(f"{scriptdir}/musubi-tuner/src/musubi_tuner/zimage_train.py")
581
+ else:
582
+ run_cmd.append(f"{scriptdir}/musubi-tuner/src/musubi_tuner/zimage_train_network.py")
583
+
584
+ if not print_only:
585
+ os.makedirs(output_dir, exist_ok=True)
586
+ formatted_datetime = datetime.now().strftime("%Y%m%d-%H%M%S")
587
+ cfg_path = os.path.join(output_dir, f"{output_name}_{formatted_datetime}.toml")
588
+
589
+ # Enhance prompt file defaults if user provided sample_prompts.
590
+ param_dict, parameters = _maybe_create_enhanced_sample_prompts_zimage(param_dict, parameters)
591
+
592
+ pattern_exclusion = [k for k, _ in parameters if k.startswith("caching_latent_") or k.startswith("caching_teo_")]
593
+
594
+ dreambooth_mode = full_finetune
595
+ exclusion_extra = []
596
+ if dreambooth_mode:
597
+ exclusion_extra.extend(
598
+ [
599
+ "network_module",
600
+ "network_dim",
601
+ "network_alpha",
602
+ "network_dropout",
603
+ "network_args",
604
+ "network_weights",
605
+ "training_comment",
606
+ "dim_from_weights",
607
+ "scale_weight_norms",
608
+ "base_weights",
609
+ "base_weights_multiplier",
610
+ "no_metadata",
611
+ ]
612
+ )
613
+ else:
614
+ # These options are implemented by zimage_train.py, not the LoRA trainer.
615
+ exclusion_extra.extend(["mem_eff_save", "fused_backward_pass"])
616
+
617
+ run_config_exclusion = [
618
+ "file_path",
619
+ "save_as",
620
+ "save_as_bool",
621
+ "headless",
622
+ "print_only",
623
+ "num_cpu_threads_per_process",
624
+ "num_processes",
625
+ "num_machines",
626
+ "multi_gpu",
627
+ "gpu_ids",
628
+ "main_process_port",
629
+ "dynamo_backend",
630
+ "dynamo_mode",
631
+ "dynamo_use_fullgraph",
632
+ "dynamo_use_dynamic",
633
+ "extra_accelerate_launch_args",
634
+ # GUI-only dataset generation fields
635
+ "dataset_config_mode",
636
+ "parent_folder_path",
637
+ "dataset_resolution_width",
638
+ "dataset_resolution_height",
639
+ "dataset_caption_extension",
640
+ "create_missing_captions",
641
+ "caption_strategy",
642
+ "dataset_batch_size",
643
+ "dataset_enable_bucket",
644
+ "dataset_bucket_no_upscale",
645
+ "dataset_cache_directory",
646
+ "generated_toml_path",
647
+ # GUI-only variant selector and prompt helper
648
+ "zimage_variant",
649
+ "sample_cfg_scale",
650
+ "disable_prompt_enhancement",
651
+ "sample_output_dir",
652
+ "sample_width",
653
+ "sample_height",
654
+ "sample_steps",
655
+ "sample_guidance_scale",
656
+ "sample_seed",
657
+ "sample_negative_prompt",
658
+ "training_mode",
659
+ "training_adapter_path",
660
+ "training_adapter_multiplier",
661
+ "additional_parameters",
662
+ "debug_mode",
663
+ # Cache-only toggle
664
+ "caching_teo_fp8_llm",
665
+ ] + pattern_exclusion + exclusion_extra + list(training_mode_runtime_exclusions(training_mode))
666
+ mandatory_keys = ["dataset_config", "dit", "vae", "text_encoder"] + (
667
+ [] if dreambooth_mode else ["network_module"]
668
+ )
669
+ if print_only:
670
+ cfg_path = save_training_preview_config(
671
+ parameters,
672
+ f"zimage_{output_name}",
673
+ run_config_exclusion,
674
+ mandatory_keys,
675
+ )
676
+ else:
677
+ SaveConfigFileToRun(
678
+ parameters=parameters,
679
+ file_path=cfg_path,
680
+ exclusion=run_config_exclusion,
681
+ mandatory_keys=mandatory_keys,
682
+ )
683
+
684
+ run_cmd.append("--config_file")
685
+ run_cmd.append(cfg_path)
686
+
687
+ additional_params = (param_dict.get("additional_parameters") or "").strip()
688
+ debug_mode_selected = (param_dict.get("debug_mode") or "None").strip()
689
+ if debug_mode_selected and debug_mode_selected != "None":
690
+ debug_params = _get_debug_parameters_for_mode(debug_mode_selected)
691
+ if debug_params:
692
+ additional_params = (additional_params + " " + debug_params).strip() if additional_params else debug_params
693
+
694
+ run_cmd = run_cmd_advanced_training(run_cmd=run_cmd, additional_parameters=additional_params)
695
+
696
+ if print_only:
697
+ if latent_cache_cmd:
698
+ print_command_and_toml(latent_cache_cmd, "")
699
+ if teo_cache_cmd:
700
+ print_command_and_toml(teo_cache_cmd, "")
701
+ print_command_and_toml(run_cmd, cfg_path)
702
+ return
703
+
704
+ # Match Qwen/WAN launch strategy:
705
+ # 1) run latent caching synchronously (so failures surface before training),
706
+ # 2) then run (optional) text-encoder caching + training via a wrapper script so Stop cancels both.
707
+ env = setup_environment(compile_requested=requires_native_compile_toolchain(param_dict))
708
+
709
+ if latent_cache_cmd:
710
+ log.info("Running latent caching...")
711
+ latent_cache_script = generate_script_content(latent_cache_cmd, "Z-Image latent caching")
712
+ save_executed_script(script_content=latent_cache_script, config_name=output_name, script_type="zimage_latent_cache")
713
+ try:
714
+ gr.Info("Starting latent caching... This may take a while.")
715
+ import subprocess
716
+
717
+ subprocess.run(latent_cache_cmd, env=setup_environment(), check=True)
718
+ gr.Info("Latent caching completed successfully!")
719
+ except subprocess.CalledProcessError as e:
720
+ log.error(f"Latent caching failed with return code {e.returncode}")
721
+ gr.Warning(f"Latent caching failed with return code {e.returncode}")
722
+ raise RuntimeError(f"Latent caching failed with return code {e.returncode}")
723
+ except FileNotFoundError:
724
+ raise RuntimeError(f"Python executable not found: {python_cmd}")
725
+
726
+ if teo_cache_cmd:
727
+ import platform
728
+ import tempfile
729
+ import subprocess
730
+
731
+ if platform.system() == "Windows":
732
+ script_ext = ".bat"
733
+ teo_cache_cmd_str = " ".join([f"\"{arg}\"" if " " in str(arg) else str(arg) for arg in teo_cache_cmd])
734
+ run_cmd_str = " ".join([f"\"{arg}\"" if " " in str(arg) else str(arg) for arg in run_cmd])
735
+ script_content = f"""@echo off
736
+ echo Starting text encoder output caching...
737
+ {teo_cache_cmd_str}
738
+ if %errorlevel% neq 0 (
739
+ echo Text encoder output caching failed with error code %errorlevel%
740
+ exit /b %errorlevel%
741
+ )
742
+ echo Text encoder output caching completed successfully.
743
+ echo Starting training...
744
+ {run_cmd_str}
745
+ """
746
+ else:
747
+ script_ext = ".sh"
748
+ teo_cache_cmd_str = shlex.join(teo_cache_cmd)
749
+ run_cmd_str = shlex.join(run_cmd)
750
+ script_content = f"""#!/bin/bash
751
+ set -e
752
+ echo "Starting text encoder output caching..."
753
+ {teo_cache_cmd_str}
754
+ echo "Text encoder output caching completed successfully."
755
+ echo "Starting training..."
756
+ {run_cmd_str}
757
+ """
758
+
759
+ with tempfile.NamedTemporaryFile(mode="w", suffix=script_ext, delete=False, encoding="utf-8") as f:
760
+ temp_script = f.name
761
+ f.write(script_content)
762
+
763
+ if platform.system() != "Windows":
764
+ import stat
765
+
766
+ os.chmod(temp_script, os.stat(temp_script).st_mode | stat.S_IEXEC)
767
+
768
+ save_executed_script(script_content=script_content, config_name=output_name, script_type="zimage")
769
+ final_cmd = [temp_script] if platform.system() == "Windows" else ["bash", temp_script]
770
+ gr.Info("Starting text encoder caching followed by training...")
771
+ executor.execute_command(run_cmd=final_cmd, env=env, shell=True if platform.system() == "Windows" else False)
772
+ else:
773
+ training_script = generate_script_content(run_cmd, "Z-Image training")
774
+ save_executed_script(script_content=training_script, config_name=output_name, script_type="zimage")
775
+ gr.Info("Starting training...")
776
+ executor.execute_command(run_cmd=run_cmd, env=env)
777
+
778
+ train_state_value = time.time()
779
+ return (
780
+ gr.Button(visible=False or headless),
781
+ gr.Row(visible=True),
782
+ gr.Button(interactive=True),
783
+ gr.Textbox(value="Training in progress..."),
784
+ gr.Textbox(value=train_state_value),
785
+ )
786
+
787
+
788
+ ZIMAGE_PARAM_KEYS = [
789
+ # accelerate_launch
790
+ "mixed_precision",
791
+ "num_cpu_threads_per_process",
792
+ "num_processes",
793
+ "num_machines",
794
+ "multi_gpu",
795
+ "gpu_ids",
796
+ "main_process_port",
797
+ "dynamo_backend",
798
+ "dynamo_mode",
799
+ "dynamo_use_fullgraph",
800
+ "dynamo_use_dynamic",
801
+ "extra_accelerate_launch_args",
802
+ # advanced_training
803
+ "additional_parameters",
804
+ "debug_mode",
805
+ # dataset
806
+ "dataset_config_mode",
807
+ "dataset_config",
808
+ "parent_folder_path",
809
+ "dataset_resolution_width",
810
+ "dataset_resolution_height",
811
+ "dataset_caption_extension",
812
+ "create_missing_captions",
813
+ "caption_strategy",
814
+ "dataset_batch_size",
815
+ "dataset_enable_bucket",
816
+ "dataset_bucket_no_upscale",
817
+ "dataset_cache_directory",
818
+ "generated_toml_path",
819
+ # gui-only model selector
820
+ "training_mode",
821
+ "zimage_variant",
822
+ "training_adapter_path",
823
+ "training_adapter_multiplier",
824
+ # model
825
+ "dit",
826
+ "vae",
827
+ "text_encoder",
828
+ "fp8_base",
829
+ "fp8_scaled",
830
+ "fp8_llm",
831
+ "disable_numpy_memmap",
832
+ "blocks_to_swap",
833
+ "use_pinned_memory_for_block_swap",
834
+ "block_swap_h2d_only",
835
+ "block_swap_ring_size",
836
+ "img_in_txt_in_offloading",
837
+ # torch compile
838
+ "compile",
839
+ "compile_backend",
840
+ "compile_mode",
841
+ "compile_dynamic",
842
+ "compile_fullgraph",
843
+ "compile_cache_size_limit",
844
+ # schedule
845
+ "timestep_sampling",
846
+ "weighting_scheme",
847
+ "discrete_flow_shift",
848
+ "sigmoid_scale",
849
+ "min_timestep",
850
+ "max_timestep",
851
+ # training settings
852
+ "sdpa",
853
+ "flash_attn",
854
+ "sage_attn",
855
+ "xformers",
856
+ "split_attn",
857
+ "use_legacy_sdpa",
858
+ "max_train_steps",
859
+ "max_train_epochs",
860
+ "max_data_loader_n_workers",
861
+ "persistent_data_loader_workers",
862
+ "seed",
863
+ "gradient_checkpointing",
864
+ "gradient_checkpointing_cpu_offload",
865
+ "gradient_accumulation_steps",
866
+ "full_bf16",
867
+ "full_fp16",
868
+ "logging_dir",
869
+ "log_with",
870
+ "log_prefix",
871
+ "log_tracker_name",
872
+ "wandb_run_name",
873
+ "log_tracker_config",
874
+ "wandb_api_key",
875
+ "log_config",
876
+ "ddp_timeout",
877
+ "ddp_gradient_as_bucket_view",
878
+ "ddp_static_graph",
879
+ # samples
880
+ "sample_every_n_steps",
881
+ "sample_every_n_epochs",
882
+ "sample_at_first",
883
+ "sample_prompts",
884
+ "disable_prompt_enhancement",
885
+ "sample_output_dir",
886
+ "sample_width",
887
+ "sample_height",
888
+ "sample_steps",
889
+ "sample_guidance_scale",
890
+ "sample_seed",
891
+ "sample_negative_prompt",
892
+ "sample_cfg_scale",
893
+ # caching
894
+ "caching_latent_device",
895
+ "caching_latent_batch_size",
896
+ "caching_latent_num_workers",
897
+ "caching_latent_skip_existing",
898
+ "caching_latent_keep_cache",
899
+ "caching_teo_device",
900
+ "caching_teo_batch_size",
901
+ "caching_teo_num_workers",
902
+ "caching_teo_skip_existing",
903
+ "caching_teo_keep_cache",
904
+ "caching_teo_fp8_llm",
905
+ # optimizer/scheduler
906
+ "optimizer_type",
907
+ "optimizer_args",
908
+ "learning_rate",
909
+ "max_grad_norm",
910
+ "fused_backward_pass",
911
+ "lr_scheduler",
912
+ "lr_warmup_steps",
913
+ "lr_decay_steps",
914
+ "lr_scheduler_num_cycles",
915
+ "lr_scheduler_power",
916
+ "lr_scheduler_timescale",
917
+ "lr_scheduler_min_lr_ratio",
918
+ "lr_scheduler_type",
919
+ "lr_scheduler_args",
920
+ # network
921
+ "no_metadata",
922
+ "network_weights",
923
+ "network_module",
924
+ "network_dim",
925
+ "network_alpha",
926
+ "network_dropout",
927
+ "network_args",
928
+ "training_comment",
929
+ "dim_from_weights",
930
+ "scale_weight_norms",
931
+ "base_weights",
932
+ "base_weights_multiplier",
933
+ # save/load
934
+ "output_dir",
935
+ "output_name",
936
+ "resume",
937
+ "save_precision",
938
+ "save_every_n_epochs",
939
+ "save_last_n_epochs",
940
+ "save_every_n_steps",
941
+ "save_last_n_steps",
942
+ "save_last_n_epochs_state",
943
+ "save_last_n_steps_state",
944
+ "save_state",
945
+ "save_state_on_train_end",
946
+ "mem_eff_save",
947
+ # metadata
948
+ "metadata_author",
949
+ "metadata_description",
950
+ "metadata_license",
951
+ "metadata_tags",
952
+ "metadata_title",
953
+ "metadata_reso",
954
+ "metadata_arch",
955
+ # huggingface
956
+ "huggingface_repo_id",
957
+ "huggingface_token",
958
+ "huggingface_repo_type",
959
+ "huggingface_repo_visibility",
960
+ "huggingface_path_in_repo",
961
+ "save_state_to_huggingface",
962
+ "resume_from_huggingface",
963
+ "async_upload",
964
+ ]
965
+
966
+
967
+ def zimage_gui_actions(action: str, ask_for_file: bool, config_file_name: str, headless: bool, print_only: bool, *args):
968
+ if action == "open_configuration":
969
+ return open_zimage_configuration(ask_for_file, config_file_name, list(zip(ZIMAGE_PARAM_KEYS, args)))
970
+ if action == "save_configuration":
971
+ return save_zimage_configuration(ask_for_file, config_file_name, list(zip(ZIMAGE_PARAM_KEYS, args)))
972
+ if action == "train_model":
973
+ return train_zimage_model(headless=headless, print_only=print_only, parameters=list(zip(ZIMAGE_PARAM_KEYS, args)))
974
+
975
+
976
+ def zimage_lora_tab(headless=False, config: GUIConfig = {}):
977
+ global executor
978
+
979
+ dummy_true = gr.Checkbox(value=True, visible=False)
980
+ dummy_false = gr.Checkbox(value=False, visible=False)
981
+ dummy_headless = gr.Checkbox(value=headless, visible=False)
982
+
983
+ defaults = {
984
+ "training_mode": "LoRA Training",
985
+ "zimage_variant": "base",
986
+ "training_adapter_path": "",
987
+ "training_adapter_multiplier": 1.0,
988
+ "network_module": "networks.lora_zimage",
989
+ "output_name": "my-zimage-lora",
990
+ # Torch compile defaults
991
+ "compile": False,
992
+ "compile_backend": "inductor",
993
+ "compile_mode": "default",
994
+ "compile_dynamic": "auto",
995
+ "compile_fullgraph": False,
996
+ "compile_cache_size_limit": 0,
997
+ "mixed_precision": "bf16",
998
+ "num_cpu_threads_per_process": 1,
999
+ "sdpa": True,
1000
+ "optimizer_type": "adamw8bit",
1001
+ "learning_rate": 1e-4,
1002
+ "fused_backward_pass": False,
1003
+ "gradient_checkpointing": True,
1004
+ "timestep_sampling": "shift",
1005
+ "weighting_scheme": "none",
1006
+ "discrete_flow_shift": 2.0,
1007
+ "dataset_config_mode": "Generate from Folder Structure",
1008
+ "dataset_resolution_width": 1024,
1009
+ "dataset_resolution_height": 1024,
1010
+ "dataset_enable_bucket": True,
1011
+ "dataset_cache_directory": "cache_dir",
1012
+ # Caching defaults
1013
+ "caching_latent_device": "cuda",
1014
+ "caching_latent_batch_size": 1,
1015
+ "caching_latent_num_workers": 2,
1016
+ "caching_latent_skip_existing": True,
1017
+ "caching_latent_keep_cache": True,
1018
+ "caching_teo_device": "cuda",
1019
+ "caching_teo_batch_size": 8,
1020
+ "caching_teo_num_workers": 2,
1021
+ "caching_teo_skip_existing": True,
1022
+ "caching_teo_keep_cache": True,
1023
+ "caching_teo_fp8_llm": False,
1024
+ # Samples
1025
+ "disable_prompt_enhancement": False,
1026
+ "sample_width": 1024,
1027
+ "sample_height": 1024,
1028
+ "sample_steps": 25,
1029
+ "sample_cfg_scale": 4.0,
1030
+ }
1031
+
1032
+ if isinstance(config, dict):
1033
+ config.update({k: v for k, v in defaults.items() if k not in config})
1034
+ config = type("GUIConfig", (), {"config": config, "get": config.get})()
1035
+ elif hasattr(config, "config"):
1036
+ if not getattr(config, "config", None):
1037
+ config.config = defaults.copy()
1038
+ else:
1039
+ config.config.update({k: v for k, v in defaults.items() if k not in config.config})
1040
+
1041
+ with gr.Accordion("Configuration file Settings", open=True):
1042
+ configuration = ConfigurationFile(headless=headless, config=config)
1043
+
1044
+ # Add search functionality and unified toggle button
1045
+ with gr.Row():
1046
+ with gr.Column(scale=2):
1047
+ search_input = gr.Textbox(
1048
+ label="🔍 Search Settings",
1049
+ placeholder="Type to search and filter panels (e.g., 'model', 'learning', 'fp8', 'cache', 'epochs')",
1050
+ lines=1,
1051
+ interactive=True,
1052
+ info="Filter settings panels by keyword.",
1053
+ )
1054
+ with gr.Column(scale=1):
1055
+ toggle_all_btn = gr.Button(
1056
+ value="Open All Panels",
1057
+ variant="secondary",
1058
+ size="lg",
1059
+ elem_id="toggle-all-btn"
1060
+ )
1061
+ # Hidden state to track if panels are open or closed
1062
+ panels_state = gr.State(value="closed") # Default state is closed
1063
+
1064
+ # Hidden elements for search functionality (not displayed)
1065
+ search_results_row = gr.Row(visible=False)
1066
+ search_results = gr.HTML(visible=False)
1067
+
1068
+ # Create accordion references
1069
+ accordions = []
1070
+
1071
+ accelerate_accordion = gr.Accordion("Accelerate launch Settings", open=False, elem_classes="flux1_background")
1072
+ accordions.append(accelerate_accordion)
1073
+ with accelerate_accordion:
1074
+ accelerate_launch = AccelerateLaunch(config=config)
1075
+
1076
+ save_load_accordion = gr.Accordion("Save Models and Resume Training Settings", open=False, elem_classes="samples_background")
1077
+ accordions.append(save_load_accordion)
1078
+ with save_load_accordion:
1079
+ save_load = SaveLoadSettings(headless=headless, config=config)
1080
+
1081
+ dataset_accordion = gr.Accordion("Z-Image Training Dataset", open=False, elem_classes="samples_background")
1082
+ accordions.append(dataset_accordion)
1083
+ with dataset_accordion:
1084
+ with gr.Row():
1085
+ dataset_config_mode = gr.Radio(
1086
+ label="Dataset Configuration Method",
1087
+ choices=["Use TOML File", "Generate from Folder Structure"],
1088
+ value=config.get("dataset_config_mode", "Generate from Folder Structure"),
1089
+ info="Choose how to configure your dataset: provide a TOML file or auto-generate from folder structure",
1090
+ )
1091
+
1092
+ def _toggle_dataset_mode(mode):
1093
+ toml_visible = mode == "Use TOML File"
1094
+ folder_visible = mode == "Generate from Folder Structure"
1095
+ return gr.Row(visible=toml_visible), gr.Column(visible=folder_visible)
1096
+
1097
+ with gr.Row(
1098
+ visible=config.get("dataset_config_mode", "Generate from Folder Structure") == "Use TOML File"
1099
+ ) as toml_mode_row:
1100
+ dataset_config = gr.Textbox(
1101
+ label="dataset_config",
1102
+ value=config.get("dataset_config", ""),
1103
+ interactive=True,
1104
+ info="Path to dataset TOML used by caching and training.",
1105
+ )
1106
+ dataset_config_btn = gr.Button("📁", size="lg", visible=not headless)
1107
+ dataset_config_btn.click(
1108
+ fn=lambda: get_file_path(file_path="", default_extension=".toml", extension_name="TOML files"),
1109
+ outputs=[dataset_config],
1110
+ )
1111
+
1112
+ with gr.Column(
1113
+ visible=config.get("dataset_config_mode", "Generate from Folder Structure") == "Generate from Folder Structure"
1114
+ ) as folder_mode_column:
1115
+ with gr.Row():
1116
+ parent_folder_path = gr.Textbox(
1117
+ label="parent_folder_path",
1118
+ value=config.get("parent_folder_path", ""),
1119
+ interactive=True,
1120
+ info="Parent folder used to generate a dataset TOML (only in Generate mode).",
1121
+ )
1122
+ parent_folder_btn = gr.Button("📂", size="lg", visible=not headless)
1123
+ parent_folder_btn.click(fn=lambda: get_folder_path(folder_path=""), outputs=[parent_folder_path])
1124
+
1125
+ with gr.Row():
1126
+ dataset_resolution_width = gr.Number(
1127
+ label="dataset_resolution_width",
1128
+ value=config.get("dataset_resolution_width", 1024),
1129
+ step=8,
1130
+ interactive=True,
1131
+ info="Target dataset width in pixels (multiples of 8 recommended).",
1132
+ )
1133
+ dataset_resolution_height = gr.Number(
1134
+ label="dataset_resolution_height",
1135
+ value=config.get("dataset_resolution_height", 1024),
1136
+ step=8,
1137
+ interactive=True,
1138
+ info="Target dataset height in pixels (multiples of 8 recommended).",
1139
+ )
1140
+
1141
+ with gr.Row():
1142
+ dataset_caption_extension = gr.Textbox(
1143
+ label="dataset_caption_extension",
1144
+ value=config.get("dataset_caption_extension", ".txt"),
1145
+ interactive=True,
1146
+ info="Caption file extension to read/write (e.g., .txt).",
1147
+ )
1148
+ create_missing_captions = gr.Checkbox(
1149
+ label="create_missing_captions",
1150
+ value=bool(config.get("create_missing_captions", True)),
1151
+ info="Create empty captions when missing during TOML generation.",
1152
+ )
1153
+ caption_strategy = gr.Dropdown(
1154
+ label="caption_strategy",
1155
+ choices=["folder_name", "empty"],
1156
+ value=config.get("caption_strategy", "folder_name"),
1157
+ interactive=True,
1158
+ info="folder_name uses the folder name as caption; empty writes blank captions.",
1159
+ )
1160
+
1161
+ with gr.Row():
1162
+ dataset_batch_size = gr.Number(
1163
+ label="dataset_batch_size",
1164
+ value=config.get("dataset_batch_size", 1),
1165
+ minimum=1,
1166
+ step=1,
1167
+ interactive=True,
1168
+ info="Batch size recorded in the dataset config.",
1169
+ )
1170
+ dataset_enable_bucket = gr.Checkbox(
1171
+ label="dataset_enable_bucket",
1172
+ value=bool(config.get("dataset_enable_bucket", True)),
1173
+ info="Enable resolution bucketing in the dataset config.",
1174
+ )
1175
+ dataset_bucket_no_upscale = gr.Checkbox(
1176
+ label="dataset_bucket_no_upscale",
1177
+ value=bool(config.get("dataset_bucket_no_upscale", False)),
1178
+ info="Do not upscale smaller images when bucketing.",
1179
+ )
1180
+
1181
+ with gr.Row():
1182
+ dataset_cache_directory = gr.Textbox(
1183
+ label="dataset_cache_directory",
1184
+ value=config.get("dataset_cache_directory", "cache_dir"),
1185
+ interactive=True,
1186
+ info="Cache directory name for latent/text encoder outputs.",
1187
+ )
1188
+ generated_toml_path = gr.Textbox(
1189
+ label="generated_toml_path",
1190
+ value=config.get("generated_toml_path", ""),
1191
+ interactive=False,
1192
+ info="Read-only: path of the generated dataset TOML.",
1193
+ )
1194
+
1195
+ with gr.Row():
1196
+ dataset_status = gr.Textbox(label="Dataset status", value="", interactive=False, info="Validation and status messages.")
1197
+
1198
+ with gr.Row():
1199
+ generate_toml_btn = gr.Button("Generate dataset TOML", variant="primary")
1200
+ generate_toml_btn.click(
1201
+ fn=_generate_zimage_dataset_toml,
1202
+ inputs=[
1203
+ parent_folder_path,
1204
+ dataset_resolution_width,
1205
+ dataset_resolution_height,
1206
+ dataset_caption_extension,
1207
+ create_missing_captions,
1208
+ caption_strategy,
1209
+ dataset_batch_size,
1210
+ dataset_enable_bucket,
1211
+ dataset_bucket_no_upscale,
1212
+ dataset_cache_directory,
1213
+ save_load.output_dir,
1214
+ ],
1215
+ outputs=[dataset_config, generated_toml_path, dataset_status],
1216
+ )
1217
+
1218
+ dataset_config_mode.change(
1219
+ fn=_toggle_dataset_mode,
1220
+ inputs=[dataset_config_mode],
1221
+ outputs=[toml_mode_row, folder_mode_column],
1222
+ )
1223
+
1224
+ model_accordion = gr.Accordion("Z-Image Model Settings", open=False, elem_classes="preset_background")
1225
+ accordions.append(model_accordion)
1226
+ with model_accordion:
1227
+ with gr.Row():
1228
+ training_mode = gr.Radio(
1229
+ label="Training Mode",
1230
+ choices=["LoRA Training", "DreamBooth Fine-Tuning"],
1231
+ value=config.get("training_mode", "LoRA Training"),
1232
+ info="LoRA: parameter-efficient. DreamBooth: full fine-tuning (more VRAM).",
1233
+ )
1234
+ with gr.Row():
1235
+ zimage_variant = gr.Dropdown(
1236
+ label="zimage_variant",
1237
+ choices=[("Base", "base"), ("Turbo", "turbo")],
1238
+ value=config.get("zimage_variant", "base"),
1239
+ interactive=True,
1240
+ info="Select Base vs Turbo defaults (your actual DiT checkpoint decides what you train).",
1241
+ )
1242
+ with gr.Row():
1243
+ training_adapter_path = gr.Textbox(
1244
+ label="training_adapter_path",
1245
+ value=config.get("training_adapter_path", ""),
1246
+ placeholder="Optional: zimage_turbo_training_adapter_*.safetensors",
1247
+ interactive=True,
1248
+ info="Optional Turbo Training Adapter (LoRA). If set, it is passed as base_weights (--base_weights).",
1249
+ )
1250
+ adapter_btn = gr.Button("📁", size="lg", visible=not headless)
1251
+ adapter_btn.click(fn=lambda: get_file_path(file_path="", default_extension=".safetensors", extension_name="Model files"), outputs=[training_adapter_path])
1252
+ training_adapter_multiplier = gr.Number(
1253
+ label="training_adapter_multiplier",
1254
+ value=float(config.get("training_adapter_multiplier", 1.0) or 1.0),
1255
+ step=0.1,
1256
+ interactive=True,
1257
+ info="Strength multiplier for the training adapter when merged as base_weights (1.0 = full strength).",
1258
+ )
1259
+ with gr.Row():
1260
+ dit = gr.Textbox(
1261
+ label="DiT (Base Model) Checkpoint Path",
1262
+ value=config.get("dit", ""),
1263
+ placeholder="Path to DiT base model checkpoint (Z_Image_BF16.safetensors)",
1264
+ interactive=True,
1265
+ info="Required DiT checkpoint. Examples: Z_Image_BF16.safetensors or Z_Image_Turbo_BF16.safetensors.",
1266
+ )
1267
+ dit_btn = gr.Button("📁", size="lg", visible=not headless)
1268
+ dit_btn.click(fn=lambda: get_file_path(file_path="", default_extension=".safetensors", extension_name="Model files"), outputs=[dit])
1269
+ with gr.Row():
1270
+ vae = gr.Textbox(
1271
+ label="vae",
1272
+ value=config.get("vae", ""),
1273
+ placeholder="Example: Z_Image_Train_VAE.safetensors",
1274
+ interactive=True,
1275
+ info="Required VAE checkpoint (e.g., Z_Image_Train_VAE.safetensors).",
1276
+ )
1277
+ vae_btn = gr.Button("📁", size="lg", visible=not headless)
1278
+ vae_btn.click(fn=lambda: get_file_path(file_path="", default_extension=".safetensors", extension_name="Model files"), outputs=[vae])
1279
+ with gr.Row():
1280
+ text_encoder = gr.Textbox(
1281
+ label="text_encoder",
1282
+ value=config.get("text_encoder", ""),
1283
+ placeholder="Example: qwen_3_8b.safetensors",
1284
+ interactive=True,
1285
+ info="Required Qwen3 text encoder (Z_Image_Training_Text_Encoder.safetensors).",
1286
+ )
1287
+ te_btn = gr.Button("📁", size="lg", visible=not headless)
1288
+ te_btn.click(fn=lambda: get_file_path(file_path="", default_extension=".safetensors", extension_name="Model files"), outputs=[text_encoder])
1289
+ with gr.Row():
1290
+ fp8_base = gr.Checkbox(
1291
+ label="fp8_base",
1292
+ value=bool(config.get("fp8_base", False)),
1293
+ info="Use FP8 for the base model (DiT) to reduce VRAM.",
1294
+ )
1295
+ fp8_scaled = gr.Checkbox(
1296
+ label="fp8_scaled",
1297
+ value=bool(config.get("fp8_scaled", False)),
1298
+ info="Use scaled FP8 for the base model (recommended with fp8_base).",
1299
+ )
1300
+ fp8_llm = gr.Checkbox(
1301
+ label="fp8_llm",
1302
+ value=bool(config.get("fp8_llm", False)),
1303
+ info="Use FP8 for the Qwen3 text encoder during training.",
1304
+ )
1305
+ with gr.Row():
1306
+ disable_numpy_memmap = gr.Checkbox(
1307
+ label="disable_numpy_memmap",
1308
+ value=bool(config.get("disable_numpy_memmap", False)),
1309
+ info="Disable numpy memmap when loading weights (uses more RAM but can avoid mmap issues).",
1310
+ )
1311
+ blocks_to_swap = gr.Number(
1312
+ label="blocks_to_swap",
1313
+ value=config.get("blocks_to_swap", 0),
1314
+ minimum=0,
1315
+ maximum=28,
1316
+ step=1,
1317
+ interactive=True,
1318
+ info="Offload N transformer blocks to CPU for VRAM savings. Maximum 28.",
1319
+ )
1320
+ use_pinned_memory_for_block_swap = gr.Checkbox(
1321
+ label="use_pinned_memory_for_block_swap",
1322
+ value=bool(config.get("use_pinned_memory_for_block_swap", False)),
1323
+ info="Use pinned memory for faster CPU<->GPU transfers (uses more shared memory on Windows).",
1324
+ )
1325
+ block_swap_h2d_only = gr.Checkbox(
1326
+ label="block_swap_h2d_only",
1327
+ value=bool(config.get("block_swap_h2d_only", False)),
1328
+ info="LoRA only. Stream frozen blocks host-to-device without copying them back. Requires blocks_to_swap > 0 and gradient checkpointing.",
1329
+ )
1330
+ block_swap_ring_size = gr.Number(
1331
+ label="block_swap_ring_size",
1332
+ value=config.get("block_swap_ring_size", 2),
1333
+ minimum=1,
1334
+ step=1,
1335
+ interactive=True,
1336
+ info="GPU buffers used by H2D-only block swap. 2 overlaps transfer and compute; 1 minimizes VRAM.",
1337
+ )
1338
+ img_in_txt_in_offloading = gr.Checkbox(
1339
+ label="img_in_txt_in_offloading",
1340
+ value=bool(config.get("img_in_txt_in_offloading", False)),
1341
+ info="Offload img_in and txt_in tensors to CPU to reduce VRAM.",
1342
+ )
1343
+
1344
+ torch_compile_accordion = gr.Accordion("Torch Compile Settings", open=False)
1345
+ accordions.append(torch_compile_accordion)
1346
+ with torch_compile_accordion:
1347
+ gr.Markdown(
1348
+ """⚠️ **Important:** If you get errors with torch.compile just disable it. It can increase speed and slightly reduce VRAM with no quality loss."""
1349
+ )
1350
+
1351
+ with gr.Row():
1352
+ compile = gr.Checkbox(
1353
+ label="Enable torch.compile",
1354
+ info="Enable torch.compile for faster training (requires PyTorch 2.1+, Triton for CUDA). Disable gradient checkpointing for best results!",
1355
+ value=bool(config.get("compile", False)),
1356
+ interactive=True,
1357
+ )
1358
+ compile_backend = gr.Dropdown(
1359
+ label="Compile Backend",
1360
+ info="Backend for torch.compile (default: inductor)",
1361
+ choices=["inductor", "cudagraphs", "eager", "aot_eager", "aot_ts_nvfuser"],
1362
+ value=config.get("compile_backend", "inductor"),
1363
+ interactive=True,
1364
+ )
1365
+ compile_mode = gr.Dropdown(
1366
+ label="Compile Mode",
1367
+ info="Optimization mode for torch.compile",
1368
+ choices=["default", "reduce-overhead", "max-autotune", "max-autotune-no-cudagraphs"],
1369
+ value=config.get("compile_mode", "default"),
1370
+ interactive=True,
1371
+ )
1372
+
1373
+ with gr.Row():
1374
+ compile_dynamic = gr.Dropdown(
1375
+ label="Dynamic Shapes",
1376
+ info="Dynamic shape handling: auto (default), true (enable), false (disable)",
1377
+ choices=["auto", "true", "false"],
1378
+ value=config.get("compile_dynamic", "auto"),
1379
+ allow_custom_value=False,
1380
+ interactive=True,
1381
+ )
1382
+ compile_fullgraph = gr.Checkbox(
1383
+ label="Fullgraph Mode",
1384
+ info="Enable fullgraph mode in torch.compile (may fail with complex models)",
1385
+ value=bool(config.get("compile_fullgraph", False)),
1386
+ interactive=True,
1387
+ )
1388
+ compile_cache_size_limit = gr.Number(
1389
+ label="Cache Size Limit",
1390
+ info="Set torch._dynamo.config.cache_size_limit (0 = use PyTorch default, typically 8-32)",
1391
+ value=config.get("compile_cache_size_limit", 0),
1392
+ step=1,
1393
+ minimum=0,
1394
+ interactive=True,
1395
+ )
1396
+
1397
+ schedule_accordion = gr.Accordion("Flow Matching and Timestep Settings", open=False, elem_classes="flux1_background")
1398
+ accordions.append(schedule_accordion)
1399
+ with schedule_accordion:
1400
+ with gr.Row():
1401
+ timestep_sampling = gr.Dropdown(
1402
+ label="timestep_sampling",
1403
+ choices=["sigma", "uniform", "sigmoid", "shift", "flux_shift", "flux2_shift", "qwen_shift", "logsnr", "qinglong_flux", "qinglong_qwen"],
1404
+ value=config.get("timestep_sampling", "shift"),
1405
+ interactive=True,
1406
+ info="Timestep sampling method for flow matching (shift recommended for Z-Image).",
1407
+ )
1408
+ weighting_scheme = gr.Dropdown(
1409
+ label="weighting_scheme",
1410
+ choices=["logit_normal", "mode", "cosmap", "sigma_sqrt", "none"],
1411
+ value=config.get("weighting_scheme", "none"),
1412
+ interactive=True,
1413
+ info="Loss weighting scheme for timestep distribution (none disables weighting).",
1414
+ )
1415
+ with gr.Row():
1416
+ discrete_flow_shift = gr.Number(
1417
+ label="discrete_flow_shift",
1418
+ value=config.get("discrete_flow_shift", 2.0),
1419
+ step=0.1,
1420
+ interactive=True,
1421
+ info="Shift factor used by shift/flux_shift sampling.",
1422
+ )
1423
+ sigmoid_scale = gr.Number(
1424
+ label="sigmoid_scale",
1425
+ value=config.get("sigmoid_scale", 1.0),
1426
+ step=0.1,
1427
+ interactive=True,
1428
+ info="Scale for sigmoid/shift timestep sampling.",
1429
+ )
1430
+ with gr.Row():
1431
+ min_timestep = gr.Number(
1432
+ label="min_timestep",
1433
+ value=config.get("min_timestep", 0),
1434
+ step=1,
1435
+ interactive=True,
1436
+ info="Minimum timestep clamp (0-999).",
1437
+ )
1438
+ max_timestep = gr.Number(
1439
+ label="max_timestep",
1440
+ value=config.get("max_timestep", 1000),
1441
+ step=1,
1442
+ interactive=True,
1443
+ info="Maximum timestep clamp (1-1000).",
1444
+ )
1445
+
1446
+ training_accordion = gr.Accordion("Training Settings", open=False, elem_classes="preset_background")
1447
+ accordions.append(training_accordion)
1448
+ with training_accordion:
1449
+ training = TrainingSettings(headless=headless, config=config)
1450
+
1451
+ sample_accordion = gr.Accordion("Sample Generation Settings", open=False, elem_classes="samples_background")
1452
+ accordions.append(sample_accordion)
1453
+ with sample_accordion:
1454
+ _variant_init = (config.get("zimage_variant", "base") or "base").strip().lower()
1455
+ _default_sample_steps = 20 if _variant_init == "turbo" else 25
1456
+ _default_cfg_scale = 1.0 if _variant_init == "turbo" else 4.0
1457
+ with gr.Row():
1458
+ sample_every_n_steps = gr.Number(
1459
+ label="sample_every_n_steps",
1460
+ value=config.get("sample_every_n_steps", 0),
1461
+ minimum=0,
1462
+ step=1,
1463
+ interactive=True,
1464
+ info="Generate samples every N steps (0 disables).",
1465
+ )
1466
+ sample_every_n_epochs = gr.Number(
1467
+ label="sample_every_n_epochs",
1468
+ value=config.get("sample_every_n_epochs", 0),
1469
+ minimum=0,
1470
+ step=1,
1471
+ interactive=True,
1472
+ info="Generate samples every N epochs (overrides steps).",
1473
+ )
1474
+ sample_at_first = gr.Checkbox(
1475
+ label="sample_at_first",
1476
+ value=bool(config.get("sample_at_first", False)),
1477
+ info="Generate samples before training starts.",
1478
+ )
1479
+ with gr.Row():
1480
+ sample_prompts = gr.Textbox(
1481
+ label="sample_prompts",
1482
+ value=config.get("sample_prompts", ""),
1483
+ interactive=True,
1484
+ info="Path to a prompt file (one prompt per line). Missing defaults are auto-added unless disabled below.",
1485
+ )
1486
+ sample_prompts_btn = gr.Button("📁", size="lg", visible=not headless)
1487
+ sample_prompts_btn.click(fn=lambda: get_file_path(file_path="", default_extension=".txt", extension_name="Text files"), outputs=[sample_prompts])
1488
+ with gr.Row():
1489
+ disable_prompt_enhancement = gr.Checkbox(
1490
+ label="Disable Automatic Prompt Enhancement",
1491
+ value=bool(config.get("disable_prompt_enhancement", False)),
1492
+ info="Use prompt file as-is (do not auto-add default --w/--h/--s/--l/--d/--n values).",
1493
+ )
1494
+ with gr.Row():
1495
+ sample_output_dir = gr.Textbox(
1496
+ label="sample_output_dir",
1497
+ value=config.get("sample_output_dir", ""),
1498
+ interactive=True,
1499
+ info="Folder to save generated samples.",
1500
+ )
1501
+ sample_output_dir_btn = gr.Button("📂", size="lg", visible=not headless)
1502
+ sample_output_dir_btn.click(fn=lambda: get_folder_path(folder_path=""), outputs=[sample_output_dir])
1503
+ with gr.Row():
1504
+ sample_width = gr.Number(
1505
+ label="sample_width",
1506
+ value=config.get("sample_width", 1024),
1507
+ step=8,
1508
+ interactive=True,
1509
+ info="Sample width in pixels (multiples of 8 recommended).",
1510
+ )
1511
+ sample_height = gr.Number(
1512
+ label="sample_height",
1513
+ value=config.get("sample_height", 1024),
1514
+ step=8,
1515
+ interactive=True,
1516
+ info="Sample height in pixels (multiples of 8 recommended).",
1517
+ )
1518
+ with gr.Row():
1519
+ sample_steps = gr.Number(
1520
+ label="sample_steps",
1521
+ value=config.get("sample_steps", _default_sample_steps),
1522
+ step=1,
1523
+ interactive=True,
1524
+ info="Sampling steps (Base ~25, Turbo ~20 by default).",
1525
+ )
1526
+ sample_guidance_scale = gr.Number(
1527
+ label="sample_guidance_scale",
1528
+ value=config.get("sample_guidance_scale", 0.0),
1529
+ step=0.1,
1530
+ interactive=True,
1531
+ info="Legacy guidance scale; Z-Image uses sample_cfg_scale (--l) instead.",
1532
+ )
1533
+ sample_seed = gr.Number(
1534
+ label="sample_seed",
1535
+ value=config.get("sample_seed", 42),
1536
+ step=1,
1537
+ interactive=True,
1538
+ info="Seed for sample generation.",
1539
+ )
1540
+ with gr.Row():
1541
+ sample_cfg_scale = gr.Number(
1542
+ label="sample_cfg_scale",
1543
+ value=config.get("sample_cfg_scale", _default_cfg_scale),
1544
+ step=0.1,
1545
+ interactive=True,
1546
+ info="CFG scale for Z-Image sampling (kohya flag: --l).",
1547
+ )
1548
+ sample_negative_prompt = gr.Textbox(
1549
+ label="sample_negative_prompt",
1550
+ value=config.get("sample_negative_prompt", ""),
1551
+ interactive=True,
1552
+ info="Optional negative prompt (used when cfg_scale > 1).",
1553
+ )
1554
+
1555
+ # Variant-based suggestions (doesn't force anything, but helps defaults)
1556
+ def _variant_defaults(variant: str):
1557
+ if variant == "turbo":
1558
+ return gr.update(value=1.0), gr.update(value=20)
1559
+ return gr.update(value=4.0), gr.update(value=25)
1560
+
1561
+ zimage_variant.change(fn=_variant_defaults, inputs=[zimage_variant], outputs=[sample_cfg_scale, sample_steps])
1562
+
1563
+ caching_accordion = gr.Accordion("Caching Settings", open=False, elem_classes="samples_background")
1564
+ accordions.append(caching_accordion)
1565
+ with caching_accordion:
1566
+ with gr.Row():
1567
+ caching_latent_device = gr.Textbox(
1568
+ label="caching_latent_device",
1569
+ value=config.get("caching_latent_device", "cuda"),
1570
+ interactive=True,
1571
+ info="Device for latent caching (e.g., cuda, cuda:0, cpu).",
1572
+ )
1573
+ caching_latent_batch_size = gr.Number(
1574
+ label="caching_latent_batch_size",
1575
+ value=config.get("caching_latent_batch_size", 1),
1576
+ step=1,
1577
+ interactive=True,
1578
+ info="Batch size for latent caching.",
1579
+ )
1580
+ caching_latent_num_workers = gr.Number(
1581
+ label="caching_latent_num_workers",
1582
+ value=config.get("caching_latent_num_workers", 2),
1583
+ step=1,
1584
+ interactive=True,
1585
+ info="Dataloader workers for latent caching.",
1586
+ )
1587
+ with gr.Row():
1588
+ caching_latent_skip_existing = gr.Checkbox(
1589
+ label="caching_latent_skip_existing",
1590
+ value=bool(config.get("caching_latent_skip_existing", True)),
1591
+ info="Skip existing cache entries (set false to disable latent caching step).",
1592
+ )
1593
+ caching_latent_keep_cache = gr.Checkbox(
1594
+ label="caching_latent_keep_cache",
1595
+ value=bool(config.get("caching_latent_keep_cache", True)),
1596
+ info="Keep latent cache after training.",
1597
+ )
1598
+ with gr.Row():
1599
+ caching_teo_device = gr.Textbox(
1600
+ label="caching_teo_device",
1601
+ value=config.get("caching_teo_device", "cuda"),
1602
+ interactive=True,
1603
+ info="Device for text encoder output caching.",
1604
+ )
1605
+ caching_teo_batch_size = gr.Number(
1606
+ label="caching_teo_batch_size",
1607
+ value=config.get("caching_teo_batch_size", 8),
1608
+ step=1,
1609
+ interactive=True,
1610
+ info="Batch size for text encoder output caching.",
1611
+ )
1612
+ caching_teo_num_workers = gr.Number(
1613
+ label="caching_teo_num_workers",
1614
+ value=config.get("caching_teo_num_workers", 2),
1615
+ step=1,
1616
+ interactive=True,
1617
+ info="Dataloader workers for text encoder output caching.",
1618
+ )
1619
+ with gr.Row():
1620
+ caching_teo_skip_existing = gr.Checkbox(
1621
+ label="caching_teo_skip_existing",
1622
+ value=bool(config.get("caching_teo_skip_existing", True)),
1623
+ info="Skip existing caches (set false to disable text encoder caching step).",
1624
+ )
1625
+ caching_teo_keep_cache = gr.Checkbox(
1626
+ label="caching_teo_keep_cache",
1627
+ value=bool(config.get("caching_teo_keep_cache", True)),
1628
+ info="Keep text encoder output cache after training.",
1629
+ )
1630
+ caching_teo_fp8_llm = gr.Checkbox(
1631
+ label="caching_teo_fp8_llm",
1632
+ value=bool(config.get("caching_teo_fp8_llm", False)),
1633
+ interactive=True,
1634
+ info="Use FP8 for the Qwen3 text encoder during caching.",
1635
+ )
1636
+
1637
+ optimizer_accordion = gr.Accordion("Learning Rate, Optimizer and Scheduler Settings", open=False, elem_classes="flux1_rank_layers_background")
1638
+ accordions.append(optimizer_accordion)
1639
+ with optimizer_accordion:
1640
+ optim = OptimizerAndScheduler(headless=headless, config=config)
1641
+ fused_backward_pass = gr.Checkbox(
1642
+ label="fused_backward_pass",
1643
+ value=bool(config.get("fused_backward_pass", False)),
1644
+ info="DreamBooth only: reduces VRAM during backward pass with AdaFactor. Not effective for LoRA training.",
1645
+ )
1646
+
1647
+ network_accordion = gr.Accordion("LoRA Settings", open=False, elem_classes="flux1_background")
1648
+ accordions.append(network_accordion)
1649
+ with network_accordion:
1650
+ network = Network(headless=headless, config=config)
1651
+
1652
+ advanced_accordion = gr.Accordion("Advanced Settings", open=False, elem_classes="samples_background")
1653
+ accordions.append(advanced_accordion)
1654
+ with advanced_accordion:
1655
+ advanced = AdvancedTraining(headless=headless, config=config)
1656
+
1657
+ metadata_accordion = gr.Accordion("Metadata Settings", open=False, elem_classes="flux1_rank_layers_background")
1658
+ accordions.append(metadata_accordion)
1659
+ with metadata_accordion:
1660
+ metadata = MetaData(config=config)
1661
+
1662
+ huggingface_accordion = gr.Accordion("HuggingFace Settings", open=False, elem_classes="huggingface_background")
1663
+ accordions.append(huggingface_accordion)
1664
+ with huggingface_accordion:
1665
+ huggingface = HuggingFace(config=config)
1666
+
1667
+ executor = CommandExecutor(headless=headless)
1668
+ run_state = gr.Textbox(value=train_state_value, visible=False)
1669
+
1670
+ with gr.Column(), gr.Group():
1671
+ with gr.Row():
1672
+ button_print = gr.Button("Print training command")
1673
+ toggle_all_btn_bottom = gr.Button(
1674
+ value="Open All Panels",
1675
+ variant="secondary"
1676
+ )
1677
+
1678
+ settings_list = [
1679
+ # accelerate_launch
1680
+ accelerate_launch.mixed_precision,
1681
+ accelerate_launch.num_cpu_threads_per_process,
1682
+ accelerate_launch.num_processes,
1683
+ accelerate_launch.num_machines,
1684
+ accelerate_launch.multi_gpu,
1685
+ accelerate_launch.gpu_ids,
1686
+ accelerate_launch.main_process_port,
1687
+ accelerate_launch.dynamo_backend,
1688
+ accelerate_launch.dynamo_mode,
1689
+ accelerate_launch.dynamo_use_fullgraph,
1690
+ accelerate_launch.dynamo_use_dynamic,
1691
+ accelerate_launch.extra_accelerate_launch_args,
1692
+ # advanced_training
1693
+ advanced.additional_parameters,
1694
+ advanced.debug_mode,
1695
+ # dataset
1696
+ dataset_config_mode,
1697
+ dataset_config,
1698
+ parent_folder_path,
1699
+ dataset_resolution_width,
1700
+ dataset_resolution_height,
1701
+ dataset_caption_extension,
1702
+ create_missing_captions,
1703
+ caption_strategy,
1704
+ dataset_batch_size,
1705
+ dataset_enable_bucket,
1706
+ dataset_bucket_no_upscale,
1707
+ dataset_cache_directory,
1708
+ generated_toml_path,
1709
+ # variant
1710
+ training_mode,
1711
+ zimage_variant,
1712
+ training_adapter_path,
1713
+ training_adapter_multiplier,
1714
+ # model
1715
+ dit,
1716
+ vae,
1717
+ text_encoder,
1718
+ fp8_base,
1719
+ fp8_scaled,
1720
+ fp8_llm,
1721
+ disable_numpy_memmap,
1722
+ blocks_to_swap,
1723
+ use_pinned_memory_for_block_swap,
1724
+ block_swap_h2d_only,
1725
+ block_swap_ring_size,
1726
+ img_in_txt_in_offloading,
1727
+ # torch compile
1728
+ compile,
1729
+ compile_backend,
1730
+ compile_mode,
1731
+ compile_dynamic,
1732
+ compile_fullgraph,
1733
+ compile_cache_size_limit,
1734
+ # schedule
1735
+ timestep_sampling,
1736
+ weighting_scheme,
1737
+ discrete_flow_shift,
1738
+ sigmoid_scale,
1739
+ min_timestep,
1740
+ max_timestep,
1741
+ # training settings
1742
+ training.sdpa,
1743
+ training.flash_attn,
1744
+ training.sage_attn,
1745
+ training.xformers,
1746
+ training.split_attn,
1747
+ training.use_legacy_sdpa,
1748
+ training.max_train_steps,
1749
+ training.max_train_epochs,
1750
+ training.max_data_loader_n_workers,
1751
+ training.persistent_data_loader_workers,
1752
+ training.seed,
1753
+ training.gradient_checkpointing,
1754
+ training.gradient_checkpointing_cpu_offload,
1755
+ training.gradient_accumulation_steps,
1756
+ training.full_bf16,
1757
+ training.full_fp16,
1758
+ training.logging_dir,
1759
+ training.log_with,
1760
+ training.log_prefix,
1761
+ training.log_tracker_name,
1762
+ training.wandb_run_name,
1763
+ training.log_tracker_config,
1764
+ training.wandb_api_key,
1765
+ training.log_config,
1766
+ training.ddp_timeout,
1767
+ training.ddp_gradient_as_bucket_view,
1768
+ training.ddp_static_graph,
1769
+ # samples
1770
+ sample_every_n_steps,
1771
+ sample_every_n_epochs,
1772
+ sample_at_first,
1773
+ sample_prompts,
1774
+ disable_prompt_enhancement,
1775
+ sample_output_dir,
1776
+ sample_width,
1777
+ sample_height,
1778
+ sample_steps,
1779
+ sample_guidance_scale,
1780
+ sample_seed,
1781
+ sample_negative_prompt,
1782
+ sample_cfg_scale,
1783
+ # caching
1784
+ caching_latent_device,
1785
+ caching_latent_batch_size,
1786
+ caching_latent_num_workers,
1787
+ caching_latent_skip_existing,
1788
+ caching_latent_keep_cache,
1789
+ caching_teo_device,
1790
+ caching_teo_batch_size,
1791
+ caching_teo_num_workers,
1792
+ caching_teo_skip_existing,
1793
+ caching_teo_keep_cache,
1794
+ caching_teo_fp8_llm,
1795
+ # optimizer/scheduler
1796
+ optim.optimizer_type,
1797
+ optim.optimizer_args,
1798
+ optim.learning_rate,
1799
+ optim.max_grad_norm,
1800
+ fused_backward_pass,
1801
+ optim.lr_scheduler,
1802
+ optim.lr_warmup_steps,
1803
+ optim.lr_decay_steps,
1804
+ optim.lr_scheduler_num_cycles,
1805
+ optim.lr_scheduler_power,
1806
+ optim.lr_scheduler_timescale,
1807
+ optim.lr_scheduler_min_lr_ratio,
1808
+ optim.lr_scheduler_type,
1809
+ optim.lr_scheduler_args,
1810
+ # network
1811
+ network.no_metadata,
1812
+ network.network_weights,
1813
+ network.network_module,
1814
+ network.network_dim,
1815
+ network.network_alpha,
1816
+ network.network_dropout,
1817
+ network.network_args,
1818
+ network.training_comment,
1819
+ network.dim_from_weights,
1820
+ network.scale_weight_norms,
1821
+ network.base_weights,
1822
+ network.base_weights_multiplier,
1823
+ # save/load
1824
+ save_load.output_dir,
1825
+ save_load.output_name,
1826
+ save_load.resume,
1827
+ save_load.save_precision,
1828
+ save_load.save_every_n_epochs,
1829
+ save_load.save_last_n_epochs,
1830
+ save_load.save_every_n_steps,
1831
+ save_load.save_last_n_steps,
1832
+ save_load.save_last_n_epochs_state,
1833
+ save_load.save_last_n_steps_state,
1834
+ save_load.save_state,
1835
+ save_load.save_state_on_train_end,
1836
+ save_load.mem_eff_save,
1837
+ # metadata
1838
+ metadata.metadata_author,
1839
+ metadata.metadata_description,
1840
+ metadata.metadata_license,
1841
+ metadata.metadata_tags,
1842
+ metadata.metadata_title,
1843
+ metadata.metadata_reso,
1844
+ metadata.metadata_arch,
1845
+ # huggingface
1846
+ huggingface.huggingface_repo_id,
1847
+ huggingface.huggingface_token,
1848
+ huggingface.huggingface_repo_type,
1849
+ huggingface.huggingface_repo_visibility,
1850
+ huggingface.huggingface_path_in_repo,
1851
+ huggingface.save_state_to_huggingface,
1852
+ huggingface.resume_from_huggingface,
1853
+ huggingface.async_upload,
1854
+ ]
1855
+
1856
+ assert len(settings_list) == len(ZIMAGE_PARAM_KEYS), f"settings_list ({len(settings_list)}) != keys ({len(ZIMAGE_PARAM_KEYS)})"
1857
+
1858
+ # Add handler for search functionality
1859
+ def search_settings(query):
1860
+ if not query or len(query.strip()) < 1:
1861
+ return gr.Row(visible=False), ""
1862
+
1863
+ query_lower = query.lower().strip()
1864
+ results = []
1865
+
1866
+ # Comprehensive parameter map for Z-Image
1867
+ parameter_map = {
1868
+ # Model Variant
1869
+ "training_mode": ("Z-Image Model Settings", "Training Mode (LoRA/DreamBooth)"),
1870
+ "zimage_variant": ("Z-Image Model Settings", "Z-Image Variant (Base/Turbo)"),
1871
+ "base": ("Z-Image Model Settings", "Base Model"),
1872
+ "turbo": ("Z-Image Model Settings", "Turbo Model (Distilled)"),
1873
+ "variant": ("Z-Image Model Settings", "Model Variant"),
1874
+ "adapter": ("Z-Image Model Settings", "Turbo Training Adapter (LoRA)"),
1875
+ "training_adapter": ("Z-Image Model Settings", "Turbo Training Adapter (LoRA)"),
1876
+ "base_weights": ("LoRA Settings", "Base Weights"),
1877
+
1878
+ # Model Paths
1879
+ "dit": ("Z-Image Model Settings", "DiT (Base Model) Checkpoint Path"),
1880
+ "vae": ("Z-Image Model Settings", "VAE Checkpoint Path"),
1881
+ "text_encoder": ("Z-Image Model Settings", "Text Encoder (Qwen3) Path"),
1882
+
1883
+ # FP8 and Memory
1884
+ "fp8_base": ("Z-Image Model Settings", "FP8 for Base Model (DiT)"),
1885
+ "fp8_scaled": ("Z-Image Model Settings", "Scaled FP8 for Base Model"),
1886
+ "fp8_llm": ("Z-Image Model Settings", "FP8 for Qwen3 Text Encoder"),
1887
+ "blocks_to_swap": ("Z-Image Model Settings", "Blocks to Swap to CPU"),
1888
+ "blocks": ("Z-Image Model Settings", "Blocks to Swap"),
1889
+ "swap": ("Z-Image Model Settings", "Blocks to Swap"),
1890
+ "cpu": ("Z-Image Model Settings", "CPU Offloading"),
1891
+ "disable_numpy_memmap": ("Z-Image Model Settings", "Disable NumPy Memmap"),
1892
+ "use_pinned_memory_for_block_swap": ("Z-Image Model Settings", "Use Pinned Memory for Block Swap"),
1893
+ "img_in_txt_in_offloading": ("Z-Image Model Settings", "Image-in-Text Input Offloading"),
1894
+
1895
+ # Torch Compile
1896
+ "compile": ("Torch Compile Settings", "Enable torch.compile"),
1897
+ "compile_backend": ("Torch Compile Settings", "Compile Backend"),
1898
+ "compile_mode": ("Torch Compile Settings", "Compile Mode"),
1899
+ "compile_dynamic": ("Torch Compile Settings", "Dynamic Shapes"),
1900
+ "compile_fullgraph": ("Torch Compile Settings", "Fullgraph Mode"),
1901
+ "compile_cache_size_limit": ("Torch Compile Settings", "Cache Size Limit"),
1902
+
1903
+ # Dataset Settings
1904
+ "dataset": ("Z-Image Training Dataset", "Dataset Configuration"),
1905
+ "dataset_config_mode": ("Z-Image Training Dataset", "Dataset Configuration Method"),
1906
+ "dataset_config": ("Z-Image Training Dataset", "Dataset Config File"),
1907
+ "parent_folder": ("Z-Image Training Dataset", "Parent Folder Path"),
1908
+ "resolution": ("Z-Image Training Dataset", "Resolution"),
1909
+ "caption": ("Z-Image Training Dataset", "Caption Settings"),
1910
+ "bucket": ("Z-Image Training Dataset", "Bucketing"),
1911
+ "batch_size": ("Z-Image Training Dataset", "Batch Size"),
1912
+ "cache_directory": ("Z-Image Training Dataset", "Cache Directory"),
1913
+
1914
+ # Flow Matching
1915
+ "timestep": ("Flow Matching and Timestep Settings", "Timestep Sampling"),
1916
+ "weighting": ("Flow Matching and Timestep Settings", "Weighting Scheme"),
1917
+ "discrete_flow_shift": ("Flow Matching and Timestep Settings", "Discrete Flow Shift"),
1918
+ "sigmoid": ("Flow Matching and Timestep Settings", "Sigmoid Scale"),
1919
+
1920
+ # Training Settings
1921
+ "sdpa": ("Training Settings", "Use SDPA"),
1922
+ "flash_attn": ("Training Settings", "Use FlashAttention"),
1923
+ "sage_attn": ("Training Settings", "Use SageAttention"),
1924
+ "xformers": ("Training Settings", "Use xformers"),
1925
+ "split_attn": ("Training Settings", "Split Attention"),
1926
+ "use_legacy_sdpa": ("Training Settings", "Use Legacy PyTorch SDPA"),
1927
+ "max_train_steps": ("Training Settings", "Max Training Steps"),
1928
+ "max_train_epochs": ("Training Settings", "Max Training Epochs"),
1929
+ "epochs": ("Training Settings", "Training Epochs"),
1930
+ "steps": ("Training Settings", "Training Steps"),
1931
+ "seed": ("Training Settings", "Random Seed"),
1932
+ "gradient": ("Training Settings", "Gradient Settings"),
1933
+ "gradient_checkpointing": ("Training Settings", "Gradient Checkpointing"),
1934
+ "gradient_accumulation": ("Training Settings", "Gradient Accumulation Steps"),
1935
+ "full_bf16": ("Training Settings", "Full BF16"),
1936
+ "full_fp16": ("Training Settings", "Full FP16"),
1937
+ "workers": ("Training Settings", "DataLoader Workers"),
1938
+ "persistent": ("Training Settings", "Persistent DataLoader Workers"),
1939
+
1940
+ # Optimizer Settings
1941
+ "optimizer": ("Learning Rate, Optimizer and Scheduler Settings", "Optimizer Type"),
1942
+ "learning_rate": ("Learning Rate, Optimizer and Scheduler Settings", "Learning Rate"),
1943
+ "lr": ("Learning Rate, Optimizer and Scheduler Settings", "Learning Rate"),
1944
+ "adamw": ("Learning Rate, Optimizer and Scheduler Settings", "AdamW Optimizer"),
1945
+ "scheduler": ("Learning Rate, Optimizer and Scheduler Settings", "LR Scheduler"),
1946
+ "warmup": ("Learning Rate, Optimizer and Scheduler Settings", "LR Warmup Steps"),
1947
+ "max_grad_norm": ("Learning Rate, Optimizer and Scheduler Settings", "Max Gradient Norm"),
1948
+ "fused_backward_pass": ("Learning Rate, Optimizer and Scheduler Settings", "Fused Backward Pass"),
1949
+
1950
+ # Network/LoRA Settings
1951
+ "lora": ("LoRA Settings", "LoRA Configuration"),
1952
+ "network_module": ("LoRA Settings", "Network Module"),
1953
+ "network_dim": ("LoRA Settings", "Network Dimension (LoRA Rank)"),
1954
+ "network_alpha": ("LoRA Settings", "Network Alpha"),
1955
+ "network_dropout": ("LoRA Settings", "Network Dropout"),
1956
+ "network_args": ("LoRA Settings", "Network Arguments"),
1957
+ "rank": ("LoRA Settings", "LoRA Rank"),
1958
+ "alpha": ("LoRA Settings", "LoRA Alpha"),
1959
+ "lora_zimage": ("LoRA Settings", "LoRA Z-Image Module"),
1960
+
1961
+ # Caching
1962
+ "cache": ("Caching Settings", "Caching Configuration"),
1963
+ "latent_cache": ("Caching Settings", "Latent Caching"),
1964
+ "text_encoder_cache": ("Caching Settings", "Text Encoder Output Caching"),
1965
+ "teo_cache": ("Caching Settings", "Text Encoder Output Caching"),
1966
+ "caching_device": ("Caching Settings", "Caching Device"),
1967
+ "skip_existing": ("Caching Settings", "Skip Existing Cache"),
1968
+ "keep_cache": ("Caching Settings", "Keep Cache Files"),
1969
+ "fp8_llm_cache": ("Caching Settings", "FP8 for Text Encoder Caching"),
1970
+
1971
+ # Samples
1972
+ "sample": ("Sample Generation Settings", "Sample Generation"),
1973
+ "sample_prompts": ("Sample Generation Settings", "Sample Prompts File"),
1974
+ "disable_prompt_enhancement": ("Sample Generation Settings", "Disable Automatic Prompt Enhancement"),
1975
+ "sample_steps": ("Sample Generation Settings", "Sample Steps"),
1976
+ "sample_cfg_scale": ("Sample Generation Settings", "Sample CFG Scale"),
1977
+ "guidance": ("Sample Generation Settings", "Guidance Scale"),
1978
+ "cfg": ("Sample Generation Settings", "CFG Scale"),
1979
+
1980
+ # Save/Load
1981
+ "output": ("Save Models and Resume Training Settings", "Output Settings"),
1982
+ "output_dir": ("Save Models and Resume Training Settings", "Output Directory"),
1983
+ "output_name": ("Save Models and Resume Training Settings", "Output Name"),
1984
+ "save_every": ("Save Models and Resume Training Settings", "Save Frequency"),
1985
+ "resume": ("Save Models and Resume Training Settings", "Resume Training"),
1986
+ "save_state": ("Save Models and Resume Training Settings", "Save Optimizer State"),
1987
+ "mem_eff_save": ("Save Models and Resume Training Settings", "Memory Efficient Save"),
1988
+
1989
+ # Accelerate
1990
+ "mixed_precision": ("Accelerate launch Settings", "Mixed Precision"),
1991
+ "bf16": ("Accelerate launch Settings", "BF16 Mixed Precision"),
1992
+ "num_processes": ("Accelerate launch Settings", "Number of Processes"),
1993
+ "multi_gpu": ("Accelerate launch Settings", "Multi GPU"),
1994
+ "gpu_ids": ("Accelerate launch Settings", "GPU IDs"),
1995
+ "dynamo": ("Accelerate launch Settings", "Dynamo Backend"),
1996
+
1997
+ # Metadata
1998
+ "metadata": ("Metadata Settings", "Model Metadata"),
1999
+ "author": ("Metadata Settings", "Metadata Author"),
2000
+ "description": ("Metadata Settings", "Metadata Description"),
2001
+ "license": ("Metadata Settings", "Metadata License"),
2002
+ "tags": ("Metadata Settings", "Metadata Tags"),
2003
+
2004
+ # HuggingFace
2005
+ "huggingface": ("HuggingFace Settings", "HuggingFace Upload"),
2006
+ "repo_id": ("HuggingFace Settings", "Repository ID"),
2007
+ "huggingface_token": ("HuggingFace Settings", "HuggingFace Token"),
2008
+
2009
+ # Advanced
2010
+ "additional_parameters": ("Advanced Settings", "Additional Parameters"),
2011
+ "debug": ("Advanced Settings", "Debug Mode"),
2012
+ }
2013
+
2014
+ # Search through parameter map
2015
+ for param, (location, display_name) in parameter_map.items():
2016
+ if query_lower in param.lower() or query_lower in display_name.lower() or param.lower() in query_lower:
2017
+ score = 0
2018
+ if query_lower == param.lower():
2019
+ score = 100
2020
+ elif param.lower().startswith(query_lower):
2021
+ score = 80
2022
+ elif query_lower in param.lower():
2023
+ score = 60
2024
+ elif query_lower in display_name.lower():
2025
+ score = 40
2026
+
2027
+ results.append((location, display_name, param, score))
2028
+
2029
+ # Sort by score
2030
+ results.sort(key=lambda x: x[3], reverse=True)
2031
+
2032
+ # Remove duplicates
2033
+ seen = set()
2034
+ unique_results = []
2035
+ for item in results:
2036
+ key = (item[0], item[1])
2037
+ if key not in seen:
2038
+ seen.add(key)
2039
+ unique_results.append(item[:3])
2040
+
2041
+ if not unique_results:
2042
+ html = f"<div style='padding: 10px; background: #fff3cd; border: 1px solid #ffc107; border-radius: 5px;'>"
2043
+ html += f"<strong>No results found for '{query}'</strong><br>"
2044
+ html += f"<span style='color: #666; font-size: 0.9em;'>Try: learning, optimizer, fp8, vram, epochs, batch, cache, sample, zimage, turbo</span>"
2045
+ html += "</div>"
2046
+ return gr.Row(visible=True), html
2047
+
2048
+ # Format results
2049
+ html = f"<div style='padding: 10px; background: #f0f0f0; border-radius: 5px;'>"
2050
+ html += f"<strong>Found {len(unique_results)} result(s) for '{query}':</strong><br><br>"
2051
+
2052
+ unique_panels = set()
2053
+ for location, display_name, param in unique_results:
2054
+ panel_name = location.split('→')[0].strip()
2055
+ unique_panels.add(panel_name)
2056
+
2057
+ html += f"<div style='margin-bottom: 10px; padding: 8px; background: #d4edda; border: 1px solid #c3e6cb; border-radius: 3px; color: #155724;'>"
2058
+ html += f"✅ <strong>Opening {len(unique_panels)} relevant panel{'s' if len(unique_panels) > 1 else ''}:</strong> "
2059
+ html += ", ".join(sorted(unique_panels))
2060
+ html += "</div>"
2061
+
2062
+ for location, display_name, param in unique_results[:10]:
2063
+ html += f"<div style='margin-bottom: 8px; padding: 8px; background: white; border-radius: 3px; border-left: 3px solid #007bff;'>"
2064
+ html += f"📍 <strong>{location}</strong><br>"
2065
+ html += f"<span style='margin-left: 20px; color: #333;'>→ {display_name}</span>"
2066
+ html += f"</div>"
2067
+
2068
+ if len(unique_results) > 10:
2069
+ html += f"<div style='color: #666; margin-top: 5px;'>... and {len(unique_results) - 10} more results</div>"
2070
+
2071
+ html += "</div>"
2072
+
2073
+ return gr.Row(visible=True), html
2074
+
2075
+ # Modified search functionality to open relevant panels
2076
+ def search_and_open_panels(query):
2077
+ if not query or len(query.strip()) < 1:
2078
+ accordion_states = [gr.Accordion(open=False) for _ in accordions]
2079
+ return [gr.Row(visible=False), "", gr.Button(value="Open All Panels"), gr.Button(value="Open All Panels"), "closed"] + accordion_states
2080
+
2081
+ results_row, results_html = search_settings(query)
2082
+
2083
+ panels_to_open = set()
2084
+
2085
+ panel_map = {
2086
+ "Accelerate launch Settings": 0,
2087
+ "Save Models and Resume Training Settings": 1,
2088
+ "Z-Image Training Dataset": 2,
2089
+ "Z-Image Model Settings": 3,
2090
+ "Torch Compile Settings": 4,
2091
+ "Flow Matching and Timestep Settings": 5,
2092
+ "Training Settings": 6,
2093
+ "Sample Generation Settings": 7,
2094
+ "Caching Settings": 8,
2095
+ "Learning Rate, Optimizer and Scheduler Settings": 9,
2096
+ "LoRA Settings": 10,
2097
+ "Advanced Settings": 11,
2098
+ "Metadata Settings": 12,
2099
+ "HuggingFace Settings": 13,
2100
+ }
2101
+
2102
+ import re
2103
+ panel_pattern = r'📍 <strong>([^<]+)</strong>'
2104
+ matches = re.findall(panel_pattern, results_html)
2105
+
2106
+ for match in matches:
2107
+ base_panel = match.split('→')[0].strip()
2108
+ if base_panel in panel_map:
2109
+ panels_to_open.add(panel_map[base_panel])
2110
+
2111
+ accordion_states = []
2112
+ for i in range(len(accordions)):
2113
+ if i in panels_to_open:
2114
+ accordion_states.append(gr.Accordion(open=True))
2115
+ else:
2116
+ accordion_states.append(gr.Accordion(open=False))
2117
+
2118
+ if panels_to_open:
2119
+ button_text = f"Reset Search ({len(panels_to_open)} panel{'s' if len(panels_to_open) > 1 else ''} filtered)"
2120
+ state = "search"
2121
+ else:
2122
+ button_text = "Open All Panels"
2123
+ state = "closed"
2124
+
2125
+ return [gr.Row(visible=False), "", gr.Button(value=button_text), gr.Button(value=button_text), state] + accordion_states
2126
+
2127
+ search_input.change(
2128
+ search_and_open_panels,
2129
+ inputs=[search_input],
2130
+ outputs=[search_results_row, search_results, toggle_all_btn, toggle_all_btn_bottom, panels_state] + accordions,
2131
+ show_progress=False,
2132
+ )
2133
+
2134
+ # Add handler for unified toggle button
2135
+ def toggle_all_panels(current_state):
2136
+ if current_state == "search":
2137
+ new_state = "closed"
2138
+ new_button_text = "Open All Panels"
2139
+ accordion_states = [gr.Accordion(open=False) for _ in accordions]
2140
+ search_value = ""
2141
+ results_visibility = gr.Row(visible=False)
2142
+ results_content = ""
2143
+ elif current_state == "closed":
2144
+ new_state = "open"
2145
+ new_button_text = "Hide All Panels"
2146
+ accordion_states = [gr.Accordion(open=True) for _ in accordions]
2147
+ search_value = gr.Textbox(value="")
2148
+ results_visibility = gr.Row(visible=False)
2149
+ results_content = ""
2150
+ else:
2151
+ new_state = "closed"
2152
+ new_button_text = "Open All Panels"
2153
+ accordion_states = [gr.Accordion(open=False) for _ in accordions]
2154
+ search_value = gr.Textbox(value="")
2155
+ results_visibility = gr.Row(visible=False)
2156
+ results_content = ""
2157
+
2158
+ return [new_state, gr.Button(value=new_button_text), gr.Button(value=new_button_text), search_value, results_visibility, results_content] + accordion_states
2159
+
2160
+ toggle_all_btn.click(
2161
+ toggle_all_panels,
2162
+ inputs=[panels_state],
2163
+ outputs=[panels_state, toggle_all_btn, toggle_all_btn_bottom, search_input, search_results_row, search_results] + accordions,
2164
+ show_progress=False,
2165
+ )
2166
+
2167
+ toggle_all_btn_bottom.click(
2168
+ toggle_all_panels,
2169
+ inputs=[panels_state],
2170
+ outputs=[panels_state, toggle_all_btn, toggle_all_btn_bottom, search_input, search_results_row, search_results] + accordions,
2171
+ show_progress=False,
2172
+ )
2173
+
2174
+ configuration.button_open_config.click(
2175
+ zimage_gui_actions,
2176
+ inputs=[gr.Textbox(value="open_configuration", visible=False), dummy_true, configuration.config_file_name, dummy_headless, dummy_false] + settings_list,
2177
+ outputs=[configuration.config_file_name, configuration.config_status] + settings_list,
2178
+ show_progress=False,
2179
+ )
2180
+ configuration.button_load_config.click(
2181
+ zimage_gui_actions,
2182
+ inputs=[gr.Textbox(value="open_configuration", visible=False), dummy_false, configuration.config_file_name, dummy_headless, dummy_false] + settings_list,
2183
+ outputs=[configuration.config_file_name, configuration.config_status] + settings_list,
2184
+ show_progress=False,
2185
+ queue=False,
2186
+ )
2187
+ configuration.button_save_config.click(
2188
+ zimage_gui_actions,
2189
+ inputs=[gr.Textbox(value="save_configuration", visible=False), dummy_false, configuration.config_file_name, dummy_headless, dummy_false] + settings_list,
2190
+ outputs=[configuration.config_file_name, configuration.config_status],
2191
+ show_progress=False,
2192
+ queue=False,
2193
+ )
2194
+
2195
+ button_print.click(
2196
+ zimage_gui_actions,
2197
+ inputs=[gr.Textbox(value="train_model", visible=False), dummy_false, configuration.config_file_name, dummy_headless, dummy_true] + settings_list,
2198
+ show_progress=False,
2199
+ )
2200
+
2201
+ executor.button_run.click(
2202
+ zimage_gui_actions,
2203
+ inputs=[gr.Textbox(value="train_model", visible=False), dummy_false, configuration.config_file_name, dummy_headless, dummy_false] + settings_list,
2204
+ outputs=[executor.button_run, executor.stop_row, executor.button_stop_training, executor.training_status, run_state],
2205
+ show_progress=False,
2206
+ )
2207
+
2208
+ executor.button_stop_training.click(
2209
+ executor.kill_command,
2210
+ inputs=[],
2211
+ outputs=[executor.button_run, executor.stop_row, executor.button_stop_training, executor.training_status],
2212
+ js="() => { if (confirm('Stop training/caching?')) { return []; } else { throw new Error('Cancelled'); } }",
2213
+ )
2214
+
2215
+ run_state.change(
2216
+ fn=executor.wait_for_training_to_end,
2217
+ outputs=[executor.button_run, executor.stop_row, executor.button_stop_training, executor.training_status],
2218
+ show_progress=False,
2219
+ )
SECourses_Musubi_Trainer/pytest.ini ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [pytest]
2
+ testpaths = tests
SECourses_Musubi_Trainer/qwen_image_defaults.toml ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Qwen Image Training - Optimal Defaults Configuration
2
+ # This file contains the recommended default values for Qwen Image training
3
+ # Supports both LoRA (parameter-efficient) and DreamBooth (full fine-tuning) modes
4
+ # Based on documentation examples and best practices
5
+
6
+ # Training Mode Selection
7
+ training_mode = "LoRA Training" # Options: "LoRA Training" (efficient, lower VRAM) or "DreamBooth Fine-Tuning" (higher VRAM)
8
+
9
+ # Model Settings - REQUIRED FIELDS MUST BE SET BY USER
10
+ dit = "" # REQUIRED: Path to DiT checkpoint (qwen_image_bf16.safetensors)
11
+ vae = "" # REQUIRED: Path to VAE checkpoint (diffusion_pytorch_model.safetensors)
12
+ text_encoder = "" # REQUIRED: Path to Qwen2.5-VL checkpoint
13
+ dataset_config = "" # Path to dataset TOML configuration (required if using "Use TOML File" mode)
14
+ dataset_config_mode = "Generate from Folder Structure" # Default to auto-generate from folder structure
15
+
16
+ # Folder Structure Settings (used when dataset_config_mode = "Generate from Folder Structure")
17
+ parent_folder_path = "" # REQUIRED when using folder structure mode: Path to parent folder containing training images
18
+ dataset_resolution_width = 1328 # Target width for training images
19
+ dataset_resolution_height = 1328 # Target height for training images
20
+ dataset_caption_extension = ".txt" # Extension for caption files
21
+ create_missing_captions = true # Auto-create empty captions for images without caption files
22
+ caption_strategy = "folder_name" # How to handle missing captions: "folder_name" or "empty"
23
+ dataset_batch_size = 1 # Batch size for dataset processing
24
+ dataset_enable_bucket = false # Enable bucketing for variable aspect ratios
25
+ dataset_bucket_no_upscale = false # Prevent upscaling in bucket mode
26
+ dataset_cache_directory = "cache_dir" # Directory for caching processed data
27
+ dataset_control_directory = "edit_images" # [EDIT MODE] Directory name for control/reference images (only used when edit=true)
28
+ dataset_qwen_image_edit_no_resize_control = false # [EDIT MODE] Keep control images at original size. Only used when edit=true. Cannot be used with control resolution settings
29
+ dataset_qwen_image_edit_control_resolution_width = 1328 # [EDIT MODE] Control image width. 0=same as training images, 1024=official Qwen default, 1328=optimal for Qwen models. Only when edit=true
30
+ dataset_qwen_image_edit_control_resolution_height = 1328 # [EDIT MODE] Control image height. 0=same as training images, 1024=official Qwen default, 1328=optimal for Qwen models. Only when edit=true
31
+ auto_generate_black_control_images = false # [EDIT MODE] Auto-generate pitch black PNG control images with same filenames as training images. Uses control resolution settings
32
+ generated_toml_path = "" # Path where generated TOML will be saved (auto-set)
33
+
34
+ dit_dtype = "bfloat16" # HARDCODED: Must be bfloat16 for Qwen Image
35
+ dit_in_channels = 16 # [DO NOT CHANGE] VAE latent channel count. MUST be 16 for Qwen (different from SD's 4). Changing breaks training!
36
+ # num_layers = 60 # [ADVANCED] Number of DiT transformer layers. Leave commented out for auto-detection (60 for standard Qwen). Uncomment and change value only for custom/pruned models
37
+ text_encoder_dtype = "bfloat16" # Data type for Qwen2.5-VL. float16=faster, bfloat16=better precision
38
+ vae_dtype = "bfloat16" # Data type for VAE. bfloat16=Qwen Image default, float16=faster
39
+
40
+ # VAE Optimization Settings
41
+ vae_tiling = false # Enable spatial tiling to reduce VRAM usage during VAE operations (supported in Qwen Image)
42
+ vae_chunk_size = 0 # 0 = auto/disabled. Higher = faster but more VRAM
43
+ vae_spatial_tile_sample_min_size = 0 # 0 = disabled. 256 = typical. Auto-enables vae_tiling if set
44
+
45
+ fp8_vl = false # Enable for lower VRAM GPUs. Reduces VRAM with minimal quality loss
46
+ fp8_base = false # Optional: FP8 for DiT model, reduces VRAM usage
47
+ fp8_scaled = false # REQUIRED when fp8_base=true, better quality than standard FP8
48
+ blocks_to_swap = 0 # 0 = disabled. Max 59 (Qwen has 60 blocks). Higher values save more VRAM but require more RAM
49
+
50
+ # Additional Model Settings
51
+ guidance_scale = 1.0 # Classifier-free guidance scale. 1.0 = default, higher = stronger prompt adherence
52
+ img_in_txt_in_offloading = false # Memory optimization for mixed image-text inputs
53
+
54
+ # Model Variant Selection
55
+ # Upstream musubi-tuner now supports:
56
+ # - original (text-to-image)
57
+ # - edit-2509 (Edit Plus, multiple control images)
58
+ # - edit-2511 (Edit-2511, multiple control images)
59
+ # NOTE: The older base "edit" variant is intentionally removed from this GUI.
60
+ model_version = "original" # Options: "original", "edit-2509", "edit-2511"
61
+
62
+ faster_model_loading = false # Faster Model Loading: Disables numpy memmap for faster model loading. Uses more RAM but speeds up loading, especially useful for RunPod and similar environments
63
+ use_pinned_memory_for_block_swap = false # Use Pinned Memory for Block Swapping: Uses more system RAM but speeds up training. The speed up maybe significant depending on system settings. To work, go to Advanced Graphics settings in System > Display > Graphics as in tutorial video and disable Hardware-Accelerated GPU Scheduling and restart your PC. Only effective when blocks_to_swap > 0
64
+ block_swap_h2d_only = false # LoRA only; requires blocks_to_swap > 0 and gradient_checkpointing
65
+ block_swap_ring_size = 2 # 2 overlaps transfer/compute; 1 minimizes VRAM
66
+
67
+ # Flow Matching Settings
68
+ timestep_sampling = "qwen_shift" # Use Qwen-specific resolution-aware sampling
69
+ discrete_flow_shift = 2.2 # Discrete flow shift for training (used with 'shift' method)
70
+ flow_shift = 7.0 # [ADVANCED] Noise schedule control. 7.0 is optimal. Higher (8-10)=smoother/slower, Lower (5-6)=faster/unstable
71
+ weighting_scheme = "none" # Set to "mode" if you want to use mode_scale
72
+ logit_mean = 0.0
73
+ logit_std = 1.0
74
+ mode_scale = 1.0 # Optimized for Qwen (lower than SD3's 1.29 for better stability)
75
+
76
+ # Advanced Timestep Parameters (usually leave as defaults)
77
+ sigmoid_scale = 1.0 # Scale factor for sigmoid timestep sampling. Only used with 'sigmoid' method
78
+ min_timestep = 0 # 0 = no minimum constraint. 0-999 = constrain minimum timestep
79
+ max_timestep = 1000 # Maximum timestep value. 1000 = default (full range). 1-1000 = constrain maximum timestep
80
+ preserve_distribution_shape = false # Preserve original distribution when using min/max constraints
81
+
82
+ # Advanced Timestep Settings
83
+ num_timestep_buckets = 0 # 0 = disabled. 4-10 = bucketed sampling for uniform timestep distribution
84
+
85
+ # Debugging
86
+ show_timesteps = ""
87
+
88
+ # Training Settings
89
+ sdpa = true
90
+ flash_attn = false
91
+ sage_attn = false
92
+ xformers = false
93
+ flash3 = false # EXPERIMENTAL: FlashAttention 3, not confirmed to work with Qwen Image
94
+ split_attn = false # REQUIRED if using flash_attn/sage_attn/xformers/flash3
95
+ use_legacy_sdpa = false # Force the older PyTorch SDPA path instead of automatic verified acceleration
96
+ max_train_steps = 90000
97
+ max_train_epochs = 200
98
+ max_data_loader_n_workers = 2
99
+ persistent_data_loader_workers = true
100
+ seed = 99
101
+ gradient_checkpointing = true
102
+ gradient_accumulation_steps = 1
103
+ full_bf16 = false # [EXPERIMENTAL] Store gradients in BF16. Requires mixed_precision='bf16'; monitor loss for instability.
104
+ full_fp16 = false # [EXPERIMENTAL] Store gradients in FP16. Saves ~30% VRAM but risk of underflow. Use full_bf16 instead if possible
105
+
106
+ # Optimizer Settings
107
+ optimizer_type = "adamw8bit"
108
+ optimizer_args = [] # Additional optimizer arguments like ["weight_decay=0.01", "betas=0.9,0.999"]
109
+ learning_rate = 5e-5 # RECOMMENDED: Changed from 1e-4 to 5e-5 per official documentation update
110
+ max_grad_norm = 1.0
111
+ fused_backward_pass = true # [DREAMBOOT EXCLUSIVE] Advanced memory optimization for DreamBooth fine-tuning. Automatically enabled for DreamBooth mode, disabled for LoRA mode. Requires AdaFactor optimizer. Reduces VRAM during gradient computation
112
+ lr_scheduler = "constant"
113
+ lr_warmup_steps = 0 # 0 = no warmup. Integer = steps, float <1 = ratio of total steps
114
+ lr_decay_steps = 0 # 0 = no decay. Integer = steps, float <1 = ratio of total steps
115
+ lr_scheduler_num_cycles = 1
116
+ lr_scheduler_power = 1.0
117
+ lr_scheduler_timescale = 0 # 0 = auto (uses warmup steps). Advanced parameter
118
+ lr_scheduler_min_lr_ratio = 0.0 # 0.0 = can reach zero LR. 0.1 = minimum 10% of initial LR
119
+ lr_scheduler_type = ""
120
+ lr_scheduler_args = [] # Additional scheduler arguments like ["T_max=100"]
121
+
122
+ # Network Settings (LoRA Mode Only - Ignored in DreamBooth Mode)
123
+ no_metadata = false
124
+ network_weights = "" # [LORA ONLY] Path to pretrained LoRA weights to continue training
125
+ network_module = "networks.lora_qwen_image" # [AUTO-SET] Set to empty for DreamBooth, networks.lora_qwen_image for LoRA
126
+ network_dim = 128 # [LORA ONLY] Network dimension/rank. RECOMMENDED: 16 per official documentation
127
+ network_alpha = 128.0 # [LORA ONLY] Alpha for scaling. RECOMMENDED: Equal to network_dim for best results
128
+ network_dropout = 0.0 # [LORA ONLY] Dropout rate. 0.0 = no dropout, 0.1 = 10% dropout for regularization
129
+ # Additional network arguments. Supported options:
130
+ # - loraplus_lr_ratio=N: Enables LoRA+ with learning rate ratio for "up" matrices (e.g., "loraplus_lr_ratio=4")
131
+ # - exclude_patterns=["regex"]: Regex patterns to exclude modules from LoRA (default excludes ".*(_mod_).*")
132
+ # - include_patterns=["regex"]: Regex patterns to re-include excluded modules
133
+ # - verbose=true: Print detailed info about which modules are being trained
134
+ # Example: ["loraplus_lr_ratio=4", "verbose=true"]
135
+ network_args = []
136
+ training_comment = ""
137
+ dim_from_weights = false
138
+ scale_weight_norms = 0.0 # 0.0 = disabled. 1.0+ = scale weights to prevent exploding gradients
139
+ base_weights = "" # Path to LoRA weights to merge before training (empty = none)
140
+ base_weights_multiplier = 1.0 # Strength multiplier for base weights (1.0 = full strength)
141
+
142
+ # Save/Load Settings
143
+ output_dir = ""
144
+ output_name = "my-qwen-lora" # Base filename without .safetensors extension - musubi auto-adds it
145
+ resume = ""
146
+ save_precision = "bf16" # LoRA output dtype; BF16 keeps files about half the size of FP32
147
+ save_every_n_epochs = 10
148
+ save_every_n_steps = 0 # 0 = disabled. Positive integer = save every N steps
149
+ save_last_n_epochs = 0 # 0 = keep all. Positive integer = keep only last N epoch checkpoints
150
+ save_last_n_epochs_state = 0 # 0 = keep all. Positive integer = keep only last N epoch states
151
+ save_last_n_steps = 0 # 0 = keep all. Positive integer = keep only last N step checkpoints
152
+ save_last_n_steps_state = 0 # 0 = keep all. Positive integer = keep only last N step states
153
+ save_state = false
154
+ save_state_on_train_end = false
155
+ mem_eff_save = false # [DreamBooth Only] Dramatically reduces RAM usage during checkpoint saving (from ~40GB to ~20GB). Essential for low-RAM systems doing DreamBooth fine-tuning. Ignored for LoRA training. NOTE: Optimizer state saves still require full RAM
156
+
157
+ # Caching Settings - Latents
158
+ caching_latent_device = "cuda"
159
+ caching_latent_batch_size = 4
160
+ caching_latent_num_workers = 8
161
+ caching_latent_skip_existing = true
162
+ caching_latent_keep_cache = true
163
+ caching_latent_debug_mode = ""
164
+ caching_latent_console_width = 80
165
+ caching_latent_console_back = ""
166
+ caching_latent_console_num_images = 0 # 0 = no limit. Positive integer = max images in debug console
167
+
168
+ # Caching Settings - Text Encoder
169
+ caching_teo_text_encoder = ""
170
+ caching_teo_device = "cuda"
171
+ caching_teo_fp8_vl = false
172
+ caching_teo_batch_size = 16
173
+ caching_teo_num_workers = 8
174
+ caching_teo_skip_existing = true
175
+ caching_teo_keep_cache = true
176
+
177
+ # Torch compile (optional)
178
+ compile = false
179
+ compile_resident_blocks_only = true # Recommended: compile resident Qwen blocks; swapped blocks remain eager
180
+ compile_backend = "inductor"
181
+ compile_mode = "default"
182
+ compile_dynamic = "auto" # "auto" | "true" | "false"
183
+ compile_fullgraph = false
184
+ compile_cache_size_limit = 0 # 0 = use PyTorch default
185
+
186
+ # Accelerate Launch Settings
187
+ mixed_precision = "bf16" # RECOMMENDED for Qwen Image. fp16 may cause instability, fp8 not supported
188
+ multi_gpu = false # Enable distributed multi-GPU training
189
+ gpu_ids = "0" # GPU IDs for distributed training (e.g., "0,1,2,3")
190
+ num_processes = 1 # Number of processes for distributed training
191
+ num_machines = 1 # Number of machines for distributed training
192
+ num_cpu_threads_per_process = 2 # CPU threads per process
193
+ main_process_port = 0 # Port for distributed training communication (0 = auto)
194
+ dynamo_backend = "no" # no = disabled (recommended). Use inductor for PyTorch 2.0+ optimization
195
+ dynamo_mode = "" # Empty = default. Options: "default", "reduce-overhead", "max-autotune"
196
+ dynamo_use_fullgraph = false # Use fullgraph mode for dynamo
197
+ dynamo_use_dynamic = false # Use dynamic mode for dynamo
198
+ extra_accelerate_launch_args = "" # Additional accelerate launch arguments
199
+
200
+ # Logging Settings
201
+ logging_dir = ""
202
+ # log_with = "" # Leave commented out or set to specific logger like "tensorboard"
203
+ log_prefix = ""
204
+ log_tracker_name = ""
205
+ wandb_run_name = ""
206
+ log_tracker_config = ""
207
+ wandb_api_key = ""
208
+ log_config = false
209
+
210
+ # DDP Settings
211
+ ddp_timeout = 0 # 0 = use default (30min). Positive integer = timeout in minutes for distributed training
212
+ ddp_gradient_as_bucket_view = false
213
+ ddp_static_graph = false
214
+
215
+ # Sample Generation
216
+ # Generate sample images during training to monitor progress
217
+ sample_every_n_steps = 0 # 0 = disabled. 100-500 recommended for step-based sampling
218
+ sample_every_n_epochs = 0 # 0 = disabled. 1 = generate samples every epoch (recommended)
219
+ sample_at_first = false
220
+ sample_prompts = "" # Path to text file with prompts for sample generation
221
+ disable_prompt_enhancement = false # true = use prompt file exactly as written (no auto-added defaults)
222
+
223
+ # Default Sample Parameters
224
+ # These will be automatically added to prompts that don't specify them
225
+ # An enhanced prompt file will be saved to your output directory
226
+ sample_width = 1328 # Default width (Qwen optimal: 1328)
227
+ sample_height = 1328 # Default height (Qwen optimal: 1328)
228
+ sample_steps = 20 # Number of denoising steps
229
+ sample_guidance_scale = 1.0 # Legacy/compat guidance flag (--g). Qwen training sampling primarily uses --l.
230
+ sample_seed = 99 # Random seed (-1 = random each time)
231
+ sample_discrete_flow_shift = 2.2 # Discrete flow shift (0 = use training value, 2.2 = Qwen optimal)
232
+ sample_cfg_scale = 4.0 # Primary CFG scale (--l) for Qwen training samples. Set 1.0 to disable CFG.
233
+ sample_negative_prompt = "" # Default negative prompt for all samples
234
+
235
+ # Metadata Settings
236
+ metadata_author = ""
237
+ metadata_description = ""
238
+ metadata_license = ""
239
+ metadata_tags = ""
240
+ metadata_title = ""
241
+ metadata_reso = ""
242
+ metadata_arch = ""
243
+
244
+ # HuggingFace Settings
245
+ huggingface_repo_id = ""
246
+ huggingface_token = ""
247
+ huggingface_repo_type = ""
248
+ huggingface_repo_visibility = ""
249
+ huggingface_path_in_repo = ""
250
+ save_state_to_huggingface = false
251
+ resume_from_huggingface = ""
252
+ async_upload = false
SECourses_Musubi_Trainer/sitecustomize.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """Apply project-wide Python compatibility hooks in launched worker processes."""
2
+
3
+ import musubi_tuner_gui.torch_compat # noqa: F401
SECourses_Musubi_Trainer/tests/test_automagic_gui.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pytest
3
+
4
+ from musubi_tuner_gui.class_optimizer_and_scheduler import OptimizerAndScheduler
5
+ from musubi_tuner_gui.optimizer_catalog import (
6
+ AUTOMAGIC_OPTIMIZER_CHOICES,
7
+ add_automagic_optimizer_choices,
8
+ optimizer_guidance,
9
+ )
10
+ from musubi_tuner_gui.qwen_image_lora_gui import QwenImageOptimizerSettings
11
+
12
+
13
+ def dropdown_values(component):
14
+ return [value for _, value in component.choices]
15
+
16
+
17
+ def test_add_automagic_choices_preserves_defaults_and_avoids_duplicates():
18
+ choices = add_automagic_optimizer_choices(["AdamW", "automagic"])
19
+
20
+ assert choices[:2] == ["AdamW", "automagic"]
21
+ assert sum(choice.casefold() == "automagic" for choice in choices) == 1
22
+ assert {choice.casefold() for choice in choices} >= {choice.casefold() for choice in AUTOMAGIC_OPTIMIZER_CHOICES}
23
+
24
+
25
+ @pytest.mark.parametrize("optimizer_type", AUTOMAGIC_OPTIMIZER_CHOICES)
26
+ def test_automagic_guidance_explains_adaptive_lr_and_scheduler(optimizer_type):
27
+ guidance = optimizer_guidance(optimizer_type)
28
+
29
+ expected_version = "v1" if optimizer_type == "Automagic" else optimizer_type.replace("Automagic", "v")
30
+ assert expected_version in guidance
31
+ assert "starting rate" in guidance
32
+ assert "scheduler" in guidance.casefold()
33
+ assert "Fused Backward Pass" in guidance
34
+ assert "Adafactor-only preset arguments" in guidance
35
+ assert "ignored automatically" in guidance
36
+ assert "block swapping" in guidance.casefold()
37
+
38
+
39
+ def test_automagic2_guidance_explains_hard_compatibility_limits():
40
+ guidance = optimizer_guidance("Automagic2")
41
+
42
+ for expected in ("single-process", "Gradient Accumulation Steps = 1", "Max Gradient Norm = 0", "fp16"):
43
+ assert expected in guidance
44
+
45
+
46
+ def test_automagic3_guidance_explains_automatic_safe_mode():
47
+ guidance = optimizer_guidance("Automagic3")
48
+
49
+ assert "automatically" in guidance
50
+ assert "fused=False" in guidance
51
+ assert "fused=True" in guidance
52
+
53
+
54
+ @pytest.mark.parametrize(
55
+ ("component_factory", "selected"),
56
+ [
57
+ (lambda: OptimizerAndScheduler(config={"optimizer_type": "Automagic3"}), "Automagic3"),
58
+ (lambda: QwenImageOptimizerSettings(False, {"optimizer_type": "Automagic2"}), "Automagic2"),
59
+ ],
60
+ )
61
+ def test_all_optimizer_component_variants_expose_choices_and_initial_guidance(component_factory, selected):
62
+ with gr.Blocks():
63
+ component = component_factory()
64
+
65
+ values = dropdown_values(component.optimizer_type)
66
+ assert set(AUTOMAGIC_OPTIMIZER_CHOICES) <= set(values)
67
+ expected_version = "v1" if selected == "Automagic" else selected.replace("Automagic", "v")
68
+ assert expected_version in component.optimizer_guidance.value
69
+
70
+
71
+ def test_custom_optimizer_guidance_is_explicit():
72
+ guidance = optimizer_guidance("example.CustomOptimizer")
73
+
74
+ assert "Custom optimizer" in guidance
75
+ assert "example.CustomOptimizer" in guidance
SECourses_Musubi_Trainer/tests/test_full_finetune_gui.py ADDED
@@ -0,0 +1,875 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ from pathlib import Path
5
+ from types import SimpleNamespace
6
+
7
+ import gradio as gr
8
+ import pytest
9
+ import toml
10
+
11
+ from musubi_tuner_gui import (
12
+ flux2_lora_gui,
13
+ flux_klein_lora_gui,
14
+ flux_lora_gui,
15
+ modern_image_lora_gui,
16
+ qwen_image_lora_gui,
17
+ wan_lora_gui,
18
+ zimage_lora_gui,
19
+ )
20
+ from musubi_tuner_gui.full_finetune_gui import (
21
+ FULL_FINE_TUNING_MODE,
22
+ FULL_FINE_TUNING_NETWORK_KEYS,
23
+ LORA_TRAINING_MODE,
24
+ normalize_image_training_parameters,
25
+ training_mode_runtime_exclusions,
26
+ )
27
+ from musubi_tuner_gui.modern_image_lora_gui import (
28
+ ModernImageWorkflow,
29
+ _architecture_defaults,
30
+ _build_workflow_script,
31
+ get_architecture,
32
+ prepare_modern_image_workflow,
33
+ )
34
+ from musubi_tuner_gui.class_tab_config_manager import TabConfigManager
35
+
36
+
37
+ class _FakeExecutor:
38
+ def __init__(self):
39
+ self.calls = []
40
+
41
+ def execute_command(self, **kwargs):
42
+ self.calls.append(kwargs)
43
+
44
+
45
+ def _touch(path: Path, contents: str = "placeholder") -> str:
46
+ path.write_text(contents, encoding="utf-8")
47
+ return str(path)
48
+
49
+
50
+ def _ordered_parameters(keys: list[str], values: dict[str, object]) -> list[tuple[str, object]]:
51
+ return [(key, values.get(key)) for key in keys]
52
+
53
+
54
+ def _base_full_values(tmp_path: Path, keys: list[str], *, model_version: str) -> dict[str, object]:
55
+ dataset = _touch(tmp_path / "dataset.toml", "[[datasets]]\nimage_directory = 'images'\n")
56
+ values = {key: None for key in keys}
57
+ values.update(
58
+ {
59
+ "training_mode": FULL_FINE_TUNING_MODE,
60
+ "mixed_precision": "bf16",
61
+ "num_cpu_threads_per_process": 1,
62
+ "num_processes": 1,
63
+ "num_machines": 1,
64
+ "multi_gpu": False,
65
+ "gpu_ids": "0",
66
+ "dynamo_backend": "no",
67
+ "dataset_config_mode": "Use TOML File",
68
+ "dataset_config": dataset,
69
+ "model_version": model_version,
70
+ "dit": _touch(tmp_path / "dit.safetensors"),
71
+ "vae": _touch(tmp_path / "vae.safetensors"),
72
+ "text_encoder": _touch(tmp_path / "text_encoder.safetensors"),
73
+ "fp8_base": False,
74
+ "fp8_scaled": False,
75
+ "blocks_to_swap": 0,
76
+ "sdpa": True,
77
+ "use_legacy_sdpa": True,
78
+ "gradient_checkpointing": True,
79
+ "gradient_accumulation_steps": 1,
80
+ "full_bf16": True,
81
+ "full_fp16": False,
82
+ "fused_backward_pass": True,
83
+ "block_swap_optimizer_patch_params": False,
84
+ "optimizer_type": "AdaFactor",
85
+ "optimizer_args": [],
86
+ "learning_rate": 1e-5,
87
+ "max_grad_norm": 0,
88
+ "lr_scheduler": "constant",
89
+ "network_module": "networks.lora_flux_2",
90
+ "network_dim": 32,
91
+ "network_alpha": 32,
92
+ "network_dropout": 0,
93
+ "network_args": [],
94
+ "output_dir": str(tmp_path / "output"),
95
+ "output_name": "full-smoke",
96
+ "save_precision": "bf16",
97
+ "save_every_n_steps": 1,
98
+ "caching_latent_skip_existing": False,
99
+ "caching_teo_skip_existing": False,
100
+ }
101
+ )
102
+ return values
103
+
104
+
105
+ def test_shared_full_finetune_rules_remove_quantized_base_and_align_precision():
106
+ parameters = [
107
+ ("training_mode", "DreamBooth Fine-Tuning"),
108
+ ("mixed_precision", "bf16"),
109
+ ("full_bf16", True),
110
+ ("full_fp16", False),
111
+ ("fp8_base", True),
112
+ ("fp8_scaled", True),
113
+ ("block_swap_h2d_only", True),
114
+ ("dit_dtype", "float16"),
115
+ ("save_precision", "fp32"),
116
+ ("blocks_to_swap", 8),
117
+ ("num_processes", 1),
118
+ ("gradient_accumulation_steps", 1),
119
+ ("optimizer_type", "AdaFactor"),
120
+ ("fused_backward_pass", True),
121
+ ("block_swap_optimizer_patch_params", False),
122
+ ]
123
+
124
+ values, normalized, full_finetune = normalize_image_training_parameters(parameters)
125
+
126
+ assert full_finetune is True
127
+ assert values["training_mode"] == FULL_FINE_TUNING_MODE
128
+ assert values["fp8_base"] is False
129
+ assert values["fp8_scaled"] is False
130
+ assert values["block_swap_h2d_only"] is False
131
+ assert values["dit_dtype"] == "bfloat16"
132
+ assert values["save_precision"] == "bf16"
133
+ assert dict(normalized) == values
134
+
135
+
136
+ @pytest.mark.parametrize(
137
+ "overrides, message",
138
+ [
139
+ ({"full_fp16": True}, "Full FP16"),
140
+ ({"num_processes": 2, "blocks_to_swap": 1}, "multi-process"),
141
+ ({"optimizer_type": "AdamW", "fused_backward_pass": True}, "Adafactor"),
142
+ ({"gradient_accumulation_steps": 2, "fused_backward_pass": True}, "accumulation"),
143
+ ({"blocks_to_swap": 0, "block_swap_optimizer_patch_params": True}, "blocks_to_swap"),
144
+ (
145
+ {"blocks_to_swap": 1, "optimizer_type": "Automagic2", "block_swap_optimizer_patch_params": True},
146
+ "Automagic3",
147
+ ),
148
+ ],
149
+ )
150
+ def test_shared_full_finetune_rules_reject_unsupported_combinations(overrides, message):
151
+ values = {
152
+ "training_mode": FULL_FINE_TUNING_MODE,
153
+ "mixed_precision": "bf16",
154
+ "full_bf16": True,
155
+ "full_fp16": False,
156
+ "blocks_to_swap": 0,
157
+ "num_processes": 1,
158
+ "gradient_accumulation_steps": 1,
159
+ "optimizer_type": "AdaFactor",
160
+ "fused_backward_pass": False,
161
+ "block_swap_optimizer_patch_params": False,
162
+ }
163
+ values.update(overrides)
164
+
165
+ with pytest.raises(ValueError, match=message):
166
+ normalize_image_training_parameters(list(values.items()))
167
+
168
+
169
+ @pytest.mark.parametrize("optimizer_type", ["Automagic", "Automagic3"])
170
+ def test_full_finetune_block_swap_patch_accepts_non_fused_automagic(optimizer_type):
171
+ values = {
172
+ "training_mode": FULL_FINE_TUNING_MODE,
173
+ "mixed_precision": "bf16",
174
+ "full_bf16": True,
175
+ "full_fp16": False,
176
+ "blocks_to_swap": 1,
177
+ "num_processes": 1,
178
+ "gradient_accumulation_steps": 1,
179
+ "optimizer_type": optimizer_type,
180
+ "fused_backward_pass": False,
181
+ "block_swap_optimizer_patch_params": True,
182
+ }
183
+
184
+ normalized_values, normalized, full_finetune = normalize_image_training_parameters(list(values.items()))
185
+
186
+ assert full_finetune is True
187
+ assert normalized_values["block_swap_optimizer_patch_params"] is True
188
+ assert dict(normalized)["block_swap_optimizer_patch_params"] is True
189
+
190
+
191
+ def test_training_mode_exclusions_keep_runtime_configs_mode_correct():
192
+ full = training_mode_runtime_exclusions(FULL_FINE_TUNING_MODE)
193
+ lora = training_mode_runtime_exclusions(LORA_TRAINING_MODE)
194
+
195
+ assert {"network_module", "network_dim", "network_alpha", "full_fp16"} <= full
196
+ assert {"fused_backward_pass", "block_swap_optimizer_patch_params", "mem_eff_save"} <= lora
197
+ assert "network_module" not in lora
198
+
199
+
200
+ def test_qwen_dreambooth_preview_normalizes_full_model_runtime_config(tmp_path: Path, monkeypatch):
201
+ dataset = tmp_path / "dataset.toml"
202
+ dataset.write_text("[[datasets]]\nimage_directory = 'images'\n", encoding="utf-8")
203
+ dit = _touch(tmp_path / "dit.safetensors")
204
+ vae = _touch(tmp_path / "vae.safetensors")
205
+ text_encoder = _touch(tmp_path / "text_encoder.safetensors")
206
+ captured: dict[str, object] = {}
207
+
208
+ def capture_preview(command, config_path):
209
+ captured["command"] = command
210
+ captured["config"] = toml.load(config_path)
211
+
212
+ monkeypatch.setattr(qwen_image_lora_gui, "print_command_and_toml", capture_preview)
213
+ parameters = [
214
+ ("training_mode", "DreamBooth Fine-Tuning"),
215
+ ("dataset_config_mode", "Use TOML File"),
216
+ ("dataset_config", str(dataset)),
217
+ ("model_version", "original"),
218
+ ("dit", dit),
219
+ ("vae", vae),
220
+ ("text_encoder", text_encoder),
221
+ ("output_dir", str(tmp_path / "output")),
222
+ ("output_name", "qwen-full-preview"),
223
+ ("mixed_precision", "bf16"),
224
+ ("full_bf16", True),
225
+ ("full_fp16", False),
226
+ ("save_precision", "fp32"),
227
+ ("dit_dtype", "float16"),
228
+ ("fp8_base", True),
229
+ ("fp8_scaled", True),
230
+ ("block_swap_h2d_only", True),
231
+ ("block_swap_ring_size", 2),
232
+ ("blocks_to_swap", 6),
233
+ ("gradient_checkpointing", True),
234
+ ("gradient_accumulation_steps", 1),
235
+ ("num_processes", 1),
236
+ ("num_machines", 1),
237
+ ("num_cpu_threads_per_process", 1),
238
+ ("gpu_ids", "0"),
239
+ ("dynamo_backend", "no"),
240
+ ("optimizer_type", "Automagic3"),
241
+ ("optimizer_args", ["scale_parameter=False", "relative_step=False"]),
242
+ ("fused_backward_pass", False),
243
+ ("block_swap_optimizer_patch_params", False),
244
+ ("network_module", "networks.lora_qwen_image"),
245
+ ("network_dim", 32),
246
+ ("network_alpha", 32),
247
+ ("network_dropout", 0),
248
+ ("network_args", []),
249
+ ("sdpa", True),
250
+ ("additional_parameters", ""),
251
+ ("mem_eff_save", True),
252
+ ]
253
+
254
+ qwen_image_lora_gui.train_qwen_image_model(True, True, parameters)
255
+
256
+ command = captured["command"]
257
+ config = captured["config"]
258
+ assert any(str(part).endswith("qwen_image_train.py") for part in command)
259
+ assert not any(str(part).endswith("qwen_image_train_network.py") for part in command)
260
+ assert config.get("fp8_base", False) is False
261
+ assert config.get("fp8_scaled", False) is False
262
+ assert config.get("dit_dtype", "bfloat16") == "bfloat16"
263
+ assert config["save_precision"] == "bf16"
264
+ assert config["optimizer_type"] == "Automagic3"
265
+ assert config["mem_eff_save"] is True
266
+ assert not FULL_FINE_TUNING_NETWORK_KEYS.intersection(config)
267
+ assert "block_swap_h2d_only" not in config
268
+
269
+
270
+ def test_shipped_qwen_default_enables_resident_compile():
271
+ defaults_path = Path(__file__).resolve().parents[1] / "qwen_image_defaults.toml"
272
+
273
+ assert toml.load(defaults_path)["compile_resident_blocks_only"] is True
274
+
275
+
276
+ @pytest.mark.parametrize(
277
+ ("config", "expected"),
278
+ [
279
+ ({}, True),
280
+ ({"compile_resident_blocks_only": True}, True),
281
+ ({"compile_resident_blocks_only": False}, False),
282
+ ],
283
+ )
284
+ def test_qwen_resident_compile_default_preserves_config_override(config, expected):
285
+ with gr.Blocks():
286
+ model = qwen_image_lora_gui.QwenImageModel(headless=True, config=config)
287
+
288
+ assert model.compile_resident_blocks_only.value is expected
289
+
290
+
291
+ def test_qwen_resident_compile_callback_order_and_search_mapping_are_wired():
292
+ parameter_names = list(inspect.signature(qwen_image_lora_gui.qwen_image_gui_actions).parameters)
293
+ compile_start = parameter_names.index("compile")
294
+ assert parameter_names[compile_start : compile_start + 7] == [
295
+ "compile",
296
+ "compile_resident_blocks_only",
297
+ "compile_backend",
298
+ "compile_mode",
299
+ "compile_dynamic",
300
+ "compile_fullgraph",
301
+ "compile_cache_size_limit",
302
+ ]
303
+
304
+ tab_source = inspect.getsource(qwen_image_lora_gui.qwen_image_lora_tab)
305
+ component_names = [
306
+ "compile",
307
+ "compile_resident_blocks_only",
308
+ "compile_backend",
309
+ "compile_mode",
310
+ "compile_dynamic",
311
+ "compile_fullgraph",
312
+ "compile_cache_size_limit",
313
+ ]
314
+ positions = [tab_source.index(f"qwen_model.{name},") for name in component_names]
315
+ assert positions == sorted(positions)
316
+ assert (
317
+ '"compile_resident_blocks_only": ("Qwen Image Model Settings", "Compile Resident Blocks Only")'
318
+ in tab_source
319
+ )
320
+
321
+
322
+ @pytest.mark.parametrize("enabled", [True, False])
323
+ def test_qwen_resident_compile_persistent_config_round_trip(tmp_path: Path, enabled):
324
+ config_path = tmp_path / "qwen.toml"
325
+ parameters = [
326
+ ("training_mode", "LoRA Training"),
327
+ ("network_module", qwen_image_lora_gui.QWEN_IMAGE_NETWORK_MODULE),
328
+ ("fused_backward_pass", False),
329
+ ("compile_resident_blocks_only", enabled),
330
+ ]
331
+
332
+ qwen_image_lora_gui.save_qwen_image_configuration(False, str(config_path), parameters)
333
+
334
+ assert toml.load(config_path)["compile_resident_blocks_only"] is enabled
335
+ loaded = qwen_image_lora_gui.open_qwen_image_configuration(
336
+ False,
337
+ str(config_path),
338
+ [("compile_resident_blocks_only", not enabled)],
339
+ )
340
+ assert loaded[2] is enabled
341
+
342
+
343
+ @pytest.mark.parametrize("enabled", [True, False])
344
+ def test_qwen_resident_compile_reaches_training_preview_config(tmp_path: Path, monkeypatch, enabled):
345
+ dataset = tmp_path / "dataset.toml"
346
+ dataset.write_text("[[datasets]]\nimage_directory = 'images'\n", encoding="utf-8")
347
+ captured = {}
348
+
349
+ def capture_preview(command, config_path):
350
+ captured["command"] = command
351
+ captured["config"] = toml.load(config_path)
352
+
353
+ monkeypatch.setattr(qwen_image_lora_gui, "print_command_and_toml", capture_preview)
354
+ parameters = [
355
+ ("training_mode", "LoRA Training"),
356
+ ("dataset_config_mode", "Use TOML File"),
357
+ ("dataset_config", str(dataset)),
358
+ ("model_version", "original"),
359
+ ("dit", _touch(tmp_path / "dit.safetensors")),
360
+ ("vae", _touch(tmp_path / "vae.safetensors")),
361
+ ("text_encoder", _touch(tmp_path / "text_encoder.safetensors")),
362
+ ("output_dir", str(tmp_path / "output")),
363
+ ("output_name", f"qwen-resident-{enabled}"),
364
+ ("mixed_precision", "bf16"),
365
+ ("gradient_checkpointing", True),
366
+ ("blocks_to_swap", 6),
367
+ ("block_swap_h2d_only", False),
368
+ ("block_swap_ring_size", 2),
369
+ ("num_processes", 1),
370
+ ("num_machines", 1),
371
+ ("num_cpu_threads_per_process", 1),
372
+ ("gpu_ids", "0"),
373
+ ("dynamo_backend", "no"),
374
+ ("network_module", qwen_image_lora_gui.QWEN_IMAGE_NETWORK_MODULE),
375
+ ("network_dim", 16),
376
+ ("network_alpha", 16),
377
+ ("network_dropout", 0),
378
+ ("network_args", []),
379
+ ("compile", True),
380
+ ("compile_backend", "inductor"),
381
+ ("compile_mode", "default"),
382
+ ("compile_dynamic", "auto"),
383
+ ("compile_fullgraph", False),
384
+ ("compile_cache_size_limit", 0),
385
+ ("compile_resident_blocks_only", enabled),
386
+ ("sdpa", True),
387
+ ("additional_parameters", ""),
388
+ ]
389
+
390
+ qwen_image_lora_gui.train_qwen_image_model(True, True, parameters)
391
+
392
+ assert any(str(part).endswith("qwen_image_train_network.py") for part in captured["command"])
393
+ if enabled:
394
+ assert captured["config"]["compile_resident_blocks_only"] is True
395
+ else:
396
+ assert "compile_resident_blocks_only" not in captured["config"]
397
+
398
+
399
+ def test_zimage_dreambooth_preview_normalizes_full_model_runtime_config(tmp_path: Path, monkeypatch):
400
+ dataset = tmp_path / "dataset.toml"
401
+ dataset.write_text("[[datasets]]\nimage_directory = 'images'\n", encoding="utf-8")
402
+ captured: list[tuple[list[str], str]] = []
403
+ monkeypatch.setattr(
404
+ zimage_lora_gui,
405
+ "print_command_and_toml",
406
+ lambda command, config_path: captured.append((command, config_path)),
407
+ )
408
+ parameters = [
409
+ ("training_mode", "DreamBooth Fine-Tuning"),
410
+ ("dataset_config_mode", "Use TOML File"),
411
+ ("dataset_config", str(dataset)),
412
+ ("dit", _touch(tmp_path / "dit.safetensors")),
413
+ ("vae", _touch(tmp_path / "vae.safetensors")),
414
+ ("text_encoder", _touch(tmp_path / "text_encoder.safetensors")),
415
+ ("output_dir", str(tmp_path / "output")),
416
+ ("output_name", "zimage-full-preview"),
417
+ ("mixed_precision", "bf16"),
418
+ ("full_bf16", True),
419
+ ("full_fp16", False),
420
+ ("save_precision", "fp32"),
421
+ ("fp8_base", True),
422
+ ("fp8_scaled", True),
423
+ ("block_swap_h2d_only", True),
424
+ ("block_swap_ring_size", 2),
425
+ ("blocks_to_swap", 6),
426
+ ("gradient_checkpointing", True),
427
+ ("gradient_accumulation_steps", 1),
428
+ ("num_processes", 1),
429
+ ("num_machines", 1),
430
+ ("num_cpu_threads_per_process", 1),
431
+ ("gpu_ids", "0"),
432
+ ("dynamo_backend", "no"),
433
+ ("optimizer_type", "Automagic3"),
434
+ ("optimizer_args", []),
435
+ ("fused_backward_pass", False),
436
+ ("block_swap_optimizer_patch_params", False),
437
+ ("network_module", "networks.lora_zimage"),
438
+ ("network_dim", 32),
439
+ ("network_alpha", 32),
440
+ ("network_dropout", 0),
441
+ ("network_args", []),
442
+ ("base_weights", ["old-adapter.safetensors"]),
443
+ ("base_weights_multiplier", [1.0]),
444
+ ("sdpa", True),
445
+ ("caching_latent_skip_existing", False),
446
+ ("caching_teo_skip_existing", False),
447
+ ("additional_parameters", ""),
448
+ ("mem_eff_save", True),
449
+ ]
450
+
451
+ zimage_lora_gui.train_zimage_model(True, True, parameters)
452
+
453
+ command, config_path = captured[-1]
454
+ config = toml.load(config_path)
455
+ assert any(str(part).endswith("zimage_train.py") for part in command)
456
+ assert not any(str(part).endswith("zimage_train_network.py") for part in command)
457
+ assert config.get("fp8_base", False) is False
458
+ assert config.get("fp8_scaled", False) is False
459
+ assert config["save_precision"] == "bf16"
460
+ assert config["optimizer_type"] == "Automagic3"
461
+ assert config["mem_eff_save"] is True
462
+ assert not FULL_FINE_TUNING_NETWORK_KEYS.intersection(config)
463
+ assert "block_swap_h2d_only" not in config
464
+
465
+
466
+ def test_flux_accelerate_lookup_prefers_the_active_python_environment(tmp_path: Path, monkeypatch):
467
+ scripts = tmp_path / "venv" / "Scripts"
468
+ scripts.mkdir(parents=True)
469
+ python = scripts / "python.exe"
470
+ accelerate = scripts / "accelerate.exe"
471
+ python.touch()
472
+ accelerate.touch()
473
+ monkeypatch.setattr(flux2_lora_gui.shutil, "which", lambda _name: r"C:\Python310\Scripts\accelerate.exe")
474
+
475
+ command = flux2_lora_gui._find_accelerate_launch(str(python))
476
+
477
+ assert Path(command[0]) == accelerate
478
+ assert command[1] == "launch"
479
+
480
+
481
+ def test_custom_config_is_isolated_between_gui_tabs(tmp_path: Path):
482
+ config_path = tmp_path / "custom.toml"
483
+ config_path.write_text('training_mode = "Full Fine-Tuning"\n[nested]\nvalue = 1\n', encoding="utf-8")
484
+ manager = TabConfigManager(str(config_path))
485
+
486
+ wan_config = manager.get_config_for_tab("wan")
487
+ flux_config = manager.get_config_for_tab("flux")
488
+ wan_config.config["max_timestep"] = 0
489
+ wan_config.config["nested"]["value"] = 2
490
+
491
+ assert wan_config is not flux_config
492
+ assert "max_timestep" not in flux_config.config
493
+ assert flux_config.config["nested"]["value"] == 1
494
+ assert "max_timestep" not in manager.base_config.config
495
+
496
+
497
+ @pytest.mark.parametrize(
498
+ "spec_key, expected_script",
499
+ [("ideogram4", "ideogram4_train.py"), ("krea2", "krea2_train.py")],
500
+ )
501
+ def test_modern_full_finetune_workflow_selects_full_trainer_and_strips_lora(
502
+ tmp_path: Path,
503
+ spec_key: str,
504
+ expected_script: str,
505
+ ):
506
+ spec = get_architecture(spec_key)
507
+ values = _architecture_defaults(spec)
508
+ values.update(
509
+ {
510
+ "training_mode": FULL_FINE_TUNING_MODE,
511
+ "mixed_precision": "bf16",
512
+ "full_bf16": True,
513
+ "full_fp16": False,
514
+ "fused_backward_pass": True,
515
+ "block_swap_optimizer_patch_params": False,
516
+ "optimizer_type": "AdaFactor",
517
+ "gradient_accumulation_steps": 1,
518
+ "fp8_base": True,
519
+ "fp8_scaled": True,
520
+ "block_swap_h2d_only": True,
521
+ "use_legacy_sdpa": True,
522
+ "dataset_config": _touch(tmp_path / "dataset.toml"),
523
+ "dit": _touch(tmp_path / "dit.safetensors"),
524
+ "vae": _touch(tmp_path / "vae.safetensors"),
525
+ "text_encoder": _touch(tmp_path / "text_encoder.safetensors"),
526
+ "output_dir": str(tmp_path / "output"),
527
+ "output_name": "modern-full",
528
+ "save_precision": "bf16",
529
+ "dit_variant": "raw",
530
+ "turbo_dit": "",
531
+ "turbo_dit_cache": False,
532
+ "blocks_to_swap": 32 if spec.is_ideogram else spec.max_blocks_to_swap,
533
+ }
534
+ )
535
+ config_path = tmp_path / "runtime.toml"
536
+
537
+ workflow = prepare_modern_image_workflow(
538
+ spec_key,
539
+ list(values.items()),
540
+ str(config_path),
541
+ python_cmd="python",
542
+ )
543
+ runtime = toml.load(config_path)
544
+
545
+ assert Path(workflow.train_command[-3]).name == expected_script
546
+ assert workflow.train_command[-2:] == ["--config_file", str(config_path)]
547
+ assert runtime["full_bf16"] is True
548
+ assert runtime["fused_backward_pass"] is True
549
+ assert runtime["use_legacy_sdpa"] is True
550
+ assert runtime["save_precision"] == "bf16"
551
+ assert "network_module" not in runtime
552
+ assert "network_dim" not in runtime
553
+ assert "fp8_base" not in runtime
554
+ assert "block_swap_h2d_only" not in runtime
555
+
556
+
557
+ @pytest.mark.parametrize("spec_key", ["ideogram4", "krea2"])
558
+ def test_modern_legacy_sdpa_persists_in_runtime_config(tmp_path: Path, spec_key: str):
559
+ spec = get_architecture(spec_key)
560
+ values = _architecture_defaults(spec)
561
+ values.update(
562
+ {
563
+ "dataset_config": _touch(tmp_path / "dataset.toml"),
564
+ "dit": _touch(tmp_path / "dit.safetensors"),
565
+ "vae": _touch(tmp_path / "vae.safetensors"),
566
+ "text_encoder": _touch(tmp_path / "text_encoder.safetensors"),
567
+ "output_dir": str(tmp_path / "output"),
568
+ "output_name": "legacy-sdpa",
569
+ "use_legacy_sdpa": True,
570
+ }
571
+ )
572
+ config_path = tmp_path / "runtime.toml"
573
+
574
+ workflow = prepare_modern_image_workflow(spec_key, list(values.items()), str(config_path), python_cmd="python")
575
+ runtime = toml.load(config_path)
576
+
577
+ assert dict(workflow.parameters)["use_legacy_sdpa"] is True
578
+ assert runtime["use_legacy_sdpa"] is True
579
+ assert _architecture_defaults(spec)["use_legacy_sdpa"] is False
580
+
581
+
582
+ @pytest.mark.parametrize(
583
+ "operating_system",
584
+ ["Windows", "Linux"],
585
+ )
586
+ def test_workflow_script_does_not_mutate_attention_environment(tmp_path: Path, monkeypatch, operating_system):
587
+ monkeypatch.setattr(modern_image_lora_gui.platform, "system", lambda: operating_system)
588
+ workflow = ModernImageWorkflow(
589
+ parameters=[("use_legacy_sdpa", True)],
590
+ config_path=str(tmp_path / "runtime.toml"),
591
+ latent_cache_command=None,
592
+ text_cache_command=None,
593
+ train_command=["python", "train.py"],
594
+ )
595
+
596
+ script_path, content = _build_workflow_script(get_architecture("krea2"), workflow)
597
+ Path(script_path).unlink()
598
+
599
+ assert "MUSUBI_DISABLE_EXTERNAL_FLASH_SDPA" not in content
600
+
601
+
602
+ @pytest.mark.parametrize(
603
+ "module, trainer, keys, model_version, model_family",
604
+ [
605
+ (flux2_lora_gui, flux2_lora_gui.train_flux2_model, flux2_lora_gui.FLUX2_PARAM_KEYS, "dev", None),
606
+ (
607
+ flux_klein_lora_gui,
608
+ flux_klein_lora_gui.train_flux_klein_model,
609
+ flux2_lora_gui.FLUX2_PARAM_KEYS,
610
+ "klein-base-4b",
611
+ None,
612
+ ),
613
+ (flux_lora_gui, flux_lora_gui.train_flux_model, flux_lora_gui.FLUX_PARAM_KEYS, "dev", "FLUX.2"),
614
+ (
615
+ flux_lora_gui,
616
+ flux_lora_gui.train_flux_model,
617
+ flux_lora_gui.FLUX_PARAM_KEYS,
618
+ "klein-base-4b",
619
+ "FLUX Klein",
620
+ ),
621
+ ],
622
+ )
623
+ def test_flux_full_finetune_runtime_uses_full_script_and_valid_config(
624
+ tmp_path: Path,
625
+ monkeypatch,
626
+ module,
627
+ trainer,
628
+ keys: list[str],
629
+ model_version: str,
630
+ model_family: str | None,
631
+ ):
632
+ values = _base_full_values(tmp_path, keys, model_version=model_version)
633
+ if model_family:
634
+ values["model_family"] = model_family
635
+ fake_executor = _FakeExecutor()
636
+ monkeypatch.setattr(module, "executor", fake_executor)
637
+ monkeypatch.setattr(module, "save_executed_script", lambda **_kwargs: None)
638
+ monkeypatch.setattr(module, "setup_environment", lambda **_kwargs: {})
639
+
640
+ trainer(
641
+ headless=True,
642
+ print_only=False,
643
+ parameters=_ordered_parameters(keys, values),
644
+ )
645
+
646
+ assert len(fake_executor.calls) == 1
647
+ command = fake_executor.calls[0]["run_cmd"]
648
+ assert any(Path(str(part)).name == "flux_2_train.py" for part in command)
649
+ runtime_files = list((tmp_path / "output").glob("full-smoke_*.toml"))
650
+ assert len(runtime_files) == 1
651
+ runtime = toml.load(runtime_files[0])
652
+ assert runtime["full_bf16"] is True
653
+ assert runtime["fused_backward_pass"] is True
654
+ assert runtime["use_legacy_sdpa"] is True
655
+ assert runtime["save_precision"] == "bf16"
656
+ assert "training_mode" not in runtime
657
+ assert "network_module" not in runtime
658
+ assert "network_dim" not in runtime
659
+
660
+
661
+ def test_wan_compile_callback_parameter_order_includes_residency_control():
662
+ assert wan_lora_gui.WAN_COMPILE_PARAMETER_NAMES == (
663
+ "compile",
664
+ "compile_resident_blocks_only",
665
+ "compile_backend",
666
+ "compile_mode",
667
+ "compile_dynamic",
668
+ "compile_fullgraph",
669
+ "compile_cache_size_limit",
670
+ )
671
+
672
+
673
+ @pytest.mark.parametrize(
674
+ ("task", "expected"),
675
+ [
676
+ ("t2v-A14B", True),
677
+ ("i2v-A14B", True),
678
+ ("t2v-14B", False),
679
+ ("i2v-14B", False),
680
+ ],
681
+ )
682
+ def test_wan_compile_residency_default_is_wan22_only(task: str, expected: bool):
683
+ assert wan_lora_gui.wan_compile_resident_blocks_default(task) is expected
684
+
685
+
686
+ @pytest.mark.parametrize(
687
+ ("task", "explicit_value", "expected"),
688
+ [
689
+ ("t2v-A14B", None, True),
690
+ ("t2v-14B", None, False),
691
+ ("t2v-A14B", False, False),
692
+ ("t2v-14B", True, True),
693
+ ],
694
+ )
695
+ def test_wan_model_settings_control_uses_task_aware_compile_default(
696
+ task: str,
697
+ explicit_value: bool | None,
698
+ expected: bool,
699
+ ):
700
+ values = {"task": task}
701
+ if explicit_value is not None:
702
+ values["compile_resident_blocks_only"] = explicit_value
703
+ config = SimpleNamespace(config=values, get=values.get)
704
+
705
+ with gr.Blocks():
706
+ settings = wan_lora_gui.WanModelSettings(headless=True, config=config)
707
+
708
+ assert settings.compile_resident_blocks_only.value is expected
709
+ assert settings.compile_resident_blocks_only_overridden.value is (
710
+ explicit_value is not None
711
+ )
712
+
713
+
714
+ @pytest.mark.parametrize(
715
+ ("task", "explicit_value"),
716
+ [
717
+ ("t2v-A14B", False),
718
+ ("t2v-14B", True),
719
+ ],
720
+ )
721
+ def test_wan_compile_residency_default_preserves_explicit_override(
722
+ task: str,
723
+ explicit_value: bool,
724
+ ):
725
+ parameters = [
726
+ ("task", task),
727
+ ("compile_resident_blocks_only", explicit_value),
728
+ ]
729
+
730
+ normalized = wan_lora_gui.apply_wan_compile_residency_default(parameters)
731
+
732
+ assert dict(normalized)["compile_resident_blocks_only"] is explicit_value
733
+ assert sum(key == "compile_resident_blocks_only" for key, _ in normalized) == 1
734
+
735
+
736
+ @pytest.mark.parametrize(
737
+ ("task", "configured_value", "expected"),
738
+ [
739
+ ("t2v-A14B", None, True),
740
+ ("t2v-14B", None, False),
741
+ ("t2v-A14B", False, False),
742
+ ("t2v-14B", True, True),
743
+ ],
744
+ )
745
+ def test_wan_load_config_uses_task_compile_default_only_when_missing(
746
+ tmp_path: Path,
747
+ monkeypatch: pytest.MonkeyPatch,
748
+ task: str,
749
+ configured_value: bool | None,
750
+ expected: bool,
751
+ ):
752
+ monkeypatch.setattr(wan_lora_gui.gr, "Info", lambda *_args, **_kwargs: None)
753
+ config_path = tmp_path / "wan.toml"
754
+ config = {"task": task}
755
+ if configured_value is not None:
756
+ config["compile_resident_blocks_only"] = configured_value
757
+ config_path.write_text(toml.dumps(config), encoding="utf-8")
758
+
759
+ result = wan_lora_gui.open_wan_configuration(
760
+ False,
761
+ str(config_path),
762
+ [
763
+ ("task", "t2v-14B"),
764
+ ("compile_resident_blocks_only", False),
765
+ ],
766
+ )
767
+
768
+ assert result[2] == task
769
+ assert result[3] is expected
770
+ assert wan_lora_gui.wan_config_has_compile_residency_override(config_path) is (
771
+ configured_value is not None
772
+ )
773
+
774
+
775
+ @pytest.mark.parametrize(
776
+ ("task", "explicit_value", "expected"),
777
+ [
778
+ ("t2v-A14B", None, True),
779
+ ("t2v-14B", None, False),
780
+ ("t2v-A14B", False, False),
781
+ ("t2v-14B", True, True),
782
+ ],
783
+ )
784
+ def test_wan_training_preview_serializes_effective_compile_residency(
785
+ tmp_path: Path,
786
+ monkeypatch: pytest.MonkeyPatch,
787
+ task: str,
788
+ explicit_value: bool | None,
789
+ expected: bool,
790
+ ):
791
+ captured: list[str] = []
792
+ monkeypatch.setattr(
793
+ wan_lora_gui,
794
+ "print_command_and_toml",
795
+ lambda _command, config_path: captured.append(config_path) if config_path else None,
796
+ )
797
+
798
+ dataset = tmp_path / "dataset.toml"
799
+ dataset.write_text("[[datasets]]\nimage_directory = 'images'\n", encoding="utf-8")
800
+ parameters = [
801
+ ("training_mode", "LoRA Training"),
802
+ ("task", task),
803
+ ("dataset_config_mode", "Use TOML File"),
804
+ ("dataset_config", str(dataset)),
805
+ ("dit", str(tmp_path / "dit.safetensors")),
806
+ ("vae", str(tmp_path / "vae.safetensors")),
807
+ ("t5", str(tmp_path / "t5.safetensors")),
808
+ ("clip", str(tmp_path / "clip.safetensors")),
809
+ ("output_name", "wan-compile-default"),
810
+ ("network_module", "networks.lora_wan"),
811
+ ("compile", True),
812
+ ("compile_backend", "inductor"),
813
+ ("compile_mode", "default"),
814
+ ("compile_dynamic", "auto"),
815
+ ("caching_latent_skip_existing", False),
816
+ ("caching_teo_skip_existing", False),
817
+ ("dynamo_backend", "no"),
818
+ ("additional_parameters", ""),
819
+ ]
820
+ if explicit_value is not None:
821
+ parameters.append(("compile_resident_blocks_only", explicit_value))
822
+
823
+ wan_lora_gui.train_wan_model(True, True, parameters)
824
+
825
+ assert captured
826
+ runtime_config = toml.load(captured[-1])
827
+ if expected:
828
+ assert runtime_config["compile_resident_blocks_only"] is True
829
+ else:
830
+ assert "compile_resident_blocks_only" not in runtime_config
831
+
832
+
833
+ def test_wan_saved_gui_config_keeps_explicit_compile_residency_override(
834
+ tmp_path: Path,
835
+ monkeypatch: pytest.MonkeyPatch,
836
+ ):
837
+ monkeypatch.setattr(wan_lora_gui.gr, "Info", lambda *_args, **_kwargs: None)
838
+ config_path = tmp_path / "wan-explicit.toml"
839
+
840
+ wan_lora_gui.save_wan_configuration(
841
+ False,
842
+ str(config_path),
843
+ [
844
+ ("training_mode", "LoRA Training"),
845
+ ("task", "t2v-A14B"),
846
+ ("compile_resident_blocks_only", False),
847
+ ],
848
+ )
849
+
850
+ saved = toml.load(config_path)
851
+ assert saved["compile_resident_blocks_only"] is False
852
+
853
+
854
+ @pytest.mark.parametrize(
855
+ ("task", "current_value", "overridden", "expected"),
856
+ [
857
+ ("t2v-A14B", False, False, True),
858
+ ("t2v-14B", True, False, False),
859
+ ("t2v-A14B", False, True, False),
860
+ ("t2v-14B", True, True, True),
861
+ ],
862
+ )
863
+ def test_wan_task_switch_updates_only_automatic_compile_default(
864
+ task: str,
865
+ current_value: bool,
866
+ overridden: bool,
867
+ expected: bool,
868
+ ):
869
+ result = wan_lora_gui.WanModelSettings._update_compile_residency_default(
870
+ task,
871
+ current_value,
872
+ overridden,
873
+ )
874
+
875
+ assert result is expected
SECourses_Musubi_Trainer/tests/test_model_quantizer_gui.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import io
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import musubi_tuner_gui.model_quantizer_gui as model_quantizer_gui
7
+ import pytest
8
+
9
+ from musubi_tuner_gui.common_gui import utf8_subprocess_options
10
+ from musubi_tuner_gui.model_quantizer_gui import (
11
+ MODEL_PRESET_NONE,
12
+ MODEL_PRESET_PRIMARY_CHOICES,
13
+ PRESET_INT8_CONVROT_HQ,
14
+ QUANT_FORMAT_INT8,
15
+ WORKFLOW_QUANTIZE,
16
+ ModelQuantizer,
17
+ _combined_preset_settings,
18
+ _model_preset_filters,
19
+ _model_preset_label,
20
+ _model_preset_value,
21
+ )
22
+
23
+
24
+ LTX_2_3_LABEL = "LTX 2.3 (INT8 ConvRot Learned HQ)"
25
+
26
+
27
+ def _flag_value(command, flag):
28
+ return command[command.index(flag) + 1]
29
+
30
+
31
+ def test_ltx_2_3_hq_is_a_distinct_primary_model_preset():
32
+ assert _model_preset_label("ltx2_3") == LTX_2_3_LABEL
33
+ assert _model_preset_value(LTX_2_3_LABEL) == "ltx2_3"
34
+ assert LTX_2_3_LABEL in MODEL_PRESET_PRIMARY_CHOICES
35
+
36
+ # Preserve the legacy combined preset and its stored label.
37
+ assert _model_preset_value("LTX (2 / 2.3)") == "ltxv2"
38
+ assert _model_preset_value(MODEL_PRESET_NONE) == MODEL_PRESET_NONE
39
+
40
+
41
+ def test_ltx_2_3_hq_resolves_the_learned_fixed_convrot_recipe():
42
+ effective_preset, settings = _combined_preset_settings(
43
+ "ltx2_3",
44
+ None,
45
+ use_model_default_preset=True,
46
+ )
47
+
48
+ assert effective_preset == PRESET_INT8_CONVROT_HQ
49
+ assert settings["quant_format"] == QUANT_FORMAT_INT8
50
+ assert settings["comfy_quant"] is True
51
+ assert settings["scaling_mode"] == "row"
52
+ assert settings["block_size"] == 128
53
+ assert settings["convrot"] is True
54
+ assert settings["convrot_group_size"] == 256
55
+ assert settings["dynamic_convrot"] is False
56
+ assert settings["simple"] is False
57
+ assert settings["calib_samples"] == 2048
58
+ assert settings["optimizer"] == "prodigy"
59
+ assert settings["num_iter"] == 2000
60
+ assert settings["lr"] == 1.0
61
+ assert settings["lr_schedule"] == "adaptive"
62
+ assert settings["lr_factor"] == 0.965
63
+ assert settings["lr_cooldown"] == 1
64
+ assert settings["top_p"] == 0.2
65
+ assert settings["min_k"] == 128
66
+ assert settings["max_k"] == 1280
67
+ assert settings["scale_optimization"] == "fixed"
68
+ assert settings["scale_refinement_rounds"] == 1
69
+ assert settings["full_matrix"] is False
70
+ assert settings["full_precision_matrix_mult"] is False
71
+ assert settings["low_memory"] is True
72
+ assert settings["save_quant_metadata"] is True
73
+ assert _model_preset_filters("ltx2_3") == {"ltx2_3"}
74
+
75
+
76
+ def test_ltx_2_3_hq_command_uses_native_convrot_and_ignores_layer_config():
77
+ _, params = _combined_preset_settings(
78
+ "ltx2_3",
79
+ None,
80
+ use_model_default_preset=True,
81
+ )
82
+ params.update(
83
+ {
84
+ "workflow": WORKFLOW_QUANTIZE,
85
+ "model_preset": "ltx2_3",
86
+ "model_filters": {"ltx2_3": True},
87
+ "layer_config_path": "stale-layer-config.json",
88
+ "layer_config_fullmatch": True,
89
+ }
90
+ )
91
+
92
+ command = ModelQuantizer(headless=True, config=None)._build_command(
93
+ "ltx-2.3-22b-distilled-1.1.safetensors",
94
+ "ltx-2.3-22b-distilled-1.1-int8-convrot-hq.safetensors",
95
+ params,
96
+ )
97
+
98
+ assert "--comfy_quant" in command
99
+ assert "--int8" in command
100
+ assert "--convrot" in command
101
+ assert _flag_value(command, "--convrot-group-size") == "256"
102
+ assert _flag_value(command, "--scaling_mode") == "row"
103
+ assert _flag_value(command, "--block_size") == "128"
104
+ assert _flag_value(command, "--calib_samples") == "2048"
105
+ assert _flag_value(command, "--optimizer") == "prodigy"
106
+ assert _flag_value(command, "--num_iter") == "2000"
107
+ assert _flag_value(command, "--scale-refinement") == "1"
108
+ assert _flag_value(command, "--scale-optimization") == "fixed"
109
+ assert "--ltx2_3" in command
110
+ assert "--simple" not in command
111
+ assert "--dynamic-convrot" not in command
112
+ assert "--layer-config" not in command
113
+ assert "--fullmatch" not in command
114
+
115
+
116
+ def test_manual_no_model_preset_keeps_custom_layer_config_without_model_filter():
117
+ command = ModelQuantizer(headless=True, config=None)._build_command(
118
+ "model.safetensors",
119
+ "model-int8.safetensors",
120
+ {
121
+ "workflow": WORKFLOW_QUANTIZE,
122
+ "model_preset": MODEL_PRESET_NONE,
123
+ "model_filters": {},
124
+ "quant_format": QUANT_FORMAT_INT8,
125
+ "layer_config_path": "custom-layer-config.json",
126
+ "layer_config_fullmatch": True,
127
+ },
128
+ )
129
+
130
+ assert "--int8" in command
131
+ assert _flag_value(command, "--layer-config") == "custom-layer-config.json"
132
+ assert "--fullmatch" in command
133
+ assert "--ltx2_3" not in command
134
+
135
+
136
+ def test_utf8_subprocess_options_override_host_locale_without_mutating_input():
137
+ original_env = {
138
+ "PYTHONIOENCODING": "cp1252",
139
+ "PYTHONUTF8": "0",
140
+ "KEEP_ME": "yes",
141
+ }
142
+
143
+ options = utf8_subprocess_options(original_env)
144
+
145
+ assert original_env["PYTHONIOENCODING"] == "cp1252"
146
+ assert options["text"] is True
147
+ assert options["encoding"] == "utf-8"
148
+ assert options["errors"] == "replace"
149
+ assert options["env"]["PYTHONIOENCODING"] == "utf-8:backslashreplace"
150
+ assert options["env"]["PYTHONUTF8"] == "1"
151
+ assert options["env"]["KEEP_ME"] == "yes"
152
+
153
+
154
+ def test_progress_output_survives_non_utf8_console(monkeypatch):
155
+ buffer = io.BytesIO()
156
+ stream = io.TextIOWrapper(buffer, encoding="cp1252", errors="strict")
157
+
158
+ with monkeypatch.context() as patch:
159
+ patch.setattr(sys, "stdout", stream)
160
+ ModelQuantizer._write_stdout(f"progress {chr(0x258F)}")
161
+
162
+ assert buffer.getvalue() == b"progress \\u258f"
163
+
164
+
165
+ def test_all_gui_text_subprocesses_declare_a_non_throwing_decoder():
166
+ gui_root = Path(model_quantizer_gui.__file__).parent
167
+ missing_policy = []
168
+
169
+ for source_path in gui_root.glob("*.py"):
170
+ tree = ast.parse(source_path.read_text(encoding="utf-8"), filename=str(source_path))
171
+ for node in ast.walk(tree):
172
+ if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):
173
+ continue
174
+ if not isinstance(node.func.value, ast.Name) or node.func.value.id != "subprocess":
175
+ continue
176
+
177
+ keyword_values = {keyword.arg: keyword.value for keyword in node.keywords if keyword.arg}
178
+ if node.func.attr == "Popen":
179
+ stdout = keyword_values.get("stdout")
180
+ captures_stdout = (
181
+ isinstance(stdout, ast.Attribute)
182
+ and isinstance(stdout.value, ast.Name)
183
+ and stdout.value.id == "subprocess"
184
+ and stdout.attr == "PIPE"
185
+ )
186
+ if not captures_stdout:
187
+ continue
188
+ uses_shared_policy = any(
189
+ keyword.arg is None
190
+ and isinstance(keyword.value, ast.Call)
191
+ and isinstance(keyword.value.func, ast.Name)
192
+ and keyword.value.func.id == "utf8_subprocess_options"
193
+ for keyword in node.keywords
194
+ )
195
+ if not uses_shared_policy:
196
+ missing_policy.append(f"{source_path.name}:{node.lineno}")
197
+ elif node.func.attr == "run":
198
+ text_mode = isinstance(keyword_values.get("text"), ast.Constant) and keyword_values["text"].value is True
199
+ captures_output = (
200
+ isinstance(keyword_values.get("capture_output"), ast.Constant)
201
+ and keyword_values["capture_output"].value is True
202
+ )
203
+ if text_mode and captures_output and "errors" not in keyword_values:
204
+ missing_policy.append(f"{source_path.name}:{node.lineno}")
205
+
206
+ assert missing_policy == []
207
+
208
+
209
+ @pytest.mark.parametrize(
210
+ "config",
211
+ [None, object()],
212
+ ids=["manual-no-config", "config-driven"],
213
+ )
214
+ def test_run_command_decodes_utf8_and_invalid_bytes_from_real_subprocess(monkeypatch, config):
215
+ monkeypatch.setattr(model_quantizer_gui, "save_executed_script", lambda **_kwargs: None)
216
+ command = [
217
+ sys.executable,
218
+ "-c",
219
+ "import sys; sys.stdout.buffer.write(b'Optimizing (AdaRound-prodigy-adaptive): 1%|\\xe2\\x96\\x8f| 16/2000\\nNative byte: \\xff\\n')",
220
+ ]
221
+
222
+ output, return_code = ModelQuantizer(headless=True, config=config)._run_command(
223
+ command,
224
+ "single_process",
225
+ "UTF-8 subprocess regression",
226
+ )
227
+
228
+ assert return_code == 0
229
+ assert output.splitlines() == [
230
+ f"Optimizing (AdaRound-prodigy-adaptive): 1%|{chr(0x258F)}| 16/2000",
231
+ f"Native byte: {chr(0xFFFD)}",
232
+ ]
SECourses_Musubi_Trainer/tmp_quantizer_expected.json ADDED
@@ -0,0 +1,2066 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fields": [
3
+ "quant_format",
4
+ "comfy_quant",
5
+ "full_precision_matrix_mult",
6
+ "scaling_mode",
7
+ "block_size",
8
+ "include_input_scale",
9
+ "convrot",
10
+ "convrot_group_size",
11
+ "exclude_layers",
12
+ "custom_type",
13
+ "custom_block_size",
14
+ "custom_scaling_mode",
15
+ "custom_simple",
16
+ "custom_heur",
17
+ "fallback_type",
18
+ "fallback_block_size",
19
+ "fallback_simple",
20
+ "simple",
21
+ "skip_inefficient_layers",
22
+ "full_matrix",
23
+ "calib_samples",
24
+ "manual_seed",
25
+ "optimizer",
26
+ "num_iter",
27
+ "lr",
28
+ "lr_schedule",
29
+ "top_p",
30
+ "min_k",
31
+ "max_k",
32
+ "lr_gamma",
33
+ "lr_patience",
34
+ "lr_factor",
35
+ "lr_min",
36
+ "lr_cooldown",
37
+ "lr_threshold",
38
+ "lr_adaptive_mode",
39
+ "lr_shape_influence",
40
+ "lr_threshold_mode",
41
+ "early_stop_loss",
42
+ "early_stop_lr",
43
+ "early_stop_stall",
44
+ "scale_optimization",
45
+ "scale_refinement_rounds",
46
+ "layer_config_path",
47
+ "layer_config_fullmatch",
48
+ "verbose",
49
+ "low_memory",
50
+ "save_quant_metadata"
51
+ ],
52
+ "quality": {
53
+ "0": {
54
+ "label": "Custom (manual)",
55
+ "settings": {}
56
+ },
57
+ "1": {
58
+ "label": "Fast (Simple Quantization)",
59
+ "settings": {
60
+ "calib_samples": 1024,
61
+ "optimizer": "original",
62
+ "num_iter": 200,
63
+ "lr": 0.008077300000003,
64
+ "lr_schedule": "adaptive",
65
+ "top_p": 0.02,
66
+ "min_k": 16,
67
+ "max_k": 64,
68
+ "lr_gamma": 0.99,
69
+ "lr_patience": 1,
70
+ "lr_factor": 0.95,
71
+ "lr_min": 1e-08,
72
+ "lr_cooldown": 0,
73
+ "lr_threshold": 0.0,
74
+ "lr_adaptive_mode": "simple-reset",
75
+ "lr_shape_influence": 1.0,
76
+ "lr_threshold_mode": "rel",
77
+ "early_stop_loss": 5e-09,
78
+ "early_stop_lr": 1.01e-08,
79
+ "early_stop_stall": 2000,
80
+ "quant_format": "FP8 (E4M3)",
81
+ "comfy_quant": true,
82
+ "full_precision_matrix_mult": false,
83
+ "scaling_mode": "tensor",
84
+ "block_size": null,
85
+ "convrot": false,
86
+ "convrot_group_size": 256,
87
+ "exclude_layers": "^(first|last|tmlp|tproj|txtmlp|img_in|final_layer|time_embed|time_mod_proj)([.]|$)|^(txtfusion|text_fusion)[.]projector([.]|$)",
88
+ "custom_type": null,
89
+ "custom_block_size": null,
90
+ "custom_scaling_mode": null,
91
+ "custom_simple": false,
92
+ "custom_heur": false,
93
+ "fallback_type": null,
94
+ "fallback_block_size": null,
95
+ "fallback_simple": false,
96
+ "simple": false,
97
+ "skip_inefficient_layers": false,
98
+ "full_matrix": false,
99
+ "scale_optimization": "fixed",
100
+ "scale_refinement_rounds": 1,
101
+ "layer_config_path": "F:\\SECourses_Musubi_Trainer_v16\\SECourses_Musubi_Trainer\\model_quantizer_presets\\krea2_fp8_layer_config.json",
102
+ "layer_config_fullmatch": false,
103
+ "manual_seed": -1,
104
+ "verbose": "NORMAL",
105
+ "low_memory": true,
106
+ "save_quant_metadata": true
107
+ }
108
+ },
109
+ "2": {
110
+ "label": "Normal (Balanced)",
111
+ "settings": {
112
+ "calib_samples": 2048,
113
+ "optimizer": "prodigy",
114
+ "num_iter": 2000,
115
+ "lr": 1.0,
116
+ "lr_schedule": "plateau",
117
+ "top_p": 0.12,
118
+ "min_k": 128,
119
+ "max_k": 896,
120
+ "lr_gamma": 0.99,
121
+ "lr_patience": 1,
122
+ "lr_factor": 0.95,
123
+ "lr_min": 1e-08,
124
+ "lr_cooldown": 0,
125
+ "lr_threshold": 0.0,
126
+ "lr_adaptive_mode": "simple-reset",
127
+ "lr_shape_influence": 1.0,
128
+ "lr_threshold_mode": "rel",
129
+ "early_stop_loss": 5e-09,
130
+ "early_stop_lr": 1.01e-08,
131
+ "early_stop_stall": 2000,
132
+ "quant_format": "FP8 (E4M3)",
133
+ "comfy_quant": true,
134
+ "full_precision_matrix_mult": false,
135
+ "scaling_mode": "tensor",
136
+ "block_size": null,
137
+ "convrot": false,
138
+ "convrot_group_size": 256,
139
+ "exclude_layers": "^(first|last|tmlp|tproj|txtmlp|img_in|final_layer|time_embed|time_mod_proj)([.]|$)|^(txtfusion|text_fusion)[.]projector([.]|$)",
140
+ "custom_type": null,
141
+ "custom_block_size": null,
142
+ "custom_scaling_mode": null,
143
+ "custom_simple": false,
144
+ "custom_heur": false,
145
+ "fallback_type": null,
146
+ "fallback_block_size": null,
147
+ "fallback_simple": false,
148
+ "simple": false,
149
+ "skip_inefficient_layers": false,
150
+ "full_matrix": false,
151
+ "scale_optimization": "fixed",
152
+ "scale_refinement_rounds": 1,
153
+ "layer_config_path": "F:\\SECourses_Musubi_Trainer_v16\\SECourses_Musubi_Trainer\\model_quantizer_presets\\krea2_fp8_layer_config.json",
154
+ "layer_config_fullmatch": false,
155
+ "manual_seed": -1,
156
+ "verbose": "NORMAL",
157
+ "low_memory": true,
158
+ "save_quant_metadata": true
159
+ }
160
+ },
161
+ "3": {
162
+ "label": "High Quality (Slow)",
163
+ "settings": {
164
+ "calib_samples": 4096,
165
+ "optimizer": "prodigy",
166
+ "num_iter": 6000,
167
+ "lr": 1.0,
168
+ "lr_schedule": "plateau",
169
+ "top_p": 0.2,
170
+ "min_k": 256,
171
+ "max_k": 1536,
172
+ "lr_gamma": 0.99,
173
+ "lr_patience": 1,
174
+ "lr_factor": 0.95,
175
+ "lr_min": 1e-08,
176
+ "lr_cooldown": 0,
177
+ "lr_threshold": 0.0,
178
+ "lr_adaptive_mode": "simple-reset",
179
+ "lr_shape_influence": 1.0,
180
+ "lr_threshold_mode": "rel",
181
+ "early_stop_loss": 5e-09,
182
+ "early_stop_lr": 1.01e-08,
183
+ "early_stop_stall": 2000,
184
+ "quant_format": "FP8 (E4M3)",
185
+ "comfy_quant": true,
186
+ "full_precision_matrix_mult": false,
187
+ "scaling_mode": "tensor",
188
+ "block_size": null,
189
+ "convrot": false,
190
+ "convrot_group_size": 256,
191
+ "exclude_layers": "^(first|last|tmlp|tproj|txtmlp|img_in|final_layer|time_embed|time_mod_proj)([.]|$)|^(txtfusion|text_fusion)[.]projector([.]|$)",
192
+ "custom_type": null,
193
+ "custom_block_size": null,
194
+ "custom_scaling_mode": null,
195
+ "custom_simple": false,
196
+ "custom_heur": false,
197
+ "fallback_type": null,
198
+ "fallback_block_size": null,
199
+ "fallback_simple": false,
200
+ "simple": false,
201
+ "skip_inefficient_layers": false,
202
+ "full_matrix": false,
203
+ "scale_optimization": "fixed",
204
+ "scale_refinement_rounds": 1,
205
+ "layer_config_path": "F:\\SECourses_Musubi_Trainer_v16\\SECourses_Musubi_Trainer\\model_quantizer_presets\\krea2_fp8_layer_config.json",
206
+ "layer_config_fullmatch": false,
207
+ "manual_seed": -1,
208
+ "verbose": "NORMAL",
209
+ "low_memory": true,
210
+ "save_quant_metadata": true
211
+ }
212
+ },
213
+ "4": {
214
+ "label": "Extreme Quality (Very Slow)",
215
+ "settings": {
216
+ "calib_samples": 4096,
217
+ "optimizer": "prodigy",
218
+ "num_iter": 6000,
219
+ "lr": 1.0,
220
+ "lr_schedule": "plateau",
221
+ "top_p": 0.2,
222
+ "min_k": 256,
223
+ "max_k": 1536,
224
+ "lr_gamma": 0.99,
225
+ "lr_patience": 1,
226
+ "lr_factor": 0.95,
227
+ "lr_min": 1e-08,
228
+ "lr_cooldown": 0,
229
+ "lr_threshold": 0.0,
230
+ "lr_adaptive_mode": "simple-reset",
231
+ "lr_shape_influence": 1.0,
232
+ "lr_threshold_mode": "rel",
233
+ "early_stop_loss": 5e-09,
234
+ "early_stop_lr": 1.01e-08,
235
+ "early_stop_stall": 2000,
236
+ "quant_format": "FP8 (E4M3)",
237
+ "comfy_quant": true,
238
+ "full_precision_matrix_mult": false,
239
+ "scaling_mode": "tensor",
240
+ "block_size": null,
241
+ "convrot": false,
242
+ "convrot_group_size": 256,
243
+ "exclude_layers": "^(first|last|tmlp|tproj|txtmlp|img_in|final_layer|time_embed|time_mod_proj)([.]|$)|^(txtfusion|text_fusion)[.]projector([.]|$)",
244
+ "custom_type": null,
245
+ "custom_block_size": null,
246
+ "custom_scaling_mode": null,
247
+ "custom_simple": false,
248
+ "custom_heur": false,
249
+ "fallback_type": null,
250
+ "fallback_block_size": null,
251
+ "fallback_simple": false,
252
+ "simple": false,
253
+ "skip_inefficient_layers": false,
254
+ "full_matrix": true,
255
+ "scale_optimization": "fixed",
256
+ "scale_refinement_rounds": 1,
257
+ "layer_config_path": "F:\\SECourses_Musubi_Trainer_v16\\SECourses_Musubi_Trainer\\model_quantizer_presets\\krea2_fp8_layer_config.json",
258
+ "layer_config_fullmatch": false,
259
+ "manual_seed": -1,
260
+ "verbose": "NORMAL",
261
+ "low_memory": true,
262
+ "save_quant_metadata": true
263
+ }
264
+ },
265
+ "5": {
266
+ "label": "FP8 Scaled (Tensorwise)",
267
+ "settings": {
268
+ "calib_samples": 3072,
269
+ "optimizer": "prodigy",
270
+ "num_iter": 3000,
271
+ "lr": 1.0,
272
+ "lr_schedule": "plateau",
273
+ "top_p": 0.16,
274
+ "min_k": 128,
275
+ "max_k": 1024,
276
+ "lr_gamma": 0.99,
277
+ "lr_patience": 1,
278
+ "lr_factor": 0.95,
279
+ "lr_min": 1e-08,
280
+ "lr_cooldown": 0,
281
+ "lr_threshold": 0.0,
282
+ "lr_adaptive_mode": "simple-reset",
283
+ "lr_shape_influence": 1.0,
284
+ "lr_threshold_mode": "rel",
285
+ "early_stop_loss": 5e-09,
286
+ "early_stop_lr": 1.01e-08,
287
+ "early_stop_stall": 2000,
288
+ "quant_format": "FP8 (E4M3)",
289
+ "comfy_quant": true,
290
+ "full_precision_matrix_mult": false,
291
+ "scaling_mode": "tensor",
292
+ "block_size": null,
293
+ "convrot": false,
294
+ "convrot_group_size": 256,
295
+ "exclude_layers": "^(first|last|tmlp|tproj|txtmlp|img_in|final_layer|time_embed|time_mod_proj)([.]|$)|^(txtfusion|text_fusion)[.]projector([.]|$)",
296
+ "custom_type": null,
297
+ "custom_block_size": null,
298
+ "custom_scaling_mode": null,
299
+ "custom_simple": false,
300
+ "custom_heur": false,
301
+ "fallback_type": null,
302
+ "fallback_block_size": null,
303
+ "fallback_simple": false,
304
+ "simple": false,
305
+ "skip_inefficient_layers": false,
306
+ "full_matrix": false,
307
+ "scale_optimization": "fixed",
308
+ "scale_refinement_rounds": 1,
309
+ "layer_config_path": "F:\\SECourses_Musubi_Trainer_v16\\SECourses_Musubi_Trainer\\model_quantizer_presets\\krea2_fp8_layer_config.json",
310
+ "layer_config_fullmatch": false,
311
+ "manual_seed": -1,
312
+ "verbose": "NORMAL",
313
+ "low_memory": true,
314
+ "save_quant_metadata": true
315
+ }
316
+ },
317
+ "6": {
318
+ "label": "FP8 Compatibility (Tensorwise)",
319
+ "settings": {
320
+ "calib_samples": 3072,
321
+ "optimizer": "prodigy",
322
+ "num_iter": 2500,
323
+ "lr": 1.0,
324
+ "lr_schedule": "plateau",
325
+ "top_p": 0.14,
326
+ "min_k": 128,
327
+ "max_k": 1024,
328
+ "lr_gamma": 0.99,
329
+ "lr_patience": 1,
330
+ "lr_factor": 0.95,
331
+ "lr_min": 1e-08,
332
+ "lr_cooldown": 0,
333
+ "lr_threshold": 0.0,
334
+ "lr_adaptive_mode": "simple-reset",
335
+ "lr_shape_influence": 1.0,
336
+ "lr_threshold_mode": "rel",
337
+ "early_stop_loss": 5e-09,
338
+ "early_stop_lr": 1.01e-08,
339
+ "early_stop_stall": 2000,
340
+ "quant_format": "FP8 (E4M3)",
341
+ "comfy_quant": true,
342
+ "full_precision_matrix_mult": false,
343
+ "scaling_mode": "tensor",
344
+ "block_size": null,
345
+ "convrot": false,
346
+ "convrot_group_size": 256,
347
+ "exclude_layers": "^(first|last|tmlp|tproj|txtmlp|img_in|final_layer|time_embed|time_mod_proj)([.]|$)|^(txtfusion|text_fusion)[.]projector([.]|$)",
348
+ "custom_type": null,
349
+ "custom_block_size": null,
350
+ "custom_scaling_mode": null,
351
+ "custom_simple": false,
352
+ "custom_heur": false,
353
+ "fallback_type": null,
354
+ "fallback_block_size": null,
355
+ "fallback_simple": false,
356
+ "simple": false,
357
+ "skip_inefficient_layers": false,
358
+ "full_matrix": false,
359
+ "scale_optimization": "fixed",
360
+ "scale_refinement_rounds": 1,
361
+ "layer_config_path": "F:\\SECourses_Musubi_Trainer_v16\\SECourses_Musubi_Trainer\\model_quantizer_presets\\krea2_fp8_layer_config.json",
362
+ "layer_config_fullmatch": false,
363
+ "manual_seed": -1,
364
+ "verbose": "NORMAL",
365
+ "low_memory": true,
366
+ "save_quant_metadata": true
367
+ }
368
+ },
369
+ "7": {
370
+ "label": "INT8 Blockwise (QuantOps / Experimental)",
371
+ "settings": {
372
+ "calib_samples": 1024,
373
+ "optimizer": "original",
374
+ "num_iter": 200,
375
+ "lr": 0.008077300000003,
376
+ "lr_schedule": "adaptive",
377
+ "top_p": 0.02,
378
+ "min_k": 16,
379
+ "max_k": 64,
380
+ "lr_gamma": 0.99,
381
+ "lr_patience": 1,
382
+ "lr_factor": 0.95,
383
+ "lr_min": 1e-08,
384
+ "lr_cooldown": 0,
385
+ "lr_threshold": 0.0,
386
+ "lr_adaptive_mode": "simple-reset",
387
+ "lr_shape_influence": 1.0,
388
+ "lr_threshold_mode": "rel",
389
+ "early_stop_loss": 5e-09,
390
+ "early_stop_lr": 1.01e-08,
391
+ "early_stop_stall": 2000,
392
+ "quant_format": "INT8",
393
+ "comfy_quant": true,
394
+ "full_precision_matrix_mult": false,
395
+ "scaling_mode": "block",
396
+ "block_size": 128,
397
+ "convrot": false,
398
+ "convrot_group_size": 256,
399
+ "exclude_layers": "",
400
+ "custom_type": null,
401
+ "custom_block_size": null,
402
+ "custom_scaling_mode": null,
403
+ "custom_simple": false,
404
+ "custom_heur": false,
405
+ "fallback_type": null,
406
+ "fallback_block_size": null,
407
+ "fallback_simple": false,
408
+ "simple": true,
409
+ "skip_inefficient_layers": false,
410
+ "full_matrix": false,
411
+ "scale_optimization": "fixed",
412
+ "scale_refinement_rounds": 1,
413
+ "layer_config_path": "",
414
+ "layer_config_fullmatch": false,
415
+ "manual_seed": -1,
416
+ "verbose": "NORMAL",
417
+ "low_memory": true,
418
+ "save_quant_metadata": true
419
+ }
420
+ },
421
+ "8": {
422
+ "label": "INT8 Tensorwise (QuantOps custom / RTX 30xx+)",
423
+ "settings": {
424
+ "calib_samples": 512,
425
+ "optimizer": "original",
426
+ "num_iter": 120,
427
+ "lr": 0.008077300000003,
428
+ "lr_schedule": "adaptive",
429
+ "top_p": 0.02,
430
+ "min_k": 16,
431
+ "max_k": 64,
432
+ "lr_gamma": 0.99,
433
+ "lr_patience": 1,
434
+ "lr_factor": 0.95,
435
+ "lr_min": 1e-08,
436
+ "lr_cooldown": 0,
437
+ "lr_threshold": 0.0,
438
+ "lr_adaptive_mode": "simple-reset",
439
+ "lr_shape_influence": 1.0,
440
+ "lr_threshold_mode": "rel",
441
+ "early_stop_loss": 5e-09,
442
+ "early_stop_lr": 1.01e-08,
443
+ "early_stop_stall": 2000,
444
+ "quant_format": "INT8",
445
+ "comfy_quant": true,
446
+ "full_precision_matrix_mult": false,
447
+ "scaling_mode": "tensor",
448
+ "block_size": null,
449
+ "convrot": false,
450
+ "convrot_group_size": 256,
451
+ "exclude_layers": "",
452
+ "custom_type": null,
453
+ "custom_block_size": null,
454
+ "custom_scaling_mode": null,
455
+ "custom_simple": false,
456
+ "custom_heur": false,
457
+ "fallback_type": null,
458
+ "fallback_block_size": null,
459
+ "fallback_simple": false,
460
+ "simple": true,
461
+ "skip_inefficient_layers": false,
462
+ "full_matrix": false,
463
+ "scale_optimization": "fixed",
464
+ "scale_refinement_rounds": 1,
465
+ "layer_config_path": "",
466
+ "layer_config_fullmatch": false,
467
+ "manual_seed": -1,
468
+ "verbose": "NORMAL",
469
+ "low_memory": true,
470
+ "save_quant_metadata": true
471
+ }
472
+ },
473
+ "9": {
474
+ "label": "INT8 ConvRot Rowwise (QuantOps custom / Best INT8)",
475
+ "settings": {
476
+ "calib_samples": 1024,
477
+ "optimizer": "original",
478
+ "num_iter": 200,
479
+ "lr": 0.008077300000003,
480
+ "lr_schedule": "adaptive",
481
+ "top_p": 0.02,
482
+ "min_k": 16,
483
+ "max_k": 64,
484
+ "lr_gamma": 0.99,
485
+ "lr_patience": 1,
486
+ "lr_factor": 0.95,
487
+ "lr_min": 1e-08,
488
+ "lr_cooldown": 0,
489
+ "lr_threshold": 0.0,
490
+ "lr_adaptive_mode": "simple-reset",
491
+ "lr_shape_influence": 1.0,
492
+ "lr_threshold_mode": "rel",
493
+ "early_stop_loss": 5e-09,
494
+ "early_stop_lr": 1.01e-08,
495
+ "early_stop_stall": 2000,
496
+ "quant_format": "INT8",
497
+ "comfy_quant": true,
498
+ "full_precision_matrix_mult": false,
499
+ "scaling_mode": "row",
500
+ "block_size": 128,
501
+ "convrot": true,
502
+ "convrot_group_size": 256,
503
+ "exclude_layers": "",
504
+ "custom_type": null,
505
+ "custom_block_size": null,
506
+ "custom_scaling_mode": null,
507
+ "custom_simple": false,
508
+ "custom_heur": false,
509
+ "fallback_type": null,
510
+ "fallback_block_size": null,
511
+ "fallback_simple": false,
512
+ "simple": true,
513
+ "skip_inefficient_layers": false,
514
+ "full_matrix": false,
515
+ "scale_optimization": "fixed",
516
+ "scale_refinement_rounds": 1,
517
+ "layer_config_path": "",
518
+ "layer_config_fullmatch": false,
519
+ "manual_seed": -1,
520
+ "verbose": "NORMAL",
521
+ "low_memory": true,
522
+ "save_quant_metadata": true
523
+ }
524
+ },
525
+ "10": {
526
+ "label": "MXFP8 Balanced (QuantOps / Blackwell)",
527
+ "settings": {
528
+ "calib_samples": 3072,
529
+ "optimizer": "prodigy",
530
+ "num_iter": 3000,
531
+ "lr": 1.0,
532
+ "lr_schedule": "plateau",
533
+ "top_p": 0.2,
534
+ "min_k": 128,
535
+ "max_k": 1280,
536
+ "lr_gamma": 0.99,
537
+ "lr_patience": 1,
538
+ "lr_factor": 0.95,
539
+ "lr_min": 1e-08,
540
+ "lr_cooldown": 0,
541
+ "lr_threshold": 0.0,
542
+ "lr_adaptive_mode": "simple-reset",
543
+ "lr_shape_influence": 1.0,
544
+ "lr_threshold_mode": "rel",
545
+ "early_stop_loss": 5e-09,
546
+ "early_stop_lr": 1.01e-08,
547
+ "early_stop_stall": 2000,
548
+ "quant_format": "MXFP8 (Microscaling)",
549
+ "comfy_quant": true,
550
+ "full_precision_matrix_mult": true,
551
+ "scaling_mode": "tensor",
552
+ "block_size": null,
553
+ "convrot": false,
554
+ "convrot_group_size": 256,
555
+ "exclude_layers": "",
556
+ "custom_type": null,
557
+ "custom_block_size": null,
558
+ "custom_scaling_mode": null,
559
+ "custom_simple": false,
560
+ "custom_heur": false,
561
+ "fallback_type": null,
562
+ "fallback_block_size": null,
563
+ "fallback_simple": false,
564
+ "simple": false,
565
+ "skip_inefficient_layers": false,
566
+ "full_matrix": false,
567
+ "scale_optimization": "fixed",
568
+ "scale_refinement_rounds": 1,
569
+ "layer_config_path": "",
570
+ "layer_config_fullmatch": false,
571
+ "manual_seed": -1,
572
+ "verbose": "NORMAL",
573
+ "low_memory": true,
574
+ "save_quant_metadata": true
575
+ }
576
+ },
577
+ "11": {
578
+ "label": "NVFP4 Balanced (QuantOps / Blackwell)",
579
+ "settings": {
580
+ "calib_samples": 4096,
581
+ "optimizer": "prodigy",
582
+ "num_iter": 4000,
583
+ "lr": 1.0,
584
+ "lr_schedule": "plateau",
585
+ "top_p": 0.2,
586
+ "min_k": 128,
587
+ "max_k": 1280,
588
+ "lr_gamma": 0.99,
589
+ "lr_patience": 1,
590
+ "lr_factor": 0.95,
591
+ "lr_min": 1e-08,
592
+ "lr_cooldown": 0,
593
+ "lr_threshold": 0.0,
594
+ "lr_adaptive_mode": "simple-reset",
595
+ "lr_shape_influence": 1.0,
596
+ "lr_threshold_mode": "rel",
597
+ "early_stop_loss": 5e-09,
598
+ "early_stop_lr": 1.01e-08,
599
+ "early_stop_stall": 2000,
600
+ "quant_format": "NVFP4 (FP4 E2M1)",
601
+ "comfy_quant": true,
602
+ "full_precision_matrix_mult": true,
603
+ "scaling_mode": "tensor",
604
+ "block_size": null,
605
+ "convrot": false,
606
+ "convrot_group_size": 256,
607
+ "exclude_layers": "",
608
+ "custom_type": null,
609
+ "custom_block_size": null,
610
+ "custom_scaling_mode": null,
611
+ "custom_simple": false,
612
+ "custom_heur": false,
613
+ "fallback_type": null,
614
+ "fallback_block_size": null,
615
+ "fallback_simple": false,
616
+ "simple": false,
617
+ "skip_inefficient_layers": true,
618
+ "full_matrix": false,
619
+ "scale_optimization": "iterative",
620
+ "scale_refinement_rounds": 1,
621
+ "layer_config_path": "",
622
+ "layer_config_fullmatch": false,
623
+ "manual_seed": -1,
624
+ "verbose": "NORMAL",
625
+ "low_memory": true,
626
+ "save_quant_metadata": true
627
+ }
628
+ },
629
+ "12": {
630
+ "label": "NVFP4 Z-Image (Aggressive / Expert)",
631
+ "settings": {
632
+ "calib_samples": 8192,
633
+ "optimizer": "prodigy",
634
+ "num_iter": 12000,
635
+ "lr": 1.0,
636
+ "lr_schedule": "plateau",
637
+ "top_p": 0.2,
638
+ "min_k": 256,
639
+ "max_k": 2048,
640
+ "lr_gamma": 0.99,
641
+ "lr_patience": 1,
642
+ "lr_factor": 0.95,
643
+ "lr_min": 1e-08,
644
+ "lr_cooldown": 0,
645
+ "lr_threshold": 0.0,
646
+ "lr_adaptive_mode": "simple-reset",
647
+ "lr_shape_influence": 1.0,
648
+ "lr_threshold_mode": "rel",
649
+ "early_stop_loss": 5e-09,
650
+ "early_stop_lr": 1.01e-08,
651
+ "early_stop_stall": 2000,
652
+ "quant_format": "NVFP4 (FP4 E2M1)",
653
+ "comfy_quant": true,
654
+ "full_precision_matrix_mult": true,
655
+ "scaling_mode": "tensor",
656
+ "block_size": null,
657
+ "convrot": false,
658
+ "convrot_group_size": 256,
659
+ "exclude_layers": "",
660
+ "custom_type": null,
661
+ "custom_block_size": null,
662
+ "custom_scaling_mode": null,
663
+ "custom_simple": false,
664
+ "custom_heur": false,
665
+ "fallback_type": null,
666
+ "fallback_block_size": null,
667
+ "fallback_simple": false,
668
+ "simple": false,
669
+ "skip_inefficient_layers": false,
670
+ "full_matrix": false,
671
+ "scale_optimization": "iterative",
672
+ "scale_refinement_rounds": 1,
673
+ "layer_config_path": "",
674
+ "layer_config_fullmatch": false,
675
+ "manual_seed": 42,
676
+ "verbose": "NORMAL",
677
+ "low_memory": true,
678
+ "save_quant_metadata": true
679
+ }
680
+ }
681
+ },
682
+ "models": {
683
+ "0": {
684
+ "label": "Anima (Base/Turbo)",
685
+ "value": "anima",
686
+ "preset_value": "FP8 Compatibility (Tensorwise)",
687
+ "filters": [
688
+ "anima"
689
+ ],
690
+ "settings": {
691
+ "calib_samples": 3072,
692
+ "optimizer": "prodigy",
693
+ "num_iter": 2500,
694
+ "lr": 1.0,
695
+ "lr_schedule": "plateau",
696
+ "top_p": 0.14,
697
+ "min_k": 128,
698
+ "max_k": 1024,
699
+ "lr_gamma": 0.99,
700
+ "lr_patience": 1,
701
+ "lr_factor": 0.95,
702
+ "lr_min": 1e-08,
703
+ "lr_cooldown": 0,
704
+ "lr_threshold": 0.0,
705
+ "lr_adaptive_mode": "simple-reset",
706
+ "lr_shape_influence": 1.0,
707
+ "lr_threshold_mode": "rel",
708
+ "early_stop_loss": 5e-09,
709
+ "early_stop_lr": 1.01e-08,
710
+ "early_stop_stall": 2000,
711
+ "quant_format": "FP8 (E4M3)",
712
+ "comfy_quant": true,
713
+ "full_precision_matrix_mult": true,
714
+ "scaling_mode": "tensor",
715
+ "block_size": null,
716
+ "convrot": false,
717
+ "convrot_group_size": 256,
718
+ "exclude_layers": "",
719
+ "custom_type": null,
720
+ "custom_block_size": null,
721
+ "custom_scaling_mode": null,
722
+ "custom_simple": false,
723
+ "custom_heur": false,
724
+ "fallback_type": null,
725
+ "fallback_block_size": null,
726
+ "fallback_simple": false,
727
+ "simple": false,
728
+ "skip_inefficient_layers": false,
729
+ "full_matrix": false,
730
+ "scale_optimization": "fixed",
731
+ "scale_refinement_rounds": 1,
732
+ "layer_config_path": "",
733
+ "layer_config_fullmatch": false,
734
+ "manual_seed": -1,
735
+ "verbose": "NORMAL",
736
+ "low_memory": true,
737
+ "save_quant_metadata": true
738
+ }
739
+ },
740
+ "1": {
741
+ "label": "Boogu-Image",
742
+ "value": "boogu",
743
+ "preset_value": "INT8 Blockwise (QuantOps / Experimental)",
744
+ "filters": [],
745
+ "settings": {
746
+ "calib_samples": 1024,
747
+ "optimizer": "original",
748
+ "num_iter": 200,
749
+ "lr": 0.008077300000003,
750
+ "lr_schedule": "adaptive",
751
+ "top_p": 0.02,
752
+ "min_k": 16,
753
+ "max_k": 64,
754
+ "lr_gamma": 0.99,
755
+ "lr_patience": 1,
756
+ "lr_factor": 0.95,
757
+ "lr_min": 1e-08,
758
+ "lr_cooldown": 0,
759
+ "lr_threshold": 0.0,
760
+ "lr_adaptive_mode": "simple-reset",
761
+ "lr_shape_influence": 1.0,
762
+ "lr_threshold_mode": "rel",
763
+ "early_stop_loss": 5e-09,
764
+ "early_stop_lr": 1.01e-08,
765
+ "early_stop_stall": 2000,
766
+ "quant_format": "INT8",
767
+ "comfy_quant": true,
768
+ "full_precision_matrix_mult": false,
769
+ "scaling_mode": "block",
770
+ "block_size": 128,
771
+ "convrot": false,
772
+ "convrot_group_size": 256,
773
+ "exclude_layers": "(image_index_embedding|ref_image_patch_embedder)",
774
+ "custom_type": null,
775
+ "custom_block_size": null,
776
+ "custom_scaling_mode": null,
777
+ "custom_simple": false,
778
+ "custom_heur": false,
779
+ "fallback_type": null,
780
+ "fallback_block_size": null,
781
+ "fallback_simple": false,
782
+ "simple": true,
783
+ "skip_inefficient_layers": false,
784
+ "full_matrix": false,
785
+ "scale_optimization": "fixed",
786
+ "scale_refinement_rounds": 1,
787
+ "layer_config_path": "",
788
+ "layer_config_fullmatch": false,
789
+ "manual_seed": -1,
790
+ "verbose": "NORMAL",
791
+ "low_memory": true,
792
+ "save_quant_metadata": true
793
+ }
794
+ },
795
+ "2": {
796
+ "label": "ERNIE Image",
797
+ "value": "ernie_image",
798
+ "preset_value": "FP8 Scaled (Tensorwise)",
799
+ "filters": [],
800
+ "settings": {
801
+ "calib_samples": 3072,
802
+ "optimizer": "prodigy",
803
+ "num_iter": 3000,
804
+ "lr": 1.0,
805
+ "lr_schedule": "plateau",
806
+ "top_p": 0.16,
807
+ "min_k": 128,
808
+ "max_k": 1024,
809
+ "lr_gamma": 0.99,
810
+ "lr_patience": 1,
811
+ "lr_factor": 0.95,
812
+ "lr_min": 1e-08,
813
+ "lr_cooldown": 0,
814
+ "lr_threshold": 0.0,
815
+ "lr_adaptive_mode": "simple-reset",
816
+ "lr_shape_influence": 1.0,
817
+ "lr_threshold_mode": "rel",
818
+ "early_stop_loss": 5e-09,
819
+ "early_stop_lr": 1.01e-08,
820
+ "early_stop_stall": 2000,
821
+ "quant_format": "FP8 (E4M3)",
822
+ "comfy_quant": true,
823
+ "full_precision_matrix_mult": true,
824
+ "scaling_mode": "tensor",
825
+ "block_size": null,
826
+ "convrot": false,
827
+ "convrot_group_size": 256,
828
+ "exclude_layers": "(time_embedding|adaLN_modulation|final_linear|final_norm|x_embedder|layers[.]0[.]self_attention|layers[.]0[.]mlp.gate_proj|layers[.]0[.]mlp[.]up_proj|text_proj)",
829
+ "custom_type": null,
830
+ "custom_block_size": null,
831
+ "custom_scaling_mode": null,
832
+ "custom_simple": false,
833
+ "custom_heur": false,
834
+ "fallback_type": null,
835
+ "fallback_block_size": null,
836
+ "fallback_simple": false,
837
+ "simple": false,
838
+ "skip_inefficient_layers": false,
839
+ "full_matrix": false,
840
+ "scale_optimization": "fixed",
841
+ "scale_refinement_rounds": 1,
842
+ "layer_config_path": "",
843
+ "layer_config_fullmatch": false,
844
+ "manual_seed": -1,
845
+ "verbose": "NORMAL",
846
+ "low_memory": true,
847
+ "save_quant_metadata": true
848
+ }
849
+ },
850
+ "3": {
851
+ "label": "FLUX.1",
852
+ "value": "flux1",
853
+ "preset_value": "FP8 Scaled (Tensorwise)",
854
+ "filters": [],
855
+ "settings": {
856
+ "calib_samples": 3072,
857
+ "optimizer": "prodigy",
858
+ "num_iter": 3000,
859
+ "lr": 1.0,
860
+ "lr_schedule": "plateau",
861
+ "top_p": 0.16,
862
+ "min_k": 128,
863
+ "max_k": 1024,
864
+ "lr_gamma": 0.99,
865
+ "lr_patience": 1,
866
+ "lr_factor": 0.95,
867
+ "lr_min": 1e-08,
868
+ "lr_cooldown": 0,
869
+ "lr_threshold": 0.0,
870
+ "lr_adaptive_mode": "simple-reset",
871
+ "lr_shape_influence": 1.0,
872
+ "lr_threshold_mode": "rel",
873
+ "early_stop_loss": 5e-09,
874
+ "early_stop_lr": 1.01e-08,
875
+ "early_stop_stall": 2000,
876
+ "quant_format": "FP8 (E4M3)",
877
+ "comfy_quant": true,
878
+ "full_precision_matrix_mult": true,
879
+ "scaling_mode": "tensor",
880
+ "block_size": null,
881
+ "convrot": false,
882
+ "convrot_group_size": 256,
883
+ "exclude_layers": "",
884
+ "custom_type": null,
885
+ "custom_block_size": null,
886
+ "custom_scaling_mode": null,
887
+ "custom_simple": false,
888
+ "custom_heur": false,
889
+ "fallback_type": null,
890
+ "fallback_block_size": null,
891
+ "fallback_simple": false,
892
+ "simple": false,
893
+ "skip_inefficient_layers": false,
894
+ "full_matrix": false,
895
+ "scale_optimization": "fixed",
896
+ "scale_refinement_rounds": 1,
897
+ "layer_config_path": "",
898
+ "layer_config_fullmatch": false,
899
+ "manual_seed": -1,
900
+ "verbose": "NORMAL",
901
+ "low_memory": true,
902
+ "save_quant_metadata": true,
903
+ "include_input_scale": true
904
+ }
905
+ },
906
+ "4": {
907
+ "label": "FLUX.2",
908
+ "value": "flux2",
909
+ "preset_value": "Normal (Balanced)",
910
+ "filters": [
911
+ "flux2"
912
+ ],
913
+ "settings": {
914
+ "calib_samples": 2048,
915
+ "optimizer": "prodigy",
916
+ "num_iter": 2000,
917
+ "lr": 1.0,
918
+ "lr_schedule": "plateau",
919
+ "top_p": 0.12,
920
+ "min_k": 128,
921
+ "max_k": 896,
922
+ "lr_gamma": 0.99,
923
+ "lr_patience": 1,
924
+ "lr_factor": 0.95,
925
+ "lr_min": 1e-08,
926
+ "lr_cooldown": 0,
927
+ "lr_threshold": 0.0,
928
+ "lr_adaptive_mode": "simple-reset",
929
+ "lr_shape_influence": 1.0,
930
+ "lr_threshold_mode": "rel",
931
+ "early_stop_loss": 5e-09,
932
+ "early_stop_lr": 1.01e-08,
933
+ "early_stop_stall": 2000,
934
+ "quant_format": "FP8 (E4M3)",
935
+ "comfy_quant": true,
936
+ "full_precision_matrix_mult": true,
937
+ "scaling_mode": "tensor",
938
+ "block_size": null,
939
+ "convrot": false,
940
+ "convrot_group_size": 256,
941
+ "exclude_layers": "",
942
+ "custom_type": null,
943
+ "custom_block_size": null,
944
+ "custom_scaling_mode": null,
945
+ "custom_simple": false,
946
+ "custom_heur": false,
947
+ "fallback_type": null,
948
+ "fallback_block_size": null,
949
+ "fallback_simple": false,
950
+ "simple": false,
951
+ "skip_inefficient_layers": false,
952
+ "full_matrix": false,
953
+ "scale_optimization": "fixed",
954
+ "scale_refinement_rounds": 1,
955
+ "layer_config_path": "",
956
+ "layer_config_fullmatch": false,
957
+ "manual_seed": -1,
958
+ "verbose": "NORMAL",
959
+ "low_memory": true,
960
+ "save_quant_metadata": true
961
+ }
962
+ },
963
+ "5": {
964
+ "label": "Hunyuan Video 1.5",
965
+ "value": "hunyuan",
966
+ "preset_value": "Normal (Balanced)",
967
+ "filters": [
968
+ "hunyuan"
969
+ ],
970
+ "settings": {
971
+ "calib_samples": 2048,
972
+ "optimizer": "prodigy",
973
+ "num_iter": 2000,
974
+ "lr": 1.0,
975
+ "lr_schedule": "plateau",
976
+ "top_p": 0.12,
977
+ "min_k": 128,
978
+ "max_k": 896,
979
+ "lr_gamma": 0.99,
980
+ "lr_patience": 1,
981
+ "lr_factor": 0.95,
982
+ "lr_min": 1e-08,
983
+ "lr_cooldown": 0,
984
+ "lr_threshold": 0.0,
985
+ "lr_adaptive_mode": "simple-reset",
986
+ "lr_shape_influence": 1.0,
987
+ "lr_threshold_mode": "rel",
988
+ "early_stop_loss": 5e-09,
989
+ "early_stop_lr": 1.01e-08,
990
+ "early_stop_stall": 2000,
991
+ "quant_format": "FP8 (E4M3)",
992
+ "comfy_quant": true,
993
+ "full_precision_matrix_mult": true,
994
+ "scaling_mode": "tensor",
995
+ "block_size": null,
996
+ "convrot": false,
997
+ "convrot_group_size": 256,
998
+ "exclude_layers": "",
999
+ "custom_type": null,
1000
+ "custom_block_size": null,
1001
+ "custom_scaling_mode": null,
1002
+ "custom_simple": false,
1003
+ "custom_heur": false,
1004
+ "fallback_type": null,
1005
+ "fallback_block_size": null,
1006
+ "fallback_simple": false,
1007
+ "simple": false,
1008
+ "skip_inefficient_layers": false,
1009
+ "full_matrix": false,
1010
+ "scale_optimization": "fixed",
1011
+ "scale_refinement_rounds": 1,
1012
+ "layer_config_path": "",
1013
+ "layer_config_fullmatch": false,
1014
+ "manual_seed": -1,
1015
+ "verbose": "NORMAL",
1016
+ "low_memory": true,
1017
+ "save_quant_metadata": true
1018
+ }
1019
+ },
1020
+ "6": {
1021
+ "label": "Krea 2 (Raw/Turbo)",
1022
+ "value": "krea2",
1023
+ "preset_value": "Normal (Balanced)",
1024
+ "filters": [],
1025
+ "settings": {
1026
+ "calib_samples": 2048,
1027
+ "optimizer": "prodigy",
1028
+ "num_iter": 2000,
1029
+ "lr": 1.0,
1030
+ "lr_schedule": "plateau",
1031
+ "top_p": 0.12,
1032
+ "min_k": 128,
1033
+ "max_k": 896,
1034
+ "lr_gamma": 0.99,
1035
+ "lr_patience": 1,
1036
+ "lr_factor": 0.95,
1037
+ "lr_min": 1e-08,
1038
+ "lr_cooldown": 0,
1039
+ "lr_threshold": 0.0,
1040
+ "lr_adaptive_mode": "simple-reset",
1041
+ "lr_shape_influence": 1.0,
1042
+ "lr_threshold_mode": "rel",
1043
+ "early_stop_loss": 5e-09,
1044
+ "early_stop_lr": 1.01e-08,
1045
+ "early_stop_stall": 2000,
1046
+ "quant_format": "FP8 (E4M3)",
1047
+ "comfy_quant": true,
1048
+ "full_precision_matrix_mult": false,
1049
+ "scaling_mode": "tensor",
1050
+ "block_size": null,
1051
+ "convrot": false,
1052
+ "convrot_group_size": 256,
1053
+ "exclude_layers": "^(first|last|tmlp|tproj|txtmlp|img_in|final_layer|time_embed|time_mod_proj)([.]|$)|^(txtfusion|text_fusion)[.]projector([.]|$)",
1054
+ "custom_type": null,
1055
+ "custom_block_size": null,
1056
+ "custom_scaling_mode": null,
1057
+ "custom_simple": false,
1058
+ "custom_heur": false,
1059
+ "fallback_type": null,
1060
+ "fallback_block_size": null,
1061
+ "fallback_simple": false,
1062
+ "simple": false,
1063
+ "skip_inefficient_layers": false,
1064
+ "full_matrix": false,
1065
+ "scale_optimization": "fixed",
1066
+ "scale_refinement_rounds": 1,
1067
+ "layer_config_path": "F:\\SECourses_Musubi_Trainer_v16\\SECourses_Musubi_Trainer\\model_quantizer_presets\\krea2_fp8_layer_config.json",
1068
+ "layer_config_fullmatch": false,
1069
+ "manual_seed": -1,
1070
+ "verbose": "NORMAL",
1071
+ "low_memory": true,
1072
+ "save_quant_metadata": true
1073
+ }
1074
+ },
1075
+ "7": {
1076
+ "label": "LTX (2 / 2.3)",
1077
+ "value": "ltxv2",
1078
+ "preset_value": "FP8 Compatibility (Tensorwise)",
1079
+ "filters": [
1080
+ "ltxv2"
1081
+ ],
1082
+ "settings": {
1083
+ "calib_samples": 3072,
1084
+ "optimizer": "prodigy",
1085
+ "num_iter": 2500,
1086
+ "lr": 1.0,
1087
+ "lr_schedule": "plateau",
1088
+ "top_p": 0.14,
1089
+ "min_k": 128,
1090
+ "max_k": 1024,
1091
+ "lr_gamma": 0.99,
1092
+ "lr_patience": 1,
1093
+ "lr_factor": 0.95,
1094
+ "lr_min": 1e-08,
1095
+ "lr_cooldown": 0,
1096
+ "lr_threshold": 0.0,
1097
+ "lr_adaptive_mode": "simple-reset",
1098
+ "lr_shape_influence": 1.0,
1099
+ "lr_threshold_mode": "rel",
1100
+ "early_stop_loss": 5e-09,
1101
+ "early_stop_lr": 1.01e-08,
1102
+ "early_stop_stall": 2000,
1103
+ "quant_format": "FP8 (E4M3)",
1104
+ "comfy_quant": true,
1105
+ "full_precision_matrix_mult": true,
1106
+ "scaling_mode": "tensor",
1107
+ "block_size": null,
1108
+ "convrot": false,
1109
+ "convrot_group_size": 256,
1110
+ "exclude_layers": "",
1111
+ "custom_type": null,
1112
+ "custom_block_size": null,
1113
+ "custom_scaling_mode": null,
1114
+ "custom_simple": false,
1115
+ "custom_heur": false,
1116
+ "fallback_type": null,
1117
+ "fallback_block_size": null,
1118
+ "fallback_simple": false,
1119
+ "simple": false,
1120
+ "skip_inefficient_layers": false,
1121
+ "full_matrix": false,
1122
+ "scale_optimization": "fixed",
1123
+ "scale_refinement_rounds": 1,
1124
+ "layer_config_path": "",
1125
+ "layer_config_fullmatch": false,
1126
+ "manual_seed": -1,
1127
+ "verbose": "NORMAL",
1128
+ "low_memory": true,
1129
+ "save_quant_metadata": true
1130
+ }
1131
+ },
1132
+ "8": {
1133
+ "label": "Microsoft LENS",
1134
+ "value": "lens",
1135
+ "preset_value": "Normal (Balanced)",
1136
+ "filters": [
1137
+ "lens"
1138
+ ],
1139
+ "settings": {
1140
+ "calib_samples": 2048,
1141
+ "optimizer": "prodigy",
1142
+ "num_iter": 2000,
1143
+ "lr": 1.0,
1144
+ "lr_schedule": "plateau",
1145
+ "top_p": 0.12,
1146
+ "min_k": 128,
1147
+ "max_k": 896,
1148
+ "lr_gamma": 0.99,
1149
+ "lr_patience": 1,
1150
+ "lr_factor": 0.95,
1151
+ "lr_min": 1e-08,
1152
+ "lr_cooldown": 0,
1153
+ "lr_threshold": 0.0,
1154
+ "lr_adaptive_mode": "simple-reset",
1155
+ "lr_shape_influence": 1.0,
1156
+ "lr_threshold_mode": "rel",
1157
+ "early_stop_loss": 5e-09,
1158
+ "early_stop_lr": 1.01e-08,
1159
+ "early_stop_stall": 2000,
1160
+ "quant_format": "FP8 (E4M3)",
1161
+ "comfy_quant": true,
1162
+ "full_precision_matrix_mult": true,
1163
+ "scaling_mode": "tensor",
1164
+ "block_size": null,
1165
+ "convrot": false,
1166
+ "convrot_group_size": 256,
1167
+ "exclude_layers": "",
1168
+ "custom_type": null,
1169
+ "custom_block_size": null,
1170
+ "custom_scaling_mode": null,
1171
+ "custom_simple": false,
1172
+ "custom_heur": false,
1173
+ "fallback_type": null,
1174
+ "fallback_block_size": null,
1175
+ "fallback_simple": false,
1176
+ "simple": false,
1177
+ "skip_inefficient_layers": false,
1178
+ "full_matrix": false,
1179
+ "scale_optimization": "fixed",
1180
+ "scale_refinement_rounds": 1,
1181
+ "layer_config_path": "",
1182
+ "layer_config_fullmatch": false,
1183
+ "manual_seed": -1,
1184
+ "verbose": "NORMAL",
1185
+ "low_memory": true,
1186
+ "save_quant_metadata": true
1187
+ }
1188
+ },
1189
+ "9": {
1190
+ "label": "Qwen Image / Edit (2509, 2511, 2512)",
1191
+ "value": "qwen",
1192
+ "preset_value": "FP8 Scaled (Tensorwise)",
1193
+ "filters": [
1194
+ "qwen"
1195
+ ],
1196
+ "settings": {
1197
+ "calib_samples": 3072,
1198
+ "optimizer": "prodigy",
1199
+ "num_iter": 3000,
1200
+ "lr": 1.0,
1201
+ "lr_schedule": "plateau",
1202
+ "top_p": 0.16,
1203
+ "min_k": 128,
1204
+ "max_k": 1024,
1205
+ "lr_gamma": 0.99,
1206
+ "lr_patience": 1,
1207
+ "lr_factor": 0.95,
1208
+ "lr_min": 1e-08,
1209
+ "lr_cooldown": 0,
1210
+ "lr_threshold": 0.0,
1211
+ "lr_adaptive_mode": "simple-reset",
1212
+ "lr_shape_influence": 1.0,
1213
+ "lr_threshold_mode": "rel",
1214
+ "early_stop_loss": 5e-09,
1215
+ "early_stop_lr": 1.01e-08,
1216
+ "early_stop_stall": 2000,
1217
+ "quant_format": "FP8 (E4M3)",
1218
+ "comfy_quant": true,
1219
+ "full_precision_matrix_mult": true,
1220
+ "scaling_mode": "tensor",
1221
+ "block_size": null,
1222
+ "convrot": false,
1223
+ "convrot_group_size": 256,
1224
+ "exclude_layers": "",
1225
+ "custom_type": null,
1226
+ "custom_block_size": null,
1227
+ "custom_scaling_mode": null,
1228
+ "custom_simple": false,
1229
+ "custom_heur": false,
1230
+ "fallback_type": null,
1231
+ "fallback_block_size": null,
1232
+ "fallback_simple": false,
1233
+ "simple": false,
1234
+ "skip_inefficient_layers": false,
1235
+ "full_matrix": false,
1236
+ "scale_optimization": "fixed",
1237
+ "scale_refinement_rounds": 1,
1238
+ "layer_config_path": "",
1239
+ "layer_config_fullmatch": false,
1240
+ "manual_seed": -1,
1241
+ "verbose": "NORMAL",
1242
+ "low_memory": true,
1243
+ "save_quant_metadata": true
1244
+ }
1245
+ },
1246
+ "10": {
1247
+ "label": "WAN (2.1 / 2.2)",
1248
+ "value": "wan",
1249
+ "preset_value": "FP8 Scaled (Tensorwise)",
1250
+ "filters": [
1251
+ "wan"
1252
+ ],
1253
+ "settings": {
1254
+ "calib_samples": 3072,
1255
+ "optimizer": "prodigy",
1256
+ "num_iter": 3000,
1257
+ "lr": 1.0,
1258
+ "lr_schedule": "plateau",
1259
+ "top_p": 0.16,
1260
+ "min_k": 128,
1261
+ "max_k": 1024,
1262
+ "lr_gamma": 0.99,
1263
+ "lr_patience": 1,
1264
+ "lr_factor": 0.95,
1265
+ "lr_min": 1e-08,
1266
+ "lr_cooldown": 0,
1267
+ "lr_threshold": 0.0,
1268
+ "lr_adaptive_mode": "simple-reset",
1269
+ "lr_shape_influence": 1.0,
1270
+ "lr_threshold_mode": "rel",
1271
+ "early_stop_loss": 5e-09,
1272
+ "early_stop_lr": 1.01e-08,
1273
+ "early_stop_stall": 2000,
1274
+ "quant_format": "FP8 (E4M3)",
1275
+ "comfy_quant": true,
1276
+ "full_precision_matrix_mult": true,
1277
+ "scaling_mode": "tensor",
1278
+ "block_size": null,
1279
+ "convrot": false,
1280
+ "convrot_group_size": 256,
1281
+ "exclude_layers": "",
1282
+ "custom_type": null,
1283
+ "custom_block_size": null,
1284
+ "custom_scaling_mode": null,
1285
+ "custom_simple": false,
1286
+ "custom_heur": false,
1287
+ "fallback_type": null,
1288
+ "fallback_block_size": null,
1289
+ "fallback_simple": false,
1290
+ "simple": false,
1291
+ "skip_inefficient_layers": false,
1292
+ "full_matrix": false,
1293
+ "scale_optimization": "fixed",
1294
+ "scale_refinement_rounds": 1,
1295
+ "layer_config_path": "",
1296
+ "layer_config_fullmatch": false,
1297
+ "manual_seed": -1,
1298
+ "verbose": "NORMAL",
1299
+ "low_memory": true,
1300
+ "save_quant_metadata": true
1301
+ }
1302
+ },
1303
+ "11": {
1304
+ "label": "Z-Image",
1305
+ "value": "zimage",
1306
+ "preset_value": "FP8 Compatibility (Tensorwise)",
1307
+ "filters": [
1308
+ "zimage"
1309
+ ],
1310
+ "settings": {
1311
+ "calib_samples": 3072,
1312
+ "optimizer": "prodigy",
1313
+ "num_iter": 2500,
1314
+ "lr": 1.0,
1315
+ "lr_schedule": "plateau",
1316
+ "top_p": 0.14,
1317
+ "min_k": 128,
1318
+ "max_k": 1024,
1319
+ "lr_gamma": 0.99,
1320
+ "lr_patience": 1,
1321
+ "lr_factor": 0.95,
1322
+ "lr_min": 1e-08,
1323
+ "lr_cooldown": 0,
1324
+ "lr_threshold": 0.0,
1325
+ "lr_adaptive_mode": "simple-reset",
1326
+ "lr_shape_influence": 1.0,
1327
+ "lr_threshold_mode": "rel",
1328
+ "early_stop_loss": 5e-09,
1329
+ "early_stop_lr": 1.01e-08,
1330
+ "early_stop_stall": 2000,
1331
+ "quant_format": "FP8 (E4M3)",
1332
+ "comfy_quant": true,
1333
+ "full_precision_matrix_mult": true,
1334
+ "scaling_mode": "tensor",
1335
+ "block_size": null,
1336
+ "convrot": false,
1337
+ "convrot_group_size": 256,
1338
+ "exclude_layers": "",
1339
+ "custom_type": null,
1340
+ "custom_block_size": null,
1341
+ "custom_scaling_mode": null,
1342
+ "custom_simple": false,
1343
+ "custom_heur": false,
1344
+ "fallback_type": null,
1345
+ "fallback_block_size": null,
1346
+ "fallback_simple": false,
1347
+ "simple": false,
1348
+ "skip_inefficient_layers": false,
1349
+ "full_matrix": false,
1350
+ "scale_optimization": "fixed",
1351
+ "scale_refinement_rounds": 1,
1352
+ "layer_config_path": "",
1353
+ "layer_config_fullmatch": false,
1354
+ "manual_seed": -1,
1355
+ "verbose": "NORMAL",
1356
+ "low_memory": true,
1357
+ "save_quant_metadata": true
1358
+ }
1359
+ },
1360
+ "12": {
1361
+ "label": "Z-Image Refiner",
1362
+ "value": "zimage_refiner",
1363
+ "preset_value": "FP8 Compatibility (Tensorwise)",
1364
+ "filters": [
1365
+ "zimage_refiner"
1366
+ ],
1367
+ "settings": {
1368
+ "calib_samples": 3072,
1369
+ "optimizer": "prodigy",
1370
+ "num_iter": 2500,
1371
+ "lr": 1.0,
1372
+ "lr_schedule": "plateau",
1373
+ "top_p": 0.14,
1374
+ "min_k": 128,
1375
+ "max_k": 1024,
1376
+ "lr_gamma": 0.99,
1377
+ "lr_patience": 1,
1378
+ "lr_factor": 0.95,
1379
+ "lr_min": 1e-08,
1380
+ "lr_cooldown": 0,
1381
+ "lr_threshold": 0.0,
1382
+ "lr_adaptive_mode": "simple-reset",
1383
+ "lr_shape_influence": 1.0,
1384
+ "lr_threshold_mode": "rel",
1385
+ "early_stop_loss": 5e-09,
1386
+ "early_stop_lr": 1.01e-08,
1387
+ "early_stop_stall": 2000,
1388
+ "quant_format": "FP8 (E4M3)",
1389
+ "comfy_quant": true,
1390
+ "full_precision_matrix_mult": true,
1391
+ "scaling_mode": "tensor",
1392
+ "block_size": null,
1393
+ "convrot": false,
1394
+ "convrot_group_size": 256,
1395
+ "exclude_layers": "",
1396
+ "custom_type": null,
1397
+ "custom_block_size": null,
1398
+ "custom_scaling_mode": null,
1399
+ "custom_simple": false,
1400
+ "custom_heur": false,
1401
+ "fallback_type": null,
1402
+ "fallback_block_size": null,
1403
+ "fallback_simple": false,
1404
+ "simple": false,
1405
+ "skip_inefficient_layers": false,
1406
+ "full_matrix": false,
1407
+ "scale_optimization": "fixed",
1408
+ "scale_refinement_rounds": 1,
1409
+ "layer_config_path": "",
1410
+ "layer_config_fullmatch": false,
1411
+ "manual_seed": -1,
1412
+ "verbose": "NORMAL",
1413
+ "low_memory": true,
1414
+ "save_quant_metadata": true
1415
+ }
1416
+ },
1417
+ "13": {
1418
+ "label": "distillation_large",
1419
+ "value": "distillation_large",
1420
+ "preset_value": "Normal (Balanced)",
1421
+ "filters": [
1422
+ "distillation_large"
1423
+ ],
1424
+ "settings": {
1425
+ "calib_samples": 2048,
1426
+ "optimizer": "prodigy",
1427
+ "num_iter": 2000,
1428
+ "lr": 1.0,
1429
+ "lr_schedule": "plateau",
1430
+ "top_p": 0.12,
1431
+ "min_k": 128,
1432
+ "max_k": 896,
1433
+ "lr_gamma": 0.99,
1434
+ "lr_patience": 1,
1435
+ "lr_factor": 0.95,
1436
+ "lr_min": 1e-08,
1437
+ "lr_cooldown": 0,
1438
+ "lr_threshold": 0.0,
1439
+ "lr_adaptive_mode": "simple-reset",
1440
+ "lr_shape_influence": 1.0,
1441
+ "lr_threshold_mode": "rel",
1442
+ "early_stop_loss": 5e-09,
1443
+ "early_stop_lr": 1.01e-08,
1444
+ "early_stop_stall": 2000,
1445
+ "quant_format": "FP8 (E4M3)",
1446
+ "comfy_quant": true,
1447
+ "full_precision_matrix_mult": true,
1448
+ "scaling_mode": "tensor",
1449
+ "block_size": null,
1450
+ "convrot": false,
1451
+ "convrot_group_size": 256,
1452
+ "exclude_layers": "",
1453
+ "custom_type": null,
1454
+ "custom_block_size": null,
1455
+ "custom_scaling_mode": null,
1456
+ "custom_simple": false,
1457
+ "custom_heur": false,
1458
+ "fallback_type": null,
1459
+ "fallback_block_size": null,
1460
+ "fallback_simple": false,
1461
+ "simple": false,
1462
+ "skip_inefficient_layers": false,
1463
+ "full_matrix": false,
1464
+ "scale_optimization": "fixed",
1465
+ "scale_refinement_rounds": 1,
1466
+ "layer_config_path": "",
1467
+ "layer_config_fullmatch": false,
1468
+ "manual_seed": -1,
1469
+ "verbose": "NORMAL",
1470
+ "low_memory": true,
1471
+ "save_quant_metadata": true
1472
+ }
1473
+ },
1474
+ "14": {
1475
+ "label": "distillation_small",
1476
+ "value": "distillation_small",
1477
+ "preset_value": "Normal (Balanced)",
1478
+ "filters": [
1479
+ "distillation_small"
1480
+ ],
1481
+ "settings": {
1482
+ "calib_samples": 2048,
1483
+ "optimizer": "prodigy",
1484
+ "num_iter": 2000,
1485
+ "lr": 1.0,
1486
+ "lr_schedule": "plateau",
1487
+ "top_p": 0.12,
1488
+ "min_k": 128,
1489
+ "max_k": 896,
1490
+ "lr_gamma": 0.99,
1491
+ "lr_patience": 1,
1492
+ "lr_factor": 0.95,
1493
+ "lr_min": 1e-08,
1494
+ "lr_cooldown": 0,
1495
+ "lr_threshold": 0.0,
1496
+ "lr_adaptive_mode": "simple-reset",
1497
+ "lr_shape_influence": 1.0,
1498
+ "lr_threshold_mode": "rel",
1499
+ "early_stop_loss": 5e-09,
1500
+ "early_stop_lr": 1.01e-08,
1501
+ "early_stop_stall": 2000,
1502
+ "quant_format": "FP8 (E4M3)",
1503
+ "comfy_quant": true,
1504
+ "full_precision_matrix_mult": true,
1505
+ "scaling_mode": "tensor",
1506
+ "block_size": null,
1507
+ "convrot": false,
1508
+ "convrot_group_size": 256,
1509
+ "exclude_layers": "",
1510
+ "custom_type": null,
1511
+ "custom_block_size": null,
1512
+ "custom_scaling_mode": null,
1513
+ "custom_simple": false,
1514
+ "custom_heur": false,
1515
+ "fallback_type": null,
1516
+ "fallback_block_size": null,
1517
+ "fallback_simple": false,
1518
+ "simple": false,
1519
+ "skip_inefficient_layers": false,
1520
+ "full_matrix": false,
1521
+ "scale_optimization": "fixed",
1522
+ "scale_refinement_rounds": 1,
1523
+ "layer_config_path": "",
1524
+ "layer_config_fullmatch": false,
1525
+ "manual_seed": -1,
1526
+ "verbose": "NORMAL",
1527
+ "low_memory": true,
1528
+ "save_quant_metadata": true
1529
+ }
1530
+ },
1531
+ "15": {
1532
+ "label": "FLUX 2 Klein Models",
1533
+ "value": "flux_klein",
1534
+ "preset_value": "Normal (Balanced)",
1535
+ "filters": [],
1536
+ "settings": {
1537
+ "calib_samples": 2048,
1538
+ "optimizer": "prodigy",
1539
+ "num_iter": 2000,
1540
+ "lr": 1.0,
1541
+ "lr_schedule": "plateau",
1542
+ "top_p": 0.12,
1543
+ "min_k": 128,
1544
+ "max_k": 896,
1545
+ "lr_gamma": 0.99,
1546
+ "lr_patience": 1,
1547
+ "lr_factor": 0.95,
1548
+ "lr_min": 1e-08,
1549
+ "lr_cooldown": 0,
1550
+ "lr_threshold": 0.0,
1551
+ "lr_adaptive_mode": "simple-reset",
1552
+ "lr_shape_influence": 1.0,
1553
+ "lr_threshold_mode": "rel",
1554
+ "early_stop_loss": 5e-09,
1555
+ "early_stop_lr": 1.01e-08,
1556
+ "early_stop_stall": 2000,
1557
+ "quant_format": "FP8 (E4M3)",
1558
+ "comfy_quant": true,
1559
+ "full_precision_matrix_mult": true,
1560
+ "scaling_mode": "tensor",
1561
+ "block_size": null,
1562
+ "convrot": false,
1563
+ "convrot_group_size": 256,
1564
+ "exclude_layers": "",
1565
+ "custom_type": null,
1566
+ "custom_block_size": null,
1567
+ "custom_scaling_mode": null,
1568
+ "custom_simple": false,
1569
+ "custom_heur": false,
1570
+ "fallback_type": null,
1571
+ "fallback_block_size": null,
1572
+ "fallback_simple": false,
1573
+ "simple": false,
1574
+ "skip_inefficient_layers": false,
1575
+ "full_matrix": false,
1576
+ "scale_optimization": "fixed",
1577
+ "scale_refinement_rounds": 1,
1578
+ "layer_config_path": "",
1579
+ "layer_config_fullmatch": false,
1580
+ "manual_seed": -1,
1581
+ "verbose": "NORMAL",
1582
+ "low_memory": true,
1583
+ "save_quant_metadata": true
1584
+ }
1585
+ },
1586
+ "16": {
1587
+ "label": "Generic Text Encoder",
1588
+ "value": "generic_text",
1589
+ "preset_value": "Normal (Balanced)",
1590
+ "filters": [
1591
+ "generic_text"
1592
+ ],
1593
+ "settings": {
1594
+ "calib_samples": 2048,
1595
+ "optimizer": "prodigy",
1596
+ "num_iter": 2000,
1597
+ "lr": 1.0,
1598
+ "lr_schedule": "plateau",
1599
+ "top_p": 0.12,
1600
+ "min_k": 128,
1601
+ "max_k": 896,
1602
+ "lr_gamma": 0.99,
1603
+ "lr_patience": 1,
1604
+ "lr_factor": 0.95,
1605
+ "lr_min": 1e-08,
1606
+ "lr_cooldown": 0,
1607
+ "lr_threshold": 0.0,
1608
+ "lr_adaptive_mode": "simple-reset",
1609
+ "lr_shape_influence": 1.0,
1610
+ "lr_threshold_mode": "rel",
1611
+ "early_stop_loss": 5e-09,
1612
+ "early_stop_lr": 1.01e-08,
1613
+ "early_stop_stall": 2000,
1614
+ "quant_format": "FP8 (E4M3)",
1615
+ "comfy_quant": true,
1616
+ "full_precision_matrix_mult": true,
1617
+ "scaling_mode": "tensor",
1618
+ "block_size": null,
1619
+ "convrot": false,
1620
+ "convrot_group_size": 256,
1621
+ "exclude_layers": "",
1622
+ "custom_type": null,
1623
+ "custom_block_size": null,
1624
+ "custom_scaling_mode": null,
1625
+ "custom_simple": false,
1626
+ "custom_heur": false,
1627
+ "fallback_type": null,
1628
+ "fallback_block_size": null,
1629
+ "fallback_simple": false,
1630
+ "simple": false,
1631
+ "skip_inefficient_layers": false,
1632
+ "full_matrix": false,
1633
+ "scale_optimization": "fixed",
1634
+ "scale_refinement_rounds": 1,
1635
+ "layer_config_path": "",
1636
+ "layer_config_fullmatch": false,
1637
+ "manual_seed": -1,
1638
+ "verbose": "NORMAL",
1639
+ "low_memory": true,
1640
+ "save_quant_metadata": true
1641
+ }
1642
+ },
1643
+ "17": {
1644
+ "label": "mistral",
1645
+ "value": "mistral",
1646
+ "preset_value": "Normal (Balanced)",
1647
+ "filters": [
1648
+ "mistral"
1649
+ ],
1650
+ "settings": {
1651
+ "calib_samples": 2048,
1652
+ "optimizer": "prodigy",
1653
+ "num_iter": 2000,
1654
+ "lr": 1.0,
1655
+ "lr_schedule": "plateau",
1656
+ "top_p": 0.12,
1657
+ "min_k": 128,
1658
+ "max_k": 896,
1659
+ "lr_gamma": 0.99,
1660
+ "lr_patience": 1,
1661
+ "lr_factor": 0.95,
1662
+ "lr_min": 1e-08,
1663
+ "lr_cooldown": 0,
1664
+ "lr_threshold": 0.0,
1665
+ "lr_adaptive_mode": "simple-reset",
1666
+ "lr_shape_influence": 1.0,
1667
+ "lr_threshold_mode": "rel",
1668
+ "early_stop_loss": 5e-09,
1669
+ "early_stop_lr": 1.01e-08,
1670
+ "early_stop_stall": 2000,
1671
+ "quant_format": "FP8 (E4M3)",
1672
+ "comfy_quant": true,
1673
+ "full_precision_matrix_mult": true,
1674
+ "scaling_mode": "tensor",
1675
+ "block_size": null,
1676
+ "convrot": false,
1677
+ "convrot_group_size": 256,
1678
+ "exclude_layers": "",
1679
+ "custom_type": null,
1680
+ "custom_block_size": null,
1681
+ "custom_scaling_mode": null,
1682
+ "custom_simple": false,
1683
+ "custom_heur": false,
1684
+ "fallback_type": null,
1685
+ "fallback_block_size": null,
1686
+ "fallback_simple": false,
1687
+ "simple": false,
1688
+ "skip_inefficient_layers": false,
1689
+ "full_matrix": false,
1690
+ "scale_optimization": "fixed",
1691
+ "scale_refinement_rounds": 1,
1692
+ "layer_config_path": "",
1693
+ "layer_config_fullmatch": false,
1694
+ "manual_seed": -1,
1695
+ "verbose": "NORMAL",
1696
+ "low_memory": true,
1697
+ "save_quant_metadata": true
1698
+ }
1699
+ },
1700
+ "18": {
1701
+ "label": "nerf_large",
1702
+ "value": "nerf_large",
1703
+ "preset_value": "Normal (Balanced)",
1704
+ "filters": [
1705
+ "nerf_large"
1706
+ ],
1707
+ "settings": {
1708
+ "calib_samples": 2048,
1709
+ "optimizer": "prodigy",
1710
+ "num_iter": 2000,
1711
+ "lr": 1.0,
1712
+ "lr_schedule": "plateau",
1713
+ "top_p": 0.12,
1714
+ "min_k": 128,
1715
+ "max_k": 896,
1716
+ "lr_gamma": 0.99,
1717
+ "lr_patience": 1,
1718
+ "lr_factor": 0.95,
1719
+ "lr_min": 1e-08,
1720
+ "lr_cooldown": 0,
1721
+ "lr_threshold": 0.0,
1722
+ "lr_adaptive_mode": "simple-reset",
1723
+ "lr_shape_influence": 1.0,
1724
+ "lr_threshold_mode": "rel",
1725
+ "early_stop_loss": 5e-09,
1726
+ "early_stop_lr": 1.01e-08,
1727
+ "early_stop_stall": 2000,
1728
+ "quant_format": "FP8 (E4M3)",
1729
+ "comfy_quant": true,
1730
+ "full_precision_matrix_mult": true,
1731
+ "scaling_mode": "tensor",
1732
+ "block_size": null,
1733
+ "convrot": false,
1734
+ "convrot_group_size": 256,
1735
+ "exclude_layers": "",
1736
+ "custom_type": null,
1737
+ "custom_block_size": null,
1738
+ "custom_scaling_mode": null,
1739
+ "custom_simple": false,
1740
+ "custom_heur": false,
1741
+ "fallback_type": null,
1742
+ "fallback_block_size": null,
1743
+ "fallback_simple": false,
1744
+ "simple": false,
1745
+ "skip_inefficient_layers": false,
1746
+ "full_matrix": false,
1747
+ "scale_optimization": "fixed",
1748
+ "scale_refinement_rounds": 1,
1749
+ "layer_config_path": "",
1750
+ "layer_config_fullmatch": false,
1751
+ "manual_seed": -1,
1752
+ "verbose": "NORMAL",
1753
+ "low_memory": true,
1754
+ "save_quant_metadata": true
1755
+ }
1756
+ },
1757
+ "19": {
1758
+ "label": "nerf_small",
1759
+ "value": "nerf_small",
1760
+ "preset_value": "Normal (Balanced)",
1761
+ "filters": [
1762
+ "nerf_small"
1763
+ ],
1764
+ "settings": {
1765
+ "calib_samples": 2048,
1766
+ "optimizer": "prodigy",
1767
+ "num_iter": 2000,
1768
+ "lr": 1.0,
1769
+ "lr_schedule": "plateau",
1770
+ "top_p": 0.12,
1771
+ "min_k": 128,
1772
+ "max_k": 896,
1773
+ "lr_gamma": 0.99,
1774
+ "lr_patience": 1,
1775
+ "lr_factor": 0.95,
1776
+ "lr_min": 1e-08,
1777
+ "lr_cooldown": 0,
1778
+ "lr_threshold": 0.0,
1779
+ "lr_adaptive_mode": "simple-reset",
1780
+ "lr_shape_influence": 1.0,
1781
+ "lr_threshold_mode": "rel",
1782
+ "early_stop_loss": 5e-09,
1783
+ "early_stop_lr": 1.01e-08,
1784
+ "early_stop_stall": 2000,
1785
+ "quant_format": "FP8 (E4M3)",
1786
+ "comfy_quant": true,
1787
+ "full_precision_matrix_mult": true,
1788
+ "scaling_mode": "tensor",
1789
+ "block_size": null,
1790
+ "convrot": false,
1791
+ "convrot_group_size": 256,
1792
+ "exclude_layers": "",
1793
+ "custom_type": null,
1794
+ "custom_block_size": null,
1795
+ "custom_scaling_mode": null,
1796
+ "custom_simple": false,
1797
+ "custom_heur": false,
1798
+ "fallback_type": null,
1799
+ "fallback_block_size": null,
1800
+ "fallback_simple": false,
1801
+ "simple": false,
1802
+ "skip_inefficient_layers": false,
1803
+ "full_matrix": false,
1804
+ "scale_optimization": "fixed",
1805
+ "scale_refinement_rounds": 1,
1806
+ "layer_config_path": "",
1807
+ "layer_config_fullmatch": false,
1808
+ "manual_seed": -1,
1809
+ "verbose": "NORMAL",
1810
+ "low_memory": true,
1811
+ "save_quant_metadata": true
1812
+ }
1813
+ },
1814
+ "20": {
1815
+ "label": "Qwen2.5 Text/Multimodal",
1816
+ "value": "qwen35",
1817
+ "preset_value": "Normal (Balanced)",
1818
+ "filters": [
1819
+ "generic_text",
1820
+ "qwen35"
1821
+ ],
1822
+ "settings": {
1823
+ "calib_samples": 2048,
1824
+ "optimizer": "prodigy",
1825
+ "num_iter": 2000,
1826
+ "lr": 1.0,
1827
+ "lr_schedule": "plateau",
1828
+ "top_p": 0.12,
1829
+ "min_k": 128,
1830
+ "max_k": 896,
1831
+ "lr_gamma": 0.99,
1832
+ "lr_patience": 1,
1833
+ "lr_factor": 0.95,
1834
+ "lr_min": 1e-08,
1835
+ "lr_cooldown": 0,
1836
+ "lr_threshold": 0.0,
1837
+ "lr_adaptive_mode": "simple-reset",
1838
+ "lr_shape_influence": 1.0,
1839
+ "lr_threshold_mode": "rel",
1840
+ "early_stop_loss": 5e-09,
1841
+ "early_stop_lr": 1.01e-08,
1842
+ "early_stop_stall": 2000,
1843
+ "quant_format": "FP8 (E4M3)",
1844
+ "comfy_quant": true,
1845
+ "full_precision_matrix_mult": true,
1846
+ "scaling_mode": "tensor",
1847
+ "block_size": null,
1848
+ "convrot": false,
1849
+ "convrot_group_size": 256,
1850
+ "exclude_layers": "",
1851
+ "custom_type": null,
1852
+ "custom_block_size": null,
1853
+ "custom_scaling_mode": null,
1854
+ "custom_simple": false,
1855
+ "custom_heur": false,
1856
+ "fallback_type": null,
1857
+ "fallback_block_size": null,
1858
+ "fallback_simple": false,
1859
+ "simple": false,
1860
+ "skip_inefficient_layers": false,
1861
+ "full_matrix": false,
1862
+ "scale_optimization": "fixed",
1863
+ "scale_refinement_rounds": 1,
1864
+ "layer_config_path": "",
1865
+ "layer_config_fullmatch": false,
1866
+ "manual_seed": -1,
1867
+ "verbose": "NORMAL",
1868
+ "low_memory": true,
1869
+ "save_quant_metadata": true
1870
+ }
1871
+ },
1872
+ "21": {
1873
+ "label": "radiance",
1874
+ "value": "radiance",
1875
+ "preset_value": "Normal (Balanced)",
1876
+ "filters": [
1877
+ "radiance"
1878
+ ],
1879
+ "settings": {
1880
+ "calib_samples": 2048,
1881
+ "optimizer": "prodigy",
1882
+ "num_iter": 2000,
1883
+ "lr": 1.0,
1884
+ "lr_schedule": "plateau",
1885
+ "top_p": 0.12,
1886
+ "min_k": 128,
1887
+ "max_k": 896,
1888
+ "lr_gamma": 0.99,
1889
+ "lr_patience": 1,
1890
+ "lr_factor": 0.95,
1891
+ "lr_min": 1e-08,
1892
+ "lr_cooldown": 0,
1893
+ "lr_threshold": 0.0,
1894
+ "lr_adaptive_mode": "simple-reset",
1895
+ "lr_shape_influence": 1.0,
1896
+ "lr_threshold_mode": "rel",
1897
+ "early_stop_loss": 5e-09,
1898
+ "early_stop_lr": 1.01e-08,
1899
+ "early_stop_stall": 2000,
1900
+ "quant_format": "FP8 (E4M3)",
1901
+ "comfy_quant": true,
1902
+ "full_precision_matrix_mult": true,
1903
+ "scaling_mode": "tensor",
1904
+ "block_size": null,
1905
+ "convrot": false,
1906
+ "convrot_group_size": 256,
1907
+ "exclude_layers": "",
1908
+ "custom_type": null,
1909
+ "custom_block_size": null,
1910
+ "custom_scaling_mode": null,
1911
+ "custom_simple": false,
1912
+ "custom_heur": false,
1913
+ "fallback_type": null,
1914
+ "fallback_block_size": null,
1915
+ "fallback_simple": false,
1916
+ "simple": false,
1917
+ "skip_inefficient_layers": false,
1918
+ "full_matrix": false,
1919
+ "scale_optimization": "fixed",
1920
+ "scale_refinement_rounds": 1,
1921
+ "layer_config_path": "",
1922
+ "layer_config_fullmatch": false,
1923
+ "manual_seed": -1,
1924
+ "verbose": "NORMAL",
1925
+ "low_memory": true,
1926
+ "save_quant_metadata": true
1927
+ }
1928
+ },
1929
+ "22": {
1930
+ "label": "T5-XXL",
1931
+ "value": "t5xxl",
1932
+ "preset_value": "Normal (Balanced)",
1933
+ "filters": [
1934
+ "t5xxl"
1935
+ ],
1936
+ "settings": {
1937
+ "calib_samples": 2048,
1938
+ "optimizer": "prodigy",
1939
+ "num_iter": 2000,
1940
+ "lr": 1.0,
1941
+ "lr_schedule": "plateau",
1942
+ "top_p": 0.12,
1943
+ "min_k": 128,
1944
+ "max_k": 896,
1945
+ "lr_gamma": 0.99,
1946
+ "lr_patience": 1,
1947
+ "lr_factor": 0.95,
1948
+ "lr_min": 1e-08,
1949
+ "lr_cooldown": 0,
1950
+ "lr_threshold": 0.0,
1951
+ "lr_adaptive_mode": "simple-reset",
1952
+ "lr_shape_influence": 1.0,
1953
+ "lr_threshold_mode": "rel",
1954
+ "early_stop_loss": 5e-09,
1955
+ "early_stop_lr": 1.01e-08,
1956
+ "early_stop_stall": 2000,
1957
+ "quant_format": "FP8 (E4M3)",
1958
+ "comfy_quant": true,
1959
+ "full_precision_matrix_mult": true,
1960
+ "scaling_mode": "tensor",
1961
+ "block_size": null,
1962
+ "convrot": false,
1963
+ "convrot_group_size": 256,
1964
+ "exclude_layers": "",
1965
+ "custom_type": null,
1966
+ "custom_block_size": null,
1967
+ "custom_scaling_mode": null,
1968
+ "custom_simple": false,
1969
+ "custom_heur": false,
1970
+ "fallback_type": null,
1971
+ "fallback_block_size": null,
1972
+ "fallback_simple": false,
1973
+ "simple": false,
1974
+ "skip_inefficient_layers": false,
1975
+ "full_matrix": false,
1976
+ "scale_optimization": "fixed",
1977
+ "scale_refinement_rounds": 1,
1978
+ "layer_config_path": "",
1979
+ "layer_config_fullmatch": false,
1980
+ "manual_seed": -1,
1981
+ "verbose": "NORMAL",
1982
+ "low_memory": true,
1983
+ "save_quant_metadata": true,
1984
+ "include_input_scale": true
1985
+ }
1986
+ },
1987
+ "23": {
1988
+ "label": "visual",
1989
+ "value": "visual",
1990
+ "preset_value": "Normal (Balanced)",
1991
+ "filters": [
1992
+ "visual"
1993
+ ],
1994
+ "settings": {
1995
+ "calib_samples": 2048,
1996
+ "optimizer": "prodigy",
1997
+ "num_iter": 2000,
1998
+ "lr": 1.0,
1999
+ "lr_schedule": "plateau",
2000
+ "top_p": 0.12,
2001
+ "min_k": 128,
2002
+ "max_k": 896,
2003
+ "lr_gamma": 0.99,
2004
+ "lr_patience": 1,
2005
+ "lr_factor": 0.95,
2006
+ "lr_min": 1e-08,
2007
+ "lr_cooldown": 0,
2008
+ "lr_threshold": 0.0,
2009
+ "lr_adaptive_mode": "simple-reset",
2010
+ "lr_shape_influence": 1.0,
2011
+ "lr_threshold_mode": "rel",
2012
+ "early_stop_loss": 5e-09,
2013
+ "early_stop_lr": 1.01e-08,
2014
+ "early_stop_stall": 2000,
2015
+ "quant_format": "FP8 (E4M3)",
2016
+ "comfy_quant": true,
2017
+ "full_precision_matrix_mult": true,
2018
+ "scaling_mode": "tensor",
2019
+ "block_size": null,
2020
+ "convrot": false,
2021
+ "convrot_group_size": 256,
2022
+ "exclude_layers": "",
2023
+ "custom_type": null,
2024
+ "custom_block_size": null,
2025
+ "custom_scaling_mode": null,
2026
+ "custom_simple": false,
2027
+ "custom_heur": false,
2028
+ "fallback_type": null,
2029
+ "fallback_block_size": null,
2030
+ "fallback_simple": false,
2031
+ "simple": false,
2032
+ "skip_inefficient_layers": false,
2033
+ "full_matrix": false,
2034
+ "scale_optimization": "fixed",
2035
+ "scale_refinement_rounds": 1,
2036
+ "layer_config_path": "",
2037
+ "layer_config_fullmatch": false,
2038
+ "manual_seed": -1,
2039
+ "verbose": "NORMAL",
2040
+ "low_memory": true,
2041
+ "save_quant_metadata": true
2042
+ }
2043
+ }
2044
+ },
2045
+ "known_filters": [
2046
+ "anima",
2047
+ "distillation_large",
2048
+ "distillation_small",
2049
+ "flux2",
2050
+ "generic_text",
2051
+ "hunyuan",
2052
+ "lens",
2053
+ "ltxv2",
2054
+ "mistral",
2055
+ "nerf_large",
2056
+ "nerf_small",
2057
+ "qwen",
2058
+ "qwen35",
2059
+ "radiance",
2060
+ "t5xxl",
2061
+ "visual",
2062
+ "wan",
2063
+ "zimage",
2064
+ "zimage_refiner"
2065
+ ]
2066
+ }
SECourses_Musubi_Trainer/venv/bin/python ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b94e9b56bc1f96b18d36a0f1d14308575bb7b5960eda94ae0520f0376e95d12d
3
+ size 5909000
SECourses_Musubi_Trainer/venv/bin/python3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b94e9b56bc1f96b18d36a0f1d14308575bb7b5960eda94ae0520f0376e95d12d
3
+ size 5909000
SECourses_Musubi_Trainer/venv/bin/python3.10 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b94e9b56bc1f96b18d36a0f1d14308575bb7b5960eda94ae0520f0376e95d12d
3
+ size 5909000
SECourses_Musubi_Trainer/venv/pyvenv.cfg ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ home = /usr/bin
2
+ include-system-site-packages = false
3
+ version = 3.10.12
SECourses_Musubi_Trainer/wan_defaults.toml ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Wan Models Training - Optimal Defaults Configuration
2
+ # This file contains the recommended default values for Wan model training
3
+ # Supports all Wan models: T2V, I2V, T2I, FLF2V, Fun-Control, and Wan 2.2 Advanced models
4
+ # Based on Wan documentation and best practices
5
+
6
+ # Training Mode Selection
7
+ training_mode = "LoRA Training" # The installed Wan backend supports LoRA/network training.
8
+
9
+ # Wan Model Selection - REQUIRED
10
+ task = "t2v-14B" # REQUIRED: Wan model type (t2v-14B, t2v-1.3B, i2v-14B, t2i-14B, flf2v-14B, t2v-1.3B-FC, t2v-14B-FC, i2v-14B-FC, t2v-A14B, i2v-A14B)
11
+
12
+ # Model Settings - REQUIRED FIELDS MUST BE SET BY USER
13
+ dit = "" # REQUIRED: Path to DiT checkpoint (.safetensors)
14
+ vae = "" # REQUIRED: Path to VAE checkpoint (Wan2.1_VAE.pth or wan_2.1_vae.safetensors)
15
+ t5 = "" # REQUIRED: Path to T5 text encoder (umt5-xxl-enc-bf16.safetensors)
16
+ clip = "" # REQUIRED ONLY for i2v-14B, flf2v-14B, i2v-14B-FC models. Path to CLIP vision encoder (models_clip_open-clip-xlm-roberta-large-vit-huge-14.safetensors)
17
+ dataset_config = "" # Path to dataset TOML configuration (required if using "Use TOML File" mode)
18
+ dataset_config_mode = "Generate from Folder Structure" # Default to auto-generate from folder structure
19
+
20
+ # Wan 2.2 Advanced Models (A14B) - Dual Model System
21
+ dit_high_noise = "" # [WAN 2.2 ONLY] Path to high noise DiT model for Wan 2.2 Advanced models (t2v-A14B, i2v-A14B)
22
+ timestep_boundary = 0.0 # [WAN 2.2 ONLY] Timestep boundary for dual model system. Auto-detected from model config if not set
23
+ offload_inactive_dit = false # [WAN 2.2 ONLY] Offload inactive DiT to CPU to save VRAM during dual model training
24
+ use_pinned_memory_for_block_swap = false # Use Pinned Memory for Block Swapping: Uses more system RAM but speeds up training. The speed up maybe significant depending on system settings. To work, go to Advanced Graphics settings in System > Display > Graphics as in tutorial video and disable Hardware-Accelerated GPU Scheduling and restart your PC. Only effective when blocks_to_swap > 0
25
+ block_swap_h2d_only = false # LoRA only; requires blocks_to_swap > 0 and gradient_checkpointing; use standard swap for Wan 2.2 dual-DiT
26
+ block_swap_ring_size = 2 # 2 overlaps transfer/compute; 1 minimizes VRAM
27
+
28
+ # Folder Structure Settings (used when dataset_config_mode = "Generate from Folder Structure")
29
+ parent_folder_path = "" # REQUIRED when using folder structure mode: Path to parent folder containing training images/videos
30
+ dataset_resolution_width = 960 # Target width for training. Optimal resolutions: 960×960, 1280×720, 720×1280
31
+ dataset_resolution_height = 960 # Target height for training. Optimal resolutions: 960×960, 1280×720, 720×1280
32
+ dataset_caption_extension = ".txt" # Extension for caption files
33
+ create_missing_captions = true # Auto-create empty captions for images without caption files
34
+ caption_strategy = "folder_name" # How to handle missing captions: "folder_name" or "empty"
35
+ dataset_batch_size = 1 # Batch size for dataset processing
36
+ dataset_enable_bucket = false # Enable bucketing for variable aspect ratios
37
+ dataset_bucket_no_upscale = false # Prevent upscaling in bucket mode
38
+ dataset_cache_directory = "cache_dir" # Directory for caching processed data
39
+ generated_toml_path = "" # Path where generated TOML will be saved (auto-set)
40
+
41
+ # Video-specific Settings (for T2V, I2V, FLF2V models)
42
+ num_frames = 81 # Number of frames for video training (81 is default for Wan models)
43
+ one_frame = false # Enable one-frame training mode for image-like training on video models
44
+
45
+ # Video Frame Extraction Settings
46
+ frame_extraction = "head" # Frame extraction method: "head" (recommended), "chunk", "slide", "uniform", "full"
47
+ frame_stride = 1 # Step size for sliding window extraction (used with "slide" method)
48
+ frame_sample = 1 # Number of samples to extract (used with "uniform" method)
49
+ # Dataset generation target_frames (written into generated dataset TOML for video datasets)
50
+ target_frames = 81 # Target video frame count for dataset generation (saved as target_frames=[N]). Must be N*4+1 (1,5,9,...,81)
51
+ auto_normalize_target_frames = true # Scan dataset and clamp Target Frames to the minimum video length found (then round to N*4+1)
52
+ max_frames = 129 # Maximum number of frames to extract from any video (used with "full" method)
53
+ source_fps = 0 # Original video FPS for frame rate conversion (0=auto-detect)
54
+
55
+ # Data Types and Precision
56
+ dit_dtype = "bfloat16" # DiT model data type. bfloat16=best quality, float16=faster
57
+ text_encoder_dtype = "bfloat16" # T5 text encoder data type
58
+ vae_dtype = "bfloat16" # VAE data type
59
+ clip_vision_dtype = "bfloat16" # CLIP vision encoder data type
60
+
61
+ # Memory Optimization Settings
62
+ fp8_base = false # Enable FP8 for DiT model to reduce VRAM usage (requires fp8_scaled=true)
63
+ fp8_scaled = false # REQUIRED when fp8_base=true, provides better quality than standard FP8
64
+ fp8_t5 = false # Enable FP8 for the T5 text encoder to reduce VRAM usage
65
+ blocks_to_swap = 0 # 0=disabled. Max varies by model. Higher values save more VRAM but require more RAM
66
+
67
+ # VAE Optimization Settings
68
+ vae_tiling = false # Enable spatial tiling to reduce VRAM usage during VAE operations
69
+ vae_chunk_size = 0 # 0=auto/disabled. Higher=faster but more VRAM
70
+ vae_spatial_tile_sample_min_size = 0 # 0=disabled. 256=typical. Auto-enables vae_tiling if set
71
+
72
+ # Flow Matching Settings (Wan uses Flow Matching instead of diffusion)
73
+ timestep_sampling = "uniform" # Timestep sampling method: "uniform", "sigmoid", "shift"
74
+ discrete_flow_shift = 1.0 # Discrete flow shift parameter
75
+ weighting_scheme = "none" # Loss weighting scheme: "none", "mode"
76
+ logit_mean = 0.0 # Logit mean for timestep sampling
77
+ logit_std = 1.0 # Logit standard deviation for timestep sampling
78
+ mode_scale = 1.29 # Mode scale for weighting scheme
79
+
80
+ # Advanced Timestep Parameters
81
+ sigmoid_scale = 1.0 # Scale factor for sigmoid timestep sampling
82
+ min_timestep = 0 # Minimum timestep constraint (0=no constraint)
83
+ max_timestep = 1000 # Maximum timestep constraint (1000=no constraint)
84
+ preserve_distribution_shape = false # Preserve original distribution when using min/max constraints
85
+ num_timestep_buckets = 0 # 0=disabled. 4-10=bucketed sampling for uniform distribution
86
+
87
+ # Training Settings
88
+ sdpa = true # Use PyTorch's scaled dot product attention (recommended)
89
+ flash_attn = false # Use Flash Attention (requires installation)
90
+ sage_attn = false # Use Sage Attention (inference only)
91
+ xformers = false # Use xFormers attention
92
+ split_attn = false # Split attention computation to reduce peak memory use
93
+ use_legacy_sdpa = false # Force the older PyTorch SDPA path instead of automatic verified acceleration
94
+ max_train_steps = 90000 # Maximum training steps
95
+ max_train_epochs = 200 # Maximum training epochs
96
+ max_data_loader_n_workers = 2 # Number of data loader workers
97
+ persistent_data_loader_workers = true # Keep data loader workers persistent
98
+ seed = 99 # Random seed for reproducibility
99
+ gradient_checkpointing = true # Enable gradient checkpointing to save VRAM
100
+ gradient_accumulation_steps = 1 # Number of gradient accumulation steps
101
+ full_bf16 = false # EXPERIMENTAL: Store gradients in BF16 to save VRAM (currently disabled in backend)
102
+ full_fp16 = false # EXPERIMENTAL: Store gradients in FP16 to save VRAM (currently disabled in backend)
103
+
104
+ # Optimizer Settings
105
+ optimizer_type = "adamw8bit" # Optimizer type (adamw8bit recommended for memory efficiency)
106
+ optimizer_args = [] # Additional optimizer arguments
107
+ learning_rate = 1e-4 # Learning rate (1e-4 is good default for Wan models)
108
+ max_grad_norm = 1.0 # Maximum gradient norm for clipping
109
+ lr_scheduler = "constant" # Learning rate scheduler type
110
+ lr_warmup_steps = 0 # Number of warmup steps (0=no warmup)
111
+ lr_decay_steps = 0 # Number of decay steps (0=no decay)
112
+ lr_scheduler_num_cycles = 1 # Number of scheduler cycles
113
+ lr_scheduler_power = 1.0 # Scheduler power parameter
114
+ lr_scheduler_timescale = 0 # Scheduler timescale (0=auto)
115
+ lr_scheduler_min_lr_ratio = 0.0 # Minimum learning rate ratio
116
+ lr_scheduler_type = "" # Additional scheduler type
117
+ lr_scheduler_args = [] # Additional scheduler arguments
118
+
119
+ # Network Settings (LoRA Mode Only - Ignored in DreamBooth Mode)
120
+ no_metadata = false # Disable metadata saving
121
+ network_weights = "" # Path to pretrained LoRA weights to continue training
122
+ network_module = "networks.lora_wan" # Network module for LoRA (auto-set based on training mode)
123
+ network_dim = 16 # LoRA network dimension/rank (16 recommended for Wan models)
124
+ network_alpha = 16.0 # LoRA alpha parameter (typically equal to network_dim)
125
+ network_dropout = 0.0 # LoRA dropout rate (0.0=no dropout)
126
+ network_args = [] # Additional network arguments
127
+ training_comment = "" # Training comment for metadata
128
+ dim_from_weights = false # Extract dimensions from existing weights
129
+ scale_weight_norms = 0.0 # Scale weight norms (0.0=disabled)
130
+ base_weights = "" # Path to base LoRA weights to merge
131
+ base_weights_multiplier = 1.0 # Multiplier for base weights
132
+
133
+ # Save/Load Settings
134
+ output_dir = "" # Output directory for saved models
135
+ output_name = "my-wan-lora" # Base filename for saved models
136
+ resume = "" # Path to checkpoint to resume training from
137
+ save_precision = "bf16" # LoRA output dtype; BF16 keeps files about half the size of FP32
138
+ save_every_n_epochs = 10 # Save checkpoint every N epochs
139
+ save_every_n_steps = 0 # Save checkpoint every N steps (0=disabled)
140
+ save_last_n_epochs = 0 # Keep only last N epoch checkpoints (0=keep all)
141
+ save_last_n_epochs_state = 0 # Keep only last N epoch states (0=keep all)
142
+ save_last_n_steps = 0 # Keep only last N step checkpoints (0=keep all)
143
+ save_last_n_steps_state = 0 # Keep only last N step states (0=keep all)
144
+ save_state = false # Save training state
145
+ save_state_on_train_end = false # Save state when training ends
146
+ mem_eff_save = false # Memory efficient saving for DreamBooth fine-tuning mode
147
+
148
+ # Caching Settings - Latents
149
+ caching_latent_device = "cuda" # Device for latent caching
150
+ caching_latent_batch_size = 4 # Batch size for latent caching
151
+ caching_latent_num_workers = 8 # Number of workers for latent caching
152
+ caching_latent_skip_existing = true # Skip existing cached latents
153
+ caching_latent_keep_cache = true # Keep cache after training
154
+ caching_latent_debug_mode = "" # Debug mode for latent caching
155
+ caching_latent_console_width = 80 # Console width for debug output
156
+ caching_latent_console_back = "" # Console background for debug
157
+ caching_latent_console_num_images = 0 # Number of images in debug console (0=no limit)
158
+
159
+ # Caching Settings - Text Encoder
160
+ caching_teo_text_encoder1 = "" # Optional T5 override for caching; empty uses the model T5 path
161
+ caching_teo_text_encoder2 = "" # Reserved optional second text encoder path
162
+ caching_teo_device = "cuda" # Device for text encoder caching
163
+ caching_teo_fp8_llm = false # Use FP8 for T5 text encoder caching
164
+ caching_teo_batch_size = 16 # Batch size for text encoder caching
165
+ caching_teo_num_workers = 8 # Number of workers for text encoder caching
166
+ caching_teo_skip_existing = true # Skip existing cached outputs
167
+ caching_teo_keep_cache = true # Keep cache after training
168
+
169
+ # Torch compile (optional)
170
+ compile = false
171
+ compile_backend = "inductor"
172
+ compile_mode = "default"
173
+ compile_dynamic = "auto" # "auto" | "true" | "false"
174
+ compile_fullgraph = false
175
+ compile_cache_size_limit = 0 # 0 = use PyTorch default
176
+
177
+ # Accelerate Launch Settings
178
+ mixed_precision = "bf16" # Mixed precision training (bf16 recommended for Wan)
179
+ multi_gpu = false # Enable multi-GPU training
180
+ gpu_ids = "0" # GPU IDs for distributed training
181
+ num_processes = 1 # Number of processes for distributed training
182
+ num_machines = 1 # Number of machines for distributed training
183
+ num_cpu_threads_per_process = 2 # CPU threads per process
184
+ main_process_port = 0 # Port for distributed communication (0=auto)
185
+ dynamo_backend = "no" # PyTorch dynamo backend (no=disabled)
186
+ dynamo_mode = "" # Dynamo optimization mode
187
+ dynamo_use_fullgraph = false # Use fullgraph mode for dynamo
188
+ dynamo_use_dynamic = false # Use dynamic mode for dynamo
189
+ extra_accelerate_launch_args = "" # Additional accelerate launch arguments
190
+
191
+ # Logging Settings
192
+ logging_dir = "" # Directory for training logs
193
+ log_prefix = "" # Prefix for log files
194
+ log_tracker_name = "" # Name for experiment tracking
195
+ wandb_run_name = "" # Weights & Biases run name
196
+ log_tracker_config = "" # Configuration for experiment tracking
197
+ wandb_api_key = "" # Weights & Biases API key
198
+ log_config = false # Log configuration to tracker
199
+
200
+ # DDP Settings (Distributed Training)
201
+ ddp_timeout = 0 # DDP timeout in minutes (0=default)
202
+ ddp_gradient_as_bucket_view = false # Use gradient as bucket view
203
+ ddp_static_graph = false # Use static graph for DDP
204
+
205
+ # Sample Generation Settings
206
+ sample_every_n_steps = 0 # Generate samples every N steps (0=disabled)
207
+ sample_every_n_epochs = 0 # Generate samples every N epochs (0=disabled)
208
+ sample_at_first = false # Generate samples before training starts
209
+ sample_prompts = "" # Path to file with sample prompts
210
+ disable_prompt_enhancement = false # true = use prompt file exactly as written (no auto-added defaults)
211
+
212
+ # Default Sample Parameters for Video Generation
213
+ sample_width = 960 # Sample video width. Optimal resolutions: 960×960, 1280×720, 720×1280
214
+ sample_height = 960 # Sample video height. Optimal resolutions: 960×960, 1280×720, 720×1280
215
+ sample_num_frames = 81 # Number of frames in sample videos
216
+ sample_steps = 20 # Number of inference steps for samples
217
+ sample_guidance_scale = 7.0 # Default WAN training sample CFG scale (written as --l in enhanced prompts)
218
+ sample_seed = 99 # Seed for sample generation (-1=random)
219
+ sample_negative_prompt = "" # Default negative prompt for samples
220
+
221
+ # Metadata Settings
222
+ metadata_author = "" # Author metadata
223
+ metadata_description = "" # Description metadata
224
+ metadata_license = "" # License metadata
225
+ metadata_tags = "" # Tags metadata
226
+ metadata_title = "" # Title metadata
227
+ metadata_reso = "" # Optional resolution metadata, e.g. 960,960
228
+ metadata_arch = "" # Optional custom architecture metadata
229
+
230
+ # HuggingFace Settings
231
+ huggingface_repo_id = "" # HuggingFace repository ID
232
+ huggingface_token = "" # HuggingFace API token
233
+ huggingface_repo_type = "" # Repository type
234
+ huggingface_repo_visibility = "" # Repository visibility
235
+ huggingface_path_in_repo = "" # Path within repository
236
+ save_state_to_huggingface = false # Save training state to HuggingFace
237
+ resume_from_huggingface = "" # Optional Hugging Face resume specification
238
+ async_upload = false # Use async upload to HuggingFace
SECourses_Musubi_Trainer/zimage_defaults.toml ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Z-Image Training - Recommended Defaults (Base + Turbo)
2
+ # Based on musubi-tuner/docs/zimage.md training example.
3
+
4
+ # Z-Image variant selector (GUI-only; training uses your selected DiT checkpoint)
5
+ zimage_variant = "base" # "base" | "turbo"
6
+
7
+ # Training mode (GUI only)
8
+ training_mode = "LoRA Training" # "LoRA Training" | "DreamBooth Fine-Tuning"
9
+
10
+ # Optional: Turbo Training Adapter (LoRA). If set, GUI passes it as base_weights (--base_weights) during training.
11
+ training_adapter_path = ""
12
+ training_adapter_multiplier = 1.0
13
+
14
+ # Required model paths (set these)
15
+ dit = "" # REQUIRED: path to Z-Image DiT checkpoint (Base or Turbo/De-Turbo)
16
+ vae = "" # REQUIRED: path to Z-Image VAE checkpoint
17
+ text_encoder = "" # REQUIRED: path to Qwen3 text encoder (split file 00001-of-...)
18
+
19
+ # Dataset config
20
+ dataset_config_mode = "Generate from Folder Structure" # "Generate from Folder Structure" | "Use TOML File"
21
+ dataset_config = "" # Used when dataset_config_mode="Use TOML File"
22
+ parent_folder_path = "" # Used when dataset_config_mode="Generate from Folder Structure"
23
+ dataset_resolution_width = 1024
24
+ dataset_resolution_height = 1024
25
+ dataset_caption_extension = ".txt"
26
+ create_missing_captions = true
27
+ caption_strategy = "folder_name"
28
+ dataset_batch_size = 1
29
+ dataset_enable_bucket = true
30
+ dataset_bucket_no_upscale = false
31
+ dataset_cache_directory = "cache_dir"
32
+ generated_toml_path = ""
33
+
34
+ # Precision / memory
35
+ mixed_precision = "bf16"
36
+ num_cpu_threads_per_process = 1
37
+ fp8_base = false
38
+ fp8_scaled = false
39
+ fp8_llm = false
40
+ disable_numpy_memmap = false
41
+ blocks_to_swap = 0
42
+ use_pinned_memory_for_block_swap = false
43
+ block_swap_h2d_only = false
44
+ block_swap_ring_size = 2
45
+
46
+ # Training core
47
+ sdpa = true
48
+ flash_attn = false
49
+ sage_attn = false
50
+ xformers = false
51
+ split_attn = false
52
+ use_legacy_sdpa = false
53
+ max_train_epochs = 16
54
+ max_train_steps = 1600
55
+ max_data_loader_n_workers = 2
56
+ persistent_data_loader_workers = true
57
+ seed = 42
58
+ gradient_checkpointing = true
59
+ gradient_checkpointing_cpu_offload = false
60
+ gradient_accumulation_steps = 1
61
+
62
+ # Torch compile (optional)
63
+ compile = false
64
+ compile_backend = "inductor"
65
+ compile_mode = "default"
66
+ compile_dynamic = "auto" # "auto" | "true" | "false"
67
+ compile_fullgraph = false
68
+ compile_cache_size_limit = 0 # 0 = use PyTorch default
69
+
70
+ # Flow matching / timestep sampling (example defaults; adjust if needed)
71
+ timestep_sampling = "shift"
72
+ weighting_scheme = "none"
73
+ discrete_flow_shift = 2.0
74
+ sigmoid_scale = 1.0
75
+ min_timestep = 0
76
+ max_timestep = 1000
77
+
78
+ # Optimizer
79
+ optimizer_type = "adamw8bit"
80
+ optimizer_args = ""
81
+ learning_rate = 1e-4
82
+ max_grad_norm = 1.0
83
+ fused_backward_pass = false # DreamBooth only: reduces VRAM during backward pass with AdaFactor
84
+ lr_scheduler = "constant"
85
+ lr_warmup_steps = 0
86
+ lr_decay_steps = 0
87
+ lr_scheduler_num_cycles = 1
88
+ lr_scheduler_power = 1.0
89
+ lr_scheduler_timescale = 0
90
+ lr_scheduler_min_lr_ratio = 0.0
91
+ lr_scheduler_type = ""
92
+ lr_scheduler_args = ""
93
+
94
+ # Network (LoRA)
95
+ network_module = "networks.lora_zimage"
96
+ network_dim = 32
97
+ network_alpha = 32.0
98
+ network_dropout = 0.0
99
+ network_args = ""
100
+ network_weights = ""
101
+ training_comment = ""
102
+ dim_from_weights = false
103
+ scale_weight_norms = 0.0
104
+ base_weights = ""
105
+ base_weights_multiplier = 1.0
106
+ no_metadata = false
107
+
108
+ # Caching (recommended)
109
+ caching_latent_device = "cuda"
110
+ caching_latent_batch_size = 1
111
+ caching_latent_num_workers = 2
112
+ caching_latent_skip_existing = true
113
+ caching_latent_keep_cache = true
114
+
115
+ caching_teo_device = "cuda"
116
+ caching_teo_batch_size = 8
117
+ caching_teo_num_workers = 2
118
+ caching_teo_skip_existing = true
119
+ caching_teo_keep_cache = true
120
+
121
+ # Samples (optional)
122
+ sample_every_n_steps = 0
123
+ sample_every_n_epochs = 0
124
+ sample_at_first = false
125
+ sample_prompts = ""
126
+ disable_prompt_enhancement = false
127
+ sample_output_dir = ""
128
+ sample_width = 1024
129
+ sample_height = 1024
130
+ sample_steps = 25
131
+ sample_seed = 42
132
+ sample_negative_prompt = ""
133
+ sample_cfg_scale = 4.0
134
+
135
+ # Save / resume
136
+ output_dir = ""
137
+ output_name = "my-zimage-lora"
138
+ resume = ""
139
+ save_precision = "bf16"
140
+ save_every_n_epochs = 1
141
+ save_every_n_steps = 0
142
+ save_last_n_epochs = 0
143
+ save_last_n_steps = 0
144
+ save_last_n_epochs_state = 0
145
+ save_last_n_steps_state = 0
146
+ save_state = false
147
+ save_state_on_train_end = false
148
+ mem_eff_save = false
149
+
150
+ # Advanced
151
+ additional_parameters = ""
152
+ debug_mode = "None"
gradio/frpc/frpc_linux_amd64_v0.3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c791d1f047b41ff5885772fc4bf20b797c6059bbd82abb9e31de15e55d6a57c4
3
+ size 11907224
hub/models--Qwen--Qwen-Image/.no_exist/75e0b4be04f60ec59a75f475837eced720f823b6/tokenizer/tokenizer.json ADDED
File without changes
hub/models--Qwen--Qwen-Image/blobs/28028c056af412405debd878cdda0171e35fa5d1 ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0]['role'] == 'system' %}
4
+ {{- messages[0]['content'] }}
5
+ {%- else %}
6
+ {{- 'You are a helpful assistant.' }}
7
+ {%- endif %}
8
+ {{- "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
9
+ {%- for tool in tools %}
10
+ {{- "\n" }}
11
+ {{- tool | tojson }}
12
+ {%- endfor %}
13
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
14
+ {%- else %}
15
+ {%- if messages[0]['role'] == 'system' %}
16
+ {{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }}
17
+ {%- else %}
18
+ {{- '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }}
19
+ {%- endif %}
20
+ {%- endif %}
21
+ {%- for message in messages %}
22
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) %}
23
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }}
24
+ {%- elif message.role == "assistant" %}
25
+ {{- '<|im_start|>' + message.role }}
26
+ {%- if message.content %}
27
+ {{- '\n' + message.content }}
28
+ {%- endif %}
29
+ {%- for tool_call in message.tool_calls %}
30
+ {%- if tool_call.function is defined %}
31
+ {%- set tool_call = tool_call.function %}
32
+ {%- endif %}
33
+ {{- '\n<tool_call>\n{"name": "' }}
34
+ {{- tool_call.name }}
35
+ {{- '", "arguments": ' }}
36
+ {{- tool_call.arguments | tojson }}
37
+ {{- '}\n</tool_call>' }}
38
+ {%- endfor %}
39
+ {{- '<|im_end|>\n' }}
40
+ {%- elif message.role == "tool" %}
41
+ {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %}
42
+ {{- '<|im_start|>user' }}
43
+ {%- endif %}
44
+ {{- '\n<tool_response>\n' }}
45
+ {{- message.content }}
46
+ {{- '\n</tool_response>' }}
47
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
48
+ {{- '<|im_end|>\n' }}
49
+ {%- endif %}
50
+ {%- endif %}
51
+ {%- endfor %}
52
+ {%- if add_generation_prompt %}
53
+ {{- '<|im_start|>assistant\n' }}
54
+ {%- endif %}
hub/models--Qwen--Qwen-Image/blobs/31349551d90c7606f325fe0f11bbb8bd5fa0d7c7 ADDED
The diff for this file is too large to render. See raw diff
 
hub/models--Qwen--Qwen-Image/blobs/482ced4679301bf287ebb310bdd1790eb4514232 ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</tool_call>": 151658,
3
+ "<tool_call>": 151657,
4
+ "<|box_end|>": 151649,
5
+ "<|box_start|>": 151648,
6
+ "<|endoftext|>": 151643,
7
+ "<|file_sep|>": 151664,
8
+ "<|fim_middle|>": 151660,
9
+ "<|fim_pad|>": 151662,
10
+ "<|fim_prefix|>": 151659,
11
+ "<|fim_suffix|>": 151661,
12
+ "<|im_end|>": 151645,
13
+ "<|im_start|>": 151644,
14
+ "<|image_pad|>": 151655,
15
+ "<|object_ref_end|>": 151647,
16
+ "<|object_ref_start|>": 151646,
17
+ "<|quad_end|>": 151651,
18
+ "<|quad_start|>": 151650,
19
+ "<|repo_name|>": 151663,
20
+ "<|video_pad|>": 151656,
21
+ "<|vision_end|>": 151653,
22
+ "<|vision_pad|>": 151654,
23
+ "<|vision_start|>": 151652
24
+ }
hub/models--Qwen--Qwen-Image/blobs/6bce3a0a3866c4791a74d83d78f6824c3af64ec3 ADDED
The diff for this file is too large to render. See raw diff
 
hub/models--Qwen--Qwen-Image/blobs/ac23c0aaa2434523c494330aeb79c58395378103 ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|im_end|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "<|endoftext|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
hub/models--Qwen--Qwen-Image/blobs/eaed590d62aaf0ba31e284b66ddcb18222f066c2 ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ }
181
+ },
182
+ "additional_special_tokens": [
183
+ "<|im_start|>",
184
+ "<|im_end|>",
185
+ "<|object_ref_start|>",
186
+ "<|object_ref_end|>",
187
+ "<|box_start|>",
188
+ "<|box_end|>",
189
+ "<|quad_start|>",
190
+ "<|quad_end|>",
191
+ "<|vision_start|>",
192
+ "<|vision_end|>",
193
+ "<|vision_pad|>",
194
+ "<|image_pad|>",
195
+ "<|video_pad|>"
196
+ ],
197
+ "bos_token": null,
198
+ "clean_up_tokenization_spaces": false,
199
+ "eos_token": "<|im_end|>",
200
+ "errors": "replace",
201
+ "extra_special_tokens": {},
202
+ "model_max_length": 131072,
203
+ "pad_token": "<|endoftext|>",
204
+ "split_special_tokens": false,
205
+ "tokenizer_class": "Qwen2Tokenizer",
206
+ "unk_token": null
207
+ }
hub/models--Qwen--Qwen-Image/refs/main ADDED
@@ -0,0 +1 @@
 
 
1
+ 75e0b4be04f60ec59a75f475837eced720f823b6
hub/models--Qwen--Qwen-Image/snapshots/75e0b4be04f60ec59a75f475837eced720f823b6/tokenizer/added_tokens.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</tool_call>": 151658,
3
+ "<tool_call>": 151657,
4
+ "<|box_end|>": 151649,
5
+ "<|box_start|>": 151648,
6
+ "<|endoftext|>": 151643,
7
+ "<|file_sep|>": 151664,
8
+ "<|fim_middle|>": 151660,
9
+ "<|fim_pad|>": 151662,
10
+ "<|fim_prefix|>": 151659,
11
+ "<|fim_suffix|>": 151661,
12
+ "<|im_end|>": 151645,
13
+ "<|im_start|>": 151644,
14
+ "<|image_pad|>": 151655,
15
+ "<|object_ref_end|>": 151647,
16
+ "<|object_ref_start|>": 151646,
17
+ "<|quad_end|>": 151651,
18
+ "<|quad_start|>": 151650,
19
+ "<|repo_name|>": 151663,
20
+ "<|video_pad|>": 151656,
21
+ "<|vision_end|>": 151653,
22
+ "<|vision_pad|>": 151654,
23
+ "<|vision_start|>": 151652
24
+ }
hub/models--Qwen--Qwen-Image/snapshots/75e0b4be04f60ec59a75f475837eced720f823b6/tokenizer/chat_template.jinja ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0]['role'] == 'system' %}
4
+ {{- messages[0]['content'] }}
5
+ {%- else %}
6
+ {{- 'You are a helpful assistant.' }}
7
+ {%- endif %}
8
+ {{- "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
9
+ {%- for tool in tools %}
10
+ {{- "\n" }}
11
+ {{- tool | tojson }}
12
+ {%- endfor %}
13
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
14
+ {%- else %}
15
+ {%- if messages[0]['role'] == 'system' %}
16
+ {{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }}
17
+ {%- else %}
18
+ {{- '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }}
19
+ {%- endif %}
20
+ {%- endif %}
21
+ {%- for message in messages %}
22
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) %}
23
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }}
24
+ {%- elif message.role == "assistant" %}
25
+ {{- '<|im_start|>' + message.role }}
26
+ {%- if message.content %}
27
+ {{- '\n' + message.content }}
28
+ {%- endif %}
29
+ {%- for tool_call in message.tool_calls %}
30
+ {%- if tool_call.function is defined %}
31
+ {%- set tool_call = tool_call.function %}
32
+ {%- endif %}
33
+ {{- '\n<tool_call>\n{"name": "' }}
34
+ {{- tool_call.name }}
35
+ {{- '", "arguments": ' }}
36
+ {{- tool_call.arguments | tojson }}
37
+ {{- '}\n</tool_call>' }}
38
+ {%- endfor %}
39
+ {{- '<|im_end|>\n' }}
40
+ {%- elif message.role == "tool" %}
41
+ {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %}
42
+ {{- '<|im_start|>user' }}
43
+ {%- endif %}
44
+ {{- '\n<tool_response>\n' }}
45
+ {{- message.content }}
46
+ {{- '\n</tool_response>' }}
47
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
48
+ {{- '<|im_end|>\n' }}
49
+ {%- endif %}
50
+ {%- endif %}
51
+ {%- endfor %}
52
+ {%- if add_generation_prompt %}
53
+ {{- '<|im_start|>assistant\n' }}
54
+ {%- endif %}
hub/models--Qwen--Qwen-Image/snapshots/75e0b4be04f60ec59a75f475837eced720f823b6/tokenizer/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
hub/models--Qwen--Qwen-Image/snapshots/75e0b4be04f60ec59a75f475837eced720f823b6/tokenizer/special_tokens_map.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|im_end|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "<|endoftext|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
hub/models--Qwen--Qwen-Image/snapshots/75e0b4be04f60ec59a75f475837eced720f823b6/tokenizer/tokenizer_config.json ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ }
181
+ },
182
+ "additional_special_tokens": [
183
+ "<|im_start|>",
184
+ "<|im_end|>",
185
+ "<|object_ref_start|>",
186
+ "<|object_ref_end|>",
187
+ "<|box_start|>",
188
+ "<|box_end|>",
189
+ "<|quad_start|>",
190
+ "<|quad_end|>",
191
+ "<|vision_start|>",
192
+ "<|vision_end|>",
193
+ "<|vision_pad|>",
194
+ "<|image_pad|>",
195
+ "<|video_pad|>"
196
+ ],
197
+ "bos_token": null,
198
+ "clean_up_tokenization_spaces": false,
199
+ "eos_token": "<|im_end|>",
200
+ "errors": "replace",
201
+ "extra_special_tokens": {},
202
+ "model_max_length": 131072,
203
+ "pad_token": "<|endoftext|>",
204
+ "split_special_tokens": false,
205
+ "tokenizer_class": "Qwen2Tokenizer",
206
+ "unk_token": null
207
+ }
hub/models--Qwen--Qwen-Image/snapshots/75e0b4be04f60ec59a75f475837eced720f823b6/tokenizer/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
hub/version_diffusers_cache.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1
venv/.lock ADDED
File without changes
venv/bin/Activate.ps1 ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <#
2
+ .Synopsis
3
+ Activate a Python virtual environment for the current PowerShell session.
4
+
5
+ .Description
6
+ Pushes the python executable for a virtual environment to the front of the
7
+ $Env:PATH environment variable and sets the prompt to signify that you are
8
+ in a Python virtual environment. Makes use of the command line switches as
9
+ well as the `pyvenv.cfg` file values present in the virtual environment.
10
+
11
+ .Parameter VenvDir
12
+ Path to the directory that contains the virtual environment to activate. The
13
+ default value for this is the parent of the directory that the Activate.ps1
14
+ script is located within.
15
+
16
+ .Parameter Prompt
17
+ The prompt prefix to display when this virtual environment is activated. By
18
+ default, this prompt is the name of the virtual environment folder (VenvDir)
19
+ surrounded by parentheses and followed by a single space (ie. '(.venv) ').
20
+
21
+ .Example
22
+ Activate.ps1
23
+ Activates the Python virtual environment that contains the Activate.ps1 script.
24
+
25
+ .Example
26
+ Activate.ps1 -Verbose
27
+ Activates the Python virtual environment that contains the Activate.ps1 script,
28
+ and shows extra information about the activation as it executes.
29
+
30
+ .Example
31
+ Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
32
+ Activates the Python virtual environment located in the specified location.
33
+
34
+ .Example
35
+ Activate.ps1 -Prompt "MyPython"
36
+ Activates the Python virtual environment that contains the Activate.ps1 script,
37
+ and prefixes the current prompt with the specified string (surrounded in
38
+ parentheses) while the virtual environment is active.
39
+
40
+ .Notes
41
+ On Windows, it may be required to enable this Activate.ps1 script by setting the
42
+ execution policy for the user. You can do this by issuing the following PowerShell
43
+ command:
44
+
45
+ PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
46
+
47
+ For more information on Execution Policies:
48
+ https://go.microsoft.com/fwlink/?LinkID=135170
49
+
50
+ #>
51
+ Param(
52
+ [Parameter(Mandatory = $false)]
53
+ [String]
54
+ $VenvDir,
55
+ [Parameter(Mandatory = $false)]
56
+ [String]
57
+ $Prompt
58
+ )
59
+
60
+ <# Function declarations --------------------------------------------------- #>
61
+
62
+ <#
63
+ .Synopsis
64
+ Remove all shell session elements added by the Activate script, including the
65
+ addition of the virtual environment's Python executable from the beginning of
66
+ the PATH variable.
67
+
68
+ .Parameter NonDestructive
69
+ If present, do not remove this function from the global namespace for the
70
+ session.
71
+
72
+ #>
73
+ function global:deactivate ([switch]$NonDestructive) {
74
+ # Revert to original values
75
+
76
+ # The prior prompt:
77
+ if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {
78
+ Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt
79
+ Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT
80
+ }
81
+
82
+ # The prior PYTHONHOME:
83
+ if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {
84
+ Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME
85
+ Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME
86
+ }
87
+
88
+ # The prior PATH:
89
+ if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {
90
+ Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH
91
+ Remove-Item -Path Env:_OLD_VIRTUAL_PATH
92
+ }
93
+
94
+ # Just remove the VIRTUAL_ENV altogether:
95
+ if (Test-Path -Path Env:VIRTUAL_ENV) {
96
+ Remove-Item -Path env:VIRTUAL_ENV
97
+ }
98
+
99
+ # Just remove VIRTUAL_ENV_PROMPT altogether.
100
+ if (Test-Path -Path Env:VIRTUAL_ENV_PROMPT) {
101
+ Remove-Item -Path env:VIRTUAL_ENV_PROMPT
102
+ }
103
+
104
+ # Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:
105
+ if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
106
+ Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
107
+ }
108
+
109
+ # Leave deactivate function in the global namespace if requested:
110
+ if (-not $NonDestructive) {
111
+ Remove-Item -Path function:deactivate
112
+ }
113
+ }
114
+
115
+ <#
116
+ .Description
117
+ Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the
118
+ given folder, and returns them in a map.
119
+
120
+ For each line in the pyvenv.cfg file, if that line can be parsed into exactly
121
+ two strings separated by `=` (with any amount of whitespace surrounding the =)
122
+ then it is considered a `key = value` line. The left hand string is the key,
123
+ the right hand is the value.
124
+
125
+ If the value starts with a `'` or a `"` then the first and last character is
126
+ stripped from the value before being captured.
127
+
128
+ .Parameter ConfigDir
129
+ Path to the directory that contains the `pyvenv.cfg` file.
130
+ #>
131
+ function Get-PyVenvConfig(
132
+ [String]
133
+ $ConfigDir
134
+ ) {
135
+ Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
136
+
137
+ # Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).
138
+ $pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
139
+
140
+ # An empty map will be returned if no config file is found.
141
+ $pyvenvConfig = @{ }
142
+
143
+ if ($pyvenvConfigPath) {
144
+
145
+ Write-Verbose "File exists, parse `key = value` lines"
146
+ $pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
147
+
148
+ $pyvenvConfigContent | ForEach-Object {
149
+ $keyval = $PSItem -split "\s*=\s*", 2
150
+ if ($keyval[0] -and $keyval[1]) {
151
+ $val = $keyval[1]
152
+
153
+ # Remove extraneous quotations around a string value.
154
+ if ("'""".Contains($val.Substring(0, 1))) {
155
+ $val = $val.Substring(1, $val.Length - 2)
156
+ }
157
+
158
+ $pyvenvConfig[$keyval[0]] = $val
159
+ Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
160
+ }
161
+ }
162
+ }
163
+ return $pyvenvConfig
164
+ }
165
+
166
+
167
+ <# Begin Activate script --------------------------------------------------- #>
168
+
169
+ # Determine the containing directory of this script
170
+ $VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
171
+ $VenvExecDir = Get-Item -Path $VenvExecPath
172
+
173
+ Write-Verbose "Activation script is located in path: '$VenvExecPath'"
174
+ Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"
175
+ Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"
176
+
177
+ # Set values required in priority: CmdLine, ConfigFile, Default
178
+ # First, get the location of the virtual environment, it might not be
179
+ # VenvExecDir if specified on the command line.
180
+ if ($VenvDir) {
181
+ Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
182
+ }
183
+ else {
184
+ Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."
185
+ $VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
186
+ Write-Verbose "VenvDir=$VenvDir"
187
+ }
188
+
189
+ # Next, read the `pyvenv.cfg` file to determine any required value such
190
+ # as `prompt`.
191
+ $pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
192
+
193
+ # Next, set the prompt from the command line, or the config file, or
194
+ # just use the name of the virtual environment folder.
195
+ if ($Prompt) {
196
+ Write-Verbose "Prompt specified as argument, using '$Prompt'"
197
+ }
198
+ else {
199
+ Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"
200
+ if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
201
+ Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
202
+ $Prompt = $pyvenvCfg['prompt'];
203
+ }
204
+ else {
205
+ Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)"
206
+ Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"
207
+ $Prompt = Split-Path -Path $venvDir -Leaf
208
+ }
209
+ }
210
+
211
+ Write-Verbose "Prompt = '$Prompt'"
212
+ Write-Verbose "VenvDir='$VenvDir'"
213
+
214
+ # Deactivate any currently active virtual environment, but leave the
215
+ # deactivate function in place.
216
+ deactivate -nondestructive
217
+
218
+ # Now set the environment variable VIRTUAL_ENV, used by many tools to determine
219
+ # that there is an activated venv.
220
+ $env:VIRTUAL_ENV = $VenvDir
221
+
222
+ if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
223
+
224
+ Write-Verbose "Setting prompt to '$Prompt'"
225
+
226
+ # Set the prompt to include the env name
227
+ # Make sure _OLD_VIRTUAL_PROMPT is global
228
+ function global:_OLD_VIRTUAL_PROMPT { "" }
229
+ Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT
230
+ New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
231
+
232
+ function global:prompt {
233
+ Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
234
+ _OLD_VIRTUAL_PROMPT
235
+ }
236
+ $env:VIRTUAL_ENV_PROMPT = $Prompt
237
+ }
238
+
239
+ # Clear PYTHONHOME
240
+ if (Test-Path -Path Env:PYTHONHOME) {
241
+ Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME
242
+ Remove-Item -Path Env:PYTHONHOME
243
+ }
244
+
245
+ # Add the venv to the PATH
246
+ Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH
247
+ $Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"
venv/bin/accelerate ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/workspace/venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from accelerate.commands.accelerate_cli import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
venv/bin/accelerate-config ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/workspace/venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from accelerate.commands.config import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
venv/bin/accelerate-estimate-memory ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/workspace/venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from accelerate.commands.estimate import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
venv/bin/accelerate-launch ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/workspace/venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from accelerate.commands.launch import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
venv/bin/accelerate-merge-weights ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/workspace/venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from accelerate.commands.merge import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
venv/bin/activate ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file must be used with "source bin/activate" *from bash*
2
+ # you cannot run it directly
3
+
4
+ deactivate () {
5
+ # reset old environment variables
6
+ if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
7
+ PATH="${_OLD_VIRTUAL_PATH:-}"
8
+ export PATH
9
+ unset _OLD_VIRTUAL_PATH
10
+ fi
11
+ if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
12
+ PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
13
+ export PYTHONHOME
14
+ unset _OLD_VIRTUAL_PYTHONHOME
15
+ fi
16
+
17
+ # Call hash to forget past commands. Without forgetting
18
+ # past commands the $PATH changes we made may not be respected
19
+ hash -r 2> /dev/null
20
+
21
+ if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
22
+ PS1="${_OLD_VIRTUAL_PS1:-}"
23
+ export PS1
24
+ unset _OLD_VIRTUAL_PS1
25
+ fi
26
+
27
+ unset VIRTUAL_ENV
28
+ unset VIRTUAL_ENV_PROMPT
29
+ if [ ! "${1:-}" = "nondestructive" ] ; then
30
+ # Self destruct!
31
+ unset -f deactivate
32
+ fi
33
+ }
34
+
35
+ # unset irrelevant variables
36
+ deactivate nondestructive
37
+
38
+ VIRTUAL_ENV="/workspace/venv"
39
+ export VIRTUAL_ENV
40
+
41
+ _OLD_VIRTUAL_PATH="$PATH"
42
+ PATH="$VIRTUAL_ENV/bin:$PATH"
43
+ export PATH
44
+
45
+ # unset PYTHONHOME if set
46
+ # this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
47
+ # could use `if (set -u; : $PYTHONHOME) ;` in bash
48
+ if [ -n "${PYTHONHOME:-}" ] ; then
49
+ _OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}"
50
+ unset PYTHONHOME
51
+ fi
52
+
53
+ if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
54
+ _OLD_VIRTUAL_PS1="${PS1:-}"
55
+ PS1="(venv) ${PS1:-}"
56
+ export PS1
57
+ VIRTUAL_ENV_PROMPT="(venv) "
58
+ export VIRTUAL_ENV_PROMPT
59
+ fi
60
+
61
+ # Call hash to forget past commands. Without forgetting
62
+ # past commands the $PATH changes we made may not be respected
63
+ hash -r 2> /dev/null
venv/bin/activate.csh ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file must be used with "source bin/activate.csh" *from csh*.
2
+ # You cannot run it directly.
3
+ # Created by Davide Di Blasi <davidedb@gmail.com>.
4
+ # Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com>
5
+
6
+ alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate'
7
+
8
+ # Unset irrelevant variables.
9
+ deactivate nondestructive
10
+
11
+ setenv VIRTUAL_ENV "/workspace/venv"
12
+
13
+ set _OLD_VIRTUAL_PATH="$PATH"
14
+ setenv PATH "$VIRTUAL_ENV/bin:$PATH"
15
+
16
+
17
+ set _OLD_VIRTUAL_PROMPT="$prompt"
18
+
19
+ if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
20
+ set prompt = "(venv) $prompt"
21
+ setenv VIRTUAL_ENV_PROMPT "(venv) "
22
+ endif
23
+
24
+ alias pydoc python -m pydoc
25
+
26
+ rehash
venv/bin/activate.fish ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file must be used with "source <venv>/bin/activate.fish" *from fish*
2
+ # (https://fishshell.com/); you cannot run it directly.
3
+
4
+ function deactivate -d "Exit virtual environment and return to normal shell environment"
5
+ # reset old environment variables
6
+ if test -n "$_OLD_VIRTUAL_PATH"
7
+ set -gx PATH $_OLD_VIRTUAL_PATH
8
+ set -e _OLD_VIRTUAL_PATH
9
+ end
10
+ if test -n "$_OLD_VIRTUAL_PYTHONHOME"
11
+ set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME
12
+ set -e _OLD_VIRTUAL_PYTHONHOME
13
+ end
14
+
15
+ if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
16
+ set -e _OLD_FISH_PROMPT_OVERRIDE
17
+ # prevents error when using nested fish instances (Issue #93858)
18
+ if functions -q _old_fish_prompt
19
+ functions -e fish_prompt
20
+ functions -c _old_fish_prompt fish_prompt
21
+ functions -e _old_fish_prompt
22
+ end
23
+ end
24
+
25
+ set -e VIRTUAL_ENV
26
+ set -e VIRTUAL_ENV_PROMPT
27
+ if test "$argv[1]" != "nondestructive"
28
+ # Self-destruct!
29
+ functions -e deactivate
30
+ end
31
+ end
32
+
33
+ # Unset irrelevant variables.
34
+ deactivate nondestructive
35
+
36
+ set -gx VIRTUAL_ENV "/workspace/venv"
37
+
38
+ set -gx _OLD_VIRTUAL_PATH $PATH
39
+ set -gx PATH "$VIRTUAL_ENV/bin" $PATH
40
+
41
+ # Unset PYTHONHOME if set.
42
+ if set -q PYTHONHOME
43
+ set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
44
+ set -e PYTHONHOME
45
+ end
46
+
47
+ if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
48
+ # fish uses a function instead of an env var to generate the prompt.
49
+
50
+ # Save the current fish_prompt function as the function _old_fish_prompt.
51
+ functions -c fish_prompt _old_fish_prompt
52
+
53
+ # With the original prompt function renamed, we can override with our own.
54
+ function fish_prompt
55
+ # Save the return status of the last command.
56
+ set -l old_status $status
57
+
58
+ # Output the venv prompt; color taken from the blue of the Python logo.
59
+ printf "%s%s%s" (set_color 4B8BBE) "(venv) " (set_color normal)
60
+
61
+ # Restore the return status of the previous command.
62
+ echo "exit $old_status" | .
63
+ # Output the original/"old" prompt.
64
+ _old_fish_prompt
65
+ end
66
+
67
+ set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
68
+ set -gx VIRTUAL_ENV_PROMPT "(venv) "
69
+ end
venv/bin/convert-to-quant ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/workspace/venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from convert_to_quant.convert_to_quant import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
venv/bin/convert_to_quant ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/workspace/venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from convert_to_quant.convert_to_quant import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
venv/bin/ctq ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/workspace/venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from convert_to_quant.convert_to_quant import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
venv/bin/diffusers-cli ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/workspace/venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from diffusers.commands.diffusers_cli import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
venv/bin/f2py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/venv/bin/python
2
+ import sys
3
+ from numpy.f2py.f2py2e import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
venv/bin/fastapi ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/venv/bin/python
2
+ import sys
3
+ from fastapi.cli import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
venv/bin/ftfy ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/workspace/venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from ftfy.cli import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
venv/bin/gradio ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/venv/bin/python
2
+ import sys
3
+ from gradio.cli import cli
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(cli())