mirror of
https://github.com/modelscope/DiffSynth-Studio.git
synced 2026-03-18 22:08:13 +00:00
124 lines
5.4 KiB
Python
124 lines
5.4 KiB
Python
import torch, os, json
|
|
from diffsynth.pipelines.qwen_image import QwenImagePipeline, ModelConfig
|
|
from diffsynth.trainers.utils import DiffusionTrainingModule, ImageDataset, ModelLogger, launch_training_task, qwen_image_parser
|
|
from diffsynth.models.lora import QwenImageLoRAConverter
|
|
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
|
|
|
|
|
|
|
class QwenImageTrainingModule(DiffusionTrainingModule):
|
|
def __init__(
|
|
self,
|
|
model_paths=None, model_id_with_origin_paths=None,
|
|
tokenizer_path=None,
|
|
trainable_models=None,
|
|
lora_base_model=None, lora_target_modules="", lora_rank=32,
|
|
use_gradient_checkpointing=True,
|
|
use_gradient_checkpointing_offload=False,
|
|
extra_inputs=None,
|
|
):
|
|
super().__init__()
|
|
# Load models
|
|
model_configs = []
|
|
if model_paths is not None:
|
|
model_paths = json.loads(model_paths)
|
|
model_configs += [ModelConfig(path=path) for path in model_paths]
|
|
if model_id_with_origin_paths is not None:
|
|
model_id_with_origin_paths = model_id_with_origin_paths.split(",")
|
|
model_configs += [ModelConfig(model_id=i.split(":")[0], origin_file_pattern=i.split(":")[1]) for i in model_id_with_origin_paths]
|
|
if tokenizer_path is not None:
|
|
self.pipe = QwenImagePipeline.from_pretrained(torch_dtype=torch.bfloat16, device="cpu", model_configs=model_configs, tokenizer_config=ModelConfig(tokenizer_path))
|
|
else:
|
|
self.pipe = QwenImagePipeline.from_pretrained(torch_dtype=torch.bfloat16, device="cpu", model_configs=model_configs)
|
|
|
|
# Reset training scheduler (do it in each training step)
|
|
self.pipe.scheduler.set_timesteps(1000, training=True)
|
|
|
|
# Freeze untrainable models
|
|
self.pipe.freeze_except([] if trainable_models is None else trainable_models.split(","))
|
|
|
|
# Add LoRA to the base models
|
|
if lora_base_model is not None:
|
|
model = self.add_lora_to_model(
|
|
getattr(self.pipe, lora_base_model),
|
|
target_modules=lora_target_modules.split(","),
|
|
lora_rank=lora_rank
|
|
)
|
|
setattr(self.pipe, lora_base_model, model)
|
|
|
|
# Store other configs
|
|
self.use_gradient_checkpointing = use_gradient_checkpointing
|
|
self.use_gradient_checkpointing_offload = use_gradient_checkpointing_offload
|
|
self.extra_inputs = extra_inputs.split(",") if extra_inputs is not None else []
|
|
|
|
|
|
def forward_preprocess(self, data):
|
|
# CFG-sensitive parameters
|
|
inputs_posi = {"prompt": data["prompt"]}
|
|
inputs_nega = {"negative_prompt": ""}
|
|
|
|
# CFG-unsensitive parameters
|
|
inputs_shared = {
|
|
# Assume you are using this pipeline for inference,
|
|
# please fill in the input parameters.
|
|
"input_image": data["image"],
|
|
"height": data["image"].size[1],
|
|
"width": data["image"].size[0],
|
|
# Please do not modify the following parameters
|
|
# unless you clearly know what this will cause.
|
|
"cfg_scale": 1,
|
|
"rand_device": self.pipe.device,
|
|
"use_gradient_checkpointing": self.use_gradient_checkpointing,
|
|
"use_gradient_checkpointing_offload": self.use_gradient_checkpointing_offload,
|
|
}
|
|
|
|
# Extra inputs
|
|
for extra_input in self.extra_inputs:
|
|
inputs_shared[extra_input] = data[extra_input]
|
|
|
|
# Pipeline units will automatically process the input parameters.
|
|
for unit in self.pipe.units:
|
|
inputs_shared, inputs_posi, inputs_nega = self.pipe.unit_runner(unit, self.pipe, inputs_shared, inputs_posi, inputs_nega)
|
|
return {**inputs_shared, **inputs_posi}
|
|
|
|
|
|
def forward(self, data, inputs=None):
|
|
if inputs is None: inputs = self.forward_preprocess(data)
|
|
models = {name: getattr(self.pipe, name) for name in self.pipe.in_iteration_models}
|
|
loss = self.pipe.training_loss(**models, **inputs)
|
|
return loss
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
parser = qwen_image_parser()
|
|
args = parser.parse_args()
|
|
dataset = ImageDataset(args=args)
|
|
model = QwenImageTrainingModule(
|
|
model_paths=args.model_paths,
|
|
model_id_with_origin_paths=args.model_id_with_origin_paths,
|
|
tokenizer_path=args.tokenizer_path,
|
|
trainable_models=args.trainable_models,
|
|
lora_base_model=args.lora_base_model,
|
|
lora_target_modules=args.lora_target_modules,
|
|
lora_rank=args.lora_rank,
|
|
use_gradient_checkpointing=args.use_gradient_checkpointing,
|
|
use_gradient_checkpointing_offload=args.use_gradient_checkpointing_offload,
|
|
extra_inputs=args.extra_inputs,
|
|
)
|
|
model_logger = ModelLogger(
|
|
args.output_path,
|
|
remove_prefix_in_ckpt=args.remove_prefix_in_ckpt,
|
|
state_dict_converter=QwenImageLoRAConverter.align_to_opensource_format if args.align_to_opensource_format else lambda x:x,
|
|
)
|
|
optimizer = torch.optim.AdamW(model.trainable_modules(), lr=args.learning_rate)
|
|
scheduler = torch.optim.lr_scheduler.ConstantLR(optimizer)
|
|
launch_training_task(
|
|
dataset, model, model_logger, optimizer, scheduler,
|
|
num_epochs=args.num_epochs,
|
|
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
|
save_steps=args.save_steps,
|
|
find_unused_parameters=args.find_unused_parameters,
|
|
num_workers=args.dataset_num_workers,
|
|
)
|