File size: 13,017 Bytes
0a63786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
from typing import List, Union, Tuple
from tqdm import tqdm
from .inference import Inference

class InferenceDAMO(Inference):
    @torch.no_grad()
    def __call__(
        self,
        latent: torch.Tensor,
        context: torch.Tensor,
        uncond_context: torch.Tensor=None,
        start_time: int = 0,
        null_embedding: List[torch.Tensor]=None,
    ):
        all_latent = []
        all_pred = [] # x0_hat
        do_classifier_free_guidance = self.guidance_scale > 1 and ((uncond_context is not None) or (null_embedding is not None))
        for i, t in enumerate(tqdm(self.scheduler.timesteps[start_time:])):
            t = int(t)
            if do_classifier_free_guidance:
                latent_input = torch.cat([latent, latent], dim=0)
                if null_embedding is not None:
                    context_input = torch.cat([null_embedding[i], context], dim=0)
                else:
                    context_input = torch.cat([uncond_context, context], dim=0)
            else:
                latent_input = latent
                context_input = context
            noise_pred = self.unet(
                latent_input,
                torch.full((len(latent_input),), t, device=latent_input.device, dtype=torch.long), 
                context_input,
            )

            if do_classifier_free_guidance:
                noise_pred_uncond, noise_pred_cond = noise_pred.chunk(2, dim=0)
                noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_cond - noise_pred_uncond)

            pred_samples = self.scheduler.step(noise_pred, t, latent)
            latent = pred_samples.prev_sample
            pred = pred_samples.pred_original_sample
            all_latent.append(latent.detach())
            all_pred.append(pred.detach())

        return {
            'latent': latent,
            'all_latent': all_latent,
            'all_pred': all_pred
        }

class InferenceDAMO_PTP(Inference):
    def infer_old_context(self, latent, context, t, uncond_context=None):
        do_classifier_free_guidance = self.guidance_scale > 1 and (uncond_context is not None)

        if do_classifier_free_guidance:
            latent_input = torch.cat([latent, latent], dim=0)
            context_input = torch.cat([uncond_context, context], dim=0)
        else:
            latent_input = latent
            context_input = context

        noise_pred = self.unet(
            latent_input,
            torch.full((len(latent_input),), t, device=latent_input.device, dtype=torch.long), 
            context_input,
        )

        if do_classifier_free_guidance:
            noise_pred_uncond, noise_pred_cond = noise_pred.chunk(2, dim=0)
            noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_cond - noise_pred_uncond)

        pred_samples = self.scheduler.step(noise_pred, t, latent)
        latent = pred_samples.prev_sample
        pred = pred_samples.pred_original_sample
        return latent, pred

    def infer_new_context(self, latent, context, t, uncond_context=None):
        do_classifier_free_guidance = self.guidance_scale > 1 and (uncond_context is not None)

        if do_classifier_free_guidance:
            latent_input = torch.cat([latent, latent], dim=0)
            if isinstance(context, (list, tuple)):
                context_input = (
                    torch.cat([uncond_context, context[0]], dim=0),
                    torch.cat([uncond_context, context[1]], dim=0),
                )
            else:
                context_input = torch.cat([uncond_context, context], dim=0)
        else:
            latent_input = latent
            context_input = context

        noise_pred = self.unet(
            latent_input,
            torch.full((len(latent_input),), t, device=latent_input.device, dtype=torch.long), 
            context_input,
        )

        if do_classifier_free_guidance:
            noise_pred_uncond, noise_pred_cond = noise_pred.chunk(2, dim=0)
            noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_cond - noise_pred_uncond)

        pred_samples = self.scheduler.step(noise_pred, t, latent)
        latent = pred_samples.prev_sample
        pred = pred_samples.pred_original_sample
        return latent, pred

    @torch.no_grad()
    def __call__(
        self,
        latent: torch.Tensor,
        context: torch.Tensor, # used when > ca_end_time
        old_context: torch.Tensor=None, # used when < sa_end_time
        old_to_new_context: Union[Tuple, List]=None, # used when sa_end_time < t < ca_end_time
        uncond_context: torch.Tensor=None,
        sa_end_time: float=0.3,
        ca_end_time: float=0.8,
        start_time: int = 0,
    ):
        assert sa_end_time < ca_end_time, f"sa_end_time must be less than ca_end_time, got {sa_end_time} and {ca_end_time} respectively"
        all_latent = []
        all_pred = []
        all_latent_old = []
        all_pred_old = []
        old_latent = latent.clone()
        new_latent = latent.clone()
        for i, t in enumerate(tqdm(self.scheduler.timesteps[start_time:])):
            t = int(t)
            old_latent_next_t, pred_old = self.infer_old_context(old_latent, old_context, t, uncond_context)
            if i < sa_end_time * self.num_ddim_steps:
                new_latent_next_t, pred_new = old_latent_next_t, pred_old
            elif sa_end_time * self.num_ddim_steps <= i < ca_end_time * self.num_ddim_steps:
                new_latent_next_t, pred_new = self.infer_new_context(
                    new_latent, old_to_new_context, t, uncond_context
                )
            else:
                new_latent_next_t, pred_new = self.infer_new_context(
                    new_latent, context, t, uncond_context
                )

            old_latent = old_latent_next_t
            new_latent = new_latent_next_t

            all_latent.append(new_latent_next_t.detach())
            all_pred.append(pred_new.detach())
            all_latent_old.append(old_latent_next_t.detach())
            all_pred_old.append(pred_old.detach())

        return {
            'latent': new_latent,
            'latent_old': old_latent,
            'all_latent': all_latent,
            'all_pred': all_pred,
            'all_latent_old': all_latent_old,
            'all_pred_old': all_pred_old,
        }

