> Agents: page URLs you remember may be outdated. Fetch https://huggingface.co/docs/transformers/main/llms.txt to find the right page first, and add `.md` to a page's path (before any `#`) to get Markdown instead of HTML. To search these docs, use the Hugging Face MCP server: https://huggingface.co/mcp

# Liquid Codec

## Overview

Liquid Codec is the speech codec of LFM3-Audio by [Liquid AI](https://liquid.ai/): 24 kHz audio to 12 codebooks of
2016 codes at 12.5 Hz, and back. It is made of a causal [LFM3](./lfm3) encoder, a finite scalar quantizer, and a causal
LFM3 decoder followed by an inverse STFT head that synthesizes the waveform.

## Usage

```python
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_values
```

### Batch processing

Pass the masks along: `encode` returns `audio_codes_mask`, `decode` returns `audio_values_mask`. Right padding only.

```python
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.

```python
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[[transformers.LiquidCodecConfig]]

#### transformers.LiquidCodecConfig[[transformers.LiquidCodecConfig]]

```python
transformers.LiquidCodecConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, encoder_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 = 12, sampling_rate: int = 24000, initializer_range: float = 0.02)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/liquid_codec/configuration_liquid_codec.py#L200)

**Parameters:**

encoder_config (`dict` or [LiquidCodecEncoderConfig](/docs/transformers/main/en/model_doc/liquid_codec#transformers.LiquidCodecEncoderConfig), *optional*) : Encoder config. `None`: no encoder (`from_pretrained(..., encoder_config=None)` loads the decoder only).

decoder_config (`dict` or [LiquidCodecDecoderConfig](/docs/transformers/main/en/model_doc/liquid_codec#transformers.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 to `24000`) : The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).

initializer_range (`float`, *optional*, defaults to `0.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](https://huggingface.co/LiquidAI/Liquid-Codec)

Configuration objects inherit from [PreTrainedConfig](/docs/transformers/main/en/main_classes/configuration#transformers.PreTrainedConfig) and can be used to control the model outputs. Read the
documentation from [PreTrainedConfig](/docs/transformers/main/en/main_classes/configuration#transformers.PreTrainedConfig) for more information.

## LiquidCodecEncoderConfig[[transformers.LiquidCodecEncoderConfig]]

#### transformers.LiquidCodecEncoderConfig[[transformers.LiquidCodecEncoderConfig]]

```python
transformers.LiquidCodecEncoderConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 512, intermediate_size: int = 2304, num_hidden_layers: int = 8, num_attention_heads: int = 8, num_key_value_heads: int = 2, max_position_embeddings: int = 131072, initializer_range: float = 0.02, norm_eps: float = 1e-05, use_cache: bool = False, rope_parameters: dict | None = None, conv_bias: bool = False, conv_L_cache: int = 7, layer_types: list[str] | None = None, head_dim: int = 64, sliding_window: int | None = None, use_sandwich_norm: bool = True, use_attention_gate: bool = True, attention_bias: bool = False, attention_dropout: float = 0.0, n_fft: int = 1280, subsampling_factor: int = 6, subsampling_conv_channels: int = 256, quantization_dim: int = 256, num_codebooks: int = 12, codebook_dim: int = 4)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/liquid_codec/configuration_liquid_codec.py#L32)

**Parameters:**

hidden_size (`int`, *optional*, defaults to `512`) : Dimension of the hidden representations.

intermediate_size (`int`, *optional*, defaults to `2304`) : Dimension of the MLP representations.

num_hidden_layers (`int`, *optional*, defaults to `8`) : Number of hidden layers in the Transformer decoder.

num_attention_heads (`int`, *optional*, defaults to `8`) : Number of attention heads for each attention layer in the Transformer decoder.

num_key_value_heads (`int`, *optional*, defaults to `2`) : This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the 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](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `num_attention_heads`.

max_position_embeddings (`int`, *optional*, defaults to `131072`) : The maximum sequence length that this model might ever be used with.

initializer_range (`float`, *optional*, defaults to `0.02`) : The standard deviation of the truncated_normal_initializer for initializing all weight matrices.

norm_eps (`float`, *optional*, defaults to `1e-05`) : The epsilon used by the layer normalization layers.

use_cache (`bool`, *optional*, defaults to `False`) : Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True` or 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 for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE with longer `max_position_embeddings`.

conv_bias (`bool`, *optional*, defaults to `False`) : 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 to `64`) : The attention head dimension. If None, it will default to hidden_size // num_attention_heads

sliding_window (`int`, *optional*) : Sliding window attention window size. If `None`, no sliding window is applied.

use_sandwich_norm (`bool`, *optional*, defaults to `True`) : Whether to apply an RMSNorm to the operator and feed-forward outputs before they enter the residual stream.

use_attention_gate (`bool`, *optional*, defaults to `True`) : Whether the attention layers scale each head's output by a sigmoid gate computed from the layer input.

attention_bias (`bool`, *optional*, defaults to `False`) : Whether to use a bias in the query, key, value and output projection layers during self-attention.

attention_dropout (`float`, *optional*, defaults to `0.0`) : The dropout ratio for the attention probabilities.

n_fft (`int`, *optional*, defaults to 1280) : FFT size; the input spectrogram has `3 * (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 has `num_codebooks * codebook_dim` channels.

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](https://huggingface.co/LiquidAI/Liquid-Codec)

Configuration objects inherit from [PreTrainedConfig](/docs/transformers/main/en/main_classes/configuration#transformers.PreTrainedConfig) and can be used to control the model outputs. Read the
documentation from [PreTrainedConfig](/docs/transformers/main/en/main_classes/configuration#transformers.PreTrainedConfig) for more information.

## LiquidCodecDecoderConfig[[transformers.LiquidCodecDecoderConfig]]

#### transformers.LiquidCodecDecoderConfig[[transformers.LiquidCodecDecoderConfig]]

```python
transformers.LiquidCodecDecoderConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 512, intermediate_size: int = 2304, num_hidden_layers: int = 8, num_attention_heads: int = 8, num_key_value_heads: int = 2, max_position_embeddings: int = 131072, initializer_range: float = 0.02, norm_eps: float = 1e-05, use_cache: bool = False, rope_parameters: dict | None = None, conv_bias: bool = False, conv_L_cache: int = 7, layer_types: list[str] | None = None, head_dim: int = 64, sliding_window: int | None = 30, use_sandwich_norm: bool = True, use_attention_gate: bool = True, attention_bias: bool = False, attention_dropout: float = 0.0, n_fft: int = 1280, hop_length: int = 320, upsampling_factor: int = 6, quantization_dim: int = 256, num_codebooks: int = 12, codebook_dim: int = 4)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/liquid_codec/configuration_liquid_codec.py#L115)

**Parameters:**

hidden_size (`int`, *optional*, defaults to `512`) : Dimension of the hidden representations.

intermediate_size (`int`, *optional*, defaults to `2304`) : Dimension of the MLP representations.

num_hidden_layers (`int`, *optional*, defaults to `8`) : Number of hidden layers in the Transformer decoder.

num_attention_heads (`int`, *optional*, defaults to `8`) : Number of attention heads for each attention layer in the Transformer decoder.

num_key_value_heads (`int`, *optional*, defaults to `2`) : This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the 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](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `num_attention_heads`.

max_position_embeddings (`int`, *optional*, defaults to `131072`) : The maximum sequence length that this model might ever be used with.

initializer_range (`float`, *optional*, defaults to `0.02`) : The standard deviation of the truncated_normal_initializer for initializing all weight matrices.

norm_eps (`float`, *optional*, defaults to `1e-05`) : The epsilon used by the layer normalization layers.

use_cache (`bool`, *optional*, defaults to `False`) : Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True` or 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 for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE with longer `max_position_embeddings`.

conv_bias (`bool`, *optional*, defaults to `False`) : 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 to `64`) : The attention head dimension. If None, it will default to hidden_size // num_attention_heads

sliding_window (`int`, *optional*, defaults to `30`) : Sliding window attention window size. If `None`, no sliding window is applied.

use_sandwich_norm (`bool`, *optional*, defaults to `True`) : Whether to apply an RMSNorm to the operator and feed-forward outputs before they enter the residual stream.

use_attention_gate (`bool`, *optional*, defaults to `True`) : Whether the attention layers scale each head's output by a sigmoid gate computed from the layer input.

attention_bias (`bool`, *optional*, defaults to `False`) : Whether to use a bias in the query, key, value and output projection layers during self-attention.

attention_dropout (`float`, *optional*, defaults to `0.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 has `num_codebooks * codebook_dim` channels.

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](https://huggingface.co/LiquidAI/Liquid-Codec)

Configuration objects inherit from [PreTrainedConfig](/docs/transformers/main/en/main_classes/configuration#transformers.PreTrainedConfig) and can be used to control the model outputs. Read the
documentation from [PreTrainedConfig](/docs/transformers/main/en/main_classes/configuration#transformers.PreTrainedConfig) for more information.

## LiquidCodecFeatureExtractor[[transformers.LiquidCodecFeatureExtractor]]

#### transformers.LiquidCodecFeatureExtractor[[transformers.LiquidCodecFeatureExtractor]]

```python
transformers.LiquidCodecFeatureExtractor(sampling_rate = 24000, n_fft = 1280, hop_length = 320, win_length = 1280, subsampling_factor = 6, padding_value = 0.0, **kwargs)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/liquid_codec/feature_extraction_liquid_codec.py#L30)

**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](/docs/transformers/main/en/main_classes/feature_extractor#transformers.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__[[transformers.LiquidCodecFeatureExtractor.__call__]]

```python
__call__(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 = True, max_length: int | None = None, truncation: bool = False, return_tensors: str | transformers.utils.generic.TensorType | None = None, sampling_rate: int | None = None, device: str | None = 'cpu', **kwargs)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/liquid_codec/feature_extraction_liquid_codec.py#L92)

**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`, `str` or [PaddingStrategy](/docs/transformers/main/en/internal/file_utils#transformers.utils.PaddingStrategy), *optional*, defaults to `True`) : Select a strategy to pad the returned sequences among:  - `True` or `'longest'`: Pad to the longest clip of the batch. - `'max_length'`: Pad to `max_length` samples. - `False` or `'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 to `False`) : Whether to cut clips longer than `max_length`.

return_tensors (`str` or [TensorType](/docs/transformers/main/en/internal/file_utils#transformers.TensorType), *optional*) : If set, will return tensors instead of list of python integers. Acceptable values are: - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return Numpy `np.ndarray` objects.

sampling_rate (`int`, *optional*) : The sampling rate at which the `audio` input was sampled. It is strongly recommended to pass `sampling_rate` at 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_features` method. (e.g., "cpu", "cuda")

**Returns:** [BatchFeature](/docs/transformers/main/en/main_classes/feature_extractor#transformers.BatchFeature)

`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[[transformers.LiquidCodecISTFTCache]]

#### transformers.LiquidCodecISTFTCache[[transformers.LiquidCodecISTFTCache]]

```python
transformers.LiquidCodecISTFTCache(config: LiquidCodecDecoderConfig)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/liquid_codec/modeling_liquid_codec.py#L289)

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

#### update[[transformers.LiquidCodecISTFTCache.update]]

```python
update(audio: Tensor)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/liquid_codec/modeling_liquid_codec.py#L363)

Crossfades the cached samples with the start of a chunk, then caches its last ones. Returns the samples no
later chunk overlaps.

#### flush[[transformers.LiquidCodecISTFTCache.flush]]

```python
flush()
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/liquid_codec/modeling_liquid_codec.py#L379)

Ends the stream: last samples, up to the padding, then resets the cache.

## LiquidCodecModel[[transformers.LiquidCodecModel]]

#### transformers.LiquidCodecModel[[transformers.LiquidCodecModel]]

```python
transformers.LiquidCodecModel(config: LiquidCodecConfig)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/liquid_codec/modeling_liquid_codec.py#L1172)

**Parameters:**

config ([LiquidCodecConfig](/docs/transformers/main/en/model_doc/liquid_codec#transformers.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()](/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

The Liquid Codec audio tokenizer.

This model inherits from [PreTrainedModel](/docs/transformers/main/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#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[[transformers.LiquidCodecModel.encode]]

```python
encode(input_features: FloatTensor, input_features_mask: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/liquid_codec/modeling_liquid_codec.py#L1184)

**Parameters:**

input_features (`torch.FloatTensor` of shape `(batch_size, feature_size, num_frames)`) : Spectrogram from [LiquidCodecFeatureExtractor](/docs/transformers/main/en/model_doc/liquid_codec#transformers.LiquidCodecFeatureExtractor).

input_features_mask (`torch.Tensor` of shape `(batch_size, num_frames)`, *optional*) : Valid spectrogram frames of each clip (right-padded); returns `audio_codes_mask`. 

Encodes the spectrogram into discrete codes of shape `(batch_size, num_codebooks, num_frames)` : the latents of

[LiquidCodecEncoderModel.forward()](/docs/transformers/main/en/model_doc/liquid_codec#transformers.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](/docs/transformers/main/en/model_doc/liquid_codec#transformers.LiquidCodecConfig)) and inputs.

- **audio_codes** (`torch.LongTensor` of shape `(batch_size, num_codebooks, num_frames)`) -- Codes, per codebook and frame.
- **audio_codes_mask** (`torch.BoolTensor` of shape `(batch_size, num_frames)`, *optional*, returned with an
  `input_features_mask`) -- Valid frames of each clip.
- **hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`) -- Hidden states of the encoder at the output of each layer plus its input.
- **attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`) -- Attention weights of each attention layer of the encoder.

#### decode[[transformers.LiquidCodecModel.decode]]

```python
decode(audio_codes: LongTensor, audio_codes_mask: typing.Optional[torch.Tensor] = None, decoder_cache: transformers.cache_utils.Cache | None = None, istft_cache: transformers.models.liquid_codec.modeling_liquid_codec.LiquidCodecISTFTCache | None = None, use_streaming: bool = False, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/liquid_codec/modeling_liquid_codec.py#L1222)

**Parameters:**

audio_codes (`torch.LongTensor` of shape `(batch_size, num_codebooks, num_frames)`) : Codes to decode; `hop_length * upsampling_factor` samples per frame.

audio_codes_mask (`torch.Tensor` of shape `(batch_size, num_frames)`, *optional*) : Valid frames of each clip (right-padded): each clip decoded as alone; returns `audio_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](/docs/transformers/main/en/model_doc/liquid_codec#transformers.LiquidCodecISTFTCache), *optional*) : ISTFT cache from the previous chunk.

use_streaming (`bool`, *optional*, defaults to `False`) : Decode chunk by chunk: caches created on the first chunk, returned with each. Trailing samples stay in `istft_cache` until `istft_cache.flush()`. 

Decodes the codes into audio : the codes are dequantized into the latents of [LiquidCodecDecoderModel.forward()](/docs/transformers/main/en/model_doc/liquid_codec#transformers.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](/docs/transformers/main/en/model_doc/liquid_codec#transformers.LiquidCodecConfig)) and inputs.

- **audio_values** (`torch.FloatTensor` of shape `(batch_size, num_samples)`) -- Decoded audio, float32, at the codec's `sampling_rate`.
- **audio_values_mask** (`torch.BoolTensor` of shape `(batch_size, num_samples)`, *optional*, returned with an
  `audio_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 when `output_hidden_states=True`) -- Hidden states of the decoder at the output of each layer plus its input.
- **attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`) -- Attention weights of each attention layer of the decoder.

#### forward[[transformers.LiquidCodecModel.forward]]

```python
forward(input_features: FloatTensor, input_features_mask: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/liquid_codec/modeling_liquid_codec.py#L1270)

**Parameters:**

input_features (`torch.FloatTensor` of shape `(batch_size, feature_size, num_frames)`) : Spectrogram from [LiquidCodecFeatureExtractor](/docs/transformers/main/en/model_doc/liquid_codec#transformers.LiquidCodecFeatureExtractor).

input_features_mask (`torch.Tensor` of 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](/docs/transformers/main/en/model_doc/liquid_codec#transformers.LiquidCodecConfig)) and inputs.

The [LiquidCodecModel](/docs/transformers/main/en/model_doc/liquid_codec#transformers.LiquidCodecModel) forward method, overrides the `__call__` special method.

> [!TIP]
> 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.

- **audio_values** (`torch.FloatTensor` of shape `(batch_size, num_samples)`) -- Reconstructed audio.
- **audio_values_mask** (`torch.BoolTensor` of shape `(batch_size, num_samples)`, *optional*, returned with an
  `input_features_mask`) -- Samples decoded from the valid frames of each clip.
- **audio_codes** (`torch.LongTensor` of shape `(batch_size, num_codebooks, num_frames)`) -- Codes, per codebook and frame.
- **audio_codes_mask** (`torch.BoolTensor` of shape `(batch_size, num_frames)`, *optional*, returned with an
  `input_features_mask`) -- Valid frames of each clip.
- **hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`) -- Hidden states of the encoder at the output of each layer plus its input.
- **attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`) -- Attention weights of each attention layer of the encoder.

## LiquidCodecEncoderModel[[transformers.LiquidCodecEncoderModel]]

#### transformers.LiquidCodecEncoderModel[[transformers.LiquidCodecEncoderModel]]

```python
transformers.LiquidCodecEncoderModel(config: LiquidCodecEncoderConfig)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/liquid_codec/modeling_liquid_codec.py#L980)

**Parameters:**

config ([LiquidCodecEncoderConfig](/docs/transformers/main/en/model_doc/liquid_codec#transformers.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()](/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel.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](/docs/transformers/main/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#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[[transformers.LiquidCodecEncoderModel.forward]]

```python
forward(input_features: FloatTensor, input_features_mask: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/liquid_codec/modeling_liquid_codec.py#L1000)

**Parameters:**

input_features (`torch.FloatTensor` of shape `(batch_size, feature_size, num_frames)`) : Spectrogram from [LiquidCodecFeatureExtractor](/docs/transformers/main/en/model_doc/liquid_codec#transformers.LiquidCodecFeatureExtractor), whole codec frames per clip.

input_features_mask (`torch.Tensor` of shape `(batch_size, num_frames)`, *optional*) : Valid spectrogram frames of each clip (right-padded); returns `latents_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](/docs/transformers/main/en/model_doc/liquid_codec#transformers.LiquidCodecConfig)) and inputs.

The [LiquidCodecEncoderModel](/docs/transformers/main/en/model_doc/liquid_codec#transformers.LiquidCodecEncoderModel) forward method, overrides the `__call__` special method.

> [!TIP]
> 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.

- **latents** (`torch.FloatTensor` of shape `(batch_size, num_codebooks * codebook_dim, num_frames)`) -- Latents given to the FSQ quantizer, one per codec frame.
- **latents_mask** (`torch.BoolTensor` of shape `(batch_size, num_frames)`, *optional*, returned with an
  `input_features_mask`) -- Valid frames of each clip.
- **hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`) -- Hidden states of the encoder at the output of each layer plus its input.
- **attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`) -- Attention weights of each attention layer of the encoder.

## LiquidCodecDecoderModel[[transformers.LiquidCodecDecoderModel]]

#### transformers.LiquidCodecDecoderModel[[transformers.LiquidCodecDecoderModel]]

```python
transformers.LiquidCodecDecoderModel(config: LiquidCodecDecoderConfig)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/liquid_codec/modeling_liquid_codec.py#L1068)

**Parameters:**

config ([LiquidCodecDecoderConfig](/docs/transformers/main/en/model_doc/liquid_codec#transformers.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()](/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel.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](/docs/transformers/main/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#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[[transformers.LiquidCodecDecoderModel.forward]]

```python
forward(latents: FloatTensor, latents_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, cache: transformers.cache_utils.Cache | None = None, istft_cache: transformers.models.liquid_codec.modeling_liquid_codec.LiquidCodecISTFTCache | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/liquid_codec/modeling_liquid_codec.py#L1089)

**Parameters:**

latents (`torch.FloatTensor` of shape `(batch_size, num_codebooks * codebook_dim, num_frames)`) : FSQ values from the quantizer, one per codec frame.

latents_mask (`torch.Tensor` of shape `(batch_size, num_frames)`, *optional*) : Valid frames of each clip (right-padded): each clip decoded as alone; returns `audio_values_mask`.

position_ids (`torch.LongTensor` of 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]`.  [What are position IDs?](../glossary#position-ids)

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 the `cache` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.  Only [Cache](/docs/transformers/main/en/internal/generation_utils#transformers.Cache) instance is allowed as input, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). If no `cache` are passed, [DynamicCache](/docs/transformers/main/en/internal/generation_utils#transformers.DynamicCache) will be initialized by default.  The model will output the same cache format that is fed as input.  If `cache` are used, the user is expected to input only unprocessed `input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, unprocessed_length)` instead of all `input_ids` of shape `(batch_size, sequence_length)`.

istft_cache ([LiquidCodecISTFTCache](/docs/transformers/main/en/model_doc/liquid_codec#transformers.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](/docs/transformers/main/en/model_doc/liquid_codec#transformers.LiquidCodecConfig)) and inputs.

The [LiquidCodecDecoderModel](/docs/transformers/main/en/model_doc/liquid_codec#transformers.LiquidCodecDecoderModel) forward method, overrides the `__call__` special method.

> [!TIP]
> 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.

- **audio_values** (`torch.FloatTensor` of shape `(batch_size, num_samples)`) -- Decoded audio, float32, at the codec's `sampling_rate`.
- **audio_values_mask** (`torch.BoolTensor` of shape `(batch_size, num_samples)`, *optional*, returned with an
  `audio_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 when `output_hidden_states=True`) -- Hidden states of the decoder at the output of each layer plus its input.
- **attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`) -- Attention weights of each attention layer of the decoder.
