"""NanoCodec's decoder with a memory: T new frames of dequantized codes in, T * 1024 samples out, every convolution's past carried in one flat array. Same layers and weights as NeMo's CausalHiFiGANDecoder (weight norm folded in).""" import sys from pathlib import Path import torch from torch import nn from torch.nn import functional as F sys.path.insert(0, str(Path(__file__).parent)) import codec # noqa: E402 class Mem: """Hands out and collects the pieces of the flat memory, in order.""" def __init__(self, flat): self.flat, self.at, self.out = flat, 0, [] def take(self, c, p): x = self.flat[self.at:self.at + c * p].reshape(1, c, p) self.at += c * p return x def put(self, x): self.out.append(x.reshape(-1)) class SConv(nn.Module): def __init__(self, src): super().__init__() conv = src.conv k, d = conv.kernel_size[0], conv.dilation[0] self.d, self.pad = d, (k - 1) * d self.c_in = conv.in_channels self.weight, self.bias = nn.Parameter(conv.weight.detach().clone()), nn.Parameter(conv.bias.detach().clone()) self.act = src.activation def size(self): return self.c_in * self.pad def forward(self, x, mem): h = torch.cat((mem.take(self.c_in, self.pad), x), -1) mem.put(h[:, :, h.shape[2] - self.pad:]) return self.act(F.conv1d(h, self.weight, self.bias, dilation=self.d)) class SUp(nn.Module): def __init__(self, src): super().__init__() conv = src.conv self.s, self.k, self.groups = conv.stride[0], conv.kernel_size[0], conv.groups self.c_in = conv.in_channels assert self.k == 2 * self.s self.weight, self.bias = nn.Parameter(conv.weight.detach().clone()), nn.Parameter(conv.bias.detach().clone()) def size(self): return self.c_in def forward(self, x, mem): h = torch.cat((mem.take(self.c_in, 1), x), -1) mem.put(h[:, :, -1:]) y = F.conv_transpose1d(h, self.weight, self.bias, stride=self.s, groups=self.groups) return y[:, :, self.s:self.s + x.shape[2] * self.s] class SRes(nn.Module): """ResidualBlock: activation, conv, activation, conv, added to the input.""" def __init__(self, src): super().__init__() self.a1, self.c1, self.a2, self.c2 = src.input_activation, SConv(src.input_conv), src.skip_activation, SConv(src.skip_conv) def forward(self, x, mem): return x + self.c2(self.a2(self.c1(self.a1(x), mem)), mem) class StreamDecoder(nn.Module): def __init__(self, dec): super().__init__() self.pre = SConv(dec.pre_conv) self.acts, self.ups = dec.activations, nn.ModuleList(SUp(u) for u in dec.up_sample_conv_layers) self.layers = nn.ModuleList(nn.ModuleList(nn.ModuleList(SRes(r) for r in b.res_blocks) for b in layer.res_blocks) for layer in dec.res_layers) self.post_act, self.post, self.out_act = dec.post_activation, SConv(dec.post_conv), dec.out_activation def convs(self): yield self.pre for up, layer in zip(self.ups, self.layers): yield up for b in layer: for r in b: yield r.c1 yield r.c2 yield self.post def size(self): return sum(c.size() for c in self.convs()) def forward(self, z, memory): mem = Mem(memory) x = self.pre(z, mem) for act, up, layer in zip(self.acts, self.ups, self.layers): x = up(act(x), mem) outs = [] for b in layer: y = x for r in b: y = r(y, mem) outs.append(y) x = sum(outs) / len(outs) x = self.post(self.post_act(x), mem) return self.out_act(x).reshape(1, -1), torch.cat(mem.out) if __name__ == "__main__": m = codec.load() sd = StreamDecoder(m.audio_decoder).eval() n = sd.size() print("memory values", n, f"({n * 4 / 1e3:.0f} KB)") torch.manual_seed(0) codes = torch.cat([torch.randint(0, l, (1, 1, 100)) for l in [8, 7, 6, 6] * 8], 1).float() half = torch.tensor([4, 3, 3, 3] * 8).float() z = (codes - half[None, :, None]) / half[None, :, None] with torch.no_grad(): ref, _ = m.audio_decoder(inputs=z, input_len=torch.tensor([100])) mem, out = torch.zeros(n), [] for i in (0, 12, 24, 40, 41, 60): j = {0: 12, 12: 24, 24: 40, 40: 41, 41: 60, 60: 100}[i] a, mem = sd(z[:, :, i:j], mem) out.append(a) out = torch.cat(out, 1) print("streamed vs whole: max diff", float((out - ref).abs().max()), "mean", float((out - ref).abs().mean()), out.shape, ref.shape)