Home Stable diffusion XL script
Post
Cancel

Stable diffusion XL script

This is a simple code that uses stable diffusion XL for text guided image generation. Check the official SDXL huggingface page for more details.

A demo image:

drawing

Generated by:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from diffusers import DiffusionPipeline
import torch
import argparse
import os

# load both base & refiner
base = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
)
base.to("cuda")
refiner = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-refiner-1.0",
    text_encoder_2=base.text_encoder_2,
    vae=base.vae,
    torch_dtype=torch.float16,
    use_safetensors=True,
    variant="fp16",
)
refiner.to("cuda")


def SDXL_img(prompt, n_steps=40, high_noise_frac=0.8):

    # run both experts
    image = base(
        prompt=prompt,
        num_inference_steps=n_steps,
        denoising_end=high_noise_frac,
        output_type="latent",
    ).images
    image = refiner(
        prompt=prompt,
        num_inference_steps=n_steps,
        denoising_start=high_noise_frac,
        image=image,
    ).images[0]

    return image


if __name__ == "__main__":


    save_folder = './SDXL_img'
    file_name = 'golden_retriver.png'
    save_dir = os.path.join(save_folder, file_name)

    prompt = "A cute golden retriver puppy with background of mapple leaves."

    image = SDXL_img(prompt)
    image.save(save_dir)
This post is licensed under CC BY 4.0 by the author.