CLAP (original) (raw)

PyTorch

Overview

The CLAP model was proposed in Large Scale Contrastive Language-Audio pretraining with feature fusion and keyword-to-caption augmentation by Yusong Wu, Ke Chen, Tianyu Zhang, Yuchen Hui, Taylor Berg-Kirkpatrick, Shlomo Dubnov.

CLAP (Contrastive Language-Audio Pretraining) is a neural network trained on a variety of (audio, text) pairs. It can be instructed in to predict the most relevant text snippet, given an audio, without directly optimizing for the task. The CLAP model uses a SWINTransformer to get audio features from a log-Mel spectrogram input, and a RoBERTa model to get text features. Both the text and audio features are then projected to a latent space with identical dimension. The dot product between the projected audio and text features is then used as a similar score.

The abstract from the paper is the following:

Contrastive learning has shown remarkable success in the field of multimodal representation learning. In this paper, we propose a pipeline of contrastive language-audio pretraining to develop an audio representation by combining audio data with natural language descriptions. To accomplish this target, we first release LAION-Audio-630K, a large collection of 633,526 audio-text pairs from different data sources. Second, we construct a contrastive language-audio pretraining model by considering different audio encoders and text encoders. We incorporate the feature fusion mechanism and keyword-to-caption augmentation into the model design to further enable the model to process audio inputs of variable lengths and enhance the performance. Third, we perform comprehensive experiments to evaluate our model across three tasks: text-to-audio retrieval, zero-shot audio classification, and supervised audio classification. The results demonstrate that our model achieves superior performance in text-to-audio retrieval task. In audio classification tasks, the model achieves state-of-the-art performance in the zeroshot setting and is able to obtain performance comparable to models’ results in the non-zero-shot setting. LAION-Audio-6

This model was contributed by Younes Belkada and Arthur Zucker . The original code can be found here.

ClapConfig

class transformers.ClapConfig

< source >

( text_config = None audio_config = None logit_scale_init_value = 14.285714285714285 projection_dim = 512 projection_hidden_act = 'relu' initializer_factor = 1.0 **kwargs )

Parameters

ClapConfig is the configuration class to store the configuration of a ClapModel. It is used to instantiate a CLAP model according to the specified arguments, defining the text model and audio model configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the CLAPlaion/clap-htsat-fused architecture.

Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.

Example:

from transformers import ClapConfig, ClapModel

configuration = ClapConfig()

model = ClapModel(configuration)

configuration = model.config

from transformers import ClapTextConfig, ClapAudioConfig

config_text = ClapTextConfig() config_audio = ClapAudioConfig()

config = ClapConfig.from_text_audio_configs(config_text, config_audio)

from_text_audio_configs

< source >

( text_config: ClapTextConfig audio_config: ClapAudioConfig **kwargs ) → ClapConfig

An instance of a configuration object

Instantiate a ClapConfig (or a derived class) from clap text model configuration and clap audio model configuration.

ClapTextConfig

class transformers.ClapTextConfig

< source >

( vocab_size = 50265 hidden_size = 768 num_hidden_layers = 12 num_attention_heads = 12 intermediate_size = 3072 hidden_act = 'gelu' hidden_dropout_prob = 0.1 attention_probs_dropout_prob = 0.1 max_position_embeddings = 514 type_vocab_size = 1 initializer_factor = 1.0 layer_norm_eps = 1e-12 projection_dim = 512 pad_token_id = 1 bos_token_id = 0 eos_token_id = 2 position_embedding_type = 'absolute' use_cache = True projection_hidden_act = 'relu' **kwargs )

Parameters

This is the configuration class to store the configuration of a ClapTextModel. It is used to instantiate a CLAP 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 CLAPcalp-hsat-fused architecture.

Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.

Examples:

from transformers import ClapTextConfig, ClapTextModel

configuration = ClapTextConfig()

model = ClapTextModel(configuration)

configuration = model.config

ClapAudioConfig

class transformers.ClapAudioConfig

< source >

( window_size = 8 num_mel_bins = 64 spec_size = 256 hidden_act = 'gelu' patch_size = 4 patch_stride = [4, 4] num_classes = 527 hidden_size = 768 projection_dim = 512 depths = [2, 2, 6, 2] num_attention_heads = [4, 8, 16, 32] enable_fusion = False hidden_dropout_prob = 0.1 fusion_type = None patch_embed_input_channels = 1 flatten_patch_embeds = True patch_embeds_hidden_size = 96 enable_patch_layer_norm = True drop_path_rate = 0.0 attention_probs_dropout_prob = 0.0 qkv_bias = True mlp_ratio = 4.0 aff_block_r = 4 num_hidden_layers = 4 projection_hidden_act = 'relu' layer_norm_eps = 1e-05 initializer_factor = 1.0 **kwargs )

