File size: 11,170 Bytes
e73da9c
 
7c56def
e73da9c
7c56def
e73da9c
 
 
 
 
 
 
 
 
7c56def
 
 
 
e73da9c
 
 
 
7c56def
 
 
 
 
 
 
e73da9c
 
7c56def
e73da9c
7c56def
 
 
 
 
 
 
 
 
 
e73da9c
7c56def
 
 
 
 
 
e73da9c
 
7c56def
 
e73da9c
 
7c56def
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e73da9c
 
 
7c56def
e73da9c
7c56def
 
 
 
 
 
 
 
 
 
 
e73da9c
 
 
 
 
 
7c56def
 
e73da9c
 
 
 
7c56def
e73da9c
 
 
 
 
7c56def
 
 
 
 
e73da9c
 
 
7c56def
 
 
 
 
 
e73da9c
7c56def
e73da9c
 
 
 
 
 
 
 
7c56def
 
 
 
 
 
 
 
 
 
 
 
 
 
e73da9c
 
 
7c56def
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e73da9c
 
 
 
7c56def
e73da9c
 
 
7c56def
 
e73da9c
 
7c56def
 
e73da9c
7c56def
e73da9c
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
import torch
from tqdm import tqdm
from typing import List, Optional, Tuple
from models import PipelineWrapper
import gradio as gr


def inversion_forward_process(model: PipelineWrapper,
                              x0: torch.Tensor,
                              etas: Optional[float] = None,
                              prompts: List[str] = [""],
                              cfg_scales: List[float] = [3.5],
                              num_inference_steps: int = 50,
                              numerical_fix: bool = False,
                              duration: Optional[float] = None,
                              first_order: bool = False,
                              save_compute: bool = True,
                              progress=gr.Progress()) -> Tuple:
    if len(prompts) > 1 or prompts[0] != "":
        text_embeddings_hidden_states, text_embeddings_class_labels, \
            text_embeddings_boolean_prompt_mask = model.encode_text(prompts)

        # In the forward negative prompts are not supported currently (TODO)
        uncond_embeddings_hidden_states, uncond_embeddings_class_lables, uncond_boolean_prompt_mask = model.encode_text(
            [""], negative=True, save_compute=save_compute, cond_length=text_embeddings_class_labels.shape[1]
            if text_embeddings_class_labels is not None else None)
    else:
        uncond_embeddings_hidden_states, uncond_embeddings_class_lables, uncond_boolean_prompt_mask = model.encode_text(
            [""], negative=True, save_compute=False)

    timesteps = model.model.scheduler.timesteps.to(model.device)
    variance_noise_shape = model.get_noise_shape(x0, num_inference_steps)

    if type(etas) in [int, float]:
        etas = [etas]*model.model.scheduler.num_inference_steps
    xts = model.sample_xts_from_x0(x0, num_inference_steps=num_inference_steps)
    zs = torch.zeros(size=variance_noise_shape, device=model.device)
    extra_info = [None] * len(zs)

    if timesteps[0].dtype == torch.int64:
        t_to_idx = {int(v): k for k, v in enumerate(timesteps)}
    elif timesteps[0].dtype == torch.float32:
        t_to_idx = {float(v): k for k, v in enumerate(timesteps)}
    xt = x0
    op = tqdm(timesteps, desc="Inverting")
    model.setup_extra_inputs(xt, init_timestep=timesteps[0], audio_end_in_s=duration,
                             save_compute=save_compute and prompts[0] != "")
    app_op = progress.tqdm(timesteps, desc="Inverting")
    for t, _ in zip(op, app_op):
        idx = num_inference_steps - t_to_idx[int(t) if timesteps[0].dtype == torch.int64 else float(t)] - 1

        # 1. predict noise residual
        xt = xts[idx+1][None]
        xt_inp = model.model.scheduler.scale_model_input(xt, t)

        with torch.no_grad():
            if save_compute and prompts[0] != "":
                comb_out, _, _ = model.unet_forward(
                    xt_inp.expand(2, -1, -1, -1) if hasattr(model.model, 'unet') else xt_inp.expand(2, -1, -1),
                    timestep=t,
                    encoder_hidden_states=torch.cat([uncond_embeddings_hidden_states, text_embeddings_hidden_states
                                                     ], dim=0)
                    if uncond_embeddings_hidden_states is not None else None,
                    class_labels=torch.cat([uncond_embeddings_class_lables, text_embeddings_class_labels], dim=0)
                    if uncond_embeddings_class_lables is not None else None,
                    encoder_attention_mask=torch.cat([uncond_boolean_prompt_mask, text_embeddings_boolean_prompt_mask
                                                      ], dim=0)
                    if uncond_boolean_prompt_mask is not None else None,
                )
                out, cond_out = comb_out.sample.chunk(2, dim=0)
            else:
                out = model.unet_forward(xt_inp, timestep=t,
                                         encoder_hidden_states=uncond_embeddings_hidden_states,
                                         class_labels=uncond_embeddings_class_lables,
                                         encoder_attention_mask=uncond_boolean_prompt_mask)[0].sample
                if len(prompts) > 1 or prompts[0] != "":
                    cond_out = model.unet_forward(
                        xt_inp,
                        timestep=t,
                        encoder_hidden_states=text_embeddings_hidden_states,
                        class_labels=text_embeddings_class_labels,
                        encoder_attention_mask=text_embeddings_boolean_prompt_mask)[0].sample

        if len(prompts) > 1 or prompts[0] != "":
            # # classifier free guidance
            noise_pred = out + (cfg_scales[0] * (cond_out - out)).sum(axis=0).unsqueeze(0)
        else:
            noise_pred = out

        # xtm1 =  xts[idx+1][None]
        xtm1 = xts[idx][None]
        z, xtm1, extra = model.get_zs_from_xts(xt, xtm1, noise_pred, t,
                                               eta=etas[idx], numerical_fix=numerical_fix,
                                               first_order=first_order)
        zs[idx] = z
        # print(f"Fix Xt-1 distance -  NORM:{torch.norm(xts[idx] - xtm1):.4g}, MSE:{((xts[idx] - xtm1)**2).mean():.4g}")
        xts[idx] = xtm1
        extra_info[idx] = extra

    if zs is not None:
        # zs[-1] = torch.zeros_like(zs[-1])
        zs[0] = torch.zeros_like(zs[0])
        # zs_cycle[0] = torch.zeros_like(zs[0])

    del app_op.iterables[0]
    return xt, zs, xts, extra_info


