sthui/SimpleSeg
010
1from transformers.configuration_utils import PretrainedConfig2from transformers.utils import logging3from typing import Optional, Union4 5logger = logging.get_logger(__name__)6 7DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP = {}8 9 10class DeepseekV3Config(PretrainedConfig):11 r"""12 This is the configuration class to store the configuration of a [`DeepseekV3Model`]. It is used to instantiate an DeepSeek13 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the14 defaults will yield a similar configuration to that of the DeepSeek-V3.15 16 Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the17 documentation from [`PretrainedConfig`] for more information.18 19 Copy from https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/configuration_deepseek.py20 21 Args:22 vocab_size (`int`, *optional*, defaults to 129280):23 Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the24 `inputs_ids` passed when calling [`DeepseekV3Model`]25 hidden_size (`int`, *optional*, defaults to 4096):26 Dimension of the hidden representations.27 intermediate_size (`int`, *optional*, defaults to 11008):28 Dimension of the MLP representations.29 moe_intermediate_size (`int`, *optional*, defaults to 1407):30 Dimension of the MoE representations.31 num_hidden_layers (`int`, *optional*, defaults to 32):32 Number of hidden layers in the Transformer decoder.33 num_nextn_predict_layers (`int`, *optional*, defaults to 1):34 Number of nextn predict layers in the DeepSeekV3 Model.35 num_attention_heads (`int`, *optional*, defaults to 32):36 Number of attention heads for each attention layer in the Transformer decoder.37 n_shared_experts (`int`, *optional*, defaults to None):38 Number of shared experts, None means dense model.39 n_routed_experts (`int`, *optional*, defaults to None):40 Number of routed experts, None means dense model.41 routed_scaling_factor (`float`, *optional*, defaults to 1.0):42 Scaling factor or routed experts.43 topk_method (`str`, *optional*, defaults to `gready`):44 Topk method used in routed gate.45 n_group (`int`, *optional*, defaults to None):46 Number of groups for routed experts.47 topk_group (`int`, *optional*, defaults to None):48 Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).49 num_experts_per_tok (`int`, *optional*, defaults to None):50 Number of selected experts, None means dense model.51 moe_layer_freq (`int`, *optional*, defaults to 1):52 The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.53 first_k_dense_replace (`int`, *optional*, defaults to 0):54 Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).55 \--k dense layers--/56 norm_topk_prob (`bool`, *optional*, defaults to False):57 Whether to normalize the weights of the routed experts.58 scoring_func (`str`, *optional*, defaults to 'softmax'):59 Method of computing expert weights.60 aux_loss_alpha (`float`, *optional*, defaults to 0.001):61 Auxiliary loss weight coefficient.62 seq_aux = (`bool`, *optional*, defaults to True):63 Whether to compute the auxiliary loss for each individual sample.64 num_key_value_heads (`int`, *optional*):65 This is the number of key_value heads that should be used to implement Grouped Query Attention. If66 `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if67 `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When68 converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed69 by meanpooling all the original heads within that group. For more details checkout [this70 paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to71 `num_attention_heads`.72 hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):73 The non-linear activation function (function or string) in the decoder.74 max_position_embeddings (`int`, *optional*, defaults to 2048):75 The maximum sequence length that this model might ever be used with.76 initializer_range (`float`, *optional*, defaults to 0.02):77 The standard deviation of the truncated_normal_initializer for initializing all weight matrices.78 rms_norm_eps (`float`, *optional*, defaults to 1e-06):79 The epsilon used by the rms normalization layers.80 use_cache (`bool`, *optional*, defaults to `True`):81 Whether or not the model should return the last key/values attentions (not used by all models). Only82 relevant if `config.is_decoder=True`.83 pad_token_id (`int`, *optional*):84 Padding token id.85 bos_token_id (`int`, *optional*, defaults to 1):86 Beginning of stream token id.87 eos_token_id (`int`, *optional*, defaults to 2):88 End of stream token id.89 pretraining_tp (`int`, *optional*, defaults to 1):90 Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this91 document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is92 necessary to ensure exact reproducibility of the pretraining results. Please refer to [this93 issue](https://github.com/pytorch/pytorch/issues/76232).94 tie_word_embeddings (`bool`, *optional*, defaults to `False`):95 Whether to tie weight embeddings96 rope_theta (`float`, *optional*, defaults to 10000.0):97 The base period of the RoPE embeddings.98 rope_scaling (`Dict`, *optional*):99 Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling100 strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is101 `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update102 `max_position_embeddings` to the expected new maximum.103 attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):104 Whether to use a bias in the query, key, value and output projection layers during self-attention.105 attention_dropout (`float`, *optional*, defaults to 0.0):106 The dropout ratio for the attention probabilities.107 108 ```python109 >>> from transformers import DeepseekV3Model, DeepseekV3Config110 111 >>> # Initializing a Deepseek-V3 style configuration112 >>> configuration = DeepseekV3Config()113 114 >>> # Accessing the model configuration115 >>> configuration = model.config116 ```"""117 118 model_type = "deepseek_v3"119 keys_to_ignore_at_inference = ["past_key_values"]120 121 def __init__(122 self,123 vocab_size=129280,124 hidden_size=7168,125 intermediate_size=18432,126 moe_intermediate_size=2048,127 num_hidden_layers=61,128 num_nextn_predict_layers=1,129 num_attention_heads=128,130 num_key_value_heads=128,131 n_shared_experts=1,132 n_routed_experts=256,133 ep_size=1,134 routed_scaling_factor=2.5,135 kv_lora_rank=512,136 q_lora_rank=1536,137 qk_rope_head_dim=64,138 v_head_dim=128,139 qk_nope_head_dim=128,140 topk_method="noaux_tc",141 n_group=8,142 topk_group=4,143 num_experts_per_tok=8,144 moe_layer_freq=1,145 first_k_dense_replace=3,146 norm_topk_prob=True,147 scoring_func="sigmoid",148 aux_loss_alpha=0.001,149 seq_aux=True,150 hidden_act="silu",151 max_position_embeddings=4096,152 initializer_range=0.02,153 rms_norm_eps=1e-6,154 use_cache=True,155 pad_token_id=None,156 bos_token_id=0,157 eos_token_id=1,158 pretraining_tp=1,159 tie_word_embeddings=False,160 rope_theta=10000.0,161 rope_scaling=None,162 attention_bias=False,163 attention_dropout=0.0,164 **kwargs,165 ):166 self.vocab_size = vocab_size167 self.max_position_embeddings = max_position_embeddings168 self.hidden_size = hidden_size169 self.intermediate_size = intermediate_size170 self.moe_intermediate_size = moe_intermediate_size171 self.num_hidden_layers = num_hidden_layers172 self.num_nextn_predict_layers = num_nextn_predict_layers173 self.num_attention_heads = num_attention_heads174 self.n_shared_experts = n_shared_experts175 self.n_routed_experts = n_routed_experts176 self.ep_size = ep_size177 self.routed_scaling_factor = routed_scaling_factor178 self.kv_lora_rank = kv_lora_rank179 self.q_lora_rank = q_lora_rank180 self.qk_rope_head_dim = qk_rope_head_dim181 self.v_head_dim = v_head_dim182 self.qk_nope_head_dim = qk_nope_head_dim183 self.topk_method = topk_method184 self.n_group = n_group185 self.topk_group = topk_group186 self.num_experts_per_tok = num_experts_per_tok187 self.moe_layer_freq = moe_layer_freq188 self.first_k_dense_replace = first_k_dense_replace189 self.norm_topk_prob = norm_topk_prob190 self.scoring_func = scoring_func191 self.aux_loss_alpha = aux_loss_alpha192 self.seq_aux = seq_aux193 # for backward compatibility194 if num_key_value_heads is None:195 num_key_value_heads = num_attention_heads196 197 self.num_key_value_heads = num_key_value_heads198 self.hidden_act = hidden_act199 self.initializer_range = initializer_range200 self.rms_norm_eps = rms_norm_eps201 self.pretraining_tp = pretraining_tp202 self.use_cache = use_cache203 self.rope_theta = rope_theta204 self.rope_scaling = rope_scaling205 self.attention_bias = attention_bias206 self.attention_dropout = attention_dropout207 208 super().__init__(209 pad_token_id=pad_token_id,210 bos_token_id=bos_token_id,211 eos_token_id=eos_token_id,212 tie_word_embeddings=tie_word_embeddings,213 **kwargs,214 )215 216 217class MoonViTConfig(PretrainedConfig):218 model_type = "moonvit"219 220 def __init__(221 self,222 patch_size: int = 14,223 init_pos_emb_height: int = 64,224 init_pos_emb_width: int = 64,225 num_attention_heads: int = 16,226 num_hidden_layers: int = 27,227 hidden_size: int = 1152,228 intermediate_size: int = 4304,229 merge_kernel_size: tuple[int, int] = (2, 2),230 **kwargs,231 ):232 super().__init__(**kwargs)233 self.patch_size = patch_size234 # Positional embedding config235 self.init_pos_emb_height = init_pos_emb_height236 self.init_pos_emb_width = init_pos_emb_width237 # Transformer config238 self.num_hidden_layers = num_hidden_layers239 self.num_attention_heads = num_attention_heads240 self.hidden_size = hidden_size241 self.intermediate_size = intermediate_size242 # Patch merger config243 self.merge_kernel_size = merge_kernel_size244 245 246class KimiVLConfig(PretrainedConfig):247 model_type = "kimi_vl"248 249 def __init__(250 self,251 vision_config: Optional[Union[dict, MoonViTConfig]] = None,252 text_config: Optional[Union[dict, DeepseekV3Config]] = None,253 ignore_index: int = -100,254 media_placeholder_token_id: int = 163605,255 pad_token_id: int = 0,256 **kwargs,257 ):258 if vision_config is None:259 vision_config = MoonViTConfig()260 elif isinstance(vision_config, dict):261 vision_config = MoonViTConfig(**vision_config)262 self.vision_config = vision_config263 264 if text_config is None:265 text_config = DeepseekV3Config()266 elif isinstance(text_config, dict):267 text_config = DeepseekV3Config(**text_config)268 self.text_config = text_config269 270 self.ignore_index = ignore_index271 self.media_placeholder_token_id = media_placeholder_token_id272 273 attn_implementation = kwargs.get("attn_implementation")274 if attn_implementation is not None:275 if attn_implementation in ["eager", "flash_attention_2"]:276 self._attn_implementation = attn_implementation277 self.vision_config._attn_implementation = attn_implementation278 self.text_config._attn_implementation = attn_implementation279 else:280 raise ValueError(281 f"Invalid attention implementation: {attn_implementation}"282 )283 284 super().__init__(pad_token_id=pad_token_id, **kwargs)285 