Niansuh commited on
Commit
eeb848f
1 Parent(s): 9b21e24

Update custom_pipeline.py

Browse files
Files changed (1) hide show
  1. custom_pipeline.py +9 -66
custom_pipeline.py CHANGED
@@ -44,7 +44,6 @@ from diffusers.utils.torch_utils import randn_tensor
44
  from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
45
  from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
46
 
47
-
48
  if is_invisible_watermark_available():
49
  from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
50
 
@@ -88,7 +87,6 @@ EXAMPLE_DOC_STRING = """
88
  ```
89
  """
90
 
91
-
92
  # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
93
  def retrieve_latents(
94
  encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
@@ -773,7 +771,7 @@ class CosStableDiffusionXLInstructPix2PixPipeline(
773
  # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
774
  # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
775
  # corresponds to doing no classifier free guidance.
776
- do_classifier_free_guidance = guidance_scale > 10.0 and image_guidance_scale >= 5.0
777
 
778
  # 3. Encode input prompt
779
  text_encoder_lora_scale = (
@@ -815,9 +813,7 @@ class CosStableDiffusionXLInstructPix2PixPipeline(
815
  device,
816
  do_classifier_free_guidance,
817
  )
818
-
819
- image_latents = image_latents * self.vae.config.scaling_factor
820
-
821
  # 7. Prepare latent variables
822
  num_channels_latents = self.vae.config.latent_channels
823
  latents = self.prepare_latents(
@@ -859,7 +855,8 @@ class CosStableDiffusionXLInstructPix2PixPipeline(
859
  dtype=prompt_embeds.dtype,
860
  text_encoder_projection_dim=text_encoder_projection_dim,
861
  )
862
-
 
863
  if do_classifier_free_guidance:
864
  # The extra concat similar to how it's done in SD InstructPix2Pix.
865
  prompt_embeds = torch.cat([prompt_embeds, negative_prompt_embeds, negative_prompt_embeds], dim=0)
@@ -870,35 +867,19 @@ class CosStableDiffusionXLInstructPix2PixPipeline(
870
 
871
  prompt_embeds = prompt_embeds.to(device)
872
  add_text_embeds = add_text_embeds.to(device)
873
- add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
874
 
875
  # 11. Denoising loop
876
  num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
877
- if denoising_end is not None and isinstance(denoising_end, float) and denoising_end > 0 and denoising_end < 1:
878
- discrete_timestep_cutoff = int(
879
- round(
880
- self.scheduler.config.num_train_timesteps
881
- - (denoising_end * self.scheduler.config.num_train_timesteps)
882
- )
883
- )
884
- num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
885
- timesteps = timesteps[:num_inference_steps]
886
-
887
  with self.progress_bar(total=num_inference_steps) as progress_bar:
888
  for i, t in enumerate(timesteps):
889
- # Expand the latents if we are doing classifier free guidance.
890
- # The latents are expanded 3 times because for pix2pix the guidance
891
- # is applied for both the text and the input image.
892
  latent_model_input = torch.cat([latents] * 3) if do_classifier_free_guidance else latents
893
-
894
- # concat latents, image_latents in the channel dimension
895
- scaled_latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
896
- scaled_latent_model_input = torch.cat([scaled_latent_model_input, image_latents], dim=1)
897
 
898
  # predict the noise residual
899
  added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
900
  noise_pred = self.unet(
901
- scaled_latent_model_input,
902
  t,
903
  encoder_hidden_states=prompt_embeds,
904
  cross_attention_kwargs=cross_attention_kwargs,
@@ -911,7 +892,7 @@ class CosStableDiffusionXLInstructPix2PixPipeline(
911
  noise_pred_text, noise_pred_image, noise_pred_uncond = noise_pred.chunk(3)
912
  noise_pred = (
913
  noise_pred_uncond
914
- + guidance_scale * (noise_pred_text - noise_pred_image)
915
  + image_guidance_scale * (noise_pred_image - noise_pred_uncond)
916
  )
917
 
@@ -920,12 +901,7 @@ class CosStableDiffusionXLInstructPix2PixPipeline(
920
  noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
921
 
922
  # compute the previous noisy sample x_t -> x_t-1
923
- latents_dtype = latents.dtype
924
  latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
925
- if latents.dtype != latents_dtype:
926
- if torch.backends.mps.is_available():
927
- # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
928
- latents = latents.to(latents_dtype)
929
 
930
  # call the callback, if provided
931
  if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
@@ -934,41 +910,8 @@ class CosStableDiffusionXLInstructPix2PixPipeline(
934
  step_idx = i // getattr(self.scheduler, "order", 1)
935
  callback(step_idx, t, latents)
936
 
937
- if XLA_AVAILABLE:
938
- xm.mark_step()
939
-
940
  if not output_type == "latent":
941
- # make sure the VAE is in float32 mode, as it overflows in float16
942
- needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
943
-
944
- if needs_upcasting:
945
- self.upcast_vae()
946
- latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
947
- elif latents.dtype != self.vae.dtype:
948
- if torch.backends.mps.is_available():
949
- # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
950
- self.vae = self.vae.to(latents.dtype)
951
-
952
- # unscale/denormalize the latents
953
- # denormalize with the mean and std if available and not None
954
- has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
955
- has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
956
- if has_latents_mean and has_latents_std:
957
- latents_mean = (
958
- torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
959
- )
960
- latents_std = (
961
- torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
962
- )
963
- latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
964
- else:
965
- latents = latents / self.vae.config.scaling_factor
966
-
967
- image = self.vae.decode(latents, return_dict=False)[0]
968
-
969
- # cast back to fp16 if needed
970
- if needs_upcasting:
971
- self.vae.to(dtype=torch.float16)
972
  else:
973
  return StableDiffusionXLPipelineOutput(images=latents)
974
 
 
44
  from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
45
  from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
46
 
 
47
  if is_invisible_watermark_available():
48
  from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
49
 
 
87
  ```
88
  """
89
 
 
90
  # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
91
  def retrieve_latents(
92
  encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
 
771
  # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
772
  # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
773
  # corresponds to doing no classifier free guidance.
774
+ do_classifier_free_guidance = guidance_scale > 1.0 and image_guidance_scale >= 1.0
775
 
776
  # 3. Encode input prompt
777
  text_encoder_lora_scale = (
 
813
  device,
814
  do_classifier_free_guidance,
815
  )
816
+
 
 
817
  # 7. Prepare latent variables
818
  num_channels_latents = self.vae.config.latent_channels
819
  latents = self.prepare_latents(
 
855
  dtype=prompt_embeds.dtype,
856
  text_encoder_projection_dim=text_encoder_projection_dim,
857
  )
858
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
859
+
860
  if do_classifier_free_guidance:
861
  # The extra concat similar to how it's done in SD InstructPix2Pix.
862
  prompt_embeds = torch.cat([prompt_embeds, negative_prompt_embeds, negative_prompt_embeds], dim=0)
 
867
 
868
  prompt_embeds = prompt_embeds.to(device)
869
  add_text_embeds = add_text_embeds.to(device)
 
870
 
871
  # 11. Denoising loop
872
  num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
 
 
 
 
 
 
 
 
 
 
873
  with self.progress_bar(total=num_inference_steps) as progress_bar:
874
  for i, t in enumerate(timesteps):
875
+ # expand the latents if we are doing classifier free guidance
 
 
876
  latent_model_input = torch.cat([latents] * 3) if do_classifier_free_guidance else latents
877
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
 
 
 
878
 
879
  # predict the noise residual
880
  added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
881
  noise_pred = self.unet(
882
+ torch.cat([latent_model_input, image_latents], dim=1),
883
  t,
884
  encoder_hidden_states=prompt_embeds,
885
  cross_attention_kwargs=cross_attention_kwargs,
 
892
  noise_pred_text, noise_pred_image, noise_pred_uncond = noise_pred.chunk(3)
893
  noise_pred = (
894
  noise_pred_uncond
895
+ + guidance_scale * (noise_pred_text - noise_pred_uncond)
896
  + image_guidance_scale * (noise_pred_image - noise_pred_uncond)
897
  )
898
 
 
901
  noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
902
 
903
  # compute the previous noisy sample x_t -> x_t-1
 
904
  latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
 
 
 
 
905
 
906
  # call the callback, if provided
907
  if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
 
910
  step_idx = i // getattr(self.scheduler, "order", 1)
911
  callback(step_idx, t, latents)
912
 
 
 
 
913
  if not output_type == "latent":
914
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
915
  else:
916
  return StableDiffusionXLPipelineOutput(images=latents)
917