Skip to content

timesformer

mindnlp.transformers.models.timesformer.configuration_timesformer

TimeSformer model configuration

mindnlp.transformers.models.timesformer.configuration_timesformer.TimesformerConfig

Bases: PretrainedConfig

This is the configuration class to store the configuration of a [TimesformerModel]. It is used to instantiate a TimeSformer 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 TimeSformer facebook/timesformer-base-finetuned-k600 architecture.

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

PARAMETER DESCRIPTION
image_size

The size (resolution) of each image.

TYPE: `int`, *optional*, defaults to 224 DEFAULT: 224

patch_size

The size (resolution) of each patch.

TYPE: `int`, *optional*, defaults to 16 DEFAULT: 16

num_channels

The number of input channels.

TYPE: `int`, *optional*, defaults to 3 DEFAULT: 3

num_frames

The number of frames in each video.

TYPE: `int`, *optional*, defaults to 8 DEFAULT: 8

hidden_size

Dimensionality of the encoder layers and the pooler layer.

TYPE: `int`, *optional*, defaults to 768 DEFAULT: 768

num_hidden_layers

Number of hidden layers in the Transformer encoder.

TYPE: `int`, *optional*, defaults to 12 DEFAULT: 12

num_attention_heads

Number of attention heads for each attention layer in the Transformer encoder.

TYPE: `int`, *optional*, defaults to 12 DEFAULT: 12

intermediate_size

Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.

TYPE: `int`, *optional*, defaults to 3072 DEFAULT: 3072

hidden_act

The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu", "relu", "selu" and "gelu_new" are supported.

TYPE: `str` or `function`, *optional*, defaults to `"gelu"` DEFAULT: 'gelu'

hidden_dropout_prob

The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.

TYPE: `float`, *optional*, defaults to 0.0 DEFAULT: 0.0

attention_probs_dropout_prob

The dropout ratio for the attention probabilities.

TYPE: `float`, *optional*, defaults to 0.0 DEFAULT: 0.0

initializer_range

The standard deviation of the truncated_normal_initializer for initializing all weight matrices.

TYPE: `float`, *optional*, defaults to 0.02 DEFAULT: 0.02

layer_norm_eps

The epsilon used by the layer normalization layers.

TYPE: `float`, *optional*, defaults to 1e-06 DEFAULT: 1e-06

qkv_bias

Whether to add a bias to the queries, keys and values.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

attention_type

The attention type to use. Must be one of "divided_space_time", "space_only", "joint_space_time".

TYPE: `str`, *optional*, defaults to `"divided_space_time"` DEFAULT: 'divided_space_time'

drop_path_rate

The dropout ratio for stochastic depth.

TYPE: `float`, *optional*, defaults to 0 DEFAULT: 0

Example
>>> from transformers import TimesformerConfig, TimesformerModel
...
>>> # Initializing a TimeSformer timesformer-base style configuration
>>> configuration = TimesformerConfig()
...
>>> # Initializing a model from the configuration
>>> model = TimesformerModel(configuration)
...
>>> # Accessing the model configuration
>>> configuration = model.config
Source code in mindnlp/transformers/models/timesformer/configuration_timesformer.py
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
class TimesformerConfig(PretrainedConfig):
    r"""
    This is the configuration class to store the configuration of a [`TimesformerModel`]. It is used to instantiate a
    TimeSformer 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 TimeSformer
    [facebook/timesformer-base-finetuned-k600](https://hf-mirror.com/facebook/timesformer-base-finetuned-k600)
    architecture.

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

    Args:
        image_size (`int`, *optional*, defaults to 224):
            The size (resolution) of each image.
        patch_size (`int`, *optional*, defaults to 16):
            The size (resolution) of each patch.
        num_channels (`int`, *optional*, defaults to 3):
            The number of input channels.
        num_frames (`int`, *optional*, defaults to 8):
            The number of frames in each video.
        hidden_size (`int`, *optional*, defaults to 768):
            Dimensionality of the encoder layers and the pooler layer.
        num_hidden_layers (`int`, *optional*, defaults to 12):
            Number of hidden layers in the Transformer encoder.
        num_attention_heads (`int`, *optional*, defaults to 12):
            Number of attention heads for each attention layer in the Transformer encoder.
        intermediate_size (`int`, *optional*, defaults to 3072):
            Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
        hidden_act (`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.
        hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
        attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the attention probabilities.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        layer_norm_eps (`float`, *optional*, defaults to 1e-06):
            The epsilon used by the layer normalization layers.
        qkv_bias (`bool`, *optional*, defaults to `True`):
            Whether to add a bias to the queries, keys and values.
        attention_type (`str`, *optional*, defaults to `"divided_space_time"`):
            The attention type to use. Must be one of `"divided_space_time"`, `"space_only"`, `"joint_space_time"`.
        drop_path_rate (`float`, *optional*, defaults to 0):
            The dropout ratio for stochastic depth.

    Example:
        ```python
        >>> from transformers import TimesformerConfig, TimesformerModel
        ...
        >>> # Initializing a TimeSformer timesformer-base style configuration
        >>> configuration = TimesformerConfig()
        ...
        >>> # Initializing a model from the configuration
        >>> model = TimesformerModel(configuration)
        ...
        >>> # Accessing the model configuration
        >>> configuration = model.config
        ```
    """
    model_type = "timesformer"

    def __init__(
        self,
        image_size=224,
        patch_size=16,
        num_channels=3,
        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-6,
        qkv_bias=True,
        attention_type="divided_space_time",
        drop_path_rate=0,
        **kwargs,
    ):
        """
        Initializes an instance of the TimesformerConfig class.

        Args:
            self (object): The TimesformerConfig object itself.
            image_size (int, optional): The size of the input image. Defaults to 224.
            patch_size (int, optional): The size of each patch in the input image. Defaults to 16.
            num_channels (int, optional): The number of channels in the input image. Defaults to 3.
            num_frames (int, optional): The number of frames in a video sequence. Defaults to 8.
            hidden_size (int, optional): The size of the hidden state in the transformer layers. Defaults to 768.
            num_hidden_layers (int, optional): The number of hidden layers in the transformer. Defaults to 12.
            num_attention_heads (int, optional): The number of attention heads in the transformer. Defaults to 12.
            intermediate_size (int, optional): The size of the intermediate layer in the transformer. Defaults to 3072.
            hidden_act (str, optional): The activation function for the hidden layers. Defaults to 'gelu'.
            hidden_dropout_prob (float, optional): The dropout probability for the hidden layers. Defaults to 0.0.
            attention_probs_dropout_prob (float, optional): The dropout probability for the attention layer. Defaults to 0.0.
            initializer_range (float, optional): The range for the initializer. Defaults to 0.02.
            layer_norm_eps (float, optional): The epsilon value for layer normalization. Defaults to 1e-06.
            qkv_bias (bool, optional): Whether to include bias terms in the qkv layers. Defaults to True.
            attention_type (str, optional): The type of attention used in the transformer. Defaults to 'divided_space_time'.
            drop_path_rate (float, optional): The drop path rate for stochastic depth. Defaults to 0.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__(**kwargs)

        self.image_size = image_size
        self.patch_size = patch_size
        self.num_channels = num_channels
        self.num_frames = num_frames

        self.hidden_size = hidden_size
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.intermediate_size = intermediate_size
        self.hidden_act = hidden_act
        self.hidden_dropout_prob = hidden_dropout_prob
        self.attention_probs_dropout_prob = attention_probs_dropout_prob
        self.initializer_range = initializer_range
        self.layer_norm_eps = layer_norm_eps
        self.qkv_bias = qkv_bias

        self.attention_type = attention_type
        self.drop_path_rate = drop_path_rate

mindnlp.transformers.models.timesformer.configuration_timesformer.TimesformerConfig.__init__(image_size=224, patch_size=16, num_channels=3, 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, attention_type='divided_space_time', drop_path_rate=0, **kwargs)

Initializes an instance of the TimesformerConfig class.

PARAMETER DESCRIPTION
self

The TimesformerConfig object itself.

TYPE: object

image_size

The size of the input image. Defaults to 224.

TYPE: int DEFAULT: 224

patch_size

The size of each patch in the input image. Defaults to 16.

TYPE: int DEFAULT: 16

num_channels

The number of channels in the input image. Defaults to 3.

TYPE: int DEFAULT: 3

num_frames

The number of frames in a video sequence. Defaults to 8.

TYPE: int DEFAULT: 8

hidden_size

The size of the hidden state in the transformer layers. Defaults to 768.

TYPE: int DEFAULT: 768

num_hidden_layers

The number of hidden layers in the transformer. Defaults to 12.

TYPE: int DEFAULT: 12

num_attention_heads

The number of attention heads in the transformer. Defaults to 12.

TYPE: int DEFAULT: 12

intermediate_size

The size of the intermediate layer in the transformer. Defaults to 3072.

TYPE: int DEFAULT: 3072

hidden_act

The activation function for the hidden layers. Defaults to 'gelu'.

TYPE: str DEFAULT: 'gelu'

hidden_dropout_prob

The dropout probability for the hidden layers. Defaults to 0.0.

TYPE: float DEFAULT: 0.0

attention_probs_dropout_prob

The dropout probability for the attention layer. Defaults to 0.0.

TYPE: float DEFAULT: 0.0

initializer_range

The range for the initializer. Defaults to 0.02.

TYPE: float DEFAULT: 0.02

layer_norm_eps

The epsilon value for layer normalization. Defaults to 1e-06.

TYPE: float DEFAULT: 1e-06

qkv_bias

Whether to include bias terms in the qkv layers. Defaults to True.

TYPE: bool DEFAULT: True

attention_type

The type of attention used in the transformer. Defaults to 'divided_space_time'.

TYPE: str DEFAULT: 'divided_space_time'

drop_path_rate

The drop path rate for stochastic depth. Defaults to 0.

TYPE: float DEFAULT: 0

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/timesformer/configuration_timesformer.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def __init__(
    self,
    image_size=224,
    patch_size=16,
    num_channels=3,
    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-6,
    qkv_bias=True,
    attention_type="divided_space_time",
    drop_path_rate=0,
    **kwargs,
):
    """
    Initializes an instance of the TimesformerConfig class.

    Args:
        self (object): The TimesformerConfig object itself.
        image_size (int, optional): The size of the input image. Defaults to 224.
        patch_size (int, optional): The size of each patch in the input image. Defaults to 16.
        num_channels (int, optional): The number of channels in the input image. Defaults to 3.
        num_frames (int, optional): The number of frames in a video sequence. Defaults to 8.
        hidden_size (int, optional): The size of the hidden state in the transformer layers. Defaults to 768.
        num_hidden_layers (int, optional): The number of hidden layers in the transformer. Defaults to 12.
        num_attention_heads (int, optional): The number of attention heads in the transformer. Defaults to 12.
        intermediate_size (int, optional): The size of the intermediate layer in the transformer. Defaults to 3072.
        hidden_act (str, optional): The activation function for the hidden layers. Defaults to 'gelu'.
        hidden_dropout_prob (float, optional): The dropout probability for the hidden layers. Defaults to 0.0.
        attention_probs_dropout_prob (float, optional): The dropout probability for the attention layer. Defaults to 0.0.
        initializer_range (float, optional): The range for the initializer. Defaults to 0.02.
        layer_norm_eps (float, optional): The epsilon value for layer normalization. Defaults to 1e-06.
        qkv_bias (bool, optional): Whether to include bias terms in the qkv layers. Defaults to True.
        attention_type (str, optional): The type of attention used in the transformer. Defaults to 'divided_space_time'.
        drop_path_rate (float, optional): The drop path rate for stochastic depth. Defaults to 0.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(**kwargs)

    self.image_size = image_size
    self.patch_size = patch_size
    self.num_channels = num_channels
    self.num_frames = num_frames

    self.hidden_size = hidden_size
    self.num_hidden_layers = num_hidden_layers
    self.num_attention_heads = num_attention_heads
    self.intermediate_size = intermediate_size
    self.hidden_act = hidden_act
    self.hidden_dropout_prob = hidden_dropout_prob
    self.attention_probs_dropout_prob = attention_probs_dropout_prob
    self.initializer_range = initializer_range
    self.layer_norm_eps = layer_norm_eps
    self.qkv_bias = qkv_bias

    self.attention_type = attention_type
    self.drop_path_rate = drop_path_rate

mindnlp.transformers.models.timesformer.modeling_timesformer

MindSpore TimeSformer model.

mindnlp.transformers.models.timesformer.modeling_timesformer.TimeSformerAttention

Bases: Module

The TimeSformerAttention class represents the self-attention mechanism for the TimeSformer model. It inherits from the nn.Module class and is responsible for performing self-attention and generating attention-based outputs.

The class contains the following methods:

  • init: Initializes the TimeSformerAttention instance with the provided configuration.
  • forward: Constructs the self-attention mechanism using the provided hidden states and optionally returns attention outputs.

This class is an essential component of the TimeSformer model, providing the functionality for self-attention computations and output generation.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
class TimeSformerAttention(nn.Module):

    """
    The TimeSformerAttention class represents the self-attention mechanism for the TimeSformer model. It inherits from
    the nn.Module class and is responsible for performing self-attention and generating attention-based outputs.

    The class contains the following methods:

    - __init__: Initializes the TimeSformerAttention instance with the provided configuration.
    - forward: Constructs the self-attention mechanism using the provided hidden states and optionally returns
    attention outputs.

    This class is an essential component of the TimeSformer model, providing the functionality for self-attention
    computations and output generation.
    """
    def __init__(self, config: TimesformerConfig) -> None:
        """
        Initializes a new instance of the TimeSformerAttention class.

        Args:
            self: The current instance of the TimeSformerAttention class.
            config (TimesformerConfig): The configuration object specifying the settings for the TimeSformerAttention.

        Returns:
            None.

        Raises:
            None.

        This method initializes the TimeSformerAttention class by setting up the attention and output layers.
        The 'self' parameter refers to the current instance of the class, while the 'config' parameter is an instance
        of the TimesformerConfig class that specifies the configuration settings for the TimeSformerAttention.

        The 'attention' attribute is assigned an instance of the TimesformerSelfAttention class, which handles the
        attention mechanism.
        The 'output' attribute is assigned an instance of the TimesformerSelfOutput class, which processes the
        attention output.

        Example:
            ```python
            >>> config = TimesformerConfig()
            >>> time_sformer_attention = TimeSformerAttention(config)
            ```
        """
        super().__init__()
        self.attention = TimesformerSelfAttention(config)
        self.output = TimesformerSelfOutput(config)

    def forward(
        self,
        hidden_states: mindspore.Tensor,
        output_attentions: bool = False,
    ) -> Union[Tuple[mindspore.Tensor, mindspore.Tensor], Tuple[mindspore.Tensor]]:
        '''
        This method forwards the attention mechanism for the TimeSformer model.

        Args:
            self: This parameter refers to the instance of the class itself.
            hidden_states (mindspore.Tensor): The input hidden states on which the attention mechanism is applied.
            output_attentions (bool, optional): A flag indicating whether to return the attention outputs.
                Defaults to False.

        Returns:
            Union[Tuple[mindspore.Tensor, mindspore.Tensor], Tuple[mindspore.Tensor]]:

                - If output_attentions is True, returns a tuple containing the attention output tensor and the attention
                weights tensor.
                - If output_attentions is False, returns a tuple containing only the attention output tensor.

        Raises:
            ValueError: If the hidden_states tensor is not of the expected format or shape.
            TypeError: If the input arguments are not of the expected types.
        '''
        self_outputs = self.attention(hidden_states, output_attentions)

        attention_output = self.output(self_outputs[0])

        outputs = (attention_output,) + self_outputs[1:]  # add attentions if we output them
        return outputs

mindnlp.transformers.models.timesformer.modeling_timesformer.TimeSformerAttention.__init__(config)

Initializes a new instance of the TimeSformerAttention class.

PARAMETER DESCRIPTION
self

The current instance of the TimeSformerAttention class.

config

The configuration object specifying the settings for the TimeSformerAttention.

TYPE: TimesformerConfig

RETURNS DESCRIPTION
None

None.

This method initializes the TimeSformerAttention class by setting up the attention and output layers. The 'self' parameter refers to the current instance of the class, while the 'config' parameter is an instance of the TimesformerConfig class that specifies the configuration settings for the TimeSformerAttention.

The 'attention' attribute is assigned an instance of the TimesformerSelfAttention class, which handles the attention mechanism. The 'output' attribute is assigned an instance of the TimesformerSelfOutput class, which processes the attention output.

Example
>>> config = TimesformerConfig()
>>> time_sformer_attention = TimeSformerAttention(config)
Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
def __init__(self, config: TimesformerConfig) -> None:
    """
    Initializes a new instance of the TimeSformerAttention class.

    Args:
        self: The current instance of the TimeSformerAttention class.
        config (TimesformerConfig): The configuration object specifying the settings for the TimeSformerAttention.

    Returns:
        None.

    Raises:
        None.

    This method initializes the TimeSformerAttention class by setting up the attention and output layers.
    The 'self' parameter refers to the current instance of the class, while the 'config' parameter is an instance
    of the TimesformerConfig class that specifies the configuration settings for the TimeSformerAttention.

    The 'attention' attribute is assigned an instance of the TimesformerSelfAttention class, which handles the
    attention mechanism.
    The 'output' attribute is assigned an instance of the TimesformerSelfOutput class, which processes the
    attention output.

    Example:
        ```python
        >>> config = TimesformerConfig()
        >>> time_sformer_attention = TimeSformerAttention(config)
        ```
    """
    super().__init__()
    self.attention = TimesformerSelfAttention(config)
    self.output = TimesformerSelfOutput(config)

mindnlp.transformers.models.timesformer.modeling_timesformer.TimeSformerAttention.forward(hidden_states, output_attentions=False)

This method forwards the attention mechanism for the TimeSformer model.

PARAMETER DESCRIPTION
self

This parameter refers to the instance of the class itself.

hidden_states

The input hidden states on which the attention mechanism is applied.

TYPE: Tensor

output_attentions

A flag indicating whether to return the attention outputs. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Union[Tuple[Tensor, Tensor], Tuple[Tensor]]

Union[Tuple[mindspore.Tensor, mindspore.Tensor], Tuple[mindspore.Tensor]]:

  • If output_attentions is True, returns a tuple containing the attention output tensor and the attention weights tensor.
  • If output_attentions is False, returns a tuple containing only the attention output tensor.
RAISES DESCRIPTION
ValueError

If the hidden_states tensor is not of the expected format or shape.

TypeError

