File size: 8,607 Bytes
779acf3
 
 
 
59135a5
72b0fe6
59135a5
779acf3
72b0fe6
779acf3
7aa55b4
1869bcd
 
779acf3
11cddad
 
 
e955768
59135a5
e955768
11cddad
779acf3
1869bcd
 
 
 
 
 
 
 
 
 
 
 
72b0fe6
 
 
 
 
 
 
 
 
 
1869bcd
 
 
 
 
 
7aa55b4
1869bcd
 
 
 
 
72b0fe6
1869bcd
 
 
 
 
 
 
 
72b0fe6
 
1869bcd
72b0fe6
1869bcd
 
 
 
 
 
 
 
 
 
72b0fe6
1869bcd
 
 
 
 
 
 
 
 
72b0fe6
1869bcd
 
779acf3
 
 
 
 
 
 
 
1869bcd
 
 
 
 
 
 
e3c9822
779acf3
 
11cddad
779acf3
11cddad
 
 
 
 
779acf3
 
 
 
11cddad
779acf3
11cddad
779acf3
11cddad
 
 
779acf3
11cddad
779acf3
11cddad
 
72b0fe6
11cddad
 
 
72b0fe6
11cddad
 
 
72b0fe6
 
 
 
 
11cddad
 
 
 
72b0fe6
11cddad
 
 
 
 
 
779acf3
11cddad
779acf3
 
 
38a02d4
11cddad
 
38a02d4
 
 
 
11cddad
 
38a02d4
 
 
779acf3
11cddad
 
779acf3
 
 
 
11cddad
 
779acf3
 
 
 
11cddad
 
779acf3
 
 
 
11cddad
 
779acf3
 
 
 
11cddad
 
779acf3
 
 
 
11cddad
 
779acf3
 
 
 
11cddad
 
779acf3
 
 
 
11cddad
 
779acf3
 
 
 
11cddad
 
779acf3
 
 
 
11cddad
 
779acf3
 
 
 
11cddad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
779acf3
e3c9822
1869bcd
93fd2ea
e3c9822
 
1869bcd
e3c9822
779acf3
eaf1941
 
72b0fe6
 
 
 
 
 
1869bcd
93fd2ea
e3c9822
 
11cddad
e3c9822
1869bcd
eaf1941
 
 
 
 
 
 
 
e3c9822
11cddad
e3c9822
779acf3
11cddad
98d1c03
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
#!/usr/bin/env python

from __future__ import annotations

import os
import random

import gradio as gr
import numpy as np
import PIL.Image
import spaces
import torch
from diffusers import StableDiffusionAttendAndExcitePipeline, StableDiffusionPipeline

DESCRIPTION = """\
# Attend-and-Excite

This is a demo for [Attend-and-Excite](https://arxiv.org/abs/2301.13826).
Attend-and-Excite performs attention-based generative semantic guidance to mitigate subject neglect in Stable Diffusion.
Select a prompt and a set of indices matching the subjects you wish to strengthen (the `Check token indices` cell can help map between a word and its index).
"""

if not torch.cuda.is_available():
    DESCRIPTION += "\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>"

if torch.cuda.is_available():
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    model_id = "CompVis/stable-diffusion-v1-4"
    ax_pipe = StableDiffusionAttendAndExcitePipeline.from_pretrained(model_id)
    ax_pipe.to(device)
    sd_pipe = StableDiffusionPipeline.from_pretrained(model_id)
    sd_pipe.to(device)


MAX_INFERENCE_STEPS = 100
MAX_SEED = np.iinfo(np.int32).max


def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
    if randomize_seed:
        seed = random.randint(0, MAX_SEED)
    return seed


def get_token_table(prompt: str) -> list[tuple[int, str]]:
    tokens = [ax_pipe.tokenizer.decode(t) for t in ax_pipe.tokenizer(prompt)["input_ids"]]
    tokens = tokens[1:-1]
    return list(enumerate(tokens, start=1))


@spaces.GPU
def run(
    prompt: str,
    indices_to_alter_str: str,
    seed: int = 0,
    apply_attend_and_excite: bool = True,
    num_inference_steps: int = 50,
    guidance_scale: float = 7.5,
    scale_factor: int = 20,
    thresholds: dict[int, float] = {
        10: 0.5,
        20: 0.8,
    },
    max_iter_to_alter: int = 25,
) -> PIL.Image.Image:
    if num_inference_steps > MAX_INFERENCE_STEPS:
        raise gr.Error(f"Number of steps cannot exceed {MAX_INFERENCE_STEPS}.")

    generator = torch.Generator(device=device).manual_seed(seed)
    if apply_attend_and_excite:
        try:
            token_indices = list(map(int, indices_to_alter_str.split(",")))
        except Exception:
            raise ValueError("Invalid token indices.")
        out = ax_pipe(
            prompt=prompt,
            token_indices=token_indices,
            guidance_scale=guidance_scale,
            generator=generator,
            num_inference_steps=num_inference_steps,
            max_iter_to_alter=max_iter_to_alter,
            thresholds=thresholds,
            scale_factor=scale_factor,
        )
    else:
        out = sd_pipe(
            prompt=prompt,
            guidance_scale=guidance_scale,
            generator=generator,
            num_inference_steps=num_inference_steps,
        )
    return out.images[0]


