Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ShivamShrirao
GitHub Repository: ShivamShrirao/diffusers
Path: blob/main/examples/research_projects/intel_opts/inference_bf16.py
1979 views
1
import intel_extension_for_pytorch as ipex
2
import torch
3
from PIL import Image
4
5
from diffusers import StableDiffusionPipeline
6
7
8
def image_grid(imgs, rows, cols):
9
assert len(imgs) == rows * cols
10
11
w, h = imgs[0].size
12
grid = Image.new("RGB", size=(cols * w, rows * h))
13
grid_w, grid_h = grid.size
14
15
for i, img in enumerate(imgs):
16
grid.paste(img, box=(i % cols * w, i // cols * h))
17
return grid
18
19
20
prompt = ["a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings"]
21
batch_size = 8
22
prompt = prompt * batch_size
23
24
device = "cpu"
25
model_id = "path-to-your-trained-model"
26
model = StableDiffusionPipeline.from_pretrained(model_id)
27
model = model.to(device)
28
29
# to channels last
30
model.unet = model.unet.to(memory_format=torch.channels_last)
31
model.vae = model.vae.to(memory_format=torch.channels_last)
32
model.text_encoder = model.text_encoder.to(memory_format=torch.channels_last)
33
model.safety_checker = model.safety_checker.to(memory_format=torch.channels_last)
34
35
# optimize with ipex
36
model.unet = ipex.optimize(model.unet.eval(), dtype=torch.bfloat16, inplace=True)
37
model.vae = ipex.optimize(model.vae.eval(), dtype=torch.bfloat16, inplace=True)
38
model.text_encoder = ipex.optimize(model.text_encoder.eval(), dtype=torch.bfloat16, inplace=True)
39
model.safety_checker = ipex.optimize(model.safety_checker.eval(), dtype=torch.bfloat16, inplace=True)
40
41
# compute
42
seed = 666
43
generator = torch.Generator(device).manual_seed(seed)
44
with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloat16):
45
images = model(prompt, guidance_scale=7.5, num_inference_steps=50, generator=generator).images
46
47
# save image
48
grid = image_grid(images, rows=2, cols=4)
49
grid.save(model_id + ".png")
50
51