If the input arguments are not of the expected types.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
def forward(
    self,
    hidden_states: mindspore.Tensor,
    output_attentions: bool = False,
) -> Union[Tuple[mindspore.Tensor, mindspore.Tensor], Tuple[mindspore.Tensor]]:
    '''
    This method forwards the attention mechanism for the TimeSformer model.

    Args:
        self: This parameter refers to the instance of the class itself.
        hidden_states (mindspore.Tensor): The input hidden states on which the attention mechanism is applied.
        output_attentions (bool, optional): A flag indicating whether to return the attention outputs.
            Defaults to False.

    Returns:
        Union[Tuple[mindspore.Tensor, mindspore.Tensor], Tuple[mindspore.Tensor]]:

            - If output_attentions is True, returns a tuple containing the attention output tensor and the attention
            weights tensor.
            - If output_attentions is False, returns a tuple containing only the attention output tensor.

    Raises:
        ValueError: If the hidden_states tensor is not of the expected format or shape.
        TypeError: If the input arguments are not of the expected types.
    '''
    self_outputs = self.attention(hidden_states, output_attentions)

    attention_output = self.output(self_outputs[0])

    outputs = (attention_output,) + self_outputs[1:]  # add attentions if we output them
    return outputs

mindnlp.transformers.models.timesformer.modeling_timesformer.TimeSformerDropPath

Bases: Module

Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
class TimeSformerDropPath(nn.Module):
    """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
    def __init__(self, drop_prob: Optional[float] = None) -> None:
        """
        Initializes an instance of the TimeSformerDropPath class.

        Args:
            self: The instance of the class.
            drop_prob (Optional[float]): The probability of dropping a path during training. Default is None.
                A floating-point number between 0 and 1 representing the probability of dropping a path.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__()
        self.drop_prob = drop_prob

    def forward(self, hidden_states: mindspore.Tensor) -> mindspore.Tensor:
        """
        Method to apply drop path regularization to the hidden states.

        Args:
            self (TimeSformerDropPath): An instance of the TimeSformerDropPath class.
            hidden_states (mindspore.Tensor):
                The hidden states tensor to apply drop path regularization to.

                - Type: mindspore.Tensor
                - Purpose: Represents the intermediate hidden states in the model.
                - Restrictions: Should be a tensor compatible with the drop_path function.

        Returns:
            mindspore.Tensor:
                The hidden states tensor after applying drop path regularization.

                - Type: mindspore.Tensor
                - Purpose: Represents the modified hidden states with drop path regularization applied.

        Raises:
            None.
        """
        return drop_path(hidden_states, self.drop_prob, self.training)

    def extra_repr(self) -> str:
        """
        Returns a string representation of the TimeSformerDropPath object.

        Args:
            self: The current instance of the TimeSformerDropPath class.

        Returns:
            string:
                A string representing the TimeSformerDropPath object. The string is formatted as 'p={}' where '{}'
                is replaced with the value of the 'drop_prob' attribute of the current instance.

        Raises:
            None.
        """
        return "p={}".format(self.drop_prob)

mindnlp.transformers.models.timesformer.modeling_timesformer.TimeSformerDropPath.__init__(drop_prob=None)

Initializes an instance of the TimeSformerDropPath class.

PARAMETER DESCRIPTION
self

The instance of the class.

drop_prob

The probability of dropping a path during training. Default is None. A floating-point number between 0 and 1 representing the probability of dropping a path.

TYPE: Optional[float] DEFAULT: None

RETURNS DESCRIPTION
None

