Transformers documentation
Liquid Codec
This model was contributed to Hugging Face Transformers on 2026-12-02.
Liquid Codec
Overview
Liquid Codec is the speech codec of LFM3-Audio by Liquid AI: 24 kHz audio to 12 codebooks of 2016 codes at 12.5 Hz, and back. It is made of a causal LFM3 encoder, a finite scalar quantizer, and a causal LFM3 decoder followed by an inverse STFT head that synthesizes the waveform.
Usage
from transformers import AutoFeatureExtractor, AutoModel
from transformers.audio_utils import load_audio
model_id, revision = "LiquidAI/Liquid-Codec", "refs/pr/1"
model = AutoModel.from_pretrained(model_id, revision=revision, device_map="auto")
feature_extractor = AutoFeatureExtractor.from_pretrained(model_id, revision=revision)
url = "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/librispeech_mr_quilter.wav"
audio = load_audio(url, sampling_rate=feature_extractor.sampling_rate)
inputs = feature_extractor(
audio=audio,
sampling_rate=feature_extractor.sampling_rate,
return_tensors="pt",
).to(model.device, model.dtype)
audio_codes = model.encode(**inputs).audio_codes
print("Audio codes shape:", audio_codes.shape)
# Audio codes shape: torch.Size([1, 12, 74])
audio_values = model.decode(audio_codes).audio_values
print("Audio values shape:", audio_values.shape)
# Audio values shape: torch.Size([1, 142080])
# or encode and decode in one step
model_output = model(**inputs)
audio_codes = model_output.audio_codes
audio_values = model_output.audio_valuesBatch processing
Pass the masks along: encode returns audio_codes_mask, decode returns audio_values_mask. Right padding only.
from transformers import AutoFeatureExtractor, AutoModel
from transformers.audio_utils import load_audio
model_id, revision = "LiquidAI/Liquid-Codec", "refs/pr/1"
model = AutoModel.from_pretrained(model_id, revision=revision, device_map="auto")
feature_extractor = AutoFeatureExtractor.from_pretrained(model_id, revision=revision)
samples = "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/"
audios = [
load_audio(samples + name, sampling_rate=feature_extractor.sampling_rate)
for name in ("librispeech_mr_quilter.wav", "dude_where_is_my_car.wav")
]
inputs = feature_extractor(
audio=audios,
sampling_rate=feature_extractor.sampling_rate,
return_tensors="pt",
).to(model.device, model.dtype)
encoder_output = model.encode(**inputs)
print("Audio codes shape:", encoder_output.audio_codes.shape)
# Audio codes shape: torch.Size([2, 12, 814])
print("Frames per clip:", encoder_output.audio_codes_mask.sum(-1).tolist())
# Frames per clip: [74, 814]
decoder_output = model.decode(
encoder_output.audio_codes,
encoder_output.audio_codes_mask,
)
print("Samples per clip:", decoder_output.audio_values_mask.sum(-1).tolist())
# Samples per clip: [142080, 1562880]
# drop the padding
audio_values = [
values[mask]
for values, mask in zip(decoder_output.audio_values, decoder_output.audio_values_mask)
]Streaming decoding
With use_streaming=True, decode returns decoder_cache and istft_cache to pass to the next chunk. istft_cache.flush() returns the last samples. audio_codes_mask is not supported.
import torch
from transformers import AutoFeatureExtractor, AutoModel
from transformers.audio_utils import load_audio
model_id, revision = "LiquidAI/Liquid-Codec", "refs/pr/1"
model = AutoModel.from_pretrained(model_id, revision=revision, device_map="auto")
feature_extractor = AutoFeatureExtractor.from_pretrained(model_id, revision=revision)
url = "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/librispeech_mr_quilter.wav"
audio = load_audio(url, sampling_rate=feature_extractor.sampling_rate)
inputs = feature_extractor(
audio=audio,
sampling_rate=feature_extractor.sampling_rate,
return_tensors="pt",
).to(model.device, model.dtype)
audio_codes = model.encode(**inputs).audio_codes
chunk_size = 4 # codec frames per chunk, arbitrary
decoder_cache, istft_cache = None, None
chunks = []
for start in range(0, audio_codes.shape[-1], chunk_size):
outputs = model.decode(
audio_codes[..., start : start + chunk_size],
decoder_cache=decoder_cache,
istft_cache=istft_cache,
use_streaming=True,
)
decoder_cache, istft_cache = outputs.decoder_cache, outputs.istft_cache
chunks.append(outputs.audio_values)
chunks.append(istft_cache.flush().audio_values)
audio_values = torch.cat(chunks, dim=-1)
print("Audio values shape:", audio_values.shape)
# Audio values shape: torch.Size([1, 142080])LiquidCodecConfig
class transformers.LiquidCodecConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneencoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = <factory>decoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = <factory>quantization_levels: list[int] | tuple[int, ...] = (8, 7, 6, 6)num_codebooks: int = 12sampling_rate: int = 24000initializer_range: float = 0.02 )
Parameters
- encoder_config (
dictor LiquidCodecEncoderConfig, optional) — Encoder config.None: no encoder (from_pretrained(..., encoder_config=None)loads the decoder only). - decoder_config (
dictor LiquidCodecDecoderConfig, optional) — Decoder config.None: no decoder (from_pretrained(..., decoder_config=None)loads the encoder only). - quantization_levels (
list[int], optional, defaults to[8, 7, 6, 6]) — Levels per FSQ dimension; their product is the codebook size. - num_codebooks (
int, optional, defaults to 12) — Number of parallel FSQ codebooks: the latent is split into this many groups, each quantized separately. - sampling_rate (
int, optional, defaults to24000) — The sampling rate at which the audio files should be digitalized expressed in hertz (Hz). - initializer_range (
float, optional, defaults to0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
This is the configuration class to store the configuration of a LiquidCodecModel. It is used to instantiate a Liquid Codec 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 LiquidAI/Liquid-Codec
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
LiquidCodecEncoderConfig
class transformers.LiquidCodecEncoderConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 512intermediate_size: int = 2304num_hidden_layers: int = 8num_attention_heads: int = 8num_key_value_heads: int = 2max_position_embeddings: int = 131072initializer_range: float = 0.02norm_eps: float = 1e-05use_cache: bool = Falserope_parameters: dict | None = Noneconv_bias: bool = Falseconv_L_cache: int = 7layer_types: list[str] | None = Nonehead_dim: int = 64sliding_window: int | None = Noneuse_sandwich_norm: bool = Trueuse_attention_gate: bool = Trueattention_bias: bool = Falseattention_dropout: float = 0.0n_fft: int = 1280subsampling_factor: int = 6subsampling_conv_channels: int = 256quantization_dim: int = 256num_codebooks: int = 12codebook_dim: int = 4 )
Parameters
- hidden_size (
int, optional, defaults to512) — Dimension of the hidden representations. - intermediate_size (
int, optional, defaults to2304) — Dimension of the MLP representations. - num_hidden_layers (
int, optional, defaults to8) — Number of hidden layers in the Transformer decoder. - num_attention_heads (
int, optional, defaults to8) — Number of attention heads for each attention layer in the Transformer decoder. - num_key_value_heads (
int, optional, defaults to2) — This is the number of key_value heads that should be used to implement Grouped Query Attention. Ifnum_key_value_heads=num_attention_heads, the model will use Multi Head Attention (MHA), ifnum_key_value_heads=1the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out this paper. If it is not specified, will default tonum_attention_heads. - max_position_embeddings (
int, optional, defaults to131072) — The maximum sequence length that this model might ever be used with. - initializer_range (
float, optional, defaults to0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - norm_eps (
float, optional, defaults to1e-05) — The epsilon used by the layer normalization layers. - use_cache (
bool, optional, defaults toFalse) — Whether or not the model should return the last key/values attentions (not used by all models). Only relevant ifconfig.is_decoder=Trueor when the model is a decoder-only generative model. - rope_parameters (
dict, optional) — Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain a value forrope_thetaand optionally parameters used for scaling in case you want to use RoPE with longermax_position_embeddings. - conv_bias (
bool, optional, defaults toFalse) — Whether to use bias in the conv layers. - conv_L_cache (
int, optional, defaults to 7) — L_cache dim in the conv layers. - layer_types (
list[str], optional) — A list that explicitly maps each layer index with its layer type. If not provided, it will be automatically generated based on config values. - head_dim (
int, optional, defaults to64) — The attention head dimension. If None, it will default to hidden_size // num_attention_heads - sliding_window (
int, optional) — Sliding window attention window size. IfNone, no sliding window is applied. - use_sandwich_norm (
bool, optional, defaults toTrue) — Whether to apply an RMSNorm to the operator and feed-forward outputs before they enter the residual stream. - use_attention_gate (
bool, optional, defaults toTrue) — Whether the attention layers scale each head’s output by a sigmoid gate computed from the layer input. - attention_bias (
bool, optional, defaults toFalse) — Whether to use a bias in the query, key, value and output projection layers during self-attention. - attention_dropout (
float, optional, defaults to0.0) — The dropout ratio for the attention probabilities. - n_fft (
int, optional, defaults to 1280) — FFT size; the input spectrogram has3 * (n_fft // 2 + 1)channels. - subsampling_factor (
int, optional, defaults to 6) — Spectrogram frames per codec frame: stride of the convolutional subsampler. - subsampling_conv_channels (
int, optional, defaults to 256) — Channels of the convolutional subsampler before the backbone. - quantization_dim (
int, optional, defaults to 256) — Width of the bottleneck between the backbone and the quantizer projection. - num_codebooks (
int, optional, defaults to 12) — Number of FSQ codebooks the output latent is split into. - codebook_dim (
int, optional, defaults to 4) — FSQ dimensions per codebook: the output latent hasnum_codebooks * codebook_dimchannels.
This is the configuration class to store the configuration of a LiquidCodecModel. It is used to instantiate a Liquid Codec 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 LiquidAI/Liquid-Codec
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
LiquidCodecDecoderConfig
class transformers.LiquidCodecDecoderConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 512intermediate_size: int = 2304num_hidden_layers: int = 8num_attention_heads: int = 8num_key_value_heads: int = 2max_position_embeddings: int = 131072initializer_range: float = 0.02norm_eps: float = 1e-05use_cache: bool = Falserope_parameters: dict | None = Noneconv_bias: bool = Falseconv_L_cache: int = 7layer_types: list[str] | None = Nonehead_dim: int = 64sliding_window: int | None = 30use_sandwich_norm: bool = Trueuse_attention_gate: bool = Trueattention_bias: bool = Falseattention_dropout: float = 0.0n_fft: int = 1280hop_length: int = 320upsampling_factor: int = 6quantization_dim: int = 256num_codebooks: int = 12codebook_dim: int = 4 )
Parameters
- hidden_size (
int, optional, defaults to512) — Dimension of the hidden representations. - intermediate_size (
int, optional, defaults to2304) — Dimension of the MLP representations. - num_hidden_layers (
int, optional, defaults to8) — Number of hidden layers in the Transformer decoder. - num_attention_heads (
int, optional, defaults to8) — Number of attention heads for each attention layer in the Transformer decoder. - num_key_value_heads (
int, optional, defaults to2) — This is the number of key_value heads that should be used to implement Grouped Query Attention. Ifnum_key_value_heads=num_attention_heads, the model will use Multi Head Attention (MHA), ifnum_key_value_heads=1the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out this paper. If it is not specified, will default tonum_attention_heads. - max_position_embeddings (
int, optional, defaults to131072) — The maximum sequence length that this model might ever be used with. - initializer_range (
float, optional, defaults to0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - norm_eps (
float, optional, defaults to1e-05) — The epsilon used by the layer normalization layers. - use_cache (
bool, optional, defaults toFalse) — Whether or not the model should return the last key/values attentions (not used by all models). Only relevant ifconfig.is_decoder=Trueor when the model is a decoder-only generative model. - rope_parameters (
dict, optional) — Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain a value forrope_thetaand optionally parameters used for scaling in case you want to use RoPE with longermax_position_embeddings. - conv_bias (
bool, optional, defaults toFalse) — Whether to use bias in the conv layers. - conv_L_cache (
int, optional, defaults to 7) — L_cache dim in the conv layers. - layer_types (
list[str], optional) — A list that explicitly maps each layer index with its layer type. If not provided, it will be automatically generated based on config values. - head_dim (
int, optional, defaults to64) — The attention head dimension. If None, it will default to hidden_size // num_attention_heads - sliding_window (
int, optional, defaults to30) — Sliding window attention window size. IfNone, no sliding window is applied. - use_sandwich_norm (
bool, optional, defaults toTrue) — Whether to apply an RMSNorm to the operator and feed-forward outputs before they enter the residual stream. - use_attention_gate (
bool, optional, defaults toTrue) — Whether the attention layers scale each head’s output by a sigmoid gate computed from the layer input. - attention_bias (
bool, optional, defaults toFalse) — Whether to use a bias in the query, key, value and output projection layers during self-attention. - attention_dropout (
float, optional, defaults to0.0) — The dropout ratio for the attention probabilities. - n_fft (
int, optional, defaults to 1280) — Synthesis FFT size. - hop_length (
int, optional, defaults to 320) — Synthesis hop length. - upsampling_factor (
int, optional, defaults to 6) — STFT frames per codec frame: each codec frame is repeated this many times before the backbone. - quantization_dim (
int, optional, defaults to 256) — Width of the bottleneck between the quantizer projection and the backbone. - num_codebooks (
int, optional, defaults to 12) — Number of FSQ codebooks the input latent is made of. - codebook_dim (
int, optional, defaults to 4) — FSQ dimensions per codebook: the input latent hasnum_codebooks * codebook_dimchannels.
This is the configuration class to store the configuration of a LiquidCodecModel. It is used to instantiate a Liquid Codec 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 LiquidAI/Liquid-Codec
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
LiquidCodecFeatureExtractor
class transformers.LiquidCodecFeatureExtractor
< source >( sampling_rate = 24000n_fft = 1280hop_length = 320win_length = 1280subsampling_factor = 6padding_value = 0.0**kwargs )
Parameters
- sampling_rate (
int, optional, defaults to 24000) — The sampling rate at which the audio files should be digitalized expressed in hertz (Hz). - n_fft (
int, optional, defaults to 1280) — Size of the Fourier transform. - hop_length (
int, optional, defaults to 320) — Length of the overlapping windows for the STFT. - win_length (
int, optional, defaults to 1280) — The window length for the STFT computation. - subsampling_factor (
int, optional, defaults to 6) — Spectrogram frames per codec frame; clips are zero-padded to whole codec frames. - padding_value (
float, optional, defaults to 0.0) — Padding value used to pad the spectrograms of a batch.
Constructs a Liquid Codec 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.
Extracts the encoder’s spectrogram with torch.stft: per frequency bin, log magnitude and phase (real and
imaginary parts over the magnitude).
__call__
< source >( audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], list[float], list[list[float]]]padding: bool | str | transformers.utils.generic.PaddingStrategy = Truemax_length: int | None = Nonetruncation: bool = Falsereturn_tensors: str | transformers.utils.generic.TensorType | None = Nonesampling_rate: int | None = Nonedevice: str | None = 'cpu'**kwargs ) → BatchFeature
Parameters
- audio (
np.ndarray,list[float],list[np.ndarray],list[list[float]],torch.Tensor) — The sequence or batch of sequences to featurize. Must be mono channel audio, not stereo, i.e. single float per timestep. - padding (
bool,stror PaddingStrategy, optional, defaults toTrue) — Select a strategy to pad the returned sequences among:Trueor'longest': Pad to the longest clip of the batch.'max_length': Pad tomax_lengthsamples.Falseor'do_not_pad': No padding: the clips must have the same number of codec frames.
Whatever the strategy, each clip is first zero-padded to whole codec frames.
- max_length (
int, optional) — Length in samples to truncate / pad to, rounded up to whole codec frames. - truncation (
bool, optional, defaults toFalse) — Whether to cut clips longer thanmax_length. - return_tensors (
stror TensorType, optional) — If set, will return tensors instead of list of python integers. Acceptable values are:'pt': Return PyTorchtorch.Tensorobjects.'np': Return Numpynp.ndarrayobjects.
- sampling_rate (
int, optional) — The sampling rate at which theaudioinput was sampled. It is strongly recommended to passsampling_rateat the forward call to prevent silent errors. - device (
str, optional, defaults to'cpu') — Specifies the device for computation of the spectrogram of audio signals in the_torch_extract_fbank_featuresmethod. (e.g., “cpu”, “cuda”)
Returns
input_features of shape (batch_size, feature_size, num_frames), right-padded to
the longest clip, and input_features_mask of shape (batch_size, num_frames).
Main method to featurize and prepare for the model one or several sequence(s).
LiquidCodecISTFTCache
Streaming cache of LiquidCodecISTFTHead.
With the default n_fft = 1280, hop_length = 320, upsampling_factor = 6, in samples:
codec frame = upsampling_factor * hop_length = 1920 cache = n_fft - hop_length = 960 pad = (n_fft - hop_length) // 2 = 480 first emit = codec frame - pad = 1440
codec frames ├──── codec frame 0 ────┼──── codec frame 1 ────┼──── codec frame 2 ────┤ spec frames 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 chunk 0 ├──────── windows of frames 0-5 ────┤ chunk 1 ├─────── windows of frames 6-11 ────┤ chunk 2 ├─────── windows of frames 12-17 ───┤
update 0 ├─pad─┼─── emit 1440 ───┼ cache 960 ┤ update 1 ├────── emit 1920 ──────┼ cache 960 ┤ update 2 ├────── emit 1920 ──────┼ cache 960 ┤ … flush (last cache) ├─480─┼─pad─┤
Per-chunk ISTFT: normalized by the chunk’s own envelope (sum of its squared windows). Crossfade over the overlap restores the full one, as non-streaming:
fade_out = tail_envelope / (tail_envelope + head_envelope) tail: previous chunk’s last 960 samples (cache) fade_in = head_envelope / (tail_envelope + head_envelope) head: new chunk’s first 960 samples emitted = overlap_samples fade_out + head fade_in
Crossfades the cached samples with the start of a chunk, then caches its last ones. Returns the samples no later chunk overlaps.
Ends the stream: last samples, up to the padding, then resets the cache.
LiquidCodecModel
class transformers.LiquidCodecModel
< source >( config: LiquidCodecConfig )
Parameters
- config (LiquidCodecConfig) — 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 Liquid Codec audio tokenizer.
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.
encode
< source >( input_features: FloatTensorinput_features_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → LiquidCodecEncoderOutput or tuple(torch.Tensor)
Parameters
- input_features (
torch.FloatTensorof shape(batch_size, feature_size, num_frames)) — Spectrogram from LiquidCodecFeatureExtractor. - input_features_mask (
torch.Tensorof shape(batch_size, num_frames), optional) — Valid spectrogram frames of each clip (right-padded); returnsaudio_codes_mask. - Encodes the spectrogram into discrete codes of shape
(batch_size, num_codebooks, num_frames)— the latents of - LiquidCodecEncoderModel.forward(), quantized. —
Returns
LiquidCodecEncoderOutput or tuple(torch.Tensor)
A LiquidCodecEncoderOutput or a tuple of
torch.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (LiquidCodecConfig) and inputs.
- audio_codes (
torch.LongTensorof shape(batch_size, num_codebooks, num_frames)) — Codes, per codebook and frame. - audio_codes_mask (
torch.BoolTensorof shape(batch_size, num_frames), optional, returned with aninput_features_mask) — Valid frames of each clip. - hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=True) — Hidden states of the encoder at the output of each layer plus its input. - attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=True) — Attention weights of each attention layer of the encoder.
decode
< source >( audio_codes: LongTensoraudio_codes_mask: typing.Optional[torch.Tensor] = Nonedecoder_cache: transformers.cache_utils.Cache | None = Noneistft_cache: transformers.models.liquid_codec.modeling_liquid_codec.LiquidCodecISTFTCache | None = Noneuse_streaming: bool = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → LiquidCodecDecoderOutput or tuple(torch.Tensor)
Parameters
- audio_codes (
torch.LongTensorof shape(batch_size, num_codebooks, num_frames)) — Codes to decode;hop_length * upsampling_factorsamples per frame. - audio_codes_mask (
torch.Tensorof shape(batch_size, num_frames), optional) — Valid frames of each clip (right-padded): each clip decoded as alone; returnsaudio_values_mask. Not supported when streaming, which decodes one stream per batch row. - decoder_cache (
Cache, optional) — Decoder cache from the previous chunk. - istft_cache (LiquidCodecISTFTCache, optional) — ISTFT cache from the previous chunk.
- use_streaming (
bool, optional, defaults toFalse) — Decode chunk by chunk: caches created on the first chunk, returned with each. Trailing samples stay inistft_cacheuntilistft_cache.flush(). - Decodes the codes into audio — the codes are dequantized into the latents of LiquidCodecDecoderModel.forward().
Returns
LiquidCodecDecoderOutput or tuple(torch.Tensor)
A LiquidCodecDecoderOutput or a tuple of
torch.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (LiquidCodecConfig) and inputs.
- audio_values (
torch.FloatTensorof shape(batch_size, num_samples)) — Decoded audio, float32, at the codec’ssampling_rate. - audio_values_mask (
torch.BoolTensorof shape(batch_size, num_samples), optional, returned with anaudio_codes_mask) — Samples decoded from the valid frames of each clip. - decoder_cache (
Cache, optional, returned when streaming) — Decoder cache, to pass with the next chunk. - istft_cache (
[LiquidCodecISTFTCache](/docs/transformers/main/en/model_doc/liquid_codec#transformers.LiquidCodecISTFTCache), optional, returned when streaming) — ISTFT cache, to pass with the next chunk;flush()ends the stream. - hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=True) — Hidden states of the decoder at the output of each layer plus its input. - attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=True) — Attention weights of each attention layer of the decoder.
forward
< source >( input_features: FloatTensorinput_features_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → LiquidCodecOutput or tuple(torch.Tensor)
Parameters
- input_features (
torch.FloatTensorof shape(batch_size, feature_size, num_frames)) — Spectrogram from LiquidCodecFeatureExtractor. - input_features_mask (
torch.Tensorof shape(batch_size, num_frames), optional) — Valid spectrogram frames of each clip (right-padded): each clip decoded as alone.
Returns
LiquidCodecOutput or tuple(torch.Tensor)
A LiquidCodecOutput or a tuple of
torch.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (LiquidCodecConfig) and inputs.
The LiquidCodecModel forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
- audio_values (
torch.FloatTensorof shape(batch_size, num_samples)) — Reconstructed audio. - audio_values_mask (
torch.BoolTensorof shape(batch_size, num_samples), optional, returned with aninput_features_mask) — Samples decoded from the valid frames of each clip. - audio_codes (
torch.LongTensorof shape(batch_size, num_codebooks, num_frames)) — Codes, per codebook and frame. - audio_codes_mask (
torch.BoolTensorof shape(batch_size, num_frames), optional, returned with aninput_features_mask) — Valid frames of each clip. - hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=True) — Hidden states of the encoder at the output of each layer plus its input. - attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=True) — Attention weights of each attention layer of the encoder.
LiquidCodecEncoderModel
class transformers.LiquidCodecEncoderModel
< source >( config: LiquidCodecEncoderConfig )
Parameters
- config (LiquidCodecEncoderConfig) — 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 encoder half of Liquid Codec: embedder, LFM3 layers and output projections, from spectrogram to the continuous latents of the FSQ quantizer.
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.
forward
< source >( input_features: FloatTensorinput_features_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → LiquidCodecEncoderModelOutput or tuple(torch.Tensor)
Parameters
- input_features (
torch.FloatTensorof shape(batch_size, feature_size, num_frames)) — Spectrogram from LiquidCodecFeatureExtractor, whole codec frames per clip. - input_features_mask (
torch.Tensorof shape(batch_size, num_frames), optional) — Valid spectrogram frames of each clip (right-padded); returnslatents_mask.
Returns
LiquidCodecEncoderModelOutput or tuple(torch.Tensor)
A LiquidCodecEncoderModelOutput or a tuple of
torch.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (LiquidCodecConfig) and inputs.
The LiquidCodecEncoderModel forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
- latents (
torch.FloatTensorof shape(batch_size, num_codebooks * codebook_dim, num_frames)) — Latents given to the FSQ quantizer, one per codec frame. - latents_mask (
torch.BoolTensorof shape(batch_size, num_frames), optional, returned with aninput_features_mask) — Valid frames of each clip. - hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=True) — Hidden states of the encoder at the output of each layer plus its input. - attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=True) — Attention weights of each attention layer of the encoder.
LiquidCodecDecoderModel
class transformers.LiquidCodecDecoderModel
< source >( config: LiquidCodecDecoderConfig )
Parameters
- config (LiquidCodecDecoderConfig) — 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 decoder half of Liquid Codec: input projection, upsampler, LFM3 layers and ISTFT head, from FSQ values to audio.
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.
forward
< source >( latents: FloatTensorlatents_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneistft_cache: transformers.models.liquid_codec.modeling_liquid_codec.LiquidCodecISTFTCache | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → LiquidCodecDecoderOutput or tuple(torch.Tensor)
Parameters
- latents (
torch.FloatTensorof shape(batch_size, num_codebooks * codebook_dim, num_frames)) — FSQ values from the quantizer, one per codec frame. - latents_mask (
torch.Tensorof shape(batch_size, num_frames), optional) — Valid frames of each clip (right-padded): each clip decoded as alone; returnsaudio_values_mask. - position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1]. - cache (
~cache_utils.Cache, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in thecachereturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
cacheare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
cacheare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - istft_cache (LiquidCodecISTFTCache, optional) — ISTFT cache from the previous chunk.
Returns
LiquidCodecDecoderOutput or tuple(torch.Tensor)
A LiquidCodecDecoderOutput or a tuple of
torch.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (LiquidCodecConfig) and inputs.
The LiquidCodecDecoderModel forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
- audio_values (
torch.FloatTensorof shape(batch_size, num_samples)) — Decoded audio, float32, at the codec’ssampling_rate. - audio_values_mask (
torch.BoolTensorof shape(batch_size, num_samples), optional, returned with anaudio_codes_mask) — Samples decoded from the valid frames of each clip. - decoder_cache (
Cache, optional, returned when streaming) — Decoder cache, to pass with the next chunk. - istft_cache (
[LiquidCodecISTFTCache](/docs/transformers/main/en/model_doc/liquid_codec#transformers.LiquidCodecISTFTCache), optional, returned when streaming) — ISTFT cache, to pass with the next chunk;flush()ends the stream. - hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=True) — Hidden states of the decoder at the output of each layer plus its input. - attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=True) — Attention weights of each attention layer of the decoder.