configuration_tvp.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. # coding=utf-8
  2. # Copyright 2023 The Intel AIA Team Authors, and HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License=, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing=, software
  11. # distributed under the License is distributed on an "AS IS" BASIS=,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND=, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """TVP model configuration"""
  16. import copy
  17. from ...configuration_utils import PretrainedConfig
  18. from ...utils import logging
  19. from ...utils.backbone_utils import verify_backbone_config_arguments
  20. from ..auto import CONFIG_MAPPING
  21. logger = logging.get_logger(__name__)
  22. class TvpConfig(PretrainedConfig):
  23. r"""
  24. This is the configuration class to store the configuration of a [`TvpModel`]. It is used to instantiate an Tvp
  25. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  26. defaults will yield a similar configuration to that of the Tvp
  27. [Intel/tvp-base](https://huggingface.co/Intel/tvp-base) architecture.
  28. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  29. documentation from [`PretrainedConfig`] for more information.
  30. Args:
  31. backbone_config (`PretrainedConfig` or `dict`, *optional*):
  32. The configuration of the backbone model.
  33. backbone (`str`, *optional*):
  34. Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
  35. will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
  36. is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
  37. use_pretrained_backbone (`bool`, *optional*, defaults to `False`):
  38. Whether to use pretrained weights for the backbone.
  39. use_timm_backbone (`bool`, *optional*, defaults to `False`):
  40. Whether to load `backbone` from the timm library. If `False`, the backbone is loaded from the transformers
  41. library.
  42. backbone_kwargs (`dict`, *optional*):
  43. Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
  44. e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
  45. distance_loss_weight (`float`, *optional*, defaults to 1.0):
  46. The weight of distance loss.
  47. duration_loss_weight (`float`, *optional*, defaults to 0.1):
  48. The weight of duration loss.
  49. visual_prompter_type (`str`, *optional*, defaults to `"framepad"`):
  50. Visual prompt type. The type of padding. Framepad means padding on each frame. Should be one of "framepad"
  51. or "framedownpad"
  52. visual_prompter_apply (`str`, *optional*, defaults to `"replace"`):
  53. The way of applying visual prompt. Replace means use the value of prompt to change the original value in
  54. visual inputs. Should be one of "replace", or "add", or "remove".
  55. visual_prompt_size (`int`, *optional*, defaults to 96):
  56. The size of visual prompt.
  57. max_img_size (`int`, *optional*, defaults to 448):
  58. The maximum size of frame.
  59. num_frames (`int`, *optional*, defaults to 48):
  60. The number of frames extracted from a video.
  61. vocab_size (`int`, *optional*, defaults to 30522):
  62. Vocabulary size of the Tvp text model. Defines the number of different tokens that can be represented by
  63. the `inputs_ids` passed when calling [`TvpModel`].
  64. hidden_size (`int`, *optional*, defaults to 768):
  65. Dimensionality of the encoder layers.
  66. intermediate_size (`int`, *optional*, defaults to 3072):
  67. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  68. num_hidden_layers (`int`, *optional*, defaults to 12):
  69. Number of hidden layers in the Transformer encoder.
  70. num_attention_heads (`int`, *optional*, defaults to 12):
  71. Number of attention heads for each attention layer in the Transformer encoder.
  72. max_position_embeddings (`int`, *optional*, defaults to 512):
  73. The maximum sequence length that this model might ever be used with. Typically set this to something large
  74. just in case (e.g., 512 or 1024 or 2048).
  75. max_grid_col_position_embeddings (`int`, *optional*, defaults to 100):
  76. The largest number of horizontal patches from a video frame.
  77. max_grid_row_position_embeddings (`int`, *optional*, defaults to 100):
  78. The largest number of vertical patches from a video frame.
  79. hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
  80. The dropout probability of hidden layers.
  81. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  82. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  83. `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
  84. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  85. The epsilon used by the layer normalization layers.
  86. initializer_range (`float`, *optional*, defaults to 0.02):
  87. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  88. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
  89. The dropout probability of attention layers.
  90. """
  91. model_type = "tvp"
  92. def __init__(
  93. self,
  94. backbone_config=None,
  95. backbone=None,
  96. use_pretrained_backbone=False,
  97. use_timm_backbone=False,
  98. backbone_kwargs=None,
  99. distance_loss_weight=1.0,
  100. duration_loss_weight=0.1,
  101. visual_prompter_type="framepad",
  102. visual_prompter_apply="replace",
  103. visual_prompt_size=96,
  104. max_img_size=448,
  105. num_frames=48,
  106. vocab_size=30522,
  107. hidden_size=768,
  108. intermediate_size=3072,
  109. num_hidden_layers=12,
  110. num_attention_heads=12,
  111. max_position_embeddings=512,
  112. max_grid_col_position_embeddings=100,
  113. max_grid_row_position_embeddings=100,
  114. hidden_dropout_prob=0.1,
  115. hidden_act="gelu",
  116. layer_norm_eps=1e-12,
  117. initializer_range=0.02,
  118. attention_probs_dropout_prob=0.1,
  119. **kwargs,
  120. ):
  121. super().__init__(**kwargs)
  122. if backbone_config is None and backbone is None:
  123. logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.")
  124. backbone_config = CONFIG_MAPPING["resnet"](out_features=["stage4"])
  125. elif isinstance(backbone_config, dict):
  126. backbone_model_type = backbone_config.get("model_type")
  127. config_class = CONFIG_MAPPING[backbone_model_type]
  128. backbone_config = config_class.from_dict(backbone_config)
  129. verify_backbone_config_arguments(
  130. use_timm_backbone=use_timm_backbone,
  131. use_pretrained_backbone=use_pretrained_backbone,
  132. backbone=backbone,
  133. backbone_config=backbone_config,
  134. backbone_kwargs=backbone_kwargs,
  135. )
  136. self.backbone_config = backbone_config
  137. self.backbone = backbone
  138. self.use_pretrained_backbone = use_pretrained_backbone
  139. self.use_timm_backbone = use_timm_backbone
  140. self.backbone_kwargs = backbone_kwargs
  141. self.distance_loss_weight = distance_loss_weight
  142. self.duration_loss_weight = duration_loss_weight
  143. self.visual_prompter_type = visual_prompter_type
  144. self.visual_prompter_apply = visual_prompter_apply
  145. self.visual_prompt_size = visual_prompt_size
  146. self.max_img_size = max_img_size
  147. self.num_frames = num_frames
  148. self.vocab_size = vocab_size
  149. self.hidden_size = hidden_size
  150. self.intermediate_size = intermediate_size
  151. self.num_hidden_layers = num_hidden_layers
  152. self.num_attention_heads = num_attention_heads
  153. self.max_position_embeddings = max_position_embeddings
  154. self.max_grid_col_position_embeddings = max_grid_col_position_embeddings
  155. self.max_grid_row_position_embeddings = max_grid_row_position_embeddings
  156. self.layer_norm_eps = layer_norm_eps
  157. self.hidden_dropout_prob = hidden_dropout_prob
  158. self.hidden_act = hidden_act
  159. self.initializer_range = initializer_range
  160. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  161. @property
  162. def sub_configs(self):
  163. return (
  164. {"backbone_config": type(self.backbone_config)}
  165. if getattr(self, "backbone_config", None) is not None
  166. else {}
  167. )
  168. @classmethod
  169. def from_backbone_config(cls, backbone_config: PretrainedConfig, **kwargs):
  170. """Instantiate a [`TvpConfig`] (or a derived class) from a pre-trained backbone model configuration.
  171. Args:
  172. backbone_config ([`PretrainedConfig`]):
  173. The backbone configuration.
  174. Returns:
  175. [`TvpConfig`]: An instance of a configuration object
  176. """
  177. return cls(backbone_config=backbone_config, **kwargs)
  178. def to_dict(self):
  179. """
  180. Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
  181. Returns:
  182. `dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
  183. """
  184. output = copy.deepcopy(self.__dict__)
  185. if output["backbone_config"] is not None:
  186. output["backbone_config"] = self.backbone_config.to_dict()
  187. output["model_type"] = self.__class__.model_type
  188. return output
  189. __all__ = ["TvpConfig"]