The TVLT model was proposed in TVLT: Textless Vision-Language Transformer by Zineng Tang, Jaemin Cho, Yixin Nie, Mohit Bansal (the first three authors contributed equally). The Textless Vision-Language Transformer (TVLT) is a model that uses raw visual and audio inputs for vision-and-language representation learning, without using text-specific modules such as tokenization or automatic speech recognition (ASR). It can perform various audiovisual and vision-language tasks like retrieval, question answering, etc.
The abstract from the paper is the following:
In this work, we present the Textless Vision-Language Transformer (TVLT), where homogeneous transformer blocks take raw visual and audio inputs for vision-and-language representation learning with minimal modality-specific design, and do not use text-specific modules such as tokenization or automatic speech recognition (ASR). TVLT is trained by reconstructing masked patches of continuous video frames and audio spectrograms (masked autoencoding) and contrastive modeling to align video and audio. TVLT attains performance comparable to its text-based counterpart on various multimodal tasks, such as visual question answering, image retrieval, video retrieval, and multimodal sentiment analysis, with 28x faster inference speed and only 1/3 of the parameters. Our findings suggest the possibility of learning compact and efficient visual-linguistic representations from low-level visual and audio signals without assuming the prior existence of text.
Tips:
pixel_values
and audio_values
as input. One can use TvltProcessor to prepare data for the model.
This processor wraps an image processor (for the image/video modality) and an audio feature extractor (for the audio modality) into one.pixel_mask
that indicates which pixels are real/padding and audio_mask
that indicates which audio values are real/padding.The original code can be found here. This model was contributed by Zineng Tang.
( image_size = 224 spectrogram_length = 2048 frequency_length = 128 image_patch_size = [16, 16] audio_patch_size = [16, 16] num_image_channels = 3 num_audio_channels = 1 num_frames = 8 hidden_size = 768 num_hidden_layers = 12 num_attention_heads = 12 intermediate_size = 3072 hidden_act = 'gelu' hidden_dropout_prob = 0.0 attention_probs_dropout_prob = 0.0 initializer_range = 0.02 layer_norm_eps = 1e-06 qkv_bias = True use_mean_pooling = False decoder_num_attention_heads = 16 decoder_hidden_size = 512 decoder_num_hidden_layers = 8 decoder_intermediate_size = 2048 pixel_mask_ratio = 0.75 audio_mask_ratio = 0.15 audio_mask_type = 'frame-level' task_matching = True task_mae = True loss_type = 'classification' **kwargs )
Parameters
int
, optional, defaults to 224) —
The size (resolution) of each image.
int
, optional, defaults to 2048) —
The time length of each audio spectrogram.
int
, optional, defaults to 128) —
The frequency length of audio spectrogram.
List[int]
, optional, defaults to [16, 16]
) —
The size (resolution) of each image patch.
List[int]
, optional, defaults to [16, 16]
) —
The size (resolution) of each audio patch.
int
, optional, defaults to 3) —
The number of input image channels.
int
, optional, defaults to 1) —
The number of input audio channels.
int
, optional, defaults to 8) —
The maximum number of frames for an input video.
int
, optional, defaults to 768) —
Dimensionality of the encoder layers and the pooler layer.
int
, optional, defaults to 12) —
Number of hidden layers in the Transformer encoder.
int
, optional, defaults to 12) —
Number of attention heads for each attention layer in the Transformer encoder.
int
, optional, defaults to 3072) —
Dimensionality of the “intermediate” (i.e., feed-forward) layer in the Transformer encoder.
str
or function
, optional, defaults to "gelu"
) —
The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu"
,
"relu"
, "selu"
and "gelu_new"
are supported.
float
, optional, defaults to 0.0) —
The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.
float
, optional, defaults to 0.0) —
The dropout ratio for the attention probabilities.
float
, optional, defaults to 0.02) —
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
float
, optional, defaults to 1e-6) —
The epsilon used by the layer normalization layers.
bool
, optional, defaults to True
) —
Whether to add a bias to the queries, keys and values.
bool
, optional, defaults to False
) —
Whether to mean pool the final hidden states instead of using the final hidden state of the [CLS] token.
int
, optional, defaults to 16) —
Number of attention heads for each attention layer in the decoder.
int
, optional, defaults to 512) —
Dimensionality of the decoder.
int
, optional, defaults to 8) —
Number of hidden layers in the decoder.
int
, optional, defaults to 2048) —
Dimensionality of the “intermediate” (i.e., feed-forward) layer in the decoder.
float
, optional, defaults to 0.75) —
Image patch masking ratio.
float
, optional, defaults to 0.15) —
Audio patch masking ratio.
str
, optional, defaults to "frame-level"
) —
Audio patch masking type, choose between “frame-level” and “patch-level”.
bool
, optional, defaults to True
) —
Whether to use vision audio matching task in pretraining.
bool
, optional, defaults to True
) —
Whether to use the masked auto-encoder (MAE) in pretraining.
str
, optional, defaults to "classification"
) —
Loss types including regression and classification.
This is the configuration class to store the configuration of a TvltModel. It is used to instantiate a TVLT 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 TVLT ZinengTang/tvlt-base 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 TvltConfig, TvltModel
>>> # # Initializing a TVLT ZinengTang/tvlt-base style configuration
>>> configuration = TvltConfig()
>>> # # Initializing a model (with random weights) from the ZinengTang/tvlt-base style configuration
>>> model = TvltModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
( image_processor feature_extractor )
Parameters
TvltImageProcessor
) —
An instance of TvltImageProcessor. The image processor is a required input.
TvltFeatureExtractor
) —
An instance of TvltFeatureExtractor. The feature extractor is a required input.
Constructs a TVLT processor which wraps a TVLT image processor and TVLT feature extractor into a single processor.
TvltProcessor offers all the functionalities of TvltImageProcessor and TvltFeatureExtractor. See the docstring of call() for more information.
( images = None audio = None images_mixed = None sampling_rate = None mask_audio = False mask_pixel = False *args **kwargs )
Forwards the images
argument to TvltImageProcessor’s preprocess() and the audio
argument to TvltFeatureExtractor’s call(). Please refer to the docstring of the
above two methods for more information.
( do_resize: bool = True size: typing.Dict[str, int] = None patch_size: typing.List[int] = [16, 16] num_frames: int = 8 resample: Resampling = <Resampling.BILINEAR: 2> do_center_crop: bool = True crop_size: typing.Dict[str, int] = None do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, typing.List[float], NoneType] = [0.5, 0.5, 0.5] image_std: typing.Union[float, typing.List[float], NoneType] = [0.5, 0.5, 0.5] init_mask_generator = False **kwargs )
Parameters
bool
, optional, defaults to True
) —
Whether to resize the image’s (height, width) dimensions to the specified size
. Can be overridden by the
do_resize
parameter in the preprocess
method.
Dict[str, int]
optional, defaults to {"shortest_edge" -- 224}
):
Size of the output image after resizing. The shortest edge of the image will be resized to
size["shortest_edge"]
while maintaining the aspect ratio of the original image. Can be overriden by
size
in the preprocess
method.
List[int]
optional, defaults to [16,16]) —
The patch size of image patch embedding.
int
optional, defaults to 8) —
The maximum number of video frames.
PILImageResampling
, optional, defaults to PILImageResampling.BILINEAR
) —
Resampling filter to use if resizing the image. Can be overridden by the resample
parameter in the
preprocess
method.
bool
, optional, defaults to True
) —
Whether to center crop the image to the specified crop_size
. Can be overridden by the do_center_crop
parameter in the preprocess
method.
Dict[str, int]
, optional, defaults to {"height" -- 224, "width": 224}
):
Size of the image after applying the center crop. Can be overridden by the crop_size
parameter in the
preprocess
method.
bool
, optional, defaults to True
) —
Whether to rescale the image by the specified scale rescale_factor
. Can be overridden by the do_rescale
parameter in the preprocess
method.
int
or float
, optional, defaults to 1/255) —
Defines the scale factor to use if rescaling the image. Can be overridden by the rescale_factor
parameter
in the preprocess
method.
bool
, optional, defaults to True
) —
Whether to normalize the image. Can be overridden by the do_normalize
parameter in the preprocess
method.
float
or List[float]
, optional, defaults to IMAGENET_STANDARD_MEAN
) —
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
channels in the image. Can be overridden by the image_mean
parameter in the preprocess
method.
float
or List[float]
, optional, defaults to IMAGENET_STANDARD_STD
) —
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
number of channels in the image. Can be overridden by the image_std
parameter in the preprocess
method.
Constructs a TVLT image processor.
This processor can be used to prepare either videos or images for the model by converting images to 1-frame videos.
( videos: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]] do_resize: bool = None size: typing.Dict[str, int] = None patch_size: typing.List[int] = None num_frames: int = None resample: Resampling = None do_center_crop: bool = None crop_size: typing.Dict[str, int] = None do_rescale: bool = None rescale_factor: float = None do_normalize: bool = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None is_mixed: bool = False return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'> **kwargs ) → BatchFeature
Parameters
ImageInput
) —
Images or videos to preprocess.
bool
, optional, defaults to self.do_resize
) —
Whether to resize the image.
Dict[str, int]
, optional, defaults to self.size
) —
Size of the image after applying resize.
List[int]
optional, defaults to self.patch_size) —
The patch size of image patch embedding.
int
optional, defaults to self.num_frames) —
The maximum number of video frames.
PILImageResampling
, optional, defaults to self.resample
) —
Resampling filter to use if resizing the image. This can be one of the enum PILImageResampling
, Only
has an effect if do_resize
is set to True
.
bool
, optional, defaults to self.do_centre_crop
) —
Whether to centre crop the image.
Dict[str, int]
, optional, defaults to self.crop_size
) —
Size of the image after applying the centre crop.
bool
, optional, defaults to self.do_rescale
) —
Whether to rescale the image values between [0 - 1].
float
, optional, defaults to self.rescale_factor
) —
Rescale factor to rescale the image by if do_rescale
is set to True
.
bool
, optional, defaults to self.do_normalize
) —
Whether to normalize the image.
float
or List[float]
, optional, defaults to self.image_mean
) —
Image mean.
float
or List[float]
, optional, defaults to self.image_std
) —
Image standard deviation.
bool
, optional) —
If the input video has negative samples.
str
or TensorType
, optional) —
The type of tensors to return. Can be one of:np.ndarray
.TensorType.TENSORFLOW
or 'tf'
: Return a batch of type tf.Tensor
.TensorType.PYTORCH
or 'pt'
: Return a batch of type torch.Tensor
.TensorType.NUMPY
or 'np'
: Return a batch of type np.ndarray
.TensorType.JAX
or 'jax'
: Return a batch of type jax.numpy.ndarray
.ChannelDimension
or str
, optional, defaults to ChannelDimension.FIRST
) —
The channel dimension format for the output image. Can be one of:ChannelDimension.FIRST
: image in (num_channels, height, width) format.ChannelDimension.LAST
: image in (height, width, num_channels) format.Returns
A BatchFeature with the following fields:
pixel_values — Pixel values to be fed to a model, of shape (batch_size, num_channels, height, width).
pixel_mask — Pixel masks to be fed to a model, of shape (batch_size, num_pixel_patches).
pixel_values_mixed — Pixel values with both postive or negative to be fed to a model, of shape (batch_size, num_channels, height, width).
pixel_mask_mixed — Pixel masks with both postive or negative to be fed to a model, of shape (batch_size, num_pixel_patches).
Preprocess an videos or image or batch of videos or images.
( spectrogram_length = 2048 num_channels = 1 patch_size = [16, 16] feature_size = 128 sampling_rate = 44100 hop_length_to_sampling_rate = 86 n_fft = 2048 padding_value = 0.0 **kwargs )
Parameters
Dict[str, int]
optional, defaults to 2048) —
The time length of each audio spectrogram.
int
optional, defaults to 1) —
Number of audio channels.
List[int]
optional, defaults to [16, 16]
) —
The patch size of audio patch embedding.
int
, defaults to 128) —
The frequency length of audio spectrogram.
int
, defaults to 44100) —
The sampling rate at which the audio files should be digitalized expressed in Hertz (Hz).
int
, defaults to 86) —
Hop length is length of the overlaping windows for the STFT used to obtain the Mel Frequency coefficients.
For example, with sampling rate 44100, the hop length is 512, with 44100 / 512 = 86
int
, defaults to 2048) —
Size of the Fourier transform.
float
, optional, defaults to 0.0) —
Padding value used to pad the audio. Should correspond to silences.
Constructs a TVLT audio feature extractor. This feature extractor can be used to prepare audios for the model.
This feature extractor inherits from FeatureExtractionMixin which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.
( raw_speech: typing.Union[numpy.ndarray, typing.List[float], typing.List[numpy.ndarray], typing.List[typing.List[float]]] return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None return_attention_mask: typing.Optional[bool] = True sampling_rate: typing.Optional[int] = None resample: bool = False mask_audio: bool = False **kwargs ) → BatchFeature
Parameters
np.ndarray
, List[float]
, List[np.ndarray]
, List[List[float]]
) —
The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
values, a list of numpy arrays or a list of list of float values.
str
or 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.bool
, optional, default to True
) —
Whether to return the attention mask. If left to the default, will return the attention mask according
to the specific feature_extractor’s default. What are attention masks?
For TvltTransformer models, attention_mask
should alwys be passed for batched inference, to avoid
subtle bugs.
int
, optional) —
The sampling rate at which the raw_speech
input was sampled. It is strongly recommended to pass
sampling_rate
at the forward call to prevent silent errors and allow automatic speech recognition
pipeline. Current model supports sampling rate 16000 and 44100.
bool
, optional, defaults to False
) —
If the sampling rate is not matched, resample the input audio to match.
bool
, optional, defaults to False
) —
Whether or not to mask input audio for MAE task.
Returns
A BatchFeature with the following fields:
audio_values — Audio values to be fed to a model, of shape (batch_size, num_channels, height, width).
audio_mask — Audio masks to be fed to a model, of shape (batch_size, num_audio_patches).
Main method to prepare one or several audio(s) for the model.
( config )
Parameters
The bare TVLT Model transformer outputting raw hidden-states without any specific head on top. This model is 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.
(
pixel_values
audio_values
pixel_mask = None
audio_mask = None
mask_pixel = False
mask_audio = False
output_attentions = None
output_hidden_states = None
return_dict = None
)
→
transformers.models.tvlt.modeling_tvlt.TvltModelOutput
or tuple(torch.FloatTensor)
Parameters
torch.FloatTensor
of shape (batch_size, num_frames, num_channels, height, width)
) —
Pixel values. Pixel values can be obtained using TvltProcessor. See TvltProcessor.call() for
details.
torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) —
Audio values. Audio values can be obtained using TvltProcessor. See TvltProcessor.call() for
details.
torch.FloatTensor
of shape (batch_size, num_pixel_patches)
) —
Pixel masks. Pixel masks can be obtained using TvltProcessor. See TvltProcessor.call() for
details.
torch.FloatTensor
of shape (batch_size, num_audio_patches)
) —
Audio masks. Audio masks can be obtained using TvltProcessor. See TvltProcessor.call() for
details.
torch.FloatTensor
of shape (batch_size, num_frames, num_channels, height, width)
) —
Pixel values that mix positive and negative samples in Tvlt vision-audio matching. Pixel values mixed can
be obtained using TvltProcessor. See TvltProcessor.call() for details.
torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) —
Pixel masks of pixel_values_mixed. Pixel masks mixed can be obtained using TvltProcessor. See
TvltProcessor.call() for details.
bool
, optional) —
Whether to mask pixel for MAE tasks. Only set to True in TvltForPreTraining.
bool
, optional) —
Whether to mask audio for MAE tasks. Only set to True in TvltForPreTraining.
bool
, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions
under returned
tensors for more detail.
bool
, optional) —
Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for
more detail.
bool
, optional) —
Whether or not to return a ModelOutput instead of a plain tuple.
Returns
transformers.models.tvlt.modeling_tvlt.TvltModelOutput
or tuple(torch.FloatTensor)
A transformers.models.tvlt.modeling_tvlt.TvltModelOutput
or a tuple of
torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various
elements depending on the configuration (TvltConfig) and inputs.
torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
) — Sequence of hidden-states at the output of the last layer of the model.torch.FloatTensor
of shape (batch_size, pixel_sequence_length, hidden_size)
) — Pixel sequence of hidden-states at the output of the last layer of the model.torch.FloatTensor
of shape (batch_size, audio_sequence_length, hidden_size)
) — Audio sequence of hidden-states at the output of the last layer of the model.torch.FloatTensor
of shape (batch_size, pixel_patch_length)
) — Tensor indicating which pixel patches are masked (1) and which are not (0).torch.FloatTensor
of shape (batch_size, audio_patch_length)
) — Tensor indicating which audio patches are masked (1) and which are not (0).torch.LongTensor
of shape (batch_size, pixel_patch_length)
) — Tensor containing the ids permutation of pixel masking.torch.LongTensor
of shape (batch_size, audio_patch_length)
) — Tensor containing the ids permutation of audio masking.tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of torch.FloatTensor
(one for the output of the embeddings and one for the output of each layer) of
shape (batch_size, sequence_length, hidden_size)
. Hidden-states of the model at the output of each layer
plus the initial embedding outputs.tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in
the self-attention heads.The TvltModel forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Examples:
>>> from transformers import TvltProcessor, TvltModel
>>> import numpy as np
>>> import torch
>>> num_frames = 8
>>> images = list(np.random.randn(num_frames, 3, 224, 224))
>>> audio = list(np.random.randn(10000))
>>> processor = TvltProcessor.from_pretrained("ZinengTang/tvlt-base")
>>> model = TvltModel.from_pretrained("ZinengTang/tvlt-base")
>>> input_dict = processor(images, audio, sampling_rate=44100, return_tensors="pt")
>>> outputs = model(**input_dict)
>>> loss = outputs.loss
( config )
Parameters
The TVLT Model transformer with the decoder on top for self-supervised pre-training. This model is 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.
(
pixel_values
audio_values
pixel_mask = None
audio_mask = None
labels = None
pixel_values_mixed = None
pixel_mask_mixed = None
output_attentions = None
output_hidden_states = None
return_dict = None
)
→
transformers.models.tvlt.modeling_tvlt.TvltForPreTrainingOutput
or tuple(torch.FloatTensor)
Parameters
torch.FloatTensor
of shape (batch_size, num_frames, num_channels, height, width)
) —
Pixel values. Pixel values can be obtained using TvltProcessor. See TvltProcessor.call() for
details.
torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) —
Audio values. Audio values can be obtained using TvltProcessor. See TvltProcessor.call() for
details.
torch.FloatTensor
of shape (batch_size, num_pixel_patches)
) —
Pixel masks. Pixel masks can be obtained using TvltProcessor. See TvltProcessor.call() for
details.
torch.FloatTensor
of shape (batch_size, num_audio_patches)
) —
Audio masks. Audio masks can be obtained using TvltProcessor. See TvltProcessor.call() for
details.
torch.FloatTensor
of shape (batch_size, num_frames, num_channels, height, width)
) —
Pixel values that mix positive and negative samples in Tvlt vision-audio matching. Pixel values mixed can
be obtained using TvltProcessor. See TvltProcessor.call() for details.
torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) —
Pixel masks of pixel_values_mixed. Pixel masks mixed can be obtained using TvltProcessor. See
TvltProcessor.call() for details.
bool
, optional) —
Whether to mask pixel for MAE tasks. Only set to True in TvltForPreTraining.
bool
, optional) —
Whether to mask audio for MAE tasks. Only set to True in TvltForPreTraining.
bool
, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions
under returned
tensors for more detail.
bool
, optional) —
Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for
more detail.
bool
, optional) —
Whether or not to return a ModelOutput instead of a plain tuple.
torch.FloatTensor
of shape (batch_size, num_frames, num_channels, height, width)
) —
Pixel values that mix positive and negative samples in Tvlt vision-audio matching. Audio values can be
obtained using TvltProcessor. See TvltProcessor.call() for details.
torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) —
Pixel masks of pixel_values_mixed. Pixel values mixed can be obtained using TvltProcessor. See
TvltProcessor.call() for details.
torch.LongTensor
of shape (batch_size, num_labels)
, optional) —
Labels for computing the vision audio matching loss. Indices should be in [0, 1]
. num_labels has to be 1.
Returns
transformers.models.tvlt.modeling_tvlt.TvltForPreTrainingOutput
or tuple(torch.FloatTensor)
A transformers.models.tvlt.modeling_tvlt.TvltForPreTrainingOutput
or a tuple of
torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various
elements depending on the configuration (TvltConfig) and inputs.
torch.FloatTensor
of shape (1,)
) — Pixel reconstruction loss.torch.FloatTensor
of shape (batch_size, 1)
) — Matching objective logits.torch.FloatTensor
of shape
(batch_size, pixel_patch_length, image_patch_size ** 3 * pixel_num_channels)
): Pixel reconstruction
logits.torch.FloatTensor
of shape
(batch_size, audio_patch_length, image_patch_size[0] * image_patch_size[1])
): Audio reconstruction
logits.tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of torch.FloatTensor
(one for the output of the embeddings and one for the output of each layer) of
shape (batch_size, sequence_length, hidden_size)
. Hidden-states of the model at the output of each layer
plus the initial embedding outputs.tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
. Attentions weights after the attention softmax, used to compute the weighted average in
the self-attention heads.The TvltForPreTraining forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Examples:
>>> from transformers import TvltProcessor, TvltForPreTraining
>>> import numpy as np
>>> import torch
>>> num_frames = 8
>>> images = list(np.random.randn(num_frames, 3, 224, 224))
>>> images_mixed = list(np.random.randn(num_frames, 3, 224, 224))
>>> audio = list(np.random.randn(10000))
>>> processor = TvltProcessor.from_pretrained("ZinengTang/tvlt-base")
>>> model = TvltForPreTraining.from_pretrained("ZinengTang/tvlt-base")
>>> input_dict = processor(
... images, audio, images_mixed, sampling_rate=44100, mask_pixel=True, mask_audio=True, return_tensors="pt"
... )
>>> outputs = model(**input_dict)
>>> loss = outputs.loss
( config )
Parameters
Tvlt Model transformer with a classifier head on top (an MLP on top of the final hidden state of the [CLS] token) for audiovisual classification tasks, e.g. CMU-MOSEI Sentiment Analysis and Audio to Video Retrieval.
This model is 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.
(
pixel_values
audio_values
pixel_mask = None
audio_mask = None
output_attentions = None
output_hidden_states = None
return_dict = None
labels = None
)
→
transformers.modeling_outputs.SequenceClassifierOutput or tuple(torch.FloatTensor)
Parameters
torch.FloatTensor
of shape (batch_size, num_frames, num_channels, height, width)
) —
Pixel values. Pixel values can be obtained using TvltProcessor. See TvltProcessor.call() for
details.
torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) —
Audio values. Audio values can be obtained using TvltProcessor. See TvltProcessor.call() for
details.
torch.FloatTensor
of shape (batch_size, num_pixel_patches)
) —
Pixel masks. Pixel masks can be obtained using TvltProcessor. See TvltProcessor.call() for
details.
torch.FloatTensor
of shape (batch_size, num_audio_patches)
) —
Audio masks. Audio masks can be obtained using TvltProcessor. See TvltProcessor.call() for
details.
torch.FloatTensor
of shape (batch_size, num_frames, num_channels, height, width)
) —
Pixel values that mix positive and negative samples in Tvlt vision-audio matching. Pixel values mixed can
be obtained using TvltProcessor. See TvltProcessor.call() for details.
torch.FloatTensor
of shape (batch_size, num_channels, height, width)
) —
Pixel masks of pixel_values_mixed. Pixel masks mixed can be obtained using TvltProcessor. See
TvltProcessor.call() for details.
bool
, optional) —
Whether to mask pixel for MAE tasks. Only set to True in TvltForPreTraining.
bool
, optional) —
Whether to mask audio for MAE tasks. Only set to True in TvltForPreTraining.
bool
, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions
under returned
tensors for more detail.
bool
, optional) —
Whether or not to return the hidden states of all layers. See hidden_states
under returned tensors for
more detail.
bool
, optional) —
Whether or not to return a ModelOutput instead of a plain tuple.
torch.LongTensor
of shape (batch_size, num_labels)
, optional) —
Labels for computing the audiovisual loss. Indices should be in [0, ..., num_classes-1]
where num_classes
refers to the number of classes in audiovisual tasks.
Returns
transformers.modeling_outputs.SequenceClassifierOutput or tuple(torch.FloatTensor)
A transformers.modeling_outputs.SequenceClassifierOutput or a tuple of
torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various
elements depending on the configuration (TvltConfig) and inputs.
loss (torch.FloatTensor
of shape (1,)
, optional, returned when labels
is provided) — Classification (or regression if config.num_labels==1) loss.
logits (torch.FloatTensor
of shape (batch_size, config.num_labels)
) — Classification (or regression if config.num_labels==1) scores (before SoftMax).
hidden_states (tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) — Tuple of torch.FloatTensor
(one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape (batch_size, sequence_length, hidden_size)
.
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) — Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
The TvltForAudioVisualClassification forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Examples:
>>> from transformers import TvltProcessor, TvltForAudioVisualClassification
>>> import numpy as np
>>> import torch
>>> num_frames = 8
>>> images = list(np.random.randn(num_frames, 3, 224, 224))
>>> audio = list(np.random.randn(10000))
>>> processor = TvltProcessor.from_pretrained("ZinengTang/tvlt-base")
>>> model = TvltForAudioVisualClassification.from_pretrained("ZinengTang/tvlt-base")
>>> input_dict = processor(images, audio, sampling_rate=44100, return_tensors="pt")
>>> outputs = model(**input_dict)
>>> loss = outputs.loss