def inversion_reverse_process(model: PipelineWrapper,
                              xT: torch.Tensor,
                              tstart: torch.Tensor,
                              etas: float = 0,
                              prompts: List[str] = [""],
                              neg_prompts: List[str] = [""],
                              cfg_scales: Optional[List[float]] = None,
                              zs: Optional[List[torch.Tensor]] = None,
                              duration: Optional[float] = None,
                              first_order: bool = False,
                              extra_info: Optional[List] = None,
                              save_compute: bool = True,
                              progress=gr.Progress()) -> Tuple[torch.Tensor, torch.Tensor]:

    text_embeddings_hidden_states, text_embeddings_class_labels, \
        text_embeddings_boolean_prompt_mask = model.encode_text(prompts)
    uncond_embeddings_hidden_states, uncond_embeddings_class_lables, \
        uncond_boolean_prompt_mask = model.encode_text(neg_prompts,
                                                       negative=True,
                                                       save_compute=save_compute,
                                                       cond_length=text_embeddings_class_labels.shape[1]
                                                       if text_embeddings_class_labels is not None else None)

    xt = xT[tstart.max()].unsqueeze(0)

    if etas is None:
        etas = 0
    if type(etas) in [int, float]:
        etas = [etas]*model.model.scheduler.num_inference_steps
    assert len(etas) == model.model.scheduler.num_inference_steps
    timesteps = model.model.scheduler.timesteps.to(model.device)

    op = tqdm(timesteps[-zs.shape[0]:], desc="Editing")
    if timesteps[0].dtype == torch.int64:
        t_to_idx = {int(v): k for k, v in enumerate(timesteps[-zs.shape[0]:])}
    elif timesteps[0].dtype == torch.float32:
        t_to_idx = {float(v): k for k, v in enumerate(timesteps[-zs.shape[0]:])}
    model.setup_extra_inputs(xt, extra_info=extra_info, init_timestep=timesteps[-zs.shape[0]],
                             audio_end_in_s=duration, save_compute=save_compute)
    app_op = progress.tqdm(timesteps[-zs.shape[0]:], desc="Editing")
    for it, (t, _) in enumerate(zip(op, app_op)):
        idx = model.model.scheduler.num_inference_steps - t_to_idx[
            int(t) if timesteps[0].dtype == torch.int64 else float(t)] - \
                (model.model.scheduler.num_inference_steps - zs.shape[0] + 1)

        xt_inp = model.model.scheduler.scale_model_input(xt, t)

        # # Unconditional embedding
        with torch.no_grad():
            # print(f'xt_inp.shape: {xt_inp.shape}')
            # print(f't.shape: {t.shape}')
            # print(f'uncond_embeddings_hidden_states.shape: {uncond_embeddings_hidden_states.shape}')
            # print(f'uncond_embeddings_class_lables.shape: {uncond_embeddings_class_lables.shape}')
            # print(f'uncond_boolean_prompt_mask.shape: {uncond_boolean_prompt_mask.shape}')
            # print(f'text_embeddings_hidden_states.shape: {text_embeddings_hidden_states.shape}')
            # print(f'text_embeddings_class_labels.shape: {text_embeddings_class_labels.shape}')
            # print(f'text_embeddings_boolean_prompt_mask.shape: {text_embeddings_boolean_prompt_mask.shape}')

            if save_compute:
                comb_out, _, _ = model.unet_forward(
                    xt_inp.expand(2, -1, -1, -1) if hasattr(model.model, 'unet') else xt_inp.expand(2, -1, -1),
                    timestep=t,
                    encoder_hidden_states=torch.cat([uncond_embeddings_hidden_states, text_embeddings_hidden_states
                                                     ], dim=0)
                    if uncond_embeddings_hidden_states is not None else None,
                    class_labels=torch.cat([uncond_embeddings_class_lables, text_embeddings_class_labels], dim=0)
                    if uncond_embeddings_class_lables is not None else None,
                    encoder_attention_mask=torch.cat([uncond_boolean_prompt_mask, text_embeddings_boolean_prompt_mask
                                                      ], dim=0)
                    if uncond_boolean_prompt_mask is not None else None,
                )
                uncond_out, cond_out = comb_out.sample.chunk(2, dim=0)
            else:
                uncond_out = model.unet_forward(
                    xt_inp, timestep=t,
                    encoder_hidden_states=uncond_embeddings_hidden_states,
                    class_labels=uncond_embeddings_class_lables,
                    encoder_attention_mask=uncond_boolean_prompt_mask,
                    )[0].sample

                # Conditional embedding
                cond_out = model.unet_forward(
                    xt_inp,
                    timestep=t,
                    encoder_hidden_states=text_embeddings_hidden_states,
                    class_labels=text_embeddings_class_labels,
                    encoder_attention_mask=text_embeddings_boolean_prompt_mask,
                    )[0].sample

        z = zs[idx] if zs is not None else None
        z = z.unsqueeze(0)
        # classifier free guidance
        noise_pred = uncond_out + (cfg_scales[0] * (cond_out - uncond_out)).sum(axis=0).unsqueeze(0)

        # 2. compute less noisy image and set x_t -> x_t-1
        xt = model.reverse_step_with_custom_noise(noise_pred, t, xt, variance_noise=z,
                                                  eta=etas[idx], first_order=first_order)

    del app_op.iterables[0]
    return xt, zs