Parameters

This is the configuration class to store the configuration of a ClapAudioModel. It is used to instantiate a CLAP audio encoder according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the audio encoder of the CLAPlaion/clap-htsat-fused architecture.

Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.

Example:

from transformers import ClapAudioConfig, ClapAudioModel

configuration = ClapAudioConfig()

model = ClapAudioModel(configuration)

configuration = model.config

ClapFeatureExtractor

( feature_size = 64 sampling_rate = 48000 hop_length = 480 max_length_s = 10 fft_window_size = 1024 padding_value = 0.0 return_attention_mask = False frequency_min: float = 0 frequency_max: float = 14000 top_db: typing.Optional[int] = None truncation: str = 'fusion' padding: str = 'repeatpad' **kwargs )

Parameters

Constructs a CLAP 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.

This class extracts mel-filter bank features from raw speech using a custom numpy implementation of the Short Time Fourier Transform (STFT) which should match pytorch’s torch.stft equivalent.

( ) → Dict[str, Any]

Dictionary of all the attributes that make up this configuration instance, except for the mel filter banks, which do not need to be saved or printed as they are too long.

Serializes this instance to a Python dictionary.

ClapProcessor

Constructs a CLAP processor which wraps a CLAP feature extractor and a RoBerta tokenizer into a single processor.

ClapProcessor offers all the functionalities of ClapFeatureExtractor and RobertaTokenizerFast. See the__call__() and decode() for more information.

This method forwards all its arguments to RobertaTokenizerFast’s batch_decode(). Please refer to the docstring of this method for more information.

This method forwards all its arguments to RobertaTokenizerFast’s decode(). Please refer to the docstring of this method for more information.

ClapModel

class transformers.ClapModel

< source >

( config: ClapConfig )

