dune codec source
Browse files- codec/audio_processing/descriptaudiocodec/dac/model/base.py +286 -0
- codec/audio_processing/descriptaudiocodec/dac/model/dac.py +365 -0
- codec/audio_processing/descriptaudiocodec/dac/nn/layers.py +33 -0
- codec/audio_processing/descriptaudiocodec/dac/nn/quantize.py +251 -0
- codec/audio_processing/dune_codec.py +349 -0
- codec/audio_processing/quantization/__init__.py +8 -0
- codec/audio_processing/quantization/ac.py +292 -0
- codec/audio_processing/quantization/core_vq.py +360 -0
- codec/audio_processing/quantization/core_vq_lsx_version.py +425 -0
- codec/audio_processing/quantization/ddp_utils.py +197 -0
- codec/audio_processing/quantization/distrib.py +123 -0
- codec/audio_processing/quantization/vq.py +116 -0
- codec/audio_processing/semantic_module.py +282 -0
codec/audio_processing/descriptaudiocodec/dac/model/base.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Union
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
import tqdm
|
| 9 |
+
from audiotools import AudioSignal
|
| 10 |
+
from torch import nn
|
| 11 |
+
|
| 12 |
+
SUPPORTED_VERSIONS = ["1.0.0"]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@dataclass
|
| 16 |
+
class DACFile:
|
| 17 |
+
codes: torch.Tensor
|
| 18 |
+
|
| 19 |
+
# Metadata
|
| 20 |
+
chunk_length: int
|
| 21 |
+
original_length: int
|
| 22 |
+
input_db: float
|
| 23 |
+
channels: int
|
| 24 |
+
sample_rate: int
|
| 25 |
+
padding: bool
|
| 26 |
+
dac_version: str
|
| 27 |
+
|
| 28 |
+
def save(self, path):
|
| 29 |
+
artifacts = {
|
| 30 |
+
"codes": self.codes.numpy().astype(np.uint16),
|
| 31 |
+
"metadata": {
|
| 32 |
+
"input_db": self.input_db.numpy().astype(np.float32),
|
| 33 |
+
"original_length": self.original_length,
|
| 34 |
+
"sample_rate": self.sample_rate,
|
| 35 |
+
"chunk_length": self.chunk_length,
|
| 36 |
+
"channels": self.channels,
|
| 37 |
+
"padding": self.padding,
|
| 38 |
+
"dac_version": SUPPORTED_VERSIONS[-1],
|
| 39 |
+
},
|
| 40 |
+
}
|
| 41 |
+
path = Path(path).with_suffix(".dac")
|
| 42 |
+
with open(path, "wb") as f:
|
| 43 |
+
np.save(f, artifacts)
|
| 44 |
+
return path
|
| 45 |
+
|
| 46 |
+
@classmethod
|
| 47 |
+
def load(cls, path):
|
| 48 |
+
artifacts = np.load(path, allow_pickle=True)[()]
|
| 49 |
+
codes = torch.from_numpy(artifacts["codes"].astype(int))
|
| 50 |
+
if artifacts["metadata"].get("dac_version", None) not in SUPPORTED_VERSIONS:
|
| 51 |
+
raise RuntimeError(f"Given file {path} can't be loaded with this version of descript-audio-codec.")
|
| 52 |
+
return cls(codes=codes, **artifacts["metadata"])
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class CodecMixin:
|
| 56 |
+
@property
|
| 57 |
+
def padding(self):
|
| 58 |
+
if not hasattr(self, "_padding"):
|
| 59 |
+
self._padding = True
|
| 60 |
+
return self._padding
|
| 61 |
+
|
| 62 |
+
@padding.setter
|
| 63 |
+
def padding(self, value):
|
| 64 |
+
assert isinstance(value, bool)
|
| 65 |
+
|
| 66 |
+
layers = [l for l in self.modules() if isinstance(l, (nn.Conv1d, nn.ConvTranspose1d))]
|
| 67 |
+
|
| 68 |
+
for layer in layers:
|
| 69 |
+
if value:
|
| 70 |
+
if hasattr(layer, "original_padding"):
|
| 71 |
+
layer.padding = layer.original_padding
|
| 72 |
+
else:
|
| 73 |
+
layer.original_padding = layer.padding
|
| 74 |
+
layer.padding = tuple(0 for _ in range(len(layer.padding)))
|
| 75 |
+
|
| 76 |
+
self._padding = value
|
| 77 |
+
|
| 78 |
+
def get_delay(self):
|
| 79 |
+
# Any number works here, delay is invariant to input length
|
| 80 |
+
l_out = self.get_output_length(0)
|
| 81 |
+
L = l_out
|
| 82 |
+
|
| 83 |
+
layers = []
|
| 84 |
+
for layer in self.modules():
|
| 85 |
+
if isinstance(layer, (nn.Conv1d, nn.ConvTranspose1d)):
|
| 86 |
+
layers.append(layer)
|
| 87 |
+
|
| 88 |
+
for layer in reversed(layers):
|
| 89 |
+
d = layer.dilation[0]
|
| 90 |
+
k = layer.kernel_size[0]
|
| 91 |
+
s = layer.stride[0]
|
| 92 |
+
|
| 93 |
+
if isinstance(layer, nn.ConvTranspose1d):
|
| 94 |
+
L = ((L - d * (k - 1) - 1) / s) + 1
|
| 95 |
+
elif isinstance(layer, nn.Conv1d):
|
| 96 |
+
L = (L - 1) * s + d * (k - 1) + 1
|
| 97 |
+
|
| 98 |
+
L = math.ceil(L)
|
| 99 |
+
|
| 100 |
+
l_in = L
|
| 101 |
+
|
| 102 |
+
return (l_in - l_out) // 2
|
| 103 |
+
|
| 104 |
+
def get_output_length(self, input_length):
|
| 105 |
+
L = input_length
|
| 106 |
+
# Calculate output length
|
| 107 |
+
for layer in self.modules():
|
| 108 |
+
if isinstance(layer, (nn.Conv1d, nn.ConvTranspose1d)):
|
| 109 |
+
d = layer.dilation[0]
|
| 110 |
+
k = layer.kernel_size[0]
|
| 111 |
+
s = layer.stride[0]
|
| 112 |
+
|
| 113 |
+
if isinstance(layer, nn.Conv1d):
|
| 114 |
+
L = ((L - d * (k - 1) - 1) / s) + 1
|
| 115 |
+
elif isinstance(layer, nn.ConvTranspose1d):
|
| 116 |
+
L = (L - 1) * s + d * (k - 1) + 1
|
| 117 |
+
|
| 118 |
+
L = math.floor(L)
|
| 119 |
+
return L
|
| 120 |
+
|
| 121 |
+
@torch.no_grad()
|
| 122 |
+
def compress(
|
| 123 |
+
self,
|
| 124 |
+
audio_path_or_signal: Union[str, Path, AudioSignal],
|
| 125 |
+
win_duration: float = 1.0,
|
| 126 |
+
verbose: bool = False,
|
| 127 |
+
normalize_db: float = -16,
|
| 128 |
+
n_quantizers: int = None,
|
| 129 |
+
) -> DACFile:
|
| 130 |
+
"""Processes an audio signal from a file or AudioSignal object into
|
| 131 |
+
discrete codes. This function processes the signal in short windows,
|
| 132 |
+
using constant GPU memory.
|
| 133 |
+
|
| 134 |
+
Parameters
|
| 135 |
+
----------
|
| 136 |
+
audio_path_or_signal : Union[str, Path, AudioSignal]
|
| 137 |
+
audio signal to reconstruct
|
| 138 |
+
win_duration : float, optional
|
| 139 |
+
window duration in seconds, by default 5.0
|
| 140 |
+
verbose : bool, optional
|
| 141 |
+
by default False
|
| 142 |
+
normalize_db : float, optional
|
| 143 |
+
normalize db, by default -16
|
| 144 |
+
|
| 145 |
+
Returns
|
| 146 |
+
-------
|
| 147 |
+
DACFile
|
| 148 |
+
Object containing compressed codes and metadata
|
| 149 |
+
required for decompression
|
| 150 |
+
"""
|
| 151 |
+
audio_signal = audio_path_or_signal
|
| 152 |
+
if isinstance(audio_signal, (str, Path)):
|
| 153 |
+
audio_signal = AudioSignal.load_from_file_with_ffmpeg(str(audio_signal))
|
| 154 |
+
|
| 155 |
+
self.eval()
|
| 156 |
+
original_padding = self.padding
|
| 157 |
+
original_device = audio_signal.device
|
| 158 |
+
|
| 159 |
+
audio_signal = audio_signal.clone()
|
| 160 |
+
original_sr = audio_signal.sample_rate
|
| 161 |
+
|
| 162 |
+
resample_fn = audio_signal.resample
|
| 163 |
+
loudness_fn = audio_signal.loudness
|
| 164 |
+
|
| 165 |
+
# If audio is > 10 minutes long, use the ffmpeg versions
|
| 166 |
+
if audio_signal.signal_duration >= 10 * 60 * 60:
|
| 167 |
+
resample_fn = audio_signal.ffmpeg_resample
|
| 168 |
+
loudness_fn = audio_signal.ffmpeg_loudness
|
| 169 |
+
|
| 170 |
+
original_length = audio_signal.signal_length
|
| 171 |
+
resample_fn(self.sample_rate)
|
| 172 |
+
input_db = loudness_fn()
|
| 173 |
+
|
| 174 |
+
if normalize_db is not None:
|
| 175 |
+
audio_signal.normalize(normalize_db)
|
| 176 |
+
audio_signal.ensure_max_of_audio()
|
| 177 |
+
|
| 178 |
+
nb, nac, nt = audio_signal.audio_data.shape
|
| 179 |
+
audio_signal.audio_data = audio_signal.audio_data.reshape(nb * nac, 1, nt)
|
| 180 |
+
win_duration = audio_signal.signal_duration if win_duration is None else win_duration
|
| 181 |
+
|
| 182 |
+
if audio_signal.signal_duration <= win_duration:
|
| 183 |
+
# Unchunked compression (used if signal length < win duration)
|
| 184 |
+
self.padding = True
|
| 185 |
+
n_samples = nt
|
| 186 |
+
hop = nt
|
| 187 |
+
else:
|
| 188 |
+
# Chunked inference
|
| 189 |
+
self.padding = False
|
| 190 |
+
# Zero-pad signal on either side by the delay
|
| 191 |
+
audio_signal.zero_pad(self.delay, self.delay)
|
| 192 |
+
n_samples = int(win_duration * self.sample_rate)
|
| 193 |
+
# Round n_samples to nearest hop length multiple
|
| 194 |
+
n_samples = int(math.ceil(n_samples / self.hop_length) * self.hop_length)
|
| 195 |
+
hop = self.get_output_length(n_samples)
|
| 196 |
+
|
| 197 |
+
codes = []
|
| 198 |
+
range_fn = range if not verbose else tqdm.trange
|
| 199 |
+
|
| 200 |
+
for i in range_fn(0, nt, hop):
|
| 201 |
+
x = audio_signal[..., i : i + n_samples]
|
| 202 |
+
x = x.zero_pad(0, max(0, n_samples - x.shape[-1]))
|
| 203 |
+
|
| 204 |
+
audio_data = x.audio_data.to(self.device)
|
| 205 |
+
audio_data = self.preprocess(audio_data, self.sample_rate)
|
| 206 |
+
_, c, _, _, _ = self.encode(audio_data, n_quantizers)
|
| 207 |
+
codes.append(c.to(original_device))
|
| 208 |
+
chunk_length = c.shape[-1]
|
| 209 |
+
|
| 210 |
+
codes = torch.cat(codes, dim=-1)
|
| 211 |
+
|
| 212 |
+
dac_file = DACFile(
|
| 213 |
+
codes=codes,
|
| 214 |
+
chunk_length=chunk_length,
|
| 215 |
+
original_length=original_length,
|
| 216 |
+
input_db=input_db,
|
| 217 |
+
channels=nac,
|
| 218 |
+
sample_rate=original_sr,
|
| 219 |
+
padding=self.padding,
|
| 220 |
+
dac_version=SUPPORTED_VERSIONS[-1],
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
if n_quantizers is not None:
|
| 224 |
+
codes = codes[:, :n_quantizers, :]
|
| 225 |
+
|
| 226 |
+
self.padding = original_padding
|
| 227 |
+
return dac_file
|
| 228 |
+
|
| 229 |
+
@torch.no_grad()
|
| 230 |
+
def decompress(
|
| 231 |
+
self,
|
| 232 |
+
obj: Union[str, Path, DACFile],
|
| 233 |
+
verbose: bool = False,
|
| 234 |
+
) -> AudioSignal:
|
| 235 |
+
"""Reconstruct audio from a given .dac file
|
| 236 |
+
|
| 237 |
+
Parameters
|
| 238 |
+
----------
|
| 239 |
+
obj : Union[str, Path, DACFile]
|
| 240 |
+
.dac file location or corresponding DACFile object.
|
| 241 |
+
verbose : bool, optional
|
| 242 |
+
Prints progress if True, by default False
|
| 243 |
+
|
| 244 |
+
Returns
|
| 245 |
+
-------
|
| 246 |
+
AudioSignal
|
| 247 |
+
Object with the reconstructed audio
|
| 248 |
+
"""
|
| 249 |
+
self.eval()
|
| 250 |
+
if isinstance(obj, (str, Path)):
|
| 251 |
+
obj = DACFile.load(obj)
|
| 252 |
+
|
| 253 |
+
original_padding = self.padding
|
| 254 |
+
self.padding = obj.padding
|
| 255 |
+
|
| 256 |
+
range_fn = range if not verbose else tqdm.trange
|
| 257 |
+
codes = obj.codes
|
| 258 |
+
original_device = codes.device
|
| 259 |
+
chunk_length = obj.chunk_length
|
| 260 |
+
recons = []
|
| 261 |
+
|
| 262 |
+
for i in range_fn(0, codes.shape[-1], chunk_length):
|
| 263 |
+
c = codes[..., i : i + chunk_length].to(self.device)
|
| 264 |
+
z = self.quantizer.from_codes(c)[0]
|
| 265 |
+
r = self.decode(z)
|
| 266 |
+
recons.append(r.to(original_device))
|
| 267 |
+
|
| 268 |
+
recons = torch.cat(recons, dim=-1)
|
| 269 |
+
recons = AudioSignal(recons, self.sample_rate)
|
| 270 |
+
|
| 271 |
+
resample_fn = recons.resample
|
| 272 |
+
loudness_fn = recons.loudness
|
| 273 |
+
|
| 274 |
+
# If audio is > 10 minutes long, use the ffmpeg versions
|
| 275 |
+
if recons.signal_duration >= 10 * 60 * 60:
|
| 276 |
+
resample_fn = recons.ffmpeg_resample
|
| 277 |
+
loudness_fn = recons.ffmpeg_loudness
|
| 278 |
+
|
| 279 |
+
recons.normalize(obj.input_db)
|
| 280 |
+
resample_fn(obj.sample_rate)
|
| 281 |
+
recons = recons[..., : obj.original_length]
|
| 282 |
+
loudness_fn()
|
| 283 |
+
recons.audio_data = recons.audio_data.reshape(-1, obj.channels, obj.original_length)
|
| 284 |
+
|
| 285 |
+
self.padding =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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from typing import List
|
| 3 |
+
from typing import Union
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
from audiotools import AudioSignal
|
| 8 |
+
from audiotools.ml import BaseModel
|
| 9 |
+
from torch import nn
|
| 10 |
+
|
| 11 |
+
from .base import CodecMixin
|
| 12 |
+
from dac.nn.layers import Snake1d
|
| 13 |
+
from dac.nn.layers import WNConv1d
|
| 14 |
+
from dac.nn.layers import WNConvTranspose1d
|
| 15 |
+
from dac.nn.quantize import ResidualVectorQuantize
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def init_weights(m):
|
| 19 |
+
if isinstance(m, nn.Conv1d):
|
| 20 |
+
nn.init.trunc_normal_(m.weight, std=0.02)
|
| 21 |
+
nn.init.constant_(m.bias, 0)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class ResidualUnit(nn.Module):
|
| 25 |
+
def __init__(self, dim: int = 16, dilation: int = 1):
|
| 26 |
+
super().__init__()
|
| 27 |
+
pad = ((7 - 1) * dilation) // 2
|
| 28 |
+
self.block = nn.Sequential(
|
| 29 |
+
Snake1d(dim),
|
| 30 |
+
WNConv1d(dim, dim, kernel_size=7, dilation=dilation, padding=pad),
|
| 31 |
+
Snake1d(dim),
|
| 32 |
+
WNConv1d(dim, dim, kernel_size=1),
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
def forward(self, x):
|
| 36 |
+
y = self.block(x)
|
| 37 |
+
pad = (x.shape[-1] - y.shape[-1]) // 2
|
| 38 |
+
if pad > 0:
|
| 39 |
+
x = x[..., pad:-pad]
|
| 40 |
+
return x + y
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class EncoderBlock(nn.Module):
|
| 44 |
+
def __init__(self, dim: int = 16, stride: int = 1):
|
| 45 |
+
super().__init__()
|
| 46 |
+
self.block = nn.Sequential(
|
| 47 |
+
ResidualUnit(dim // 2, dilation=1),
|
| 48 |
+
ResidualUnit(dim // 2, dilation=3),
|
| 49 |
+
ResidualUnit(dim // 2, dilation=9),
|
| 50 |
+
Snake1d(dim // 2),
|
| 51 |
+
WNConv1d(
|
| 52 |
+
dim // 2,
|
| 53 |
+
dim,
|
| 54 |
+
kernel_size=2 * stride,
|
| 55 |
+
stride=stride,
|
| 56 |
+
padding=math.ceil(stride / 2),
|
| 57 |
+
),
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
def forward(self, x):
|
| 61 |
+
return self.block(x)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class Encoder(nn.Module):
|
| 65 |
+
def __init__(
|
| 66 |
+
self,
|
| 67 |
+
d_model: int = 64,
|
| 68 |
+
strides: list = [2, 4, 8, 8],
|
| 69 |
+
d_latent: int = 256,
|
| 70 |
+
):
|
| 71 |
+
super().__init__()
|
| 72 |
+
# Create first convolution
|
| 73 |
+
self.block = [WNConv1d(1, d_model, kernel_size=7, padding=3)]
|
| 74 |
+
|
| 75 |
+
# Create EncoderBlocks that double channels as they downsample by `stride`
|
| 76 |
+
for stride in strides:
|
| 77 |
+
d_model *= 2
|
| 78 |
+
self.block += [EncoderBlock(d_model, stride=stride)]
|
| 79 |
+
|
| 80 |
+
# Create last convolution
|
| 81 |
+
self.block += [
|
| 82 |
+
Snake1d(d_model),
|
| 83 |
+
WNConv1d(d_model, d_latent, kernel_size=3, padding=1),
|
| 84 |
+
]
|
| 85 |
+
|
| 86 |
+
# Wrap black into nn.Sequential
|
| 87 |
+
self.block = nn.Sequential(*self.block)
|
| 88 |
+
self.enc_dim = d_model
|
| 89 |
+
|
| 90 |
+
def forward(self, x):
|
| 91 |
+
return self.block(x)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class DecoderBlock(nn.Module):
|
| 95 |
+
def __init__(self, input_dim: int = 16, output_dim: int = 8, stride: int = 1, out_pad=0):
|
| 96 |
+
super().__init__()
|
| 97 |
+
self.block = nn.Sequential(
|
| 98 |
+
Snake1d(input_dim),
|
| 99 |
+
WNConvTranspose1d(
|
| 100 |
+
input_dim,
|
| 101 |
+
output_dim,
|
| 102 |
+
kernel_size=2 * stride,
|
| 103 |
+
stride=stride,
|
| 104 |
+
padding=math.ceil(stride / 2),
|
| 105 |
+
output_padding=stride % 2, # out_pad,
|
| 106 |
+
),
|
| 107 |
+
ResidualUnit(output_dim, dilation=1),
|
| 108 |
+
ResidualUnit(output_dim, dilation=3),
|
| 109 |
+
ResidualUnit(output_dim, dilation=9),
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
def forward(self, x):
|
| 113 |
+
return self.block(x)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class Decoder(nn.Module):
|
| 117 |
+
def __init__(
|
| 118 |
+
self,
|
| 119 |
+
input_channel,
|
| 120 |
+
channels,
|
| 121 |
+
rates,
|
| 122 |
+
d_out: int = 1,
|
| 123 |
+
):
|
| 124 |
+
super().__init__()
|
| 125 |
+
|
| 126 |
+
# Add first conv layer
|
| 127 |
+
layers = [WNConv1d(input_channel, channels, kernel_size=7, padding=3)]
|
| 128 |
+
|
| 129 |
+
# Add upsampling + MRF blocks
|
| 130 |
+
for i, stride in enumerate(rates):
|
| 131 |
+
input_dim = channels // 2**i
|
| 132 |
+
output_dim = channels // 2 ** (i + 1)
|
| 133 |
+
if i == 1:
|
| 134 |
+
out_pad = 1
|
| 135 |
+
else:
|
| 136 |
+
out_pad = 0
|
| 137 |
+
layers += [DecoderBlock(input_dim, output_dim, stride, out_pad)]
|
| 138 |
+
|
| 139 |
+
# Add final conv layer
|
| 140 |
+
layers += [
|
| 141 |
+
Snake1d(output_dim),
|
| 142 |
+
WNConv1d(output_dim, d_out, kernel_size=7, padding=3),
|
| 143 |
+
# nn.Tanh(),
|
| 144 |
+
]
|
| 145 |
+
|
| 146 |
+
self.model = nn.Sequential(*layers)
|
| 147 |
+
|
| 148 |
+
def forward(self, x):
|
| 149 |
+
return self.model(x)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class DAC(BaseModel, CodecMixin):
|
| 153 |
+
def __init__(
|
| 154 |
+
self,
|
| 155 |
+
encoder_dim: int = 64,
|
| 156 |
+
encoder_rates: List[int] = [2, 4, 8, 8],
|
| 157 |
+
latent_dim: int = None,
|
| 158 |
+
decoder_dim: int = 1536,
|
| 159 |
+
decoder_rates: List[int] = [8, 8, 4, 2],
|
| 160 |
+
n_codebooks: int = 9,
|
| 161 |
+
codebook_size: int = 1024,
|
| 162 |
+
codebook_dim: Union[int, list] = 8,
|
| 163 |
+
quantizer_dropout: bool = False,
|
| 164 |
+
sample_rate: int = 44100,
|
| 165 |
+
):
|
| 166 |
+
super().__init__()
|
| 167 |
+
|
| 168 |
+
self.encoder_dim = encoder_dim
|
| 169 |
+
self.encoder_rates = encoder_rates
|
| 170 |
+
self.decoder_dim = decoder_dim
|
| 171 |
+
self.decoder_rates = decoder_rates
|
| 172 |
+
self.sample_rate = sample_rate
|
| 173 |
+
|
| 174 |
+
if latent_dim is None:
|
| 175 |
+
latent_dim = encoder_dim * (2 ** len(encoder_rates))
|
| 176 |
+
|
| 177 |
+
self.latent_dim = latent_dim
|
| 178 |
+
|
| 179 |
+
self.hop_length = np.prod(encoder_rates)
|
| 180 |
+
self.encoder = Encoder(encoder_dim, encoder_rates, latent_dim)
|
| 181 |
+
|
| 182 |
+
self.n_codebooks = n_codebooks
|
| 183 |
+
self.codebook_size = codebook_size
|
| 184 |
+
self.codebook_dim = codebook_dim
|
| 185 |
+
self.quantizer = ResidualVectorQuantize(
|
| 186 |
+
input_dim=latent_dim,
|
| 187 |
+
n_codebooks=n_codebooks,
|
| 188 |
+
codebook_size=codebook_size,
|
| 189 |
+
codebook_dim=codebook_dim,
|
| 190 |
+
quantizer_dropout=quantizer_dropout,
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
self.decoder = Decoder(
|
| 194 |
+
latent_dim,
|
| 195 |
+
decoder_dim,
|
| 196 |
+
decoder_rates,
|
| 197 |
+
)
|
| 198 |
+
self.sample_rate = sample_rate
|
| 199 |
+
self.apply(init_weights)
|
| 200 |
+
|
| 201 |
+
self.delay = self.get_delay()
|
| 202 |
+
|
| 203 |
+
def preprocess(self, audio_data, sample_rate):
|
| 204 |
+
if sample_rate is None:
|
| 205 |
+
sample_rate = self.sample_rate
|
| 206 |
+
assert sample_rate == self.sample_rate
|
| 207 |
+
|
| 208 |
+
length = audio_data.shape[-1]
|
| 209 |
+
right_pad = math.ceil(length / self.hop_length) * self.hop_length - length
|
| 210 |
+
audio_data = nn.functional.pad(audio_data, (0, right_pad))
|
| 211 |
+
|
| 212 |
+
return audio_data
|
| 213 |
+
|
| 214 |
+
def encode(
|
| 215 |
+
self,
|
| 216 |
+
audio_data: torch.Tensor,
|
| 217 |
+
n_quantizers: int = None,
|
| 218 |
+
):
|
| 219 |
+
"""Encode given audio data and return quantized latent codes
|
| 220 |
+
|
| 221 |
+
Parameters
|
| 222 |
+
----------
|
| 223 |
+
audio_data : Tensor[B x 1 x T]
|
| 224 |
+
Audio data to encode
|
| 225 |
+
n_quantizers : int, optional
|
| 226 |
+
Number of quantizers to use, by default None
|
| 227 |
+
If None, all quantizers are used.
|
| 228 |
+
|
| 229 |
+
Returns
|
| 230 |
+
-------
|
| 231 |
+
dict
|
| 232 |
+
A dictionary with the following keys:
|
| 233 |
+
"z" : Tensor[B x D x T]
|
| 234 |
+
Quantized continuous representation of input
|
| 235 |
+
"codes" : Tensor[B x N x T]
|
| 236 |
+
Codebook indices for each codebook
|
| 237 |
+
(quantized discrete representation of input)
|
| 238 |
+
"latents" : Tensor[B x N*D x T]
|
| 239 |
+
Projected latents (continuous representation of input before quantization)
|
| 240 |
+
"vq/commitment_loss" : Tensor[1]
|
| 241 |
+
Commitment loss to train encoder to predict vectors closer to codebook
|
| 242 |
+
entries
|
| 243 |
+
"vq/codebook_loss" : Tensor[1]
|
| 244 |
+
Codebook loss to update the codebook
|
| 245 |
+
"length" : int
|
| 246 |
+
Number of samples in input audio
|
| 247 |
+
"""
|
| 248 |
+
z = self.encoder(audio_data)
|
| 249 |
+
z, codes, latents, commitment_loss, codebook_loss = self.quantizer(z, n_quantizers)
|
| 250 |
+
return z, codes, latents, commitment_loss, codebook_loss
|
| 251 |
+
|
| 252 |
+
def decode(self, z: torch.Tensor):
|
| 253 |
+
"""Decode given latent codes and return audio data
|
| 254 |
+
|
| 255 |
+
Parameters
|
| 256 |
+
----------
|
| 257 |
+
z : Tensor[B x D x T]
|
| 258 |
+
Quantized continuous representation of input
|
| 259 |
+
length : int, optional
|
| 260 |
+
Number of samples in output audio, by default None
|
| 261 |
+
|
| 262 |
+
Returns
|
| 263 |
+
-------
|
| 264 |
+
dict
|
| 265 |
+
A dictionary with the following keys:
|
| 266 |
+
"audio" : Tensor[B x 1 x length]
|
| 267 |
+
Decoded audio data.
|
| 268 |
+
"""
|
| 269 |
+
return self.decoder(z)
|
| 270 |
+
|
| 271 |
+
def forward(
|
| 272 |
+
self,
|
| 273 |
+
audio_data: torch.Tensor,
|
| 274 |
+
sample_rate: int = None,
|
| 275 |
+
n_quantizers: int = None,
|
| 276 |
+
):
|
| 277 |
+
"""Model forward pass
|
| 278 |
+
|
| 279 |
+
Parameters
|
| 280 |
+
----------
|
| 281 |
+
audio_data : Tensor[B x 1 x T]
|
| 282 |
+
Audio data to encode
|
| 283 |
+
sample_rate : int, optional
|
| 284 |
+
Sample rate of audio data in Hz, by default None
|
| 285 |
+
If None, defaults to `self.sample_rate`
|
| 286 |
+
n_quantizers : int, optional
|
| 287 |
+
Number of quantizers to use, by default None.
|
| 288 |
+
If None, all quantizers are used.
|
| 289 |
+
|
| 290 |
+
Returns
|
| 291 |
+
-------
|
| 292 |
+
dict
|
| 293 |
+
A dictionary with the following keys:
|
| 294 |
+
"z" : Tensor[B x D x T]
|
| 295 |
+
Quantized continuous representation of input
|
| 296 |
+
"codes" : Tensor[B x N x T]
|
| 297 |
+
Codebook indices for each codebook
|
| 298 |
+
(quantized discrete representation of input)
|
| 299 |
+
"latents" : Tensor[B x N*D x T]
|
| 300 |
+
Projected latents (continuous representation of input before quantization)
|
| 301 |
+
"vq/commitment_loss" : Tensor[1]
|
| 302 |
+
Commitment loss to train encoder to predict vectors closer to codebook
|
| 303 |
+
entries
|
| 304 |
+
"vq/codebook_loss" : Tensor[1]
|
| 305 |
+
Codebook loss to update the codebook
|
| 306 |
+
"length" : int
|
| 307 |
+
Number of samples in input audio
|
| 308 |
+
"audio" : Tensor[B x 1 x length]
|
| 309 |
+
Decoded audio data.
|
| 310 |
+
"""
|
| 311 |
+
length = audio_data.shape[-1]
|
| 312 |
+
audio_data = self.preprocess(audio_data, sample_rate)
|
| 313 |
+
z, codes, latents, commitment_loss, codebook_loss = self.encode(audio_data, n_quantizers)
|
| 314 |
+
|
| 315 |
+
x = self.decode(z)
|
| 316 |
+
return {
|
| 317 |
+
"audio": x[..., :length],
|
| 318 |
+
"z": z,
|
| 319 |
+
"codes": codes,
|
| 320 |
+
"latents": latents,
|
| 321 |
+
"vq/commitment_loss": commitment_loss,
|
| 322 |
+
"vq/codebook_loss": codebook_loss,
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
if __name__ == "__main__":
|
| 327 |
+
import numpy as np
|
| 328 |
+
from functools import partial
|
| 329 |
+
|
| 330 |
+
model = DAC().to("cpu")
|
| 331 |
+
|
| 332 |
+
for n, m in model.named_modules():
|
| 333 |
+
o = m.extra_repr()
|
| 334 |
+
p = sum([np.prod(p.size()) for p in m.parameters()])
|
| 335 |
+
fn = lambda o, p: o + f" {p / 1e6:<.3f}M params."
|
| 336 |
+
setattr(m, "extra_repr", partial(fn, o=o, p=p))
|
| 337 |
+
print(model)
|
| 338 |
+
print("Total # of params: ", sum([np.prod(p.size()) for p in model.parameters()]))
|
| 339 |
+
|
| 340 |
+
length = 88200 * 2
|
| 341 |
+
x = torch.randn(1, 1, length).to(model.device)
|
| 342 |
+
x.requires_grad_(True)
|
| 343 |
+
x.retain_grad()
|
| 344 |
+
|
| 345 |
+
# Make a forward pass
|
| 346 |
+
out = model(x)["audio"]
|
| 347 |
+
print("Input shape:", x.shape)
|
| 348 |
+
print("Output shape:", out.shape)
|
| 349 |
+
|
| 350 |
+
# Create gradient variable
|
| 351 |
+
grad = torch.zeros_like(out)
|
| 352 |
+
grad[:, :, grad.shape[-1] // 2] = 1
|
| 353 |
+
|
| 354 |
+
# Make a backward pass
|
| 355 |
+
out.backward(grad)
|
| 356 |
+
|
| 357 |
+
# Check non-zero values
|
| 358 |
+
gradmap = x.grad.squeeze(0)
|
| 359 |
+
gradmap = (gradmap != 0).sum(0) # sum across features
|
| 360 |
+
rf = (gradmap != 0).sum()
|
| 361 |
+
|
| 362 |
+
print(f"Receptive field: {rf.item()}")
|
| 363 |
+
|
| 364 |
+
x = AudioSignal(torch.randn(1, 1, 44100 * 60), 44100)
|
| 365 |
+
model.decompress(model.compress(x, verbose=True), verbose=True)
|
codec/audio_processing/descriptaudiocodec/dac/nn/layers.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from einops import rearrange
|
| 6 |
+
from torch.nn.utils import weight_norm
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def WNConv1d(*args, **kwargs):
|
| 10 |
+
return weight_norm(nn.Conv1d(*args, **kwargs))
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def WNConvTranspose1d(*args, **kwargs):
|
| 14 |
+
return weight_norm(nn.ConvTranspose1d(*args, **kwargs))
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# Scripting this brings model speed up 1.4x
|
| 18 |
+
@torch.jit.script
|
| 19 |
+
def snake(x, alpha):
|
| 20 |
+
shape = x.shape
|
| 21 |
+
x = x.reshape(shape[0], shape[1], -1)
|
| 22 |
+
x = x + (alpha + 1e-9).reciprocal() * torch.sin(alpha * x).pow(2)
|
| 23 |
+
x = x.reshape(shape)
|
| 24 |
+
return x
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class Snake1d(nn.Module):
|
| 28 |
+
def __init__(self, channels):
|
| 29 |
+
super().__init__()
|
| 30 |
+
self.alpha = nn.Parameter(torch.ones(1, channels, 1))
|
| 31 |
+
|
| 32 |
+
def forward(self, x):
|
| 33 |
+
return snake(x, self.alpha)
|
codec/audio_processing/descriptaudiocodec/dac/nn/quantize.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Union
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from einops import rearrange
|
| 8 |
+
from torch.nn.utils import weight_norm
|
| 9 |
+
|
| 10 |
+
from dac.nn.layers import WNConv1d
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class VectorQuantize(nn.Module):
|
| 14 |
+
"""
|
| 15 |
+
Implementation of VQ similar to Karpathy's repo:
|
| 16 |
+
https://github.com/karpathy/deep-vector-quantization
|
| 17 |
+
Additionally uses following tricks from Improved VQGAN
|
| 18 |
+
(https://arxiv.org/pdf/2110.04627.pdf):
|
| 19 |
+
1. Factorized codes: Perform nearest neighbor lookup in low-dimensional space
|
| 20 |
+
for improved codebook usage
|
| 21 |
+
2. l2-normalized codes: Converts euclidean distance to cosine similarity which
|
| 22 |
+
improves training stability
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init__(self, input_dim: int, codebook_size: int, codebook_dim: int):
|
| 26 |
+
super().__init__()
|
| 27 |
+
self.codebook_size = codebook_size
|
| 28 |
+
self.codebook_dim = codebook_dim
|
| 29 |
+
|
| 30 |
+
self.in_proj = WNConv1d(input_dim, codebook_dim, kernel_size=1)
|
| 31 |
+
self.out_proj = WNConv1d(codebook_dim, input_dim, kernel_size=1)
|
| 32 |
+
self.codebook = nn.Embedding(codebook_size, codebook_dim)
|
| 33 |
+
|
| 34 |
+
def forward(self, z):
|
| 35 |
+
"""Quantized the input tensor using a fixed codebook and returns
|
| 36 |
+
the corresponding codebook vectors
|
| 37 |
+
|
| 38 |
+
Parameters
|
| 39 |
+
----------
|
| 40 |
+
z : Tensor[B x D x T]
|
| 41 |
+
|
| 42 |
+
Returns
|
| 43 |
+
-------
|
| 44 |
+
Tensor[B x D x T]
|
| 45 |
+
Quantized continuous representation of input
|
| 46 |
+
Tensor[1]
|
| 47 |
+
Commitment loss to train encoder to predict vectors closer to codebook
|
| 48 |
+
entries
|
| 49 |
+
Tensor[1]
|
| 50 |
+
Codebook loss to update the codebook
|
| 51 |
+
Tensor[B x T]
|
| 52 |
+
Codebook indices (quantized discrete representation of input)
|
| 53 |
+
Tensor[B x D x T]
|
| 54 |
+
Projected latents (continuous representation of input before quantization)
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
# Factorized codes (ViT-VQGAN) Project input into low-dimensional space
|
| 58 |
+
z_e = self.in_proj(z) # z_e : (B x D x T)
|
| 59 |
+
z_q, indices = self.decode_latents(z_e)
|
| 60 |
+
|
| 61 |
+
commitment_loss = F.mse_loss(z_e, z_q.detach(), reduction="none").mean([1, 2])
|
| 62 |
+
codebook_loss = F.mse_loss(z_q, z_e.detach(), reduction="none").mean([1, 2])
|
| 63 |
+
|
| 64 |
+
z_q = z_e + (z_q - z_e).detach() # noop in forward pass, straight-through gradient estimator in backward pass
|
| 65 |
+
|
| 66 |
+
z_q = self.out_proj(z_q)
|
| 67 |
+
|
| 68 |
+
return z_q, commitment_loss, codebook_loss, indices, z_e
|
| 69 |
+
|
| 70 |
+
def embed_code(self, embed_id):
|
| 71 |
+
return F.embedding(embed_id, self.codebook.weight)
|
| 72 |
+
|
| 73 |
+
def decode_code(self, embed_id):
|
| 74 |
+
return self.embed_code(embed_id).transpose(1, 2)
|
| 75 |
+
|
| 76 |
+
def decode_latents(self, latents):
|
| 77 |
+
encodings = rearrange(latents, "b d t -> (b t) d")
|
| 78 |
+
codebook = self.codebook.weight # codebook: (N x D)
|
| 79 |
+
|
| 80 |
+
# L2 normalize encodings and codebook (ViT-VQGAN)
|
| 81 |
+
encodings = F.normalize(encodings)
|
| 82 |
+
codebook = F.normalize(codebook)
|
| 83 |
+
|
| 84 |
+
# Compute euclidean distance with codebook
|
| 85 |
+
dist = (
|
| 86 |
+
encodings.pow(2).sum(1, keepdim=True)
|
| 87 |
+
- 2 * encodings @ codebook.t()
|
| 88 |
+
+ codebook.pow(2).sum(1, keepdim=True).t()
|
| 89 |
+
)
|
| 90 |
+
indices = rearrange((-dist).max(1)[1], "(b t) -> b t", b=latents.size(0))
|
| 91 |
+
z_q = self.decode_code(indices)
|
| 92 |
+
return z_q, indices
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class ResidualVectorQuantize(nn.Module):
|
| 96 |
+
"""
|
| 97 |
+
Introduced in SoundStream: An end2end neural audio codec
|
| 98 |
+
https://arxiv.org/abs/2107.03312
|
| 99 |
+
"""
|
| 100 |
+
|
| 101 |
+
def __init__(
|
| 102 |
+
self,
|
| 103 |
+
input_dim: int = 512,
|
| 104 |
+
n_codebooks: int = 9,
|
| 105 |
+
codebook_size: int = 1024,
|
| 106 |
+
codebook_dim: Union[int, list] = 8,
|
| 107 |
+
quantizer_dropout: float = 0.0,
|
| 108 |
+
):
|
| 109 |
+
super().__init__()
|
| 110 |
+
if isinstance(codebook_dim, int):
|
| 111 |
+
codebook_dim = [codebook_dim for _ in range(n_codebooks)]
|
| 112 |
+
|
| 113 |
+
self.n_codebooks = n_codebooks
|
| 114 |
+
self.codebook_dim = codebook_dim
|
| 115 |
+
self.codebook_size = codebook_size
|
| 116 |
+
|
| 117 |
+
self.quantizers = nn.ModuleList(
|
| 118 |
+
[VectorQuantize(input_dim, codebook_size, codebook_dim[i]) for i in range(n_codebooks)]
|
| 119 |
+
)
|
| 120 |
+
self.quantizer_dropout = quantizer_dropout
|
| 121 |
+
|
| 122 |
+
def forward(self, z, n_quantizers: int = None):
|
| 123 |
+
"""Quantized the input tensor using a fixed set of `n` codebooks and returns
|
| 124 |
+
the corresponding codebook vectors
|
| 125 |
+
Parameters
|
| 126 |
+
----------
|
| 127 |
+
z : Tensor[B x D x T]
|
| 128 |
+
n_quantizers : int, optional
|
| 129 |
+
No. of quantizers to use
|
| 130 |
+
(n_quantizers < self.n_codebooks ex: for quantizer dropout)
|
| 131 |
+
Note: if `self.quantizer_dropout` is True, this argument is ignored
|
| 132 |
+
when in training mode, and a random number of quantizers is used.
|
| 133 |
+
Returns
|
| 134 |
+
-------
|
| 135 |
+
dict
|
| 136 |
+
A dictionary with the following keys:
|
| 137 |
+
|
| 138 |
+
"z" : Tensor[B x D x T]
|
| 139 |
+
Quantized continuous representation of input
|
| 140 |
+
"codes" : Tensor[B x N x T]
|
| 141 |
+
Codebook indices for each codebook
|
| 142 |
+
(quantized discrete representation of input)
|
| 143 |
+
"latents" : Tensor[B x N*D x T]
|
| 144 |
+
Projected latents (continuous representation of input before quantization)
|
| 145 |
+
"vq/commitment_loss" : Tensor[1]
|
| 146 |
+
Commitment loss to train encoder to predict vectors closer to codebook
|
| 147 |
+
entries
|
| 148 |
+
"vq/codebook_loss" : Tensor[1]
|
| 149 |
+
Codebook loss to update the codebook
|
| 150 |
+
"""
|
| 151 |
+
z_q = 0
|
| 152 |
+
residual = z
|
| 153 |
+
commitment_loss = 0
|
| 154 |
+
codebook_loss = 0
|
| 155 |
+
|
| 156 |
+
codebook_indices = []
|
| 157 |
+
latents = []
|
| 158 |
+
|
| 159 |
+
if n_quantizers is None:
|
| 160 |
+
n_quantizers = self.n_codebooks
|
| 161 |
+
if self.training:
|
| 162 |
+
n_quantizers = torch.ones((z.shape[0],)) * self.n_codebooks + 1
|
| 163 |
+
dropout = torch.randint(1, self.n_codebooks + 1, (z.shape[0],))
|
| 164 |
+
n_dropout = int(z.shape[0] * self.quantizer_dropout)
|
| 165 |
+
n_quantizers[:n_dropout] = dropout[:n_dropout]
|
| 166 |
+
n_quantizers = n_quantizers.to(z.device)
|
| 167 |
+
|
| 168 |
+
for i, quantizer in enumerate(self.quantizers):
|
| 169 |
+
if self.training is False and i >= n_quantizers:
|
| 170 |
+
break
|
| 171 |
+
|
| 172 |
+
z_q_i, commitment_loss_i, codebook_loss_i, indices_i, z_e_i = quantizer(residual)
|
| 173 |
+
|
| 174 |
+
# Create mask to apply quantizer dropout
|
| 175 |
+
mask = torch.full((z.shape[0],), fill_value=i, device=z.device) < n_quantizers
|
| 176 |
+
z_q = z_q + z_q_i * mask[:, None, None]
|
| 177 |
+
residual = residual - z_q_i
|
| 178 |
+
|
| 179 |
+
# Sum losses
|
| 180 |
+
commitment_loss += (commitment_loss_i * mask).mean()
|
| 181 |
+
codebook_loss += (codebook_loss_i * mask).mean()
|
| 182 |
+
|
| 183 |
+
codebook_indices.append(indices_i)
|
| 184 |
+
latents.append(z_e_i)
|
| 185 |
+
|
| 186 |
+
codes = torch.stack(codebook_indices, dim=1)
|
| 187 |
+
latents = torch.cat(latents, dim=1)
|
| 188 |
+
|
| 189 |
+
return z_q, codes, latents, commitment_loss, codebook_loss
|
| 190 |
+
|
| 191 |
+
def from_codes(self, codes: torch.Tensor):
|
| 192 |
+
"""Given the quantized codes, reconstruct the continuous representation
|
| 193 |
+
Parameters
|
| 194 |
+
----------
|
| 195 |
+
codes : Tensor[B x N x T]
|
| 196 |
+
Quantized discrete representation of input
|
| 197 |
+
Returns
|
| 198 |
+
-------
|
| 199 |
+
Tensor[B x D x T]
|
| 200 |
+
Quantized continuous representation of input
|
| 201 |
+
"""
|
| 202 |
+
z_q = 0.0
|
| 203 |
+
z_p = []
|
| 204 |
+
n_codebooks = codes.shape[1]
|
| 205 |
+
for i in range(n_codebooks):
|
| 206 |
+
z_p_i = self.quantizers[i].decode_code(codes[:, i, :])
|
| 207 |
+
z_p.append(z_p_i)
|
| 208 |
+
|
| 209 |
+
z_q_i = self.quantizers[i].out_proj(z_p_i)
|
| 210 |
+
z_q = z_q + z_q_i
|
| 211 |
+
return z_q, torch.cat(z_p, dim=1), codes
|
| 212 |
+
|
| 213 |
+
def from_latents(self, latents: torch.Tensor):
|
| 214 |
+
"""Given the unquantized latents, reconstruct the
|
| 215 |
+
continuous representation after quantization.
|
| 216 |
+
|
| 217 |
+
Parameters
|
| 218 |
+
----------
|
| 219 |
+
latents : Tensor[B x N x T]
|
| 220 |
+
Continuous representation of input after projection
|
| 221 |
+
|
| 222 |
+
Returns
|
| 223 |
+
-------
|
| 224 |
+
Tensor[B x D x T]
|
| 225 |
+
Quantized representation of full-projected space
|
| 226 |
+
Tensor[B x D x T]
|
| 227 |
+
Quantized representation of latent space
|
| 228 |
+
"""
|
| 229 |
+
z_q = 0
|
| 230 |
+
z_p = []
|
| 231 |
+
codes = []
|
| 232 |
+
dims = np.cumsum([0] + [q.codebook_dim for q in self.quantizers])
|
| 233 |
+
|
| 234 |
+
n_codebooks = np.where(dims <= latents.shape[1])[0].max(axis=0, keepdims=True)[0]
|
| 235 |
+
for i in range(n_codebooks):
|
| 236 |
+
j, k = dims[i], dims[i + 1]
|
| 237 |
+
z_p_i, codes_i = self.quantizers[i].decode_latents(latents[:, j:k, :])
|
| 238 |
+
z_p.append(z_p_i)
|
| 239 |
+
codes.append(codes_i)
|
| 240 |
+
|
| 241 |
+
z_q_i = self.quantizers[i].out_proj(z_p_i)
|
| 242 |
+
z_q = z_q + z_q_i
|
| 243 |
+
|
| 244 |
+
return z_q, torch.cat(z_p, dim=1), torch.stack(codes, dim=1)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
if __name__ == "__main__":
|
| 248 |
+
rvq = ResidualVectorQuantize(quantizer_dropout=True)
|
| 249 |
+
x = torch.randn(16, 512, 80)
|
| 250 |
+
y = rvq(x)
|
| 251 |
+
print(y["latents"].shape)
|
codec/audio_processing/dune_codec.py
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import contextlib
|
| 2 |
+
import inspect
|
| 3 |
+
import json
|
| 4 |
+
import logging
|
| 5 |
+
import math
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
import librosa
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
import torchaudio
|
| 14 |
+
from huggingface_hub import snapshot_download
|
| 15 |
+
from nemo.collections.tts.models import AudioCodecModel
|
| 16 |
+
import pyloudnorm as pyln
|
| 17 |
+
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def WNConv1d(*args, **kwargs):
|
| 22 |
+
return nn.utils.weight_norm(nn.Conv1d(*args, **kwargs))
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def WNConvTranspose1d(*args, **kwargs):
|
| 26 |
+
return nn.utils.weight_norm(nn.ConvTranspose1d(*args, **kwargs))
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class Snake1d(nn.Module):
|
| 30 |
+
def __init__(self, channels):
|
| 31 |
+
super().__init__()
|
| 32 |
+
self.alpha = nn.Parameter(torch.ones(1, channels, 1))
|
| 33 |
+
|
| 34 |
+
def forward(self, x):
|
| 35 |
+
return x + (1.0 / (self.alpha + 1e-9)) * torch.sin(self.alpha * x).pow(2)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class ResidualUnit(nn.Module):
|
| 39 |
+
def __init__(self, dim=16, dilation=1):
|
| 40 |
+
super().__init__()
|
| 41 |
+
pad = ((7 - 1) * dilation) // 2
|
| 42 |
+
self.block = nn.Sequential(
|
| 43 |
+
Snake1d(dim),
|
| 44 |
+
WNConv1d(dim, dim, kernel_size=7, dilation=dilation, padding=pad),
|
| 45 |
+
Snake1d(dim),
|
| 46 |
+
WNConv1d(dim, dim, kernel_size=1),
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
def forward(self, x):
|
| 50 |
+
y = self.block(x)
|
| 51 |
+
pad = (x.shape[-1] - y.shape[-1]) // 2
|
| 52 |
+
if pad > 0:
|
| 53 |
+
x = x[..., pad:-pad]
|
| 54 |
+
return x + y
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class DACDecoderBlock(nn.Module):
|
| 58 |
+
def __init__(self, input_dim=16, output_dim=8, stride=1):
|
| 59 |
+
super().__init__()
|
| 60 |
+
self.block = nn.Sequential(
|
| 61 |
+
Snake1d(input_dim),
|
| 62 |
+
WNConvTranspose1d(
|
| 63 |
+
input_dim,
|
| 64 |
+
output_dim,
|
| 65 |
+
kernel_size=2 * stride,
|
| 66 |
+
stride=stride,
|
| 67 |
+
padding=math.ceil(stride / 2),
|
| 68 |
+
output_padding=stride % 2,
|
| 69 |
+
),
|
| 70 |
+
ResidualUnit(output_dim, dilation=1),
|
| 71 |
+
ResidualUnit(output_dim, dilation=3),
|
| 72 |
+
ResidualUnit(output_dim, dilation=9),
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
def forward(self, x):
|
| 76 |
+
return self.block(x)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class DACStyleDecoder(nn.Module):
|
| 80 |
+
def __init__(self, input_channels, decoder_dim, upsample_rates, d_out=1):
|
| 81 |
+
super().__init__()
|
| 82 |
+
|
| 83 |
+
layers = [WNConv1d(input_channels, decoder_dim, kernel_size=7, padding=3)]
|
| 84 |
+
for i, stride in enumerate(upsample_rates):
|
| 85 |
+
layers.append(
|
| 86 |
+
DACDecoderBlock(decoder_dim // (2 ** i), decoder_dim // (2 ** (i + 1)), stride)
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
final_dim = decoder_dim // (2 ** len(upsample_rates))
|
| 90 |
+
layers += [
|
| 91 |
+
Snake1d(final_dim),
|
| 92 |
+
WNConv1d(final_dim, d_out, kernel_size=7, padding=3),
|
| 93 |
+
nn.Tanh(),
|
| 94 |
+
]
|
| 95 |
+
|
| 96 |
+
self.model = nn.Sequential(*layers)
|
| 97 |
+
|
| 98 |
+
def forward(self, x):
|
| 99 |
+
return self.model(x)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class DuneAudioTokenizer(nn.Module):
|
| 103 |
+
def __init__(
|
| 104 |
+
self,
|
| 105 |
+
nemo_model="nvidia/nemo-nano-codec-22khz-1.78kbps-12.5fps", # i only borrow its encoder as training a codec encoder (even FSQ) from scratch is a pain in the 🍑
|
| 106 |
+
sample_rate=44100,
|
| 107 |
+
encoder_sample_rate=None,
|
| 108 |
+
output_sample_rate=None,
|
| 109 |
+
latent_dim=52,
|
| 110 |
+
upsample_ratio=None,
|
| 111 |
+
decoder_dim=1024,
|
| 112 |
+
device="cuda",
|
| 113 |
+
**kwargs,
|
| 114 |
+
):
|
| 115 |
+
super().__init__()
|
| 116 |
+
|
| 117 |
+
self.device = device
|
| 118 |
+
self.nemo_model = nemo_model
|
| 119 |
+
|
| 120 |
+
self.codec = AudioCodecModel.from_pretrained(nemo_model)
|
| 121 |
+
self.codec.to(device)
|
| 122 |
+
self.codec.eval()
|
| 123 |
+
|
| 124 |
+
self.encoder_sample_rate = int(getattr(self.codec, "sample_rate", None) or encoder_sample_rate)
|
| 125 |
+
self.samples_per_frame_in = int(
|
| 126 |
+
getattr(self.codec, "samples_per_frame", None) or self._infer_samples_per_frame_in()
|
| 127 |
+
)
|
| 128 |
+
self.frame_rate = self.encoder_sample_rate / self.samples_per_frame_in
|
| 129 |
+
|
| 130 |
+
self.output_sample_rate = int(output_sample_rate or sample_rate)
|
| 131 |
+
self.samples_per_frame_out = self._compute_samples_per_frame_out()
|
| 132 |
+
|
| 133 |
+
self.latent_dim = int(latent_dim)
|
| 134 |
+
self._backbone_frozen = False
|
| 135 |
+
|
| 136 |
+
if upsample_ratio:
|
| 137 |
+
self.upsample_ratio = list(upsample_ratio)
|
| 138 |
+
elif self.output_sample_rate == self.encoder_sample_rate:
|
| 139 |
+
self.upsample_ratio = []
|
| 140 |
+
else:
|
| 141 |
+
sr_ratio = self.output_sample_rate // self.encoder_sample_rate
|
| 142 |
+
self.upsample_ratio = list(self._infer_codec_upsample_rates()) + [sr_ratio]
|
| 143 |
+
|
| 144 |
+
self.is_upsampling_model = bool(self.upsample_ratio)
|
| 145 |
+
|
| 146 |
+
if not self.is_upsampling_model:
|
| 147 |
+
self.dac_decoder = None
|
| 148 |
+
else:
|
| 149 |
+
self._validate_upsample_ratio()
|
| 150 |
+
self.dac_decoder = DACStyleDecoder(
|
| 151 |
+
input_channels=self.latent_dim,
|
| 152 |
+
decoder_dim=decoder_dim,
|
| 153 |
+
upsample_rates=self.upsample_ratio,
|
| 154 |
+
d_out=1,
|
| 155 |
+
).to(device)
|
| 156 |
+
|
| 157 |
+
def _infer_samples_per_frame_in(self):
|
| 158 |
+
return int(np.prod([int(r) for r in self.codec.audio_encoder.down_sample_rates]))
|
| 159 |
+
|
| 160 |
+
def _infer_codec_upsample_rates(self):
|
| 161 |
+
return [int(r) for r in self.codec.audio_decoder.up_sample_rates]
|
| 162 |
+
|
| 163 |
+
def _compute_samples_per_frame_out(self):
|
| 164 |
+
num = self.output_sample_rate * self.samples_per_frame_in
|
| 165 |
+
if num % self.encoder_sample_rate != 0:
|
| 166 |
+
raise ValueError(
|
| 167 |
+
f"{self.output_sample_rate}Hz output is not reachable from "
|
| 168 |
+
f"{self.encoder_sample_rate}Hz at {self.samples_per_frame_in} samples/frame"
|
| 169 |
+
)
|
| 170 |
+
return int(num // self.encoder_sample_rate)
|
| 171 |
+
|
| 172 |
+
def _validate_upsample_ratio(self):
|
| 173 |
+
total = int(np.prod(self.upsample_ratio)) if self.upsample_ratio else 1
|
| 174 |
+
if total != self.samples_per_frame_out:
|
| 175 |
+
raise ValueError(
|
| 176 |
+
f"upsample_ratio product {total} != samples_per_frame_out "
|
| 177 |
+
f"{self.samples_per_frame_out}"
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
def _set_frozen_eval(self):
|
| 181 |
+
self.codec.audio_encoder.eval()
|
| 182 |
+
self.codec.vector_quantizer.eval()
|
| 183 |
+
|
| 184 |
+
def freeze_for_upsampling_finetune(self):
|
| 185 |
+
prefixes = ("dac_decoder",) if self.dac_decoder is not None else ("codec.audio_decoder",)
|
| 186 |
+
for name, param in self.named_parameters():
|
| 187 |
+
param.requires_grad = name.startswith(prefixes)
|
| 188 |
+
|
| 189 |
+
self._backbone_frozen = True
|
| 190 |
+
self._set_frozen_eval()
|
| 191 |
+
|
| 192 |
+
total = sum(p.numel() for p in self.parameters())
|
| 193 |
+
trainable = sum(p.numel() for p in self.parameters() if p.requires_grad)
|
| 194 |
+
logger.info(f"trainable {trainable / 1e6:.2f}M / {total / 1e6:.2f}M params")
|
| 195 |
+
|
| 196 |
+
def train(self, mode=True):
|
| 197 |
+
super().train(mode)
|
| 198 |
+
if self._backbone_frozen:
|
| 199 |
+
self._set_frozen_eval()
|
| 200 |
+
return self
|
| 201 |
+
|
| 202 |
+
@property
|
| 203 |
+
def tps(self):
|
| 204 |
+
return self.frame_rate
|
| 205 |
+
|
| 206 |
+
@property
|
| 207 |
+
def sampling_rate(self):
|
| 208 |
+
return self.output_sample_rate
|
| 209 |
+
|
| 210 |
+
def _maybe_no_grad(self):
|
| 211 |
+
return torch.no_grad() if self._backbone_frozen else contextlib.nullcontext()
|
| 212 |
+
|
| 213 |
+
def _dequantize(self, tokens, tokens_len):
|
| 214 |
+
return self.codec.dequantize(tokens=tokens, tokens_len=tokens_len)
|
| 215 |
+
|
| 216 |
+
def forward(self, x, bw=None):
|
| 217 |
+
target_length = x.shape[-1]
|
| 218 |
+
|
| 219 |
+
x_mono = x[:, 0, :] if x.dim() == 3 else x
|
| 220 |
+
|
| 221 |
+
if self.output_sample_rate != self.encoder_sample_rate:
|
| 222 |
+
x_enc = torchaudio.functional.resample(
|
| 223 |
+
x_mono, self.output_sample_rate, self.encoder_sample_rate
|
| 224 |
+
)
|
| 225 |
+
else:
|
| 226 |
+
x_enc = x_mono
|
| 227 |
+
|
| 228 |
+
audio_len = torch.full(
|
| 229 |
+
(x_enc.shape[0],), x_enc.shape[1], device=x_enc.device, dtype=torch.long
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
with self._maybe_no_grad():
|
| 233 |
+
tokens, tokens_len = self.codec.encode(audio=x_enc, audio_len=audio_len)
|
| 234 |
+
|
| 235 |
+
if self.dac_decoder is not None:
|
| 236 |
+
with self._maybe_no_grad():
|
| 237 |
+
dequant = self._dequantize(tokens, tokens_len)
|
| 238 |
+
o = self.dac_decoder(dequant)
|
| 239 |
+
else:
|
| 240 |
+
o, _ = self.codec.decode(tokens=tokens, tokens_len=tokens_len)
|
| 241 |
+
|
| 242 |
+
if o.dim() == 2:
|
| 243 |
+
o = o.unsqueeze(1)
|
| 244 |
+
|
| 245 |
+
if o.shape[-1] > target_length:
|
| 246 |
+
o = o[..., :target_length]
|
| 247 |
+
elif o.shape[-1] < target_length:
|
| 248 |
+
o = F.pad(o, (0, target_length - o.shape[-1]))
|
| 249 |
+
|
| 250 |
+
zero = torch.zeros((), device=x.device)
|
| 251 |
+
return o, zero, zero, None
|
| 252 |
+
|
| 253 |
+
def encode(self, audio_path_or_wv, sr=None, loudness_normalize=False, loudness_threshold=-23.0):
|
| 254 |
+
if isinstance(audio_path_or_wv, str):
|
| 255 |
+
wv, sr = librosa.load(audio_path_or_wv, mono=True, sr=None)
|
| 256 |
+
else:
|
| 257 |
+
wv = audio_path_or_wv
|
| 258 |
+
if sr is None:
|
| 259 |
+
raise ValueError("sr is required when passing a waveform")
|
| 260 |
+
|
| 261 |
+
if loudness_normalize:
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
meter = pyln.Meter(sr)
|
| 265 |
+
wv = pyln.normalize.loudness(wv, meter.integrated_loudness(wv), loudness_threshold)
|
| 266 |
+
|
| 267 |
+
if sr != self.encoder_sample_rate:
|
| 268 |
+
wv = librosa.resample(wv, orig_sr=sr, target_sr=self.encoder_sample_rate)
|
| 269 |
+
|
| 270 |
+
audio = torch.from_numpy(wv).float().unsqueeze(0).to(self.device)
|
| 271 |
+
audio_len = torch.tensor([audio.shape[-1]], device=self.device, dtype=torch.long)
|
| 272 |
+
|
| 273 |
+
with torch.no_grad():
|
| 274 |
+
tokens, _ = self.codec.encode(audio=audio, audio_len=audio_len)
|
| 275 |
+
|
| 276 |
+
return tokens[0]
|
| 277 |
+
|
| 278 |
+
def decode(self, vq_code):
|
| 279 |
+
tokens = vq_code if vq_code.dim() == 3 else vq_code.unsqueeze(0)
|
| 280 |
+
tokens = tokens.to(self.device)
|
| 281 |
+
tokens_len = torch.full(
|
| 282 |
+
(tokens.shape[0],), tokens.shape[-1], device=self.device, dtype=torch.long
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
with torch.no_grad():
|
| 286 |
+
if self.dac_decoder is not None:
|
| 287 |
+
audio = self.dac_decoder(self._dequantize(tokens, tokens_len))
|
| 288 |
+
if audio.dim() == 3:
|
| 289 |
+
audio = audio[:, 0, :]
|
| 290 |
+
else:
|
| 291 |
+
audio, _ = self.codec.decode(tokens=tokens, tokens_len=tokens_len)
|
| 292 |
+
|
| 293 |
+
return audio.cpu().numpy()
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _state_dict_from(ckpt):
|
| 297 |
+
state_dict = ckpt.get("model_state_dict") or ckpt.get("state_dict") or ckpt
|
| 298 |
+
out = {}
|
| 299 |
+
for key, value in state_dict.items():
|
| 300 |
+
for prefix in ("module.", "_orig_mod."):
|
| 301 |
+
if key.startswith(prefix):
|
| 302 |
+
key = key[len(prefix):]
|
| 303 |
+
out[key] = value
|
| 304 |
+
return out
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def _model_kwargs(cfg):
|
| 308 |
+
cfg = dict(cfg)
|
| 309 |
+
if "nemo_model" not in cfg and "nemo_model_name" in cfg:
|
| 310 |
+
cfg["nemo_model"] = cfg.pop("nemo_model_name")
|
| 311 |
+
|
| 312 |
+
accepted = set(inspect.signature(DuneAudioTokenizer.__init__).parameters)
|
| 313 |
+
return {k: v for k, v in cfg.items() if k in accepted - {"self", "device", "kwargs"}}
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def prepare(checkpoint_path, config_path=None, device="cuda", compile_after_load=False):
|
| 317 |
+
ckpt = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
|
| 318 |
+
|
| 319 |
+
cfg = ckpt.get("config")
|
| 320 |
+
if not isinstance(cfg, dict):
|
| 321 |
+
with open(config_path, "r") as f:
|
| 322 |
+
cfg = json.load(f)
|
| 323 |
+
|
| 324 |
+
model = DuneAudioTokenizer(**_model_kwargs(cfg), device=device).to(device)
|
| 325 |
+
|
| 326 |
+
missing, unexpected = model.load_state_dict(_state_dict_from(ckpt), strict=False)
|
| 327 |
+
logger.info(f"loaded {checkpoint_path} | missing={len(missing)} unexpected={len(unexpected)}")
|
| 328 |
+
|
| 329 |
+
model.eval()
|
| 330 |
+
if compile_after_load:
|
| 331 |
+
model = torch.compile(model, mode="default").eval()
|
| 332 |
+
|
| 333 |
+
return model
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def load_dune_audio_tokenizer(tokenizer_name_or_path, device="cuda"):
|
| 337 |
+
is_local = os.path.exists(tokenizer_name_or_path)
|
| 338 |
+
if not is_local:
|
| 339 |
+
tokenizer_path = snapshot_download(tokenizer_name_or_path)
|
| 340 |
+
else:
|
| 341 |
+
tokenizer_path = tokenizer_name_or_path
|
| 342 |
+
|
| 343 |
+
config_path = os.path.join(tokenizer_path, "config.json")
|
| 344 |
+
checkpoint_path = os.path.join(tokenizer_path, "model_209k.pth")
|
| 345 |
+
config = json.load(open(config_path))
|
| 346 |
+
|
| 347 |
+
model = prepare(checkpoint_path, config_path, device)
|
| 348 |
+
model.eval()
|
| 349 |
+
return model
|
codec/audio_processing/quantization/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# flake8: noqa
|
| 8 |
+
from .vq import QuantizedResult, ResidualVectorQuantizer
|
codec/audio_processing/quantization/ac.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""Arithmetic coder."""
|
| 8 |
+
|
| 9 |
+
import io
|
| 10 |
+
import math
|
| 11 |
+
import random
|
| 12 |
+
import typing as tp
|
| 13 |
+
import torch
|
| 14 |
+
|
| 15 |
+
from ..binary import BitPacker, BitUnpacker
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def build_stable_quantized_cdf(
|
| 19 |
+
pdf: torch.Tensor, total_range_bits: int, roundoff: float = 1e-8, min_range: int = 2, check: bool = True
|
| 20 |
+
) -> torch.Tensor:
|
| 21 |
+
"""Turn the given PDF into a quantized CDF that splits
|
| 22 |
+
[0, 2 ** self.total_range_bits - 1] into chunks of size roughly proportional
|
| 23 |
+
to the PDF.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
pdf (torch.Tensor): probability distribution, shape should be `[N]`.
|
| 27 |
+
total_range_bits (int): see `ArithmeticCoder`, the typical range we expect
|
| 28 |
+
during the coding process is `[0, 2 ** total_range_bits - 1]`.
|
| 29 |
+
roundoff (float): will round the pdf up to that level to remove difference coming
|
| 30 |
+
from e.g. evaluating the Language Model on different architectures.
|
| 31 |
+
min_range (int): minimum range width. Should always be at least 2 for numerical
|
| 32 |
+
stability. Use this to avoid pathological behavior is a value
|
| 33 |
+
that is expected to be rare actually happens in real life.
|
| 34 |
+
check (bool): if True, checks that nothing bad happened, can be deactivated for speed.
|
| 35 |
+
"""
|
| 36 |
+
pdf = pdf.detach()
|
| 37 |
+
if roundoff:
|
| 38 |
+
pdf = (pdf / roundoff).floor() * roundoff
|
| 39 |
+
# interpolate with uniform distribution to achieve desired minimum probability.
|
| 40 |
+
total_range = 2**total_range_bits
|
| 41 |
+
cardinality = len(pdf)
|
| 42 |
+
alpha = min_range * cardinality / total_range
|
| 43 |
+
assert alpha <= 1, "you must reduce min_range"
|
| 44 |
+
ranges = (((1 - alpha) * total_range) * pdf).floor().long()
|
| 45 |
+
ranges += min_range
|
| 46 |
+
quantized_cdf = torch.cumsum(ranges, dim=-1)
|
| 47 |
+
if min_range < 2:
|
| 48 |
+
raise ValueError("min_range must be at least 2.")
|
| 49 |
+
if check:
|
| 50 |
+
assert quantized_cdf[-1] <= 2**total_range_bits, quantized_cdf[-1]
|
| 51 |
+
if ((quantized_cdf[1:] - quantized_cdf[:-1]) < min_range).any() or quantized_cdf[0] < min_range:
|
| 52 |
+
raise ValueError("You must increase your total_range_bits.")
|
| 53 |
+
return quantized_cdf
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class ArithmeticCoder:
|
| 57 |
+
"""ArithmeticCoder,
|
| 58 |
+
Let us take a distribution `p` over `N` symbols, and assume we have a stream
|
| 59 |
+
of random variables `s_t` sampled from `p`. Let us assume that we have a budget
|
| 60 |
+
of `B` bits that we can afford to write on device. There are `2**B` possible numbers,
|
| 61 |
+
corresponding to the range `[0, 2 ** B - 1]`. We can map each of those number to a single
|
| 62 |
+
sequence `(s_t)` by doing the following:
|
| 63 |
+
|
| 64 |
+
1) Initialize the current range to` [0 ** 2 B - 1]`.
|
| 65 |
+
2) For each time step t, split the current range into contiguous chunks,
|
| 66 |
+
one for each possible outcome, with size roughly proportional to `p`.
|
| 67 |
+
For instance, if `p = [0.75, 0.25]`, and the range is `[0, 3]`, the chunks
|
| 68 |
+
would be `{[0, 2], [3, 3]}`.
|
| 69 |
+
3) Select the chunk corresponding to `s_t`, and replace the current range with this.
|
| 70 |
+
4) When done encoding all the values, just select any value remaining in the range.
|
| 71 |
+
|
| 72 |
+
You will notice that this procedure can fail: for instance if at any point in time
|
| 73 |
+
the range is smaller than `N`, then we can no longer assign a non-empty chunk to each
|
| 74 |
+
possible outcome. Intuitively, the more likely a value is, the less the range width
|
| 75 |
+
will reduce, and the longer we can go on encoding values. This makes sense: for any efficient
|
| 76 |
+
coding scheme, likely outcomes would take less bits, and more of them can be coded
|
| 77 |
+
with a fixed budget.
|
| 78 |
+
|
| 79 |
+
In practice, we do not know `B` ahead of time, but we have a way to inject new bits
|
| 80 |
+
when the current range decreases below a given limit (given by `total_range_bits`), without
|
| 81 |
+
having to redo all the computations. If we encode mostly likely values, we will seldom
|
| 82 |
+
need to inject new bits, but a single rare value can deplete our stock of entropy!
|
| 83 |
+
|
| 84 |
+
In this explanation, we assumed that the distribution `p` was constant. In fact, the present
|
| 85 |
+
code works for any sequence `(p_t)` possibly different for each timestep.
|
| 86 |
+
We also assume that `s_t ~ p_t`, but that doesn't need to be true, although the smaller
|
| 87 |
+
the KL between the true distribution and `p_t`, the most efficient the coding will be.
|
| 88 |
+
|
| 89 |
+
Args:
|
| 90 |
+
fo (IO[bytes]): file-like object to which the bytes will be written to.
|
| 91 |
+
total_range_bits (int): the range `M` described above is `2 ** total_range_bits.
|
| 92 |
+
Any time the current range width fall under this limit, new bits will
|
| 93 |
+
be injected to rescale the initial range.
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
def __init__(self, fo: tp.IO[bytes], total_range_bits: int = 24):
|
| 97 |
+
assert total_range_bits <= 30
|
| 98 |
+
self.total_range_bits = total_range_bits
|
| 99 |
+
self.packer = BitPacker(bits=1, fo=fo) # we push single bits at a time.
|
| 100 |
+
self.low: int = 0
|
| 101 |
+
self.high: int = 0
|
| 102 |
+
self.max_bit: int = -1
|
| 103 |
+
self._dbg: tp.List[tp.Any] = []
|
| 104 |
+
self._dbg2: tp.List[tp.Any] = []
|
| 105 |
+
|
| 106 |
+
@property
|
| 107 |
+
def delta(self) -> int:
|
| 108 |
+
"""Return the current range width."""
|
| 109 |
+
return self.high - self.low + 1
|
| 110 |
+
|
| 111 |
+
def _flush_common_prefix(self):
|
| 112 |
+
# If self.low and self.high start with the sames bits,
|
| 113 |
+
# those won't change anymore as we always just increase the range
|
| 114 |
+
# by powers of 2, and we can flush them out to the bit stream.
|
| 115 |
+
assert self.high >= self.low, (self.low, self.high)
|
| 116 |
+
assert self.high < 2 ** (self.max_bit + 1)
|
| 117 |
+
while self.max_bit >= 0:
|
| 118 |
+
b1 = self.low >> self.max_bit
|
| 119 |
+
b2 = self.high >> self.max_bit
|
| 120 |
+
if b1 == b2:
|
| 121 |
+
self.low -= b1 << self.max_bit
|
| 122 |
+
self.high -= b1 << self.max_bit
|
| 123 |
+
assert self.high >= self.low, (self.high, self.low, self.max_bit)
|
| 124 |
+
assert self.low >= 0
|
| 125 |
+
self.max_bit -= 1
|
| 126 |
+
self.packer.push(b1)
|
| 127 |
+
else:
|
| 128 |
+
break
|
| 129 |
+
|
| 130 |
+
def push(self, symbol: int, quantized_cdf: torch.Tensor):
|
| 131 |
+
"""Push the given symbol on the stream, flushing out bits
|
| 132 |
+
if possible.
|
| 133 |
+
|
| 134 |
+
Args:
|
| 135 |
+
symbol (int): symbol to encode with the AC.
|
| 136 |
+
quantized_cdf (torch.Tensor): use `build_stable_quantized_cdf`
|
| 137 |
+
to build this from your pdf estimate.
|
| 138 |
+
"""
|
| 139 |
+
while self.delta < 2**self.total_range_bits:
|
| 140 |
+
self.low *= 2
|
| 141 |
+
self.high = self.high * 2 + 1
|
| 142 |
+
self.max_bit += 1
|
| 143 |
+
|
| 144 |
+
range_low = 0 if symbol == 0 else quantized_cdf[symbol - 1].item()
|
| 145 |
+
range_high = quantized_cdf[symbol].item() - 1
|
| 146 |
+
effective_low = int(math.ceil(range_low * (self.delta / (2**self.total_range_bits))))
|
| 147 |
+
effective_high = int(math.floor(range_high * (self.delta / (2**self.total_range_bits))))
|
| 148 |
+
assert self.low <= self.high
|
| 149 |
+
self.high = self.low + effective_high
|
| 150 |
+
self.low = self.low + effective_low
|
| 151 |
+
assert self.low <= self.high, (effective_low, effective_high, range_low, range_high)
|
| 152 |
+
self._dbg.append((self.low, self.high))
|
| 153 |
+
self._dbg2.append((self.low, self.high))
|
| 154 |
+
outs = self._flush_common_prefix()
|
| 155 |
+
assert self.low <= self.high
|
| 156 |
+
assert self.max_bit >= -1
|
| 157 |
+
assert self.max_bit <= 61, self.max_bit
|
| 158 |
+
return outs
|
| 159 |
+
|
| 160 |
+
def flush(self):
|
| 161 |
+
"""Flush the remaining information to the stream."""
|
| 162 |
+
while self.max_bit >= 0:
|
| 163 |
+
b1 = (self.low >> self.max_bit) & 1
|
| 164 |
+
self.packer.push(b1)
|
| 165 |
+
self.max_bit -= 1
|
| 166 |
+
self.packer.flush()
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class ArithmeticDecoder:
|
| 170 |
+
"""ArithmeticDecoder, see `ArithmeticCoder` for a detailed explanation.
|
| 171 |
+
|
| 172 |
+
Note that this must be called with **exactly** the same parameters and sequence
|
| 173 |
+
of quantized cdf as the arithmetic encoder or the wrong values will be decoded.
|
| 174 |
+
|
| 175 |
+
If the AC encoder current range is [L, H], with `L` and `H` having the some common
|
| 176 |
+
prefix (i.e. the same most significant bits), then this prefix will be flushed to the stream.
|
| 177 |
+
For instances, having read 3 bits `b1 b2 b3`, we know that `[L, H]` is contained inside
|
| 178 |
+
`[b1 b2 b3 0 ... 0 b1 b3 b3 1 ... 1]`. Now this specific sub-range can only be obtained
|
| 179 |
+
for a specific sequence of symbols and a binary-search allows us to decode those symbols.
|
| 180 |
+
At some point, the prefix `b1 b2 b3` will no longer be sufficient to decode new symbols,
|
| 181 |
+
and we will need to read new bits from the stream and repeat the process.
|
| 182 |
+
|
| 183 |
+
"""
|
| 184 |
+
|
| 185 |
+
def __init__(self, fo: tp.IO[bytes], total_range_bits: int = 24):
|
| 186 |
+
self.total_range_bits = total_range_bits
|
| 187 |
+
self.low: int = 0
|
| 188 |
+
self.high: int = 0
|
| 189 |
+
self.current: int = 0
|
| 190 |
+
self.max_bit: int = -1
|
| 191 |
+
self.unpacker = BitUnpacker(bits=1, fo=fo) # we pull single bits at a time.
|
| 192 |
+
# Following is for debugging
|
| 193 |
+
self._dbg: tp.List[tp.Any] = []
|
| 194 |
+
self._dbg2: tp.List[tp.Any] = []
|
| 195 |
+
self._last: tp.Any = None
|
| 196 |
+
|
| 197 |
+
@property
|
| 198 |
+
def delta(self) -> int:
|
| 199 |
+
return self.high - self.low + 1
|
| 200 |
+
|
| 201 |
+
def _flush_common_prefix(self):
|
| 202 |
+
# Given the current range [L, H], if both have a common prefix,
|
| 203 |
+
# we know we can remove it from our representation to avoid handling large numbers.
|
| 204 |
+
while self.max_bit >= 0:
|
| 205 |
+
b1 = self.low >> self.max_bit
|
| 206 |
+
b2 = self.high >> self.max_bit
|
| 207 |
+
if b1 == b2:
|
| 208 |
+
self.low -= b1 << self.max_bit
|
| 209 |
+
self.high -= b1 << self.max_bit
|
| 210 |
+
self.current -= b1 << self.max_bit
|
| 211 |
+
assert self.high >= self.low
|
| 212 |
+
assert self.low >= 0
|
| 213 |
+
self.max_bit -= 1
|
| 214 |
+
else:
|
| 215 |
+
break
|
| 216 |
+
|
| 217 |
+
def pull(self, quantized_cdf: torch.Tensor) -> tp.Optional[int]:
|
| 218 |
+
"""Pull a symbol, reading as many bits from the stream as required.
|
| 219 |
+
This returns `None` when the stream has been exhausted.
|
| 220 |
+
|
| 221 |
+
Args:
|
| 222 |
+
quantized_cdf (torch.Tensor): use `build_stable_quantized_cdf`
|
| 223 |
+
to build this from your pdf estimate. This must be **exatly**
|
| 224 |
+
the same cdf as the one used at encoding time.
|
| 225 |
+
"""
|
| 226 |
+
while self.delta < 2**self.total_range_bits:
|
| 227 |
+
bit = self.unpacker.pull()
|
| 228 |
+
if bit is None:
|
| 229 |
+
return None
|
| 230 |
+
self.low *= 2
|
| 231 |
+
self.high = self.high * 2 + 1
|
| 232 |
+
self.current = self.current * 2 + bit
|
| 233 |
+
self.max_bit += 1
|
| 234 |
+
|
| 235 |
+
def bin_search(low_idx: int, high_idx: int):
|
| 236 |
+
# Binary search is not just for coding interviews :)
|
| 237 |
+
if high_idx < low_idx:
|
| 238 |
+
raise RuntimeError("Binary search failed")
|
| 239 |
+
mid = (low_idx + high_idx) // 2
|
| 240 |
+
range_low = quantized_cdf[mid - 1].item() if mid > 0 else 0
|
| 241 |
+
range_high = quantized_cdf[mid].item() - 1
|
| 242 |
+
effective_low = int(math.ceil(range_low * (self.delta / (2**self.total_range_bits))))
|
| 243 |
+
effective_high = int(math.floor(range_high * (self.delta / (2**self.total_range_bits))))
|
| 244 |
+
low = effective_low + self.low
|
| 245 |
+
high = effective_high + self.low
|
| 246 |
+
if self.current >= low:
|
| 247 |
+
if self.current <= high:
|
| 248 |
+
return (mid, low, high, self.current)
|
| 249 |
+
else:
|
| 250 |
+
return bin_search(mid + 1, high_idx)
|
| 251 |
+
else:
|
| 252 |
+
return bin_search(low_idx, mid - 1)
|
| 253 |
+
|
| 254 |
+
self._last = (self.low, self.high, self.current, self.max_bit)
|
| 255 |
+
sym, self.low, self.high, self.current = bin_search(0, len(quantized_cdf) - 1)
|
| 256 |
+
self._dbg.append((self.low, self.high, self.current))
|
| 257 |
+
self._flush_common_prefix()
|
| 258 |
+
self._dbg2.append((self.low, self.high, self.current))
|
| 259 |
+
|
| 260 |
+
return sym
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def test():
|
| 264 |
+
torch.manual_seed(1234)
|
| 265 |
+
random.seed(1234)
|
| 266 |
+
for _ in range(4):
|
| 267 |
+
pdfs = []
|
| 268 |
+
cardinality = random.randrange(4000)
|
| 269 |
+
steps = random.randrange(100, 500)
|
| 270 |
+
fo = io.BytesIO()
|
| 271 |
+
encoder = ArithmeticCoder(fo)
|
| 272 |
+
symbols = []
|
| 273 |
+
for step in range(steps):
|
| 274 |
+
pdf = torch.softmax(torch.randn(cardinality), dim=0)
|
| 275 |
+
pdfs.append(pdf)
|
| 276 |
+
q_cdf = build_stable_quantized_cdf(pdf, encoder.total_range_bits)
|
| 277 |
+
symbol = torch.multinomial(pdf, 1).item()
|
| 278 |
+
symbols.append(symbol)
|
| 279 |
+
encoder.push(symbol, q_cdf)
|
| 280 |
+
encoder.flush()
|
| 281 |
+
|
| 282 |
+
fo.seek(0)
|
| 283 |
+
decoder = ArithmeticDecoder(fo)
|
| 284 |
+
for idx, (pdf, symbol) in enumerate(zip(pdfs, symbols)):
|
| 285 |
+
q_cdf = build_stable_quantized_cdf(pdf, encoder.total_range_bits)
|
| 286 |
+
decoded_symbol = decoder.pull(q_cdf)
|
| 287 |
+
assert decoded_symbol == symbol, idx
|
| 288 |
+
assert decoder.pull(torch.zeros(1)) is None
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
if __name__ == "__main__":
|
| 292 |
+
test()
|
codec/audio_processing/quantization/core_v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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
#
|
| 7 |
+
# This implementation is inspired from
|
| 8 |
+
# https://github.com/lucidrains/vector-quantize-pytorch
|
| 9 |
+
# which is released under MIT License. Hereafter, the original license:
|
| 10 |
+
# MIT License
|
| 11 |
+
#
|
| 12 |
+
# Copyright (c) 2020 Phil Wang
|
| 13 |
+
#
|
| 14 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 15 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 16 |
+
# in the Software without restriction, including without limitation the rights
|
| 17 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 18 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 19 |
+
# furnished to do so, subject to the following conditions:
|
| 20 |
+
#
|
| 21 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 22 |
+
# copies or substantial portions of the Software.
|
| 23 |
+
#
|
| 24 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 25 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 26 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 27 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 28 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 29 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 30 |
+
# SOFTWARE.
|
| 31 |
+
|
| 32 |
+
"""Core vector quantization implementation."""
|
| 33 |
+
|
| 34 |
+
import typing as tp
|
| 35 |
+
|
| 36 |
+
from einops import rearrange, repeat
|
| 37 |
+
import torch
|
| 38 |
+
from torch import nn
|
| 39 |
+
import torch.nn.functional as F
|
| 40 |
+
|
| 41 |
+
from xcodec.quantization.distrib import broadcast_tensors, rank
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def default(val: tp.Any, d: tp.Any) -> tp.Any:
|
| 45 |
+
return val if val is not None else d
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def ema_inplace(moving_avg, new, decay: float):
|
| 49 |
+
moving_avg.data.mul_(decay).add_(new, alpha=(1 - decay))
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def laplace_smoothing(x, n_categories: int, epsilon: float = 1e-5):
|
| 53 |
+
return (x + epsilon) / (x.sum() + n_categories * epsilon)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def uniform_init(*shape: int):
|
| 57 |
+
t = torch.empty(shape)
|
| 58 |
+
nn.init.kaiming_uniform_(t)
|
| 59 |
+
return t
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def sample_vectors(samples, num: int):
|
| 63 |
+
num_samples, device = samples.shape[0], samples.device
|
| 64 |
+
|
| 65 |
+
if num_samples >= num:
|
| 66 |
+
indices = torch.randperm(num_samples, device=device)[:num]
|
| 67 |
+
else:
|
| 68 |
+
indices = torch.randint(0, num_samples, (num,), device=device)
|
| 69 |
+
|
| 70 |
+
return samples[indices]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def kmeans(samples, num_clusters: int, num_iters: int = 10):
|
| 74 |
+
dim, dtype = samples.shape[-1], samples.dtype
|
| 75 |
+
|
| 76 |
+
means = sample_vectors(samples, num_clusters)
|
| 77 |
+
|
| 78 |
+
for _ in range(num_iters):
|
| 79 |
+
diffs = rearrange(samples, "n d -> n () d") - rearrange(means, "c d -> () c d")
|
| 80 |
+
dists = -(diffs**2).sum(dim=-1)
|
| 81 |
+
|
| 82 |
+
buckets = dists.max(dim=-1).indices
|
| 83 |
+
bins = torch.bincount(buckets, minlength=num_clusters)
|
| 84 |
+
zero_mask = bins == 0
|
| 85 |
+
bins_min_clamped = bins.masked_fill(zero_mask, 1)
|
| 86 |
+
|
| 87 |
+
new_means = buckets.new_zeros(num_clusters, dim, dtype=dtype)
|
| 88 |
+
new_means.scatter_add_(0, repeat(buckets, "n -> n d", d=dim), samples)
|
| 89 |
+
new_means = new_means / bins_min_clamped[..., None]
|
| 90 |
+
|
| 91 |
+
means = torch.where(zero_mask[..., None], means, new_means)
|
| 92 |
+
|
| 93 |
+
return means, bins
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class EuclideanCodebook(nn.Module):
|
| 97 |
+
"""Codebook with Euclidean distance.
|
| 98 |
+
Args:
|
| 99 |
+
dim (int): Dimension.
|
| 100 |
+
codebook_size (int): Codebook size.
|
| 101 |
+
kmeans_init (bool): Whether to use k-means to initialize the codebooks.
|
| 102 |
+
If set to true, run the k-means algorithm on the first training batch and use
|
| 103 |
+
the learned centroids as initialization.
|
| 104 |
+
kmeans_iters (int): Number of iterations used for k-means algorithm at initialization.
|
| 105 |
+
decay (float): Decay for exponential moving average over the codebooks.
|
| 106 |
+
epsilon (float): Epsilon value for numerical stability.
|
| 107 |
+
threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes
|
| 108 |
+
that have an exponential moving average cluster size less than the specified threshold with
|
| 109 |
+
randomly selected vector from the current batch.
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
def __init__(
|
| 113 |
+
self,
|
| 114 |
+
dim: int,
|
| 115 |
+
codebook_size: int,
|
| 116 |
+
kmeans_init: int = False,
|
| 117 |
+
kmeans_iters: int = 10,
|
| 118 |
+
decay: float = 0.99,
|
| 119 |
+
epsilon: float = 1e-5,
|
| 120 |
+
threshold_ema_dead_code: int = 2,
|
| 121 |
+
):
|
| 122 |
+
super().__init__()
|
| 123 |
+
self.decay = decay
|
| 124 |
+
init_fn: tp.Union[tp.Callable[..., torch.Tensor], tp.Any] = uniform_init if not kmeans_init else torch.zeros
|
| 125 |
+
embed = init_fn(codebook_size, dim)
|
| 126 |
+
|
| 127 |
+
self.codebook_size = codebook_size
|
| 128 |
+
|
| 129 |
+
self.kmeans_iters = kmeans_iters
|
| 130 |
+
self.epsilon = epsilon
|
| 131 |
+
self.threshold_ema_dead_code = threshold_ema_dead_code
|
| 132 |
+
|
| 133 |
+
self.register_buffer("inited", torch.Tensor([not kmeans_init]))
|
| 134 |
+
self.register_buffer("cluster_size", torch.zeros(codebook_size))
|
| 135 |
+
self.register_buffer("embed", embed)
|
| 136 |
+
self.register_buffer("embed_avg", embed.clone())
|
| 137 |
+
|
| 138 |
+
@torch.jit.ignore
|
| 139 |
+
def init_embed_(self, data):
|
| 140 |
+
if self.inited:
|
| 141 |
+
return
|
| 142 |
+
|
| 143 |
+
embed, cluster_size = kmeans(data, self.codebook_size, self.kmeans_iters)
|
| 144 |
+
self.embed.data.copy_(embed)
|
| 145 |
+
self.embed_avg.data.copy_(embed.clone())
|
| 146 |
+
self.cluster_size.data.copy_(cluster_size)
|
| 147 |
+
self.inited.data.copy_(torch.Tensor([True]))
|
| 148 |
+
# Make sure all buffers across workers are in sync after initialization
|
| 149 |
+
broadcast_tensors(self.buffers())
|
| 150 |
+
|
| 151 |
+
def replace_(self, samples, mask):
|
| 152 |
+
modified_codebook = torch.where(mask[..., None], sample_vectors(samples, self.codebook_size), self.embed)
|
| 153 |
+
self.embed.data.copy_(modified_codebook)
|
| 154 |
+
|
| 155 |
+
def expire_codes_(self, batch_samples):
|
| 156 |
+
if self.threshold_ema_dead_code == 0:
|
| 157 |
+
return
|
| 158 |
+
|
| 159 |
+
expired_codes = self.cluster_size < self.threshold_ema_dead_code
|
| 160 |
+
if not torch.any(expired_codes):
|
| 161 |
+
return
|
| 162 |
+
|
| 163 |
+
batch_samples = rearrange(batch_samples, "... d -> (...) d")
|
| 164 |
+
self.replace_(batch_samples, mask=expired_codes)
|
| 165 |
+
broadcast_tensors(self.buffers())
|
| 166 |
+
|
| 167 |
+
def preprocess(self, x):
|
| 168 |
+
x = rearrange(x, "... d -> (...) d")
|
| 169 |
+
return x
|
| 170 |
+
|
| 171 |
+
def quantize(self, x):
|
| 172 |
+
embed = self.embed.t()
|
| 173 |
+
dist = -(x.pow(2).sum(1, keepdim=True) - 2 * x @ embed + embed.pow(2).sum(0, keepdim=True))
|
| 174 |
+
embed_ind = dist.max(dim=-1).indices
|
| 175 |
+
return embed_ind
|
| 176 |
+
|
| 177 |
+
def postprocess_emb(self, embed_ind, shape):
|
| 178 |
+
return embed_ind.view(*shape[:-1])
|
| 179 |
+
|
| 180 |
+
def dequantize(self, embed_ind):
|
| 181 |
+
quantize = F.embedding(embed_ind, self.embed) # get embedding based on index
|
| 182 |
+
return quantize
|
| 183 |
+
|
| 184 |
+
def encode(self, x):
|
| 185 |
+
shape = x.shape
|
| 186 |
+
# pre-process
|
| 187 |
+
x = self.preprocess(x)
|
| 188 |
+
# quantize
|
| 189 |
+
embed_ind = self.quantize(x) # get index based on Euclidean distance
|
| 190 |
+
# post-process
|
| 191 |
+
embed_ind = self.postprocess_emb(embed_ind, shape)
|
| 192 |
+
return embed_ind
|
| 193 |
+
|
| 194 |
+
def decode(self, embed_ind):
|
| 195 |
+
quantize = self.dequantize(embed_ind)
|
| 196 |
+
return quantize
|
| 197 |
+
|
| 198 |
+
def forward(self, x):
|
| 199 |
+
shape, dtype = x.shape, x.dtype
|
| 200 |
+
x = self.preprocess(x)
|
| 201 |
+
|
| 202 |
+
self.init_embed_(x)
|
| 203 |
+
|
| 204 |
+
embed_ind = self.quantize(x)
|
| 205 |
+
embed_onehot = F.one_hot(embed_ind, self.codebook_size).type(dtype)
|
| 206 |
+
embed_ind = self.postprocess_emb(embed_ind, shape)
|
| 207 |
+
quantize = self.dequantize(embed_ind)
|
| 208 |
+
|
| 209 |
+
if self.training:
|
| 210 |
+
# We do the expiry of code at that point as buffers are in sync
|
| 211 |
+
# and all the workers will take the same decision.
|
| 212 |
+
self.expire_codes_(x)
|
| 213 |
+
ema_inplace(self.cluster_size, embed_onehot.sum(0), self.decay)
|
| 214 |
+
embed_sum = x.t() @ embed_onehot
|
| 215 |
+
ema_inplace(self.embed_avg, embed_sum.t(), self.decay)
|
| 216 |
+
cluster_size = (
|
| 217 |
+
laplace_smoothing(self.cluster_size, self.codebook_size, self.epsilon) * self.cluster_size.sum()
|
| 218 |
+
)
|
| 219 |
+
embed_normalized = self.embed_avg / cluster_size.unsqueeze(1)
|
| 220 |
+
self.embed.data.copy_(embed_normalized)
|
| 221 |
+
|
| 222 |
+
return quantize, embed_ind
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
class VectorQuantization(nn.Module):
|
| 226 |
+
"""Vector quantization implementation.
|
| 227 |
+
Currently supports only euclidean distance.
|
| 228 |
+
Args:
|
| 229 |
+
dim (int): Dimension
|
| 230 |
+
codebook_size (int): Codebook size
|
| 231 |
+
codebook_dim (int): Codebook dimension. If not defined, uses the specified dimension in dim.
|
| 232 |
+
decay (float): Decay for exponential moving average over the codebooks.
|
| 233 |
+
epsilon (float): Epsilon value for numerical stability.
|
| 234 |
+
kmeans_init (bool): Whether to use kmeans to initialize the codebooks.
|
| 235 |
+
kmeans_iters (int): Number of iterations used for kmeans initialization.
|
| 236 |
+
threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes
|
| 237 |
+
that have an exponential moving average cluster size less than the specified threshold with
|
| 238 |
+
randomly selected vector from the current batch.
|
| 239 |
+
commitment_weight (float): Weight for commitment loss.
|
| 240 |
+
"""
|
| 241 |
+
|
| 242 |
+
def __init__(
|
| 243 |
+
self,
|
| 244 |
+
dim: int,
|
| 245 |
+
codebook_size: int,
|
| 246 |
+
codebook_dim: tp.Optional[int] = None,
|
| 247 |
+
decay: float = 0.99,
|
| 248 |
+
epsilon: float = 1e-5,
|
| 249 |
+
kmeans_init: bool = True,
|
| 250 |
+
kmeans_iters: int = 50,
|
| 251 |
+
threshold_ema_dead_code: int = 2,
|
| 252 |
+
commitment_weight: float = 1.0,
|
| 253 |
+
):
|
| 254 |
+
super().__init__()
|
| 255 |
+
_codebook_dim: int = default(codebook_dim, dim)
|
| 256 |
+
|
| 257 |
+
requires_projection = _codebook_dim != dim
|
| 258 |
+
self.project_in = nn.Linear(dim, _codebook_dim) if requires_projection else nn.Identity()
|
| 259 |
+
self.project_out = nn.Linear(_codebook_dim, dim) if requires_projection else nn.Identity()
|
| 260 |
+
|
| 261 |
+
self.epsilon = epsilon
|
| 262 |
+
self.commitment_weight = commitment_weight
|
| 263 |
+
|
| 264 |
+
self._codebook = EuclideanCodebook(
|
| 265 |
+
dim=_codebook_dim,
|
| 266 |
+
codebook_size=codebook_size,
|
| 267 |
+
kmeans_init=kmeans_init,
|
| 268 |
+
kmeans_iters=kmeans_iters,
|
| 269 |
+
decay=decay,
|
| 270 |
+
epsilon=epsilon,
|
| 271 |
+
threshold_ema_dead_code=threshold_ema_dead_code,
|
| 272 |
+
)
|
| 273 |
+
self.codebook_size = codebook_size
|
| 274 |
+
|
| 275 |
+
@property
|
| 276 |
+
def codebook(self):
|
| 277 |
+
return self._codebook.embed
|
| 278 |
+
|
| 279 |
+
def encode(self, x):
|
| 280 |
+
x = rearrange(x, "b d n -> b n d")
|
| 281 |
+
x = self.project_in(x)
|
| 282 |
+
embed_in = self._codebook.encode(x)
|
| 283 |
+
return embed_in
|
| 284 |
+
|
| 285 |
+
def decode(self, embed_ind):
|
| 286 |
+
quantize = self._codebook.decode(embed_ind)
|
| 287 |
+
quantize = self.project_out(quantize)
|
| 288 |
+
quantize = rearrange(quantize, "b n d -> b d n")
|
| 289 |
+
return quantize
|
| 290 |
+
|
| 291 |
+
def forward(self, x):
|
| 292 |
+
device = x.device
|
| 293 |
+
x = rearrange(x, "b d n -> b n d")
|
| 294 |
+
x = self.project_in(x)
|
| 295 |
+
|
| 296 |
+
quantize, embed_ind = self._codebook(x)
|
| 297 |
+
|
| 298 |
+
if self.training:
|
| 299 |
+
quantize = x + (quantize - x).detach()
|
| 300 |
+
|
| 301 |
+
loss = torch.tensor([0.0], device=device, requires_grad=self.training)
|
| 302 |
+
|
| 303 |
+
if self.training:
|
| 304 |
+
if self.commitment_weight > 0:
|
| 305 |
+
commit_loss = F.mse_loss(quantize.detach(), x)
|
| 306 |
+
loss = loss + commit_loss * self.commitment_weight
|
| 307 |
+
|
| 308 |
+
quantize = self.project_out(quantize)
|
| 309 |
+
quantize = rearrange(quantize, "b n d -> b d n")
|
| 310 |
+
return quantize, embed_ind, loss
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
class ResidualVectorQuantization(nn.Module):
|
| 314 |
+
"""Residual vector quantization implementation.
|
| 315 |
+
Follows Algorithm 1. in https://arxiv.org/pdf/2107.03312.pdf
|
| 316 |
+
"""
|
| 317 |
+
|
| 318 |
+
def __init__(self, *, num_quantizers, **kwargs):
|
| 319 |
+
super().__init__()
|
| 320 |
+
self.layers = nn.ModuleList([VectorQuantization(**kwargs) for _ in range(num_quantizers)])
|
| 321 |
+
|
| 322 |
+
def forward(self, x, n_q: tp.Optional[int] = None):
|
| 323 |
+
quantized_out = 0.0
|
| 324 |
+
residual = x
|
| 325 |
+
|
| 326 |
+
all_losses = []
|
| 327 |
+
all_indices = []
|
| 328 |
+
|
| 329 |
+
n_q = n_q or len(self.layers)
|
| 330 |
+
|
| 331 |
+
for layer in self.layers[:n_q]:
|
| 332 |
+
quantized, indices, loss = layer(residual)
|
| 333 |
+
residual = residual - quantized
|
| 334 |
+
quantized_out = quantized_out + quantized
|
| 335 |
+
|
| 336 |
+
all_indices.append(indices)
|
| 337 |
+
all_losses.append(loss)
|
| 338 |
+
|
| 339 |
+
out_losses, out_indices = map(torch.stack, (all_losses, all_indices))
|
| 340 |
+
return quantized_out, out_indices, out_losses
|
| 341 |
+
|
| 342 |
+
def encode(self, x: torch.Tensor, n_q: tp.Optional[int] = None) -> torch.Tensor:
|
| 343 |
+
residual = x
|
| 344 |
+
all_indices = []
|
| 345 |
+
n_q = n_q or len(self.layers)
|
| 346 |
+
for layer in self.layers[:n_q]:
|
| 347 |
+
indices = layer.encode(residual)
|
| 348 |
+
quantized = layer.decode(indices)
|
| 349 |
+
residual = residual - quantized
|
| 350 |
+
all_indices.append(indices)
|
| 351 |
+
out_indices = torch.stack(all_indices)
|
| 352 |
+
return out_indices
|
| 353 |
+
|
| 354 |
+
def decode(self, q_indices: torch.Tensor) -> torch.Tensor:
|
| 355 |
+
quantized_out = torch.tensor(0.0, device=q_indices.device)
|
| 356 |
+
for i, indices in enumerate(q_indices):
|
| 357 |
+
layer = self.layers[i]
|
| 358 |
+
quantized = layer.decode(indices)
|
| 359 |
+
quantized_out = quantized_out + quantized
|
| 360 |
+
return quantized_out
|
codec/audio_processing/quantization/core_vq_lsx_version.py
ADDED
|
@@ -0,0 +1,425 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c)
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
# This implementation is inspired from
|
| 6 |
+
# https://github.com/rosinality/vq-vae-2-pytorch/blob/master/vqvae.py and
|
| 7 |
+
# https://github.com/clementchadebec/benchmark_VAE/blob/dfa0dcf6c79172df5d27769c09c860c42008baaa/src/pythae/models/vq_vae/vq_vae_utils.py#L81
|
| 8 |
+
#
|
| 9 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 10 |
+
# All rights reserved.
|
| 11 |
+
#
|
| 12 |
+
# This source code is licensed under the license found in the
|
| 13 |
+
# LICENSE file in the root directory of this source tree.
|
| 14 |
+
#
|
| 15 |
+
# This implementation is inspired from
|
| 16 |
+
# https://github.com/lucidrains/vector-quantize-pytorch
|
| 17 |
+
# which is released under MIT License. Hereafter, the original license:
|
| 18 |
+
# MIT License
|
| 19 |
+
#
|
| 20 |
+
# Copyright (c) 2020 Phil Wang
|
| 21 |
+
#
|
| 22 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 23 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 24 |
+
# in the Software without restriction, including without limitation the rights
|
| 25 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 26 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 27 |
+
# furnished to do so, subject to the following conditions:
|
| 28 |
+
#
|
| 29 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 30 |
+
# copies or substantial portions of the Software.
|
| 31 |
+
#
|
| 32 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 33 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 34 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 35 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 36 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 37 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 38 |
+
# SOFTWARE.
|
| 39 |
+
|
| 40 |
+
"""Core vector quantization implementation."""
|
| 41 |
+
|
| 42 |
+
import typing as tp
|
| 43 |
+
|
| 44 |
+
from einops import rearrange
|
| 45 |
+
import torch
|
| 46 |
+
from torch import nn
|
| 47 |
+
import torch.nn.functional as F
|
| 48 |
+
import torch.distributed as dist
|
| 49 |
+
|
| 50 |
+
from .distrib import broadcast_tensors, is_distributed
|
| 51 |
+
from .ddp_utils import SyncFunction
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def default(val: tp.Any, d: tp.Any) -> tp.Any:
|
| 55 |
+
return val if val is not None else d
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def ema_inplace(moving_avg, new, decay: float):
|
| 59 |
+
moving_avg.data.mul_(decay).add_(new, alpha=(1 - decay))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def laplace_smoothing(x, n_categories: int, epsilon: float = 1e-5):
|
| 63 |
+
return (x + epsilon) / (x.sum() + n_categories * epsilon)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def uniform_init(*shape: int):
|
| 67 |
+
t = torch.empty(shape)
|
| 68 |
+
nn.init.kaiming_uniform_(t)
|
| 69 |
+
return t
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def sample_vectors(samples, num: int):
|
| 73 |
+
num_samples, device = samples.shape[0], samples.device
|
| 74 |
+
|
| 75 |
+
if num_samples >= num:
|
| 76 |
+
indices = torch.randperm(num_samples, device=device)[:num]
|
| 77 |
+
else:
|
| 78 |
+
indices = torch.randint(0, num_samples, (num,), device=device)
|
| 79 |
+
|
| 80 |
+
return samples[indices]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def kmeans(samples, num_clusters: int, num_iters: int = 10, frames_to_use: int = 10_000, batch_size: int = 64):
|
| 84 |
+
"""
|
| 85 |
+
Memory-efficient K-means clustering.
|
| 86 |
+
Args:
|
| 87 |
+
samples (tensor): shape [N, D]
|
| 88 |
+
num_clusters (int): number of centroids.
|
| 89 |
+
num_iters (int): number of iterations.
|
| 90 |
+
frames_to_use (int): subsample size from total samples.
|
| 91 |
+
batch_size (int): batch size used in distance computation.
|
| 92 |
+
Returns:
|
| 93 |
+
means: [num_clusters, D]
|
| 94 |
+
bins: [num_clusters] (number of points per cluster)
|
| 95 |
+
"""
|
| 96 |
+
N, D = samples.shape
|
| 97 |
+
dtype, device = samples.dtype, samples.device
|
| 98 |
+
|
| 99 |
+
if frames_to_use < N:
|
| 100 |
+
indices = torch.randperm(N, device=device)[:frames_to_use]
|
| 101 |
+
samples = samples[indices]
|
| 102 |
+
|
| 103 |
+
means = sample_vectors(samples, num_clusters)
|
| 104 |
+
|
| 105 |
+
for _ in range(num_iters):
|
| 106 |
+
# Store cluster assignments
|
| 107 |
+
all_assignments = []
|
| 108 |
+
|
| 109 |
+
for i in range(0, samples.shape[0], batch_size):
|
| 110 |
+
batch = samples[i : i + batch_size] # [B, D]
|
| 111 |
+
dists = torch.cdist(batch, means, p=2) # [B, C]
|
| 112 |
+
assignments = dists.argmin(dim=1) # [B]
|
| 113 |
+
all_assignments.append(assignments)
|
| 114 |
+
|
| 115 |
+
buckets = torch.cat(all_assignments, dim=0) # [N]
|
| 116 |
+
bins = torch.bincount(buckets, minlength=num_clusters)
|
| 117 |
+
zero_mask = bins == 0
|
| 118 |
+
bins_min_clamped = bins.masked_fill(zero_mask, 1)
|
| 119 |
+
|
| 120 |
+
# Compute new means
|
| 121 |
+
new_means = torch.zeros_like(means)
|
| 122 |
+
for i in range(num_clusters):
|
| 123 |
+
mask = buckets == i
|
| 124 |
+
if mask.any():
|
| 125 |
+
new_means[i] = samples[mask].mean(dim=0)
|
| 126 |
+
|
| 127 |
+
means = torch.where(zero_mask[:, None], means, new_means)
|
| 128 |
+
|
| 129 |
+
return means, bins
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class EuclideanCodebook(nn.Module):
|
| 133 |
+
"""Codebook with Euclidean distance.
|
| 134 |
+
Args:
|
| 135 |
+
dim (int): Dimension.
|
| 136 |
+
codebook_size (int): Codebook size.
|
| 137 |
+
kmeans_init (bool): Whether to use k-means to initialize the codebooks.
|
| 138 |
+
If set to true, run the k-means algorithm on the first training batch and use
|
| 139 |
+
the learned centroids as initialization.
|
| 140 |
+
kmeans_iters (int): Number of iterations used for k-means algorithm at initialization.
|
| 141 |
+
decay (float): Decay for exponential moving average over the codebooks.
|
| 142 |
+
epsilon (float): Epsilon value for numerical stability.
|
| 143 |
+
threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes
|
| 144 |
+
that have an exponential moving average cluster size less than the specified threshold with
|
| 145 |
+
randomly selected vector from the current batch.
|
| 146 |
+
"""
|
| 147 |
+
|
| 148 |
+
def __init__(
|
| 149 |
+
self,
|
| 150 |
+
dim: int,
|
| 151 |
+
codebook_size: int,
|
| 152 |
+
kmeans_init: int = False,
|
| 153 |
+
kmeans_iters: int = 10,
|
| 154 |
+
decay: float = 0.99,
|
| 155 |
+
epsilon: float = 1e-5,
|
| 156 |
+
threshold_ema_dead_code: int = 2,
|
| 157 |
+
):
|
| 158 |
+
super().__init__()
|
| 159 |
+
self.decay = decay
|
| 160 |
+
init_fn: tp.Union[tp.Callable[..., torch.Tensor], tp.Any] = uniform_init if not kmeans_init else torch.zeros
|
| 161 |
+
embed = init_fn(codebook_size, dim)
|
| 162 |
+
|
| 163 |
+
self.codebook_size = codebook_size
|
| 164 |
+
|
| 165 |
+
self.kmeans_iters = kmeans_iters
|
| 166 |
+
self.epsilon = epsilon
|
| 167 |
+
self.threshold_ema_dead_code = threshold_ema_dead_code
|
| 168 |
+
|
| 169 |
+
# Flag variable to indicate whether the codebook is initialized
|
| 170 |
+
self.register_buffer("inited", torch.Tensor([not kmeans_init]))
|
| 171 |
+
# Runing EMA cluster size/count: N_i^t in eq. (6) in vqvae paper
|
| 172 |
+
self.register_buffer("cluster_size", torch.zeros(codebook_size))
|
| 173 |
+
# Codebook
|
| 174 |
+
self.register_buffer("embed", embed)
|
| 175 |
+
# EMA codebook: eq. (7) in vqvae paper
|
| 176 |
+
self.register_buffer("embed_avg", embed.clone())
|
| 177 |
+
|
| 178 |
+
@torch.jit.ignore
|
| 179 |
+
def init_embed_(self, data):
|
| 180 |
+
"""Initialize codebook.
|
| 181 |
+
Args:
|
| 182 |
+
data (tensor): [B * T, D].
|
| 183 |
+
"""
|
| 184 |
+
if self.inited:
|
| 185 |
+
return
|
| 186 |
+
|
| 187 |
+
## NOTE (snippet added by Songxiang Liu): gather data from all gpus
|
| 188 |
+
if dist.is_available() and dist.is_initialized():
|
| 189 |
+
# [B * T * world_size, D]
|
| 190 |
+
data = SyncFunction.apply(data)
|
| 191 |
+
|
| 192 |
+
embed, cluster_size = kmeans(data, self.codebook_size, self.kmeans_iters)
|
| 193 |
+
self.embed.data.copy_(embed)
|
| 194 |
+
self.embed_avg.data.copy_(embed.clone())
|
| 195 |
+
self.cluster_size.data.copy_(cluster_size)
|
| 196 |
+
self.inited.data.copy_(torch.Tensor([True]))
|
| 197 |
+
# Make sure all buffers across workers are in sync after initialization
|
| 198 |
+
broadcast_tensors(self.buffers())
|
| 199 |
+
|
| 200 |
+
def replace_(self, samples, mask):
|
| 201 |
+
modified_codebook = torch.where(mask[..., None], sample_vectors(samples, self.codebook_size), self.embed)
|
| 202 |
+
self.embed.data.copy_(modified_codebook)
|
| 203 |
+
|
| 204 |
+
def expire_codes_(self, batch_samples):
|
| 205 |
+
if self.threshold_ema_dead_code == 0:
|
| 206 |
+
return
|
| 207 |
+
|
| 208 |
+
expired_codes = self.cluster_size < self.threshold_ema_dead_code
|
| 209 |
+
if not torch.any(expired_codes):
|
| 210 |
+
return
|
| 211 |
+
|
| 212 |
+
## NOTE (snippet added by Songxiang Liu): gather data from all gpus
|
| 213 |
+
if is_distributed():
|
| 214 |
+
# [B * T * world_size, D]
|
| 215 |
+
batch_samples = SyncFunction.apply(batch_samples)
|
| 216 |
+
|
| 217 |
+
batch_samples = rearrange(batch_samples, "... d -> (...) d")
|
| 218 |
+
self.replace_(batch_samples, mask=expired_codes)
|
| 219 |
+
broadcast_tensors(self.buffers())
|
| 220 |
+
|
| 221 |
+
def preprocess(self, x):
|
| 222 |
+
x = rearrange(x, "... d -> (...) d")
|
| 223 |
+
return x
|
| 224 |
+
|
| 225 |
+
def quantize(self, x):
|
| 226 |
+
embed = self.embed.t()
|
| 227 |
+
dist = -(x.pow(2).sum(1, keepdim=True) - 2 * x @ embed + embed.pow(2).sum(0, keepdim=True))
|
| 228 |
+
embed_ind = dist.max(dim=-1).indices
|
| 229 |
+
return embed_ind
|
| 230 |
+
|
| 231 |
+
def postprocess_emb(self, embed_ind, shape):
|
| 232 |
+
return embed_ind.view(*shape[:-1])
|
| 233 |
+
|
| 234 |
+
def dequantize(self, embed_ind):
|
| 235 |
+
quantize = F.embedding(embed_ind, self.embed)
|
| 236 |
+
return quantize
|
| 237 |
+
|
| 238 |
+
def encode(self, x):
|
| 239 |
+
shape = x.shape
|
| 240 |
+
# pre-process
|
| 241 |
+
x = self.preprocess(x) # [B, T, D] -> [B*T, D]
|
| 242 |
+
# quantize
|
| 243 |
+
embed_ind = self.quantize(x)
|
| 244 |
+
# post-process
|
| 245 |
+
embed_ind = self.postprocess_emb(embed_ind, shape)
|
| 246 |
+
return embed_ind
|
| 247 |
+
|
| 248 |
+
def decode(self, embed_ind):
|
| 249 |
+
quantize = self.dequantize(embed_ind)
|
| 250 |
+
return quantize
|
| 251 |
+
|
| 252 |
+
def forward(self, x):
|
| 253 |
+
# shape: [B, T, D]
|
| 254 |
+
shape, dtype = x.shape, x.dtype
|
| 255 |
+
x = self.preprocess(x) # [B, T, D] -> [B*T, D]
|
| 256 |
+
|
| 257 |
+
# Initialize codebook
|
| 258 |
+
self.init_embed_(x)
|
| 259 |
+
|
| 260 |
+
embed_ind = self.quantize(x) # [B*T,]
|
| 261 |
+
embed_onehot = F.one_hot(embed_ind, self.codebook_size).type(dtype) # [B*T, cb-size]
|
| 262 |
+
embed_ind = self.postprocess_emb(embed_ind, shape) # [B, T]
|
| 263 |
+
quantize = self.dequantize(embed_ind) # [B, T, D]
|
| 264 |
+
|
| 265 |
+
if self.training:
|
| 266 |
+
### Update codebook by EMA
|
| 267 |
+
embed_onehot_sum = embed_onehot.sum(0) # [cb-size,]
|
| 268 |
+
embed_sum = x.t() @ embed_onehot # [D, cb-size]
|
| 269 |
+
if is_distributed():
|
| 270 |
+
dist.all_reduce(embed_onehot_sum)
|
| 271 |
+
dist.all_reduce(embed_sum)
|
| 272 |
+
# Update ema cluster count N_i^t, eq. (6) in vqvae paper
|
| 273 |
+
self.cluster_size.data.mul_(self.decay).add_(embed_onehot_sum, alpha=1 - self.decay)
|
| 274 |
+
# Update ema embed: eq. (7) in vqvae paper
|
| 275 |
+
self.embed_avg.data.mul_(self.decay).add_(embed_sum.t(), alpha=1 - self.decay)
|
| 276 |
+
# apply laplace smoothing
|
| 277 |
+
n = self.cluster_size.sum()
|
| 278 |
+
cluster_size = (self.cluster_size + self.epsilon) / (n + self.codebook_size * self.epsilon) * n
|
| 279 |
+
# Update ema embed: eq. (8) in vqvae paper
|
| 280 |
+
embed_normalized = self.embed_avg / cluster_size.unsqueeze(1)
|
| 281 |
+
self.embed.data.copy_(embed_normalized)
|
| 282 |
+
|
| 283 |
+
# We do the expiry of code at that point as buffers are in sync
|
| 284 |
+
# and all the workers will take the same decision.
|
| 285 |
+
self.expire_codes_(x)
|
| 286 |
+
|
| 287 |
+
return quantize, embed_ind
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
class VectorQuantization(nn.Module):
|
| 291 |
+
"""Vector quantization implementation.
|
| 292 |
+
Currently supports only euclidean distance.
|
| 293 |
+
Args:
|
| 294 |
+
dim (int): Dimension
|
| 295 |
+
codebook_size (int): Codebook size
|
| 296 |
+
codebook_dim (int): Codebook dimension. If not defined, uses the specified dimension in dim.
|
| 297 |
+
decay (float): Decay for exponential moving average over the codebooks.
|
| 298 |
+
epsilon (float): Epsilon value for numerical stability.
|
| 299 |
+
kmeans_init (bool): Whether to use kmeans to initialize the codebooks.
|
| 300 |
+
kmeans_iters (int): Number of iterations used for kmeans initialization.
|
| 301 |
+
threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes
|
| 302 |
+
that have an exponential moving average cluster size less than the specified threshold with
|
| 303 |
+
randomly selected vector from the current batch.
|
| 304 |
+
commitment_weight (float): Weight for commitment loss.
|
| 305 |
+
"""
|
| 306 |
+
|
| 307 |
+
def __init__(
|
| 308 |
+
self,
|
| 309 |
+
dim: int,
|
| 310 |
+
codebook_size: int,
|
| 311 |
+
codebook_dim: tp.Optional[int] = None,
|
| 312 |
+
decay: float = 0.99,
|
| 313 |
+
epsilon: float = 1e-5,
|
| 314 |
+
kmeans_init: bool = True,
|
| 315 |
+
kmeans_iters: int = 50,
|
| 316 |
+
threshold_ema_dead_code: int = 2,
|
| 317 |
+
commitment_weight: float = 1.0,
|
| 318 |
+
):
|
| 319 |
+
super().__init__()
|
| 320 |
+
_codebook_dim: int = default(codebook_dim, dim)
|
| 321 |
+
|
| 322 |
+
requires_projection = _codebook_dim != dim
|
| 323 |
+
self.project_in = nn.Linear(dim, _codebook_dim) if requires_projection else nn.Identity()
|
| 324 |
+
self.project_out = nn.Linear(_codebook_dim, dim) if requires_projection else nn.Identity()
|
| 325 |
+
|
| 326 |
+
self.epsilon = epsilon
|
| 327 |
+
self.commitment_weight = commitment_weight
|
| 328 |
+
|
| 329 |
+
self._codebook = EuclideanCodebook(
|
| 330 |
+
dim=_codebook_dim,
|
| 331 |
+
codebook_size=codebook_size,
|
| 332 |
+
kmeans_init=kmeans_init,
|
| 333 |
+
kmeans_iters=kmeans_iters,
|
| 334 |
+
decay=decay,
|
| 335 |
+
epsilon=epsilon,
|
| 336 |
+
threshold_ema_dead_code=threshold_ema_dead_code,
|
| 337 |
+
)
|
| 338 |
+
self.codebook_size = codebook_size
|
| 339 |
+
|
| 340 |
+
@property
|
| 341 |
+
def codebook(self):
|
| 342 |
+
return self._codebook.embed
|
| 343 |
+
|
| 344 |
+
def encode(self, x):
|
| 345 |
+
x = rearrange(x, "b d n -> b n d")
|
| 346 |
+
x = self.project_in(x)
|
| 347 |
+
embed_in = self._codebook.encode(x)
|
| 348 |
+
return embed_in
|
| 349 |
+
|
| 350 |
+
def decode(self, embed_ind):
|
| 351 |
+
quantize = self._codebook.decode(embed_ind)
|
| 352 |
+
quantize = self.project_out(quantize)
|
| 353 |
+
quantize = rearrange(quantize, "b n d -> b d n")
|
| 354 |
+
return quantize
|
| 355 |
+
|
| 356 |
+
def forward(self, x):
|
| 357 |
+
device = x.device
|
| 358 |
+
x = x.transpose(1, 2).contiguous() # [b d n] -> [b n d]
|
| 359 |
+
x = self.project_in(x)
|
| 360 |
+
|
| 361 |
+
quantize, embed_ind = self._codebook(x)
|
| 362 |
+
|
| 363 |
+
if self.training:
|
| 364 |
+
quantize = x + (quantize - x).detach()
|
| 365 |
+
|
| 366 |
+
loss = torch.tensor([0.0], device=device, requires_grad=self.training)
|
| 367 |
+
|
| 368 |
+
if self.training:
|
| 369 |
+
if self.commitment_weight > 0:
|
| 370 |
+
commit_loss = F.mse_loss(quantize.detach(), x)
|
| 371 |
+
loss = loss + commit_loss * self.commitment_weight
|
| 372 |
+
|
| 373 |
+
quantize = self.project_out(quantize)
|
| 374 |
+
quantize = quantize.transpose(1, 2).contiguous() # [b n d] -> [b d n]
|
| 375 |
+
return quantize, embed_ind, loss
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
class ResidualVectorQuantization(nn.Module):
|
| 379 |
+
"""Residual vector quantization implementation.
|
| 380 |
+
Follows Algorithm 1. in https://arxiv.org/pdf/2107.03312.pdf
|
| 381 |
+
"""
|
| 382 |
+
|
| 383 |
+
def __init__(self, *, num_quantizers, **kwargs):
|
| 384 |
+
super().__init__()
|
| 385 |
+
self.layers = nn.ModuleList([VectorQuantization(**kwargs) for _ in range(num_quantizers)])
|
| 386 |
+
|
| 387 |
+
def forward(self, x, n_q: tp.Optional[int] = None):
|
| 388 |
+
quantized_out = 0.0
|
| 389 |
+
residual = x
|
| 390 |
+
|
| 391 |
+
all_losses = []
|
| 392 |
+
all_indices = []
|
| 393 |
+
|
| 394 |
+
n_q = n_q or len(self.layers)
|
| 395 |
+
|
| 396 |
+
for layer in self.layers[:n_q]:
|
| 397 |
+
quantized, indices, loss = layer(residual)
|
| 398 |
+
residual = residual - quantized
|
| 399 |
+
quantized_out = quantized_out + quantized
|
| 400 |
+
|
| 401 |
+
all_indices.append(indices)
|
| 402 |
+
all_losses.append(loss)
|
| 403 |
+
|
| 404 |
+
out_losses, out_indices = map(torch.stack, (all_losses, all_indices))
|
| 405 |
+
return quantized_out, out_indices, out_losses
|
| 406 |
+
|
| 407 |
+
def encode(self, x: torch.Tensor, n_q: tp.Optional[int] = None) -> torch.Tensor:
|
| 408 |
+
residual = x
|
| 409 |
+
all_indices = []
|
| 410 |
+
n_q = n_q or len(self.layers)
|
| 411 |
+
for layer in self.layers[:n_q]:
|
| 412 |
+
indices = layer.encode(residual)
|
| 413 |
+
quantized = layer.decode(indices)
|
| 414 |
+
residual = residual - quantized
|
| 415 |
+
all_indices.append(indices)
|
| 416 |
+
out_indices = torch.stack(all_indices)
|
| 417 |
+
return out_indices
|
| 418 |
+
|
| 419 |
+
def decode(self, q_indices: torch.Tensor) -> torch.Tensor:
|
| 420 |
+
quantized_out = torch.tensor(0.0, device=q_indices.device)
|
| 421 |
+
for i, indices in enumerate(q_indices):
|
| 422 |
+
layer = self.layers[i]
|
| 423 |
+
quantized = layer.decode(indices)
|
| 424 |
+
quantized_out = quantized_out + quantized
|
| 425 |
+
return quantized_out
|
codec/audio_processing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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import random
|
| 3 |
+
import subprocess
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
import torch.distributed as dist
|
| 9 |
+
from torch.nn.parallel import DistributedDataParallel
|
| 10 |
+
from torch.nn.parallel.distributed import _find_tensors
|
| 11 |
+
import torch.optim
|
| 12 |
+
import torch.utils.data
|
| 13 |
+
from packaging import version
|
| 14 |
+
from omegaconf import OmegaConf
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def set_random_seed(seed):
|
| 18 |
+
random.seed(seed)
|
| 19 |
+
np.random.seed(seed)
|
| 20 |
+
torch.manual_seed(seed)
|
| 21 |
+
torch.cuda.manual_seed_all(seed)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def is_logging_process():
|
| 25 |
+
return not dist.is_initialized() or dist.get_rank() == 0
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def get_logger(cfg, name=None):
|
| 29 |
+
# log_file_path is used when unit testing
|
| 30 |
+
if is_logging_process():
|
| 31 |
+
logging.config.dictConfig(OmegaConf.to_container(cfg.job_logging_config, resolve=True))
|
| 32 |
+
return logging.getLogger(name)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# from https://github.com/Lightning-AI/lightning-bolts/blob/5d61197cd2f491f69e238137a5edabe80ae14ad9/pl_bolts/models/self_supervised/simclr/simclr_module.py#L20
|
| 36 |
+
class SyncFunction(torch.autograd.Function):
|
| 37 |
+
@staticmethod
|
| 38 |
+
# @torch.no_grad()
|
| 39 |
+
def forward(ctx, tensor):
|
| 40 |
+
ctx.batch_size = tensor.shape[0]
|
| 41 |
+
|
| 42 |
+
gathered_tensor = [torch.zeros_like(tensor) for _ in range(torch.distributed.get_world_size())]
|
| 43 |
+
|
| 44 |
+
torch.distributed.all_gather(gathered_tensor, tensor)
|
| 45 |
+
gathered_tensor = torch.cat(gathered_tensor, 0)
|
| 46 |
+
|
| 47 |
+
return gathered_tensor
|
| 48 |
+
|
| 49 |
+
@staticmethod
|
| 50 |
+
def backward(ctx, grad_output):
|
| 51 |
+
grad_input = grad_output.clone()
|
| 52 |
+
torch.distributed.all_reduce(grad_input, op=torch.distributed.ReduceOp.SUM, async_op=False)
|
| 53 |
+
|
| 54 |
+
idx_from = torch.distributed.get_rank() * ctx.batch_size
|
| 55 |
+
idx_to = (torch.distributed.get_rank() + 1) * ctx.batch_size
|
| 56 |
+
return grad_input[idx_from:idx_to]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def get_timestamp():
|
| 60 |
+
return datetime.now().strftime("%y%m%d-%H%M%S")
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def get_commit_hash():
|
| 64 |
+
message = subprocess.check_output(["git", "rev-parse", "--short", "HEAD"])
|
| 65 |
+
return message.strip().decode("utf-8")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class DDP(DistributedDataParallel):
|
| 69 |
+
"""
|
| 70 |
+
Override the forward call in lightning so it goes to training and validation step respectively
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
def forward(self, *inputs, **kwargs): # pragma: no cover
|
| 74 |
+
if version.parse(torch.__version__[:6]) < version.parse("1.11"):
|
| 75 |
+
self._sync_params()
|
| 76 |
+
inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids)
|
| 77 |
+
assert len(self.device_ids) == 1
|
| 78 |
+
if self.module.training:
|
| 79 |
+
output = self.module.training_step(*inputs[0], **kwargs[0])
|
| 80 |
+
elif self.module.testing:
|
| 81 |
+
output = self.module.test_step(*inputs[0], **kwargs[0])
|
| 82 |
+
else:
|
| 83 |
+
output = self.module.validation_step(*inputs[0], **kwargs[0])
|
| 84 |
+
if torch.is_grad_enabled():
|
| 85 |
+
# We'll return the output object verbatim since it is a freeform
|
| 86 |
+
# object. We need to find any tensors in this object, though,
|
| 87 |
+
# because we need to figure out which parameters were used during
|
| 88 |
+
# this forward pass, to ensure we short circuit reduction for any
|
| 89 |
+
# unused parameters. Only if `find_unused_parameters` is set.
|
| 90 |
+
if self.find_unused_parameters:
|
| 91 |
+
self.reducer.prepare_for_backward(list(_find_tensors(output)))
|
| 92 |
+
else:
|
| 93 |
+
self.reducer.prepare_for_backward([])
|
| 94 |
+
else:
|
| 95 |
+
from torch.nn.parallel.distributed import (
|
| 96 |
+
logging,
|
| 97 |
+
Join,
|
| 98 |
+
_DDPSink,
|
| 99 |
+
_tree_flatten_with_rref,
|
| 100 |
+
_tree_unflatten_with_rref,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
with torch.autograd.profiler.record_function("DistributedDataParallel.forward"):
|
| 104 |
+
if torch.is_grad_enabled() and self.require_backward_grad_sync:
|
| 105 |
+
self.logger.set_runtime_stats_and_log()
|
| 106 |
+
self.num_iterations += 1
|
| 107 |
+
self.reducer.prepare_for_forward()
|
| 108 |
+
|
| 109 |
+
# Notify the join context that this process has not joined, if
|
| 110 |
+
# needed
|
| 111 |
+
work = Join.notify_join_context(self)
|
| 112 |
+
if work:
|
| 113 |
+
self.reducer._set_forward_pass_work_handle(work, self._divide_by_initial_world_size)
|
| 114 |
+
|
| 115 |
+
# Calling _rebuild_buckets before forward compuation,
|
| 116 |
+
# It may allocate new buckets before deallocating old buckets
|
| 117 |
+
# inside _rebuild_buckets. To save peak memory usage,
|
| 118 |
+
# call _rebuild_buckets before the peak memory usage increases
|
| 119 |
+
# during forward computation.
|
| 120 |
+
# This should be called only once during whole training period.
|
| 121 |
+
if torch.is_grad_enabled() and self.reducer._rebuild_buckets():
|
| 122 |
+
logging.info("Reducer buckets have been rebuilt in this iteration.")
|
| 123 |
+
self._has_rebuilt_buckets = True
|
| 124 |
+
|
| 125 |
+
# sync params according to location (before/after forward) user
|
| 126 |
+
# specified as part of hook, if hook was specified.
|
| 127 |
+
buffer_hook_registered = hasattr(self, "buffer_hook")
|
| 128 |
+
if self._check_sync_bufs_pre_fwd():
|
| 129 |
+
self._sync_buffers()
|
| 130 |
+
|
| 131 |
+
if self._join_config.enable:
|
| 132 |
+
# Notify joined ranks whether they should sync in backwards pass or not.
|
| 133 |
+
self._check_global_requires_backward_grad_sync(is_joined_rank=False)
|
| 134 |
+
|
| 135 |
+
inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids)
|
| 136 |
+
if self.module.training:
|
| 137 |
+
output = self.module.training_step(*inputs[0], **kwargs[0])
|
| 138 |
+
elif self.module.testing:
|
| 139 |
+
output = self.module.test_step(*inputs[0], **kwargs[0])
|
| 140 |
+
else:
|
| 141 |
+
output = self.module.validation_step(*inputs[0], **kwargs[0])
|
| 142 |
+
|
| 143 |
+
# sync params according to location (before/after forward) user
|
| 144 |
+
# specified as part of hook, if hook was specified.
|
| 145 |
+
if self._check_sync_bufs_post_fwd():
|
| 146 |
+
self._sync_buffers()
|
| 147 |
+
|
| 148 |
+
if torch.is_grad_enabled() and self.require_backward_grad_sync:
|
| 149 |
+
self.require_forward_param_sync = True
|
| 150 |
+
# We'll return the output object verbatim since it is a freeform
|
| 151 |
+
# object. We need to find any tensors in this object, though,
|
| 152 |
+
# because we need to figure out which parameters were used during
|
| 153 |
+
# this forward pass, to ensure we short circuit reduction for any
|
| 154 |
+
# unused parameters. Only if `find_unused_parameters` is set.
|
| 155 |
+
if self.find_unused_parameters and not self.static_graph:
|
| 156 |
+
# Do not need to populate this for static graph.
|
| 157 |
+
self.reducer.prepare_for_backward(list(_find_tensors(output)))
|
| 158 |
+
else:
|
| 159 |
+
self.reducer.prepare_for_backward([])
|
| 160 |
+
else:
|
| 161 |
+
self.require_forward_param_sync = False
|
| 162 |
+
|
| 163 |
+
# TODO: DDPSink is currently enabled for unused parameter detection and
|
| 164 |
+
# static graph training for first iteration.
|
| 165 |
+
if (self.find_unused_parameters and not self.static_graph) or (
|
| 166 |
+
self.static_graph and self.num_iterations == 1
|
| 167 |
+
):
|
| 168 |
+
state_dict = {
|
| 169 |
+
"static_graph": self.static_graph,
|
| 170 |
+
"num_iterations": self.num_iterations,
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
output_tensor_list, treespec, output_is_rref = _tree_flatten_with_rref(output)
|
| 174 |
+
output_placeholders = [None for _ in range(len(output_tensor_list))]
|
| 175 |
+
# Do not touch tensors that have no grad_fn, which can cause issues
|
| 176 |
+
# such as https://github.com/pytorch/pytorch/issues/60733
|
| 177 |
+
for i, output in enumerate(output_tensor_list):
|
| 178 |
+
if torch.is_tensor(output) and output.grad_fn is None:
|
| 179 |
+
output_placeholders[i] = output
|
| 180 |
+
|
| 181 |
+
# When find_unused_parameters=True, makes tensors which require grad
|
| 182 |
+
# run through the DDPSink backward pass. When not all outputs are
|
| 183 |
+
# used in loss, this makes those corresponding tensors receive
|
| 184 |
+
# undefined gradient which the reducer then handles to ensure
|
| 185 |
+
# param.grad field is not touched and we don't error out.
|
| 186 |
+
passthrough_tensor_list = _DDPSink.apply(
|
| 187 |
+
self.reducer,
|
| 188 |
+
state_dict,
|
| 189 |
+
*output_tensor_list,
|
| 190 |
+
)
|
| 191 |
+
for i in range(len(output_placeholders)):
|
| 192 |
+
if output_placeholders[i] is None:
|
| 193 |
+
output_placeholders[i] = passthrough_tensor_list[i]
|
| 194 |
+
|
| 195 |
+
# Reconstruct output data structure.
|
| 196 |
+
output = _tree_unflatten_with_rref(output_placeholders, treespec, output_is_rref)
|
| 197 |
+
return output
|
codec/audio_processing/quantization/distrib.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""Torch distributed utilities."""
|
| 8 |
+
|
| 9 |
+
import typing as tp
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def rank():
|
| 15 |
+
if torch.distributed.is_initialized():
|
| 16 |
+
return torch.distributed.get_rank()
|
| 17 |
+
else:
|
| 18 |
+
return 0
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def world_size():
|
| 22 |
+
if torch.distributed.is_initialized():
|
| 23 |
+
return torch.distributed.get_world_size()
|
| 24 |
+
else:
|
| 25 |
+
return 1
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def is_distributed():
|
| 29 |
+
return world_size() > 1
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def all_reduce(tensor: torch.Tensor, op=torch.distributed.ReduceOp.SUM):
|
| 33 |
+
if is_distributed():
|
| 34 |
+
return torch.distributed.all_reduce(tensor, op)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _is_complex_or_float(tensor):
|
| 38 |
+
return torch.is_floating_point(tensor) or torch.is_complex(tensor)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _check_number_of_params(params: tp.List[torch.Tensor]):
|
| 42 |
+
# utility function to check that the number of params in all workers is the same,
|
| 43 |
+
# and thus avoid a deadlock with distributed all reduce.
|
| 44 |
+
if not is_distributed() or not params:
|
| 45 |
+
return
|
| 46 |
+
# print('params[0].device ', params[0].device)
|
| 47 |
+
tensor = torch.tensor([len(params)], device=params[0].device, dtype=torch.long)
|
| 48 |
+
all_reduce(tensor)
|
| 49 |
+
if tensor.item() != len(params) * world_size():
|
| 50 |
+
# If not all the workers have the same number, for at least one of them,
|
| 51 |
+
# this inequality will be verified.
|
| 52 |
+
raise RuntimeError(
|
| 53 |
+
f"Mismatch in number of params: ours is {len(params)}, at least one worker has a different one."
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def broadcast_tensors(tensors: tp.Iterable[torch.Tensor], src: int = 0):
|
| 58 |
+
"""Broadcast the tensors from the given parameters to all workers.
|
| 59 |
+
This can be used to ensure that all workers have the same model to start with.
|
| 60 |
+
"""
|
| 61 |
+
if not is_distributed():
|
| 62 |
+
return
|
| 63 |
+
tensors = [tensor for tensor in tensors if _is_complex_or_float(tensor)]
|
| 64 |
+
_check_number_of_params(tensors)
|
| 65 |
+
handles = []
|
| 66 |
+
for tensor in tensors:
|
| 67 |
+
handle = torch.distributed.broadcast(tensor.data, src=src, async_op=True)
|
| 68 |
+
handles.append(handle)
|
| 69 |
+
for handle in handles:
|
| 70 |
+
handle.wait()
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def sync_buffer(buffers, average=True):
|
| 74 |
+
"""
|
| 75 |
+
Sync grad for buffers. If average is False, broadcast instead of averaging.
|
| 76 |
+
"""
|
| 77 |
+
if not is_distributed():
|
| 78 |
+
return
|
| 79 |
+
handles = []
|
| 80 |
+
for buffer in buffers:
|
| 81 |
+
if torch.is_floating_point(buffer.data):
|
| 82 |
+
if average:
|
| 83 |
+
handle = torch.distributed.all_reduce(buffer.data, op=torch.distributed.ReduceOp.SUM, async_op=True)
|
| 84 |
+
else:
|
| 85 |
+
handle = torch.distributed.broadcast(buffer.data, src=0, async_op=True)
|
| 86 |
+
handles.append((buffer, handle))
|
| 87 |
+
for buffer, handle in handles:
|
| 88 |
+
handle.wait()
|
| 89 |
+
if average:
|
| 90 |
+
buffer.data /= world_size
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def sync_grad(params):
|
| 94 |
+
"""
|
| 95 |
+
Simpler alternative to DistributedDataParallel, that doesn't rely
|
| 96 |
+
on any black magic. For simple models it can also be as fast.
|
| 97 |
+
Just call this on your model parameters after the call to backward!
|
| 98 |
+
"""
|
| 99 |
+
if not is_distributed():
|
| 100 |
+
return
|
| 101 |
+
handles = []
|
| 102 |
+
for p in params:
|
| 103 |
+
if p.grad is not None:
|
| 104 |
+
handle = torch.distributed.all_reduce(p.grad.data, op=torch.distributed.ReduceOp.SUM, async_op=True)
|
| 105 |
+
handles.append((p, handle))
|
| 106 |
+
for p, handle in handles:
|
| 107 |
+
handle.wait()
|
| 108 |
+
p.grad.data /= world_size()
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def average_metrics(metrics: tp.Dict[str, float], count=1.0):
|
| 112 |
+
"""Average a dictionary of metrics across all workers, using the optional
|
| 113 |
+
`count` as unormalized weight.
|
| 114 |
+
"""
|
| 115 |
+
if not is_distributed():
|
| 116 |
+
return metrics
|
| 117 |
+
keys, values = zip(*metrics.items())
|
| 118 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 119 |
+
tensor = torch.tensor(list(values) + [1], device=device, dtype=torch.float32)
|
| 120 |
+
tensor *= count
|
| 121 |
+
all_reduce(tensor)
|
| 122 |
+
averaged = (tensor[:-1] / tensor[-1]).cpu().tolist()
|
| 123 |
+
return dict(zip(keys, averaged))
|
codec/audio_processing/quantization/vq.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""Residual vector quantizer implementation."""
|
| 8 |
+
|
| 9 |
+
from dataclasses import dataclass, field
|
| 10 |
+
import math
|
| 11 |
+
import typing as tp
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
from torch import nn
|
| 15 |
+
|
| 16 |
+
# from .core_vq import ResidualVectorQuantization
|
| 17 |
+
from .core_vq_lsx_version import ResidualVectorQuantization
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class QuantizedResult:
|
| 22 |
+
quantized: torch.Tensor
|
| 23 |
+
codes: torch.Tensor
|
| 24 |
+
bandwidth: torch.Tensor # bandwidth in kb/s used, per batch item.
|
| 25 |
+
penalty: tp.Optional[torch.Tensor] = None
|
| 26 |
+
metrics: dict = field(default_factory=dict)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class ResidualVectorQuantizer(nn.Module):
|
| 30 |
+
"""Residual Vector Quantizer.
|
| 31 |
+
Args:
|
| 32 |
+
dimension (int): Dimension of the codebooks.
|
| 33 |
+
n_q (int): Number of residual vector quantizers used.
|
| 34 |
+
bins (int): Codebook size.
|
| 35 |
+
decay (float): Decay for exponential moving average over the codebooks.
|
| 36 |
+
kmeans_init (bool): Whether to use kmeans to initialize the codebooks.
|
| 37 |
+
kmeans_iters (int): Number of iterations used for kmeans initialization.
|
| 38 |
+
threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes
|
| 39 |
+
that have an exponential moving average cluster size less than the specified threshold with
|
| 40 |
+
randomly selected vector from the current batch.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def __init__(
|
| 44 |
+
self,
|
| 45 |
+
dimension: int = 256,
|
| 46 |
+
codebook_dim: int = None,
|
| 47 |
+
n_q: int = 8,
|
| 48 |
+
bins: int = 1024,
|
| 49 |
+
decay: float = 0.99,
|
| 50 |
+
kmeans_init: bool = True,
|
| 51 |
+
kmeans_iters: int = 50,
|
| 52 |
+
threshold_ema_dead_code: int = 2,
|
| 53 |
+
):
|
| 54 |
+
super().__init__()
|
| 55 |
+
self.n_q = n_q
|
| 56 |
+
self.dimension = dimension
|
| 57 |
+
self.codebook_dim = codebook_dim
|
| 58 |
+
self.bins = bins
|
| 59 |
+
self.decay = decay
|
| 60 |
+
self.kmeans_init = kmeans_init
|
| 61 |
+
self.kmeans_iters = kmeans_iters
|
| 62 |
+
self.threshold_ema_dead_code = threshold_ema_dead_code
|
| 63 |
+
self.vq = ResidualVectorQuantization(
|
| 64 |
+
dim=self.dimension,
|
| 65 |
+
codebook_dim=self.codebook_dim,
|
| 66 |
+
codebook_size=self.bins,
|
| 67 |
+
num_quantizers=self.n_q,
|
| 68 |
+
decay=self.decay,
|
| 69 |
+
kmeans_init=self.kmeans_init,
|
| 70 |
+
kmeans_iters=self.kmeans_iters,
|
| 71 |
+
threshold_ema_dead_code=self.threshold_ema_dead_code,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
def forward(self, x: torch.Tensor, sample_rate: int, bandwidth: tp.Optional[float] = None): # -> QuantizedResult:
|
| 75 |
+
"""Residual vector quantization on the given input tensor.
|
| 76 |
+
Args:
|
| 77 |
+
x (torch.Tensor): Input tensor.
|
| 78 |
+
sample_rate (int): Sample rate of the input tensor.
|
| 79 |
+
bandwidth (float): Target bandwidth.
|
| 80 |
+
Returns:
|
| 81 |
+
QuantizedResult:
|
| 82 |
+
The quantized (or approximately quantized) representation with
|
| 83 |
+
the associated bandwidth and any penalty term for the loss.
|
| 84 |
+
"""
|
| 85 |
+
bw_per_q = self.get_bandwidth_per_quantizer(sample_rate)
|
| 86 |
+
n_q = self.get_num_quantizers_for_bandwidth(sample_rate, bandwidth)
|
| 87 |
+
quantized, codes, commit_loss = self.vq(x, n_q=n_q)
|
| 88 |
+
bw = torch.tensor(n_q * bw_per_q).to(x)
|
| 89 |
+
return quantized, codes, bw, torch.mean(commit_loss)
|
| 90 |
+
# return QuantizedResult(quantized, codes, bw, penalty=torch.mean(commit_loss))
|
| 91 |
+
|
| 92 |
+
def get_num_quantizers_for_bandwidth(self, sample_rate: int, bandwidth: tp.Optional[float] = None) -> int:
|
| 93 |
+
"""Return n_q based on specified target bandwidth."""
|
| 94 |
+
bw_per_q = self.get_bandwidth_per_quantizer(sample_rate)
|
| 95 |
+
n_q = self.n_q
|
| 96 |
+
if bandwidth and bandwidth > 0.0:
|
| 97 |
+
n_q = int(max(1, math.floor(bandwidth / bw_per_q)))
|
| 98 |
+
return n_q
|
| 99 |
+
|
| 100 |
+
def get_bandwidth_per_quantizer(self, sample_rate: int):
|
| 101 |
+
"""Return bandwidth per quantizer for a given input sample rate."""
|
| 102 |
+
return math.log2(self.bins) * sample_rate / 1000
|
| 103 |
+
|
| 104 |
+
def encode(self, x: torch.Tensor, sample_rate: int, bandwidth: tp.Optional[float] = None) -> torch.Tensor:
|
| 105 |
+
"""Encode a given input tensor with the specified sample rate at the given bandwidth.
|
| 106 |
+
The RVQ encode method sets the appropriate number of quantizer to use
|
| 107 |
+
and returns indices for each quantizer.
|
| 108 |
+
"""
|
| 109 |
+
n_q = self.get_num_quantizers_for_bandwidth(sample_rate, bandwidth)
|
| 110 |
+
codes = self.vq.encode(x, n_q=n_q)
|
| 111 |
+
return codes
|
| 112 |
+
|
| 113 |
+
def decode(self, codes: torch.Tensor) -> torch.Tensor:
|
| 114 |
+
"""Decode the given codes to the quantized representation."""
|
| 115 |
+
quantized = self.vq.decode(codes)
|
| 116 |
+
return quantized
|
codec/audio_processing/semantic_module.py
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Based on code from: https://github.com/zhenye234/xcodec
|
| 2 |
+
# Licensed under MIT License
|
| 3 |
+
# Modifications by BosonAI
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Conv1d1x1(nn.Conv1d):
|
| 10 |
+
"""1x1 Conv1d."""
|
| 11 |
+
|
| 12 |
+
def __init__(self, in_channels, out_channels, bias=True):
|
| 13 |
+
super(Conv1d1x1, self).__init__(in_channels, out_channels, kernel_size=1, bias=bias)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class Conv1d(nn.Module):
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
in_channels: int,
|
| 20 |
+
out_channels: int,
|
| 21 |
+
kernel_size: int,
|
| 22 |
+
stride: int = 1,
|
| 23 |
+
padding: int = -1,
|
| 24 |
+
dilation: int = 1,
|
| 25 |
+
groups: int = 1,
|
| 26 |
+
bias: bool = True,
|
| 27 |
+
):
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.in_channels = in_channels
|
| 30 |
+
self.out_channels = out_channels
|
| 31 |
+
self.kernel_size = kernel_size
|
| 32 |
+
if padding < 0:
|
| 33 |
+
padding = (kernel_size - 1) // 2 * dilation
|
| 34 |
+
self.dilation = dilation
|
| 35 |
+
self.conv = nn.Conv1d(
|
| 36 |
+
in_channels=in_channels,
|
| 37 |
+
out_channels=out_channels,
|
| 38 |
+
kernel_size=kernel_size,
|
| 39 |
+
stride=stride,
|
| 40 |
+
padding=padding,
|
| 41 |
+
dilation=dilation,
|
| 42 |
+
groups=groups,
|
| 43 |
+
bias=bias,
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
def forward(self, x):
|
| 47 |
+
"""
|
| 48 |
+
Args:
|
| 49 |
+
x (Tensor): Float tensor variable with the shape (B, C, T).
|
| 50 |
+
Returns:
|
| 51 |
+
Tensor: Float tensor variable with the shape (B, C, T).
|
| 52 |
+
"""
|
| 53 |
+
x = self.conv(x)
|
| 54 |
+
return x
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class ResidualUnit(nn.Module):
|
| 58 |
+
def __init__(
|
| 59 |
+
self,
|
| 60 |
+
in_channels: int,
|
| 61 |
+
out_channels: int,
|
| 62 |
+
kernel_size=3,
|
| 63 |
+
dilation=1,
|
| 64 |
+
bias=False,
|
| 65 |
+
nonlinear_activation="ELU",
|
| 66 |
+
nonlinear_activation_params={},
|
| 67 |
+
):
|
| 68 |
+
super().__init__()
|
| 69 |
+
self.activation = getattr(nn, nonlinear_activation)(**nonlinear_activation_params)
|
| 70 |
+
self.conv1 = Conv1d(
|
| 71 |
+
in_channels=in_channels,
|
| 72 |
+
out_channels=out_channels,
|
| 73 |
+
kernel_size=kernel_size,
|
| 74 |
+
stride=1,
|
| 75 |
+
dilation=dilation,
|
| 76 |
+
bias=bias,
|
| 77 |
+
)
|
| 78 |
+
self.conv2 = Conv1d1x1(out_channels, out_channels, bias)
|
| 79 |
+
|
| 80 |
+
def forward(self, x):
|
| 81 |
+
y = self.conv1(self.activation(x))
|
| 82 |
+
y = self.conv2(self.activation(y))
|
| 83 |
+
return x + y
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class ConvTranspose1d(nn.Module):
|
| 87 |
+
def __init__(
|
| 88 |
+
self,
|
| 89 |
+
in_channels: int,
|
| 90 |
+
out_channels: int,
|
| 91 |
+
kernel_size: int,
|
| 92 |
+
stride: int,
|
| 93 |
+
padding=-1,
|
| 94 |
+
output_padding=-1,
|
| 95 |
+
groups=1,
|
| 96 |
+
bias=True,
|
| 97 |
+
):
|
| 98 |
+
super().__init__()
|
| 99 |
+
if padding < 0:
|
| 100 |
+
padding = (stride + 1) // 2
|
| 101 |
+
if output_padding < 0:
|
| 102 |
+
output_padding = 1 if stride % 2 else 0
|
| 103 |
+
self.deconv = nn.ConvTranspose1d(
|
| 104 |
+
in_channels=in_channels,
|
| 105 |
+
out_channels=out_channels,
|
| 106 |
+
kernel_size=kernel_size,
|
| 107 |
+
stride=stride,
|
| 108 |
+
padding=padding,
|
| 109 |
+
output_padding=output_padding,
|
| 110 |
+
groups=groups,
|
| 111 |
+
bias=bias,
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
def forward(self, x):
|
| 115 |
+
"""
|
| 116 |
+
Args:
|
| 117 |
+
x (Tensor): Float tensor variable with the shape (B, C, T).
|
| 118 |
+
Returns:
|
| 119 |
+
Tensor: Float tensor variable with the shape (B, C', T').
|
| 120 |
+
"""
|
| 121 |
+
x = self.deconv(x)
|
| 122 |
+
return x
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class EncoderBlock(nn.Module):
|
| 126 |
+
def __init__(
|
| 127 |
+
self, in_channels: int, out_channels: int, stride: int, dilations=(1, 1), unit_kernel_size=3, bias=True
|
| 128 |
+
):
|
| 129 |
+
super().__init__()
|
| 130 |
+
self.res_units = torch.nn.ModuleList()
|
| 131 |
+
for dilation in dilations:
|
| 132 |
+
self.res_units += [ResidualUnit(in_channels, in_channels, kernel_size=unit_kernel_size, dilation=dilation)]
|
| 133 |
+
self.num_res = len(self.res_units)
|
| 134 |
+
|
| 135 |
+
self.conv = Conv1d(
|
| 136 |
+
in_channels=in_channels,
|
| 137 |
+
out_channels=out_channels,
|
| 138 |
+
kernel_size=3 if stride == 1 else (2 * stride), # special case: stride=1, do not use kernel=2
|
| 139 |
+
stride=stride,
|
| 140 |
+
bias=bias,
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
def forward(self, x):
|
| 144 |
+
for idx in range(self.num_res):
|
| 145 |
+
x = self.res_units[idx](x)
|
| 146 |
+
x = self.conv(x)
|
| 147 |
+
return x
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class Encoder(nn.Module):
|
| 151 |
+
def __init__(
|
| 152 |
+
self,
|
| 153 |
+
input_channels: int,
|
| 154 |
+
encode_channels: int,
|
| 155 |
+
channel_ratios=(1, 1),
|
| 156 |
+
strides=(1, 1),
|
| 157 |
+
kernel_size=3,
|
| 158 |
+
bias=True,
|
| 159 |
+
block_dilations=(1, 1),
|
| 160 |
+
unit_kernel_size=3,
|
| 161 |
+
):
|
| 162 |
+
super().__init__()
|
| 163 |
+
assert len(channel_ratios) == len(strides)
|
| 164 |
+
|
| 165 |
+
self.conv = Conv1d(
|
| 166 |
+
in_channels=input_channels, out_channels=encode_channels, kernel_size=kernel_size, stride=1, bias=False
|
| 167 |
+
)
|
| 168 |
+
self.conv_blocks = torch.nn.ModuleList()
|
| 169 |
+
in_channels = encode_channels
|
| 170 |
+
for idx, stride in enumerate(strides):
|
| 171 |
+
out_channels = int(encode_channels * channel_ratios[idx]) # could be float
|
| 172 |
+
self.conv_blocks += [
|
| 173 |
+
EncoderBlock(
|
| 174 |
+
in_channels,
|
| 175 |
+
out_channels,
|
| 176 |
+
stride,
|
| 177 |
+
dilations=block_dilations,
|
| 178 |
+
unit_kernel_size=unit_kernel_size,
|
| 179 |
+
bias=bias,
|
| 180 |
+
)
|
| 181 |
+
]
|
| 182 |
+
in_channels = out_channels
|
| 183 |
+
self.num_blocks = len(self.conv_blocks)
|
| 184 |
+
self.out_channels = out_channels
|
| 185 |
+
|
| 186 |
+
def forward(self, x):
|
| 187 |
+
x = self.conv(x)
|
| 188 |
+
for i in range(self.num_blocks):
|
| 189 |
+
x = self.conv_blocks[i](x)
|
| 190 |
+
return x
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class DecoderBlock(nn.Module):
|
| 194 |
+
"""Decoder block (no up-sampling)"""
|
| 195 |
+
|
| 196 |
+
def __init__(
|
| 197 |
+
self, in_channels: int, out_channels: int, stride: int, dilations=(1, 1), unit_kernel_size=3, bias=True
|
| 198 |
+
):
|
| 199 |
+
super().__init__()
|
| 200 |
+
|
| 201 |
+
if stride == 1:
|
| 202 |
+
self.conv = Conv1d(
|
| 203 |
+
in_channels=in_channels,
|
| 204 |
+
out_channels=out_channels,
|
| 205 |
+
kernel_size=3, # fix kernel=3 when stride=1 for unchanged shape
|
| 206 |
+
stride=stride,
|
| 207 |
+
bias=bias,
|
| 208 |
+
)
|
| 209 |
+
else:
|
| 210 |
+
self.conv = ConvTranspose1d(
|
| 211 |
+
in_channels=in_channels,
|
| 212 |
+
out_channels=out_channels,
|
| 213 |
+
kernel_size=(2 * stride),
|
| 214 |
+
stride=stride,
|
| 215 |
+
bias=bias,
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
self.res_units = torch.nn.ModuleList()
|
| 219 |
+
for idx, dilation in enumerate(dilations):
|
| 220 |
+
self.res_units += [
|
| 221 |
+
ResidualUnit(out_channels, out_channels, kernel_size=unit_kernel_size, dilation=dilation)
|
| 222 |
+
]
|
| 223 |
+
self.num_res = len(self.res_units)
|
| 224 |
+
|
| 225 |
+
def forward(self, x):
|
| 226 |
+
x = self.conv(x)
|
| 227 |
+
for idx in range(self.num_res):
|
| 228 |
+
x = self.res_units[idx](x)
|
| 229 |
+
return x
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
class Decoder(nn.Module):
|
| 233 |
+
def __init__(
|
| 234 |
+
self,
|
| 235 |
+
code_dim: int,
|
| 236 |
+
output_channels: int,
|
| 237 |
+
decode_channels: int,
|
| 238 |
+
channel_ratios=(1, 1),
|
| 239 |
+
strides=(1, 1),
|
| 240 |
+
kernel_size=3,
|
| 241 |
+
bias=True,
|
| 242 |
+
block_dilations=(1, 1),
|
| 243 |
+
unit_kernel_size=3,
|
| 244 |
+
):
|
| 245 |
+
super().__init__()
|
| 246 |
+
assert len(channel_ratios) == len(strides)
|
| 247 |
+
|
| 248 |
+
self.conv1 = Conv1d(
|
| 249 |
+
in_channels=code_dim,
|
| 250 |
+
out_channels=int(decode_channels * channel_ratios[0]),
|
| 251 |
+
kernel_size=kernel_size,
|
| 252 |
+
stride=1,
|
| 253 |
+
bias=False,
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
self.conv_blocks = torch.nn.ModuleList()
|
| 257 |
+
for idx, stride in enumerate(strides):
|
| 258 |
+
in_channels = int(decode_channels * channel_ratios[idx])
|
| 259 |
+
if idx < (len(channel_ratios) - 1):
|
| 260 |
+
out_channels = int(decode_channels * channel_ratios[idx + 1])
|
| 261 |
+
else:
|
| 262 |
+
out_channels = decode_channels
|
| 263 |
+
self.conv_blocks += [
|
| 264 |
+
DecoderBlock(
|
| 265 |
+
in_channels,
|
| 266 |
+
out_channels,
|
| 267 |
+
stride,
|
| 268 |
+
dilations=block_dilations,
|
| 269 |
+
unit_kernel_size=unit_kernel_size,
|
| 270 |
+
bias=bias,
|
| 271 |
+
)
|
| 272 |
+
]
|
| 273 |
+
self.num_blocks = len(self.conv_blocks)
|
| 274 |
+
|
| 275 |
+
self.conv2 = Conv1d(out_channels, output_channels, kernel_size, 1, bias=False)
|
| 276 |
+
|
| 277 |
+
def forward(self, z):
|
| 278 |
+
x = self.conv1(z)
|
| 279 |
+
for i in range(self.num_blocks):
|
| 280 |
+
x = self.conv_blocks[i](x)
|
| 281 |
+
x = self.conv2(x)
|
| 282 |
+
return x
|