File size: 10,621 Bytes
3b57e92
 
d71fa96
3b57e92
 
 
 
 
 
df59904
3b57e92
 
 
 
 
 
 
 
 
 
1416f7f
154b20a
 
1416f7f
 
154b20a
3b57e92
 
 
 
 
 
 
154b20a
 
 
3b57e92
154b20a
 
 
3b57e92
 
 
 
154b20a
 
3b57e92
 
 
d71fa96
 
 
3b57e92
8401d0b
 
 
 
3b57e92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517b379
154b20a
 
 
517b379
154b20a
517b379
 
3b57e92
 
517b379
3b57e92
 
 
154b20a
3b57e92
 
 
 
 
6932478
 
3b57e92
 
 
 
 
 
154b20a
 
 
3f2ac01
 
3b57e92
 
 
 
 
 
 
 
 
 
 
6932478
 
 
 
 
 
 
 
3b57e92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154b20a
 
3b57e92
 
 
154b20a
3b57e92
 
 
 
 
 
 
 
 
 
154b20a
3b57e92
 
154b20a
3b57e92
154b20a
 
 
 
 
 
3f2ac01
 
 
154b20a
3b57e92
154b20a
3b57e92
 
 
aa34787
154b20a
3b57e92
 
 
fdedf25
 
 
 
 
154b20a
 
fdedf25
 
 
 
 
 
 
 
 
 
 
 
 
154b20a
fdedf25
 
 
 
 
 
 
 
3b57e92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154b20a
3b57e92
 
 
6932478
 
 
 
 
 
 
 
 
154b20a
 
 
 
 
 
 
 
 
 
3b57e92
 
 
154b20a
3b57e92
 
154b20a
3b57e92
 
 
 
154b20a
3b57e92
 
 
 
 
 
 
 
154b20a
3f2ac01
154b20a
 
 
 
 
 
 
3f2ac01
154b20a
 
 
79a0f65
154b20a
 
 
 
3b57e92
 
 
154b20a
 
 
 
3b57e92
 
 
 
 
 
 
 
 
 
 
 
 
154b20a
3b57e92
6932478
3b57e92
 
 
 
 
 
 
 
 
 
154b20a
3b57e92
 
 
 
 
 
 
 
 
 
6932478
 
3b57e92
 
 
 
 
 
154b20a
 
 
3f2ac01
 
3b57e92
 
 
 
 
 
 
64d98a2
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
import os
import random
from functools import partial

if os.environ.get("IN_SPACES", None) is not None:
    in_spaces = True
    import spaces
else:
    in_spaces = False
import gradio as gr
import torch

try:
    # pre-import triton can avoid diffusers/transformers make import error
    import triton
except ImportError:
    print("Triton not found, skip pre import")

## HDM model dep
import xut.env
xut.env.TORCH_COMPILE = False
xut.env.USE_LIGER = False
xut.env.USE_VANILLA = False
xut.env.USE_XFORMERS = False
xut.env.USE_XFORMERS_LAYERS = False
from hdm.pipeline import HDMXUTPipeline

## TIPO
import kgen.models as kgen_models
import kgen.executor.tipo as tipo
from kgen.formatter import apply_format, seperate_tags


torch.set_float32_matmul_precision("high")


DEFAULT_FORMAT = """
<|special|>,
<|characters|>, <|copyrights|>,
<|artist|>,

<|general|>,

<|extended|>.

<|quality|>, <|meta|>, <|rating|>
""".strip()


def GPU(func=None, duration=None):
    if func is None:
        return partial(GPU, duration=duration)
    if in_spaces:
        if duration:
            return spaces.GPU(func, duration=duration)
        else:
            return spaces.GPU(func)
    else:
        return func


def prompt_opt(tags, nl_prompt, aspect_ratio, seed):
    meta, operations, general, nl_prompt = tipo.parse_tipo_request(
        seperate_tags(tags.split(",")),
        nl_prompt,
        tag_length_target="long",
        nl_length_target="short",
        generate_extra_nl_prompt=True,
    )
    meta["aspect_ratio"] = f"{aspect_ratio:.3f}"
    result, timing = tipo.tipo_runner(meta, operations, general, nl_prompt, seed=seed)
    return apply_format(result, DEFAULT_FORMAT).strip().strip(".").strip(",")