None.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
def __init__(self, drop_prob: Optional[float] = None) -> None:
    """
    Initializes an instance of the TimeSformerDropPath class.

    Args:
        self: The instance of the class.
        drop_prob (Optional[float]): The probability of dropping a path during training. Default is None.
            A floating-point number between 0 and 1 representing the probability of dropping a path.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__()
    self.drop_prob = drop_prob

mindnlp.transformers.models.timesformer.modeling_timesformer.TimeSformerDropPath.extra_repr()

Returns a string representation of the TimeSformerDropPath object.

PARAMETER DESCRIPTION
self

The current instance of the TimeSformerDropPath class.

RETURNS DESCRIPTION
string

A string representing the TimeSformerDropPath object. The string is formatted as 'p={}' where '{}' is replaced with the value of the 'drop_prob' attribute of the current instance.

TYPE: str

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def extra_repr(self) -> str:
    """
    Returns a string representation of the TimeSformerDropPath object.

    Args:
        self: The current instance of the TimeSformerDropPath class.

    Returns:
        string:
            A string representing the TimeSformerDropPath object. The string is formatted as 'p={}' where '{}'
            is replaced with the value of the 'drop_prob' attribute of the current instance.

    Raises:
        None.
    """
    return "p={}".format(self.drop_prob)

mindnlp.transformers.models.timesformer.modeling_timesformer.TimeSformerDropPath.forward(hidden_states)

Method to apply drop path regularization to the hidden states.

PARAMETER DESCRIPTION
self

An instance of the TimeSformerDropPath class.

TYPE: TimeSformerDropPath

hidden_states

The hidden states tensor to apply drop path regularization to.

  • Type: mindspore.Tensor
  • Purpose: Represents the intermediate hidden states in the model.
  • Restrictions: Should be a tensor compatible with the drop_path function.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

mindspore.Tensor: The hidden states tensor after applying drop path regularization.

  • Type: mindspore.Tensor
  • Purpose: Represents the modified hidden states with drop path regularization applied.
Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
def forward(self, hidden_states: mindspore.Tensor) -> mindspore.Tensor:
    """
    Method to apply drop path regularization to the hidden states.

    Args:
        self (TimeSformerDropPath): An instance of the TimeSformerDropPath class.
        hidden_states (mindspore.Tensor):
            The hidden states tensor to apply drop path regularization to.

            - Type: mindspore.Tensor
            - Purpose: Represents the intermediate hidden states in the model.
            - Restrictions: Should be a tensor compatible with the drop_path function.

    Returns:
        mindspore.Tensor:
            The hidden states tensor after applying drop path regularization.

            - Type: mindspore.Tensor
            - Purpose: Represents the modified hidden states with drop path regularization applied.

    Raises:
        None.
    """
    return drop_path(hidden_states, self.drop_prob, self.training)

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerEmbeddings

Bases: Module

Construct the patch and position embeddings.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
class TimesformerEmbeddings(nn.Module):
    """
    Construct the patch and position embeddings.
    """
    def __init__(self, config):
        """
        Initialize the TimesformerEmbeddings instance with the given configuration.

        Args:
            config (object):
                An object containing the configuration parameters for the TimesformerEmbeddings.

                - hidden_size (int): The embedding dimension.
                - num_frames (int): The number of frames in the input.
                - hidden_dropout_prob (float): The dropout rate for the embeddings.
                - attention_type (str): The type of attention mechanism to be used. Can be 'space_only'
                or any other value.

        Returns:
            None

        Raises:
            None
        """
        super().__init__()

        embed_dim = config.hidden_size
        num_frames = config.num_frames
        drop_rate = config.hidden_dropout_prob
        attention_type = config.attention_type

        self.attention_type = attention_type
        self.patch_embeddings = TimesformerPatchEmbeddings(config)
        self.num_patches = self.patch_embeddings.num_patches

        # Positional Embeddings
        self.cls_token = mindspore.Parameter(ops.zeros(1, 1, embed_dim))
        self.position_embeddings = mindspore.Parameter(ops.zeros(1, self.num_patches + 1, embed_dim))
        self.pos_drop = nn.Dropout(p=drop_rate)
        if attention_type != "space_only":
            self.time_embeddings = mindspore.Parameter(ops.zeros(1, num_frames, embed_dim))
            self.time_drop = nn.Dropout(p=drop_rate)

    def forward(self, pixel_values):
        """
        Constructs the embeddings for the Timesformer model.

        Args:
            self: An instance of the TimesformerEmbeddings class.
            pixel_values (torch.Tensor): A tensor of shape (batch_size, num_frames, patch_height, patch_width)
                representing the input pixel values.

        Returns:
            torch.Tensor: A tensor of shape (batch_size, total_patches, embedding_dim) representing the
                forwarded embeddings.

        Raises:
            None.

        This method takes in a tensor of pixel values and forwards the embeddings for the Timesformer model.
        The input tensor is expected to have dimensions (batch_size, num_frames, patch_height, patch_width).
        The method first computes patch embeddings using the `patch_embeddings` function. It then adds a special token
        (`cls_token`) to the embeddings. If the shape of the embeddings does not match the shape of the position
        embeddings, the method adjusts the position embeddings to match the shape of the embeddings.
        The method then adds the adjusted position embeddings to the embeddings. The embeddings are
        then passed through a dropout layer (`pos_drop`).

        If the attention type is not 'space_only', the method separates the `cls_token` from the embeddings, converts
        the embeddings to the desired shape, and adds time embeddings to the embeddings. The time embeddings are
        adjusted to match the number of frames in the input tensor. The adjusted time embeddings are added to the
        embeddings. The embeddings are then passed through a dropout layer (`time_drop`).
        Finally, the embeddings are reshaped and the `cls_token` is concatenated back to the embeddings.

        The method returns the forwarded embeddings.
        """
        batch_size = pixel_values.shape[0]

        # create patch embeddings
        embeddings, num_frames, patch_width = self.patch_embeddings(pixel_values)

        cls_tokens = self.cls_token.broadcast_to((embeddings.shape[0], -1, -1))
        embeddings = ops.cat((cls_tokens, embeddings), axis=1)

        # resizing the positional embeddings in case they don't match the input at inference
        if embeddings.shape[1] != self.position_embeddings.shape[1]:
            position_embeddings = self.position_embeddings
            cls_pos_embed = position_embeddings[0, 0, :].unsqueeze(0).unsqueeze(1)
            other_pos_embed = position_embeddings[0, 1:, :].unsqueeze(0).swapaxes(1, 2)
            patch_num = int(other_pos_embed.shape[2] ** 0.5)
            patch_height = embeddings.shape[1] // patch_width
            other_pos_embed = other_pos_embed.reshape(1, embeddings.shape[2], patch_num, patch_num)
            new_pos_embed = ops.interpolate(
                other_pos_embed, size=(patch_height, patch_width), mode="nearest"
            )
            new_pos_embed = new_pos_embed.flatten(2)
            new_pos_embed = new_pos_embed.swapaxes(1, 2)
            new_pos_embed = ops.cat((cls_pos_embed, new_pos_embed), 1)
            embeddings = embeddings + new_pos_embed
        else:
            embeddings = embeddings + self.position_embeddings
        embeddings = self.pos_drop(embeddings)

        # Time Embeddings
        if self.attention_type != "space_only":
            cls_tokens = embeddings[:batch_size, 0, :].unsqueeze(1)
            embeddings = embeddings[:, 1:]
            _, patch_height, patch_width = embeddings.shape
            embeddings = (
                embeddings.reshape(batch_size, num_frames, patch_height, patch_width)
                .permute(0, 2, 1, 3)
                .reshape(batch_size * patch_height, num_frames, patch_width)
            )
            # Resizing time embeddings in case they don't match
            if num_frames != self.time_embeddings.shape[1]:
                time_embeddings = self.time_embeddings.swapaxes(1, 2)
                new_time_embeddings = ops.interpolate(time_embeddings, size=(num_frames), mode="nearest")
                new_time_embeddings = new_time_embeddings.swapaxes(1, 2)
                embeddings = embeddings + new_time_embeddings
            else:
                embeddings = embeddings + self.time_embeddings
            embeddings = self.time_drop(embeddings)
            embeddings = embeddings.view(batch_size, patch_height, num_frames, patch_width).reshape(
                batch_size, patch_height * num_frames, patch_width
            )
            embeddings = ops.cat((cls_tokens, embeddings), axis=1)

        return embeddings

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerEmbeddings.__init__(config)

Initialize the TimesformerEmbeddings instance with the given configuration.

PARAMETER DESCRIPTION
config

An object containing the configuration parameters for the TimesformerEmbeddings.

  • hidden_size (int): The embedding dimension.
  • num_frames (int): The number of frames in the input.
  • hidden_dropout_prob (float): The dropout rate for the embeddings.
  • attention_type (str): The type of attention mechanism to be used. Can be 'space_only' or any other value.

TYPE: object

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
def __init__(self, config):
    """
    Initialize the TimesformerEmbeddings instance with the given configuration.

    Args:
        config (object):
            An object containing the configuration parameters for the TimesformerEmbeddings.

            - hidden_size (int): The embedding dimension.
            - num_frames (int): The number of frames in the input.
            - hidden_dropout_prob (float): The dropout rate for the embeddings.
            - attention_type (str): The type of attention mechanism to be used. Can be 'space_only'
            or any other value.

    Returns:
        None

    Raises:
        None
    """
    super().__init__()

    embed_dim = config.hidden_size
    num_frames = config.num_frames
    drop_rate = config.hidden_dropout_prob
    attention_type = config.attention_type

    self.attention_type = attention_type
    self.patch_embeddings = TimesformerPatchEmbeddings(config)
    self.num_patches = self.patch_embeddings.num_patches

    # Positional Embeddings
    self.cls_token = mindspore.Parameter(ops.zeros(1, 1, embed_dim))
    self.position_embeddings = mindspore.Parameter(ops.zeros(1, self.num_patches + 1, embed_dim))
    self.pos_drop = nn.Dropout(p=drop_rate)
    if attention_type != "space_only":
        self.time_embeddings = mindspore.Parameter(ops.zeros(1, num_frames, embed_dim))
        self.time_drop = nn.Dropout(p=drop_rate)

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerEmbeddings.forward(pixel_values)

Constructs the embeddings for the Timesformer model.

PARAMETER DESCRIPTION
self

An instance of the TimesformerEmbeddings class.

pixel_values

A tensor of shape (batch_size, num_frames, patch_height, patch_width) representing the input pixel values.

TYPE: Tensor

RETURNS DESCRIPTION

torch.Tensor: A tensor of shape (batch_size, total_patches, embedding_dim) representing the forwarded embeddings.

This method takes in a tensor of pixel values and forwards the embeddings for the Timesformer model. The input tensor is expected to have dimensions (batch_size, num_frames, patch_height, patch_width). The method first computes patch embeddings using the patch_embeddings function. It then adds a special token (cls_token) to the embeddings. If the shape of the embeddings does not match the shape of the position embeddings, the method adjusts the position embeddings to match the shape of the embeddings. The method then adds the adjusted position embeddings to the embeddings. The embeddings are then passed through a dropout layer (pos_drop).

If the attention type is not 'space_only', the method separates the cls_token from the embeddings, converts the embeddings to the desired shape, and adds time embeddings to the embeddings. The time embeddings are adjusted to match the number of frames in the input tensor. The adjusted time embeddings are added to the embeddings. The embeddings are then passed through a dropout layer (time_drop). Finally, the embeddings are reshaped and the cls_token is concatenated back to the embeddings.

The method returns the forwarded embeddings.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def forward(self, pixel_values):
    """
    Constructs the embeddings for the Timesformer model.

    Args:
        self: An instance of the TimesformerEmbeddings class.
        pixel_values (torch.Tensor): A tensor of shape (batch_size, num_frames, patch_height, patch_width)
            representing the input pixel values.

    Returns:
        torch.Tensor: A tensor of shape (batch_size, total_patches, embedding_dim) representing the
            forwarded embeddings.

    Raises:
        None.

    This method takes in a tensor of pixel values and forwards the embeddings for the Timesformer model.
    The input tensor is expected to have dimensions (batch_size, num_frames, patch_height, patch_width).
    The method first computes patch embeddings using the `patch_embeddings` function. It then adds a special token
    (`cls_token`) to the embeddings. If the shape of the embeddings does not match the shape of the position
    embeddings, the method adjusts the position embeddings to match the shape of the embeddings.
    The method then adds the adjusted position embeddings to the embeddings. The embeddings are
    then passed through a dropout layer (`pos_drop`).

    If the attention type is not 'space_only', the method separates the `cls_token` from the embeddings, converts
    the embeddings to the desired shape, and adds time embeddings to the embeddings. The time embeddings are
    adjusted to match the number of frames in the input tensor. The adjusted time embeddings are added to the
    embeddings. The embeddings are then passed through a dropout layer (`time_drop`).
    Finally, the embeddings are reshaped and the `cls_token` is concatenated back to the embeddings.

    The method returns the forwarded embeddings.
    """
    batch_size = pixel_values.shape[0]

    # create patch embeddings
    embeddings, num_frames, patch_width = self.patch_embeddings(pixel_values)

    cls_tokens = self.cls_token.broadcast_to((embeddings.shape[0], -1, -1))
    embeddings = ops.cat((cls_tokens, embeddings), axis=1)

    # resizing the positional embeddings in case they don't match the input at inference
    if embeddings.shape[1] != self.position_embeddings.shape[1]:
        position_embeddings = self.position_embeddings
        cls_pos_embed = position_embeddings[0, 0, :].unsqueeze(0).unsqueeze(1)
        other_pos_embed = position_embeddings[0, 1:, :].unsqueeze(0).swapaxes(1, 2)
        patch_num = int(other_pos_embed.shape[2] ** 0.5)
        patch_height = embeddings.shape[1] // patch_width
        other_pos_embed = other_pos_embed.reshape(1, embeddings.shape[2], patch_num, patch_num)
        new_pos_embed = ops.interpolate(
            other_pos_embed, size=(patch_height, patch_width), mode="nearest"
        )
        new_pos_embed = new_pos_embed.flatten(2)
        new_pos_embed = new_pos_embed.swapaxes(1, 2)
        new_pos_embed = ops.cat((cls_pos_embed, new_pos_embed), 1)
        embeddings = embeddings + new_pos_embed
    else:
        embeddings = embeddings + self.position_embeddings
    embeddings = self.pos_drop(embeddings)

    # Time Embeddings
    if self.attention_type != "space_only":
        cls_tokens = embeddings[:batch_size, 0, :].unsqueeze(1)
        embeddings = embeddings[:, 1:]
        _, patch_height, patch_width = embeddings.shape
        embeddings = (
            embeddings.reshape(batch_size, num_frames, patch_height, patch_width)
            .permute(0, 2, 1, 3)
            .reshape(batch_size * patch_height, num_frames, patch_width)
        )
        # Resizing time embeddings in case they don't match
        if num_frames != self.time_embeddings.shape[1]:
            time_embeddings = self.time_embeddings.swapaxes(1, 2)
            new_time_embeddings = ops.interpolate(time_embeddings, size=(num_frames), mode="nearest")
            new_time_embeddings = new_time_embeddings.swapaxes(1, 2)
            embeddings = embeddings + new_time_embeddings
        else:
            embeddings = embeddings + self.time_embeddings
        embeddings = self.time_drop(embeddings)
        embeddings = embeddings.view(batch_size, patch_height, num_frames, patch_width).reshape(
            batch_size, patch_height * num_frames, patch_width
        )
        embeddings = ops.cat((cls_tokens, embeddings), axis=1)

    return embeddings

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerEncoder

Bases: Module

The TimesformerEncoder class represents a Timesformer encoder module that is used for encoding input sequences. It inherits from the nn.Module class.

ATTRIBUTE DESCRIPTION
config

The configuration object that specifies the hyperparameters of the Timesformer encoder.

TYPE: TimesformerConfig

layer

A list of TimesformerLayer instances that make up the encoder's layers.

TYPE: ModuleList

Note
  • The TimesformerEncoder is composed of multiple TimesformerLayer instances.
  • The hidden states and attention weights can be optionally returned for each layer.
  • The output can be returned either as a tuple or as a BaseModelOutput dictionary.
Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
class TimesformerEncoder(nn.Module):

    """
    The TimesformerEncoder class represents a Timesformer encoder module that is used for encoding input sequences.
    It inherits from the nn.Module class.

    Attributes:
        config (TimesformerConfig): The configuration object that specifies the hyperparameters of the
            Timesformer encoder.
        layer (nn.ModuleList): A list of TimesformerLayer instances that make up the encoder's layers.

    Note:
        - The TimesformerEncoder is composed of multiple TimesformerLayer instances.
        - The hidden states and attention weights can be optionally returned for each layer.
        - The output can be returned either as a tuple or as a BaseModelOutput dictionary.
    """
    def __init__(self, config: TimesformerConfig) -> None:
        """
        Initializes the TimesformerEncoder object with the given configuration.

        Args:
            self (TimesformerEncoder): The instance of the TimesformerEncoder class.
            config (TimesformerConfig):
                The configuration object containing the settings for the TimesformerEncoder.

                - The 'config' parameter must be an instance of the TimesformerConfig class.

        Returns:
            None

        Raises:
            None
        """
        super().__init__()
        self.config = config
        self.layer = nn.ModuleList([TimesformerLayer(config, ind) for ind in range(config.num_hidden_layers)])
        # dady self.gradient_checkpointing = False

    def forward(
        self,
        hidden_states: mindspore.Tensor,
        output_attentions: bool = False,
        output_hidden_states: bool = False,
        return_dict: bool = True,
    ) -> Union[tuple, BaseModelOutput]:
        """
        Constructs the TimesformerEncoder.

        Args:
            self (TimesformerEncoder): An instance of the TimesformerEncoder class.
            hidden_states (mindspore.Tensor): The input hidden states. Expected shape is
                (batch_size, sequence_length, hidden_size).
            output_attentions (bool, optional): Whether to output the attention weights of each layer. Defaults to False.
            output_hidden_states (bool, optional): Whether to output the hidden states of each layer. Defaults to False.
            return_dict (bool, optional): Whether to return the output as a dictionary. Defaults to True.

        Returns:
            Union[tuple, BaseModelOutput]: The output of the TimesformerEncoder.
                If return_dict is True, returns a dictionary with the following keys:

                - last_hidden_state (mindspore.Tensor): The last layer's hidden states. Shape is
                (batch_size, sequence_length, hidden_size).
                - hidden_states (tuple): A tuple containing the hidden states of each layer. Each hidden state has a
                shape of (batch_size, sequence_length, hidden_size).
                - attentions (tuple): A tuple containing the attention weights of each layer. Each attention weight
                matrix has a shape of (batch_size, num_heads, sequence_length, sequence_length).
            If return_dict is False, returns a tuple containing only the non-None values from the dictionary.

        Raises:
            None.
        """
        all_hidden_states = () if output_hidden_states else None
        all_self_attentions = () if output_attentions else None

        for i, layer_module in enumerate(self.layer):
            if output_hidden_states:
                all_hidden_states = all_hidden_states + (hidden_states,)

            layer_outputs = layer_module(hidden_states, output_attentions)

            hidden_states = layer_outputs[0]

            if output_attentions:
                all_self_attentions = all_self_attentions + (layer_outputs[1],)

        if output_hidden_states:
            all_hidden_states = all_hidden_states + (hidden_states,)

        if not return_dict:
            return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
        return BaseModelOutput(
            last_hidden_state=hidden_states,
            hidden_states=all_hidden_states,
            attentions=all_self_attentions,
        )

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerEncoder.__init__(config)

Initializes the TimesformerEncoder object with the given configuration.

PARAMETER DESCRIPTION
self

The instance of the TimesformerEncoder class.

TYPE: TimesformerEncoder

config

The configuration object containing the settings for the TimesformerEncoder.

  • The 'config' parameter must be an instance of the TimesformerConfig class.

TYPE: TimesformerConfig

RETURNS DESCRIPTION
None

None

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
def __init__(self, config: TimesformerConfig) -> None:
    """
    Initializes the TimesformerEncoder object with the given configuration.

    Args:
        self (TimesformerEncoder): The instance of the TimesformerEncoder class.
        config (TimesformerConfig):
            The configuration object containing the settings for the TimesformerEncoder.

            - The 'config' parameter must be an instance of the TimesformerConfig class.

    Returns:
        None

    Raises:
        None
    """
    super().__init__()
    self.config = config
    self.layer = nn.ModuleList([TimesformerLayer(config, ind) for ind in range(config.num_hidden_layers)])

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerEncoder.forward(hidden_states, output_attentions=False, output_hidden_states=False, return_dict=True)

Constructs the TimesformerEncoder.

PARAMETER DESCRIPTION
self

An instance of the TimesformerEncoder class.

TYPE: TimesformerEncoder

hidden_states

The input hidden states. Expected shape is (batch_size, sequence_length, hidden_size).

TYPE: Tensor

output_attentions

Whether to output the attention weights of each layer. Defaults to False.

TYPE: bool DEFAULT: False

output_hidden_states

Whether to output the hidden states of each layer. Defaults to False.

TYPE: bool DEFAULT: False

return_dict

Whether to return the output as a dictionary. Defaults to True.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
Union[tuple, BaseModelOutput]

Union[tuple, BaseModelOutput]: The output of the TimesformerEncoder. If return_dict is True, returns a dictionary with the following keys:

  • last_hidden_state (mindspore.Tensor): The last layer's hidden states. Shape is (batch_size, sequence_length, hidden_size).
  • hidden_states (tuple): A tuple containing the hidden states of each layer. Each hidden state has a shape of (batch_size, sequence_length, hidden_size).
  • attentions (tuple): A tuple containing the attention weights of each layer. Each attention weight matrix has a shape of (batch_size, num_heads, sequence_length, sequence_length).
Union[tuple, BaseModelOutput]

If return_dict is False, returns a tuple containing only the non-None values from the dictionary.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
def forward(
    self,
    hidden_states: mindspore.Tensor,
    output_attentions: bool = False,
    output_hidden_states: bool = False,
    return_dict: bool = True,
) -> Union[tuple, BaseModelOutput]:
    """
    Constructs the TimesformerEncoder.

    Args:
        self (TimesformerEncoder): An instance of the TimesformerEncoder class.
        hidden_states (mindspore.Tensor): The input hidden states. Expected shape is
            (batch_size, sequence_length, hidden_size).
        output_attentions (bool, optional): Whether to output the attention weights of each layer. Defaults to False.
        output_hidden_states (bool, optional): Whether to output the hidden states of each layer. Defaults to False.
        return_dict (bool, optional): Whether to return the output as a dictionary. Defaults to True.

    Returns:
        Union[tuple, BaseModelOutput]: The output of the TimesformerEncoder.
            If return_dict is True, returns a dictionary with the following keys:

            - last_hidden_state (mindspore.Tensor): The last layer's hidden states. Shape is
            (batch_size, sequence_length, hidden_size).
            - hidden_states (tuple): A tuple containing the hidden states of each layer. Each hidden state has a
            shape of (batch_size, sequence_length, hidden_size).
            - attentions (tuple): A tuple containing the attention weights of each layer. Each attention weight
            matrix has a shape of (batch_size, num_heads, sequence_length, sequence_length).
        If return_dict is False, returns a tuple containing only the non-None values from the dictionary.

    Raises:
        None.
    """
    all_hidden_states = () if output_hidden_states else None
    all_self_attentions = () if output_attentions else None

    for i, layer_module in enumerate(self.layer):
        if output_hidden_states:
            all_hidden_states = all_hidden_states + (hidden_states,)

        layer_outputs = layer_module(hidden_states, output_attentions)

        hidden_states = layer_outputs[0]

        if output_attentions:
            all_self_attentions = all_self_attentions + (layer_outputs[1],)

    if output_hidden_states:
        all_hidden_states = all_hidden_states + (hidden_states,)

    if not return_dict:
        return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
    return BaseModelOutput(
        last_hidden_state=hidden_states,
        hidden_states=all_hidden_states,
        attentions=all_self_attentions,
    )

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerForVideoClassification

Bases: TimesformerPreTrainedModel

TimesformerForVideoClassification

This class is a video classification model based on the Timesformer architecture. It inherits from the TimesformerPreTrainedModel class.

ATTRIBUTE DESCRIPTION
num_labels

The number of labels for classification.

TYPE: int

timesformer

The Timesformer model for video classification.

TYPE: TimesformerModel

classifier

The classifier layer for the model.

TYPE: Linear or Identity

config

The configuration object for the model.

TYPE: Config

METHOD DESCRIPTION
__init__

Initializes the TimesformerForVideoClassification instance.

forward

Constructs the model and computes the loss and output.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
class TimesformerForVideoClassification(TimesformerPreTrainedModel):

    """TimesformerForVideoClassification

    This class is a video classification model based on the Timesformer architecture.
    It inherits from the TimesformerPreTrainedModel class.

    Attributes:
        num_labels (int): The number of labels for classification.
        timesformer (TimesformerModel): The Timesformer model for video classification.
        classifier (nn.Linear or nn.Identity): The classifier layer for the model.
        config (Config): The configuration object for the model.

    Methods:
        __init__: Initializes the TimesformerForVideoClassification instance.
        forward: Constructs the model and computes the loss and output.

    """
    def __init__(self, config):
        """
        Initializes a new instance of the TimesformerForVideoClassification class.

        Args:
            self (object): The instance of the class.
            config (object):
                An object containing configuration parameters for the model.

                - num_labels (int): The number of output labels for classification.
                Must be a positive integer.
                - hidden_size (int): The size of the hidden layers in the model.
                Must be a positive integer.

        Returns:
            None.

        Raises:
            AttributeError: If the 'config' object does not contain the required attributes.
            TypeError: If the 'num_labels' or 'hidden_size' attributes in 'config' are not integers.
        """
        super().__init__(config)

        self.num_labels = config.num_labels
        self.timesformer = TimesformerModel(config)

        # Classifier head
        self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()

        # Initialize weights and apply final processing
        self.post_init()

    def forward(
        self,
        pixel_values: Optional[mindspore.Tensor] = None,
        labels: Optional[mindspore.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, ImageClassifierOutput]:
        r"""

        Args:
            labels (`mindspore.Tensor` of shape `(batch_size,)`, *optional*):
                Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
                config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
                `config.num_labels > 1` a classification loss is computed (Cross-Entropy).

        Returns:
            Union[Tuple, ImageClassifierOutput]

        Example:
            ```python
            >>> import av
            >>> import mindspore
            >>> import mindnlp
            >>> import numpy as np
            ...
            >>> from mindnlp.transformers import AutoImageProcessor, TimesformerForVideoClassification
            >>> from huggingface_hub import hf_hub_download
            ...
            >>> np.random.seed(0)
            ...
            ...
            >>> def read_video_pyav(container, indices):
            ...     '''
            ...     Decode the video with PyAV decoder.
            ...     Args:
            ...         container (`av.container.input.InputContainer`): PyAV container.
            ...         indices (`List[int]`): List of frame indices to decode.
            ...     Returns:
            ...         result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
            ...     '''
            ...     frames = []
            ...     container.seek(0)
            ...     start_index = indices[0]
            ...     end_index = indices[-1]
            ...     for i, frame in enumerate(container.decode(video=0)):
            ...         if i > end_index:
            ...             break
            ...         if i >= start_index and i in indices:
            ...             frames.append(frame)
            ...     return np.stack([x.to_ndarray(format="rgb24") for x in frames])
            ...
            ...
            >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
            ...     '''
            ...     Sample a given number of frame indices from the video.
            ...     Args:
            ...         clip_len (`int`): Total number of frames to sample.
            ...         frame_sample_rate (`int`): Sample every n-th frame.
            ...         seg_len (`int`): Maximum allowed index of sample's last frame.
            ...     Returns:
            ...         indices (`List[int]`): List of sampled frame indices
            ...     '''
            ...     converted_len = int(clip_len * frame_sample_rate)
            ...     end_idx = np.random.randint(converted_len, seg_len)
            ...     start_idx = end_idx - converted_len
            ...     indices = np.linspace(start_idx, end_idx, num=clip_len)
            ...     indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
            ...     return indices
            ...
            ...
            >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
            >>> file_path = hf_hub_download(
            ...     repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
            ... )
            >>> container = av.open(file_path)
            ...
            >>> # sample 8 frames
            >>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
            >>> video = read_video_pyav(container, indices)
            ...
            >>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics")
            >>> model = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400")
            ...
            >>> inputs = image_processor(list(video), return_tensors="ms")
            ...
            >>> outputs = model(**inputs)
            >>> logits = outputs.logits
            ...
            >>> # model predicts one of the 400 Kinetics-400 classes
            >>> predicted_label = logits.argmax(-1).item()
            >>> print(model.config.id2label[predicted_label])
            eating spaghetti
            ```
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        outputs = self.timesformer(
            pixel_values,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        sequence_output = outputs[0][:, 0]

        logits = self.classifier(sequence_output)

        loss = None
        if labels is not None:
            if self.config.problem_type is None:
                if self.num_labels == 1:
                    self.config.problem_type = "regression"
                elif self.num_labels > 1 and (labels.dtype in [mindspore.int64, mindspore.int32]):
                    self.config.problem_type = "single_label_classification"
                else:
                    self.config.problem_type = "multi_label_classification"

            if self.config.problem_type == "regression":
                if self.num_labels == 1:
                    loss = ops.mse_loss(logits.squeeze(), labels.squeeze())
                else:
                    loss = ops.mse_loss(logits, labels)
            elif self.config.problem_type == "single_label_classification":
                loss = ops.cross_entropy(logits.view(-1, self.num_labels), labels.view(-1))
            elif self.config.problem_type == "multi_label_classification":
                loss = ops.binary_cross_entropy_with_logits(logits, labels)

        if not return_dict:
            output = (logits,) + outputs[1:]
            return ((loss,) + output) if loss is not None else output

        return ImageClassifierOutput(
            loss=loss,
            logits=logits,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
        )

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerForVideoClassification.__init__(config)

Initializes a new instance of the TimesformerForVideoClassification class.

PARAMETER DESCRIPTION
self

The instance of the class.

TYPE: object

config

An object containing configuration parameters for the model.

  • num_labels (int): The number of output labels for classification. Must be a positive integer.
  • hidden_size (int): The size of the hidden layers in the model. Must be a positive integer.

TYPE: object

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
AttributeError

If the 'config' object does not contain the required attributes.

TypeError

If the 'num_labels' or 'hidden_size' attributes in 'config' are not integers.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
def __init__(self, config):
    """
    Initializes a new instance of the TimesformerForVideoClassification class.

    Args:
        self (object): The instance of the class.
        config (object):
            An object containing configuration parameters for the model.

            - num_labels (int): The number of output labels for classification.
            Must be a positive integer.
            - hidden_size (int): The size of the hidden layers in the model.
            Must be a positive integer.

    Returns:
        None.

    Raises:
        AttributeError: If the 'config' object does not contain the required attributes.
        TypeError: If the 'num_labels' or 'hidden_size' attributes in 'config' are not integers.
    """
    super().__init__(config)

    self.num_labels = config.num_labels
    self.timesformer = TimesformerModel(config)

    # Classifier head
    self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()

    # Initialize weights and apply final processing
    self.post_init()

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerForVideoClassification.forward(pixel_values=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)

PARAMETER DESCRIPTION
labels

Labels for computing the image classification/regression loss. Indices should be in [0, ..., config.num_labels - 1]. If config.num_labels == 1 a regression loss is computed (Mean-Square loss), If config.num_labels > 1 a classification loss is computed (Cross-Entropy).

TYPE: `mindspore.Tensor` of shape `(batch_size,)`, *optional* DEFAULT: None

RETURNS DESCRIPTION
Union[Tuple, ImageClassifierOutput]

Union[Tuple, ImageClassifierOutput]

Example
>>> import av
>>> import mindspore
>>> import mindnlp
>>> import numpy as np
...
>>> from mindnlp.transformers import AutoImageProcessor, TimesformerForVideoClassification
>>> from huggingface_hub import hf_hub_download
...
>>> np.random.seed(0)
...
...
>>> def read_video_pyav(container, indices):
...     '''
...     Decode the video with PyAV decoder.
...     Args:
...         container (`av.container.input.InputContainer`): PyAV container.
...         indices (`List[int]`): List of frame indices to decode.
...     Returns:
...         result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
...     '''
...     frames = []
...     container.seek(0)
...     start_index = indices[0]
...     end_index = indices[-1]
...     for i, frame in enumerate(container.decode(video=0)):
...         if i > end_index:
...             break
...         if i >= start_index and i in indices:
...             frames.append(frame)
...     return np.stack([x.to_ndarray(format="rgb24") for x in frames])
...
...
>>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
...     '''
...     Sample a given number of frame indices from the video.
...     Args:
...         clip_len (`int`): Total number of frames to sample.
...         frame_sample_rate (`int`): Sample every n-th frame.
...         seg_len (`int`): Maximum allowed index of sample's last frame.
...     Returns:
...         indices (`List[int]`): List of sampled frame indices
...     '''
...     converted_len = int(clip_len * frame_sample_rate)
...     end_idx = np.random.randint(converted_len, seg_len)
...     start_idx = end_idx - converted_len
...     indices = np.linspace(start_idx, end_idx, num=clip_len)
...     indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
...     return indices
...
...
>>> # video clip consists of 300 frames (10 seconds at 30 FPS)
>>> file_path = hf_hub_download(
...     repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
... )
>>> container = av.open(file_path)
...
>>> # sample 8 frames
>>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container, indices)
...
>>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics")
>>> model = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400")
...
>>> inputs = image_processor(list(video), return_tensors="ms")
...
>>> outputs = model(**inputs)
>>> logits = outputs.logits
...
>>> # model predicts one of the 400 Kinetics-400 classes
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
eating spaghetti
Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
def forward(
    self,
    pixel_values: Optional[mindspore.Tensor] = None,
    labels: Optional[mindspore.Tensor] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple, ImageClassifierOutput]:
    r"""

    Args:
        labels (`mindspore.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).

    Returns:
        Union[Tuple, ImageClassifierOutput]

    Example:
        ```python
        >>> import av
        >>> import mindspore
        >>> import mindnlp
        >>> import numpy as np
        ...
        >>> from mindnlp.transformers import AutoImageProcessor, TimesformerForVideoClassification
        >>> from huggingface_hub import hf_hub_download
        ...
        >>> np.random.seed(0)
        ...
        ...
        >>> def read_video_pyav(container, indices):
        ...     '''
        ...     Decode the video with PyAV decoder.
        ...     Args:
        ...         container (`av.container.input.InputContainer`): PyAV container.
        ...         indices (`List[int]`): List of frame indices to decode.
        ...     Returns:
        ...         result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
        ...     '''
        ...     frames = []
        ...     container.seek(0)
        ...     start_index = indices[0]
        ...     end_index = indices[-1]
        ...     for i, frame in enumerate(container.decode(video=0)):
        ...         if i > end_index:
        ...             break
        ...         if i >= start_index and i in indices:
        ...             frames.append(frame)
        ...     return np.stack([x.to_ndarray(format="rgb24") for x in frames])
        ...
        ...
        >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
        ...     '''
        ...     Sample a given number of frame indices from the video.
        ...     Args:
        ...         clip_len (`int`): Total number of frames to sample.
        ...         frame_sample_rate (`int`): Sample every n-th frame.
        ...         seg_len (`int`): Maximum allowed index of sample's last frame.
        ...     Returns:
        ...         indices (`List[int]`): List of sampled frame indices
        ...     '''
        ...     converted_len = int(clip_len * frame_sample_rate)
        ...     end_idx = np.random.randint(converted_len, seg_len)
        ...     start_idx = end_idx - converted_len
        ...     indices = np.linspace(start_idx, end_idx, num=clip_len)
        ...     indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
        ...     return indices
        ...
        ...
        >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
        >>> file_path = hf_hub_download(
        ...     repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
        ... )
        >>> container = av.open(file_path)
        ...
        >>> # sample 8 frames
        >>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
        >>> video = read_video_pyav(container, indices)
        ...
        >>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics")
        >>> model = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400")
        ...
        >>> inputs = image_processor(list(video), return_tensors="ms")
        ...
        >>> outputs = model(**inputs)
        >>> logits = outputs.logits
        ...
        >>> # model predicts one of the 400 Kinetics-400 classes
        >>> predicted_label = logits.argmax(-1).item()
        >>> print(model.config.id2label[predicted_label])
        eating spaghetti
        ```
    """
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    outputs = self.timesformer(
        pixel_values,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )

    sequence_output = outputs[0][:, 0]

    logits = self.classifier(sequence_output)

    loss = None
    if labels is not None:
        if self.config.problem_type is None:
            if self.num_labels == 1:
                self.config.problem_type = "regression"
            elif self.num_labels > 1 and (labels.dtype in [mindspore.int64, mindspore.int32]):
                self.config.problem_type = "single_label_classification"
            else:
                self.config.problem_type = "multi_label_classification"

        if self.config.problem_type == "regression":
            if self.num_labels == 1:
                loss = ops.mse_loss(logits.squeeze(), labels.squeeze())
            else:
                loss = ops.mse_loss(logits, labels)
        elif self.config.problem_type == "single_label_classification":
            loss = ops.cross_entropy(logits.view(-1, self.num_labels), labels.view(-1))
        elif self.config.problem_type == "multi_label_classification":
            loss = ops.binary_cross_entropy_with_logits(logits, labels)

    if not return_dict:
        output = (logits,) + outputs[1:]
        return ((loss,) + output) if loss is not None else output

    return ImageClassifierOutput(
        loss=loss,
        logits=logits,
        hidden_states=outputs.hidden_states,
        attentions=outputs.attentions,
    )

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerIntermediate

