configuration_llava.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. # coding=utf-8
  2. # Copyright 2023 Microsoft Research & University of Wisconsin-Madison and the HuggingFace Inc. team. All rights reserved.
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Llava model configuration"""
  15. from ...configuration_utils import PretrainedConfig
  16. from ...utils import logging
  17. from ..auto import CONFIG_MAPPING, AutoConfig
  18. logger = logging.get_logger(__name__)
  19. class LlavaConfig(PretrainedConfig):
  20. r"""
  21. This is the configuration class to store the configuration of a [`LlavaForConditionalGeneration`]. It is used to instantiate an
  22. Llava model according to the specified arguments, defining the model architecture. Instantiating a configuration
  23. with the defaults will yield a similar configuration to that of the Llava-9B.
  24. e.g. [llava-hf/llava-9b](https://huggingface.co/llava-hf/llava-9b)
  25. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  26. documentation from [`PretrainedConfig`] for more information.
  27. Args:
  28. vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `CLIPVisionConfig`):
  29. The config object or dictionary of the vision backbone.
  30. text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `LlamaConfig`):
  31. The config object or dictionary of the text backbone.
  32. image_token_index (`int`, *optional*, defaults to 32000):
  33. The image token index to encode the image prompt.
  34. projector_hidden_act (`str`, *optional*, defaults to `"gelu"`):
  35. The activation function used by the multimodal projector.
  36. vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
  37. The feature selection strategy used to select the vision feature from the vision backbone.
  38. Can be one of `"default"` or `"full"`.
  39. vision_feature_layer (`Union[int, list[int]]`, *optional*, defaults to -2):
  40. The index of the layer to select the vision feature. If multiple indices are provided,
  41. the vision feature of the corresponding indices will be concatenated to form the
  42. vision features.
  43. image_seq_length (`int`, *optional*, defaults to 576):
  44. Sequence length of one image embedding.
  45. multimodal_projector_bias (`bool`, *optional*, defaults to `True`):
  46. Whether to use bias in the multimodal projector.
  47. Example:
  48. ```python
  49. >>> from transformers import LlavaForConditionalGeneration, LlavaConfig, CLIPVisionConfig, LlamaConfig
  50. >>> # Initializing a CLIP-vision config
  51. >>> vision_config = CLIPVisionConfig()
  52. >>> # Initializing a Llama config
  53. >>> text_config = LlamaConfig()
  54. >>> # Initializing a Llava llava-1.5-7b style configuration
  55. >>> configuration = LlavaConfig(vision_config, text_config)
  56. >>> # Initializing a model from the llava-1.5-7b style configuration
  57. >>> model = LlavaForConditionalGeneration(configuration)
  58. >>> # Accessing the model configuration
  59. >>> configuration = model.config
  60. ```"""
  61. model_type = "llava"
  62. attribute_map = {
  63. "image_token_id": "image_token_index",
  64. }
  65. sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
  66. def __init__(
  67. self,
  68. vision_config=None,
  69. text_config=None,
  70. image_token_index=32000,
  71. projector_hidden_act="gelu",
  72. vision_feature_select_strategy="default",
  73. vision_feature_layer=-2,
  74. image_seq_length=576,
  75. multimodal_projector_bias=True,
  76. **kwargs,
  77. ):
  78. self.image_token_index = image_token_index
  79. self.projector_hidden_act = projector_hidden_act
  80. self.image_seq_length = image_seq_length
  81. if vision_feature_select_strategy not in ["default", "full"]:
  82. raise ValueError(
  83. "vision_feature_select_strategy should be one of 'default', 'full'."
  84. f"Got: {vision_feature_select_strategy}"
  85. )
  86. self.vision_feature_select_strategy = vision_feature_select_strategy
  87. self.vision_feature_layer = vision_feature_layer
  88. if isinstance(vision_config, dict):
  89. vision_config["model_type"] = vision_config.get("model_type", "clip_vision_model")
  90. vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config)
  91. elif vision_config is None:
  92. vision_config = CONFIG_MAPPING["clip_vision_model"](
  93. intermediate_size=4096,
  94. hidden_size=1024,
  95. patch_size=14,
  96. image_size=336,
  97. num_hidden_layers=24,
  98. num_attention_heads=16,
  99. vocab_size=32000,
  100. projection_dim=768,
  101. )
  102. self.vision_config = vision_config
  103. if isinstance(text_config, dict):
  104. text_config["model_type"] = text_config.get("model_type", "llama")
  105. text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
  106. elif text_config is None:
  107. text_config = CONFIG_MAPPING["llama"]()
  108. self.text_config = text_config
  109. self.multimodal_projector_bias = multimodal_projector_bias
  110. super().__init__(**kwargs)
  111. __all__ = ["LlavaConfig"]