Path: blob/main/examples/textual_inversion/textual_inversion.py
1448 views
#!/usr/bin/env python1# coding=utf-82# Copyright 2023 The HuggingFace Inc. team. All rights reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and1415import argparse16import logging17import math18import os19import random20import warnings21from pathlib import Path22from typing import Optional2324import numpy as np25import PIL26import torch27import torch.nn.functional as F28import torch.utils.checkpoint29import transformers30from accelerate import Accelerator31from accelerate.logging import get_logger32from accelerate.utils import ProjectConfiguration, set_seed33from huggingface_hub import HfFolder, Repository, create_repo, whoami3435# TODO: remove and import from diffusers.utils when the new version of diffusers is released36from packaging import version37from PIL import Image38from torch.utils.data import Dataset39from torchvision import transforms40from tqdm.auto import tqdm41from transformers import CLIPTextModel, CLIPTokenizer4243import diffusers44from diffusers import (45AutoencoderKL,46DDPMScheduler,47DiffusionPipeline,48DPMSolverMultistepScheduler,49StableDiffusionPipeline,50UNet2DConditionModel,51)52from diffusers.optimization import get_scheduler53from diffusers.utils import check_min_version, is_wandb_available54from diffusers.utils.import_utils import is_xformers_available555657if is_wandb_available():58import wandb5960if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):61PIL_INTERPOLATION = {62"linear": PIL.Image.Resampling.BILINEAR,63"bilinear": PIL.Image.Resampling.BILINEAR,64"bicubic": PIL.Image.Resampling.BICUBIC,65"lanczos": PIL.Image.Resampling.LANCZOS,66"nearest": PIL.Image.Resampling.NEAREST,67}68else:69PIL_INTERPOLATION = {70"linear": PIL.Image.LINEAR,71"bilinear": PIL.Image.BILINEAR,72"bicubic": PIL.Image.BICUBIC,73"lanczos": PIL.Image.LANCZOS,74"nearest": PIL.Image.NEAREST,75}76# ------------------------------------------------------------------------------777879# Will error if the minimal version of diffusers is not installed. Remove at your own risks.80check_min_version("0.15.0.dev0")8182logger = get_logger(__name__)838485def log_validation(text_encoder, tokenizer, unet, vae, args, accelerator, weight_dtype, epoch):86logger.info(87f"Running validation... \n Generating {args.num_validation_images} images with prompt:"88f" {args.validation_prompt}."89)90# create pipeline (note: unet and vae are loaded again in float32)91pipeline = DiffusionPipeline.from_pretrained(92args.pretrained_model_name_or_path,93text_encoder=accelerator.unwrap_model(text_encoder),94tokenizer=tokenizer,95unet=unet,96vae=vae,97revision=args.revision,98torch_dtype=weight_dtype,99)100pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)101pipeline = pipeline.to(accelerator.device)102pipeline.set_progress_bar_config(disable=True)103104# run inference105generator = None if args.seed is None else torch.Generator(device=accelerator.device).manual_seed(args.seed)106images = []107for _ in range(args.num_validation_images):108with torch.autocast("cuda"):109image = pipeline(args.validation_prompt, num_inference_steps=25, generator=generator).images[0]110images.append(image)111112for tracker in accelerator.trackers:113if tracker.name == "tensorboard":114np_images = np.stack([np.asarray(img) for img in images])115tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")116if tracker.name == "wandb":117tracker.log(118{119"validation": [120wandb.Image(image, caption=f"{i}: {args.validation_prompt}") for i, image in enumerate(images)121]122}123)124125del pipeline126torch.cuda.empty_cache()127128129def save_progress(text_encoder, placeholder_token_id, accelerator, args, save_path):130logger.info("Saving embeddings")131learned_embeds = accelerator.unwrap_model(text_encoder).get_input_embeddings().weight[placeholder_token_id]132learned_embeds_dict = {args.placeholder_token: learned_embeds.detach().cpu()}133torch.save(learned_embeds_dict, save_path)134135136def parse_args():137parser = argparse.ArgumentParser(description="Simple example of a training script.")138parser.add_argument(139"--save_steps",140type=int,141default=500,142help="Save learned_embeds.bin every X updates steps.",143)144parser.add_argument(145"--only_save_embeds",146action="store_true",147default=False,148help="Save only the embeddings for the new concept.",149)150parser.add_argument(151"--pretrained_model_name_or_path",152type=str,153default=None,154required=True,155help="Path to pretrained model or model identifier from huggingface.co/models.",156)157parser.add_argument(158"--revision",159type=str,160default=None,161required=False,162help="Revision of pretrained model identifier from huggingface.co/models.",163)164parser.add_argument(165"--tokenizer_name",166type=str,167default=None,168help="Pretrained tokenizer name or path if not the same as model_name",169)170parser.add_argument(171"--train_data_dir", type=str, default=None, required=True, help="A folder containing the training data."172)173parser.add_argument(174"--placeholder_token",175type=str,176default=None,177required=True,178help="A token to use as a placeholder for the concept.",179)180parser.add_argument(181"--initializer_token", type=str, default=None, required=True, help="A token to use as initializer word."182)183parser.add_argument("--learnable_property", type=str, default="object", help="Choose between 'object' and 'style'")184parser.add_argument("--repeats", type=int, default=100, help="How many times to repeat the training data.")185parser.add_argument(186"--output_dir",187type=str,188default="text-inversion-model",189help="The output directory where the model predictions and checkpoints will be written.",190)191parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")192parser.add_argument(193"--resolution",194type=int,195default=512,196help=(197"The resolution for input images, all the images in the train/validation dataset will be resized to this"198" resolution"199),200)201parser.add_argument(202"--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution."203)204parser.add_argument(205"--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."206)207parser.add_argument("--num_train_epochs", type=int, default=100)208parser.add_argument(209"--max_train_steps",210type=int,211default=5000,212help="Total number of training steps to perform. If provided, overrides num_train_epochs.",213)214parser.add_argument(215"--gradient_accumulation_steps",216type=int,217default=1,218help="Number of updates steps to accumulate before performing a backward/update pass.",219)220parser.add_argument(221"--gradient_checkpointing",222action="store_true",223help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",224)225parser.add_argument(226"--learning_rate",227type=float,228default=1e-4,229help="Initial learning rate (after the potential warmup period) to use.",230)231parser.add_argument(232"--scale_lr",233action="store_true",234default=False,235help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",236)237parser.add_argument(238"--lr_scheduler",239type=str,240default="constant",241help=(242'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'243' "constant", "constant_with_warmup"]'244),245)246parser.add_argument(247"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."248)249parser.add_argument(250"--dataloader_num_workers",251type=int,252default=0,253help=(254"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."255),256)257parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")258parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")259parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")260parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")261parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")262parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")263parser.add_argument(264"--hub_model_id",265type=str,266default=None,267help="The name of the repository to keep in sync with the local `output_dir`.",268)269parser.add_argument(270"--logging_dir",271type=str,272default="logs",273help=(274"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"275" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."276),277)278parser.add_argument(279"--mixed_precision",280type=str,281default="no",282choices=["no", "fp16", "bf16"],283help=(284"Whether to use mixed precision. Choose"285"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."286"and an Nvidia Ampere GPU."287),288)289parser.add_argument(290"--allow_tf32",291action="store_true",292help=(293"Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"294" https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"295),296)297parser.add_argument(298"--report_to",299type=str,300default="tensorboard",301help=(302'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'303' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'304),305)306parser.add_argument(307"--validation_prompt",308type=str,309default=None,310help="A prompt that is used during validation to verify that the model is learning.",311)312parser.add_argument(313"--num_validation_images",314type=int,315default=4,316help="Number of images that should be generated during validation with `validation_prompt`.",317)318parser.add_argument(319"--validation_steps",320type=int,321default=100,322help=(323"Run validation every X steps. Validation consists of running the prompt"324" `args.validation_prompt` multiple times: `args.num_validation_images`"325" and logging the images."326),327)328parser.add_argument(329"--validation_epochs",330type=int,331default=None,332help=(333"Deprecated in favor of validation_steps. Run validation every X epochs. Validation consists of running the prompt"334" `args.validation_prompt` multiple times: `args.num_validation_images`"335" and logging the images."336),337)338parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")339parser.add_argument(340"--checkpointing_steps",341type=int,342default=500,343help=(344"Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"345" training using `--resume_from_checkpoint`."346),347)348parser.add_argument(349"--checkpoints_total_limit",350type=int,351default=None,352help=(353"Max number of checkpoints to store. Passed as `total_limit` to the `Accelerator` `ProjectConfiguration`."354" See Accelerator::save_state https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.save_state"355" for more docs"356),357)358parser.add_argument(359"--resume_from_checkpoint",360type=str,361default=None,362help=(363"Whether training should be resumed from a previous checkpoint. Use a path saved by"364' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'365),366)367parser.add_argument(368"--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."369)370371args = parser.parse_args()372env_local_rank = int(os.environ.get("LOCAL_RANK", -1))373if env_local_rank != -1 and env_local_rank != args.local_rank:374args.local_rank = env_local_rank375376if args.train_data_dir is None:377raise ValueError("You must specify a train data directory.")378379return args380381382imagenet_templates_small = [383"a photo of a {}",384"a rendering of a {}",385"a cropped photo of the {}",386"the photo of a {}",387"a photo of a clean {}",388"a photo of a dirty {}",389"a dark photo of the {}",390"a photo of my {}",391"a photo of the cool {}",392"a close-up photo of a {}",393"a bright photo of the {}",394"a cropped photo of a {}",395"a photo of the {}",396"a good photo of the {}",397"a photo of one {}",398"a close-up photo of the {}",399"a rendition of the {}",400"a photo of the clean {}",401"a rendition of a {}",402"a photo of a nice {}",403"a good photo of a {}",404"a photo of the nice {}",405"a photo of the small {}",406"a photo of the weird {}",407"a photo of the large {}",408"a photo of a cool {}",409"a photo of a small {}",410]411412imagenet_style_templates_small = [413"a painting in the style of {}",414"a rendering in the style of {}",415"a cropped painting in the style of {}",416"the painting in the style of {}",417"a clean painting in the style of {}",418"a dirty painting in the style of {}",419"a dark painting in the style of {}",420"a picture in the style of {}",421"a cool painting in the style of {}",422"a close-up painting in the style of {}",423"a bright painting in the style of {}",424"a cropped painting in the style of {}",425"a good painting in the style of {}",426"a close-up painting in the style of {}",427"a rendition in the style of {}",428"a nice painting in the style of {}",429"a small painting in the style of {}",430"a weird painting in the style of {}",431"a large painting in the style of {}",432]433434435class TextualInversionDataset(Dataset):436def __init__(437self,438data_root,439tokenizer,440learnable_property="object", # [object, style]441size=512,442repeats=100,443interpolation="bicubic",444flip_p=0.5,445set="train",446placeholder_token="*",447center_crop=False,448):449self.data_root = data_root450self.tokenizer = tokenizer451self.learnable_property = learnable_property452self.size = size453self.placeholder_token = placeholder_token454self.center_crop = center_crop455self.flip_p = flip_p456457self.image_paths = [os.path.join(self.data_root, file_path) for file_path in os.listdir(self.data_root)]458459self.num_images = len(self.image_paths)460self._length = self.num_images461462if set == "train":463self._length = self.num_images * repeats464465self.interpolation = {466"linear": PIL_INTERPOLATION["linear"],467"bilinear": PIL_INTERPOLATION["bilinear"],468"bicubic": PIL_INTERPOLATION["bicubic"],469"lanczos": PIL_INTERPOLATION["lanczos"],470}[interpolation]471472self.templates = imagenet_style_templates_small if learnable_property == "style" else imagenet_templates_small473self.flip_transform = transforms.RandomHorizontalFlip(p=self.flip_p)474475def __len__(self):476return self._length477478def __getitem__(self, i):479example = {}480image = Image.open(self.image_paths[i % self.num_images])481482if not image.mode == "RGB":483image = image.convert("RGB")484485placeholder_string = self.placeholder_token486text = random.choice(self.templates).format(placeholder_string)487488example["input_ids"] = self.tokenizer(489text,490padding="max_length",491truncation=True,492max_length=self.tokenizer.model_max_length,493return_tensors="pt",494).input_ids[0]495496# default to score-sde preprocessing497img = np.array(image).astype(np.uint8)498499if self.center_crop:500crop = min(img.shape[0], img.shape[1])501(502h,503w,504) = (505img.shape[0],506img.shape[1],507)508img = img[(h - crop) // 2 : (h + crop) // 2, (w - crop) // 2 : (w + crop) // 2]509510image = Image.fromarray(img)511image = image.resize((self.size, self.size), resample=self.interpolation)512513image = self.flip_transform(image)514image = np.array(image).astype(np.uint8)515image = (image / 127.5 - 1.0).astype(np.float32)516517example["pixel_values"] = torch.from_numpy(image).permute(2, 0, 1)518return example519520521def get_full_repo_name(model_id: str, organization: Optional[str] = None, token: Optional[str] = None):522if token is None:523token = HfFolder.get_token()524if organization is None:525username = whoami(token)["name"]526return f"{username}/{model_id}"527else:528return f"{organization}/{model_id}"529530531def main():532args = parse_args()533logging_dir = os.path.join(args.output_dir, args.logging_dir)534535accelerator_project_config = ProjectConfiguration(total_limit=args.checkpoints_total_limit)536537accelerator = Accelerator(538gradient_accumulation_steps=args.gradient_accumulation_steps,539mixed_precision=args.mixed_precision,540log_with=args.report_to,541logging_dir=logging_dir,542project_config=accelerator_project_config,543)544545if args.report_to == "wandb":546if not is_wandb_available():547raise ImportError("Make sure to install wandb if you want to use it for logging during training.")548549# Make one log on every process with the configuration for debugging.550logging.basicConfig(551format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",552datefmt="%m/%d/%Y %H:%M:%S",553level=logging.INFO,554)555logger.info(accelerator.state, main_process_only=False)556if accelerator.is_local_main_process:557transformers.utils.logging.set_verbosity_warning()558diffusers.utils.logging.set_verbosity_info()559else:560transformers.utils.logging.set_verbosity_error()561diffusers.utils.logging.set_verbosity_error()562563# If passed along, set the training seed now.564if args.seed is not None:565set_seed(args.seed)566567# Handle the repository creation568if accelerator.is_main_process:569if args.push_to_hub:570if args.hub_model_id is None:571repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token)572else:573repo_name = args.hub_model_id574create_repo(repo_name, exist_ok=True, token=args.hub_token)575repo = Repository(args.output_dir, clone_from=repo_name, token=args.hub_token)576577with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:578if "step_*" not in gitignore:579gitignore.write("step_*\n")580if "epoch_*" not in gitignore:581gitignore.write("epoch_*\n")582elif args.output_dir is not None:583os.makedirs(args.output_dir, exist_ok=True)584585# Load tokenizer586if args.tokenizer_name:587tokenizer = CLIPTokenizer.from_pretrained(args.tokenizer_name)588elif args.pretrained_model_name_or_path:589tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")590591# Load scheduler and models592noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")593text_encoder = CLIPTextModel.from_pretrained(594args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision595)596vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision)597unet = UNet2DConditionModel.from_pretrained(598args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision599)600601# Add the placeholder token in tokenizer602num_added_tokens = tokenizer.add_tokens(args.placeholder_token)603if num_added_tokens == 0:604raise ValueError(605f"The tokenizer already contains the token {args.placeholder_token}. Please pass a different"606" `placeholder_token` that is not already in the tokenizer."607)608609# Convert the initializer_token, placeholder_token to ids610token_ids = tokenizer.encode(args.initializer_token, add_special_tokens=False)611# Check if initializer_token is a single token or a sequence of tokens612if len(token_ids) > 1:613raise ValueError("The initializer token must be a single token.")614615initializer_token_id = token_ids[0]616placeholder_token_id = tokenizer.convert_tokens_to_ids(args.placeholder_token)617618# Resize the token embeddings as we are adding new special tokens to the tokenizer619text_encoder.resize_token_embeddings(len(tokenizer))620621# Initialise the newly added placeholder token with the embeddings of the initializer token622token_embeds = text_encoder.get_input_embeddings().weight.data623token_embeds[placeholder_token_id] = token_embeds[initializer_token_id]624625# Freeze vae and unet626vae.requires_grad_(False)627unet.requires_grad_(False)628# Freeze all parameters except for the token embeddings in text encoder629text_encoder.text_model.encoder.requires_grad_(False)630text_encoder.text_model.final_layer_norm.requires_grad_(False)631text_encoder.text_model.embeddings.position_embedding.requires_grad_(False)632633if args.gradient_checkpointing:634# Keep unet in train mode if we are using gradient checkpointing to save memory.635# The dropout cannot be != 0 so it doesn't matter if we are in eval or train mode.636unet.train()637text_encoder.gradient_checkpointing_enable()638unet.enable_gradient_checkpointing()639640if args.enable_xformers_memory_efficient_attention:641if is_xformers_available():642import xformers643644xformers_version = version.parse(xformers.__version__)645if xformers_version == version.parse("0.0.16"):646logger.warn(647"xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."648)649unet.enable_xformers_memory_efficient_attention()650else:651raise ValueError("xformers is not available. Make sure it is installed correctly")652653# Enable TF32 for faster training on Ampere GPUs,654# cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices655if args.allow_tf32:656torch.backends.cuda.matmul.allow_tf32 = True657658if args.scale_lr:659args.learning_rate = (660args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes661)662663# Initialize the optimizer664optimizer = torch.optim.AdamW(665text_encoder.get_input_embeddings().parameters(), # only optimize the embeddings666lr=args.learning_rate,667betas=(args.adam_beta1, args.adam_beta2),668weight_decay=args.adam_weight_decay,669eps=args.adam_epsilon,670)671672# Dataset and DataLoaders creation:673train_dataset = TextualInversionDataset(674data_root=args.train_data_dir,675tokenizer=tokenizer,676size=args.resolution,677placeholder_token=args.placeholder_token,678repeats=args.repeats,679learnable_property=args.learnable_property,680center_crop=args.center_crop,681set="train",682)683train_dataloader = torch.utils.data.DataLoader(684train_dataset, batch_size=args.train_batch_size, shuffle=True, num_workers=args.dataloader_num_workers685)686if args.validation_epochs is not None:687warnings.warn(688f"FutureWarning: You are doing logging with validation_epochs={args.validation_epochs}."689" Deprecated validation_epochs in favor of `validation_steps`"690f"Setting `args.validation_steps` to {args.validation_epochs * len(train_dataset)}",691FutureWarning,692stacklevel=2,693)694args.validation_steps = args.validation_epochs * len(train_dataset)695696# Scheduler and math around the number of training steps.697overrode_max_train_steps = False698num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)699if args.max_train_steps is None:700args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch701overrode_max_train_steps = True702703lr_scheduler = get_scheduler(704args.lr_scheduler,705optimizer=optimizer,706num_warmup_steps=args.lr_warmup_steps * args.gradient_accumulation_steps,707num_training_steps=args.max_train_steps * args.gradient_accumulation_steps,708)709710# Prepare everything with our `accelerator`.711text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(712text_encoder, optimizer, train_dataloader, lr_scheduler713)714715# For mixed precision training we cast the unet and vae weights to half-precision716# as these models are only used for inference, keeping weights in full precision is not required.717weight_dtype = torch.float32718if accelerator.mixed_precision == "fp16":719weight_dtype = torch.float16720elif accelerator.mixed_precision == "bf16":721weight_dtype = torch.bfloat16722723# Move vae and unet to device and cast to weight_dtype724unet.to(accelerator.device, dtype=weight_dtype)725vae.to(accelerator.device, dtype=weight_dtype)726727# We need to recalculate our total training steps as the size of the training dataloader may have changed.728num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)729if overrode_max_train_steps:730args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch731# Afterwards we recalculate our number of training epochs732args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)733734# We need to initialize the trackers we use, and also store our configuration.735# The trackers initializes automatically on the main process.736if accelerator.is_main_process:737accelerator.init_trackers("textual_inversion", config=vars(args))738739# Train!740total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps741742logger.info("***** Running training *****")743logger.info(f" Num examples = {len(train_dataset)}")744logger.info(f" Num Epochs = {args.num_train_epochs}")745logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")746logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")747logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")748logger.info(f" Total optimization steps = {args.max_train_steps}")749global_step = 0750first_epoch = 0751# Potentially load in the weights and states from a previous save752if args.resume_from_checkpoint:753if args.resume_from_checkpoint != "latest":754path = os.path.basename(args.resume_from_checkpoint)755else:756# Get the most recent checkpoint757dirs = os.listdir(args.output_dir)758dirs = [d for d in dirs if d.startswith("checkpoint")]759dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))760path = dirs[-1] if len(dirs) > 0 else None761762if path is None:763accelerator.print(764f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."765)766args.resume_from_checkpoint = None767else:768accelerator.print(f"Resuming from checkpoint {path}")769accelerator.load_state(os.path.join(args.output_dir, path))770global_step = int(path.split("-")[1])771772resume_global_step = global_step * args.gradient_accumulation_steps773first_epoch = global_step // num_update_steps_per_epoch774resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)775776# Only show the progress bar once on each machine.777progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)778progress_bar.set_description("Steps")779780# keep original embeddings as reference781orig_embeds_params = accelerator.unwrap_model(text_encoder).get_input_embeddings().weight.data.clone()782783for epoch in range(first_epoch, args.num_train_epochs):784text_encoder.train()785for step, batch in enumerate(train_dataloader):786# Skip steps until we reach the resumed step787if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:788if step % args.gradient_accumulation_steps == 0:789progress_bar.update(1)790continue791792with accelerator.accumulate(text_encoder):793# Convert images to latent space794latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample().detach()795latents = latents * vae.config.scaling_factor796797# Sample noise that we'll add to the latents798noise = torch.randn_like(latents)799bsz = latents.shape[0]800# Sample a random timestep for each image801timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)802timesteps = timesteps.long()803804# Add noise to the latents according to the noise magnitude at each timestep805# (this is the forward diffusion process)806noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)807808# Get the text embedding for conditioning809encoder_hidden_states = text_encoder(batch["input_ids"])[0].to(dtype=weight_dtype)810811# Predict the noise residual812model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample813814# Get the target for loss depending on the prediction type815if noise_scheduler.config.prediction_type == "epsilon":816target = noise817elif noise_scheduler.config.prediction_type == "v_prediction":818target = noise_scheduler.get_velocity(latents, noise, timesteps)819else:820raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")821822loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")823824accelerator.backward(loss)825826optimizer.step()827lr_scheduler.step()828optimizer.zero_grad()829830# Let's make sure we don't update any embedding weights besides the newly added token831index_no_updates = torch.arange(len(tokenizer)) != placeholder_token_id832with torch.no_grad():833accelerator.unwrap_model(text_encoder).get_input_embeddings().weight[834index_no_updates835] = orig_embeds_params[index_no_updates]836837# Checks if the accelerator has performed an optimization step behind the scenes838if accelerator.sync_gradients:839progress_bar.update(1)840global_step += 1841if global_step % args.save_steps == 0:842save_path = os.path.join(args.output_dir, f"learned_embeds-steps-{global_step}.bin")843save_progress(text_encoder, placeholder_token_id, accelerator, args, save_path)844845if accelerator.is_main_process:846if global_step % args.checkpointing_steps == 0:847save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")848accelerator.save_state(save_path)849logger.info(f"Saved state to {save_path}")850851if args.validation_prompt is not None and global_step % args.validation_steps == 0:852log_validation(text_encoder, tokenizer, unet, vae, args, accelerator, weight_dtype, epoch)853854logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}855progress_bar.set_postfix(**logs)856accelerator.log(logs, step=global_step)857858if global_step >= args.max_train_steps:859break860# Create the pipeline using using the trained modules and save it.861accelerator.wait_for_everyone()862if accelerator.is_main_process:863if args.push_to_hub and args.only_save_embeds:864logger.warn("Enabling full model saving because --push_to_hub=True was specified.")865save_full_model = True866else:867save_full_model = not args.only_save_embeds868if save_full_model:869pipeline = StableDiffusionPipeline.from_pretrained(870args.pretrained_model_name_or_path,871text_encoder=accelerator.unwrap_model(text_encoder),872vae=vae,873unet=unet,874tokenizer=tokenizer,875)876pipeline.save_pretrained(args.output_dir)877# Save the newly trained embeddings878save_path = os.path.join(args.output_dir, "learned_embeds.bin")879save_progress(text_encoder, placeholder_token_id, accelerator, args, save_path)880881if args.push_to_hub:882repo.push_to_hub(commit_message="End of training", blocking=False, auto_lfs_prune=True)883884accelerator.end_training()885886887if __name__ == "__main__":888main()889890891