Bases: Module

The TimesformerIntermediate class represents a component of the Timesformer model that performs intermediate computations on the input hidden states. This class inherits from the nn.Module class.

ATTRIBUTE DESCRIPTION
dense

A dense layer used for transforming the input hidden states.

TYPE: Linear

dropout

A dropout layer with a dropout probability specified in the configuration.

TYPE: Dropout

intermediate_act_fn

The activation function applied to the intermediate hidden states.

TYPE: function

METHOD DESCRIPTION
__init__

Initializes the TimesformerIntermediate instance with the provided configuration.

forward

Performs intermediate computations on the input hidden states and returns the result.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
class TimesformerIntermediate(nn.Module):

    """
    The TimesformerIntermediate class represents a component of the Timesformer model that performs intermediate
    computations on the input hidden states. This class inherits from the nn.Module class.

    Attributes:
        dense (nn.Linear): A dense layer used for transforming the input hidden states.
        dropout (nn.Dropout): A dropout layer with a dropout probability specified in the configuration.
        intermediate_act_fn (function): The activation function applied to the intermediate hidden states.

    Methods:
        __init__: Initializes the TimesformerIntermediate instance with the provided configuration.
        forward: Performs intermediate computations on the input hidden states and returns the result.
    """
    def __init__(self, config: TimesformerConfig) -> None:
        """
        Initializes a new instance of the TimesformerIntermediate class.

        Args:
            self: The instance of the TimesformerIntermediate class.
            config (TimesformerConfig): An instance of the TimesformerConfig class containing configuration parameters
                for the TimesformerIntermediate class. It specifies the hidden size, intermediate size, and hidden
                dropout probability.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not of type TimesformerConfig.
            KeyError: If the config.hidden_act is not a valid string key in the ACT2FN dictionary.
        """
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
        self.dropout = nn.Dropout(p=config.hidden_dropout_prob)

        if isinstance(config.hidden_act, str):
            self.intermediate_act_fn = ACT2FN[config.hidden_act]
        else:
            self.intermediate_act_fn = config.hidden_act

    def forward(self, hidden_states: mindspore.Tensor) -> mindspore.Tensor:
        """
        This method forwards the intermediate representation for the Timesformer model.

        Args:
            self: An instance of the TimesformerIntermediate class.
            hidden_states (mindspore.Tensor): The input hidden states to be processed.
                It should be a Tensor object containing the hidden states data required for intermediate representation
                forwardion.

        Returns:
            mindspore.Tensor: Returns a Tensor object representing the intermediate representation forwarded using
                the input hidden states data.

        Raises:
            ValueError: If the input hidden_states is not a valid mindspore.Tensor object.
            RuntimeError: If any error occurs during the intermediate representation forwardion process.
        """
        hidden_states = self.dense(hidden_states)
        hidden_states = self.intermediate_act_fn(hidden_states)
        hidden_states = self.dropout(hidden_states)

        return hidden_states

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerIntermediate.__init__(config)

Initializes a new instance of the TimesformerIntermediate class.

PARAMETER DESCRIPTION
self

The instance of the TimesformerIntermediate class.

config

An instance of the TimesformerConfig class containing configuration parameters for the TimesformerIntermediate class. It specifies the hidden size, intermediate size, and hidden dropout probability.

TYPE: TimesformerConfig

RETURNS DESCRIPTION
None

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not of type TimesformerConfig.

KeyError

If the config.hidden_act is not a valid string key in the ACT2FN dictionary.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
def __init__(self, config: TimesformerConfig) -> None:
    """
    Initializes a new instance of the TimesformerIntermediate class.

    Args:
        self: The instance of the TimesformerIntermediate class.
        config (TimesformerConfig): An instance of the TimesformerConfig class containing configuration parameters
            for the TimesformerIntermediate class. It specifies the hidden size, intermediate size, and hidden
            dropout probability.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not of type TimesformerConfig.
        KeyError: If the config.hidden_act is not a valid string key in the ACT2FN dictionary.
    """
    super().__init__()
    self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
    self.dropout = nn.Dropout(p=config.hidden_dropout_prob)

    if isinstance(config.hidden_act, str):
        self.intermediate_act_fn = ACT2FN[config.hidden_act]
    else:
        self.intermediate_act_fn = config.hidden_act

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerIntermediate.forward(hidden_states)

This method forwards the intermediate representation for the Timesformer model.

PARAMETER DESCRIPTION
self

An instance of the TimesformerIntermediate class.

hidden_states

The input hidden states to be processed. It should be a Tensor object containing the hidden states data required for intermediate representation forwardion.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

mindspore.Tensor: Returns a Tensor object representing the intermediate representation forwarded using the input hidden states data.

RAISES DESCRIPTION
ValueError

If the input hidden_states is not a valid mindspore.Tensor object.

RuntimeError

If any error occurs during the intermediate representation forwardion process.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
def forward(self, hidden_states: mindspore.Tensor) -> mindspore.Tensor:
    """
    This method forwards the intermediate representation for the Timesformer model.

    Args:
        self: An instance of the TimesformerIntermediate class.
        hidden_states (mindspore.Tensor): The input hidden states to be processed.
            It should be a Tensor object containing the hidden states data required for intermediate representation
            forwardion.

    Returns:
        mindspore.Tensor: Returns a Tensor object representing the intermediate representation forwarded using
            the input hidden states data.

    Raises:
        ValueError: If the input hidden_states is not a valid mindspore.Tensor object.
        RuntimeError: If any error occurs during the intermediate representation forwardion process.
    """
    hidden_states = self.dense(hidden_states)
    hidden_states = self.intermediate_act_fn(hidden_states)
    hidden_states = self.dropout(hidden_states)

    return hidden_states

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerLayer

Bases: Module

This class represents a Timesformer layer, which is a component of the Timesformer model. The Timesformer layer includes various operations such as attention, intermediate, and output layers. It supports different attention types, including divided space-time, space only, and joint space-time.

The TimesformerLayer class inherits from the nn.Module class.

ATTRIBUTE DESCRIPTION
config

The configuration object for the Timesformer model.

TYPE: TimesformerConfig

attention_type

The type of attention used in the layer. Valid values are 'divided_space_time', 'space_only', and 'joint_space_time'.

TYPE: str

drop_path

The dropout layer used for drop path regularization.

TYPE: Layer or Identity

attention

The attention module used in the layer.

TYPE: TimeSformerAttention

intermediate

The intermediate module used in the layer.

TYPE: TimesformerIntermediate

output

The output module used in the layer.

TYPE: TimesformerOutput

layernorm_before

The layer normalization module applied before the attention operation.

TYPE: LayerNorm

layernorm_after

The layer normalization module applied after the attention operation.

TYPE: LayerNorm

temporal_layernorm

The layer normalization module applied to temporal embeddings in case of 'divided_space_time' attention type.

TYPE: LayerNorm

temporal_attention

The attention module applied to temporal embeddings in case of 'divided_space_time' attention type.

TYPE: TimeSformerAttention

temporal_dense

The dense layer applied to temporal embeddings in case of 'divided_space_time' attention type.

TYPE: Linear

METHOD DESCRIPTION
__init__

Initializes the TimesformerLayer object with the given configuration and layer index. Sets up the various modules and attributes of the layer.

forward

Constructs the TimesformerLayer by applying the attention and intermediate operations to the given hidden states. Returns the output hidden states and optionally the attention outputs.

Note
  • The TimesformerLayer class assumes that the following modules are defined: TimeSformerDropPath, TimeSformerAttention, TimesformerIntermediate, and TimesformerOutput.
  • The forward method assumes that the following operations are defined: mindspore.Tensor.shape, ops.linspace, ops.cat, ops.mean, ops.reshape, ops.tile, and ops.permute.
RAISES DESCRIPTION
ValueError

If the provided attention type is not one of the valid options.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
class TimesformerLayer(nn.Module):

    """
    This class represents a Timesformer layer, which is a component of the Timesformer model. The Timesformer layer
    includes various operations such as attention, intermediate, and output layers. It supports different attention types,
    including divided space-time, space only, and joint space-time.

    The TimesformerLayer class inherits from the nn.Module class.

    Attributes:
        config (TimesformerConfig): The configuration object for the Timesformer model.
        attention_type (str): The type of attention used in the layer. Valid values are 'divided_space_time',
            'space_only', and 'joint_space_time'.
        drop_path (nn.Layer or nn.Identity): The dropout layer used for drop path regularization.
        attention (TimeSformerAttention): The attention module used in the layer.
        intermediate (TimesformerIntermediate): The intermediate module used in the layer.
        output (TimesformerOutput): The output module used in the layer.
        layernorm_before (nn.LayerNorm): The layer normalization module applied before the attention operation.
        layernorm_after (nn.LayerNorm): The layer normalization module applied after the attention operation.
        temporal_layernorm (nn.LayerNorm): The layer normalization module applied to temporal embeddings in case of
            'divided_space_time' attention type.
        temporal_attention (TimeSformerAttention): The attention module applied to temporal embeddings in case of
            'divided_space_time' attention type.
        temporal_dense (nn.Linear): The dense layer applied to temporal embeddings in case of 'divided_space_time'
            attention type.

    Methods:
        __init__:
            Initializes the TimesformerLayer object with the given configuration and layer index. Sets up the various
            modules and attributes of the layer.

        forward:
            Constructs the TimesformerLayer by applying the attention and intermediate operations to the given hidden
            states. Returns the output hidden states and optionally the attention outputs.

    Note:
        - The TimesformerLayer class assumes that the following modules are defined: TimeSformerDropPath,
        TimeSformerAttention, TimesformerIntermediate, and TimesformerOutput.
        - The forward method assumes that the following operations are defined: mindspore.Tensor.shape,
        ops.linspace, ops.cat, ops.mean, ops.reshape, ops.tile, and ops.permute.

    Raises:
        ValueError: If the provided attention type is not one of the valid options.
    """
    def __init__(self, config: TimesformerConfig, layer_index: int) -> None:
        """
        Initializes a TimesformerLayer instance.

        Args:
            self: The TimesformerLayer instance.
            config (TimesformerConfig): The configuration object for the Timesformer model.
            layer_index (int): The index of the layer.

        Returns:
            None.

        Raises:
            ValueError: If the attention_type in the config is not one of
                ['divided_space_time', 'space_only', 'joint_space_time'].
        """
        super().__init__()

        attention_type = config.attention_type

        drop_path_rates = [
            x.item() for x in ops.linspace(0, config.drop_path_rate, config.num_hidden_layers)
        ]  # stochastic depth decay rule
        drop_path_rate = drop_path_rates[layer_index]

        self.drop_path = TimeSformerDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
        self.attention = TimeSformerAttention(config)
        self.intermediate = TimesformerIntermediate(config)
        self.output = TimesformerOutput(config)
        self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
        self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)

        self.config = config
        self.attention_type = attention_type
        if attention_type not in ["divided_space_time", "space_only", "joint_space_time"]:
            raise ValueError("Unknown attention type: {}".format(attention_type))

        # Temporal Attention Parameters
        if self.attention_type == "divided_space_time":
            self.temporal_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
            self.temporal_attention = TimeSformerAttention(config)
            self.temporal_dense = nn.Linear(config.hidden_size, config.hidden_size)

    def forward(self, hidden_states: mindspore.Tensor, output_attentions: bool = False):
        """
        Construct a Timesformer layer.

        Args:
            self (TimesformerLayer): The TimesformerLayer instance.
            hidden_states (mindspore.Tensor): The input hidden states tensor of shape
                (batch_size, sequence_length, hidden_size).
            output_attentions (bool, optional): Whether to output attentions. Defaults to False.

        Returns:
            None.

        Raises:
            ValueError: If the attention_type is not one of ['space_only', 'joint_space_time', 'divided_space_time'].
            ValueError: If the shape of the hidden_states tensor is not as expected.
            ValueError: If the shape of the temporal_embedding tensor is not as expected.
            ValueError: If the shape of the spatial_embedding tensor is not as expected.
            ValueError: If the shape of the cls_token tensor is not as expected.
            ValueError: If the shape of the residual_spatial tensor is not as expected.
            ValueError: If the shape of the hidden_states tensor after operations is not as expected.
            ValueError: If the shape of the layer_output tensor is not as expected.
            ValueError: If the shape of the outputs tuple is not as expected.
        """
        num_frames = self.config.num_frames
        num_patch_width = self.config.image_size // self.config.patch_size
        batch_size = hidden_states.shape[0]
        num_spatial_tokens = (hidden_states.shape[1] - 1) // num_frames
        num_patch_height = num_spatial_tokens // num_patch_width

        if self.attention_type in ["space_only", "joint_space_time"]:
            self_attention_outputs = self.attention(
                self.layernorm_before(hidden_states), output_attentions=output_attentions
            )
            attention_output = self_attention_outputs[0]
            outputs = self_attention_outputs[1:]  # add self attentions if we output attention weights

            hidden_states = hidden_states + self.drop_path(attention_output)

            layer_output = self.layernorm_after(hidden_states)
            layer_output = self.intermediate(layer_output)
            layer_output = self.output(layer_output)
            layer_output = hidden_states + self.drop_path(layer_output)

            outputs = (layer_output,) + outputs

            return outputs

        elif self.attention_type == "divided_space_time":
            # Temporal
            temporal_embedding = hidden_states[:, 1:, :]
            temporal_embedding = temporal_embedding.reshape(
                batch_size, num_patch_height, num_patch_width, num_frames, temporal_embedding.shape[2]
            ).reshape(batch_size * num_patch_height * num_patch_width, num_frames, temporal_embedding.shape[2])

            temporal_attention_outputs = self.temporal_attention(
                self.temporal_layernorm(temporal_embedding),
            )
            attention_output = temporal_attention_outputs[0]

            residual_temporal = self.drop_path(attention_output)

            residual_temporal = residual_temporal.reshape(
                batch_size, num_patch_height, num_patch_width, num_frames, residual_temporal.shape[2]
            ).reshape(batch_size, num_patch_height * num_patch_width * num_frames, residual_temporal.shape[2])
            residual_temporal = self.temporal_dense(residual_temporal)
            temporal_embedding = hidden_states[:, 1:, :] + residual_temporal

            # Spatial
            init_cls_token = hidden_states[:, 0, :].unsqueeze(1)
            cls_token = init_cls_token.tile((1, num_frames, 1))
            cls_token = cls_token.reshape(batch_size * num_frames, 1, cls_token.shape[2])
            spatial_embedding = temporal_embedding
            spatial_embedding = (
                spatial_embedding.reshape(
                    batch_size, num_patch_height, num_patch_width, num_frames, spatial_embedding.shape[2]
                )
                .permute(0, 3, 1, 2, 4)
                .reshape(batch_size * num_frames, num_patch_height * num_patch_width, spatial_embedding.shape[2])
            )
            spatial_embedding = ops.cat((cls_token, spatial_embedding), 1)

            spatial_attention_outputs = self.attention(
                self.layernorm_before(spatial_embedding), output_attentions=output_attentions
            )
            attention_output = spatial_attention_outputs[0]
            outputs = spatial_attention_outputs[1:]  # add self attentions if we output attention weights

            residual_spatial = self.drop_path(attention_output)

            # Taking care of CLS token
            cls_token = residual_spatial[:, 0, :]
            cls_token = cls_token.reshape(batch_size, num_frames, cls_token.shape[1])
            cls_token = ops.mean(cls_token, 1, True)  # averaging for every frame
            residual_spatial = residual_spatial[:, 1:, :]
            residual_spatial = (
                residual_spatial.reshape(
                    batch_size, num_frames, num_patch_height, num_patch_width, residual_spatial.shape[2]
                )
                .permute(0, 2, 3, 1, 4)
                .reshape(batch_size, num_patch_height * num_patch_width * num_frames, residual_spatial.shape[2])
            )
            residual = residual_spatial
            hidden_states = temporal_embedding

            # Mlp
            hidden_states = ops.cat((init_cls_token, hidden_states), 1) + ops.cat((cls_token, residual), 1)
            layer_output = self.layernorm_after(hidden_states)
            layer_output = self.intermediate(layer_output)
            layer_output = self.output(layer_output)
            layer_output = hidden_states + self.drop_path(layer_output)

            outputs = (layer_output,) + outputs

            return outputs

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerLayer.__init__(config, layer_index)

