File size: 8,617 Bytes
e34aada
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#! /usr/bin/python
# -*- encoding: utf-8 -*-

import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.commons.hparams import hparams
import numpy as np
import math


class LossScale(nn.Module):
    def __init__(self, init_w=10.0, init_b=-5.0):
        super(LossScale, self).__init__()
        
        self.wC = nn.Parameter(torch.tensor(init_w))
        self.bC = nn.Parameter(torch.tensor(init_b))

class CLIPLoss(nn.Module):
    def __init__(self,):
        super().__init__()

    def forward(self, audio_features, motion_features, logit_scale, clip_mask=None):
        logits_per_audio = logit_scale * audio_features @ motion_features.T # [b,c]
        logits_per_motion = logit_scale * motion_features @ audio_features.T # [b,c]
        if clip_mask is not None:
            logits_per_audio += clip_mask        
            logits_per_motion += clip_mask
        labels = torch.arange(logits_per_motion.shape[0]).to(logits_per_motion.device)
        motion_loss = F.cross_entropy(logits_per_motion, labels)
        audio_loss = F.cross_entropy(logits_per_audio, labels)
        clip_loss = (motion_loss + audio_loss) / 2
        ret = {
            "audio_loss": audio_loss,
            "motion_loss": motion_loss,
            "clip_loss": clip_loss
        }
        return ret

def accuracy(output, target, topk=(1,)):
    """Computes the precision@k for the specified values of k"""
    maxk = max(topk)
    batch_size = target.size(0)

    _, pred = output.topk(maxk, 1, True, True)
    pred = pred.t()
    correct = pred.eq(target.reshape(1, -1).expand_as(pred))

    res = []
    for k in topk:
        correct_k = correct[:k].reshape(-1).float()
        res.append(correct_k)
    return res


class LossScale(nn.Module):
    def __init__(self, init_w=10.0, init_b=-5.0):
        super(LossScale, self).__init__()
        
        self.wC = nn.Parameter(torch.tensor(init_w))
        self.bC = nn.Parameter(torch.tensor(init_b))


