diffusers/tools
1128
1#!/usr/bin/env python32from diffusers import DiffusionPipeline, AutoencoderKL3import torch4torch.backends.cudnn.deterministic = False5torch.backends.cuda.matmul.allow_tf32 = False6torch.backends.cudnn.allow_tf32 = False7torch.backends.cudnn.benchmark = True8torch.backends.cuda.enable_flash_sdp(False)9 10vae = AutoencoderKL.from_pretrained("stabilityai/sdxl-vae", torch_dtype=torch.float16)11base_pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", vae=vae, torch_dtype=torch.float16, use_safetensors=True, variant="fp16")12base_pipe.to("cuda") # OR, pipe.enable_sequential_cpu_offload() OR,13#pipe.enable_model_cpu_offload()14 15# if using torch < 2.016# pipe.enable_xformers_memory_efficient_attention()17 18# Reproducibility.19torch_seed = 420242042020refiner_seed = 69800856921prompt = "happy child flying a kite on a sunny day"22negative_prompt = ''23# Batch size.24batch_size = 225do_latent = True26prompt = [ prompt ] * batch_size27negative_prompt = [ negative_prompt ] * batch_size28# We're going to schedule 20 steps, and complete 50% of them using either model.29total_num_steps = 2030# We need multiple Generators.31generator = [ torch.Generator(device="cuda").manual_seed(torch_seed) ] * batch_size32 33pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-xl-refiner-1.0", vae=base_pipe.vae, text_encoder_2=base_pipe.text_encoder_2, torch_dtype=torch.float16, use_safetensors=True, variant="fp16")34# Using channels last layout.35# pipe.unet.to(memory_format=torch.channels_last)36pipe.to("cuda") # OR, pipe.enable_sequential_cpu_offload() OR, 37 38# Generate the base image.39pre_image = base_pipe(prompt=prompt, generator=generator,40 num_inference_steps=total_num_steps, negative_prompt=negative_prompt, output_type="latent" if do_latent else "pil").images41 42# Generate a range from 0.1 to 0.9, with 0.1 increments.43test_strengths = [0.2]44for refiner_strength in test_strengths:45 # Generate a new set of random states for each image.46 generator_two = [ torch.Generator(device="cuda").manual_seed(refiner_seed) ] * batch_size47 # Put through the refiner now.48 images = pipe(prompt=prompt, image=pre_image, aesthetic_score=10, negative_aesthetic_score=2.4, generator=generator_two,49 num_inference_steps=total_num_steps, strength=refiner_strength, negative_prompt=negative_prompt).images # denoising_start50 for idx in range(0, len(images)):51 print(f'Image: {idx}')52 images[idx].save(f'/home/patrick/images/refiner_bug/test-{refiner_strength}-{idx}--{batch_size}--{do_latent}.png', format='PNG')53 