File size: 2,476 Bytes
2d4936d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""NanoCodec's encoder and quantizer in ONNX: 22.05 kHz audio [1, N] (N a multiple of 1024) -> codes [1, T, 32] in 0..L-1, ready
for the voice compressor. Checked against NeMo's encode() on three clips."""
import sys; from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
import numpy as np, torch, soundfile as sf
from torch import nn
import codec

ROOT = Path(__file__).resolve().parents[1]
LEVELS = torch.tensor([8, 7, 6, 6] * 8).float()[None, :, None]


class Enc(nn.Module):
    def __init__(s, m):
        super().__init__()
        s.enc = m.audio_encoder
        scale = (LEVELS - 1) / 2 * (1 - 1e-3)
        off = torch.where(LEVELS % 2 == 0, 0.5, 0.0)
        s.register_buffer("scale", scale), s.register_buffer("off", off), s.register_buffer("shift", (off / scale).tan()), s.register_buffer("half_levels", LEVELS // 2)

    def forward(s, audio):
        n = torch.tensor([audio.shape[1]]) if not torch.onnx.is_in_onnx_export() else torch._shape_as_tensor(audio)[1:2]
        e, _ = s.enc(audio=audio, audio_len=n)
        q = torch.round(s.scale * torch.tanh(e + s.shift) - s.off) + s.half_levels
        return q.transpose(1, 2).to(torch.int64)


if __name__ == "__main__":
    m = codec.load()
    net = Enc(m).eval()
    with torch.no_grad():
        torch.onnx.export(net, (torch.zeros(1, 1024 * 40),), str(ROOT / "export" / "codec_encoder.onnx"), dynamo=False, opset_version=17, input_names=["audio"], output_names=["codes"], dynamic_axes={"audio": {1: "N"}, "codes": {1: "T"}})
    print("codec_encoder.onnx", round((ROOT / "export/codec_encoder.onnx").stat().st_size / 1e6), "MB")
    L4, base = torch.tensor([8, 7, 6, 6]), torch.tensor([1, 8, 56, 336])
    clips = ROOT / "runs" / "clips"; clips.mkdir(parents=True, exist_ok=True)
    import reference as R
    ref = R.Reference()
    for k, i in enumerate((29, 36, 38)):
        x, sr = sf.read(ROOT / f"runs/ref/{i:02d}.wav", dtype="float32")
        x = x[:len(x) // 1024 * 1024]
        with torch.no_grad():
            tok, _ = m.encode(audio=torch.from_numpy(x)[None], audio_len=torch.tensor([len(x)]))
            un = ((tok[0].T[:, :, None] // base) % L4).reshape(tok.shape[2], -1)
            mine = net(torch.from_numpy(x)[None])[0]
            pre = ref.comp(un[None])[0]
        np.savez(clips / f"{k}.npz", wav=x, codes=un.numpy(), prefix=pre.numpy())
        print("clip", k, f"{len(x) / 22050:.1f} s", "codes agree (PyTorch wrapper)", float((mine == un).float().mean()))