Path: blob/main/examples/dreambooth/train_dreambooth.py
1441 views
import argparse1import hashlib2import itertools3import random4import json5import logging6import math7import os8from contextlib import nullcontext9from pathlib import Path10from typing import Optional1112import torch13import torch.nn.functional as F14import torch.utils.checkpoint15from torch.utils.data import Dataset1617from accelerate import Accelerator18from accelerate.logging import get_logger19from accelerate.utils import set_seed20from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionPipeline, UNet2DConditionModel21from diffusers.optimization import get_scheduler22from diffusers.utils.import_utils import is_xformers_available23from huggingface_hub import HfFolder, Repository, whoami24from PIL import Image25from torchvision import transforms26from tqdm.auto import tqdm27from transformers import CLIPTextModel, CLIPTokenizer282930torch.backends.cudnn.benchmark = True313233logger = get_logger(__name__)343536def parse_args(input_args=None):37parser = argparse.ArgumentParser(description="Simple example of a training script.")38parser.add_argument(39"--pretrained_model_name_or_path",40type=str,41default=None,42required=True,43help="Path to pretrained model or model identifier from huggingface.co/models.",44)45parser.add_argument(46"--pretrained_vae_name_or_path",47type=str,48default=None,49help="Path to pretrained vae or vae identifier from huggingface.co/models.",50)51parser.add_argument(52"--revision",53type=str,54default=None,55required=False,56help="Revision of pretrained model identifier from huggingface.co/models.",57)58parser.add_argument(59"--tokenizer_name",60type=str,61default=None,62help="Pretrained tokenizer name or path if not the same as model_name",63)64parser.add_argument(65"--instance_data_dir",66type=str,67default=None,68help="A folder containing the training data of instance images.",69)70parser.add_argument(71"--class_data_dir",72type=str,73default=None,74help="A folder containing the training data of class images.",75)76parser.add_argument(77"--instance_prompt",78type=str,79default=None,80help="The prompt with identifier specifying the instance",81)82parser.add_argument(83"--class_prompt",84type=str,85default=None,86help="The prompt to specify images in the same class as provided instance images.",87)88parser.add_argument(89"--save_sample_prompt",90type=str,91default=None,92help="The prompt used to generate sample outputs to save.",93)94parser.add_argument(95"--save_sample_negative_prompt",96type=str,97default=None,98help="The negative prompt used to generate sample outputs to save.",99)100parser.add_argument(101"--n_save_sample",102type=int,103default=4,104help="The number of samples to save.",105)106parser.add_argument(107"--save_guidance_scale",108type=float,109default=7.5,110help="CFG for save sample.",111)112parser.add_argument(113"--save_infer_steps",114type=int,115default=20,116help="The number of inference steps for save sample.",117)118parser.add_argument(119"--pad_tokens",120default=False,121action="store_true",122help="Flag to pad tokens to length 77.",123)124parser.add_argument(125"--with_prior_preservation",126default=False,127action="store_true",128help="Flag to add prior preservation loss.",129)130parser.add_argument("--prior_loss_weight", type=float, default=1.0, help="The weight of prior preservation loss.")131parser.add_argument(132"--num_class_images",133type=int,134default=100,135help=(136"Minimal class images for prior preservation loss. If not have enough images, additional images will be"137" sampled with class_prompt."138),139)140parser.add_argument(141"--output_dir",142type=str,143default="text-inversion-model",144help="The output directory where the model predictions and checkpoints will be written.",145)146parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")147parser.add_argument(148"--resolution",149type=int,150default=512,151help=(152"The resolution for input images, all the images in the train/validation dataset will be resized to this"153" resolution"154),155)156parser.add_argument(157"--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution"158)159parser.add_argument("--train_text_encoder", action="store_true", help="Whether to train the text encoder")160parser.add_argument(161"--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."162)163parser.add_argument(164"--sample_batch_size", type=int, default=4, help="Batch size (per device) for sampling images."165)166parser.add_argument("--num_train_epochs", type=int, default=1)167parser.add_argument(168"--max_train_steps",169type=int,170default=None,171help="Total number of training steps to perform. If provided, overrides num_train_epochs.",172)173parser.add_argument(174"--gradient_accumulation_steps",175type=int,176default=1,177help="Number of updates steps to accumulate before performing a backward/update pass.",178)179parser.add_argument(180"--gradient_checkpointing",181action="store_true",182help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",183)184parser.add_argument(185"--learning_rate",186type=float,187default=5e-6,188help="Initial learning rate (after the potential warmup period) to use.",189)190parser.add_argument(191"--scale_lr",192action="store_true",193default=False,194help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",195)196parser.add_argument(197"--lr_scheduler",198type=str,199default="constant",200help=(201'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'202' "constant", "constant_with_warmup"]'203),204)205parser.add_argument(206"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."207)208parser.add_argument(209"--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."210)211parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")212parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")213parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")214parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")215parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")216parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")217parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")218parser.add_argument(219"--hub_model_id",220type=str,221default=None,222help="The name of the repository to keep in sync with the local `output_dir`.",223)224parser.add_argument(225"--logging_dir",226type=str,227default="logs",228help=(229"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"230" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."231),232)233parser.add_argument("--log_interval", type=int, default=10, help="Log every N steps.")234parser.add_argument("--save_interval", type=int, default=10_000, help="Save weights every N steps.")235parser.add_argument("--save_min_steps", type=int, default=0, help="Start saving weights after N steps.")236parser.add_argument(237"--mixed_precision",238type=str,239default=None,240choices=["no", "fp16", "bf16"],241help=(242"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="243" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"244" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."245),246)247parser.add_argument("--not_cache_latents", action="store_true", help="Do not precompute and cache latents from VAE.")248parser.add_argument("--hflip", action="store_true", help="Apply horizontal flip data augmentation.")249parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")250parser.add_argument(251"--concepts_list",252type=str,253default=None,254help="Path to json containing multiple concepts, will overwrite parameters like instance_prompt, class_prompt, etc.",255)256parser.add_argument(257"--read_prompts_from_txts",258action="store_true",259help="Use prompt per image. Put prompts in the same directory as images, e.g. for image.png create image.png.txt.",260)261262if input_args is not None:263args = parser.parse_args(input_args)264else:265args = parser.parse_args()266267env_local_rank = int(os.environ.get("LOCAL_RANK", -1))268if env_local_rank != -1 and env_local_rank != args.local_rank:269args.local_rank = env_local_rank270271return args272273274class DreamBoothDataset(Dataset):275"""276A dataset to prepare the instance and class images with the prompts for fine-tuning the model.277It pre-processes the images and the tokenizes prompts.278"""279280def __init__(281self,282concepts_list,283tokenizer,284with_prior_preservation=True,285size=512,286center_crop=False,287num_class_images=None,288pad_tokens=False,289hflip=False,290read_prompts_from_txts=False,291):292self.size = size293self.center_crop = center_crop294self.tokenizer = tokenizer295self.with_prior_preservation = with_prior_preservation296self.pad_tokens = pad_tokens297self.read_prompts_from_txts = read_prompts_from_txts298299self.instance_images_path = []300self.class_images_path = []301302for concept in concepts_list:303inst_img_path = [304(x, concept["instance_prompt"])305for x in Path(concept["instance_data_dir"]).iterdir()306if x.is_file() and not str(x).endswith(".txt")307]308self.instance_images_path.extend(inst_img_path)309310if with_prior_preservation:311class_img_path = [(x, concept["class_prompt"]) for x in Path(concept["class_data_dir"]).iterdir() if x.is_file()]312self.class_images_path.extend(class_img_path[:num_class_images])313314random.shuffle(self.instance_images_path)315self.num_instance_images = len(self.instance_images_path)316self.num_class_images = len(self.class_images_path)317self._length = max(self.num_class_images, self.num_instance_images)318319self.image_transforms = transforms.Compose(320[321transforms.RandomHorizontalFlip(0.5 * hflip),322transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR),323transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size),324transforms.ToTensor(),325transforms.Normalize([0.5], [0.5]),326]327)328329def __len__(self):330return self._length331332def __getitem__(self, index):333example = {}334instance_path, instance_prompt = self.instance_images_path[index % self.num_instance_images]335336if self.read_prompts_from_txts:337with open(str(instance_path) + ".txt") as f:338instance_prompt = f.read().strip()339340instance_image = Image.open(instance_path)341if not instance_image.mode == "RGB":342instance_image = instance_image.convert("RGB")343344example["instance_images"] = self.image_transforms(instance_image)345example["instance_prompt_ids"] = self.tokenizer(346instance_prompt,347padding="max_length" if self.pad_tokens else "do_not_pad",348truncation=True,349max_length=self.tokenizer.model_max_length,350).input_ids351352if self.with_prior_preservation:353class_path, class_prompt = self.class_images_path[index % self.num_class_images]354class_image = Image.open(class_path)355if not class_image.mode == "RGB":356class_image = class_image.convert("RGB")357example["class_images"] = self.image_transforms(class_image)358example["class_prompt_ids"] = self.tokenizer(359class_prompt,360padding="max_length" if self.pad_tokens else "do_not_pad",361truncation=True,362max_length=self.tokenizer.model_max_length,363).input_ids364365return example366367368class PromptDataset(Dataset):369"A simple dataset to prepare the prompts to generate class images on multiple GPUs."370371def __init__(self, prompt, num_samples):372self.prompt = prompt373self.num_samples = num_samples374375def __len__(self):376return self.num_samples377378def __getitem__(self, index):379example = {}380example["prompt"] = self.prompt381example["index"] = index382return example383384385class LatentsDataset(Dataset):386def __init__(self, latents_cache, text_encoder_cache):387self.latents_cache = latents_cache388self.text_encoder_cache = text_encoder_cache389390def __len__(self):391return len(self.latents_cache)392393def __getitem__(self, index):394return self.latents_cache[index], self.text_encoder_cache[index]395396397class AverageMeter:398def __init__(self, name=None):399self.name = name400self.reset()401402def reset(self):403self.sum = self.count = self.avg = 0404405def update(self, val, n=1):406self.sum += val * n407self.count += n408self.avg = self.sum / self.count409410411def get_full_repo_name(model_id: str, organization: Optional[str] = None, token: Optional[str] = None):412if token is None:413token = HfFolder.get_token()414if organization is None:415username = whoami(token)["name"]416return f"{username}/{model_id}"417else:418return f"{organization}/{model_id}"419420421def main(args):422logging_dir = Path(args.output_dir, "0", args.logging_dir)423424accelerator = Accelerator(425gradient_accumulation_steps=args.gradient_accumulation_steps,426mixed_precision=args.mixed_precision,427log_with="tensorboard",428project_dir=logging_dir,429)430431logging.basicConfig(432format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",433datefmt="%m/%d/%Y %H:%M:%S",434level=logging.INFO,435)436437# Currently, it's not possible to do gradient accumulation when training two models with accelerate.accumulate438# This will be enabled soon in accelerate. For now, we don't allow gradient accumulation when training two models.439# TODO (patil-suraj): Remove this check when gradient accumulation with two models is enabled in accelerate.440if args.train_text_encoder and args.gradient_accumulation_steps > 1 and accelerator.num_processes > 1:441raise ValueError(442"Gradient accumulation is not supported when training the text encoder in distributed training. "443"Please set gradient_accumulation_steps to 1. This feature will be supported in the future."444)445446if args.seed is not None:447set_seed(args.seed)448449if args.concepts_list is None:450args.concepts_list = [451{452"instance_prompt": args.instance_prompt,453"class_prompt": args.class_prompt,454"instance_data_dir": args.instance_data_dir,455"class_data_dir": args.class_data_dir456}457]458else:459with open(args.concepts_list, "r") as f:460args.concepts_list = json.load(f)461462if args.with_prior_preservation:463pipeline = None464for concept in args.concepts_list:465class_images_dir = Path(concept["class_data_dir"])466class_images_dir.mkdir(parents=True, exist_ok=True)467cur_class_images = len(list(class_images_dir.iterdir()))468469if cur_class_images < args.num_class_images:470torch_dtype = torch.float16 if accelerator.device.type == "cuda" else torch.float32471if pipeline is None:472pipeline = StableDiffusionPipeline.from_pretrained(473args.pretrained_model_name_or_path,474vae=AutoencoderKL.from_pretrained(475args.pretrained_vae_name_or_path or args.pretrained_model_name_or_path,476subfolder=None if args.pretrained_vae_name_or_path else "vae",477revision=None if args.pretrained_vae_name_or_path else args.revision,478torch_dtype=torch_dtype479),480torch_dtype=torch_dtype,481safety_checker=None,482revision=args.revision483)484pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)485if is_xformers_available():486pipeline.enable_xformers_memory_efficient_attention()487pipeline.set_progress_bar_config(disable=True)488pipeline.to(accelerator.device)489490num_new_images = args.num_class_images - cur_class_images491logger.info(f"Number of class images to sample: {num_new_images}.")492493sample_dataset = PromptDataset(concept["class_prompt"], num_new_images)494sample_dataloader = torch.utils.data.DataLoader(sample_dataset, batch_size=args.sample_batch_size)495496sample_dataloader = accelerator.prepare(sample_dataloader)497498with torch.autocast("cuda"), torch.inference_mode():499for example in tqdm(500sample_dataloader, desc="Generating class images", disable=not accelerator.is_local_main_process501):502images = pipeline(503example["prompt"],504num_inference_steps=args.save_infer_steps505).images506507for i, image in enumerate(images):508hash_image = hashlib.sha1(image.tobytes()).hexdigest()509image_filename = class_images_dir / f"{example['index'][i] + cur_class_images}-{hash_image}.jpg"510image.save(image_filename)511512del pipeline513if torch.cuda.is_available():514torch.cuda.empty_cache()515516# Load the tokenizer517if args.tokenizer_name:518tokenizer = CLIPTokenizer.from_pretrained(519args.tokenizer_name,520revision=args.revision,521)522elif args.pretrained_model_name_or_path:523tokenizer = CLIPTokenizer.from_pretrained(524args.pretrained_model_name_or_path,525subfolder="tokenizer",526revision=args.revision,527)528529# Load models and create wrapper for stable diffusion530text_encoder = CLIPTextModel.from_pretrained(531args.pretrained_model_name_or_path,532subfolder="text_encoder",533revision=args.revision,534)535vae = AutoencoderKL.from_pretrained(536args.pretrained_model_name_or_path,537subfolder="vae",538revision=args.revision,539)540unet = UNet2DConditionModel.from_pretrained(541args.pretrained_model_name_or_path,542subfolder="unet",543revision=args.revision,544torch_dtype=torch.float32545)546547vae.requires_grad_(False)548if not args.train_text_encoder:549text_encoder.requires_grad_(False)550551if is_xformers_available():552vae.enable_xformers_memory_efficient_attention()553unet.enable_xformers_memory_efficient_attention()554else:555logger.warning("xformers is not available. Make sure it is installed correctly")556557if args.gradient_checkpointing:558unet.enable_gradient_checkpointing()559if args.train_text_encoder:560text_encoder.gradient_checkpointing_enable()561562if args.scale_lr:563args.learning_rate = (564args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes565)566567# Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs568if args.use_8bit_adam:569try:570import bitsandbytes as bnb571except ImportError:572raise ImportError(573"To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."574)575576optimizer_class = bnb.optim.AdamW8bit577else:578optimizer_class = torch.optim.AdamW579580params_to_optimize = (581itertools.chain(unet.parameters(), text_encoder.parameters()) if args.train_text_encoder else unet.parameters()582)583optimizer = optimizer_class(584params_to_optimize,585lr=args.learning_rate,586betas=(args.adam_beta1, args.adam_beta2),587weight_decay=args.adam_weight_decay,588eps=args.adam_epsilon,589)590591noise_scheduler = DDPMScheduler.from_config(args.pretrained_model_name_or_path, subfolder="scheduler")592593train_dataset = DreamBoothDataset(594concepts_list=args.concepts_list,595tokenizer=tokenizer,596with_prior_preservation=args.with_prior_preservation,597size=args.resolution,598center_crop=args.center_crop,599num_class_images=args.num_class_images,600pad_tokens=args.pad_tokens,601hflip=args.hflip,602read_prompts_from_txts=args.read_prompts_from_txts,603)604605def collate_fn(examples):606input_ids = [example["instance_prompt_ids"] for example in examples]607pixel_values = [example["instance_images"] for example in examples]608609# Concat class and instance examples for prior preservation.610# We do this to avoid doing two forward passes.611if args.with_prior_preservation:612input_ids += [example["class_prompt_ids"] for example in examples]613pixel_values += [example["class_images"] for example in examples]614615pixel_values = torch.stack(pixel_values)616pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()617618input_ids = tokenizer.pad(619{"input_ids": input_ids},620padding=True,621return_tensors="pt",622).input_ids623624batch = {625"input_ids": input_ids,626"pixel_values": pixel_values,627}628return batch629630train_dataloader = torch.utils.data.DataLoader(631train_dataset, batch_size=args.train_batch_size, shuffle=True, collate_fn=collate_fn, pin_memory=True632)633634weight_dtype = torch.float32635if args.mixed_precision == "fp16":636weight_dtype = torch.float16637elif args.mixed_precision == "bf16":638weight_dtype = torch.bfloat16639640# Move text_encode and vae to gpu.641# For mixed precision training we cast the text_encoder and vae weights to half-precision642# as these models are only used for inference, keeping weights in full precision is not required.643vae.to(accelerator.device, dtype=weight_dtype)644if not args.train_text_encoder:645text_encoder.to(accelerator.device, dtype=weight_dtype)646647if not args.not_cache_latents:648latents_cache = []649text_encoder_cache = []650for batch in tqdm(train_dataloader, desc="Caching latents"):651with torch.no_grad():652batch["pixel_values"] = batch["pixel_values"].to(accelerator.device, non_blocking=True, dtype=weight_dtype)653batch["input_ids"] = batch["input_ids"].to(accelerator.device, non_blocking=True)654latents_cache.append(vae.encode(batch["pixel_values"]).latent_dist)655if args.train_text_encoder:656text_encoder_cache.append(batch["input_ids"])657else:658text_encoder_cache.append(text_encoder(batch["input_ids"])[0])659train_dataset = LatentsDataset(latents_cache, text_encoder_cache)660train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=1, collate_fn=lambda x: x, shuffle=True)661662del vae663if not args.train_text_encoder:664del text_encoder665if torch.cuda.is_available():666torch.cuda.empty_cache()667668# Scheduler and math around the number of training steps.669overrode_max_train_steps = False670num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)671if args.max_train_steps is None:672args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch673overrode_max_train_steps = True674675lr_scheduler = get_scheduler(676args.lr_scheduler,677optimizer=optimizer,678num_warmup_steps=args.lr_warmup_steps * args.gradient_accumulation_steps,679num_training_steps=args.max_train_steps * args.gradient_accumulation_steps,680)681682if args.train_text_encoder:683unet, text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(684unet, text_encoder, optimizer, train_dataloader, lr_scheduler685)686else:687unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(688unet, optimizer, train_dataloader, lr_scheduler689)690691# We need to recalculate our total training steps as the size of the training dataloader may have changed.692num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)693if overrode_max_train_steps:694args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch695# Afterwards we recalculate our number of training epochs696args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)697698# We need to initialize the trackers we use, and also store our configuration.699# The trackers initializes automatically on the main process.700if accelerator.is_main_process:701accelerator.init_trackers("dreambooth")702703# Train!704total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps705706logger.info("***** Running training *****")707logger.info(f" Num examples = {len(train_dataset)}")708logger.info(f" Num batches each epoch = {len(train_dataloader)}")709logger.info(f" Num Epochs = {args.num_train_epochs}")710logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")711logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")712logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")713logger.info(f" Total optimization steps = {args.max_train_steps}")714715def save_weights(step):716# Create the pipeline using using the trained modules and save it.717if accelerator.is_main_process:718if args.train_text_encoder:719text_enc_model = accelerator.unwrap_model(text_encoder, keep_fp32_wrapper=True)720else:721text_enc_model = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision)722pipeline = StableDiffusionPipeline.from_pretrained(723args.pretrained_model_name_or_path,724unet=accelerator.unwrap_model(unet, keep_fp32_wrapper=True),725text_encoder=text_enc_model,726vae=AutoencoderKL.from_pretrained(727args.pretrained_vae_name_or_path or args.pretrained_model_name_or_path,728subfolder=None if args.pretrained_vae_name_or_path else "vae",729revision=None if args.pretrained_vae_name_or_path else args.revision,730),731safety_checker=None,732torch_dtype=torch.float16,733revision=args.revision,734)735pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)736if is_xformers_available():737pipeline.enable_xformers_memory_efficient_attention()738save_dir = os.path.join(args.output_dir, f"{step}")739pipeline.save_pretrained(save_dir)740with open(os.path.join(save_dir, "args.json"), "w") as f:741json.dump(args.__dict__, f, indent=2)742743if args.save_sample_prompt is not None:744pipeline = pipeline.to(accelerator.device)745g_cuda = torch.Generator(device=accelerator.device).manual_seed(args.seed)746pipeline.set_progress_bar_config(disable=True)747sample_dir = os.path.join(save_dir, "samples")748os.makedirs(sample_dir, exist_ok=True)749with torch.autocast("cuda"), torch.inference_mode():750for i in tqdm(range(args.n_save_sample), desc="Generating samples"):751images = pipeline(752args.save_sample_prompt,753negative_prompt=args.save_sample_negative_prompt,754guidance_scale=args.save_guidance_scale,755num_inference_steps=args.save_infer_steps,756generator=g_cuda757).images758images[0].save(os.path.join(sample_dir, f"{i}.png"))759del pipeline760if torch.cuda.is_available():761torch.cuda.empty_cache()762print(f"[*] Weights saved at {save_dir}")763764# Only show the progress bar once on each machine.765progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process)766progress_bar.set_description("Steps")767global_step = 0768loss_avg = AverageMeter()769text_enc_context = nullcontext() if args.train_text_encoder else torch.no_grad()770for epoch in range(args.num_train_epochs):771unet.train()772if args.train_text_encoder:773text_encoder.train()774for step, batch in enumerate(train_dataloader):775with accelerator.accumulate(unet):776# Convert images to latent space777with torch.no_grad():778if not args.not_cache_latents:779latent_dist = batch[0][0]780else:781latent_dist = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist782latents = latent_dist.sample() * 0.18215783784# Sample noise that we'll add to the latents785noise = torch.randn_like(latents)786bsz = latents.shape[0]787# Sample a random timestep for each image788timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)789timesteps = timesteps.long()790791# Add noise to the latents according to the noise magnitude at each timestep792# (this is the forward diffusion process)793noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)794795# Get the text embedding for conditioning796with text_enc_context:797if not args.not_cache_latents:798if args.train_text_encoder:799encoder_hidden_states = text_encoder(batch[0][1])[0]800else:801encoder_hidden_states = batch[0][1]802else:803encoder_hidden_states = text_encoder(batch["input_ids"])[0]804805# Predict the noise residual806model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample807808# Get the target for loss depending on the prediction type809if noise_scheduler.config.prediction_type == "epsilon":810target = noise811elif noise_scheduler.config.prediction_type == "v_prediction":812target = noise_scheduler.get_velocity(latents, noise, timesteps)813else:814raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")815816if args.with_prior_preservation:817# Chunk the noise and model_pred into two parts and compute the loss on each part separately.818model_pred, model_pred_prior = torch.chunk(model_pred, 2, dim=0)819target, target_prior = torch.chunk(target, 2, dim=0)820821# Compute instance loss822loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")823824# Compute prior loss825prior_loss = F.mse_loss(model_pred_prior.float(), target_prior.float(), reduction="mean")826827# Add the prior loss to the instance loss.828loss = loss + args.prior_loss_weight * prior_loss829else:830loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")831832accelerator.backward(loss)833# if accelerator.sync_gradients:834# params_to_clip = (835# itertools.chain(unet.parameters(), text_encoder.parameters())836# if args.train_text_encoder837# else unet.parameters()838# )839# accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)840optimizer.step()841lr_scheduler.step()842optimizer.zero_grad(set_to_none=True)843loss_avg.update(loss.detach_(), bsz)844845if not global_step % args.log_interval:846logs = {"loss": loss_avg.avg.item(), "lr": lr_scheduler.get_last_lr()[0]}847progress_bar.set_postfix(**logs)848accelerator.log(logs, step=global_step)849850if global_step > 0 and not global_step % args.save_interval and global_step >= args.save_min_steps:851save_weights(global_step)852853progress_bar.update(1)854global_step += 1855856if global_step >= args.max_train_steps:857break858859accelerator.wait_for_everyone()860861save_weights(global_step)862863accelerator.end_training()864865866if __name__ == "__main__":867args = parse_args()868main(args)869870871