print("Loading models, please wait...")
device = torch.device("cuda")

model = (
    HDMXUTPipeline.from_pretrained(
        "KBlueLeaf/HDM-xut-340M-anime",
        trust_remote_code=True,
    )
    .to(torch.float16)
    .to(device)
)

tipo_model_name, gguf_list = kgen_models.tipo_model_list[0]
kgen_models.load_model(tipo_model_name, device="cuda")
print("Models loaded successfully. UI is ready.")


@GPU(duration=10)
@torch.no_grad()
def generate(
    nl_prompt: str,
    tag_prompt: str,
    negative_prompt: str,
    tipo_enable: bool,
    format_enable: bool,
    num_images: int,
    steps: int,
    cfg_scale: float,
    size: int,
    aspect_ratio: str,
    fixed_short_edge: bool,
    zoom: float,
    x_shift: float,
    y_shift: float,
    tread_gamma1: float,
    tread_gamma2: float,
    seed: int,
    progress=gr.Progress(),
):
    as_w, as_h = aspect_ratio.split(":")
    aspect_ratio = float(as_w) / float(as_h)
    # Set seed for reproducibility
    if seed == -1:
        seed = random.randint(0, 2**32 - 1)
    torch.manual_seed(seed)

    # TIPO
    if tipo_enable:
        tipo.BAN_TAGS = [i.strip() for i in negative_prompt.split(",") if i.strip()]
        final_prompt = prompt_opt(tag_prompt, nl_prompt, aspect_ratio, seed)
    elif format_enable:
        final_prompt = apply_format(nl_prompt, DEFAULT_FORMAT)
    else:
        final_prompt = tag_prompt + "\n" + nl_prompt

    yield None, final_prompt

    prompts_to_generate = [final_prompt.replace("\n", " ")] * num_images
    negative_prompts_to_generate = [negative_prompt] * num_images

    if fixed_short_edge:
        if aspect_ratio > 1:
            h_factor = 1
            w_factor = aspect_ratio
        else:
            h_factor = 1 / aspect_ratio
            w_factor = 1
    else:
        w_factor = aspect_ratio**0.5
        h_factor = 1 / w_factor

    w = int(size * w_factor / 16) * 16
    h = int(size * h_factor / 16) * 16

    print("=" * 100)
    print(
        f"Generating {num_images} image(s) with seed: {seed} and resolution {w}x{h}"
    )
    print("-" * 80)
    print(f"Final prompt: {final_prompt}")
    print("-" * 80)
    print(f"Negative prompt: {negative_prompt}")
    print("-" * 80)

    prompts_batch = prompts_to_generate
    neg_prompts_batch = negative_prompts_to_generate

    images = model(
        prompts_batch,
        neg_prompts_batch,
        num_inference_steps=steps,
        cfg_scale=cfg_scale,
        width=w,
        height=h,
        camera_param={
            "zoom": zoom,
            "x_shift": x_shift,
            "y_shift": y_shift,
        },
        tread_gamma1=tread_gamma1,
        tread_gamma2=tread_gamma2,
    ).images

    yield images, final_prompt


