Skip to content

Commit 0d77172

Browse files
authored
Merge pull request #9 from wolfgitpr/aug
Aug
2 parents 19d4c47 + f9f429d commit 0d77172

12 files changed

Lines changed: 464 additions & 350 deletions

File tree

binarize.py

Lines changed: 239 additions & 233 deletions
Large diffs are not rendered by default.

configs/force_alignment.yaml

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
model_name: 1201_fa
1+
model_name: 1218_fa
22

33
float32_matmul_precision: high
44
random_seed: 123456
@@ -67,7 +67,7 @@ fa_arg:
6767
optimizer_config:
6868
lr: 0.0003
6969
gamma: 0.9999
70-
total_steps: 20000
70+
total_steps: 10000
7171
muon_args:
7272
weight_decay: 0.1
7373
adamw_args:
@@ -104,9 +104,9 @@ hubert_config:
104104
mel_spec_config:
105105
n_mels: 128
106106
sample_rate: 44100
107-
window_size: 1024
108-
hop_size: 512
109-
n_fft: 2048
107+
window_size: 882
108+
hop_size: 441
109+
n_fft: 1764
110110
f_min: 40
111111
f_max: 16000
112112
clamp: 0.00001

configs/non_lexical_labeler.yaml

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
model_name: 1201_nll
1+
model_name: 1218_nll
22

33
float32_matmul_precision: high
44
random_seed: 123456
@@ -54,7 +54,7 @@ cvnt_arg:
5454
optimizer_config:
5555
lr: 0.0003
5656
gamma: 0.9999
57-
total_steps: 20000
57+
total_steps: 10000
5858
muon_args:
5959
weight_decay: 0.1
6060
adamw_args:
@@ -86,9 +86,9 @@ hubert_config:
8686
mel_spec_config:
8787
n_mels: 128
8888
sample_rate: 44100
89-
window_size: 1024
90-
hop_size: 512
91-
n_fft: 2048
89+
window_size: 882
90+
hop_size: 441
91+
n_fft: 1764
9292
f_min: 40
9393
f_max: 16000
9494
clamp: 0.00001

networks/layer/attention/__init__.py

