rsax commited on
Commit
0841207
·
verified ·
1 Parent(s): 7560f50

Upload 14 files

Browse files
models/encdec.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ from models.resnet import Resnet1D
3
+
4
+ class Encoder(nn.Module):
5
+ def __init__(self,
6
+ input_emb_width = 3,
7
+ output_emb_width = 512,
8
+ down_t = 3,
9
+ stride_t = 2,
10
+ width = 512,
11
+ depth = 3,
12
+ dilation_growth_rate = 3,
13
+ activation='relu',
14
+ norm=None):
15
+ super().__init__()
16
+
17
+ blocks = []
18
+ filter_t, pad_t = stride_t * 2, stride_t // 2
19
+ blocks.append(nn.Conv1d(input_emb_width, width, 3, 1, 1))
20
+ blocks.append(nn.ReLU())
21
+
22
+ for i in range(down_t):
23
+ input_dim = width
24
+ block = nn.Sequential(
25
+ nn.Conv1d(input_dim, width, filter_t, stride_t, pad_t),
26
+ Resnet1D(width, depth, dilation_growth_rate, activation=activation, norm=norm),
27
+ )
28
+ blocks.append(block)
29
+ blocks.append(nn.Conv1d(width, output_emb_width, 3, 1, 1))
30
+ self.model = nn.Sequential(*blocks)
31
+
32
+ def forward(self, x):
33
+ return self.model(x)
34
+
35
+ class Decoder(nn.Module):
36
+ def __init__(self,
37
+ input_emb_width = 3,
38
+ output_emb_width = 512,
39
+ down_t = 3,
40
+ stride_t = 2,
41
+ width = 512,
42
+ depth = 3,
43
+ dilation_growth_rate = 3,
44
+ activation='relu',
45
+ norm=None):
46
+ super().__init__()
47
+ blocks = []
48
+
49
+ filter_t, pad_t = stride_t * 2, stride_t // 2
50
+ blocks.append(nn.Conv1d(output_emb_width, width, 3, 1, 1))
51
+ blocks.append(nn.ReLU())
52
+ for i in range(down_t):
53
+ out_dim = width
54
+ block = nn.Sequential(
55
+ Resnet1D(width, depth, dilation_growth_rate, reverse_dilation=True, activation=activation, norm=norm),
56
+ nn.Upsample(scale_factor=2, mode='nearest'),
57
+ nn.Conv1d(width, out_dim, 3, 1, 1)
58
+ )
59
+ blocks.append(block)
60
+ blocks.append(nn.Conv1d(width, width, 3, 1, 1))
61
+ blocks.append(nn.ReLU())
62
+ blocks.append(nn.Conv1d(width, input_emb_width, 3, 1, 1))
63
+ self.model = nn.Sequential(*blocks)
64
+
65
+ def forward(self, x):
66
+ return self.model(x)
67
+
models/encdec_imp.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import torch.nn.functional as F
3
+ from models.resnet_imp import Resnet1D
4
+ import math
5
+
6
+
7
+ class SEBlock(nn.Module):
8
+ """Squeeze-and-Excitation Block"""
9
+ def __init__(self, channel, reduction=16):
10
+ super().__init__()
11
+ self.sequential = nn.Sequential(
12
+ nn.AdaptiveAvgPool1d(1),
13
+ nn.Conv1d(channel, channel // reduction, 1, bias=False),
14
+ nn.ReLU(inplace=True),
15
+ nn.Conv1d(channel // reduction, channel, 1, bias=False),
16
+ nn.Sigmoid()
17
+ )
18
+
19
+ def forward(self, x):
20
+ scale = self.sequential(x)
21
+ return x * scale
22
+
23
+
24
+ class Encoder(nn.Module):
25
+ def __init__(self,
26
+ input_emb_width=3,
27
+ output_emb_width=512,
28
+ down_t=3,
29
+ stride_t=2,
30
+ width=512,
31
+ depth=3,
32
+ dilation_growth_rate=3,
33
+ activation='relu',
34
+ norm=None,
35
+ dropout=0.1):
36
+ super().__init__()
37
+
38
+ self.dropout = dropout
39
+
40
+ blocks = []
41
+
42
+ # First layer with normalization and optional dropout
43
+ blocks.append(nn.Conv1d(input_emb_width, width, 3, padding=1))
44
+ blocks.append(nn.BatchNorm1d(width))
45
+ blocks.append(nn.ReLU())
46
+ blocks.append(nn.Dropout(dropout))
47
+
48
+ # Downsampling layers with SE blocks
49
+ filter_t, pad_t = stride_t * 2, stride_t // 2
50
+ for _ in range(down_t):
51
+ block = nn.Sequential(
52
+ nn.Conv1d(width, width, filter_t, stride_t, pad_t),
53
+ nn.BatchNorm1d(width),
54
+ nn.ReLU(),
55
+ SEBlock(width),
56
+ Resnet1D(width, depth, dilation_growth_rate, activation=activation, norm=norm, dropout=dropout)
57
+ )
58
+ blocks.append(block)
59
+
60
+ # Final layer with optional dropout
61
+ blocks.append(nn.Conv1d(width, output_emb_width, 3, padding=1))
62
+ blocks.append(nn.Dropout(dropout))
63
+
64
+ self.model = nn.Sequential(*blocks)
65
+
66
+ def forward(self, x):
67
+ return self.model(x)
68
+
69
+
70
+ class Decoder(nn.Module):
71
+ def __init__(self,
72
+ input_emb_width=3,
73
+ output_emb_width=512,
74
+ down_t=3,
75
+ stride_t=2,
76
+ width=512,
77
+ depth=3,
78
+ dilation_growth_rate=3,
79
+ activation='relu',
80
+ norm=None,
81
+ dropout=0.1):
82
+ super().__init__()
83
+
84
+ self.dropout = dropout
85
+
86
+ blocks = []
87
+
88
+ # First layer with normalization
89
+ blocks.append(nn.Conv1d(output_emb_width, width, 3, padding=1))
90
+ blocks.append(nn.BatchNorm1d(width))
91
+ blocks.append(nn.ReLU())
92
+ blocks.append(nn.Dropout(dropout))
93
+
94
+ # Upsampling layers with residual connections
95
+ for _ in range(down_t):
96
+ block = nn.Sequential(
97
+ SEBlock(width),
98
+ Resnet1D(width, depth, dilation_growth_rate, reverse_dilation=True, activation=activation, norm=norm),
99
+ nn.BatchNorm1d(width),
100
+ nn.ReLU(),
101
+ nn.Upsample(scale_factor=2, mode='nearest'),
102
+ nn.Conv1d(width, width, 3, padding=1),
103
+ nn.Dropout(dropout)
104
+ )
105
+ blocks.append(block)
106
+
107
+ # Final reconstruction layers
108
+ blocks.append(nn.Conv1d(width, input_emb_width, 3, padding=1))
109
+
110
+ self.model = nn.Sequential(*blocks)
111
+
112
+ def forward(self, x):
113
+ return self.model(x)
models/evaluator_wrapper.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import torch
3
+ from os.path import join as pjoin
4
+ import numpy as np
5
+ from models.modules import MovementConvEncoder, TextEncoderBiGRUCo, MotionEncoderBiGRUCo
6
+ from utils.word_vectorizer import POS_enumerator
7
+
8
+ def build_models(opt):
9
+ movement_enc = MovementConvEncoder(opt.dim_pose-4, opt.dim_movement_enc_hidden, opt.dim_movement_latent)
10
+ text_enc = TextEncoderBiGRUCo(word_size=opt.dim_word,
11
+ pos_size=opt.dim_pos_ohot,
12
+ hidden_size=opt.dim_text_hidden,
13
+ output_size=opt.dim_coemb_hidden,
14
+ device=opt.device)
15
+
16
+ motion_enc = MotionEncoderBiGRUCo(input_size=opt.dim_movement_latent,
17
+ hidden_size=opt.dim_motion_hidden,
18
+ output_size=opt.dim_coemb_hidden,
19
+ device=opt.device)
20
+
21
+ checkpoint = torch.load(pjoin(opt.checkpoints_dir, opt.dataset_name, 'text_mot_match', 'model', 'finest.tar'),
22
+ map_location=opt.device)
23
+ movement_enc.load_state_dict(checkpoint['movement_encoder'])
24
+ text_enc.load_state_dict(checkpoint['text_encoder'])
25
+ motion_enc.load_state_dict(checkpoint['motion_encoder'])
26
+ print('Loading Evaluation Model Wrapper (Epoch %d) Completed!!' % (checkpoint['epoch']))
27
+ return text_enc, motion_enc, movement_enc
28
+
29
+
30
+ class EvaluatorModelWrapper(object):
31
+
32
+ def __init__(self, opt):
33
+
34
+ if opt.dataset_name == 't2m':
35
+ opt.dim_pose = 263
36
+ elif opt.dataset_name == 'kit':
37
+ opt.dim_pose = 251
38
+ else:
39
+ raise KeyError('Dataset not Recognized!!!')
40
+
41
+ opt.dim_word = 300
42
+ opt.max_motion_length = 196
43
+ opt.dim_pos_ohot = len(POS_enumerator)
44
+ opt.dim_motion_hidden = 1024
45
+ opt.max_text_len = 20
46
+ opt.dim_text_hidden = 512
47
+ opt.dim_coemb_hidden = 512
48
+
49
+ # print(opt)
50
+
51
+ self.text_encoder, self.motion_encoder, self.movement_encoder = build_models(opt)
52
+ self.opt = opt
53
+ self.device = opt.device
54
+
55
+ self.text_encoder.to(opt.device)
56
+ self.motion_encoder.to(opt.device)
57
+ self.movement_encoder.to(opt.device)
58
+
59
+ self.text_encoder.eval()
60
+ self.motion_encoder.eval()
61
+ self.movement_encoder.eval()
62
+
63
+ # Please note that the results does not following the order of inputs
64
+ def get_co_embeddings(self, word_embs, pos_ohot, cap_lens, motions, m_lens):
65
+ with torch.no_grad():
66
+ word_embs = word_embs.detach().to(self.device).float()
67
+ pos_ohot = pos_ohot.detach().to(self.device).float()
68
+ motions = motions.detach().to(self.device).float()
69
+
70
+ '''Movement Encoding'''
71
+ movements = self.movement_encoder(motions[..., :-4]).detach()
72
+ m_lens = m_lens // self.opt.unit_length
73
+ motion_embedding = self.motion_encoder(movements, m_lens)
74
+
75
+ '''Text Encoding'''
76
+ text_embedding = self.text_encoder(word_embs, pos_ohot, cap_lens)
77
+ return text_embedding, motion_embedding
78
+
79
+ # Please note that the results does not following the order of inputs
80
+ def get_motion_embeddings(self, motions, m_lens):
81
+ with torch.no_grad():
82
+ motions = motions.detach().to(self.device).float()
83
+
84
+ align_idx = np.argsort(m_lens.data.tolist())[::-1].copy()
85
+ motions = motions[align_idx]
86
+ m_lens = m_lens[align_idx]
87
+
88
+ '''Movement Encoding'''
89
+ movements = self.movement_encoder(motions[..., :-4]).detach()
90
+ m_lens = m_lens // self.opt.unit_length
91
+ motion_embedding = self.motion_encoder(movements, m_lens)
92
+ return motion_embedding
models/modules.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.nn.utils.rnn import pack_padded_sequence
4
+
5
+ def init_weight(m):
6
+ if isinstance(m, nn.Conv1d) or isinstance(m, nn.Linear) or isinstance(m, nn.ConvTranspose1d):
7
+ nn.init.xavier_normal_(m.weight)
8
+ # m.bias.data.fill_(0.01)
9
+ if m.bias is not None:
10
+ nn.init.constant_(m.bias, 0)
11
+
12
+
13
+ class MovementConvEncoder(nn.Module):
14
+ def __init__(self, input_size, hidden_size, output_size):
15
+ super(MovementConvEncoder, self).__init__()
16
+ self.main = nn.Sequential(
17
+ nn.Conv1d(input_size, hidden_size, 4, 2, 1),
18
+ nn.Dropout(0.2, inplace=True),
19
+ nn.LeakyReLU(0.2, inplace=True),
20
+ nn.Conv1d(hidden_size, output_size, 4, 2, 1),
21
+ nn.Dropout(0.2, inplace=True),
22
+ nn.LeakyReLU(0.2, inplace=True),
23
+ )
24
+ self.out_net = nn.Linear(output_size, output_size)
25
+ self.main.apply(init_weight)
26
+ self.out_net.apply(init_weight)
27
+
28
+ def forward(self, inputs):
29
+ inputs = inputs.permute(0, 2, 1)
30
+ outputs = self.main(inputs).permute(0, 2, 1)
31
+ # print(outputs.shape)
32
+ return self.out_net(outputs)
33
+
34
+
35
+
36
+ class TextEncoderBiGRUCo(nn.Module):
37
+ def __init__(self, word_size, pos_size, hidden_size, output_size, device):
38
+ super(TextEncoderBiGRUCo, self).__init__()
39
+ self.device = device
40
+
41
+ self.pos_emb = nn.Linear(pos_size, word_size)
42
+ self.input_emb = nn.Linear(word_size, hidden_size)
43
+ self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True, bidirectional=True)
44
+ self.output_net = nn.Sequential(
45
+ nn.Linear(hidden_size * 2, hidden_size),
46
+ nn.LayerNorm(hidden_size),
47
+ nn.LeakyReLU(0.2, inplace=True),
48
+ nn.Linear(hidden_size, output_size)
49
+ )
50
+
51
+ self.input_emb.apply(init_weight)
52
+ self.pos_emb.apply(init_weight)
53
+ self.output_net.apply(init_weight)
54
+ self.hidden_size = hidden_size
55
+ self.hidden = nn.Parameter(torch.randn((2, 1, self.hidden_size), requires_grad=True))
56
+
57
+ # input(batch_size, seq_len, dim)
58
+ def forward(self, word_embs, pos_onehot, cap_lens):
59
+ num_samples = word_embs.shape[0]
60
+
61
+ pos_embs = self.pos_emb(pos_onehot)
62
+ inputs = word_embs + pos_embs
63
+ input_embs = self.input_emb(inputs)
64
+ hidden = self.hidden.repeat(1, num_samples, 1)
65
+
66
+ cap_lens = cap_lens.data.tolist()
67
+ emb = pack_padded_sequence(input_embs, cap_lens, batch_first=True)
68
+
69
+ gru_seq, gru_last = self.gru(emb, hidden)
70
+
71
+ gru_last = torch.cat([gru_last[0], gru_last[1]], dim=-1)
72
+
73
+ return self.output_net(gru_last)
74
+
75
+
76
+ class MotionEncoderBiGRUCo(nn.Module):
77
+ def __init__(self, input_size, hidden_size, output_size, device):
78
+ super(MotionEncoderBiGRUCo, self).__init__()
79
+ self.device = device
80
+
81
+ self.input_emb = nn.Linear(input_size, hidden_size)
82
+ self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True, bidirectional=True)
83
+ self.output_net = nn.Sequential(
84
+ nn.Linear(hidden_size*2, hidden_size),
85
+ nn.LayerNorm(hidden_size),
86
+ nn.LeakyReLU(0.2, inplace=True),
87
+ nn.Linear(hidden_size, output_size)
88
+ )
89
+
90
+ self.input_emb.apply(init_weight)
91
+ self.output_net.apply(init_weight)
92
+ self.hidden_size = hidden_size
93
+ self.hidden = nn.Parameter(torch.randn((2, 1, self.hidden_size), requires_grad=True))
94
+
95
+ # input(batch_size, seq_len, dim)
96
+ def forward(self, inputs, m_lens):
97
+ num_samples = inputs.shape[0]
98
+
99
+ input_embs = self.input_emb(inputs)
100
+ hidden = self.hidden.repeat(1, num_samples, 1)
101
+
102
+ cap_lens = m_lens.data.tolist()
103
+ emb = pack_padded_sequence(input_embs, cap_lens, batch_first=True, enforce_sorted=False)
104
+
105
+ gru_seq, gru_last = self.gru(emb, hidden)
106
+
107
+ gru_last = torch.cat([gru_last[0], gru_last[1]], dim=-1)
108
+
109
+ return self.output_net(gru_last)
models/pos_encoding.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Various positional encodings for the transformer.
3
+ """
4
+ import math
5
+ import torch
6
+ from torch import nn
7
+
8
+ def PE1d_sincos(seq_length, dim):
9
+ """
10
+ :param d_model: dimension of the model
11
+ :param length: length of positions
12
+ :return: length*d_model position matrix
13
+ """
14
+ if dim % 2 != 0:
15
+ raise ValueError("Cannot use sin/cos positional encoding with "
16
+ "odd dim (got dim={:d})".format(dim))
17
+ pe = torch.zeros(seq_length, dim)
18
+ position = torch.arange(0, seq_length).unsqueeze(1)
19
+ div_term = torch.exp((torch.arange(0, dim, 2, dtype=torch.float) *
20
+ -(math.log(10000.0) / dim)))
21
+ pe[:, 0::2] = torch.sin(position.float() * div_term)
22
+ pe[:, 1::2] = torch.cos(position.float() * div_term)
23
+
24
+ return pe.unsqueeze(1)
25
+
26
+
27
+ class PositionEmbedding(nn.Module):
28
+ """
29
+ Absolute pos embedding (standard), learned.
30
+ """
31
+ def __init__(self, seq_length, dim, dropout, grad=False):
32
+ super().__init__()
33
+ self.embed = nn.Parameter(data=PE1d_sincos(seq_length, dim), requires_grad=grad)
34
+ self.dropout = nn.Dropout(p=dropout)
35
+
36
+ def forward(self, x):
37
+ # x.shape: bs, seq_len, feat_dim
38
+ l = x.shape[1]
39
+ x = x.permute(1, 0, 2) + self.embed[:l].expand(x.permute(1, 0, 2).shape)
40
+ x = self.dropout(x.permute(1, 0, 2))
41
+ return x
42
+
43
+
models/quantize_cnn.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+
6
+ class QuantizeEMAReset(nn.Module):
7
+ def __init__(self, nb_code, code_dim, args):
8
+ super().__init__()
9
+ self.nb_code = nb_code
10
+ self.code_dim = code_dim
11
+ self.mu = args.mu
12
+ self.reset_codebook()
13
+
14
+ def reset_codebook(self):
15
+ self.init = False
16
+ self.code_sum = None
17
+ self.code_count = None
18
+ self.register_buffer('codebook', torch.zeros(self.nb_code, self.code_dim).cuda())
19
+
20
+ def _tile(self, x):
21
+ nb_code_x, code_dim = x.shape
22
+ if nb_code_x < self.nb_code:
23
+ n_repeats = (self.nb_code + nb_code_x - 1) // nb_code_x
24
+ std = 0.01 / np.sqrt(code_dim)
25
+ out = x.repeat(n_repeats, 1)
26
+ out = out + torch.randn_like(out) * std
27
+ else :
28
+ out = x
29
+ return out
30
+
31
+ def init_codebook(self, x):
32
+ out = self._tile(x)
33
+ self.codebook = out[:self.nb_code]
34
+ self.code_sum = self.codebook.clone()
35
+ self.code_count = torch.ones(self.nb_code, device=self.codebook.device)
36
+ self.init = True
37
+
38
+ @torch.no_grad()
39
+ def compute_perplexity(self, code_idx) :
40
+ # Calculate new centres
41
+ code_onehot = torch.zeros(self.nb_code, code_idx.shape[0], device=code_idx.device) # nb_code, N * L
42
+ code_onehot.scatter_(0, code_idx.view(1, code_idx.shape[0]), 1)
43
+
44
+ code_count = code_onehot.sum(dim=-1) # nb_code
45
+ prob = code_count / torch.sum(code_count)
46
+ perplexity = torch.exp(-torch.sum(prob * torch.log(prob + 1e-7)))
47
+ return perplexity
48
+
49
+ @torch.no_grad()
50
+ def update_codebook(self, x, code_idx):
51
+
52
+ code_onehot = torch.zeros(self.nb_code, x.shape[0], device=x.device) # nb_code, N * L
53
+ code_onehot.scatter_(0, code_idx.view(1, x.shape[0]), 1)
54
+
55
+ code_sum = torch.matmul(code_onehot, x) # nb_code, w
56
+ code_count = code_onehot.sum(dim=-1) # nb_code
57
+
58
+ out = self._tile(x)
59
+ code_rand = out[:self.nb_code]
60
+
61
+ # Update centres
62
+ self.code_sum = self.mu * self.code_sum + (1. - self.mu) * code_sum # w, nb_code
63
+ self.code_count = self.mu * self.code_count + (1. - self.mu) * code_count # nb_code
64
+
65
+ usage = (self.code_count.view(self.nb_code, 1) >= 1.0).float()
66
+ code_update = self.code_sum.view(self.nb_code, self.code_dim) / self.code_count.view(self.nb_code, 1)
67
+
68
+ self.codebook = usage * code_update + (1 - usage) * code_rand
69
+ prob = code_count / torch.sum(code_count)
70
+ perplexity = torch.exp(-torch.sum(prob * torch.log(prob + 1e-7)))
71
+
72
+
73
+ return perplexity
74
+
75
+ def preprocess(self, x):
76
+ # NCT -> NTC -> [NT, C]
77
+ x = x.permute(0, 2, 1).contiguous()
78
+ x = x.view(-1, x.shape[-1])
79
+ return x
80
+
81
+ def quantize(self, x):
82
+ # Calculate latent code x_l
83
+ k_w = self.codebook.t()
84
+ distance = torch.sum(x ** 2, dim=-1, keepdim=True) - 2 * torch.matmul(x, k_w) + torch.sum(k_w ** 2, dim=0,
85
+ keepdim=True) # (N * L, b)
86
+ _, code_idx = torch.min(distance, dim=-1)
87
+ return code_idx
88
+
89
+ def dequantize(self, code_idx):
90
+ x = F.embedding(code_idx, self.codebook)
91
+ return x
92
+
93
+
94
+ def forward(self, x):
95
+ N, width, T = x.shape
96
+
97
+ # Preprocess
98
+ x = self.preprocess(x)
99
+
100
+ # Init codebook if not inited
101
+ if self.training and not self.init:
102
+ self.init_codebook(x)
103
+
104
+ # quantize and dequantize through bottleneck
105
+ code_idx = self.quantize(x)
106
+ x_d = self.dequantize(code_idx)
107
+
108
+ # Update embeddings
109
+ if self.training:
110
+ perplexity = self.update_codebook(x, code_idx)
111
+ else :
112
+ perplexity = self.compute_perplexity(code_idx)
113
+
114
+ # Loss
115
+ commit_loss = F.mse_loss(x, x_d.detach())
116
+
117
+ # Passthrough
118
+ x_d = x + (x_d - x).detach()
119
+
120
+ # Postprocess
121
+ x_d = x_d.view(N, T, -1).permute(0, 2, 1).contiguous() #(N, DIM, T)
122
+
123
+ return x_d, commit_loss, perplexity
124
+
125
+
126
+
127
+ class Quantizer(nn.Module):
128
+ def __init__(self, n_e, e_dim, beta):
129
+ super(Quantizer, self).__init__()
130
+
131
+ self.e_dim = e_dim
132
+ self.n_e = n_e
133
+ self.beta = beta
134
+
135
+ self.embedding = nn.Embedding(self.n_e, self.e_dim)
136
+ self.embedding.weight.data.uniform_(-1.0 / self.n_e, 1.0 / self.n_e)
137
+
138
+ def forward(self, z):
139
+
140
+ N, width, T = z.shape
141
+ z = self.preprocess(z)
142
+ assert z.shape[-1] == self.e_dim
143
+ z_flattened = z.contiguous().view(-1, self.e_dim)
144
+
145
+ # B x V
146
+ d = torch.sum(z_flattened ** 2, dim=1, keepdim=True) + \
147
+ torch.sum(self.embedding.weight**2, dim=1) - 2 * \
148
+ torch.matmul(z_flattened, self.embedding.weight.t())
149
+ # B x 1
150
+ min_encoding_indices = torch.argmin(d, dim=1)
151
+ z_q = self.embedding(min_encoding_indices).view(z.shape)
152
+
153
+ # compute loss for embedding
154
+ loss = torch.mean((z_q - z.detach())**2) + self.beta * \
155
+ torch.mean((z_q.detach() - z)**2)
156
+
157
+ # preserve gradients
158
+ z_q = z + (z_q - z).detach()
159
+ z_q = z_q.view(N, T, -1).permute(0, 2, 1).contiguous() #(N, DIM, T)
160
+
161
+ min_encodings = F.one_hot(min_encoding_indices, self.n_e).type(z.dtype)
162
+ e_mean = torch.mean(min_encodings, dim=0)
163
+ perplexity = torch.exp(-torch.sum(e_mean*torch.log(e_mean + 1e-10)))
164
+ return z_q, loss, perplexity
165
+
166
+ def quantize(self, z):
167
+
168
+ assert z.shape[-1] == self.e_dim
169
+
170
+ # B x V
171
+ d = torch.sum(z ** 2, dim=1, keepdim=True) + \
172
+ torch.sum(self.embedding.weight ** 2, dim=1) - 2 * \
173
+ torch.matmul(z, self.embedding.weight.t())
174
+ # B x 1
175
+ min_encoding_indices = torch.argmin(d, dim=1)
176
+ return min_encoding_indices
177
+
178
+ def dequantize(self, indices):
179
+
180
+ index_flattened = indices.view(-1)
181
+ z_q = self.embedding(index_flattened)
182
+ z_q = z_q.view(indices.shape + (self.e_dim, )).contiguous()
183
+ return z_q
184
+
185
+ def preprocess(self, x):
186
+ # NCT -> NTC -> [NT, C]
187
+ x = x.permute(0, 2, 1).contiguous()
188
+ x = x.view(-1, x.shape[-1])
189
+ return x
190
+
191
+
192
+
193
+ class QuantizeReset(nn.Module):
194
+ def __init__(self, nb_code, code_dim, args):
195
+ super().__init__()
196
+ self.nb_code = nb_code
197
+ self.code_dim = code_dim
198
+ self.reset_codebook()
199
+ self.codebook = nn.Parameter(torch.randn(nb_code, code_dim))
200
+
201
+ def reset_codebook(self):
202
+ self.init = False
203
+ self.code_count = None
204
+
205
+ def _tile(self, x):
206
+ nb_code_x, code_dim = x.shape
207
+ if nb_code_x < self.nb_code:
208
+ n_repeats = (self.nb_code + nb_code_x - 1) // nb_code_x
209
+ std = 0.01 / np.sqrt(code_dim)
210
+ out = x.repeat(n_repeats, 1)
211
+ out = out + torch.randn_like(out) * std
212
+ else :
213
+ out = x
214
+ return out
215
+
216
+ def init_codebook(self, x):
217
+ out = self._tile(x)
218
+ self.codebook = nn.Parameter(out[:self.nb_code])
219
+ self.code_count = torch.ones(self.nb_code, device=self.codebook.device)
220
+ self.init = True
221
+
222
+ @torch.no_grad()
223
+ def compute_perplexity(self, code_idx) :
224
+ # Calculate new centres
225
+ code_onehot = torch.zeros(self.nb_code, code_idx.shape[0], device=code_idx.device) # nb_code, N * L
226
+ code_onehot.scatter_(0, code_idx.view(1, code_idx.shape[0]), 1)
227
+
228
+ code_count = code_onehot.sum(dim=-1) # nb_code
229
+ prob = code_count / torch.sum(code_count)
230
+ perplexity = torch.exp(-torch.sum(prob * torch.log(prob + 1e-7)))
231
+ return perplexity
232
+
233
+ def update_codebook(self, x, code_idx):
234
+
235
+ code_onehot = torch.zeros(self.nb_code, x.shape[0], device=x.device) # nb_code, N * L
236
+ code_onehot.scatter_(0, code_idx.view(1, x.shape[0]), 1)
237
+
238
+ code_count = code_onehot.sum(dim=-1) # nb_code
239
+
240
+ out = self._tile(x)
241
+ code_rand = out[:self.nb_code]
242
+
243
+ # Update centres
244
+ self.code_count = code_count # nb_code
245
+ usage = (self.code_count.view(self.nb_code, 1) >= 1.0).float()
246
+
247
+ self.codebook.data = usage * self.codebook.data + (1 - usage) * code_rand
248
+ prob = code_count / torch.sum(code_count)
249
+ perplexity = torch.exp(-torch.sum(prob * torch.log(prob + 1e-7)))
250
+
251
+
252
+ return perplexity
253
+
254
+ def preprocess(self, x):
255
+ # NCT -> NTC -> [NT, C]
256
+ x = x.permute(0, 2, 1).contiguous()
257
+ x = x.view(-1, x.shape[-1])
258
+ return x
259
+
260
+ def quantize(self, x):
261
+ # Calculate latent code x_l
262
+ k_w = self.codebook.t()
263
+ distance = torch.sum(x ** 2, dim=-1, keepdim=True) - 2 * torch.matmul(x, k_w) + torch.sum(k_w ** 2, dim=0,
264
+ keepdim=True) # (N * L, b)
265
+ _, code_idx = torch.min(distance, dim=-1)
266
+ return code_idx
267
+
268
+ def dequantize(self, code_idx):
269
+ x = F.embedding(code_idx, self.codebook)
270
+ return x
271
+
272
+
273
+ def forward(self, x):
274
+ N, width, T = x.shape
275
+ # Preprocess
276
+ x = self.preprocess(x)
277
+ # Init codebook if not inited
278
+ if self.training and not self.init:
279
+ self.init_codebook(x)
280
+ # quantize and dequantize through bottleneck
281
+ code_idx = self.quantize(x)
282
+ x_d = self.dequantize(code_idx)
283
+ # Update embeddings
284
+ if self.training:
285
+ perplexity = self.update_codebook(x, code_idx)
286
+ else :
287
+ perplexity = self.compute_perplexity(code_idx)
288
+
289
+ # Loss
290
+ commit_loss = F.mse_loss(x, x_d.detach())
291
+
292
+ # Passthrough
293
+ x_d = x + (x_d - x).detach()
294
+
295
+ # Postprocess
296
+ x_d = x_d.view(N, T, -1).permute(0, 2, 1).contiguous() #(N, DIM, T)
297
+
298
+ return x_d, commit_loss, perplexity
299
+
300
+
301
+ class QuantizeEMA(nn.Module):
302
+ def __init__(self, nb_code, code_dim, args):
303
+ super().__init__()
304
+ self.nb_code = nb_code
305
+ self.code_dim = code_dim
306
+ self.mu = 0.99
307
+ self.reset_codebook()
308
+
309
+ def reset_codebook(self):
310
+ self.init = False
311
+ self.code_sum = None
312
+ self.code_count = None
313
+ self.register_buffer('codebook', torch.zeros(self.nb_code, self.code_dim).cuda())
314
+
315
+ def _tile(self, x):
316
+ nb_code_x, code_dim = x.shape
317
+ if nb_code_x < self.nb_code:
318
+ n_repeats = (self.nb_code + nb_code_x - 1) // nb_code_x
319
+ std = 0.01 / np.sqrt(code_dim)
320
+ out = x.repeat(n_repeats, 1)
321
+ out = out + torch.randn_like(out) * std
322
+ else :
323
+ out = x
324
+ return out
325
+
326
+ def init_codebook(self, x):
327
+ out = self._tile(x)
328
+ self.codebook = out[:self.nb_code]
329
+ self.code_sum = self.codebook.clone()
330
+ self.code_count = torch.ones(self.nb_code, device=self.codebook.device)
331
+ self.init = True
332
+
333
+ @torch.no_grad()
334
+ def compute_perplexity(self, code_idx) :
335
+ # Calculate new centres
336
+ code_onehot = torch.zeros(self.nb_code, code_idx.shape[0], device=code_idx.device) # nb_code, N * L
337
+ code_onehot.scatter_(0, code_idx.view(1, code_idx.shape[0]), 1)
338
+
339
+ code_count = code_onehot.sum(dim=-1) # nb_code
340
+ prob = code_count / torch.sum(code_count)
341
+ perplexity = torch.exp(-torch.sum(prob * torch.log(prob + 1e-7)))
342
+ return perplexity
343
+
344
+ @torch.no_grad()
345
+ def update_codebook(self, x, code_idx):
346
+
347
+ code_onehot = torch.zeros(self.nb_code, x.shape[0], device=x.device) # nb_code, N * L
348
+ code_onehot.scatter_(0, code_idx.view(1, x.shape[0]), 1)
349
+
350
+ code_sum = torch.matmul(code_onehot, x) # nb_code, w
351
+ code_count = code_onehot.sum(dim=-1) # nb_code
352
+
353
+ # Update centres
354
+ self.code_sum = self.mu * self.code_sum + (1. - self.mu) * code_sum # w, nb_code
355
+ self.code_count = self.mu * self.code_count + (1. - self.mu) * code_count # nb_code
356
+
357
+ code_update = self.code_sum.view(self.nb_code, self.code_dim) / self.code_count.view(self.nb_code, 1)
358
+
359
+ self.codebook = code_update
360
+ prob = code_count / torch.sum(code_count)
361
+ perplexity = torch.exp(-torch.sum(prob * torch.log(prob + 1e-7)))
362
+
363
+ return perplexity
364
+
365
+ def preprocess(self, x):
366
+ # NCT -> NTC -> [NT, C]
367
+ x = x.permute(0, 2, 1).contiguous()
368
+ x = x.view(-1, x.shape[-1])
369
+ return x
370
+
371
+ def quantize(self, x):
372
+ # Calculate latent code x_l
373
+ k_w = self.codebook.t()
374
+ distance = torch.sum(x ** 2, dim=-1, keepdim=True) - 2 * torch.matmul(x, k_w) + torch.sum(k_w ** 2, dim=0,
375
+ keepdim=True) # (N * L, b)
376
+ _, code_idx = torch.min(distance, dim=-1)
377
+ return code_idx
378
+
379
+ def dequantize(self, code_idx):
380
+ x = F.embedding(code_idx, self.codebook)
381
+ return x
382
+
383
+
384
+ def forward(self, x):
385
+ N, width, T = x.shape
386
+
387
+ # Preprocess
388
+ x = self.preprocess(x)
389
+
390
+ # Init codebook if not inited
391
+ if self.training and not self.init:
392
+ self.init_codebook(x)
393
+
394
+ # quantize and dequantize through bottleneck
395
+ code_idx = self.quantize(x)
396
+ x_d = self.dequantize(code_idx)
397
+
398
+ # Update embeddings
399
+ if self.training:
400
+ perplexity = self.update_codebook(x, code_idx)
401
+ else :
402
+ perplexity = self.compute_perplexity(code_idx)
403
+
404
+ # Loss
405
+ commit_loss = F.mse_loss(x, x_d.detach())
406
+
407
+ # Passthrough
408
+ x_d = x + (x_d - x).detach()
409
+
410
+ # Postprocess
411
+ x_d = x_d.view(N, T, -1).permute(0, 2, 1).contiguous() #(N, DIM, T)
412
+
413
+ return x_d, commit_loss, perplexity
models/resnet.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import torch
3
+
4
+ class nonlinearity(nn.Module):
5
+ def __init__(self):
6
+ super().__init__()
7
+
8
+ def forward(self, x):
9
+ # swish
10
+ return x * torch.sigmoid(x)
11
+
12
+ class ResConv1DBlock(nn.Module):
13
+ def __init__(self, n_in, n_state, dilation=1, activation='silu', norm=None, dropout=None):
14
+ super().__init__()
15
+ padding = dilation
16
+ self.norm = norm
17
+ if norm == "LN":
18
+ self.norm1 = nn.LayerNorm(n_in)
19
+ self.norm2 = nn.LayerNorm(n_in)
20
+ elif norm == "GN":
21
+ self.norm1 = nn.GroupNorm(num_groups=32, num_channels=n_in, eps=1e-6, affine=True)
22
+ self.norm2 = nn.GroupNorm(num_groups=32, num_channels=n_in, eps=1e-6, affine=True)
23
+ elif norm == "BN":
24
+ self.norm1 = nn.BatchNorm1d(num_features=n_in, eps=1e-6, affine=True)
25
+ self.norm2 = nn.BatchNorm1d(num_features=n_in, eps=1e-6, affine=True)
26
+
27
+ else:
28
+ self.norm1 = nn.Identity()
29
+ self.norm2 = nn.Identity()
30
+
31
+ if activation == "relu":
32
+ self.activation1 = nn.ReLU()
33
+ self.activation2 = nn.ReLU()
34
+
35
+ elif activation == "silu":
36
+ self.activation1 = nonlinearity()
37
+ self.activation2 = nonlinearity()
38
+
39
+ elif activation == "gelu":
40
+ self.activation1 = nn.GELU()
41
+ self.activation2 = nn.GELU()
42
+
43
+
44
+
45
+ self.conv1 = nn.Conv1d(n_in, n_state, 3, 1, padding, dilation)
46
+ self.conv2 = nn.Conv1d(n_state, n_in, 1, 1, 0,)
47
+
48
+
49
+ def forward(self, x):
50
+ x_orig = x
51
+ if self.norm == "LN":
52
+ x = self.norm1(x.transpose(-2, -1))
53
+ x = self.activation1(x.transpose(-2, -1))
54
+ else:
55
+ x = self.norm1(x)
56
+ x = self.activation1(x)
57
+
58
+ x = self.conv1(x)
59
+
60
+ if self.norm == "LN":
61
+ x = self.norm2(x.transpose(-2, -1))
62
+ x = self.activation2(x.transpose(-2, -1))
63
+ else:
64
+ x = self.norm2(x)
65
+ x = self.activation2(x)
66
+
67
+ x = self.conv2(x)
68
+ x = x + x_orig
69
+ return x
70
+
71
+ class Resnet1D(nn.Module):
72
+ def __init__(self, n_in, n_depth, dilation_growth_rate=1, reverse_dilation=True, activation='relu', norm=None):
73
+ super().__init__()
74
+
75
+ blocks = [ResConv1DBlock(n_in, n_in, dilation=dilation_growth_rate ** depth, activation=activation, norm=norm) for depth in range(n_depth)]
76
+ if reverse_dilation:
77
+ blocks = blocks[::-1]
78
+
79
+ self.model = nn.Sequential(*blocks)
80
+
81
+ def forward(self, x):
82
+ return self.model(x)
models/resnet_imp.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import torch
3
+ import torch.nn.init as init
4
+
5
+ # Swish nonlinearity
6
+ class Swish(nn.Module):
7
+ def __init__(self):
8
+ super().__init__()
9
+
10
+ def forward(self, x):
11
+ return x * torch.sigmoid(x)
12
+
13
+ # Improved residual block with three convolutions, dropout, and normalization
14
+ class ResConv1DBlock(nn.Module):
15
+ def __init__(self, n_in, n_state, dilation=1, activation='silu', norm=None, dropout=None):
16
+ super().__init__()
17
+
18
+ self.dropout = dropout
19
+ self.norm = norm
20
+
21
+ # Select normalization
22
+ def get_norm(n):
23
+ if norm == "LN":
24
+ return nn.LayerNorm(n)
25
+ elif norm == "GN":
26
+ return nn.GroupNorm(32, n)
27
+ elif norm == "BN":
28
+ return nn.BatchNorm1d(n)
29
+ else:
30
+ return nn.Identity()
31
+
32
+ self.norm1 = get_norm(n_in)
33
+ self.norm2 = get_norm(n_state)
34
+ self.norm3 = get_norm(n_in)
35
+
36
+ # Select activation
37
+ def get_activation(a):
38
+ if a == "relu":
39
+ return nn.ReLU()
40
+ elif a == "silu":
41
+ return Swish()
42
+ elif a == "gelu":
43
+ return nn.GELU()
44
+ elif a == "leaky_relu":
45
+ return nn.LeakyReLU(0.01)
46
+ else:
47
+ raise ValueError("Unsupported activation type")
48
+
49
+ self.activation1 = get_activation(activation)
50
+ self.activation2 = get_activation(activation)
51
+ self.activation3 = get_activation(activation)
52
+
53
+ # Convolution layers with dropout and normalization
54
+ self.conv1 = nn.Conv1d(n_in, n_state, 3, padding=dilation, dilation=dilation)
55
+ self.conv2 = nn.Conv1d(n_state, n_state, 3, padding=dilation, dilation=dilation)
56
+ self.conv3 = nn.Conv1d(n_state, n_in, 1) # Back to input dimensions
57
+
58
+ if dropout:
59
+ self.drop = nn.Dropout(dropout)
60
+
61
+ # Initialize weights
62
+ init.kaiming_normal_(self.conv1.weight, nonlinearity='relu')
63
+ init.kaiming_normal_(self.conv2.weight, nonlinearity='relu')
64
+ init.kaiming_normal_(self.conv3.weight, nonlinearity='relu')
65
+
66
+ def forward(self, x):
67
+ x_orig = x
68
+
69
+ # Normalize and activate
70
+ x = self.norm1(x)
71
+ x = self.activation1(x)
72
+
73
+ # First convolution
74
+ x = self.conv1(x)
75
+
76
+ # Apply dropout if specified
77
+ if self.dropout:
78
+ x = self.drop(x)
79
+
80
+ # Normalize and activate again
81
+ x = self.norm2(x)
82
+ x = self.activation2(x)
83
+
84
+ # Second convolution
85
+ x = self.conv2(x)
86
+
87
+ # Normalize, activate, and apply the final convolution
88
+ x = self.norm3(x)
89
+ x = self.activation3(x)
90
+ x = self.conv3(x)
91
+
92
+ # Apply skip connection
93
+ x = x + x_orig
94
+
95
+ return x
96
+
97
+
98
+ # ResNet1D with multiple residual blocks
99
+ class Resnet1D(nn.Module):
100
+ def __init__(self, n_in, n_depth, dilation_growth_rate=1, reverse_dilation=True, activation='relu', norm=None, dropout=None):
101
+ super().__init__()
102
+
103
+ # Create residual blocks
104
+ blocks = [ResConv1DBlock(n_in, n_in, dilation=dilation_growth_rate ** depth, activation=activation, norm=norm, dropout=dropout) for depth in range(n_depth)]
105
+
106
+ if reverse_dilation:
107
+ blocks = blocks[::-1] # Reverse the order if needed
108
+
109
+ self.model = nn.Sequential(*blocks)
110
+
111
+ def forward(self, x):
112
+ return self.model(x)
models/resnet_imp_1.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import torch
3
+ import torch.nn.init as init
4
+
5
+ # Nonlinearity class for activation functions like Swish
6
+ class Swish(nn.Module):
7
+ def __init__():
8
+ super().__init__()
9
+
10
+ def forward(self, x):
11
+ return x * torch.sigmoid(x)
12
+
13
+ # Main residual block with 2 convolution layers and a skip connection
14
+ class ResConv1DBlock(nn.Module):
15
+ def __init__(self, n_in, n_state, dilation=1, activation='silu', norm=None, dropout=None):
16
+ super().__init__()
17
+
18
+ # Padding for convolution with dilation
19
+ padding = dilation
20
+
21
+ # Add dropout
22
+ self.dropout = dropout
23
+
24
+ # Configure normalization
25
+ self.norm = norm
26
+ if norm == "LN":
27
+ self.norm1 = nn.LayerNorm(n_in)
28
+ self.norm2 = nn.LayerNorm(n_in)
29
+ elif norm == "GN":
30
+ self.norm1 = nn.GroupNorm(32, n_in)
31
+ self.norm2 = nn.GroupNorm(32, n_in)
32
+ elif norm == "BN":
33
+ self.norm1 = nn.BatchNorm1d(n_in)
34
+ self.norm2 = nn.BatchNorm1d(n_in)
35
+ else:
36
+ self.norm1 = nn.Identity()
37
+ self.norm2 = nn.Identity()
38
+
39
+ # Configure activation
40
+ if activation == "relu":
41
+ self.activation1 = nn.ReLU()
42
+ self.activation2 = nn.ReLU()
43
+ elif activation == "silu":
44
+ self.activation1 = Swish()
45
+ self.activation2 = Swish()
46
+ elif activation == "gelu":
47
+ self.activation1 = nn.GELU()
48
+ self.activation2 = nn.GELU()
49
+ else:
50
+ raise ValueError("Unsupported activation type")
51
+
52
+ # Convolution layers with skip connection
53
+ self.conv1 = nn.Conv1d(n_in, n_state, 3, padding=padding, dilation=dilation)
54
+ self.conv_skip = nn.Conv1d(n_state, n_state, 1, stride=1, padding=0)
55
+ self.conv2 = nn.Conv1d(n_state, n_in, 1, padding=0)
56
+
57
+ # Dropout layer if specified
58
+ if self.dropout:
59
+ self.drop = nn.Dropout(dropout)
60
+
61
+ # Initialize weights with suitable initialization
62
+ init.kaiming_normal_(self.conv1.weight, nonlinearity='relu')
63
+ init.kaiming_normal_(self.conv_skip.weight, nonlinearity='relu')
64
+ init.kaiming_normal_(self.conv2.weight, nonlinearity='relu')
65
+
66
+ def forward(self, x):
67
+ x_orig = x
68
+
69
+ # Apply normalization and activation
70
+ if self.norm == "LN":
71
+ x = self.norm1(x.transpose(-2, -1)).transpose(-2, -1)
72
+ else:
73
+ x = self.norm1(x)
74
+
75
+ x = self.activation1(x)
76
+
77
+ # First convolution
78
+ x = self.conv1(x)
79
+
80
+ # Dropout after first convolution if needed
81
+ if self.dropout:
82
+ x = self.drop(x)
83
+
84
+ # Apply skip connection between two convolution layers
85
+ skip = self.conv_skip(x)
86
+
87
+ # Normalization and activation again
88
+ if self.norm == "LN":
89
+ skip = self.norm2(skip.transpose(-2, -1)).transpose(-2, -1)
90
+ else:
91
+ skip = self.norm2(skip)
92
+
93
+ skip = self.activation2(skip)
94
+
95
+ # Apply the second convolution
96
+ x = self.conv2(skip)
97
+
98
+ # Final skip connection with the original input
99
+ x = x + x_orig
100
+
101
+ return x
102
+
103
+
104
+ # Main ResNet1D class
105
+ class Resnet1D(nn.Module):
106
+ def __init__(self, n_in, n_depth, dilation_growth_rate=1, reverse_dilation=True, activation='relu', norm=None, dropout=None):
107
+ super().__init__()
108
+
109
+ # Create residual blocks with the specified configuration
110
+ blocks = [ResConv1DBlock(n_in, n_in, dilation=dilation_growth_rate ** depth, activation=activation, norm=norm, dropout=dropout) for depth in range(n_depth)]
111
+
112
+ if reverse_dilation:
113
+ blocks = blocks[::-1]
114
+
115
+ self.model = nn.Sequential(*blocks)
116
+
117
+ def forward(self, x):
118
+ return self.model(x)
models/rotation2xyz.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This code is based on https://github.com/Mathux/ACTOR.git
2
+ import torch
3
+ import utils.rotation_conversions as geometry
4
+
5
+
6
+ from models.smpl import SMPL, JOINTSTYPE_ROOT
7
+ # from .get_model import JOINTSTYPES
8
+ JOINTSTYPES = ["a2m", "a2mpl", "smpl", "vibe", "vertices"]
9
+
10
+
11
+ class Rotation2xyz:
12
+ def __init__(self, device, dataset='amass'):
13
+ self.device = device
14
+ self.dataset = dataset
15
+ self.smpl_model = SMPL().eval().to(device)
16
+
17
+ def __call__(self, x, mask, pose_rep, translation, glob,
18
+ jointstype, vertstrans, betas=None, beta=0,
19
+ glob_rot=None, get_rotations_back=False, **kwargs):
20
+ if pose_rep == "xyz":
21
+ return x
22
+
23
+ if mask is None:
24
+ mask = torch.ones((x.shape[0], x.shape[-1]), dtype=bool, device=x.device)
25
+
26
+ if not glob and glob_rot is None:
27
+ raise TypeError("You must specify global rotation if glob is False")
28
+
29
+ if jointstype not in JOINTSTYPES:
30
+ raise NotImplementedError("This jointstype is not implemented.")
31
+
32
+ if translation:
33
+ x_translations = x[:, -1, :3]
34
+ x_rotations = x[:, :-1]
35
+ else:
36
+ x_rotations = x
37
+
38
+ x_rotations = x_rotations.permute(0, 3, 1, 2)
39
+ nsamples, time, njoints, feats = x_rotations.shape
40
+
41
+ # Compute rotations (convert only masked sequences output)
42
+ if pose_rep == "rotvec":
43
+ rotations = geometry.axis_angle_to_matrix(x_rotations[mask])
44
+ elif pose_rep == "rotmat":
45
+ rotations = x_rotations[mask].view(-1, njoints, 3, 3)
46
+ elif pose_rep == "rotquat":
47
+ rotations = geometry.quaternion_to_matrix(x_rotations[mask])
48
+ elif pose_rep == "rot6d":
49
+ rotations = geometry.rotation_6d_to_matrix(x_rotations[mask])
50
+ else:
51
+ raise NotImplementedError("No geometry for this one.")
52
+
53
+ if not glob:
54
+ global_orient = torch.tensor(glob_rot, device=x.device)
55
+ global_orient = geometry.axis_angle_to_matrix(global_orient).view(1, 1, 3, 3)
56
+ global_orient = global_orient.repeat(len(rotations), 1, 1, 1)
57
+ else:
58
+ global_orient = rotations[:, 0]
59
+ rotations = rotations[:, 1:]
60
+
61
+ if betas is None:
62
+ betas = torch.zeros([rotations.shape[0], self.smpl_model.num_betas],
63
+ dtype=rotations.dtype, device=rotations.device)
64
+ betas[:, 1] = beta
65
+ # import ipdb; ipdb.set_trace()
66
+ out = self.smpl_model(body_pose=rotations, global_orient=global_orient, betas=betas)
67
+
68
+ # get the desirable joints
69
+ joints = out[jointstype]
70
+
71
+ x_xyz = torch.empty(nsamples, time, joints.shape[1], 3, device=x.device, dtype=x.dtype)
72
+ x_xyz[~mask] = 0
73
+ x_xyz[mask] = joints
74
+
75
+ x_xyz = x_xyz.permute(0, 2, 3, 1).contiguous()
76
+
77
+ # the first translation root at the origin on the prediction
78
+ if jointstype != "vertices":
79
+ rootindex = JOINTSTYPE_ROOT[jointstype]
80
+ x_xyz = x_xyz - x_xyz[:, [rootindex], :, :]
81
+
82
+ if translation and vertstrans:
83
+ # the first translation root at the origin
84
+ x_translations = x_translations - x_translations[:, :, [0]]
85
+
86
+ # add the translation to all the joints
87
+ x_xyz = x_xyz + x_translations[:, None, :, :]
88
+
89
+ if get_rotations_back:
90
+ return x_xyz, rotations, global_orient
91
+ else:
92
+ return x_xyz
models/smpl.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This code is based on https://github.com/Mathux/ACTOR.git
2
+ import numpy as np
3
+ import torch
4
+
5
+ import contextlib
6
+
7
+ from smplx import SMPLLayer as _SMPLLayer
8
+ from smplx.lbs import vertices2joints
9
+
10
+
11
+ # action2motion_joints = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 21, 24, 38]
12
+ # change 0 and 8
13
+ action2motion_joints = [8, 1, 2, 3, 4, 5, 6, 7, 0, 9, 10, 11, 12, 13, 14, 21, 24, 38]
14
+
15
+ from utils.config import SMPL_MODEL_PATH, JOINT_REGRESSOR_TRAIN_EXTRA
16
+
17
+ JOINTSTYPE_ROOT = {"a2m": 0, # action2motion
18
+ "smpl": 0,
19
+ "a2mpl": 0, # set(smpl, a2m)
20
+ "vibe": 8} # 0 is the 8 position: OP MidHip below
21
+
22
+ JOINT_MAP = {
23
+ 'OP Nose': 24, 'OP Neck': 12, 'OP RShoulder': 17,
24
+ 'OP RElbow': 19, 'OP RWrist': 21, 'OP LShoulder': 16,
25
+ 'OP LElbow': 18, 'OP LWrist': 20, 'OP MidHip': 0,
26
+ 'OP RHip': 2, 'OP RKnee': 5, 'OP RAnkle': 8,
27
+ 'OP LHip': 1, 'OP LKnee': 4, 'OP LAnkle': 7,
28
+ 'OP REye': 25, 'OP LEye': 26, 'OP REar': 27,
29
+ 'OP LEar': 28, 'OP LBigToe': 29, 'OP LSmallToe': 30,
30
+ 'OP LHeel': 31, 'OP RBigToe': 32, 'OP RSmallToe': 33, 'OP RHeel': 34,
31
+ 'Right Ankle': 8, 'Right Knee': 5, 'Right Hip': 45,
32
+ 'Left Hip': 46, 'Left Knee': 4, 'Left Ankle': 7,
33
+ 'Right Wrist': 21, 'Right Elbow': 19, 'Right Shoulder': 17,
34
+ 'Left Shoulder': 16, 'Left Elbow': 18, 'Left Wrist': 20,
35
+ 'Neck (LSP)': 47, 'Top of Head (LSP)': 48,
36
+ 'Pelvis (MPII)': 49, 'Thorax (MPII)': 50,
37
+ 'Spine (H36M)': 51, 'Jaw (H36M)': 52,
38
+ 'Head (H36M)': 53, 'Nose': 24, 'Left Eye': 26,
39
+ 'Right Eye': 25, 'Left Ear': 28, 'Right Ear': 27
40
+ }
41
+
42
+ JOINT_NAMES = [
43
+ 'OP Nose', 'OP Neck', 'OP RShoulder',
44
+ 'OP RElbow', 'OP RWrist', 'OP LShoulder',
45
+ 'OP LElbow', 'OP LWrist', 'OP MidHip',
46
+ 'OP RHip', 'OP RKnee', 'OP RAnkle',
47
+ 'OP LHip', 'OP LKnee', 'OP LAnkle',
48
+ 'OP REye', 'OP LEye', 'OP REar',
49
+ 'OP LEar', 'OP LBigToe', 'OP LSmallToe',
50
+ 'OP LHeel', 'OP RBigToe', 'OP RSmallToe', 'OP RHeel',
51
+ 'Right Ankle', 'Right Knee', 'Right Hip',
52
+ 'Left Hip', 'Left Knee', 'Left Ankle',
53
+ 'Right Wrist', 'Right Elbow', 'Right Shoulder',
54
+ 'Left Shoulder', 'Left Elbow', 'Left Wrist',
55
+ 'Neck (LSP)', 'Top of Head (LSP)',
56
+ 'Pelvis (MPII)', 'Thorax (MPII)',
57
+ 'Spine (H36M)', 'Jaw (H36M)',
58
+ 'Head (H36M)', 'Nose', 'Left Eye',
59
+ 'Right Eye', 'Left Ear', 'Right Ear'
60
+ ]
61
+
62
+
63
+ # adapted from VIBE/SPIN to output smpl_joints, vibe joints and action2motion joints
64
+ class SMPL(_SMPLLayer):
65
+ """ Extension of the official SMPL implementation to support more joints """
66
+
67
+ def __init__(self, model_path=SMPL_MODEL_PATH, **kwargs):
68
+ kwargs["model_path"] = model_path
69
+
70
+ # remove the verbosity for the 10-shapes beta parameters
71
+ with contextlib.redirect_stdout(None):
72
+ super(SMPL, self).__init__(**kwargs)
73
+
74
+ J_regressor_extra = np.load(JOINT_REGRESSOR_TRAIN_EXTRA)
75
+ self.register_buffer('J_regressor_extra', torch.tensor(J_regressor_extra, dtype=torch.float32))
76
+ vibe_indexes = np.array([JOINT_MAP[i] for i in JOINT_NAMES])
77
+ a2m_indexes = vibe_indexes[action2motion_joints]
78
+ smpl_indexes = np.arange(24)
79
+ a2mpl_indexes = np.unique(np.r_[smpl_indexes, a2m_indexes])
80
+
81
+ self.maps = {"vibe": vibe_indexes,
82
+ "a2m": a2m_indexes,
83
+ "smpl": smpl_indexes,
84
+ "a2mpl": a2mpl_indexes}
85
+
86
+ def forward(self, *args, **kwargs):
87
+ smpl_output = super(SMPL, self).forward(*args, **kwargs)
88
+
89
+ extra_joints = vertices2joints(self.J_regressor_extra, smpl_output.vertices)
90
+ all_joints = torch.cat([smpl_output.joints, extra_joints], dim=1)
91
+
92
+ output = {"vertices": smpl_output.vertices}
93
+
94
+ for joinstype, indexes in self.maps.items():
95
+ output[joinstype] = all_joints[:, indexes]
96
+
97
+ return output
models/t2m_trans.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn as nn
4
+ from torch.nn import functional as F
5
+ from torch.distributions import Categorical
6
+ import models.pos_encoding as pos_encoding
7
+
8
+ class Text2Motion_Transformer(nn.Module):
9
+
10
+ def __init__(self,
11
+ num_vq=1024,
12
+ embed_dim=512,
13
+ clip_dim=512,
14
+ block_size=16,
15
+ num_layers=2,
16
+ n_head=8,
17
+ drop_out_rate=0.1,
18
+ fc_rate=4):
19
+ super().__init__()
20
+ self.trans_base = CrossCondTransBase(num_vq, embed_dim, clip_dim, block_size, num_layers, n_head, drop_out_rate, fc_rate)
21
+ self.trans_head = CrossCondTransHead(num_vq, embed_dim, block_size, num_layers, n_head, drop_out_rate, fc_rate)
22
+ self.block_size = block_size
23
+ self.num_vq = num_vq
24
+
25
+ def get_block_size(self):
26
+ return self.block_size
27
+
28
+ def forward(self, idxs, clip_feature):
29
+ feat = self.trans_base(idxs, clip_feature)
30
+ logits = self.trans_head(feat)
31
+ return logits
32
+
33
+ def sample(self, clip_feature, if_categorial=False):
34
+ for k in range(self.block_size):
35
+ if k == 0:
36
+ x = []
37
+ else:
38
+ x = xs
39
+ logits = self.forward(x, clip_feature)
40
+ logits = logits[:, -1, :]
41
+ probs = F.softmax(logits, dim=-1)
42
+ if if_categorial:
43
+ dist = Categorical(probs)
44
+ idx = dist.sample()
45
+ if idx == self.num_vq:
46
+ break
47
+ idx = idx.unsqueeze(-1)
48
+ else:
49
+ _, idx = torch.topk(probs, k=1, dim=-1)
50
+ if idx[0] == self.num_vq:
51
+ break
52
+ # append to the sequence and continue
53
+ if k == 0:
54
+ xs = idx
55
+ else:
56
+ xs = torch.cat((xs, idx), dim=1)
57
+
58
+ if k == self.block_size - 1:
59
+ return xs[:, :-1]
60
+ return xs
61
+
62
+ class CausalCrossConditionalSelfAttention(nn.Module):
63
+
64
+ def __init__(self, embed_dim=512, block_size=16, n_head=8, drop_out_rate=0.1):
65
+ super().__init__()
66
+ assert embed_dim % 8 == 0
67
+ # key, query, value projections for all heads
68
+ self.key = nn.Linear(embed_dim, embed_dim)
69
+ self.query = nn.Linear(embed_dim, embed_dim)
70
+ self.value = nn.Linear(embed_dim, embed_dim)
71
+
72
+ self.attn_drop = nn.Dropout(drop_out_rate)
73
+ self.resid_drop = nn.Dropout(drop_out_rate)
74
+
75
+ self.proj = nn.Linear(embed_dim, embed_dim)
76
+ # causal mask to ensure that attention is only applied to the left in the input sequence
77
+ self.register_buffer("mask", torch.tril(torch.ones(block_size, block_size)).view(1, 1, block_size, block_size))
78
+ self.n_head = n_head
79
+
80
+ def forward(self, x):
81
+ B, T, C = x.size()
82
+
83
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
84
+ k = self.key(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
85
+ q = self.query(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
86
+ v = self.value(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
87
+ # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
88
+ att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
89
+ att = att.masked_fill(self.mask[:,:,:T,:T] == 0, float('-inf'))
90
+ att = F.softmax(att, dim=-1)
91
+ att = self.attn_drop(att)
92
+ y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
93
+ y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
94
+
95
+ # output projection
96
+ y = self.resid_drop(self.proj(y))
97
+ return y
98
+
99
+ class Block(nn.Module):
100
+
101
+ def __init__(self, embed_dim=512, block_size=16, n_head=8, drop_out_rate=0.1, fc_rate=4):
102
+ super().__init__()
103
+ self.ln1 = nn.LayerNorm(embed_dim)
104
+ self.ln2 = nn.LayerNorm(embed_dim)
105
+ self.attn = CausalCrossConditionalSelfAttention(embed_dim, block_size, n_head, drop_out_rate)
106
+ self.mlp = nn.Sequential(
107
+ nn.Linear(embed_dim, fc_rate * embed_dim),
108
+ nn.GELU(),
109
+ nn.Linear(fc_rate * embed_dim, embed_dim),
110
+ nn.Dropout(drop_out_rate),
111
+ )
112
+
113
+ def forward(self, x):
114
+ x = x + self.attn(self.ln1(x))
115
+ x = x + self.mlp(self.ln2(x))
116
+ return x
117
+
118
+ class CrossCondTransBase(nn.Module):
119
+
120
+ def __init__(self,
121
+ num_vq=1024,
122
+ embed_dim=512,
123
+ clip_dim=512,
124
+ block_size=16,
125
+ num_layers=2,
126
+ n_head=8,
127
+ drop_out_rate=0.1,
128
+ fc_rate=4):
129
+ super().__init__()
130
+ self.tok_emb = nn.Embedding(num_vq + 2, embed_dim)
131
+ self.cond_emb = nn.Linear(clip_dim, embed_dim)
132
+ self.pos_embedding = nn.Embedding(block_size, embed_dim)
133
+ self.drop = nn.Dropout(drop_out_rate)
134
+ # transformer block
135
+ self.blocks = nn.Sequential(*[Block(embed_dim, block_size, n_head, drop_out_rate, fc_rate) for _ in range(num_layers)])
136
+ self.pos_embed = pos_encoding.PositionEmbedding(block_size, embed_dim, 0.0, False)
137
+
138
+ self.block_size = block_size
139
+
140
+ self.apply(self._init_weights)
141
+
142
+ def get_block_size(self):
143
+ return self.block_size
144
+
145
+ def _init_weights(self, module):
146
+ if isinstance(module, (nn.Linear, nn.Embedding)):
147
+ module.weight.data.normal_(mean=0.0, std=0.02)
148
+ if isinstance(module, nn.Linear) and module.bias is not None:
149
+ module.bias.data.zero_()
150
+ elif isinstance(module, nn.LayerNorm):
151
+ module.bias.data.zero_()
152
+ module.weight.data.fill_(1.0)
153
+
154
+ def forward(self, idx, clip_feature):
155
+ if len(idx) == 0:
156
+ token_embeddings = self.cond_emb(clip_feature).unsqueeze(1)
157
+ else:
158
+ b, t = idx.size()
159
+ assert t <= self.block_size, "Cannot forward, model block size is exhausted."
160
+ # forward the Trans model
161
+ token_embeddings = self.tok_emb(idx)
162
+ token_embeddings = torch.cat([self.cond_emb(clip_feature).unsqueeze(1), token_embeddings], dim=1)
163
+
164
+ x = self.pos_embed(token_embeddings)
165
+ x = self.blocks(x)
166
+
167
+ return x
168
+
169
+
170
+ class CrossCondTransHead(nn.Module):
171
+
172
+ def __init__(self,
173
+ num_vq=1024,
174
+ embed_dim=512,
175
+ block_size=16,
176
+ num_layers=2,
177
+ n_head=8,
178
+ drop_out_rate=0.1,
179
+ fc_rate=4):
180
+ super().__init__()
181
+
182
+ self.blocks = nn.Sequential(*[Block(embed_dim, block_size, n_head, drop_out_rate, fc_rate) for _ in range(num_layers)])
183
+ self.ln_f = nn.LayerNorm(embed_dim)
184
+ self.head = nn.Linear(embed_dim, num_vq + 1, bias=False)
185
+ self.block_size = block_size
186
+
187
+ self.apply(self._init_weights)
188
+
189
+ def get_block_size(self):
190
+ return self.block_size
191
+
192
+ def _init_weights(self, module):
193
+ if isinstance(module, (nn.Linear, nn.Embedding)):
194
+ module.weight.data.normal_(mean=0.0, std=0.02)
195
+ if isinstance(module, nn.Linear) and module.bias is not None:
196
+ module.bias.data.zero_()
197
+ elif isinstance(module, nn.LayerNorm):
198
+ module.bias.data.zero_()
199
+ module.weight.data.fill_(1.0)
200
+
201
+ def forward(self, x):
202
+ x = self.blocks(x)
203
+ x = self.ln_f(x)
204
+ logits = self.head(x)
205
+ return logits
206
+
207
+
208
+
209
+
210
+
211
+
models/vqvae.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ from models.encdec import Encoder, Decoder
3
+ from models.quantize_cnn import QuantizeEMAReset, Quantizer, QuantizeEMA, QuantizeReset
4
+
5
+
6
+ class VQVAE_251(nn.Module):
7
+ def __init__(self,
8
+ args,
9
+ nb_code=1024,
10
+ code_dim=512,
11
+ output_emb_width=512,
12
+ down_t=3,
13
+ stride_t=2,
14
+ width=512,
15
+ depth=3,
16
+ dilation_growth_rate=3,
17
+ activation='relu',
18
+ norm=None):
19
+
20
+ super().__init__()
21
+ self.code_dim = code_dim
22
+ self.num_code = nb_code
23
+ self.quant = args.quantizer
24
+ self.encoder = Encoder(251 if args.dataname == 'kit' else 263, output_emb_width, down_t, stride_t, width, depth, dilation_growth_rate, activation=activation, norm=norm)
25
+ self.decoder = Decoder(251 if args.dataname == 'kit' else 263, output_emb_width, down_t, stride_t, width, depth, dilation_growth_rate, activation=activation, norm=norm)
26
+ if args.quantizer == "ema_reset":
27
+ self.quantizer = QuantizeEMAReset(nb_code, code_dim, args)
28
+ elif args.quantizer == "orig":
29
+ self.quantizer = Quantizer(nb_code, code_dim, 1.0)
30
+ elif args.quantizer == "ema":
31
+ self.quantizer = QuantizeEMA(nb_code, code_dim, args)
32
+ elif args.quantizer == "reset":
33
+ self.quantizer = QuantizeReset(nb_code, code_dim, args)
34
+
35
+
36
+ def preprocess(self, x):
37
+ # (bs, T, Jx3) -> (bs, Jx3, T)
38
+ x = x.permute(0,2,1).float()
39
+ return x
40
+
41
+
42
+ def postprocess(self, x):
43
+ # (bs, Jx3, T) -> (bs, T, Jx3)
44
+ x = x.permute(0,2,1)
45
+ return x
46
+
47
+
48
+ def encode(self, x):
49
+ N, T, _ = x.shape
50
+ x_in = self.preprocess(x)
51
+ x_encoder = self.encoder(x_in)
52
+ x_encoder = self.postprocess(x_encoder)
53
+ x_encoder = x_encoder.contiguous().view(-1, x_encoder.shape[-1]) # (NT, C)
54
+ code_idx = self.quantizer.quantize(x_encoder)
55
+ code_idx = code_idx.view(N, -1)
56
+ return code_idx
57
+
58
+
59
+ def forward(self, x):
60
+
61
+ x_in = self.preprocess(x)
62
+ # Encode
63
+ x_encoder = self.encoder(x_in)
64
+
65
+ ## quantization
66
+ x_quantized, loss, perplexity = self.quantizer(x_encoder)
67
+
68
+ ## decoder
69
+ x_decoder = self.decoder(x_quantized)
70
+ x_out = self.postprocess(x_decoder)
71
+ return x_out, loss, perplexity
72
+
73
+
74
+ def forward_decoder(self, x):
75
+ x_d = self.quantizer.dequantize(x)
76
+ x_d = x_d.view(1, -1, self.code_dim).permute(0, 2, 1).contiguous()
77
+
78
+ # decoder
79
+ x_decoder = self.decoder(x_d)
80
+ x_out = self.postprocess(x_decoder)
81
+ return x_out
82
+
83
+
84
+
85
+ class HumanVQVAE(nn.Module):
86
+ def __init__(self,
87
+ args,
88
+ nb_code=512,
89
+ code_dim=512,
90
+ output_emb_width=512,
91
+ down_t=3,
92
+ stride_t=2,
93
+ width=512,
94
+ depth=3,
95
+ dilation_growth_rate=3,
96
+ activation='relu',
97
+ norm=None):
98
+
99
+ super().__init__()
100
+
101
+ self.nb_joints = 21 if args.dataname == 'kit' else 22
102
+ self.vqvae = VQVAE_251(args, nb_code, code_dim, output_emb_width, down_t, stride_t, width, depth, dilation_growth_rate, activation=activation, norm=norm)
103
+
104
+ def encode(self, x):
105
+ b, t, c = x.size()
106
+ quants = self.vqvae.encode(x) # (N, T)
107
+ return quants
108
+
109
+ def forward(self, x):
110
+
111
+ x_out, loss, perplexity = self.vqvae(x)
112
+
113
+ return x_out, loss, perplexity
114
+
115
+ def forward_decoder(self, x):
116
+ x_out = self.vqvae.forward_decoder(x)
117
+ return x_out
118
+
models/vqvae_imp.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ from models.encdec_imp import Encoder, Decoder
3
+ from models.quantize_cnn import QuantizeEMAReset, Quantizer, QuantizeEMA, QuantizeReset
4
+
5
+
6
+ class VQVAE_251(nn.Module):
7
+ def __init__(self,
8
+ args,
9
+ nb_code=1024,
10
+ code_dim=512,
11
+ output_emb_width=512,
12
+ down_t=3,
13
+ stride_t=2,
14
+ width=512,
15
+ depth=3,
16
+ dilation_growth_rate=3,
17
+ activation='relu',
18
+ norm=None):
19
+
20
+ super().__init__()
21
+ self.code_dim = code_dim
22
+ self.num_code = nb_code
23
+ self.quant = args.quantizer
24
+ self.encoder = Encoder(251 if args.dataname == 'kit' else 263, output_emb_width, down_t, stride_t, width, depth, dilation_growth_rate, activation=activation, norm=norm)
25
+ self.decoder = Decoder(251 if args.dataname == 'kit' else 263, output_emb_width, down_t, stride_t, width, depth, dilation_growth_rate, activation=activation, norm=norm)
26
+ if args.quantizer == "ema_reset":
27
+ self.quantizer = QuantizeEMAReset(nb_code, code_dim, args)
28
+ elif args.quantizer == "orig":
29
+ self.quantizer = Quantizer(nb_code, code_dim, 1.0)
30
+ elif args.quantizer == "ema":
31
+ self.quantizer = QuantizeEMA(nb_code, code_dim, args)
32
+ elif args.quantizer == "reset":
33
+ self.quantizer = QuantizeReset(nb_code, code_dim, args)
34
+
35
+
36
+ def preprocess(self, x):
37
+ # (bs, T, Jx3) -> (bs, Jx3, T)
38
+ x = x.permute(0,2,1).float()
39
+ return x
40
+
41
+
42
+ def postprocess(self, x):
43
+ # (bs, Jx3, T) -> (bs, T, Jx3)
44
+ x = x.permute(0,2,1)
45
+ return x
46
+
47
+
48
+ def encode(self, x):
49
+ N, T, _ = x.shape
50
+ x_in = self.preprocess(x)
51
+ x_encoder = self.encoder(x_in)
52
+ x_encoder = self.postprocess(x_encoder)
53
+ x_encoder = x_encoder.contiguous().view(-1, x_encoder.shape[-1]) # (NT, C)
54
+ code_idx = self.quantizer.quantize(x_encoder)
55
+ code_idx = code_idx.view(N, -1)
56
+ return code_idx
57
+
58
+
59
+ def forward(self, x):
60
+
61
+ x_in = self.preprocess(x)
62
+ # Encode
63
+ x_encoder = self.encoder(x_in)
64
+
65
+ ## quantization
66
+ x_quantized, loss, perplexity = self.quantizer(x_encoder)
67
+
68
+ ## decoder
69
+ x_decoder = self.decoder(x_quantized)
70
+ x_out = self.postprocess(x_decoder)
71
+ return x_out, loss, perplexity
72
+
73
+
74
+ def forward_decoder(self, x):
75
+ x_d = self.quantizer.dequantize(x)
76
+ x_d = x_d.view(1, -1, self.code_dim).permute(0, 2, 1).contiguous()
77
+
78
+ # decoder
79
+ x_decoder = self.decoder(x_d)
80
+ x_out = self.postprocess(x_decoder)
81
+ return x_out
82
+
83
+
84
+
85
+ class HumanVQVAE(nn.Module):
86
+ def __init__(self,
87
+ args,
88
+ nb_code=512,
89
+ code_dim=512,
90
+ output_emb_width=512,
91
+ down_t=3,
92
+ stride_t=2,
93
+ width=512,
94
+ depth=3,
95
+ dilation_growth_rate=3,
96
+ activation='relu',
97
+ norm=None):
98
+
99
+ super().__init__()
100
+
101
+ self.nb_joints = 21 if args.dataname == 'kit' else 22
102
+ self.vqvae = VQVAE_251(args, nb_code, code_dim, output_emb_width, down_t, stride_t, width, depth, dilation_growth_rate, activation=activation, norm=norm)
103
+
104
+ def encode(self, x):
105
+ b, t, c = x.size()
106
+ quants = self.vqvae.encode(x) # (N, T)
107
+ return quants
108
+
109
+ def forward(self, x):
110
+
111
+ x_out, loss, perplexity = self.vqvae(x)
112
+
113
+ return x_out, loss, perplexity
114
+
115
+ def forward_decoder(self, x):
116
+ x_out = self.vqvae.forward_decoder(x)
117
+ return x_out
118
+