-
Notifications
You must be signed in to change notification settings - Fork 293
/
inference.py
175 lines (154 loc) · 6.75 KB
/
inference.py
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import random
import torch
from diffusers import HunyuanDiTPipeline
from transformers import T5EncoderModel
import time
from loguru import logger
import gc
import sys
NEGATIVE_PROMPT = ''
TEXT_ENCODER_CONF = {
"negative_prompt": NEGATIVE_PROMPT,
"prompt_embeds": None,
"negative_prompt_embeds": None,
"prompt_attention_mask": None,
"negative_prompt_attention_mask": None,
"max_sequence_length": 256,
"text_encoder_index": 1,
}
def flush():
gc.collect()
torch.cuda.empty_cache()
class End2End(object):
def __init__(self, model_id="Tencent-Hunyuan/HunyuanDiT-v1.1-Diffusers-Distilled"):
self.model_id = model_id
self.device = "cuda" if torch.cuda.is_available() else "cpu"
# ========================================================================
self.default_negative_prompt = NEGATIVE_PROMPT
logger.info("==================================================")
logger.info(f" Model is ready. ")
logger.info("==================================================")
def load_pipeline(self):
self.pipeline= HunyuanDiTPipeline.from_pretrained(
self.model_id,
text_encoder=None,
text_encoder_2=None,
torch_dtype=torch.float16,
).to(self.device)
def get_text_emb(self, prompts):
with torch.no_grad():
text_encoder_2 = T5EncoderModel.from_pretrained(
self.model_id,
subfolder="text_encoder_2",
load_in_8bit=True,
device_map="auto",
)
encoder_pipeline = HunyuanDiTPipeline.from_pretrained(
self.model_id,
text_encoder_2=text_encoder_2,
transformer=None,
vae=None,
torch_dtype=torch.float16,
device_map="balanced",
)
TEXT_ENCODER_CONF["negative_prompt"]=self.default_negative_prompt
prompt_emb1 = encoder_pipeline.encode_prompt(prompts, negative_prompt=self.default_negative_prompt)
prompt_emb2 = encoder_pipeline.encode_prompt(prompts, **TEXT_ENCODER_CONF)
del text_encoder_2
del encoder_pipeline
flush()
return prompt_emb1, prompt_emb2
def predict(self,
user_prompt,
seed=None,
enhanced_prompt=None,
negative_prompt=None,
infer_steps=50,
guidance_scale=6,
batch_size=1,
):
# ========================================================================
# Arguments: seed
# ========================================================================
if seed is None:
seed = random.randint(0, 1_000_000)
if not isinstance(seed, int):
raise TypeError(f"`seed` must be an integer, but got {type(seed)}")
generator = torch.Generator(device=self.device).manual_seed(seed)
# ========================================================================
# Arguments: prompt, new_prompt, negative_prompt
# ========================================================================
if not isinstance(user_prompt, str):
raise TypeError(f"`user_prompt` must be a string, but got {type(user_prompt)}")
user_prompt = user_prompt.strip()
prompt = user_prompt
if enhanced_prompt is not None:
if not isinstance(enhanced_prompt, str):
raise TypeError(f"`enhanced_prompt` must be a string, but got {type(enhanced_prompt)}")
enhanced_prompt = enhanced_prompt.strip()
prompt = enhanced_prompt
# negative prompt
if negative_prompt is not None and negative_prompt != '':
self.default_negative_prompt = negative_prompt
if not isinstance(self.default_negative_prompt, str):
raise TypeError(f"`negative_prompt` must be a string, but got {type(negative_prompt)}")
# ========================================================================
logger.debug(f"""
prompt: {user_prompt}
enhanced prompt: {enhanced_prompt}
seed: {seed}
negative_prompt: {negative_prompt}
batch_size: {batch_size}
guidance_scale: {guidance_scale}
infer_steps: {infer_steps}
""")
# get text embeding
flush()
prompt_emb1, prompt_emb2 = self.get_text_emb(prompt)
prompt_embeds, negative_prompt_embeds, prompt_attention_mask, negative_prompt_attention_mask = prompt_emb1
prompt_embeds_2,negative_prompt_embeds_2,prompt_attention_mask_2,negative_prompt_attention_mask_2 = prompt_emb2
del prompt_emb1
del prompt_emb2
# get pipeline
self.load_pipeline()
samples = self.pipeline(
prompt_embeds=prompt_embeds,
prompt_embeds_2=prompt_embeds_2,
negative_prompt_embeds=negative_prompt_embeds,
negative_prompt_embeds_2=negative_prompt_embeds_2,
prompt_attention_mask=prompt_attention_mask,
prompt_attention_mask_2=prompt_attention_mask_2,
negative_prompt_attention_mask=negative_prompt_attention_mask,
negative_prompt_attention_mask_2=negative_prompt_attention_mask_2,
num_images_per_prompt=batch_size,
guidance_scale=guidance_scale,
num_inference_steps=infer_steps,
generator=generator,
).images[0]
return {
'images': samples,
'seed': seed,
}
if __name__ == "__main__":
if len(sys.argv) != 5:
print("Usage: python lite/inference.py ${model_id} ${prompt} ${infer_steps} ${guidance_scale}")
print("model_id: Choose a diffusers repository from the official Hugging Face repository https://huggingface.co/Tencent-Hunyuan, "
"such as Tencent-Hunyuan/HunyuanDiT-v1.1-Diffusers, "
"Tencent-Hunyuan/HunyuanDiT-v1.1-Diffusers-Distilled, "
"Tencent-Hunyuan/HunyuanDiT-Diffusers, or Tencent-Hunyuan/HunyuanDiT-Diffusers-Distilled.")
print("prompt: the input prompt")
print("infer_steps: infer_steps")
print("guidance_scale: guidance_scale")
sys.exit(1)
model_id = sys.argv[1]
prompt = sys.argv[2]
infer_steps = int(sys.argv[3])
guidance_scale = int(sys.argv[4])
gen = End2End(model_id)
seed = 42
results = gen.predict(prompt,
seed = seed,
infer_steps=infer_steps,
guidance_scale=guidance_scale,
)
results['images'].save('./lite_image.png')