Whitespace-only changes.
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import torch.nn as nn
2+
3+
4+
class SEAttention(nn.Module):
5+
def __init__(self, channels, reduction=16):
6+
super().__init__()
7+
self.fc = nn.Sequential(
8+
nn.AdaptiveAvgPool1d(1),
9+
nn.Flatten(),
10+
nn.Linear(channels, channels // reduction, bias=False),
11+
nn.ReLU(inplace=True),
12+
nn.Linear(channels // reduction, channels, bias=False),
13+
nn.Sigmoid()
14+
)
15+
16+
def forward(self, x): # x: [B, C, T]
17+
B, C, T = x.shape
18+
scale = self.fc(x).view(B, C, 1) # [B, C, 1]
19+
return x * scale.expand_as(x)

networks/layer/backbone/unet.py

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import torch.nn as nn
22
import torch.nn.functional as F
33

4+
from networks.layer.attention.attention import SEAttention
5+
46

57
class UNetBackbone(nn.Module):
68
def __init__(
@@ -16,26 +18,15 @@ def __init__(
1618
channels_scaleup_factor: float = 2.0,
1719
dropout: float = 0.1,
1820
):
19-
"""_summary_
20-
21-
Args:
22-
input_dims (int):
23-
output_dims (int):
24-
hidden_dims (int):
25-
block (nn.Module): shape: (B, C, T) -> shape: (B, C, T)
26-
down_sampling (nn.Module): shape: (B, C, T) -> shape: (B, C*2, T/down_sampling_factor)
27-
up_sampling (nn.Module): shape: (B, C, T) -> shape: (B, C/2, T*down_sampling_factor)
28-
"""
2921
super(UNetBackbone, self).__init__()
3022

3123
self.input_dims = input_dims
3224
self.output_dims = output_dims
3325
self.hidden_dims = hidden_dims
34-
3526
self.divisible_factor = down_sampling_factor ** down_sampling_times
3627

3728
self.encoders = nn.ModuleList()
38-
self.encoders.append(block(input_dims, hidden_dims, dropout=dropout))
29+
self.encoders.append(self._attention_block(block, input_dims, hidden_dims, dropout))
3930
for i in range(down_sampling_times - 1):
4031
i += 1
4132
self.encoders.append(
@@ -45,10 +36,11 @@ def __init__(
4536
int(channels_scaleup_factor ** i) * hidden_dims,
4637
down_sampling_factor,
4738
),
48-
block(
39+
self._attention_block(
40+
block,
4941
int(channels_scaleup_factor ** i) * hidden_dims,
5042
int(channels_scaleup_factor ** i) * hidden_dims,
51-
dropout=dropout,
43+
dropout,
5244
),
5345
)
5446
)
@@ -59,10 +51,11 @@ def __init__(
5951
int(channels_scaleup_factor ** down_sampling_times) * hidden_dims,
6052
down_sampling_factor,
6153
),
62-
block(
54+
self._attention_block(
55+
block,
6356
int(channels_scaleup_factor ** down_sampling_times) * hidden_dims,
6457
int(channels_scaleup_factor ** down_sampling_times) * hidden_dims,
65-
dropout=dropout,
58+
dropout,
6659
),
6760
up_sampling(
6861
int(channels_scaleup_factor ** down_sampling_times) * hidden_dims,
@@ -76,12 +69,13 @@ def __init__(
7669
i += 1
7770
self.decoders.append(
7871
nn.Sequential(
79-
block(
72+
self._attention_block(
73+
block,
8074
int(channels_scaleup_factor ** (down_sampling_times - i))
8175
* hidden_dims,
8276
int(channels_scaleup_factor ** (down_sampling_times - i))
8377
* hidden_dims,
84-
dropout=dropout,
78+
dropout,
8579
),
8680
up_sampling(
8781
int(channels_scaleup_factor ** (down_sampling_times - i))
@@ -92,11 +86,16 @@ def __init__(
9286
),
9387
)
9488
)
95-
self.decoders.append(block(hidden_dims, output_dims))
89+
self.decoders.append(self._attention_block(block, hidden_dims, output_dims, dropout))
90+
91+
@staticmethod
92+
def _attention_block(block_class, in_channels, out_channels, dropout):
93+
return nn.Sequential(
94+
block_class(in_channels, out_channels, dropout=dropout),
95+
SEAttention(out_channels)
96+
)
9697

97-
def forward(self,
98-
x, # [B, C, T]
99-
):
98+
def forward(self, x): # x: [B, C, T]
10099
B, C, T = x.shape
101100
padding_len = (-T) % self.divisible_factor
102101
x = F.pad(x, (0, padding_len))

networks/layer/block/resnet_block.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import torch.nn as nn
22

3+
from networks.layer.attention.attention import SEAttention
4+
35

46
class ResidualBasicBlock(nn.Module):
57
def __init__(self, input_dims: int, output_dims: int, hidden_dims: int = None, n_groups: int = 16,
@@ -37,6 +39,47 @@ def forward(self, x): # x: [B, C, T]
3739
return x
3840

3941

42+
class AttentionResidualBasicBlock(nn.Module):
43+
def __init__(self, input_dims: int, output_dims: int, hidden_dims: int = None,
44+
n_groups: int = 16, dropout: float = 0.1):
45+
super().__init__()
46+
47+
self.input_dims = input_dims
48+
self.output_dims = output_dims
49+
self.hidden_dims = hidden_dims if hidden_dims is not None else max(n_groups, output_dims // n_groups * n_groups)
50+
self.n_groups = n_groups
51+
self.dropout = dropout
52+
53+
self.activation = nn.Hardswish()
54+
55+
self.block = nn.Sequential(
56+
nn.Conv1d(self.input_dims, self.hidden_dims, kernel_size=3, padding=1, bias=False),
57+
nn.GroupNorm(self.n_groups, self.hidden_dims),
58+
self.activation,
59+
nn.Dropout1d(dropout) if dropout > 0 else nn.Identity(),
60+
nn.Conv1d(self.hidden_dims, self.output_dims, kernel_size=3, padding=1, bias=False),
61+
)
62+
63+
self.attention = SEAttention(self.output_dims)
64+
65+
self.shortcut = nn.Identity() if self.input_dims == self.output_dims \
66+
else nn.Conv1d(self.input_dims, self.output_dims, kernel_size=1, bias=False)
67+
68+
self.out = nn.Sequential(
69+
nn.GroupNorm(1, self.output_dims),
70+
self.activation,
71+
nn.Dropout(dropout) if dropout > 0 else nn.Identity(),
72+
)
73+
74+
def forward(self, x):
75+
residual = self.shortcut(x)
76+
x = self.block(x)
77+
x = self.attention(x)
78+
x = x + residual
79+
x = self.out(x)
80+
return x
81+
82+
4083
class ResidualBottleNeckBlock(nn.Module):
4184
def __init__(self, input_dims: int, output_dims: int, hidden_dims: int = None, n_groups: int = 16):
4285
super(ResidualBottleNeckBlock, self).__init__()

networks/optimizer/muon.py

Lines changed: 32 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -39,25 +39,25 @@ def zeropower_via_newtonschulz5(G: Tensor, steps: int, use_bf16: bool) -> Tensor
3939
"""
4040
assert G.ndim == 3 # batched Muon implementation by @scottjmaddox, and put into practice in the record by @YouJiacheng
4141
a, b, c = (3.4445, -4.7750, 2.0315)
42-
if use_bf16:
43-
X = G.bfloat16()
44-
else:
45-
X = G.float()
46-
if G.size(-2) > G.size(-1):
47-
X = X.mT
42+
43+
X = G.to(dtype=torch.bfloat16 if use_bf16 else torch.float32)
4844

4945
# Ensure spectral norm is at most 1
5046
X = F.normalize(X, p=2.0, dim=(-2, -1), eps=1e-7)
5147

5248
# Perform the NS iterations
53-
for _ in range(steps):
54-
A = X @ X.mT
55-
B = torch.baddbmm(A, A, A, beta=b, alpha=c)
56-
X = torch.baddbmm(X, B, X, beta=a, alpha=1)
49+
if X.size(-2) < X.size(-1):
50+
for _ in range(steps):
51+
A = torch.bmm(X, X.mT)
52+
A = torch.baddbmm(A, A, A, beta=b, alpha=c)
53+
X = torch.baddbmm(X, A, X, beta=a, alpha=1)
54+
else:
55+
for _ in range(steps):
56+
A = torch.bmm(X.mT, X)
57+
A = torch.baddbmm(A, A, A, beta=b, alpha=c)
58+
X = torch.baddbmm(X, X, A, beta=a, alpha=1)
5759

58-
if G.size(-2) > G.size(-1):
59-
X = X.mT
60-
return X.to(G)
60+
return X
6161

6262

6363
class Muon(torch.optim.Optimizer):
@@ -92,33 +92,34 @@ def __init__(self, params, lr=5e-4, weight_decay=0.1, momentum=0.95, nesterov=Tr
9292
def step(self, closure=None):
9393
for group in self.param_groups:
9494
shape_groups = {}
95-
for p in filter(lambda p: p.grad is not None, group["params"]):
95+
for p in filter(lambda _p: _p.grad is not None, group["params"]):
9696
g = p.grad
9797
state = self.state[p]
9898
if "momentum_buffer" not in state:
9999
state["momentum_buffer"] = torch.zeros_like(g)
100-
buf: Tensor = state["momentum_buffer"]
101100
key = (p.shape, p.device, p.dtype)
102101
if key not in shape_groups:
103102
shape_groups[key] = {"params": [], "grads": [], "buffers": []}
104103
shape_groups[key]["params"].append(p)
105104
shape_groups[key]["grads"].append(g)
106-
shape_groups[key]["buffers"].append(buf)
105+
shape_groups[key]["buffers"].append(state["momentum_buffer"])
107106
for key in shape_groups:
108107
group_data = shape_groups[key]
109-
g = torch.stack(group_data["grads"])
110-
buf = torch.stack(group_data["buffers"])
111-
buf.lerp_(g, 1 - group["momentum"])
112-
g = g.lerp_(buf, group["momentum"]) if group["nesterov"] else buf
108+
p, g, buf, m = group_data["params"], group_data["grads"], group_data["buffers"], group["momentum"]
109+
torch._foreach_lerp_(buf, g, 1 - m)
110+
if group["nesterov"]:
111+
torch._foreach_lerp_(g, buf, m)
112+
g = torch.stack(g)
113+
else:
114+
g = torch.stack(buf)
115+
original_shape = g.shape
113116
if g.ndim >= 4: # for the case of conv filters
114117
g = g.view(g.size(0), g.size(1), -1)
115118
use_bf16 = self.bf16_support_map.get(g.device, False)
116119
g = zeropower_via_newtonschulz5(g, steps=group["ns_steps"], use_bf16=use_bf16)
117-
for i, p in enumerate(group_data["params"]):
118-
if group["weight_decay"] > 0:
119-
p.data.mul_(1 - group["lr"] * group["weight_decay"])
120-
p.data.add_(g[i].view_as(p), alpha=-group["lr"] * max(g[i].size()) ** 0.5)
121-
self.state[p]["momentum_buffer"] = buf[i].clone()
120+
if group["weight_decay"] > 0:
121+
torch._foreach_mul_(p, 1 - group["lr"] * group["weight_decay"])
122+
torch._foreach_add_(p, g.view(original_shape).unbind(0), alpha=-group["lr"] * max(g[0].size()) ** 0.5)
122123

123124

124125
def get_params_for_muon(model) -> List[Parameter]:
@@ -129,6 +130,7 @@ def get_params_for_muon(model) -> List[Parameter]:
129130
module: The module to filter parameters for.
130131
Returns:
131132
A list of parameters that should be optimized with muon.
133+
:param model:
132134
"""
133135
muon_params = []
134136
for module in model.modules():
@@ -141,7 +143,11 @@ def get_params_for_muon(model) -> List[Parameter]:
141143

142144

143145
class Muon_AdamW(ChainedOptimizer):
144-
def __init__(self, model, lr=0.0005, weight_decay=0.0, muon_args={}, adamw_args={}, verbose=False):
146+
def __init__(self, model, lr=0.0005, weight_decay=0.0, muon_args=None, adamw_args=None, verbose=False):
147+
if adamw_args is None:
148+
adamw_args = {}
149+
if muon_args is None:
150+
muon_args = {}
145151
muon_params_id_set = set(id(p) for p in get_params_for_muon(model))
146152
spec_muon = OptimizerSpec(Muon, muon_args, lambda param: id(param) in muon_params_id_set)
147153
spec_adamw = OptimizerSpec(torch.optim.AdamW, adamw_args, None)

networks/task/forced_alignment_task.py

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,14 @@
66
import torch.optim.lr_scheduler as lr_scheduler_module
77

88
import networks.scheduler as scheduler_module
9-
from scripts.evaluate import remove_ignored_phonemes, quantize_tier
109
from networks.layer.backbone.unet import UNetBackbone
11-
from networks.layer.block.resnet_block import ResidualBasicBlock
10+
from networks.layer.block.resnet_block import AttentionResidualBasicBlock
1211
from networks.layer.fusion.curves_fusion import PowerCurveEdgeFusion
1312
from networks.layer.scaling.stride_conv import DownSampling, UpSampling
1413
from networks.loss.GHMLoss import CTCGHMLoss, GHMLoss, MultiLabelGHMLoss
1514
from networks.optimizer.muon import Muon_AdamW
15+
from scripts.evaluate import remove_ignored_phonemes, quantize_tier
1616
from tools.decoder import AlignmentDecoder
17-
from tools.encoder import UnitsEncoder
1817
from tools.metrics import BoundaryEditRatio, BoundaryEditRatioWeighted, VlabelerEditRatio, CustomPointTier
1918

2019

@@ -49,12 +48,12 @@ def __init__(
4948
input_dims=self.hubert_config["channel"],
5049
output_dims=self.fa_arg["hidden_dims"],
5150
hidden_dims=self.fa_arg["hidden_dims"],
52-
block=ResidualBasicBlock,
51+
block=AttentionResidualBasicBlock,
5352
down_sampling=DownSampling,
5453
up_sampling=UpSampling,
55-
down_sampling_factor=self.fa_arg["down_sampling_factor"], # 2
56-
down_sampling_times=self.fa_arg["down_sampling_times"], # 3
57-
channels_scaleup_factor=self.fa_arg["channels_scaleup_factor"], # 1.5
54+
down_sampling_factor=self.fa_arg["down_sampling_factor"],
55+
down_sampling_times=self.fa_arg["down_sampling_times"],
56+
channels_scaleup_factor=self.fa_arg["channels_scaleup_factor"],
5857
dropout=self.fa_arg["dropout"],
5958
)
6059

@@ -145,10 +144,6 @@ def _losses_schedulers_step(self):
145144
def _losses_schedulers_call(self):
146145
return torch.tensor([scheduler() for scheduler in self.losses_schedulers]).to(self.device)
147146

148-
def on_predict_start(self):
149-
if self.unitsEncoder is None:
150-
self.unitsEncoder = UnitsEncoder(self.hubert_config, self.mel_spec_config, device=self.device)
151-
152147
def _get_consistency_loss(
153148
self,
154149
ph_frame_logits, # [B,vocab_size,T]

0 commit comments

Comments
 (0)