# --- Gradio UI Definition ---
with gr.Blocks(title="HDM Demo", theme=gr.themes.Soft()) as demo:
    gr.Markdown("# HDM Demo")
    gr.Markdown(
        "### Enter a natural language prompt and/or specific tags to generate an image."
    )
    with gr.Accordion("Introduction", open=False):
        gr.Markdown("""
# HDM: HomeDiffusion Model Project
HDM is a project to implement a series of generative model that can be pretrained at home.

* Project Source code: https://github.com/KBlueLeaf/HDM
* Model: https://huggingface.co/KBlueLeaf/HDM-xut-340M-anime

## Usage
This early model used a model trained on anime image set only, 
so you should expect to see anime style images only in this demo.

For prompting, enter danbooru tag prompt to the box "Tag Prompt" with comma seperated and remove the underscore.
enter natural language prompt to the box "Natural Language Prompt" and enter negative prompt to the box "Negative Prompt".

If you don't want to spent so much effort on prompting, try to keep "Enable TIPO" selected.

If you don't want to apply any pre-defined format, unselect "Enable TIPO" and "Enable Format".

## Model Spec
- Backbone: 343M XUT(UViT modified) arch
- Text Encoder: Qwen3 0.6B (596M)
- VAE: EQ-SDXL-VAE, an EQ-VAE finetuned sdxl vae.

## Pretraining Dataset
- Danbooru 2023 (latest id around 8M)
- Pixiv famous artist set
- some pvc figure photos
""")

    with gr.Row():
        with gr.Column(scale=2):
            nl_prompt_box = gr.Textbox(
                label="Natural Language Prompt",
                placeholder="e.g., A beautiful anime girl standing in a blooming cherry blossom forest",
                lines=3,
            )
            tag_prompt_box = gr.Textbox(
                label="Tag Prompt (comma-separated)",
                placeholder="e.g., 1girl, solo, long hair, cherry blossoms, school uniform",
                lines=3,
            )
            neg_prompt_box = gr.Textbox(
                label="Negative Prompt",
                value=(
                    "llow quality, worst quality, text, signature, jpeg artifacts, bad anatomy, old, early, copyright name, watermark, artist name, signature, weibo username, realistic"
                ),
                lines=3,
            )
            with gr.Row():
                tipo_enable = gr.Checkbox(
                    label="Enable TIPO",
                    value=True,
                )
                format_enable = gr.Checkbox(
                    label="Enable Format",
                    value=True,
                )
            with gr.Row():
                zoom_slider = gr.Slider(
                    label="Zoom", minimum=0.5, maximum=2.0, value=1.0, step=0.01
                )
                x_shift_slider = gr.Slider(
                    label="X Shift", minimum=-0.5, maximum=0.5, value=0.0, step=0.01
                )
                y_shift_slider = gr.Slider(
                    label="Y Shift", minimum=-0.5, maximum=0.5, value=0.0, step=0.01
                )
        with gr.Column(scale=1):
            with gr.Row():
                num_images_slider = gr.Slider(
                    label="Number of Images", minimum=1, maximum=4, value=1, step=1
                )
                steps_slider = gr.Slider(
                    label="Inference Steps", minimum=1, maximum=50, value=24, step=1
                )

            with gr.Row():
                cfg_slider = gr.Slider(
                    label="CFG Scale", minimum=1.0, maximum=7.0, value=4.0, step=0.1
                )
                seed_input = gr.Number(
                    label="Seed",
                    value=-1,
                    precision=0,
                    info="Set to -1 for a random seed.",
                )

            with gr.Row():
                tread_gamma1_slider = gr.Slider(
                    label="Tread Gamma 1",
                    minimum=0.0,
                    maximum=1.0,
                    value=0.0,
                    step=0.05,
                    interactive=True,
                )
                tread_gamma2_slider = gr.Slider(
                    label="Tread Gamma 2",
                    minimum=0.0,
                    maximum=1.0,
                    value=0.0,
                    step=0.05,
                    interactive=True,
                )

            with gr.Row():
                size_slider = gr.Slider(
                    label="Base Image Size",
                    minimum=768,
                    maximum=1280,
                    value=1024,
                    step=16,
                )
            with gr.Row():
                aspect_ratio_box = gr.Textbox(
                    label="Ratio (W:H)",
                    value="1:1",
                )
                fixed_short_edge = gr.Checkbox(
                    label="Fixed Edge",
                    value=True,
                )

    with gr.Row():
        with gr.Column(scale=1):
            generate_button = gr.Button("Generate", variant="primary")
            output_prompt = gr.TextArea(
                label="Final Prompt",
                show_label=True,
                interactive=False,
                lines=32,
                max_lines=32,
            )
        with gr.Column(scale=2):
            output_gallery = gr.Gallery(
                label="Generated Images",
                show_label=True,
                elem_id="gallery",
                columns=2,
                rows=3,
                height="800px",
            )

    generate_button.click(
        fn=generate,
        inputs=[
            nl_prompt_box,
            tag_prompt_box,
            neg_prompt_box,
            tipo_enable,
            format_enable,
            num_images_slider,
            steps_slider,
            cfg_slider,
            size_slider,
            aspect_ratio_box,
            fixed_short_edge,
            zoom_slider,
            x_shift_slider,
            y_shift_slider,
            tread_gamma1_slider,
            tread_gamma2_slider,
            seed_input,
        ],
        outputs=[output_gallery, output_prompt],
        show_progress_on=output_gallery,
    )

if __name__ == "__main__":
    demo.launch()