class SyncNetModel(nn.Module):
    def __init__(self, auddim=1024, lipdim=20*3, nOut = 1024, stride=1):
        super(SyncNetModel, self).__init__()
        self.loss_scale = LossScale()
        self.criterion = torch.nn.CrossEntropyLoss(reduction='none')
        self.clip_loss_fn = CLIPLoss()
        self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
        self.logit_scale_max = math.log(1. / 0.01)

        self.netcnnaud = nn.Sequential(
            nn.Conv1d(auddim, 512, kernel_size=3, stride=1, padding=1),
            nn.BatchNorm1d(512),
            nn.ReLU(inplace=True),
            nn.MaxPool1d(kernel_size=3, stride=1),

            nn.Conv1d(512, 512, kernel_size=3, stride=1, padding=1),
            nn.BatchNorm1d(512),
            nn.ReLU(inplace=True),
            nn.MaxPool1d(kernel_size=3, stride=1),

            nn.Conv1d(512, 512, kernel_size=3, padding=1),
            nn.BatchNorm1d(512),
            nn.ReLU(inplace=True),

            nn.Conv1d(512, 256, kernel_size=3, padding=1),
            nn.BatchNorm1d(256),
            nn.ReLU(inplace=True),
            nn.MaxPool1d(kernel_size=3, stride=1),

            nn.Conv1d(256, 256, kernel_size=3, padding=1),
            nn.BatchNorm1d(256),
            nn.ReLU(inplace=True),
            
            nn.Conv1d(256, 512, kernel_size=3, padding=1, stride=(stride)),
            nn.BatchNorm1d(512),
            nn.ReLU(),
            nn.MaxPool1d(kernel_size=3, stride=1),

            nn.Conv1d(512, 512, kernel_size=2),
            nn.BatchNorm1d(512),
            nn.ReLU(),

            nn.Conv1d(512, 512, kernel_size=1),
            nn.BatchNorm1d(512),
            nn.ReLU(),
            nn.Conv1d(512, nOut, kernel_size=1),
        )

        self.netcnnlip = nn.Sequential(
            nn.Conv1d(lipdim, 512, kernel_size=3, stride=1, padding=1),
            nn.BatchNorm1d(512),
            nn.ReLU(inplace=True),

            nn.Conv1d(512, 512, kernel_size=3, stride=1, padding=1),
            nn.BatchNorm1d(512),
            nn.ReLU(inplace=True),
            nn.MaxPool1d(kernel_size=3, stride=1),

            nn.Conv1d(512, 512, kernel_size=3, padding=1),
            nn.BatchNorm1d(512),
            nn.ReLU(inplace=True),

            nn.Conv1d(512, 256, kernel_size=3, padding=1),
            nn.BatchNorm1d(256),
            nn.ReLU(inplace=True),

            nn.Conv1d(256, 256, kernel_size=3, padding=1),
            nn.BatchNorm1d(256),
            nn.ReLU(inplace=True),
            
            nn.Conv1d(256, 512, kernel_size=(3), padding=1, stride=(stride)),
            nn.BatchNorm1d(512),
            nn.ReLU(),
            nn.MaxPool1d(kernel_size=3, stride=1),

            nn.Conv1d(512, 512, kernel_size=1),
            nn.BatchNorm1d(512),
            nn.ReLU(),
            nn.Conv1d(512, nOut, kernel_size=1),
        )

    def _forward_aud(self, x):
        # bct
        out = self.netcnnaud(x); # N x ch x 24 x M
        return out

    def _forward_vid(self, x):
        # bct
        out = self.netcnnlip(x); 
        return out
    
    def forward(self, hubert, mouth_lm): 
        # hubert := (B, T=100, C=1024)
        # mouth_lm3d := (B, T=50, C=60)
        # out: [B, T=50, C=1024]
        hubert = hubert.transpose(1,2)
        mouth_lm = mouth_lm.transpose(1,2)
        mouth_embedding = self._forward_vid(mouth_lm)
        audio_embedding = self._forward_aud(hubert)
        audio_embedding = audio_embedding.transpose(1,2)
        mouth_embedding = mouth_embedding.transpose(1,2)
        if hparams.get('normalize_embedding', False): # similar loss, no effects
            audio_embedding = F.normalize(audio_embedding, p=2, dim=-1)
            mouth_embedding = F.normalize(mouth_embedding, p=2, dim=-1)
        return audio_embedding.squeeze(1), mouth_embedding.squeeze(1)
    
    def _compute_sync_loss_batch(self, out_a, out_v, ymask=None):
        b, t, c = out_v.shape
        label = torch.arange(t).to(out_v.device)[None].repeat(b, 1)
        output = F.cosine_similarity(
            out_v[:, :, None], out_a[:, None, :], dim=-1) * self.loss_scale.wC + self.loss_scale.bC
        loss = self.criterion(output, label).mean()
        return loss
    
    def _compute_sync_loss(self, out_a, out_v, ymask=None):
         # b,t,c
        b, t, c = out_v.shape
        out_v = out_v.transpose(1,2)
        out_a = out_a.transpose(1,2)

        label = torch.arange(t).to(out_v.device)

        nloss = 0
        prec1 = 0
        if ymask is not None:
            total_num = ymask.sum()
        else:
            total_num = b*t
        for i in range(0, b):
            ft_v    = out_v[[i],:,:].transpose(2,0)
            ft_a    = out_a[[i],:,:].transpose(2,0)
            output  = F.cosine_similarity(ft_v, ft_a.transpose(0,2)) * self.loss_scale.wC + self.loss_scale.bC
            loss = self.criterion(output, label)
            if ymask is not None:
                loss = loss * ymask[i]
            nloss += loss.sum()
        nloss = nloss / total_num
        return nloss
    
    def compute_sync_loss(self,out_a, out_v, ymask=None, batch_mode=False):
        if batch_mode:
            return self._compute_sync_loss_batch(out_a, out_v)
        else:
            return self._compute_sync_loss(out_a, out_v)

    def compute_sync_score_for_infer(self, out_a, out_v, ymask=None):
         # b,t,c
        b, t, c = out_v.shape
        out_v = out_v.transpose(1,2)
        out_a = out_a.transpose(1,2)

        label = torch.arange(t).to(out_v.device)

        nloss = 0
        prec1 = 0
        if ymask is not None:
            total_num = ymask.sum()
        else:
            total_num = b*t
        for i in range(0, b):
            ft_v    = out_v[[i],:,:].transpose(2,0)
            ft_a    = out_a[[i],:,:].transpose(2,0)
            output  = F.cosine_similarity(ft_v, ft_a.transpose(0,2)) * self.loss_scale.wC + self.loss_scale.bC
            loss = self.criterion(output, label)
            if ymask is not None:
                loss = loss * ymask[i]
            nloss += loss.sum()
        nloss = nloss / total_num
        return nloss
        
    def cal_clip_loss(self, audio_embedding, mouth_embedding):
        logit_scale = torch.clamp(self.logit_scale, max=self.logit_scale_max).exp()
        clip_ret = self.clip_loss_fn(audio_embedding, mouth_embedding, logit_scale)
        loss = clip_ret['clip_loss']
        return loss

if __name__ == '__main__':
    syncnet = SyncNetModel()
    aud = torch.randn([2, 10, 1024])
    vid = torch.randn([2, 5, 60])
    aud_feat, vid_feat = syncnet.forward(aud, vid)

    print(aud_feat.shape)
    print(vid_feat.shape)