Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
prophesier
GitHub Repository: prophesier/diff-svc
Path: blob/main/modules/diff/net.py
694 views
1
import math
2
from math import sqrt
3
4
import torch
5
import torch.nn as nn
6
import torch.nn.functional as F
7
8
from modules.commons.common_layers import Mish
9
from utils.hparams import hparams
10
11
Linear = nn.Linear
12
ConvTranspose2d = nn.ConvTranspose2d
13
14
15
class AttrDict(dict):
16
def __init__(self, *args, **kwargs):
17
super(AttrDict, self).__init__(*args, **kwargs)
18
self.__dict__ = self
19
20
def override(self, attrs):
21
if isinstance(attrs, dict):
22
self.__dict__.update(**attrs)
23
elif isinstance(attrs, (list, tuple, set)):
24
for attr in attrs:
25
self.override(attr)
26
elif attrs is not None:
27
raise NotImplementedError
28
return self
29
30
31
class SinusoidalPosEmb(nn.Module):
32
def __init__(self, dim):
33
super().__init__()
34
self.dim = dim
35
36
def forward(self, x):
37
device = x.device
38
half_dim = self.dim // 2
39
emb = math.log(10000) / (half_dim - 1)
40
emb = torch.exp(torch.arange(half_dim, device=device) * -emb)
41
emb = x[:, None] * emb[None, :]
42
emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
43
return emb
44
45
46
def Conv1d(*args, **kwargs):
47
layer = nn.Conv1d(*args, **kwargs)
48
nn.init.kaiming_normal_(layer.weight)
49
return layer
50
51
52
@torch.jit.script
53
def silu(x):
54
return x * torch.sigmoid(x)
55
56
57
class ResidualBlock(nn.Module):
58
def __init__(self, encoder_hidden, residual_channels, dilation):
59
super().__init__()
60
self.dilated_conv = Conv1d(residual_channels, 2 * residual_channels, 3, padding=dilation, dilation=dilation)
61
self.diffusion_projection = Linear(residual_channels, residual_channels)
62
self.conditioner_projection = Conv1d(encoder_hidden, 2 * residual_channels, 1)
63
self.output_projection = Conv1d(residual_channels, 2 * residual_channels, 1)
64
65
def forward(self, x, conditioner, diffusion_step):
66
diffusion_step = self.diffusion_projection(diffusion_step).unsqueeze(-1)
67
conditioner = self.conditioner_projection(conditioner)
68
y = x + diffusion_step
69
70
y = self.dilated_conv(y) + conditioner
71
72
gate, filter = torch.chunk(y, 2, dim=1)
73
# Using torch.split instead of torch.chunk to avoid using onnx::Slice
74
# gate, filter = torch.split(y, torch.div(y.shape[1], 2), dim=1)
75
76
y = torch.sigmoid(gate) * torch.tanh(filter)
77
78
y = self.output_projection(y)
79
residual, skip = torch.chunk(y, 2, dim=1)
80
# Using torch.split instead of torch.chunk to avoid using onnx::Slice
81
# residual, skip = torch.split(y, torch.div(y.shape[1], 2), dim=1)
82
83
return (x + residual) / sqrt(2.0), skip
84
85
86
class DiffNet(nn.Module):
87
def __init__(self, in_dims=80):
88
super().__init__()
89
self.params = params = AttrDict(
90
# Model params
91
encoder_hidden=hparams['hidden_size'],
92
residual_layers=hparams['residual_layers'],
93
residual_channels=hparams['residual_channels'],
94
dilation_cycle_length=hparams['dilation_cycle_length'],
95
)
96
self.input_projection = Conv1d(in_dims, params.residual_channels, 1)
97
self.diffusion_embedding = SinusoidalPosEmb(params.residual_channels)
98
dim = params.residual_channels
99
self.mlp = nn.Sequential(
100
nn.Linear(dim, dim * 4),
101
Mish(),
102
nn.Linear(dim * 4, dim)
103
)
104
self.residual_layers = nn.ModuleList([
105
ResidualBlock(params.encoder_hidden, params.residual_channels, 2 ** (i % params.dilation_cycle_length))
106
for i in range(params.residual_layers)
107
])
108
self.skip_projection = Conv1d(params.residual_channels, params.residual_channels, 1)
109
self.output_projection = Conv1d(params.residual_channels, in_dims, 1)
110
nn.init.zeros_(self.output_projection.weight)
111
112
def forward(self, spec, diffusion_step, cond):
113
"""
114
115
:param spec: [B, 1, M, T]
116
:param diffusion_step: [B, 1]
117
:param cond: [B, M, T]
118
:return:
119
"""
120
x = spec[:, 0]
121
x = self.input_projection(x) # x [B, residual_channel, T]
122
123
x = F.relu(x)
124
diffusion_step = self.diffusion_embedding(diffusion_step)
125
diffusion_step = self.mlp(diffusion_step)
126
skip = []
127
for layer_id, layer in enumerate(self.residual_layers):
128
x, skip_connection = layer(x, cond, diffusion_step)
129
skip.append(skip_connection)
130
131
x = torch.sum(torch.stack(skip), dim=0) / sqrt(len(self.residual_layers))
132
x = self.skip_projection(x)
133
x = F.relu(x)
134
x = self.output_projection(x) # [B, 80, T]
135
return x[:, None, :, :]
136
137