Debian Codegraph @

examples/inference/distributed/distributed_image_generation.py

raw
1 # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 """
16 Originally by jiwooya1000, put together together by sayakpaul.
17 Documentation: https://huggingface.co/docs/diffusers/main/en/training/distributed_inference
18
19 Run:
20
21 accelerate launch distributed_image_generation.py --batch_size 8
22
23 # Enable memory optimizations for large models like SD3
24 accelerate launch distributed_image_generation.py --batch_size 8 --low_mem
25 """
26
27 import os
28 import time
29
30 import fire
31 import torch
32 from datasets import load_dataset
33 from diffusers import DiffusionPipeline
34 from tqdm import tqdm
35
36 from accelerate import PartialState
37 from accelerate.utils import gather_object
38
39
40 START_TIME = time.strftime("%Y%m%d_%H%M%S")
41 DTYPE_MAP = {"fp32": torch.float32, "fp16": torch.float16, "bf16": torch.bfloat16}
42
43
44 def get_batches(items, batch_size):
45 num_batches = (len(items) + batch_size - 1) // batch_size
46 batches = []
47
48 for i in range(num_batches):
49 start_index = i * batch_size
50 end_index = min((i + 1) * batch_size, len(items))
51 batch = items[start_index:end_index]
52 batches.append(batch)
53
54 return batches
55
56
57 def main(
58 ckpt_id: str = "PixArt-alpha/PixArt-Sigma-XL-2-1024-MS",
59 save_dir: str = "./evaluation/examples",
60 seed: int = 1,
61 batch_size: int = 4,
62 num_inference_steps: int = 20,
63 guidance_scale: float = 4.5,
64 dtype: str = "fp16",
65 low_mem: bool = False,
66 ):
67 pipeline = DiffusionPipeline.from_pretrained(ckpt_id, torch_dtype=DTYPE_MAP[dtype])
68
69 save_dir = save_dir + f"_{START_TIME}"
70
71 parti_prompts = load_dataset("nateraw/parti-prompts", split="train")
72 data_loader = get_batches(items=parti_prompts["Prompt"], batch_size=batch_size)
73
74 distributed_state = PartialState()
75 if low_mem:
76 pipeline.enable_model_cpu_offload(gpu_id=distributed_state.device.index)
77 else:
78 pipeline = pipeline.to(distributed_state.device)
79
80 if distributed_state.is_main_process:
81 if not os.path.exists(save_dir):
82 os.makedirs(save_dir)
83 print(f"Directory '{save_dir}' created successfully.")
84 else:
85 print(f"Directory '{save_dir}' already exists.")
86
87 count = 0
88 for _, prompts_raw in tqdm(enumerate(data_loader), total=len(data_loader)):
89 input_prompts = []
90
91 with distributed_state.split_between_processes(prompts_raw) as prompts:
92 generator = torch.manual_seed(seed)
93 images = pipeline(
94 prompts, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, generator=generator
95 ).images
96 input_prompts.extend(prompts)
97
98 distributed_state.wait_for_everyone()
99
100 images = gather_object(images)
101 input_prompts = gather_object(input_prompts)
102
103 if distributed_state.is_main_process:
104 for image, prompt in zip(images, input_prompts):
105 count += 1
106 temp_dir = os.path.join(save_dir, f"example_{count}")
107
108 os.makedirs(temp_dir)
109 prompt = "_".join(prompt.split())
110 image.save(f"image_{prompt}.png")
111
112 if distributed_state.is_main_process:
113 print(f">>> Image Generation Finished. Saved in {save_dir}")
114
115
116 if __name__ == "__main__":
117 fire.Fire(main)