EnCodec
EnCodec
Overview
The EnCodec neural codec model was proposed in High Fidelity Neural Audio Compression by Alexandre Défossez, Jade Copet, Gabriel Synnaeve, Yossi Adi.
The abstract from the paper is the following:
We introduce a state-of-the-art real-time, high-fidelity, audio codec leveraging neural networks. It consists in a streaming encoder-decoder architecture with quantized latent space trained in an end-to-end fashion. We simplify and speed-up the training by using a single multiscale spectrogram adversary that efficiently reduces artifacts and produce high-quality samples. We introduce a novel loss balancer mechanism to stabilize training: the weight of a loss now defines the fraction of the overall gradient it should represent, thus decoupling the choice of this hyper-parameter from the typical scale of the loss. Finally, we study how lightweight Transformer models can be used to further compress the obtained representation by up to 40%, while staying faster than real time. We provide a detailed description of the key design choices of the proposed model including: training objective, architectural changes and a study of various perceptual loss functions. We present an extensive subjective evaluation (MUSHRA tests) together with an ablation study for a range of bandwidths and audio domains, including speech, noisy-reverberant speech, and music. Our approach is superior to the baselines methods across all evaluated settings, considering both 24 kHz monophonic and 48 kHz stereophonic audio.
This model was contributed by Matthijs, Patrick Von Platen and Arthur Zucker. The original code can be found here. Here is a quick example of how to encode and decode an audio using this model:
Copied
EncodecConfig
class transformers.EncodecConfig
( target_bandwidths = [1.5, 3.0, 6.0, 12.0, 24.0]sampling_rate = 24000audio_channels = 1normalize = Falsechunk_length_s = Noneoverlap = Nonehidden_size = 128num_filters = 32num_residual_layers = 1upsampling_ratios = [8, 5, 4, 2]norm_type = 'weight_norm'kernel_size = 7last_kernel_size = 7residual_kernel_size = 3dilation_growth_rate = 2use_causal_conv = Truepad_mode = 'reflect'compress = 2num_lstm_layers = 2trim_right_ratio = 1.0codebook_size = 1024codebook_dim = Noneuse_conv_shortcut = True**kwargs )
Parameters
target_bandwidths (
List[float]
, optional, defaults to[1.5, 3.0, 6.0, 12.0, 24.0]
) — The range of diffent bandwiths the model can encode audio with.sampling_rate (
int
, optional, defaults to 24000) — The sampling rate at which the audio waveform should be digitalized expressed in hertz (Hz).audio_channels (
int
, optional, defaults to 1) — Number of channels in the audio data. Either 1 for mono or 2 for stereo.normalize (
bool
, optional, defaults toFalse
) — Whether the audio shall be normalized when passed.chunk_length_s (
float
, optional) — If defined the audio is pre-processed into chunks of lengthschunk_length_s
and then encoded.overlap (
float
, optional) — Defines the overlap between each chunk. It is used to compute thechunk_stride
using the following formulae :int((1.0 - self.overlap) * self.chunk_length)
.hidden_size (
int
, optional, defaults to 128) — Intermediate representation dimension.num_filters (
int
, optional, defaults to 32) — Number of convolution kernels of firstEncodecConv1d
down sampling layer.num_residual_layers (
int
, optional, defaults to 1) — Number of residual layers.upsampling_ratios (
Sequence[int]
, optional, defaults to[8, 5, 4, 2]
) — Kernel size and stride ratios. The encoder uses downsampling ratios instead of upsampling ratios, hence it will use the ratios in the reverse order to the ones specified here that must match the decoder order.norm_type (
str
, optional, defaults to"weight_norm"
) — Normalization method. Should be in["weight_norm", "time_group_norm"]
kernel_size (
int
, optional, defaults to 7) — Kernel size for the initial convolution.last_kernel_size (
int
, optional, defaults to 7) — Kernel size for the last convolution layer.residual_kernel_size (
int
, optional, defaults to 3) — Kernel size for the residual layers.dilation_growth_rate (
int
, optional, defaults to 2) — How much to increase the dilation with each layer.use_causal_conv (
bool
, optional, defaults toTrue
) — Whether to use fully causal convolution.pad_mode (
str
, optional, defaults to"reflect"
) — Padding mode for the convolutions.compress (
int
, optional, defaults to 2) — Reduced dimensionality in residual branches (from Demucs v3).num_lstm_layers (
int
, optional, defaults to 2) — Number of LSTM layers at the end of the encoder.trim_right_ratio (
float
, optional, defaults to 1.0) — Ratio for trimming at the right of the transposed convolution under theuse_causal_conv = True
setup. If equal to 1.0, it means that all the trimming is done at the right.codebook_size (
int
, optional, defaults to 1024) — Number of discret codes that make up VQVAE.codebook_dim (
int
, optional) — Dimension of the codebook vectors. If not defined, useshidden_size
.use_conv_shortcut (
bool
, optional, defaults toTrue
) — Whether to use a convolutional layer as the ‘skip’ connection in theEncodecResnetBlock
block. If False, an identity function will be used, giving a generic residual connection.
This is the configuration class to store the configuration of an EncodecModel. It is used to instantiate a Encodec model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the facebook/encodec_24khz architecture.
Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.
Example:
Copied
EncodecFeatureExtractor
class transformers.EncodecFeatureExtractor
( feature_size: int = 1sampling_rate: int = 24000padding_value: float = 0.0chunk_length_s: float = Noneoverlap: float = None**kwargs )
Parameters
feature_size (
int
, optional, defaults to 1) — The feature dimension of the extracted features. Use 1 for mono, 2 for stereo.sampling_rate (
int
, optional, defaults to 24000) — The sampling rate at which the audio waveform should be digitalized expressed in hertz (Hz).padding_value (
float
, optional, defaults to 0.0) — The value that is used to fill the padding values.chunk_length_s (
float
, optional) — If defined the audio is pre-processed into chunks of lengthschunk_length_s
and then encoded.overlap (
float
, optional) — Defines the overlap between each chunk. It is used to compute thechunk_stride
using the following formulae :int((1.0 - self.overlap) * self.chunk_length)
.
Constructs an EnCodec feature extractor.
This feature extractor inherits from SequenceFeatureExtractor which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.
Instantiating a feature extractor with the defaults will yield a similar configuration to that of the facebook/encodec_24khz architecture.
__call__
( raw_audio: typing.Union[numpy.ndarray, typing.List[float], typing.List[numpy.ndarray], typing.List[typing.List[float]]]padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy, NoneType] = Nonetruncation: typing.Optional[bool] = Falsemax_length: typing.Optional[int] = Nonereturn_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = Nonesampling_rate: typing.Optional[int] = None )
Parameters
raw_audio (
np.ndarray
,List[float]
,List[np.ndarray]
,List[List[float]]
) — The sequence or batch of sequences to be processed. Each sequence can be a numpy array, a list of float values, a list of numpy arrays or a list of list of float values. The numpy array must be of shape(num_samples,)
for mono audio (feature_size = 1
), or(2, num_samples)
for stereo audio (feature_size = 2
).padding (
bool
,str
or PaddingStrategy, optional, defaults toTrue
) — Select a strategy to pad the returned sequences (according to the model’s padding side and padding index) among:True
or'longest'
: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided).'max_length'
: Pad to a maximum length specified with the argumentmax_length
or to the maximum acceptable input length for the model if that argument is not provided.False
or'do_not_pad'
(default): No padding (i.e., can output a batch with sequences of different lengths).
truncation (
bool
, optional, defaults toFalse
) — Activates truncation to cut input sequences longer thanmax_length
tomax_length
.max_length (
int
, optional) — Maximum length of the returned list and optionally padding length (see above).return_tensors (
str
or TensorType, optional) — If set, will return tensors instead of list of python integers. Acceptable values are:'tf'
: Return TensorFlowtf.constant
objects.'pt'
: Return PyTorchtorch.Tensor
objects.'np'
: Return Numpynp.ndarray
objects.
sampling_rate (
int
, optional) — The sampling rate at which theaudio
input was sampled. It is strongly recommended to passsampling_rate
at the forward call to prevent silent errors.
Main method to featurize and prepare for the model one or several sequence(s).
EncodecModel
class transformers.EncodecModel
( config: EncodecConfig )
Parameters
config (EncodecConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The EnCodec neural audio codec model. This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
decode
( audio_codes: Tensoraudio_scales: Tensorpadding_mask: typing.Optional[torch.Tensor] = Nonereturn_dict: typing.Optional[bool] = None )
Parameters
audio_codes (
torch.FloatTensor
of shape(batch_size, nb_chunks, chunk_length)
, optional) — Discret code embeddings computed usingmodel.encode
.audio_scales (
torch.Tensor
of shape(batch_size, nb_chunks)
, optional) — Scaling factor for eachaudio_codes
input.padding_mask (
torch.Tensor
of shape(batch_size, channels, sequence_length)
) — Padding mask used to pad theinput_values
.return_dict (
bool
, optional) — Whether or not to return a ModelOutput instead of a plain tuple.
Decodes the given frames into an output audio waveform.
Note that the output might be a bit bigger than the input. In that case, any extra steps at the end can be trimmed.
encode
( input_values: Tensorpadding_mask: Tensor = Nonebandwidth: typing.Optional[float] = Nonereturn_dict: typing.Optional[bool] = None )
Parameters
input_values (
torch.Tensor
of shape(batch_size, channels, sequence_length)
) — Float values of the input audio waveform.padding_mask (
torch.Tensor
of shape(batch_size, channels, sequence_length)
) — Padding mask used to pad theinput_values
.bandwidth (
float
, optional) — The target bandwidth. Must be one ofconfig.target_bandwidths
. IfNone
, uses the smallest possible bandwidth. bandwidth is represented as a thousandth of what it is, e.g. 6kbps bandwidth is represented as bandwidth == 6.0
Encodes the input audio waveform into discrete codes.
forward
( input_values: Tensorpadding_mask: typing.Optional[torch.Tensor] = Nonebandwidth: typing.Optional[float] = Noneaudio_codes: typing.Optional[torch.Tensor] = Noneaudio_scales: typing.Optional[torch.Tensor] = Nonereturn_dict: typing.Optional[bool] = None ) → transformers.models.encodec.modeling_encodec.EncodecOutput
or tuple(torch.FloatTensor)
Parameters
input_values (
torch.FloatTensor
of shape(batch_size, channels, sequence_length)
, optional) — Raw audio input converted to Float and padded to the approriate length in order to be encoded using chunks of length self.chunk_length and a stride ofconfig.chunk_stride
.padding_mask (
torch.BoolTensor
of shape(batch_size, channels, sequence_length)
, optional) — Mask to avoid computing scaling factors on padding token indices (can we avoid computing conv on these+). Mask values selected in[0, 1]
:1 for tokens that are not masked,
0 for tokens that are masked.
padding_mask
should always be passed, unless the input was truncated or not padded. This is because in order to process tensors effectively, the input audio should be padded so thatinput_length % stride = step
withstep = chunk_length-stride
. This ensures that all chunks are of the same shapebandwidth (
float
, optional) — The target bandwidth. Must be one ofconfig.target_bandwidths
. IfNone
, uses the smallest possible bandwidth. bandwidth is represented as a thousandth of what it is, e.g. 6kbps bandwidth is represented asbandwidth == 6.0
audio_codes (
torch.FloatTensor
of shape(batch_size, nb_chunks, chunk_length)
, optional) — Discret code embeddings computed usingmodel.encode
.audio_scales (
torch.Tensor
of shape(batch_size, nb_chunks)
, optional) — Scaling factor for eachaudio_codes
input.return_dict (
bool
, optional) — Whether or not to return a ModelOutput instead of a plain tuple.
Returns
transformers.models.encodec.modeling_encodec.EncodecOutput
or tuple(torch.FloatTensor)
A transformers.models.encodec.modeling_encodec.EncodecOutput
or a tuple of torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the configuration (EncodecConfig) and inputs.
audio_codes (
torch.FloatTensor
of shape(batch_size, nb_chunks, chunk_length)
, optional) — Discret code embeddings computed usingmodel.encode
.audio_values (
torch.FlaotTensor
of shape(batch_size, sequence_length)
, optional) Decoded audio values, obtained using the decoder part of Encodec.
The EncodecModel forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Examples:
Copied
Last updated