Initializes a TimesformerLayer instance.

PARAMETER DESCRIPTION
self

The TimesformerLayer instance.

config

The configuration object for the Timesformer model.

TYPE: TimesformerConfig

layer_index

The index of the layer.

TYPE: int

RETURNS DESCRIPTION
None

None.

RAISES DESCRIPTION
ValueError

If the attention_type in the config is not one of ['divided_space_time', 'space_only', 'joint_space_time'].

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
def __init__(self, config: TimesformerConfig, layer_index: int) -> None:
    """
    Initializes a TimesformerLayer instance.

    Args:
        self: The TimesformerLayer instance.
        config (TimesformerConfig): The configuration object for the Timesformer model.
        layer_index (int): The index of the layer.

    Returns:
        None.

    Raises:
        ValueError: If the attention_type in the config is not one of
            ['divided_space_time', 'space_only', 'joint_space_time'].
    """
    super().__init__()

    attention_type = config.attention_type

    drop_path_rates = [
        x.item() for x in ops.linspace(0, config.drop_path_rate, config.num_hidden_layers)
    ]  # stochastic depth decay rule
    drop_path_rate = drop_path_rates[layer_index]

    self.drop_path = TimeSformerDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
    self.attention = TimeSformerAttention(config)
    self.intermediate = TimesformerIntermediate(config)
    self.output = TimesformerOutput(config)
    self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
    self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)

    self.config = config
    self.attention_type = attention_type
    if attention_type not in ["divided_space_time", "space_only", "joint_space_time"]:
        raise ValueError("Unknown attention type: {}".format(attention_type))

    # Temporal Attention Parameters
    if self.attention_type == "divided_space_time":
        self.temporal_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
        self.temporal_attention = TimeSformerAttention(config)
        self.temporal_dense = nn.Linear(config.hidden_size, config.hidden_size)

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerLayer.forward(hidden_states, output_attentions=False)

Construct a Timesformer layer.

PARAMETER DESCRIPTION
self

The TimesformerLayer instance.

TYPE: TimesformerLayer

hidden_states

The input hidden states tensor of shape (batch_size, sequence_length, hidden_size).

TYPE: Tensor

output_attentions

Whether to output attentions. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If the attention_type is not one of ['space_only', 'joint_space_time', 'divided_space_time'].

ValueError

If the shape of the hidden_states tensor is not as expected.

ValueError

If the shape of the temporal_embedding tensor is not as expected.

ValueError

If the shape of the spatial_embedding tensor is not as expected.

ValueError

If the shape of the cls_token tensor is not as expected.

ValueError

If the shape of the residual_spatial tensor is not as expected.

ValueError

If the shape of the hidden_states tensor after operations is not as expected.

ValueError

If the shape of the layer_output tensor is not as expected.

ValueError

If the shape of the outputs tuple is not as expected.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
def forward(self, hidden_states: mindspore.Tensor, output_attentions: bool = False):
    """
    Construct a Timesformer layer.

    Args:
        self (TimesformerLayer): The TimesformerLayer instance.
        hidden_states (mindspore.Tensor): The input hidden states tensor of shape
            (batch_size, sequence_length, hidden_size).
        output_attentions (bool, optional): Whether to output attentions. Defaults to False.

    Returns:
        None.

    Raises:
        ValueError: If the attention_type is not one of ['space_only', 'joint_space_time', 'divided_space_time'].
        ValueError: If the shape of the hidden_states tensor is not as expected.
        ValueError: If the shape of the temporal_embedding tensor is not as expected.
        ValueError: If the shape of the spatial_embedding tensor is not as expected.
        ValueError: If the shape of the cls_token tensor is not as expected.
        ValueError: If the shape of the residual_spatial tensor is not as expected.
        ValueError: If the shape of the hidden_states tensor after operations is not as expected.
        ValueError: If the shape of the layer_output tensor is not as expected.
        ValueError: If the shape of the outputs tuple is not as expected.
    """
    num_frames = self.config.num_frames
    num_patch_width = self.config.image_size // self.config.patch_size
    batch_size = hidden_states.shape[0]
    num_spatial_tokens = (hidden_states.shape[1] - 1) // num_frames
    num_patch_height = num_spatial_tokens // num_patch_width

    if self.attention_type in ["space_only", "joint_space_time"]:
        self_attention_outputs = self.attention(
            self.layernorm_before(hidden_states), output_attentions=output_attentions
        )
        attention_output = self_attention_outputs[0]
        outputs = self_attention_outputs[1:]  # add self attentions if we output attention weights

        hidden_states = hidden_states + self.drop_path(attention_output)

        layer_output = self.layernorm_after(hidden_states)
        layer_output = self.intermediate(layer_output)
        layer_output = self.output(layer_output)
        layer_output = hidden_states + self.drop_path(layer_output)

        outputs = (layer_output,) + outputs

        return outputs

    elif self.attention_type == "divided_space_time":
        # Temporal
        temporal_embedding = hidden_states[:, 1:, :]
        temporal_embedding = temporal_embedding.reshape(
            batch_size, num_patch_height, num_patch_width, num_frames, temporal_embedding.shape[2]
        ).reshape(batch_size * num_patch_height * num_patch_width, num_frames, temporal_embedding.shape[2])

        temporal_attention_outputs = self.temporal_attention(
            self.temporal_layernorm(temporal_embedding),
        )
        attention_output = temporal_attention_outputs[0]

        residual_temporal = self.drop_path(attention_output)

        residual_temporal = residual_temporal.reshape(
            batch_size, num_patch_height, num_patch_width, num_frames, residual_temporal.shape[2]
        ).reshape(batch_size, num_patch_height * num_patch_width * num_frames, residual_temporal.shape[2])
        residual_temporal = self.temporal_dense(residual_temporal)
        temporal_embedding = hidden_states[:, 1:, :] + residual_temporal

        # Spatial
        init_cls_token = hidden_states[:, 0, :].unsqueeze(1)
        cls_token = init_cls_token.tile((1, num_frames, 1))
        cls_token = cls_token.reshape(batch_size * num_frames, 1, cls_token.shape[2])
        spatial_embedding = temporal_embedding
        spatial_embedding = (
            spatial_embedding.reshape(
                batch_size, num_patch_height, num_patch_width, num_frames, spatial_embedding.shape[2]
            )
            .permute(0, 3, 1, 2, 4)
            .reshape(batch_size * num_frames, num_patch_height * num_patch_width, spatial_embedding.shape[2])
        )
        spatial_embedding = ops.cat((cls_token, spatial_embedding), 1)

        spatial_attention_outputs = self.attention(
            self.layernorm_before(spatial_embedding), output_attentions=output_attentions
        )
        attention_output = spatial_attention_outputs[0]
        outputs = spatial_attention_outputs[1:]  # add self attentions if we output attention weights

        residual_spatial = self.drop_path(attention_output)

        # Taking care of CLS token
        cls_token = residual_spatial[:, 0, :]
        cls_token = cls_token.reshape(batch_size, num_frames, cls_token.shape[1])
        cls_token = ops.mean(cls_token, 1, True)  # averaging for every frame
        residual_spatial = residual_spatial[:, 1:, :]
        residual_spatial = (
            residual_spatial.reshape(
                batch_size, num_frames, num_patch_height, num_patch_width, residual_spatial.shape[2]
            )
            .permute(0, 2, 3, 1, 4)
            .reshape(batch_size, num_patch_height * num_patch_width * num_frames, residual_spatial.shape[2])
        )
        residual = residual_spatial
        hidden_states = temporal_embedding

        # Mlp
        hidden_states = ops.cat((init_cls_token, hidden_states), 1) + ops.cat((cls_token, residual), 1)
        layer_output = self.layernorm_after(hidden_states)
        layer_output = self.intermediate(layer_output)
        layer_output = self.output(layer_output)
        layer_output = hidden_states + self.drop_path(layer_output)

        outputs = (layer_output,) + outputs

        return outputs

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerModel

Bases: TimesformerPreTrainedModel

Represents a Timesformer model.

This class inherits from TimesformerPreTrainedModel and implements the Timesformer model architecture for processing video data. It includes methods for initializing the model, getting input embeddings, pruning heads, and forwarding the model output.

The init method initializes the TimesformerModel with the provided configuration. The get_input_embeddings method returns the patch embeddings from the model's embeddings. The _prune_heads method prunes heads of the model based on the provided heads_to_prune dictionary. The forward method processes the input pixel values and returns the model output, with options to include attentions and hidden states in the returned dictionary.

The class also contains additional methods and attributes inherited from the base class TimesformerPreTrainedModel.

Example usage and explanations are provided within the docstring for reference and clarity.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
class TimesformerModel(TimesformerPreTrainedModel):

    """
    Represents a Timesformer model.

    This class inherits from TimesformerPreTrainedModel and implements the Timesformer model architecture for
    processing video data. It includes methods for initializing the model, getting input embeddings, pruning heads,
    and forwarding the model output.

    The __init__ method initializes the TimesformerModel with the provided configuration. The get_input_embeddings
    method returns the patch embeddings from the model's embeddings. The _prune_heads method prunes heads of the model
    based on the provided heads_to_prune dictionary. The forward method processes the input pixel values and returns
    the model output, with options to include attentions and hidden states in the returned dictionary.

    The class also contains additional methods and attributes inherited from the base class TimesformerPreTrainedModel.

    Example usage and explanations are provided within the docstring for reference and clarity.

    """
    def __init__(self, config):
        """
        Initializes a new instance of the TimesformerModel class.

        Args:
            self: An instance of the TimesformerModel class.
            config (dict): A dictionary containing configuration parameters for the model.
                This dictionary should include the necessary settings for configuring the model.
                Example fields include 'hidden_size', 'layer_norm_eps', etc.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not provided or is not of type dict.
            AttributeError: If any required field is missing in the config dictionary.
            ValueError: If the provided configuration settings are invalid or inconsistent.
            RuntimeError: If there are issues during the initialization process of the model components.
        """
        super().__init__(config)
        self.config = config

        self.embeddings = TimesformerEmbeddings(config)
        self.encoder = TimesformerEncoder(config)

        self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)

        # Initialize weights and apply final processing
        self.post_init()

    def get_input_embeddings(self):
        """
        Retrieve the input embeddings for the TimesformerModel.

        Args:
            self: TimesformerModel
                The instance of the TimesformerModel class.

        Returns:
            None.

        Raises:
            None
        """
        return self.embeddings.patch_embeddings

    def _prune_heads(self, heads_to_prune):
        """
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        """
        for layer, heads in heads_to_prune.items():
            self.encoder.layer[layer].attention.prune_heads(heads)

    def forward(
        self,
        pixel_values: mindspore.Tensor,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple[mindspore.Tensor], BaseModelOutput]:
        r"""

        Returns:
            Union[Tuple[mindspore.Tensor], BaseModelOutput]:

        Example:
            ```python
            >>> import av
            >>> import numpy as np
            ...
            >>> from transformers import AutoImageProcessor, TimesformerModel
            >>> from huggingface_hub import hf_hub_download
            ...
            >>> np.random.seed(0)
            ...
            >>> def read_video_pyav(container, indices):
            ...     '''
            ...     Decode the video with PyAV decoder.
            ...     Args:
            ...         container (`av.container.input.InputContainer`): PyAV container.
            ...         indices (`List[int]`): List of frame indices to decode.
            ...     Returns:
            ...         result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
            ...     '''
            ...     frames = []
            ...     container.seek(0)
            ...     start_index = indices[0]
            ...     end_index = indices[-1]
            ...     for i, frame in enumerate(container.decode(video=0)):
            ...         if i > end_index:
            ...             break
            ...         if i >= start_index and i in indices:
            ...             frames.append(frame)
            ...     return np.stack([x.to_ndarray(format="rgb24") for x in frames])
            ...
            ...
            >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
            ...     '''
            ...     Sample a given number of frame indices from the video.
            ...     Args:
            ...         clip_len (`int`): Total number of frames to sample.
            ...         frame_sample_rate (`int`): Sample every n-th frame.
            ...         seg_len (`int`): Maximum allowed index of sample's last frame.
            ...     Returns:
            ...         indices (`List[int]`): List of sampled frame indices
            ...     '''
            ...     converted_len = int(clip_len * frame_sample_rate)
            ...     end_idx = np.random.randint(converted_len, seg_len)
            ...     start_idx = end_idx - converted_len
            ...     indices = np.linspace(start_idx, end_idx, num=clip_len)
            ...     indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
            ...     return indices
            ...
            ...
            >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
            >>> file_path = hf_hub_download(
            ...     repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
            ... )
            >>> container = av.open(file_path)
            ...
            >>> # sample 8 frames
            >>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=4, seg_len=container.streams.video[0].frames)
            >>> video = read_video_pyav(container, indices)
            ...
            >>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base")
            >>> model = TimesformerModel.from_pretrained("facebook/timesformer-base-finetuned-k400")
            ...
            >>> # prepare video for the model
            >>> inputs = image_processor(list(video), return_tensors="pt")
            ...
            >>> # forward pass
            >>> outputs = model(**inputs)
            >>> last_hidden_states = outputs.last_hidden_state
            >>> list(last_hidden_states.shape)
            [1, 1569, 768]
            ```
        """
        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
        output_hidden_states = (
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        embedding_output = self.embeddings(pixel_values)

        encoder_outputs = self.encoder(
            embedding_output,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
        sequence_output = encoder_outputs[0]
        if self.layernorm is not None:
            sequence_output = self.layernorm(sequence_output)

        if not return_dict:
            return (sequence_output,) + encoder_outputs[1:]

        return BaseModelOutput(
            last_hidden_state=sequence_output,
            hidden_states=encoder_outputs.hidden_states,
            attentions=encoder_outputs.attentions,
        )

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerModel.__init__(config)

Initializes a new instance of the TimesformerModel class.

PARAMETER DESCRIPTION
self

An instance of the TimesformerModel class.

config

A dictionary containing configuration parameters for the model. This dictionary should include the necessary settings for configuring the model. Example fields include 'hidden_size', 'layer_norm_eps', etc.

TYPE: dict

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not provided or is not of type dict.

AttributeError

If any required field is missing in the config dictionary.

ValueError

If the provided configuration settings are invalid or inconsistent.

RuntimeError

If there are issues during the initialization process of the model components.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
def __init__(self, config):
    """
    Initializes a new instance of the TimesformerModel class.

    Args:
        self: An instance of the TimesformerModel class.
        config (dict): A dictionary containing configuration parameters for the model.
            This dictionary should include the necessary settings for configuring the model.
            Example fields include 'hidden_size', 'layer_norm_eps', etc.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not provided or is not of type dict.
        AttributeError: If any required field is missing in the config dictionary.
        ValueError: If the provided configuration settings are invalid or inconsistent.
        RuntimeError: If there are issues during the initialization process of the model components.
    """
    super().__init__(config)
    self.config = config

    self.embeddings = TimesformerEmbeddings(config)
    self.encoder = TimesformerEncoder(config)

    self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)

    # Initialize weights and apply final processing
    self.post_init()

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerModel.forward(pixel_values, output_attentions=None, output_hidden_states=None, return_dict=None)

RETURNS DESCRIPTION
Union[Tuple[Tensor], BaseModelOutput]

Union[Tuple[mindspore.Tensor], BaseModelOutput]:

Example
>>> import av
>>> import numpy as np
...
>>> from transformers import AutoImageProcessor, TimesformerModel
>>> from huggingface_hub import hf_hub_download
...
>>> np.random.seed(0)
...
>>> def read_video_pyav(container, indices):
...     '''
...     Decode the video with PyAV decoder.
...     Args:
...         container (`av.container.input.InputContainer`): PyAV container.
...         indices (`List[int]`): List of frame indices to decode.
...     Returns:
...         result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
...     '''
...     frames = []
...     container.seek(0)
...     start_index = indices[0]
...     end_index = indices[-1]
...     for i, frame in enumerate(container.decode(video=0)):
...         if i > end_index:
...             break
...         if i >= start_index and i in indices:
...             frames.append(frame)
...     return np.stack([x.to_ndarray(format="rgb24") for x in frames])
...
...
>>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
...     '''
...     Sample a given number of frame indices from the video.
...     Args:
...         clip_len (`int`): Total number of frames to sample.
...         frame_sample_rate (`int`): Sample every n-th frame.
...         seg_len (`int`): Maximum allowed index of sample's last frame.
...     Returns:
...         indices (`List[int]`): List of sampled frame indices
...     '''
...     converted_len = int(clip_len * frame_sample_rate)
...     end_idx = np.random.randint(converted_len, seg_len)
...     start_idx = end_idx - converted_len
...     indices = np.linspace(start_idx, end_idx, num=clip_len)
...     indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
...     return indices
...
...
>>> # video clip consists of 300 frames (10 seconds at 30 FPS)
>>> file_path = hf_hub_download(
...     repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
... )
>>> container = av.open(file_path)
...
>>> # sample 8 frames
>>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=4, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container, indices)
...
>>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base")
>>> model = TimesformerModel.from_pretrained("facebook/timesformer-base-finetuned-k400")
...
>>> # prepare video for the model
>>> inputs = image_processor(list(video), return_tensors="pt")
...
>>> # forward pass
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 1569, 768]
Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
def forward(
    self,
    pixel_values: mindspore.Tensor,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple[mindspore.Tensor], BaseModelOutput]:
    r"""

    Returns:
        Union[Tuple[mindspore.Tensor], BaseModelOutput]:

    Example:
        ```python
        >>> import av
        >>> import numpy as np
        ...
        >>> from transformers import AutoImageProcessor, TimesformerModel
        >>> from huggingface_hub import hf_hub_download
        ...
        >>> np.random.seed(0)
        ...
        >>> def read_video_pyav(container, indices):
        ...     '''
        ...     Decode the video with PyAV decoder.
        ...     Args:
        ...         container (`av.container.input.InputContainer`): PyAV container.
        ...         indices (`List[int]`): List of frame indices to decode.
        ...     Returns:
        ...         result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
        ...     '''
        ...     frames = []
        ...     container.seek(0)
        ...     start_index = indices[0]
        ...     end_index = indices[-1]
        ...     for i, frame in enumerate(container.decode(video=0)):
        ...         if i > end_index:
        ...             break
        ...         if i >= start_index and i in indices:
        ...             frames.append(frame)
        ...     return np.stack([x.to_ndarray(format="rgb24") for x in frames])
        ...
        ...
        >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
        ...     '''
        ...     Sample a given number of frame indices from the video.
        ...     Args:
        ...         clip_len (`int`): Total number of frames to sample.
        ...         frame_sample_rate (`int`): Sample every n-th frame.
        ...         seg_len (`int`): Maximum allowed index of sample's last frame.
        ...     Returns:
        ...         indices (`List[int]`): List of sampled frame indices
        ...     '''
        ...     converted_len = int(clip_len * frame_sample_rate)
        ...     end_idx = np.random.randint(converted_len, seg_len)
        ...     start_idx = end_idx - converted_len
        ...     indices = np.linspace(start_idx, end_idx, num=clip_len)
        ...     indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
        ...     return indices
        ...
        ...
        >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
        >>> file_path = hf_hub_download(
        ...     repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
        ... )
        >>> container = av.open(file_path)
        ...
        >>> # sample 8 frames
        >>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=4, seg_len=container.streams.video[0].frames)
        >>> video = read_video_pyav(container, indices)
        ...
        >>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base")
        >>> model = TimesformerModel.from_pretrained("facebook/timesformer-base-finetuned-k400")
        ...
        >>> # prepare video for the model
        >>> inputs = image_processor(list(video), return_tensors="pt")
        ...
        >>> # forward pass
        >>> outputs = model(**inputs)
        >>> last_hidden_states = outputs.last_hidden_state
        >>> list(last_hidden_states.shape)
        [1, 1569, 768]
        ```
    """
    output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
    output_hidden_states = (
        output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    )
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    embedding_output = self.embeddings(pixel_values)

    encoder_outputs = self.encoder(
        embedding_output,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )
    sequence_output = encoder_outputs[0]
    if self.layernorm is not None:
        sequence_output = self.layernorm(sequence_output)

    if not return_dict:
        return (sequence_output,) + encoder_outputs[1:]

    return BaseModelOutput(
        last_hidden_state=sequence_output,
        hidden_states=encoder_outputs.hidden_states,
        attentions=encoder_outputs.attentions,
    )

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerModel.get_input_embeddings()

