Spec-Vision-V1 / configuration_spec_vision.py
SVECTOR-OFFICIAL's picture
Upload configuration_spec_vision.py with huggingface_hub
b76ef48 verified
raw
history blame
7.18 kB
# coding=utf-8
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Spec-Vision model configuration"""
from typing import Dict, Optional, Union
from transformers.configuration_utils import PretrainedConfig
from transformers.utils import logging
logger = logging.get_logger(__name__)
class SpecVisionConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`SpecVisionModel`]. It is used to instantiate a Spec-Vision
model according to the specified arguments, defining the model architecture.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PretrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 32064):
Vocabulary size of the model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`SpecVisionModel`].
hidden_size (`int`, *optional*, defaults to 3072):
Dimension of the hidden representations.
intermediate_size (`int`, *optional*, defaults to 8192):
Dimension of the MLP representations.
num_hidden_layers (`int`, *optional*, defaults to 32):
Number of hidden layers in the Transformer decoder.
num_attention_heads (`int`, *optional*, defaults to 32):
Number of attention heads for each attention layer in the Transformer decoder.
num_key_value_heads (`int`, *optional*):
Number of key/value heads for implementing Grouped Query Attention.
resid_pdrop (`float`, *optional*, defaults to 0.0):
Dropout probability for MLP outputs.
embd_pdrop (`float`, *optional*, defaults to 0.0):
The dropout ratio for embeddings.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio after computing attention scores.
hidden_act (`str`, *optional*, defaults to `"silu"`):
The non-linear activation function in the decoder.
max_position_embeddings (`int`, *optional*, defaults to 4096):
The maximum sequence length that this model might ever be used with.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation for initializing all weight matrices.
rms_norm_eps (`float`, *optional*, defaults to 1e-5):
The epsilon value used for RMSNorm.
use_cache (`bool`, *optional*, defaults to `True`):
Whether to use the past key/values attentions for faster inference.
rope_theta (`float`, *optional*, defaults to 10000.0):
The base period of the RoPE embeddings.
rope_scaling (`dict`, *optional*):
Configuration for RoPE scaling strategy.
embd_layer (`dict`, *optional*):
Configuration for the embedding layer, including image embedding settings.
"""
model_type = "spec_vision"
keys_to_ignore_at_inference = ["past_key_values"]
def __init__(
self,
vocab_size: int = 32064,
hidden_size: int = 3072,
intermediate_size: int = 8192,
num_hidden_layers: int = 32,
num_attention_heads: int = 32,
num_key_value_heads: Optional[int] = None,
resid_pdrop: float = 0.0,
embd_pdrop: float = 0.0,
attention_dropout: float = 0.0,
hidden_act: str = "silu",
max_position_embeddings: int = 4096,
initializer_range: float = 0.02,
rms_norm_eps: float = 1e-5,
use_cache: bool = True,
rope_theta: float = 10000.0,
rope_scaling: Optional[Dict] = None,
embd_layer: Dict[str, Union[str, bool]] = {
"embedding_cls": "image",
"hd_transform_order": "sub_glb",
"projection_cls": "mlp",
"use_hd_transform": True,
"with_learnable_separator": True
},
bos_token_id: int = 1,
eos_token_id: int = 32000,
pad_token_id: int = 32000,
tie_word_embeddings: bool = False,
**kwargs,
):
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads or num_attention_heads
self.resid_pdrop = resid_pdrop
self.embd_pdrop = embd_pdrop
self.attention_dropout = attention_dropout
self.hidden_act = hidden_act
self.max_position_embeddings = max_position_embeddings
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.rope_theta = rope_theta
self.rope_scaling = rope_scaling
self.embd_layer = embd_layer
super().__init__(
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
pad_token_id=pad_token_id,
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
def _rope_scaling_validation(self):
"""
Validate the `rope_scaling` configuration.
"""
if self.rope_scaling is None:
return
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
raise ValueError(
"`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
f"got {self.rope_scaling}"
)
rope_scaling_type = self.rope_scaling.get("type", None)
rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
if rope_scaling_type is None or rope_scaling_type not in ["su", "yarn"]:
raise ValueError(f"`rope_scaling`'s type field must be one of ['su', 'yarn'], got {rope_scaling_type}")
head_dim = self.hidden_size // self.num_attention_heads // 2
for factor, name in [(rope_scaling_short_factor, "short_factor"), (rope_scaling_long_factor, "long_factor")]:
if not (isinstance(factor, list) and all(isinstance(x, (int, float)) for x in factor)):
raise ValueError(f"`rope_scaling`'s {name} field must be a list of numbers, got {factor}")
if len(factor) != head_dim:
raise ValueError(f"`rope_scaling`'s {name} field must have length {head_dim}, got {len(factor)}")