Parameters

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_ids: typing.Optional[torch.LongTensor] = None input_features: typing.Optional[torch.FloatTensor] = None is_longer: typing.Optional[torch.BoolTensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None return_loss: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.models.clap.modeling_clap.ClapOutput or tuple(torch.FloatTensor)

Parameters

Returns

transformers.models.clap.modeling_clap.ClapOutput or tuple(torch.FloatTensor)

A transformers.models.clap.modeling_clap.ClapOutput or a tuple oftorch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (<class 'transformers.models.clap.configuration_clap.ClapConfig'>) and inputs.

The ClapModel 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.

Examples:

from datasets import load_dataset from transformers import AutoProcessor, ClapModel

dataset = load_dataset("hf-internal-testing/ashraq-esc50-1-dog-example") audio_sample = dataset["train"]["audio"][0]["array"]

model = ClapModel.from_pretrained("laion/clap-htsat-unfused") processor = AutoProcessor.from_pretrained("laion/clap-htsat-unfused")

input_text = ["Sound of a dog", "Sound of vaccum cleaner"]

inputs = processor(text=input_text, audios=audio_sample, return_tensors="pt", padding=True)

outputs = model(**inputs) logits_per_audio = outputs.logits_per_audio
probs = logits_per_audio.softmax(dim=-1)

get_text_features

< source >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → text_features (torch.FloatTensor of shape (batch_size, output_dim)

Parameters

Returns

text_features (torch.FloatTensor of shape (batch_size, output_dim)

The text embeddings obtained by applying the projection layer to the pooled output of ClapTextModel.

The ClapModel 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.

Examples:

from transformers import AutoTokenizer, ClapModel

model = ClapModel.from_pretrained("laion/clap-htsat-unfused") tokenizer = AutoTokenizer.from_pretrained("laion/clap-htsat-unfused")

inputs = tokenizer(["the sound of a cat", "the sound of a dog"], padding=True, return_tensors="pt") text_features = model.get_text_features(**inputs)

get_audio_features

< source >

( input_features: typing.Optional[torch.Tensor] = None is_longer: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → audio_features (torch.FloatTensor of shape (batch_size, output_dim)

Parameters

Returns

audio_features (torch.FloatTensor of shape (batch_size, output_dim)

The audio embeddings obtained by applying the projection layer to the pooled output of ClapAudioModel.

The ClapModel 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.

Examples:

from transformers import AutoFeatureExtractor, ClapModel import torch

model = ClapModel.from_pretrained("laion/clap-htsat-unfused") feature_extractor = AutoFeatureExtractor.from_pretrained("laion/clap-htsat-unfused") random_audio = torch.rand((16_000)) inputs = feature_extractor(random_audio, return_tensors="pt") audio_features = model.get_audio_features(**inputs)

ClapTextModel

class transformers.ClapTextModel

< source >

( config add_pooling_layer = True )

The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of cross-attention is added between the self-attention layers, following the architecture described in Attention is all you need_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.

To behave as an decoder the model needs to be initialized with the is_decoder argument of the configuration set to True. To be used in a Seq2Seq model, the model needs to initialized with both is_decoder argument andadd_cross_attention set to True; an encoder_hidden_states is then expected as an input to the forward pass.

.. _ Attention is all you need: https://arxiv.org/abs/1706.03762

forward

< source >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None encoder_hidden_states: typing.Optional[torch.Tensor] = None encoder_attention_mask: typing.Optional[torch.Tensor] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None )

encoder_hidden_states (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional): Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is configured as a decoder. encoder_attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional): Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in the cross-attention if the model is configured as a decoder. Mask values selected in [0, 1]:

If past_key_values are used, the user can optionally input only the last decoder_input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, 1) instead of alldecoder_input_ids of shape (batch_size, sequence_length). use_cache (bool, optional): If set to True, past_key_values key value states are returned and can be used to speed up decoding (seepast_key_values).

ClapTextModelWithProjection

class transformers.ClapTextModelWithProjection

< source >

( config: ClapTextConfig )

Parameters

CLAP Text Model with a projection layer on top (a linear layer on top of the pooled output).

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_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.models.clap.modeling_clap.ClapTextModelOutput or tuple(torch.FloatTensor)

Parameters

Returns

transformers.models.clap.modeling_clap.ClapTextModelOutput or tuple(torch.FloatTensor)

A transformers.models.clap.modeling_clap.ClapTextModelOutput or a tuple oftorch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (<class 'transformers.models.clap.configuration_clap.ClapTextConfig'>) and inputs.

The ClapTextModelWithProjection 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.

Examples:

from transformers import AutoTokenizer, ClapTextModelWithProjection

model = ClapTextModelWithProjection.from_pretrained("laion/clap-htsat-unfused") tokenizer = AutoTokenizer.from_pretrained("laion/clap-htsat-unfused")

inputs = tokenizer(["a sound of a cat", "a sound of a dog"], padding=True, return_tensors="pt")

outputs = model(**inputs) text_embeds = outputs.text_embeds

ClapAudioModel

class transformers.ClapAudioModel

< source >

( config: ClapAudioConfig )

forward

< source >

( input_features: typing.Optional[torch.FloatTensor] = None is_longer: typing.Optional[torch.BoolTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutputWithPooling or tuple(torch.FloatTensor)

Parameters

A transformers.modeling_outputs.BaseModelOutputWithPooling or a tuple oftorch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (<class 'transformers.models.clap.configuration_clap.ClapAudioConfig'>) and inputs.

The ClapAudioModel 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.

Examples:

from datasets import load_dataset from transformers import AutoProcessor, ClapAudioModel

dataset = load_dataset("hf-internal-testing/ashraq-esc50-1-dog-example") audio_sample = dataset["train"]["audio"][0]["array"]

model = ClapAudioModel.from_pretrained("laion/clap-htsat-fused") processor = AutoProcessor.from_pretrained("laion/clap-htsat-fused")

inputs = processor(audios=audio_sample, return_tensors="pt")

outputs = model(**inputs) last_hidden_state = outputs.last_hidden_state

ClapAudioModelWithProjection

class transformers.ClapAudioModelWithProjection

< source >

( config: ClapAudioConfig )

Parameters

CLAP Audio Model with a projection layer on top (a linear layer on top of the pooled output).

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: typing.Optional[torch.FloatTensor] = None is_longer: typing.Optional[torch.BoolTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.models.clap.modeling_clap.ClapAudioModelOutput or tuple(torch.FloatTensor)

Parameters

Returns

transformers.models.clap.modeling_clap.ClapAudioModelOutput or tuple(torch.FloatTensor)

A transformers.models.clap.modeling_clap.ClapAudioModelOutput or a tuple oftorch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (<class 'transformers.models.clap.configuration_clap.ClapAudioConfig'>) and inputs.

The ClapAudioModelWithProjection 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.

Examples:

from datasets import load_dataset from transformers import ClapAudioModelWithProjection, ClapProcessor

model = ClapAudioModelWithProjection.from_pretrained("laion/clap-htsat-fused") processor = ClapProcessor.from_pretrained("laion/clap-htsat-fused")

dataset = load_dataset("hf-internal-testing/ashraq-esc50-1-dog-example") audio_sample = dataset["train"]["audio"][0]["array"]

inputs = processor(audios=audio_sample, return_tensors="pt") outputs = model(**inputs) audio_embeds = outputs.audio_embeds

< > Update on GitHub