Retrieve the input embeddings for the TimesformerModel.

PARAMETER DESCRIPTION
self

TimesformerModel The instance of the TimesformerModel class.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
def get_input_embeddings(self):
    """
    Retrieve the input embeddings for the TimesformerModel.

    Args:
        self: TimesformerModel
            The instance of the TimesformerModel class.

    Returns:
        None.

    Raises:
        None
    """
    return self.embeddings.patch_embeddings

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerOutput

Bases: Module

TimesformerOutput represents the output of the Timesformer model, containing methods for processing hidden states.

This class inherits from nn.Module and provides functionality for processing hidden states through dense and dropout layers.

ATTRIBUTE DESCRIPTION
dense

A dense layer used for transforming hidden states.

TYPE: Linear

dropout

A dropout layer used for regularization.

TYPE: Dropout

METHOD DESCRIPTION
__init__

Initializes the TimesformerOutput object with the provided configuration.

forward

Applies dense and dropout layers to the input hidden states.

Example
>>> config = TimesformerConfig(intermediate_size=1024, hidden_size=512, hidden_dropout_prob=0.1)
>>> output = TimesformerOutput(config)
>>> processed_states = output.forward(hidden_states)
Note

The TimesformerOutput class is designed to work in conjunction with the Timesformer model for processing hidden states efficiently.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
class TimesformerOutput(nn.Module):

    """
    TimesformerOutput represents the output of the Timesformer model, containing methods for processing hidden states.

    This class inherits from nn.Module and provides functionality for processing hidden states through dense and dropout
    layers.

    Attributes:
        dense (nn.Linear): A dense layer used for transforming hidden states.
        dropout (nn.Dropout): A dropout layer used for regularization.

    Methods:
        __init__: Initializes the TimesformerOutput object with the provided configuration.
        forward: Applies dense and dropout layers to the input hidden states.

    Example:
        ```python
        >>> config = TimesformerConfig(intermediate_size=1024, hidden_size=512, hidden_dropout_prob=0.1)
        >>> output = TimesformerOutput(config)
        >>> processed_states = output.forward(hidden_states)
        ```

    Note:
        The TimesformerOutput class is designed to work in conjunction with the Timesformer model for processing hidden
        states efficiently.
    """
    def __init__(self, config: TimesformerConfig) -> None:
        """
        Initializes a new instance of TimesformerOutput.

        Args:
            self: The instance of the class.
            config (TimesformerConfig): The configuration object for the Timesformer model,
                specifying the model's parameters.

                - Type: TimesformerConfig
                - Purpose: Specifies the configuration settings for the Timesformer model.
                - Restrictions: Must be an instance of TimesformerConfig.

        Returns:
            None.

        Raises:
            None
        """
        super().__init__()
        self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
        self.dropout = nn.Dropout(p=config.hidden_dropout_prob)

    def forward(self, hidden_states: mindspore.Tensor) -> mindspore.Tensor:
        """
        This method 'forward' is defined within the class 'TimesformerOutput' and is used to process the input
        'hidden_states' through a series of operations and return the resulting tensor.

        Args:
            self (TimesformerOutput): The instance of the TimesformerOutput class.
            hidden_states (mindspore.Tensor): The input tensor containing the hidden states.
                It is expected to be of type mindspore.Tensor.

        Returns:
            mindspore.Tensor: The processed tensor after applying the dense and dropout operations.

        Raises:
            None: This method does not explicitly raise any exceptions. However, it is important to note that the
                operations performed within this method may raise exceptions related to tensor manipulation in
                the mindspore library.
        """
        hidden_states = self.dense(hidden_states)
        hidden_states = self.dropout(hidden_states)

        return hidden_states

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerOutput.__init__(config)

Initializes a new instance of TimesformerOutput.

PARAMETER DESCRIPTION
self

The instance of the class.

config

The configuration object for the Timesformer model, specifying the model's parameters.

  • Type: TimesformerConfig
  • Purpose: Specifies the configuration settings for the Timesformer model.
  • Restrictions: Must be an instance of TimesformerConfig.

TYPE: TimesformerConfig

RETURNS DESCRIPTION
None

None.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
def __init__(self, config: TimesformerConfig) -> None:
    """
    Initializes a new instance of TimesformerOutput.

    Args:
        self: The instance of the class.
        config (TimesformerConfig): The configuration object for the Timesformer model,
            specifying the model's parameters.

            - Type: TimesformerConfig
            - Purpose: Specifies the configuration settings for the Timesformer model.
            - Restrictions: Must be an instance of TimesformerConfig.

    Returns:
        None.

    Raises:
        None
    """
    super().__init__()
    self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
    self.dropout = nn.Dropout(p=config.hidden_dropout_prob)

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerOutput.forward(hidden_states)

This method 'forward' is defined within the class 'TimesformerOutput' and is used to process the input 'hidden_states' through a series of operations and return the resulting tensor.

PARAMETER DESCRIPTION
self

The instance of the TimesformerOutput class.

TYPE: TimesformerOutput

hidden_states

The input tensor containing the hidden states. It is expected to be of type mindspore.Tensor.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

mindspore.Tensor: The processed tensor after applying the dense and dropout operations.

RAISES DESCRIPTION
None

This method does not explicitly raise any exceptions. However, it is important to note that the operations performed within this method may raise exceptions related to tensor manipulation in the mindspore library.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
def forward(self, hidden_states: mindspore.Tensor) -> mindspore.Tensor:
    """
    This method 'forward' is defined within the class 'TimesformerOutput' and is used to process the input
    'hidden_states' through a series of operations and return the resulting tensor.

    Args:
        self (TimesformerOutput): The instance of the TimesformerOutput class.
        hidden_states (mindspore.Tensor): The input tensor containing the hidden states.
            It is expected to be of type mindspore.Tensor.

    Returns:
        mindspore.Tensor: The processed tensor after applying the dense and dropout operations.

    Raises:
        None: This method does not explicitly raise any exceptions. However, it is important to note that the
            operations performed within this method may raise exceptions related to tensor manipulation in
            the mindspore library.
    """
    hidden_states = self.dense(hidden_states)
    hidden_states = self.dropout(hidden_states)

    return hidden_states

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerPatchEmbeddings

Bases: Module

Image to Patch Embedding

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
class TimesformerPatchEmbeddings(nn.Module):
    """Image to Patch Embedding"""
    def __init__(self, config):
        """
        Initializes an instance of the TimesformerPatchEmbeddings class.

        Args:
            self: The object instance.
            config:
                An object containing configuration parameters for TimesformerPatchEmbeddings.

                - image_size (int or tuple): The size of the input image. If an int is provided,
                it is assumed to be a square image.
                - patch_size (int or tuple): The size of each patch. If an int is provided,
                it is assumed to be a square patch.
                - num_channels (int): The number of input channels in the image.
                - hidden_size (int): The size of the hidden projection space.

        Returns:
            None

        Raises:
            None

        """
        super().__init__()

        image_size = config.image_size
        patch_size = config.patch_size

        image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
        patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)

        num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
        self.image_size = image_size
        self.patch_size = patch_size
        self.num_patches = num_patches

        self.projection = nn.Conv2d(config.num_channels, config.hidden_size, kernel_size=patch_size,
                                    stride=patch_size, pad_mode='valid', bias=True)

    def forward(self, pixel_values):
        '''
        forward method in TimesformerPatchEmbeddings class.

        This method forwards patch embeddings from the input pixel_values.

        Args:
            self (TimesformerPatchEmbeddings): The instance of the TimesformerPatchEmbeddings class.
            pixel_values (torch.Tensor): A 5-dimensional tensor representing the pixel values of the input images,
                with dimensions (batch_size, num_frames, num_channels, height, width).

        Returns:
            tuple:
                A tuple containing the following values:

                - embeddings (torch.Tensor): A 3-dimensional tensor representing the forwarded embeddings,
                with dimensions (batch_size * num_frames, patch_width, num_channels).
                - num_frames (int): The number of frames in the input pixel_values.
                - patch_width (int): The width of the patches in the forwarded embeddings.

        Raises:
            None
        '''
        batch_size, num_frames, num_channels, height, width = pixel_values.shape
        pixel_values = pixel_values.reshape(batch_size * num_frames, num_channels, height, width)

        embeddings = self.projection(pixel_values)
        patch_width = embeddings.shape[-1]
        embeddings = embeddings.flatten(start_dim=2).swapaxes(1, 2)
        return embeddings, num_frames, patch_width

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerPatchEmbeddings.__init__(config)

Initializes an instance of the TimesformerPatchEmbeddings class.

PARAMETER DESCRIPTION
self

The object instance.

config

An object containing configuration parameters for TimesformerPatchEmbeddings.

  • image_size (int or tuple): The size of the input image. If an int is provided, it is assumed to be a square image.
  • patch_size (int or tuple): The size of each patch. If an int is provided, it is assumed to be a square patch.
  • num_channels (int): The number of input channels in the image.
  • hidden_size (int): The size of the hidden projection space.

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def __init__(self, config):
    """
    Initializes an instance of the TimesformerPatchEmbeddings class.

    Args:
        self: The object instance.
        config:
            An object containing configuration parameters for TimesformerPatchEmbeddings.

            - image_size (int or tuple): The size of the input image. If an int is provided,
            it is assumed to be a square image.
            - patch_size (int or tuple): The size of each patch. If an int is provided,
            it is assumed to be a square patch.
            - num_channels (int): The number of input channels in the image.
            - hidden_size (int): The size of the hidden projection space.

    Returns:
        None

    Raises:
        None

    """
    super().__init__()

    image_size = config.image_size
    patch_size = config.patch_size

    image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
    patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)

    num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
    self.image_size = image_size
    self.patch_size = patch_size
    self.num_patches = num_patches

    self.projection = nn.Conv2d(config.num_channels, config.hidden_size, kernel_size=patch_size,
                                stride=patch_size, pad_mode='valid', bias=True)

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerPatchEmbeddings.forward(pixel_values)

forward method in TimesformerPatchEmbeddings class.

This method forwards patch embeddings from the input pixel_values.

PARAMETER DESCRIPTION
self

The instance of the TimesformerPatchEmbeddings class.

TYPE: TimesformerPatchEmbeddings

pixel_values

A 5-dimensional tensor representing the pixel values of the input images, with dimensions (batch_size, num_frames, num_channels, height, width).

TYPE: Tensor

RETURNS DESCRIPTION
tuple

A tuple containing the following values:

  • embeddings (torch.Tensor): A 3-dimensional tensor representing the forwarded embeddings, with dimensions (batch_size * num_frames, patch_width, num_channels).
  • num_frames (int): The number of frames in the input pixel_values.
  • patch_width (int): The width of the patches in the forwarded embeddings.
Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def forward(self, pixel_values):
    '''
    forward method in TimesformerPatchEmbeddings class.

    This method forwards patch embeddings from the input pixel_values.

    Args:
        self (TimesformerPatchEmbeddings): The instance of the TimesformerPatchEmbeddings class.
        pixel_values (torch.Tensor): A 5-dimensional tensor representing the pixel values of the input images,
            with dimensions (batch_size, num_frames, num_channels, height, width).

    Returns:
        tuple:
            A tuple containing the following values:

            - embeddings (torch.Tensor): A 3-dimensional tensor representing the forwarded embeddings,
            with dimensions (batch_size * num_frames, patch_width, num_channels).
            - num_frames (int): The number of frames in the input pixel_values.
            - patch_width (int): The width of the patches in the forwarded embeddings.

    Raises:
        None
    '''
    batch_size, num_frames, num_channels, height, width = pixel_values.shape
    pixel_values = pixel_values.reshape(batch_size * num_frames, num_channels, height, width)

    embeddings = self.projection(pixel_values)
    patch_width = embeddings.shape[-1]
    embeddings = embeddings.flatten(start_dim=2).swapaxes(1, 2)
    return embeddings, num_frames, patch_width

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerPreTrainedModel

Bases: PreTrainedModel

An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
class TimesformerPreTrainedModel(PreTrainedModel):
    """
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    """
    config_class = TimesformerConfig
    base_model_prefix = "timesformer"
    main_input_name = "pixel_values"
    supports_gradient_checkpointing = True

    def _init_weights(self, cell):
        """
        Initializes the weights and biases of the given cell.

        Args:
            self: An instance of the TimesformerPreTrainedModel class.
            cell: A cell object to initialize weights and biases for.

        Returns:
            None: This method modifies the weights and biases of the given cell in-place.

        Raises:
            None.

        This method initializes the weights and biases of the given cell based on its type.
        It supports three types of cells: nn.Linear, nn.Conv2d, and nn.LayerNorm.

        For nn.Linear and nn.Conv2d cells:

        - The weights are initialized using the initializer function with a TruncatedNormal distribution with a
        standard deviation of self.config.initializer_range.
        - The biases are initialized with zeros using the initializer function.
        - If the cell does not have biases (cell.bias is None), no bias initialization is performed.

        For nn.LayerNorm cells:

        - The biases are initialized with zeros using the initializer function.
        - The weights are initialized with ones using the initializer function.

        For TimesformerEmbeddings cells:

        - The cls_token is initialized using the initializer function with a TruncatedNormal distribution with a standard
        deviation of self.config.initializer_range.
        - The position_embeddings are initialized using the initializer function with a TruncatedNormal distribution
        with a standard deviation of self.config.initializer_range.
        - The weights of the patch_embeddings are initialized by applying the _init_weights method recursively.

        Note:
            This method modifies the weights and biases of the given cell in-place.
        """
        if isinstance(cell, (nn.Linear, nn.Conv2d)):
            cell.weight.set_data(initializer(TruncatedNormal(sigma=self.config.initializer_range), cell.weight.shape,
                                             cell.weight.dtype))
            if cell.bias is not None:
                cell.bias.set_data(initializer('zeros', cell.bias.shape, cell.bias.dtype))
        elif isinstance(cell, nn.LayerNorm):
            cell.bias.set_data(initializer('zeros', cell.bias.shape, cell.bias.dtype))
            cell.weight.set_data(initializer('ones', cell.weight.shape, cell.weight.dtype))
        elif isinstance(cell, TimesformerEmbeddings):
            cell.cls_token.set_data(initializer(TruncatedNormal(sigma=self.config.initializer_range), cell.cls_token.shape,
                                                cell.cls_token.dtype))
            cell.position_embeddings.set_data(initializer(TruncatedNormal(sigma=self.config.initializer_range),
                                                          cell.position_embeddings.shape, cell.position_embeddings.dtype))
            cell.patch_embeddings.apply(self._init_weights)

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerSelfAttention

Bases: Module

This class represents the self-attention mechanism used in the Timesformer model. It is a subclass of nn.Module.

ATTRIBUTE DESCRIPTION
num_heads

The number of attention heads.

TYPE: int

scale

The scaling factor applied to the attention scores.

TYPE: float

qkv

The fully connected layer used to compute the query, key, and value representations.

TYPE: Linear

attn_drop

The dropout layer applied to the attention scores.

TYPE: Dropout

METHOD DESCRIPTION
__init__

Initializes the TimesformerSelfAttention instance.