class InferenceDAMO_PTP_v2(Inference):
    def set_ptp_in_xattn_layers(self, prompt_to_prompt: bool, num_frames=1):
        for m in self.unet.modules():
            if m.__class__.__name__ == 'CrossAttention':
                m.ptp_sa_replace = prompt_to_prompt
                m.num_frames = num_frames

    def infer_both_with_sa_replace(self, old_latent, new_latent, old_context, new_context, t, uncond_context=None):
        do_classifier_free_guidance = self.guidance_scale > 1 and (uncond_context is not None)

        if do_classifier_free_guidance:
            latent_input = torch.cat([old_latent, new_latent, old_latent, new_latent], dim=0)
            context_input = torch.cat([uncond_context, uncond_context, old_context, new_context], dim=0)
        else:
            latent_input = torch.cat([old_latent, new_latent], dim=0)
            context_input = torch.cat([old_context, new_context], dim=0)

        noise_pred = self.unet(
            latent_input,
            torch.full((len(latent_input),), t, device=latent_input.device, dtype=torch.long), 
            context_input,
        )

        if do_classifier_free_guidance:
            noise_pred_uncond, noise_pred_cond = noise_pred.chunk(2, dim=0)
            noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_cond - noise_pred_uncond)

        noise_pred_old, noise_pred_new = noise_pred.chunk(2, dim=0)
        pred_samples_old = self.scheduler.step(noise_pred_old, t, old_latent)
        pred_samples_new = self.scheduler.step(noise_pred_new, t, new_latent)

        old_latent = pred_samples_old.prev_sample
        new_latent = pred_samples_new.prev_sample
        old_pred = pred_samples_old.pred_original_sample
        new_pred = pred_samples_new.pred_original_sample

        return old_latent, new_latent, old_pred, new_pred

    def infer_old_context(self, latent, context, t, uncond_context=None):
        do_classifier_free_guidance = self.guidance_scale > 1 and (uncond_context is not None)

        if do_classifier_free_guidance:
            latent_input = torch.cat([latent, latent], dim=0)
            context_input = torch.cat([uncond_context, context], dim=0)
        else:
            latent_input = latent
            context_input = context

        noise_pred = self.unet(
            latent_input,
            torch.full((len(latent_input),), t, device=latent_input.device, dtype=torch.long), 
            context_input,
        )

        if do_classifier_free_guidance:
            noise_pred_uncond, noise_pred_cond = noise_pred.chunk(2, dim=0)
            noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_cond - noise_pred_uncond)

        pred_samples = self.scheduler.step(noise_pred, t, latent)
        latent = pred_samples.prev_sample
        pred = pred_samples.pred_original_sample
        return latent, pred

    def infer_new_context(self, latent, context, t, uncond_context=None):
        do_classifier_free_guidance = self.guidance_scale > 1 and (uncond_context is not None)

        if do_classifier_free_guidance:
            latent_input = torch.cat([latent, latent], dim=0)
            if isinstance(context, (list, tuple)):
                context_input = (
                    torch.cat([uncond_context, context[0]], dim=0),
                    torch.cat([uncond_context, context[1]], dim=0),
                )
            else:
                context_input = torch.cat([uncond_context, context], dim=0)
        else:
            latent_input = latent
            context_input = context

        noise_pred = self.unet(
            latent_input,
            torch.full((len(latent_input),), t, device=latent_input.device, dtype=torch.long), 
            context_input,
        )

        if do_classifier_free_guidance:
            noise_pred_uncond, noise_pred_cond = noise_pred.chunk(2, dim=0)
            noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_cond - noise_pred_uncond)

        pred_samples = self.scheduler.step(noise_pred, t, latent)
        latent = pred_samples.prev_sample
        pred = pred_samples.pred_original_sample
        return latent, pred

    @torch.no_grad()
    def __call__(
        self,
        latent: torch.Tensor,
        context: torch.Tensor, # used when > ca_end_time
        old_context: torch.Tensor=None, # used when < sa_end_time
        old_to_new_context: Union[Tuple, List]=None, # used when sa_end_time < t < ca_end_time
        uncond_context: torch.Tensor=None,
        sa_end_time: float=0.3,
        ca_end_time: float=0.8,
        start_time: int = 0,
    ):
        assert sa_end_time < ca_end_time, f"sa_end_time must be less than ca_end_time, got {sa_end_time} and {ca_end_time} respectively"
        all_latent = []
        all_pred = []
        all_latent_old = []
        all_pred_old = []
        old_latent = latent.clone()
        new_latent = latent.clone()
        for i, t in enumerate(tqdm(self.scheduler.timesteps[start_time:])):
            t = int(t)
            if i < sa_end_time * self.num_ddim_steps:
                self.set_ptp_in_xattn_layers(True, num_frames=latent.shape[2])
                old_latent_next_t, new_latent_next_t, pred_old, pred_new = self.infer_both_with_sa_replace(
                    old_latent, new_latent, old_context, context, t, uncond_context
                )
            elif sa_end_time * self.num_ddim_steps <= i < ca_end_time * self.num_ddim_steps:
                self.set_ptp_in_xattn_layers(False)
                old_latent_next_t, pred_old = self.infer_old_context(old_latent, old_context, t, uncond_context)
                new_latent_next_t, pred_new = self.infer_new_context(
                    new_latent, old_to_new_context, t, uncond_context
                )
            else:
                self.set_ptp_in_xattn_layers(False)
                old_latent_next_t, pred_old = self.infer_old_context(old_latent, old_context, t, uncond_context)
                new_latent_next_t, pred_new = self.infer_new_context(
                    new_latent, context, t, uncond_context
                )

            old_latent = old_latent_next_t
            new_latent = new_latent_next_t

            all_latent.append(new_latent_next_t.detach())
            all_pred.append(pred_new.detach())
            all_latent_old.append(old_latent_next_t.detach())
            all_pred_old.append(pred_old.detach())

        return {
            'latent': new_latent,
            'latent_old': old_latent,
            'all_latent': all_latent,
            'all_pred': all_pred,
            'all_latent_old': all_latent_old,
            'all_pred_old': all_pred_old,
        }