File size: 12,356 Bytes
801501a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np
import torch
import torch.nn.functional as F
from transformers import BertModel, BertTokenizer

from salad.model_components.lstm import LSTM
from salad.models.phase1 import Phase1Model
from salad.utils import imageutil, nputil, visutil
from salad.utils.spaghetti_util import (clip_eigenvalues,
                                        generate_zc_from_sj_gaus,
                                        get_mesh_from_spaghetti, load_mesher,
                                        load_spaghetti, project_eigenvectors)
from salad.utils.train_util import get_dropout_mask
from salad.data.dataset import LangSALADDataset


class LangPhase1Model(Phase1Model):
    def __init__(self, network, variance_schedule, **kwargs):
        super().__init__(network, variance_schedule, **kwargs)
        self.tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
        if self.hparams.get("use_lstm"):
            self.bertmodel = LSTM(
                text_dim=768, embedding_dim=768, vocab_size=30522, padding_idx=0
            )
        else:
            self.bertmodel = BertModel.from_pretrained("bert-base-uncased")
        if self.hparams.get("text_encoder_freeze"):
            for p in self.bertmodel.parameters():
                p.requires_grad_(False)

    def forward(self, x, text):
        """
        Input:
            x: [B,G,16]
            text: list of length [B]
        """
        B, G = x.shape[:2]
        text = self.random_mask_text(text)
        lang_emb = self.text_to_embedding(text)
        return self.get_loss(x, lang_emb)

    def tokenizing(self, text):
        tokenized = self.tokenizer(
            text, return_tensors="pt", padding=True, truncation=True
        ).to(self.device)
        return tokenized

    def text_to_embedding(self, text):
        """
        text: list of length [B]
        return [B,768]
        """
        tokenized = self.tokenizing(text)
        if self.hparams.get("use_lstm"):
            lang_emb, _ = self.bertmodel(tokenized.input_ids)
        else:
            if self.hparams.get("text_encoder_return_seq"):
                lang_emb = self.bertmodel(**tokenized).last_hidden_state
            else:
                lang_emb = self.bertmodel(**tokenized).pooler_output
        if lang_emb.ndim == 2:
            lang_emb = lang_emb.unsqueeze(1)
        return lang_emb

    def random_mask_text(self, text):
        text = list(text)
        B = len(text)
        if self.hparams.get("classifier_free_guidance"):
            random_dp_mask = get_dropout_mask(
                B, self.hparams.conditioning_dropout_prob, self.device
            )
            for i in range(B):
                if random_dp_mask[i] == 0:
                    text[i] = ""
        return text

    def get_loss(self, x0, cond, t=None, noisy_in=False, beta_in=None, e_rand_in=None):
        B, G, D = x0.shape

        if not noisy_in:
            if t is None:
                t = self.var_sched.uniform_sample_t(B)
            x_noisy, beta, e_rand = self.add_noise(x0, t)
        else:
            x_noisy = x0
            beta = beta_in
            e_rand = e_rand_in

        e_theta = self.net(x_noisy, beta, cond)
        loss = F.mse_loss(e_theta.flatten(), e_rand.flatten(), reduction="mean")
        return loss

    def step(self, batch, stage: str):
        x, text = batch
        loss = self(x, text)
        self.log(f"{stage}/loss", loss, on_step=stage == "train", prog_bar=True)
        return loss

    @torch.no_grad()
    def sample(
        self,
        num_samples_or_text,
        return_traj=False,
        return_cond=False,
        classifier_free_guidance=True,
        free_guidance_weight=2.0,
    ):
        if isinstance(num_samples_or_text, str):
            num_samples_or_text = [num_samples_or_text]
        if isinstance(num_samples_or_text, int):
            batch_size = num_samples_or_text
            ds = self._build_dataset("val")
            texts = [ds[i][1] for i in range(batch_size)]
        elif isinstance(num_samples_or_text, list):
            texts = num_samples_or_text
            batch_size = len(num_samples_or_text)
        if self.hparams.get("use_zc"):
            x_T = torch.randn([batch_size, 16, 512]).to(self.device)
        else:
            x_T = torch.randn([batch_size, 16, 16]).to(self.device)
        G = x_T.shape[1]
        lang_emb = self.text_to_embedding(texts)

        if classifier_free_guidance:
            null_texts = ["" for _ in range(batch_size)]
            null_lang_emb = self.text_to_embedding(null_texts)

        traj = {self.var_sched.num_steps: x_T}
        for t in range(self.var_sched.num_steps, 0, -1):
            z = torch.randn_like(x_T) if t > 1 else torch.zeros_like(x_T)
            alpha = self.var_sched.alphas[t]
            alpha_bar = self.var_sched.alpha_bars[t]
            sigma = self.var_sched.get_sigmas(t, flexibility=0)

            c0 = 1.0 / torch.sqrt(alpha)
            c1 = (1 - alpha) / torch.sqrt(1 - alpha_bar)

            x_t = traj[t]

            beta = self.var_sched.betas[[t] * batch_size]
            e_theta = self.net(x_t, beta=beta, context=lang_emb)

            if classifier_free_guidance:
                null_e_theta = self.net(x_t, beta=beta, context=null_lang_emb)
                w = free_guidance_weight
                e_theta = (1 + w) * e_theta - w * null_e_theta

            x_next = c0 * (x_t - c1 * e_theta) + sigma * z
            traj[t - 1] = x_next.detach()

            traj[t] = traj[t].cpu()

            if not return_traj:
                del traj[t]

        if return_traj:
            if return_cond:
                return traj, lang_emb
            return traj
        else:
            if return_cond:
                return traj[0], lang_emb
            return traj[0]

    def sampling_gaussians(
        self,
        num_samples_or_text,
        classifier_free_guidance=True,
        free_guidance_weight=2.0,
        return_cond=False,
    ):
        gaus = self.sample(
            num_samples_or_text,
            classifier_free_guidance=classifier_free_guidance,
            free_guidance_weight=free_guidance_weight,
            return_cond=return_cond,
        )
        if isinstance(gaus, tuple):
            text = gaus[1]
            gaus = gaus[0]
        # gaus = reflect_and_concat_gmms(raw_gaus)
        if self.hparams.get("global_normalization"):
            if not hasattr(self, "data_val"):
                self._build_dataset("val")
            if self.hparams.get("global_normalization") == "partial":
                gaus = self.data_val.unnormalize_global_static(gaus, slice(12, None))
            elif self.hparams.get("global_normalization") == "all":
                gaus = self.data_val.unnormalize_global_static(gaus, slice(None))

        gaus = project_eigenvectors(clip_eigenvalues(gaus))
        if return_cond:
            return gaus, text
        return gaus

    def _build_dataset(self, stage):
        if hasattr(self, f"data_{stage}"):
            return getattr(self, f"data_{stage}")

        ds_class = (
            LangSALADDataset
        )
        if stage == "train":
            ds = ds_class(**self.hparams.dataset_kwargs)
        else:
            dataset_kwargs = self.hparams.dataset_kwargs.copy()
            dataset_kwargs["repeat"] = 1
            ds = ds_class(**dataset_kwargs)
        setattr(self, f"data_{stage}", ds)
        return ds

    def validation_zc(self):
        vis_num_shapes = 4
        vis_zcs = []
        vis_texts = []
        ds = self._build_dataset("val")
        for i in [0, 1, 2, 3]:
            zcs, text = ds[i]
            vis_zcs.append(zcs)
            vis_texts.append(text)
        vis_zcs = torch.stack(vis_zcs, 0)
        ldm_zcs = self.sample(vis_texts)

        if not hasattr(self, "spaghetti"):
            self.spaghetti = load_spaghetti(self.device, self.hparams.spaghetti_tag)
        spaghetti = self.spaghetti

        if not hasattr(self, "mesher"):
            self.mesher = load_mesher(self.device)
        mesher = self.mesher

        wandb_logger = self.get_wandb_logger()
        images = []
        for i in range(vis_num_shapes):
            try:
                v, f = get_mesh_from_spaghetti(spaghetti, mesher, vis_zcs[i], res=128)
                gt_img = visutil.render_mesh(v, f, resolution=(256, 256))
            except:
                pass
            try:
                v, f = get_mesh_from_spaghetti(spaghetti, mesher, ldm_zcs[i], res=128)
                pred_img = visutil.render_mesh(v, f, resolution=(256, 256))
            except:
                pass

            img = imageutil.merge_images([gt_img, pred_img])
            img = imageutil.draw_text(
                img,
                f"Left: GT | Right: Pred \n{vis_texts[i]}",
                font_size=14,
                max_seq_length=50,
            )
            images.append([img])

        images = imageutil.merge_images(images)
        wandb_logger.log_image("vis", [images])

    def validation(self):
        if self.hparams.get("use_zc"):
            self.validation_zc()
            return

        vis_num_shapes = 4
        vis_gaus = []
        vis_texts = []
        ds = self._build_dataset("val")
        vis_indices = [18453, 13036, 13204, 48244]
        for i in vis_indices:
            gaus, text = ds[i]
            vis_gaus.append(gaus)
            vis_texts.append(text)

        vis_gaus = torch.stack(vis_gaus, 0)
        if self.hparams.get("global_normalization"):
            if self.hparams.get("global_normalization") == "partial":
                vis_gaus = self.data_val.unnormalize_global_static(
                    vis_gaus, slice(12, None)
                )
            elif self.hparams.get("global_normalization") == "all":
                vis_gaus = self.dataval.unnormalize_global_static(vis_gaus, slice(None))

        # vis_gaus = reflect_and_concat_gmms(vis_gaus)
        pred_gaus = self.sampling_gaussians(vis_texts)

        if not hasattr(self, "spaghetti"):
            self.spaghetti = load_spaghetti(self.device, self.hparams.spaghetti_tag)
        spaghetti = self.spaghetti

        if not hasattr(self, "mesher"):
            self.mesher = load_mesher(self.device)
        mesher = self.mesher

        """ get intrinsics """
        # TODO change the ckpt path.
        if not hasattr(self, "phase2_model"):
            phase2_ckpt = "/home/juil/pvddir/results/phase2/augment_final_0214/0214_202607/checkpoints/epoch=4999-val_loss=0.0000.ckpt"
            self.phase2_model = SpaghettiConditionSALDM.load_from_checkpoint(
                phase2_ckpt, strict=False
            ).to(self.device)
            self.phase2_model.eval()
            for p in self.phase2_model.parameters():
                p.requires_grad_(False)

        phase2_model = self.phase2_model

        gt_sj = phase2_model.sample(vis_gaus)
        pred_sj = phase2_model.sample(pred_gaus)

        gt_zcs = generate_zc_from_sj_gaus(spaghetti, gt_sj, vis_gaus)
        pred_zcs = generate_zc_from_sj_gaus(spaghetti, pred_sj, pred_gaus)

        wandb_logger = self.get_wandb_logger()
        images = []
        for i in range(vis_num_shapes):
            gt_img = visutil.render_gaussians(vis_gaus[i], resolution=(256, 256))
            try:
                v, f = get_mesh_from_spaghetti(spaghetti, mesher, gt_zcs[i], res=128)
                gt_mesh_img = visutil.render_mesh(v, f, resolution=(256, 256))
                gt_img = imageutil.merge_images([gt_img, gt_mesh_img])
            except:
                pass

            pred_img = visutil.render_gaussians(pred_gaus[i], resolution=(256, 256))
            try:
                v, f = get_mesh_from_spaghetti(spaghetti, mesher, pred_zcs[i], res=128)
                pred_mesh_img = visutil.render_mesh(v, f, resolution=(256, 256))
                pred_img = imageutil.merge_images([pred_img, pred_mesh_img])
            except:
                pass

            img = imageutil.merge_images([gt_img, pred_img])
            img = imageutil.draw_text(
                img,
                f"Left: GT | Right: Pred \n{vis_texts[i]}",
                font_size=14,
                max_seq_length=50,
            )
            images.append([img])

        images = imageutil.merge_images(images)
        wandb_logger.log_image("vis", [images])