forward

Applies self-attention mechanism to the input hidden states.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
class TimesformerSelfAttention(nn.Module):

    """
    This class represents the self-attention mechanism used in the Timesformer model. It is a subclass of nn.Module.

    Attributes:
        num_heads (int): The number of attention heads.
        scale (float): The scaling factor applied to the attention scores.
        qkv (nn.Linear): The fully connected layer used to compute the query, key, and value representations.
        attn_drop (nn.Dropout): The dropout layer applied to the attention scores.

    Methods:
        __init__: Initializes the TimesformerSelfAttention instance.
        forward: Applies self-attention mechanism to the input hidden states.

    """
    def __init__(self, config: TimesformerConfig):
        """
        Initializes a new instance of the TimesformerSelfAttention class.

        Args:
            self: The current object instance.
            config (TimesformerConfig): The configuration object for Timesformer.

        Returns:
            None

        Raises:
            None
        """
        super().__init__()

        num_heads = config.num_attention_heads
        qkv_bias = config.qkv_bias
        attention_dropout_prob = config.attention_probs_dropout_prob

        self.num_heads = num_heads
        head_dim = config.hidden_size // num_heads
        self.scale = head_dim**-0.5
        self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=qkv_bias)
        self.attn_drop = nn.Dropout(p=attention_dropout_prob)

    def forward(self, hidden_states, output_attentions: bool = False):
        """
        Constructs the self-attention mechanism within a Timesformer model.

        Args:
            self (TimesformerSelfAttention): The instance of the TimesformerSelfAttention class.
            hidden_states (torch.Tensor): The input hidden states to be processed by the self-attention mechanism.
                Expected shape is (batch_size, hidden_size, num_channels).
            output_attentions (bool, optional): Flag indicating whether to output attention probabilities.
                Default is False.

        Returns:
            tuple:
                A tuple containing the context layer tensor and optionally the attention probabilities tensor.

                - context_layer (torch.Tensor): The output context layer after applying the self-attention mechanism.
                Shape is (batch_size, hidden_size, num_channels).
                - attention_probs (torch.Tensor), optional: The attention probabilities tensor if 'output_attentions'
                is True. Shape is (batch_size, self.num_heads, hidden_size, hidden_size).

        Raises:
            ValueError: If the input hidden_states tensor does not have the expected shape.
            RuntimeError: If an error occurs during the Softmax calculation or reshaping operations.
            AttributeError: If an attribute error is encountered while accessing class properties.
        """
        batch_size, hidden_size, num_channels = hidden_states.shape
        qkv = (
            self.qkv(hidden_states)
            .reshape(batch_size, hidden_size, 3, self.num_heads, num_channels // self.num_heads)
            .permute(2, 0, 3, 1, 4)
        )
        query, key, value = qkv[0], qkv[1], qkv[2]

        attention_probs = (query @ key.swapaxes(-2, -1)) * self.scale
        attention_probs = nn.Softmax(axis=-1)(attention_probs)
        attention_probs = self.attn_drop(attention_probs)

        context_layer = (attention_probs @ value).swapaxes(1, 2).reshape(batch_size, hidden_size, num_channels)

        outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)

        return outputs

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerSelfAttention.__init__(config)

Initializes a new instance of the TimesformerSelfAttention class.

PARAMETER DESCRIPTION
self

The current object instance.

config

The configuration object for Timesformer.

TYPE: TimesformerConfig

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
def __init__(self, config: TimesformerConfig):
    """
    Initializes a new instance of the TimesformerSelfAttention class.

    Args:
        self: The current object instance.
        config (TimesformerConfig): The configuration object for Timesformer.

    Returns:
        None

    Raises:
        None
    """
    super().__init__()

    num_heads = config.num_attention_heads
    qkv_bias = config.qkv_bias
    attention_dropout_prob = config.attention_probs_dropout_prob

    self.num_heads = num_heads
    head_dim = config.hidden_size // num_heads
    self.scale = head_dim**-0.5
    self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=qkv_bias)
    self.attn_drop = nn.Dropout(p=attention_dropout_prob)

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerSelfAttention.forward(hidden_states, output_attentions=False)

Constructs the self-attention mechanism within a Timesformer model.

PARAMETER DESCRIPTION
self

The instance of the TimesformerSelfAttention class.

TYPE: TimesformerSelfAttention

hidden_states

The input hidden states to be processed by the self-attention mechanism. Expected shape is (batch_size, hidden_size, num_channels).

TYPE: Tensor

output_attentions

Flag indicating whether to output attention probabilities. Default is False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
tuple

A tuple containing the context layer tensor and optionally the attention probabilities tensor.

  • context_layer (torch.Tensor): The output context layer after applying the self-attention mechanism. Shape is (batch_size, hidden_size, num_channels).
  • attention_probs (torch.Tensor), optional: The attention probabilities tensor if 'output_attentions' is True. Shape is (batch_size, self.num_heads, hidden_size, hidden_size).
RAISES DESCRIPTION
ValueError

If the input hidden_states tensor does not have the expected shape.

RuntimeError

If an error occurs during the Softmax calculation or reshaping operations.

AttributeError

If an attribute error is encountered while accessing class properties.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
def forward(self, hidden_states, output_attentions: bool = False):
    """
    Constructs the self-attention mechanism within a Timesformer model.

    Args:
        self (TimesformerSelfAttention): The instance of the TimesformerSelfAttention class.
        hidden_states (torch.Tensor): The input hidden states to be processed by the self-attention mechanism.
            Expected shape is (batch_size, hidden_size, num_channels).
        output_attentions (bool, optional): Flag indicating whether to output attention probabilities.
            Default is False.

    Returns:
        tuple:
            A tuple containing the context layer tensor and optionally the attention probabilities tensor.

            - context_layer (torch.Tensor): The output context layer after applying the self-attention mechanism.
            Shape is (batch_size, hidden_size, num_channels).
            - attention_probs (torch.Tensor), optional: The attention probabilities tensor if 'output_attentions'
            is True. Shape is (batch_size, self.num_heads, hidden_size, hidden_size).

    Raises:
        ValueError: If the input hidden_states tensor does not have the expected shape.
        RuntimeError: If an error occurs during the Softmax calculation or reshaping operations.
        AttributeError: If an attribute error is encountered while accessing class properties.
    """
    batch_size, hidden_size, num_channels = hidden_states.shape
    qkv = (
        self.qkv(hidden_states)
        .reshape(batch_size, hidden_size, 3, self.num_heads, num_channels // self.num_heads)
        .permute(2, 0, 3, 1, 4)
    )
    query, key, value = qkv[0], qkv[1], qkv[2]

    attention_probs = (query @ key.swapaxes(-2, -1)) * self.scale
    attention_probs = nn.Softmax(axis=-1)(attention_probs)
    attention_probs = self.attn_drop(attention_probs)

    context_layer = (attention_probs @ value).swapaxes(1, 2).reshape(batch_size, hidden_size, num_channels)

    outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)

    return outputs

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerSelfOutput

Bases: Module

The residual connection is defined in TimesformerLayer instead of here (as is the case with other models), due to the layernorm applied before each block.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
class TimesformerSelfOutput(nn.Module):
    """
    The residual connection is defined in TimesformerLayer instead of here (as is the case with other models), due to
    the layernorm applied before each block.
    """
    def __init__(self, config: TimesformerConfig) -> None:
        """
        Initializes a new instance of the TimesformerSelfOutput class.

        Args:
            self: The instance of the TimesformerSelfOutput class.
            config (TimesformerConfig): A configuration object containing parameters for the self output layer.
                It specifies the hidden size and dropout probability for the layer.
                It must be an instance of the TimesformerConfig class.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not of type TimesformerConfig.
        """
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.hidden_size)
        self.dropout = nn.Dropout(p=config.hidden_dropout_prob)

    def forward(self, hidden_states: mindspore.Tensor) -> mindspore.Tensor:
        """
        Constructs the self output of the Timesformer model.

        Args:
            self (TimesformerSelfOutput): An instance of the TimesformerSelfOutput class.
            hidden_states (mindspore.Tensor): The hidden states tensor representing the input to the self output layer.

        Returns:
            hidden_states (mindspore.Tensor): The output tensor after applying the self output layer operations.

        Raises:
            None.

        This method takes the hidden states tensor and applies the self output layer operations to it. It first applies
        a dense layer to transform the hidden states tensor. Then, it applies dropout to the transformed tensor to
        prevent overfitting. Finally, it returns the output tensor after the self output layer operations have been
        applied.
        """
        hidden_states = self.dense(hidden_states)
        hidden_states = self.dropout(hidden_states)

        return hidden_states

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerSelfOutput.__init__(config)

Initializes a new instance of the TimesformerSelfOutput class.

PARAMETER DESCRIPTION
self

The instance of the TimesformerSelfOutput class.

config

A configuration object containing parameters for the self output layer. It specifies the hidden size and dropout probability for the layer. It must be an instance of the TimesformerConfig class.

TYPE: TimesformerConfig

RETURNS DESCRIPTION
None

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not of type TimesformerConfig.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
def __init__(self, config: TimesformerConfig) -> None:
    """
    Initializes a new instance of the TimesformerSelfOutput class.

    Args:
        self: The instance of the TimesformerSelfOutput class.
        config (TimesformerConfig): A configuration object containing parameters for the self output layer.
            It specifies the hidden size and dropout probability for the layer.
            It must be an instance of the TimesformerConfig class.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not of type TimesformerConfig.
    """
    super().__init__()
    self.dense = nn.Linear(config.hidden_size, config.hidden_size)
    self.dropout = nn.Dropout(p=config.hidden_dropout_prob)

mindnlp.transformers.models.timesformer.modeling_timesformer.TimesformerSelfOutput.forward(hidden_states)

Constructs the self output of the Timesformer model.

PARAMETER DESCRIPTION
self

An instance of the TimesformerSelfOutput class.

TYPE: TimesformerSelfOutput

hidden_states

The hidden states tensor representing the input to the self output layer.

TYPE: Tensor

RETURNS DESCRIPTION
hidden_states

The output tensor after applying the self output layer operations.

TYPE: Tensor

This method takes the hidden states tensor and applies the self output layer operations to it. It first applies a dense layer to transform the hidden states tensor. Then, it applies dropout to the transformed tensor to prevent overfitting. Finally, it returns the output tensor after the self output layer operations have been applied.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
def forward(self, hidden_states: mindspore.Tensor) -> mindspore.Tensor:
    """
    Constructs the self output of the Timesformer model.

    Args:
        self (TimesformerSelfOutput): An instance of the TimesformerSelfOutput class.
        hidden_states (mindspore.Tensor): The hidden states tensor representing the input to the self output layer.

    Returns:
        hidden_states (mindspore.Tensor): The output tensor after applying the self output layer operations.

    Raises:
        None.

    This method takes the hidden states tensor and applies the self output layer operations to it. It first applies
    a dense layer to transform the hidden states tensor. Then, it applies dropout to the transformed tensor to
    prevent overfitting. Finally, it returns the output tensor after the self output layer operations have been
    applied.
    """
    hidden_states = self.dense(hidden_states)
    hidden_states = self.dropout(hidden_states)

    return hidden_states

mindnlp.transformers.models.timesformer.modeling_timesformer.drop_path(input, drop_prob=0.0, training=False)

Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).

Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the argument.

Source code in mindnlp/transformers/models/timesformer/modeling_timesformer.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
def drop_path(input: mindspore.Tensor, drop_prob: float = 0.0, training: bool = False) -> mindspore.Tensor:
    """
    Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).

    Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
    however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
    See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
    layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
    argument.
    """
    if drop_prob == 0.0 or not training:
        return input
    keep_prob = 1 - drop_prob
    shape = (input.shape[0],) + (1,) * (input.ndim - 1)  # work with diff dim tensors, not just 2D ConvNets
    random_tensor = keep_prob + ops.rand(shape, dtype=input.dtype)
    random_tensor = random_tensor.floor(random_tensor)  # binarize
    output = input.div(keep_prob) * random_tensor
    return output

mindnlp.transformers.models.timesformer.image_processing_videomae

Image processor class for VideoMAE model, and reused by Timesformer model.

mindnlp.transformers.models.timesformer.image_processing_videomae.VideoMAEImageProcessor

Bases: BaseImageProcessor

Constructs a VideoMAE image processor.

PARAMETER DESCRIPTION
do_resize

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.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

size