def process_example(
    prompt: str,
    indices_to_alter_str: str,
    seed: int,
    apply_attend_and_excite: bool,
) -> tuple[list[tuple[int, str]], PIL.Image.Image]:
    token_table = get_token_table(prompt)
    result = run(
        prompt=prompt,
        indices_to_alter_str=indices_to_alter_str,
        seed=seed,
        apply_attend_and_excite=apply_attend_and_excite,
    )
    return token_table, result


with gr.Blocks(css="style.css") as demo:
    gr.Markdown(DESCRIPTION)
    gr.DuplicateButton(
        value="Duplicate Space for private use",
        elem_id="duplicate-button",
        visible=os.getenv("SHOW_DUPLICATE_BUTTON") == "1",
    )

    with gr.Row():
        with gr.Column():
            prompt = gr.Text(
                label="Prompt",
                max_lines=1,
                placeholder="A pod of dolphins leaping out of the water in an ocean with a ship on the background",
            )
            with gr.Accordion(label="Check token indices", open=False):
                show_token_indices_button = gr.Button("Show token indices")
                token_indices_table = gr.Dataframe(label="Token indices", headers=["Index", "Token"], col_count=2)
            token_indices_str = gr.Text(
                label="Token indices (a comma-separated list indices of the tokens you wish to alter)",
                max_lines=1,
                placeholder="4,16",
            )
            apply_attend_and_excite = gr.Checkbox(label="Apply Attend-and-Excite", value=True)
            seed = gr.Slider(
                label="Seed",
                minimum=0,
                maximum=MAX_SEED,
                step=1,
                value=0,
            )
            randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
            num_inference_steps = gr.Slider(
                label="Number of inference steps",
                minimum=1,
                maximum=MAX_INFERENCE_STEPS,
                step=1,
                value=50,
            )
            guidance_scale = gr.Slider(
                label="Guidance scale",
                minimum=0,
                maximum=50,
                step=0.1,
                value=7.5,
            )
            run_button = gr.Button("Generate")
        with gr.Column():
            result = gr.Image(label="Result")

    with gr.Row():
        examples = [
            [
                "A mouse and a red car",
                "2,6",
                2098,
                True,
            ],
            [
                "A mouse and a red car",
                "2,6",
                2098,
                False,
            ],
            [
                "A horse and a dog",
                "2,5",
                123,
                True,
            ],
            [
                "A horse and a dog",
                "2,5",
                123,
                False,
            ],
            [
                "A painting of an elephant with glasses",
                "5,7",
                123,
                True,
            ],
            [
                "A painting of an elephant with glasses",
                "5,7",
                123,
                False,
            ],
            [
                "A playful kitten chasing a butterfly in a wildflower meadow",
                "3,6,10",
                123,
                True,
            ],
            [
                "A playful kitten chasing a butterfly in a wildflower meadow",
                "3,6,10",
                123,
                False,
            ],
            [
                "A grizzly bear catching a salmon in a crystal clear river surrounded by a forest",
                "2,6,15",
                123,
                True,
            ],
            [
                "A grizzly bear catching a salmon in a crystal clear river surrounded by a forest",
                "2,6,15",
                123,
                False,
            ],
            [
                "A pod of dolphins leaping out of the water in an ocean with a ship on the background",
                "4,16",
                123,
                True,
            ],
            [
                "A pod of dolphins leaping out of the water in an ocean with a ship on the background",
                "4,16",
                123,
                False,
            ],
        ]
        gr.Examples(
            examples=examples,
            inputs=[
                prompt,
                token_indices_str,
                seed,
                apply_attend_and_excite,
            ],
            outputs=[
                token_indices_table,
                result,
            ],
            fn=process_example,
            cache_examples=os.getenv("CACHE_EXAMPLES") == "1",
            examples_per_page=20,
        )

    show_token_indices_button.click(
        fn=get_token_table,
        inputs=prompt,
        outputs=token_indices_table,
        queue=False,
        api_name="get-token-table",
    )

    gr.on(
        triggers=[prompt.submit, token_indices_str.submit, run_button.click],
        fn=randomize_seed_fn,
        inputs=[seed, randomize_seed],
        outputs=seed,
        queue=False,
        api_name=False,
    ).then(
        fn=get_token_table,
        inputs=prompt,
        outputs=token_indices_table,
        queue=False,
        api_name=False,
    ).then(
        fn=run,
        inputs=[
            prompt,
            token_indices_str,
            seed,
            apply_attend_and_excite,
            num_inference_steps,
            guidance_scale,
        ],
        outputs=result,
        api_name="run",
    )

if __name__ == "__main__":
    demo.queue(max_size=20).launch()