224}): Size of the output image after resizing. The shortest edge of the image will be resized tosize["shortest_edge"]while maintaining the aspect ratio of the original image. Can be overriden bysizein thepreprocess` method.

TYPE: `Dict[str, int]` *optional*, defaults to `{"shortest_edge" DEFAULT: None

resample

Resampling filter to use if resizing the image. Can be overridden by the resample parameter in the preprocess method.

TYPE: `PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR` DEFAULT: BILINEAR

do_center_crop

Whether to center crop the image to the specified crop_size. Can be overridden by the do_center_crop parameter in the preprocess method.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

crop_size

224, "width": 224}): Size of the image after applying the center crop. Can be overridden by thecrop_sizeparameter in thepreprocess` method.

TYPE: `Dict[str, int]`, *optional*, defaults to `{"height" DEFAULT: None

do_rescale

Whether to rescale the image by the specified scale rescale_factor. Can be overridden by the do_rescale parameter in the preprocess method.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

rescale_factor

Defines the scale factor to use if rescaling the image. Can be overridden by the rescale_factor parameter in the preprocess method.

TYPE: `int` or `float`, *optional*, defaults to `1/255` DEFAULT: 1 / 255

do_normalize

Whether to normalize the image. Can be overridden by the do_normalize parameter in the preprocess method.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

image_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.

TYPE: `float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN` DEFAULT: None

image_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.

TYPE: `float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD` DEFAULT: None

Source code in mindnlp/transformers/models/timesformer/image_processing_videomae.py
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
class VideoMAEImageProcessor(BaseImageProcessor):
    r"""
    Constructs a VideoMAE image processor.

    Args:
        do_resize (`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.
        size (`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.
        resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
            Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
            `preprocess` method.
        do_center_crop (`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.
        crop_size (`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.
        do_rescale (`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.
        rescale_factor (`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.
        do_normalize (`bool`, *optional*, defaults to `True`):
            Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
            method.
        image_mean (`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.
        image_std (`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.
    """
    model_input_names = ["pixel_values"]

    def __init__(
        self,
        do_resize: bool = True,
        size: Dict[str, int] = None,
        resample: PILImageResampling = PILImageResampling.BILINEAR,
        do_center_crop: bool = True,
        crop_size: Dict[str, int] = None,
        do_rescale: bool = True,
        rescale_factor: Union[int, float] = 1 / 255,
        do_normalize: bool = True,
        image_mean: Optional[Union[float, List[float]]] = None,
        image_std: Optional[Union[float, List[float]]] = None,
        **kwargs,
    ) -> None:
        """Initializes an instance of the VideoMAEImageProcessor class.

        Args:
            self: The instance of the class.
            do_resize (bool, optional): Indicates whether resizing should be performed on the input image.
                Defaults to True.
            size (Dict[str, int], optional): Specifies the desired size of the image after resizing. Defaults to None.
            resample (PILImageResampling, optional): The resampling method to be used during resizing.
                Defaults to PILImageResampling.BILINEAR.
            do_center_crop (bool, optional): Indicates whether center cropping should be performed on the resized image.
                Defaults to True.
            crop_size (Dict[str, int], optional): Specifies the size of the cropped image. Defaults to None.
            do_rescale (bool, optional): Indicates whether rescaling should be performed on the image. Defaults to True.
            rescale_factor (Union[int, float], optional): The factor by which the image should be rescaled.
                Defaults to 1/255.
            do_normalize (bool, optional): Indicates whether normalization should be performed on the image.
                Defaults to True.
            image_mean (Optional[Union[float, List[float]]], optional): The mean values used for normalization.
                Defaults to None.
            image_std (Optional[Union[float, List[float]]], optional): The standard deviation values used
                for normalization. Defaults to None.
            **kwargs: Additional keyword arguments that can be passed to the super class.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__(**kwargs)
        size = size if size is not None else {"shortest_edge": 224}
        size = get_size_dict(size, default_to_square=False)
        crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
        crop_size = get_size_dict(crop_size, param_name="crop_size")

        self.do_resize = do_resize
        self.size = size
        self.do_center_crop = do_center_crop
        self.crop_size = crop_size
        self.resample = resample
        self.do_rescale = do_rescale
        self.rescale_factor = rescale_factor
        self.do_normalize = do_normalize
        self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
        self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
        self._valid_processor_keys = [
            "videos",
            "do_resize",
            "size",
            "resample",
            "do_center_crop",
            "crop_size",
            "do_rescale",
            "rescale_factor",
            "do_normalize",
            "image_mean",
            "image_std",
            "return_tensors",
            "data_format",
            "input_data_format",
        ]

    def resize(
        self,
        image: np.ndarray,
        size: Dict[str, int],
        resample: PILImageResampling = PILImageResampling.BILINEAR,
        data_format: Optional[Union[str, ChannelDimension]] = None,
        input_data_format: Optional[Union[str, ChannelDimension]] = None,
        **kwargs,
    ) -> np.ndarray:
        """
        Resize an image.

        Args:
            image (`np.ndarray`):
                Image to resize.
            size (`Dict[str, int]`):
                Size of the output image. If `size` is of the form `{"height": h, "width": w}`, the output image will
                have the size `(h, w)`. If `size` is of the form `{"shortest_edge": s}`, the output image will have its
                shortest edge of length `s` while keeping the aspect ratio of the original image.
            resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
                Resampling filter to use when resiizing the image.
            data_format (`str` or `ChannelDimension`, *optional*):
                The channel dimension format of the image. If not provided, it will be the same as the input image.
            input_data_format (`str` or `ChannelDimension`, *optional*):
                The channel dimension format of the input image. If not provided, it will be inferred.
        """
        size = get_size_dict(size, default_to_square=False)
        if "shortest_edge" in size:
            output_size = get_resize_output_image_size(
                image, size["shortest_edge"], default_to_square=False, input_data_format=input_data_format
            )
        elif "height" in size and "width" in size:
            output_size = (size["height"], size["width"])
        else:
            raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}")
        return resize(
            image,
            size=output_size,
            resample=resample,
            data_format=data_format,
            input_data_format=input_data_format,
            **kwargs,
        )

    def _preprocess_image(
        self,
        image: ImageInput,
        do_resize: bool = None,
        size: Dict[str, int] = None,
        resample: PILImageResampling = None,
        do_center_crop: bool = None,
        crop_size: Dict[str, int] = None,
        do_rescale: bool = None,
        rescale_factor: float = None,
        do_normalize: bool = None,
        image_mean: Optional[Union[float, List[float]]] = None,
        image_std: Optional[Union[float, List[float]]] = None,
        data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
        input_data_format: Optional[Union[str, ChannelDimension]] = None,
    ) -> np.ndarray:
        """Preprocesses a single image."""
        validate_preprocess_arguments(
            do_rescale=do_rescale,
            rescale_factor=rescale_factor,
            do_normalize=do_normalize,
            image_mean=image_mean,
            image_std=image_std,
            do_center_crop=do_center_crop,
            crop_size=crop_size,
            do_resize=do_resize,
            size=size,
            resample=resample,
        )

        # All transformations expect numpy arrays.
        image = to_numpy_array(image)

        if is_scaled_image(image) and do_rescale:
            logger.warning_once(
                "It looks like you are trying to rescale already rescaled images. If the input"
                " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
            )

        if input_data_format is None:
            input_data_format = infer_channel_dimension_format(image)

        if do_resize:
            image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)

        if do_center_crop:
            image = self.center_crop(image, size=crop_size, input_data_format=input_data_format)

        if do_rescale:
            image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)

        if do_normalize:
            image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)

        image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
        return image

    def preprocess(
        self,
        videos: ImageInput,
        do_resize: bool = None,
        size: Dict[str, int] = None,
        resample: PILImageResampling = None,
        do_center_crop: bool = None,
        crop_size: Dict[str, int] = None,
        do_rescale: bool = None,
        rescale_factor: float = None,
        do_normalize: bool = None,
        image_mean: Optional[Union[float, List[float]]] = None,
        image_std: Optional[Union[float, List[float]]] = None,
        return_tensors: Optional[Union[str, TensorType]] = None,
        data_format: ChannelDimension = ChannelDimension.FIRST,
        input_data_format: Optional[Union[str, ChannelDimension]] = None,
        **kwargs,
    ) -> PIL.Image.Image:
        """
        Preprocess an image or batch of images.

        Args:
            images (`ImageInput`):
                Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
                passing in images with pixel values between 0 and 1, set `do_rescale=False`.
            do_resize (`bool`, *optional*, defaults to `self.do_resize`):
                Whether to resize the image.
            size (`Dict[str, int]`, *optional*, defaults to `self.size`):
                Size of the image after applying resize.
            resample (`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`.
            do_center_crop (`bool`, *optional*, defaults to `self.do_centre_crop`):
                Whether to centre crop the image.
            crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
                Size of the image after applying the centre crop.
            do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
                Whether to rescale the image values between [0 - 1].
            rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
                Rescale factor to rescale the image by if `do_rescale` is set to `True`.
            do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
                Whether to normalize the image.
            image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
                Image mean.
            image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
                Image standard deviation.
            return_tensors (`str` or `TensorType`, *optional*):
                The type of tensors to return. Can be one of:

                - Unset: Return a list 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`.
            data_format (`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.
                - Unset: Use the inferred channel dimension format of the input image.
            input_data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format for the input image. If unset, the channel dimension format is inferred
                from the input image. Can be one of:

                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
                - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
        """
        do_resize = do_resize if do_resize is not None else self.do_resize
        resample = resample if resample is not None else self.resample
        do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
        do_rescale = do_rescale if do_rescale is not None else self.do_rescale
        rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
        do_normalize = do_normalize if do_normalize is not None else self.do_normalize
        image_mean = image_mean if image_mean is not None else self.image_mean
        image_std = image_std if image_std is not None else self.image_std

        size = size if size is not None else self.size
        size = get_size_dict(size, default_to_square=False)
        crop_size = crop_size if crop_size is not None else self.crop_size
        crop_size = get_size_dict(crop_size, param_name="crop_size")

        validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)

        if not valid_images(videos):
            raise ValueError(
                "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
                "torch.Tensor, tf.Tensor or jax.ndarray."
            )

        videos = make_batched(videos)

        videos = [
            [
                self._preprocess_image(
                    image=img,
                    do_resize=do_resize,
                    size=size,
                    resample=resample,
                    do_center_crop=do_center_crop,
                    crop_size=crop_size,
                    do_rescale=do_rescale,
                    rescale_factor=rescale_factor,
                    do_normalize=do_normalize,
                    image_mean=image_mean,
                    image_std=image_std,
                    data_format=data_format,
                    input_data_format=input_data_format,
                )
                for img in video
            ]
            for video in videos
        ]

        data = {"pixel_values": videos}
        return BatchFeature(data=data, tensor_type=return_tensors)

mindnlp.transformers.models.timesformer.image_processing_videomae.VideoMAEImageProcessor.__init__(do_resize=True, size=None, resample=PILImageResampling.BILINEAR, do_center_crop=True, crop_size=None, do_rescale=True, rescale_factor=1 / 255, do_normalize=True, image_mean=None, image_std=None, **kwargs)

Initializes an instance of the VideoMAEImageProcessor class.

PARAMETER DESCRIPTION
self

The instance of the class.

do_resize

Indicates whether resizing should be performed on the input image. Defaults to True.

TYPE: bool DEFAULT: True

size

Specifies the desired size of the image after resizing. Defaults to None.

TYPE: Dict[str, int] DEFAULT: None

resample

The resampling method to be used during resizing. Defaults to PILImageResampling.BILINEAR.

TYPE: PILImageResampling DEFAULT: BILINEAR

do_center_crop

Indicates whether center cropping should be performed on the resized image. Defaults to True.

TYPE: bool DEFAULT: True

crop_size

Specifies the size of the cropped image. Defaults to None.

TYPE: Dict[str, int] DEFAULT: None

do_rescale

Indicates whether rescaling should be performed on the image. Defaults to True.

TYPE: bool DEFAULT: True

rescale_factor

The factor by which the image should be rescaled. Defaults to 1/255.

TYPE: Union[int, float] DEFAULT: 1 / 255

do_normalize

Indicates whether normalization should be performed on the image. Defaults to True.

TYPE: bool DEFAULT: True

image_mean

The mean values used for normalization. Defaults to None.

TYPE: Optional[Union[float, List[float]]] DEFAULT: None

image_std

The standard deviation values used for normalization. Defaults to None.

TYPE: Optional[Union[float, List[float]]] DEFAULT: None

**kwargs

Additional keyword arguments that can be passed to the super class.

DEFAULT: {}

RETURNS DESCRIPTION
None

None.

Source code in mindnlp/transformers/models/timesformer/image_processing_videomae.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
def __init__(
    self,
    do_resize: bool = True,
    size: Dict[str, int] = None,
    resample: PILImageResampling = PILImageResampling.BILINEAR,
    do_center_crop: bool = True,
    crop_size: Dict[str, int] = None,
    do_rescale: bool = True,
    rescale_factor: Union[int, float] = 1 / 255,
    do_normalize: bool = True,
    image_mean: Optional[Union[float, List[float]]] = None,
    image_std: Optional[Union[float, List[float]]] = None,
    **kwargs,
) -> None:
    """Initializes an instance of the VideoMAEImageProcessor class.

    Args:
        self: The instance of the class.
        do_resize (bool, optional): Indicates whether resizing should be performed on the input image.
            Defaults to True.
        size (Dict[str, int], optional): Specifies the desired size of the image after resizing. Defaults to None.
        resample (PILImageResampling, optional): The resampling method to be used during resizing.
            Defaults to PILImageResampling.BILINEAR.
        do_center_crop (bool, optional): Indicates whether center cropping should be performed on the resized image.
            Defaults to True.
        crop_size (Dict[str, int], optional): Specifies the size of the cropped image. Defaults to None.
        do_rescale (bool, optional): Indicates whether rescaling should be performed on the image. Defaults to True.
        rescale_factor (Union[int, float], optional): The factor by which the image should be rescaled.
            Defaults to 1/255.
        do_normalize (bool, optional): Indicates whether normalization should be performed on the image.
            Defaults to True.
        image_mean (Optional[Union[float, List[float]]], optional): The mean values used for normalization.
            Defaults to None.
        image_std (Optional[Union[float, List[float]]], optional): The standard deviation values used
            for normalization. Defaults to None.
        **kwargs: Additional keyword arguments that can be passed to the super class.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(**kwargs)
    size = size if size is not None else {"shortest_edge": 224}
    size = get_size_dict(size, default_to_square=False)
    crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
    crop_size = get_size_dict(crop_size, param_name="crop_size")

    self.do_resize = do_resize
    self.size = size
    self.do_center_crop = do_center_crop
    self.crop_size = crop_size
    self.resample = resample
    self.do_rescale = do_rescale
    self.rescale_factor = rescale_factor
    self.do_normalize = do_normalize
    self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
    self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
    self._valid_processor_keys = [
        "videos",
        "do_resize",
        "size",
        "resample",
        "do_center_crop",
        "crop_size",
        "do_rescale",
        "rescale_factor",
        "do_normalize",
        "image_mean",
        "image_std",
        "return_tensors",
        "data_format",
        "input_data_format",
    ]

mindnlp.transformers.models.timesformer.image_processing_videomae.VideoMAEImageProcessor.preprocess(videos, do_resize=None, size=None, resample=None, do_center_crop=None, crop_size=None, do_rescale=None, rescale_factor=None, do_normalize=None, image_mean=None, image_std=None, return_tensors=None, data_format=ChannelDimension.FIRST, input_data_format=None, **kwargs)

Preprocess an image or batch of images.

PARAMETER DESCRIPTION
images

Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set do_rescale=False.

TYPE: `ImageInput`

do_resize

Whether to resize the image.

TYPE: `bool`, *optional*, defaults to `self.do_resize` DEFAULT: None

size

Size of the image after applying resize.

TYPE: `Dict[str, int]`, *optional*, defaults to `self.size` DEFAULT: None

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.

TYPE: `PILImageResampling`, *optional*, defaults to `self.resample` DEFAULT: None

do_center_crop

Whether to centre crop the image.

TYPE: `bool`, *optional*, defaults to `self.do_centre_crop` DEFAULT: None

crop_size

Size of the image after applying the centre crop.

TYPE: `Dict[str, int]`, *optional*, defaults to `self.crop_size` DEFAULT: None

do_rescale

Whether to rescale the image values between [0 - 1].

TYPE: `bool`, *optional*, defaults to `self.do_rescale` DEFAULT: None

rescale_factor

Rescale factor to rescale the image by if do_rescale is set to True.

TYPE: `float`, *optional*, defaults to `self.rescale_factor` DEFAULT: None

do_normalize

Whether to normalize the image.

TYPE: `bool`, *optional*, defaults to `self.do_normalize` DEFAULT: None

image_mean

Image mean.

TYPE: `float` or `List[float]`, *optional*, defaults to `self.image_mean` DEFAULT: None

image_std

Image standard deviation.

TYPE: `float` or `List[float]`, *optional*, defaults to `self.image_std` DEFAULT: None

return_tensors

The type of tensors to return. Can be one of:

  • Unset: Return a list 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.

TYPE: `str` or `TensorType`, *optional* DEFAULT: None

data_format

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.
  • Unset: Use the inferred channel dimension format of the input image.

TYPE: `ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST` DEFAULT: FIRST

input_data_format

The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of:

  • "channels_first" or ChannelDimension.FIRST: image in (num_channels, height, width) format.
  • "channels_last" or ChannelDimension.LAST: image in (height, width, num_channels) format.
  • "none" or ChannelDimension.NONE: image in (height, width) format.

TYPE: `ChannelDimension` or `str`, *optional* DEFAULT: None

Source code in mindnlp/transformers/models/timesformer/image_processing_videomae.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
def preprocess(
    self,
    videos: ImageInput,
    do_resize: bool = None,
    size: Dict[str, int] = None,
    resample: PILImageResampling = None,
    do_center_crop: bool = None,
    crop_size: Dict[str, int] = None,
    do_rescale: bool = None,
    rescale_factor: float = None,
    do_normalize: bool = None,
    image_mean: Optional[Union[float, List[float]]] = None,
    image_std: Optional[Union[float, List[float]]] = None,
    return_tensors: Optional[Union[str, TensorType]] = None,
    data_format: ChannelDimension = ChannelDimension.FIRST,
    input_data_format: Optional[Union[str, ChannelDimension]] = None,
    **kwargs,
) -> PIL.Image.Image:
    """
    Preprocess an image or batch of images.

    Args:
        images (`ImageInput`):
            Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
            passing in images with pixel values between 0 and 1, set `do_rescale=False`.
        do_resize (`bool`, *optional*, defaults to `self.do_resize`):
            Whether to resize the image.
        size (`Dict[str, int]`, *optional*, defaults to `self.size`):
            Size of the image after applying resize.
        resample (`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`.
        do_center_crop (`bool`, *optional*, defaults to `self.do_centre_crop`):
            Whether to centre crop the image.
        crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
            Size of the image after applying the centre crop.
        do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
            Whether to rescale the image values between [0 - 1].
        rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
            Rescale factor to rescale the image by if `do_rescale` is set to `True`.
        do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
            Whether to normalize the image.
        image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
            Image mean.
        image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
            Image standard deviation.
        return_tensors (`str` or `TensorType`, *optional*):
            The type of tensors to return. Can be one of:

            - Unset: Return a list 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`.
        data_format (`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.
            - Unset: Use the inferred channel dimension format of the input image.
        input_data_format (`ChannelDimension` or `str`, *optional*):
            The channel dimension format for the input image. If unset, the channel dimension format is inferred
            from the input image. Can be one of:

            - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
            - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
            - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
    """
    do_resize = do_resize if do_resize is not None else self.do_resize
    resample = resample if resample is not None else self.resample
    do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
    do_rescale = do_rescale if do_rescale is not None else self.do_rescale
    rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
    do_normalize = do_normalize if do_normalize is not None else self.do_normalize
    image_mean = image_mean if image_mean is not None else self.image_mean
    image_std = image_std if image_std is not None else self.image_std

    size = size if size is not None else self.size
    size = get_size_dict(size, default_to_square=False)
    crop_size = crop_size if crop_size is not None else self.crop_size
    crop_size = get_size_dict(crop_size, param_name="crop_size")

    validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)

    if not valid_images(videos):
        raise ValueError(
            "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
            "torch.Tensor, tf.Tensor or jax.ndarray."
        )

    videos = make_batched(videos)

    videos = [
        [
            self._preprocess_image(
                image=img,
                do_resize=do_resize,
                size=size,
                resample=resample,
                do_center_crop=do_center_crop,
                crop_size=crop_size,
                do_rescale=do_rescale,
                rescale_factor=rescale_factor,
                do_normalize=do_normalize,
                image_mean=image_mean,
                image_std=image_std,
                data_format=data_format,
                input_data_format=input_data_format,
            )
            for img in video
        ]
        for video in videos
    ]

    data = {"pixel_values": videos}
    return BatchFeature(data=data, tensor_type=return_tensors)

mindnlp.transformers.models.timesformer.image_processing_videomae.VideoMAEImageProcessor.resize(image, size, resample=PILImageResampling.BILINEAR, data_format=None, input_data_format=None, **kwargs)

Resize an image.

PARAMETER DESCRIPTION
image

Image to resize.

TYPE: `np.ndarray`

size

Size of the output image. If size is of the form {"height": h, "width": w}, the output image will have the size (h, w). If size is of the form {"shortest_edge": s}, the output image will have its shortest edge of length s while keeping the aspect ratio of the original image.

TYPE: `Dict[str, int]`

resample

Resampling filter to use when resiizing the image.

TYPE: `PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR` DEFAULT: BILINEAR

data_format

The channel dimension format of the image. If not provided, it will be the same as the input image.

TYPE: `str` or `ChannelDimension`, *optional* DEFAULT: None

input_data_format

The channel dimension format of the input image. If not provided, it will be inferred.

TYPE: `str` or `ChannelDimension`, *optional* DEFAULT: None

Source code in mindnlp/transformers/models/timesformer/image_processing_videomae.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
def resize(
    self,
    image: np.ndarray,
    size: Dict[str, int],
    resample: PILImageResampling = PILImageResampling.BILINEAR,
    data_format: Optional[Union[str, ChannelDimension]] = None,
    input_data_format: Optional[Union[str, ChannelDimension]] = None,
    **kwargs,
) -> np.ndarray:
    """
    Resize an image.

    Args:
        image (`np.ndarray`):
            Image to resize.
        size (`Dict[str, int]`):
            Size of the output image. If `size` is of the form `{"height": h, "width": w}`, the output image will
            have the size `(h, w)`. If `size` is of the form `{"shortest_edge": s}`, the output image will have its
            shortest edge of length `s` while keeping the aspect ratio of the original image.
        resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
            Resampling filter to use when resiizing the image.
        data_format (`str` or `ChannelDimension`, *optional*):
            The channel dimension format of the image. If not provided, it will be the same as the input image.
        input_data_format (`str` or `ChannelDimension`, *optional*):
            The channel dimension format of the input image. If not provided, it will be inferred.
    """
    size = get_size_dict(size, default_to_square=False)
    if "shortest_edge" in size:
        output_size = get_resize_output_image_size(
            image, size["shortest_edge"], default_to_square=False, input_data_format=input_data_format
        )
    elif "height" in size and "width" in size:
        output_size = (size["height"], size["width"])
    else:
        raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}")
    return resize(
        image,
        size=output_size,
        resample=resample,
        data_format=data_format,
        input_data_format=input_data_format,
        **kwargs,
    )

mindnlp.transformers.models.timesformer.image_processing_videomae.make_batched(videos)

PARAMETER DESCRIPTION
videos

A list or tuple of image inputs or a single image input.

TYPE: Union[List[ImageInput], Tuple[ImageInput]]

RETURNS DESCRIPTION
List[List[ImageInput]]

List[List[ImageInput]]: A batched list of image inputs.

RAISES DESCRIPTION
ValueError

If the input videos cannot be batched into a valid format.

Source code in mindnlp/transformers/models/timesformer/image_processing_videomae.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def make_batched(videos) -> List[List[ImageInput]]:
    """
    Args:
        videos (Union[List[ImageInput], Tuple[ImageInput]]):
            A list or tuple of image inputs or a single image input.

    Returns:
        List[List[ImageInput]]: A batched list of image inputs.

    Raises:
        ValueError: If the input videos cannot be batched into a valid format.
    """
    if isinstance(videos, (list, tuple)) and isinstance(videos[0], (list, tuple)) and is_valid_image(videos[0][0]):
        return videos

    elif isinstance(videos, (list, tuple)) and is_valid_image(videos[0]):
        return [videos]

    elif is_valid_image(videos):
        return [[videos]]

    raise ValueError(f"Could not make batched video from {videos}")