[Model] Add support for Nanbeige4.2 (#32151)
Co-authored-by: root <lizongqiang@kanzhun.com> Co-authored-by: Xinyuan Tong <xinyuantong.cs@gmail.com>
This commit is contained in:
@@ -52,6 +52,7 @@ from sglang.srt.configs.muse_glimmer import (
|
|||||||
MuseGlimmerAssistantConfig,
|
MuseGlimmerAssistantConfig,
|
||||||
MuseGlimmerConfig,
|
MuseGlimmerConfig,
|
||||||
)
|
)
|
||||||
|
from sglang.srt.configs.nanbeige import NanbeigeConfig
|
||||||
from sglang.srt.configs.nano_nemotron_vl import (
|
from sglang.srt.configs.nano_nemotron_vl import (
|
||||||
NemotronH_Nano_Omni_Reasoning_V3_Config,
|
NemotronH_Nano_Omni_Reasoning_V3_Config,
|
||||||
NemotronH_Nano_VL_V2_Config,
|
NemotronH_Nano_VL_V2_Config,
|
||||||
@@ -130,6 +131,7 @@ __all__ = [
|
|||||||
"NemotronHPuzzleConfig",
|
"NemotronHPuzzleConfig",
|
||||||
"NemotronH_Nano_VL_V2_Config",
|
"NemotronH_Nano_VL_V2_Config",
|
||||||
"NemotronH_Nano_Omni_Reasoning_V3_Config",
|
"NemotronH_Nano_Omni_Reasoning_V3_Config",
|
||||||
|
"NanbeigeConfig",
|
||||||
"JetNemotronConfig",
|
"JetNemotronConfig",
|
||||||
"JetVLMConfig",
|
"JetVLMConfig",
|
||||||
"MiniCPMHybridConfig",
|
"MiniCPMHybridConfig",
|
||||||
|
|||||||
@@ -1148,6 +1148,9 @@ class ModelConfig:
|
|||||||
if "IQuestLoopCoderForCausalLM" in self.hf_config.architectures:
|
if "IQuestLoopCoderForCausalLM" in self.hf_config.architectures:
|
||||||
loop_num = getattr(self.hf_text_config, "loop_num", 1)
|
loop_num = getattr(self.hf_text_config, "loop_num", 1)
|
||||||
self.num_attention_layers = int(self.num_hidden_layers * int(loop_num))
|
self.num_attention_layers = int(self.num_hidden_layers * int(loop_num))
|
||||||
|
if "NanbeigeForCausalLM" in self.hf_config.architectures:
|
||||||
|
num_loops = getattr(self.hf_text_config, "num_loops", 1)
|
||||||
|
self.num_attention_layers = int(self.num_hidden_layers * int(num_loops))
|
||||||
if "WhisperForConditionalGeneration" in self.hf_config.architectures:
|
if "WhisperForConditionalGeneration" in self.hf_config.architectures:
|
||||||
# Whisper has unique layer ID scheme:
|
# Whisper has unique layer ID scheme:
|
||||||
# - Encoder self-attention: 0 to encoder_layers-1 (no KV cache)
|
# - Encoder self-attention: 0 to encoder_layers-1 (no KV cache)
|
||||||
|
|||||||
@@ -0,0 +1,217 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
||||||
|
#
|
||||||
|
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
||||||
|
# and OPT implementations in this library. It has been modified from its
|
||||||
|
# original forms to accommodate minor architectural differences compared
|
||||||
|
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
||||||
|
#
|
||||||
|
# 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.
|
||||||
|
"""Nanbeige model configuration"""
|
||||||
|
|
||||||
|
from transformers.configuration_utils import PretrainedConfig
|
||||||
|
from transformers.utils import logging
|
||||||
|
|
||||||
|
logger = logging.get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class NanbeigeConfig(PretrainedConfig):
|
||||||
|
r"""
|
||||||
|
This is the configuration class to store the configuration of a [`NanbeigeModel`]. It is used to instantiate an Nanbeige
|
||||||
|
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 LLaMA-7B.
|
||||||
|
|
||||||
|
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 32000):
|
||||||
|
Vocabulary size of the Nanbeige model. Defines the number of different tokens that can be represented by the
|
||||||
|
`inputs_ids` passed when calling [`NanbeigeModel`]
|
||||||
|
hidden_size (`int`, *optional*, defaults to 4096):
|
||||||
|
Dimension of the hidden representations.
|
||||||
|
intermediate_size (`int`, *optional*, defaults to 11008):
|
||||||
|
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*):
|
||||||
|
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
||||||
|
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
||||||
|
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
||||||
|
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
||||||
|
by meanpooling all the original heads within that group. For more details checkout [this
|
||||||
|
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
||||||
|
`num_attention_heads`.
|
||||||
|
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
||||||
|
The non-linear activation function (function or string) in the decoder.
|
||||||
|
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
||||||
|
The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
|
||||||
|
Llama 2 up to 4096, CodeLlama up to 16384.
|
||||||
|
initializer_range (`float`, *optional*, defaults to 0.02):
|
||||||
|
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
||||||
|
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
||||||
|
The epsilon used by the rms normalization layers.
|
||||||
|
use_cache (`bool`, *optional*, defaults to `True`):
|
||||||
|
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
||||||
|
relevant if `config.is_decoder=True`.
|
||||||
|
pad_token_id (`int`, *optional*):
|
||||||
|
Padding token id.
|
||||||
|
bos_token_id (`int`, *optional*, defaults to 1):
|
||||||
|
Beginning of stream token id.
|
||||||
|
eos_token_id (`int`, *optional*, defaults to 2):
|
||||||
|
End of stream token id.
|
||||||
|
pretraining_tp (`int`, *optional*, defaults to 1):
|
||||||
|
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
||||||
|
document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to understand more about it. This value is
|
||||||
|
necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
|
||||||
|
issue](https://github.com/pytorch/pytorch/issues/76232).
|
||||||
|
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
||||||
|
Whether to tie weight embeddings
|
||||||
|
rope_theta (`float`, *optional*, defaults to 10000.0):
|
||||||
|
The base period of the RoPE embeddings.
|
||||||
|
rope_scaling (`Dict`, *optional*):
|
||||||
|
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
||||||
|
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
|
||||||
|
`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
||||||
|
`max_position_embeddings` to the expected new maximum. See the following thread for more information on how
|
||||||
|
these scaling strategies behave:
|
||||||
|
https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
|
||||||
|
experimental feature, subject to breaking API changes in future versions.
|
||||||
|
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
||||||
|
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
||||||
|
attention_dropout (`float`, *optional*, defaults to 0.0):
|
||||||
|
The dropout ratio for the attention probabilities.
|
||||||
|
num_loops (`int`, *optional*, defaults to 1):
|
||||||
|
The number of loops for the loop model.
|
||||||
|
loop_loss_weights (`List[float]`, *optional*, defaults to `[]`):
|
||||||
|
The weights for the loop loss.
|
||||||
|
skip_loop_final_norm (`bool`, *optional*, defaults to `False`):
|
||||||
|
Whether to skip final norm after each loop (except the last one).
|
||||||
|
|
||||||
|
```python
|
||||||
|
>>> from configuration_nanbeige import NanbeigeConfig
|
||||||
|
>>> from modeling_nanbeige import NanbeigeModel
|
||||||
|
|
||||||
|
>>> # Initializing a Nanbeige nanbeige-7b style configuration
|
||||||
|
>>> configuration = NanbeigeConfig()
|
||||||
|
|
||||||
|
>>> # Initializing a model from the nanbeige-7b style configuration
|
||||||
|
>>> model = NanbeigeModel(configuration)
|
||||||
|
|
||||||
|
>>> # Accessing the model configuration
|
||||||
|
>>> configuration = model.config
|
||||||
|
```"""
|
||||||
|
|
||||||
|
model_type = "nanbeige"
|
||||||
|
keys_to_ignore_at_inference = ["past_key_values"]
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
vocab_size=166144,
|
||||||
|
hidden_size=3072,
|
||||||
|
intermediate_size=10752,
|
||||||
|
num_hidden_layers=22,
|
||||||
|
num_attention_heads=48,
|
||||||
|
num_key_value_heads=None,
|
||||||
|
head_dim=None,
|
||||||
|
hidden_act="silu",
|
||||||
|
max_position_embeddings=4096,
|
||||||
|
initializer_range=0.02,
|
||||||
|
rms_norm_eps=1e-5,
|
||||||
|
use_cache=True,
|
||||||
|
pad_token_id=None,
|
||||||
|
bos_token_id=1,
|
||||||
|
eos_token_id=2,
|
||||||
|
pretraining_tp=1,
|
||||||
|
tie_word_embeddings=False,
|
||||||
|
rope_theta=50000.0,
|
||||||
|
rope_scaling=None,
|
||||||
|
attention_bias=False,
|
||||||
|
attention_dropout=0.0,
|
||||||
|
num_loops=2,
|
||||||
|
loop_loss_weights=None,
|
||||||
|
skip_loop_final_norm=False,
|
||||||
|
**kwargs,
|
||||||
|
):
|
||||||
|
self.vocab_size = vocab_size
|
||||||
|
self.max_position_embeddings = max_position_embeddings
|
||||||
|
self.hidden_size = hidden_size
|
||||||
|
self.intermediate_size = intermediate_size
|
||||||
|
self.num_hidden_layers = num_hidden_layers
|
||||||
|
self.num_attention_heads = num_attention_heads
|
||||||
|
|
||||||
|
# Add head_dim logic
|
||||||
|
if head_dim is not None:
|
||||||
|
self.head_dim = head_dim
|
||||||
|
else:
|
||||||
|
self.head_dim = hidden_size // num_attention_heads
|
||||||
|
|
||||||
|
# for backward compatibility
|
||||||
|
if num_key_value_heads is None:
|
||||||
|
num_key_value_heads = num_attention_heads
|
||||||
|
|
||||||
|
self.num_key_value_heads = num_key_value_heads
|
||||||
|
self.hidden_act = hidden_act
|
||||||
|
self.initializer_range = initializer_range
|
||||||
|
self.rms_norm_eps = rms_norm_eps
|
||||||
|
self.pretraining_tp = pretraining_tp
|
||||||
|
self.use_cache = use_cache
|
||||||
|
self.rope_theta = rope_theta
|
||||||
|
self.rope_scaling = rope_scaling
|
||||||
|
self._rope_scaling_validation()
|
||||||
|
self.attention_bias = attention_bias
|
||||||
|
self.attention_dropout = attention_dropout
|
||||||
|
|
||||||
|
self.num_loops = num_loops
|
||||||
|
self.loop_loss_weights = (
|
||||||
|
loop_loss_weights if loop_loss_weights is not None else []
|
||||||
|
)
|
||||||
|
self.skip_loop_final_norm = skip_loop_final_norm
|
||||||
|
|
||||||
|
super().__init__(
|
||||||
|
pad_token_id=pad_token_id,
|
||||||
|
bos_token_id=bos_token_id,
|
||||||
|
eos_token_id=eos_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) != 2:
|
||||||
|
raise ValueError(
|
||||||
|
"`rope_scaling` must be a dictionary with two fields, `type` and `factor`, "
|
||||||
|
f"got {self.rope_scaling}"
|
||||||
|
)
|
||||||
|
rope_scaling_type = self.rope_scaling.get("type", None)
|
||||||
|
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
||||||
|
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
|
||||||
|
raise ValueError(
|
||||||
|
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
rope_scaling_factor is None
|
||||||
|
or not isinstance(rope_scaling_factor, float)
|
||||||
|
or rope_scaling_factor <= 1.0
|
||||||
|
):
|
||||||
|
raise ValueError(
|
||||||
|
f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}"
|
||||||
|
)
|
||||||
@@ -97,6 +97,7 @@ class FunctionCallParser:
|
|||||||
"step3p5": Qwen3CoderDetector,
|
"step3p5": Qwen3CoderDetector,
|
||||||
"minimax-m2": MinimaxM2Detector,
|
"minimax-m2": MinimaxM2Detector,
|
||||||
"minimax-m3": MinimaxM3Detector,
|
"minimax-m3": MinimaxM3Detector,
|
||||||
|
"nanbeige": Qwen3CoderDetector,
|
||||||
"trinity": TrinityDetector,
|
"trinity": TrinityDetector,
|
||||||
"interns1": InternlmDetector,
|
"interns1": InternlmDetector,
|
||||||
"hermes": HermesDetector,
|
"hermes": HermesDetector,
|
||||||
|
|||||||
@@ -18,12 +18,23 @@ class AttentionAndMoeLayers(NamedTuple):
|
|||||||
mha_companion_layers: list[Any]
|
mha_companion_layers: list[Any]
|
||||||
|
|
||||||
|
|
||||||
|
def _get_loop_num(hf_config: Any) -> int:
|
||||||
|
# Nanbeige uses num_loops; IQuestLoopCoder uses loop_num.
|
||||||
|
return int(getattr(hf_config, "loop_num", getattr(hf_config, "num_loops", 1)) or 1)
|
||||||
|
|
||||||
|
|
||||||
def compute_attention_and_moe_layers(layer_model: Any) -> AttentionAndMoeLayers:
|
def compute_attention_and_moe_layers(layer_model: Any) -> AttentionAndMoeLayers:
|
||||||
attention_layers: list[Any] = []
|
attention_layers: list[Any] = []
|
||||||
moe_layers: list[Any] = []
|
moe_layers: list[Any] = []
|
||||||
moe_fusions: list[Any] = []
|
moe_fusions: list[Any] = []
|
||||||
dsa_indexers: list[Any] = []
|
dsa_indexers: list[Any] = []
|
||||||
mha_companion_layers: list[Any] = []
|
mha_companion_layers: list[Any] = []
|
||||||
|
|
||||||
|
# Loop models (Nanbeige / IQuestLoopCoder) store one RadixAttention per loop
|
||||||
|
# in a ModuleList. Prefill CUDA graph indexes by layer_id, so expand and
|
||||||
|
# reorder to a dense [0..N) list.
|
||||||
|
has_loop_attn = False
|
||||||
|
|
||||||
layers = layer_model.layers
|
layers = layer_model.layers
|
||||||
if isinstance(layers, nn.ModuleDict):
|
if isinstance(layers, nn.ModuleDict):
|
||||||
layers = layers.values()
|
layers = layers.values()
|
||||||
@@ -62,11 +73,16 @@ def compute_attention_and_moe_layers(layer_model: Any) -> AttentionAndMoeLayers:
|
|||||||
# Mamba layer with split op support - store the layer itself
|
# Mamba layer with split op support - store the layer itself
|
||||||
attn_layer = layer
|
attn_layer = layer
|
||||||
|
|
||||||
# Keep these lists aligned with global layer ids. Pipeline-parallel
|
if isinstance(attn_layer, nn.ModuleList):
|
||||||
# models retain placeholders outside the local stage, while real
|
attention_layers.extend(attn_layer)
|
||||||
# attention modules use their global layer_id during graph replay.
|
mha_companion_layers.extend([mha_companion_layer] * len(attn_layer))
|
||||||
attention_layers.append(attn_layer)
|
has_loop_attn = True
|
||||||
mha_companion_layers.append(mha_companion_layer)
|
else:
|
||||||
|
# Keep these lists aligned with global layer ids. Pipeline-parallel
|
||||||
|
# models retain placeholders outside the local stage, while real
|
||||||
|
# attention modules use their global layer_id during graph replay.
|
||||||
|
attention_layers.append(attn_layer)
|
||||||
|
mha_companion_layers.append(mha_companion_layer)
|
||||||
|
|
||||||
moe_block = None
|
moe_block = None
|
||||||
moe_fusion = None
|
moe_fusion = None
|
||||||
@@ -93,6 +109,10 @@ def compute_attention_and_moe_layers(layer_model: Any) -> AttentionAndMoeLayers:
|
|||||||
dsa_indexer = layer.self_attn.indexer
|
dsa_indexer = layer.self_attn.indexer
|
||||||
dsa_indexers.append(dsa_indexer)
|
dsa_indexers.append(dsa_indexer)
|
||||||
|
|
||||||
|
# Reorder so attention_layers[i] matches RadixAttention.layer_id.
|
||||||
|
if has_loop_attn:
|
||||||
|
attention_layers.sort(key=lambda x: x.layer_id)
|
||||||
|
|
||||||
return AttentionAndMoeLayers(
|
return AttentionAndMoeLayers(
|
||||||
attention_layers,
|
attention_layers,
|
||||||
moe_layers,
|
moe_layers,
|
||||||
@@ -132,7 +152,7 @@ def resolve_layer_indices(
|
|||||||
num_effective_layers = pp_range.end_layer - pp_range.start_layer
|
num_effective_layers = pp_range.end_layer - pp_range.start_layer
|
||||||
|
|
||||||
# For LoopCoder models, each loop has its own layer_id, so we need to multiply by loop_num
|
# For LoopCoder models, each loop has its own layer_id, so we need to multiply by loop_num
|
||||||
loop_num = getattr(model_config.hf_config, "loop_num", 1)
|
loop_num = _get_loop_num(model_config.hf_config)
|
||||||
if loop_num > 1:
|
if loop_num > 1:
|
||||||
num_effective_layers = num_effective_layers * loop_num
|
num_effective_layers = num_effective_layers * loop_num
|
||||||
|
|
||||||
|
|||||||
@@ -158,6 +158,9 @@ def _resolve_dflash_aux_hidden_state(
|
|||||||
f"in config. Got target={target_num_layers}."
|
f"in config. Got target={target_num_layers}."
|
||||||
)
|
)
|
||||||
target_num_layers = int(target_num_layers)
|
target_num_layers = int(target_num_layers)
|
||||||
|
# Loop models: target layer ids span num_hidden_layers * num_loops.
|
||||||
|
num_loops = getattr(model_config.hf_text_config, "num_loops", 1)
|
||||||
|
target_num_layers = target_num_layers * int(num_loops)
|
||||||
|
|
||||||
if (
|
if (
|
||||||
trained_target_layers is not None
|
trained_target_layers is not None
|
||||||
|
|||||||
@@ -0,0 +1,626 @@
|
|||||||
|
import logging
|
||||||
|
from typing import Iterable, List, Optional, Tuple, Union
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from torch import nn
|
||||||
|
|
||||||
|
from sglang.srt.configs import NanbeigeConfig
|
||||||
|
from sglang.srt.distributed import get_pp_group
|
||||||
|
from sglang.srt.layers.activation import SiluAndMul
|
||||||
|
from sglang.srt.layers.dp_attention import is_dp_attention_enabled
|
||||||
|
from sglang.srt.layers.layernorm import RMSNorm
|
||||||
|
from sglang.srt.layers.linear import (
|
||||||
|
MergedColumnParallelLinear,
|
||||||
|
QKVParallelLinear,
|
||||||
|
RowParallelLinear,
|
||||||
|
)
|
||||||
|
from sglang.srt.layers.logits_processor import LogitsProcessor
|
||||||
|
from sglang.srt.layers.pooler import EmbeddingPoolerOutput, Pooler, PoolingType
|
||||||
|
from sglang.srt.layers.quantization.base_config import QuantizationConfig
|
||||||
|
from sglang.srt.layers.radix_attention import RadixAttention
|
||||||
|
from sglang.srt.layers.rotary_embedding import get_rope
|
||||||
|
from sglang.srt.layers.utils import PPMissingLayer, get_layer_id
|
||||||
|
from sglang.srt.layers.vocab_parallel_embedding import (
|
||||||
|
ParallelLMHead,
|
||||||
|
VocabParallelEmbedding,
|
||||||
|
)
|
||||||
|
from sglang.srt.model_executor.forward_batch_info import ForwardBatch, PPProxyTensors
|
||||||
|
from sglang.srt.model_loader.weight_utils import default_weight_loader
|
||||||
|
from sglang.srt.runtime_context import get_parallel
|
||||||
|
from sglang.srt.utils import add_prefix, make_layers
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class NanbeigeRMSNorm(nn.Module):
|
||||||
|
def __init__(self, hidden_size, eps=1e-6):
|
||||||
|
"""
|
||||||
|
NanbeigeRMSNorm is equivalent to T5LayerNorm
|
||||||
|
"""
|
||||||
|
super().__init__()
|
||||||
|
self.weight = nn.Parameter(torch.ones(hidden_size))
|
||||||
|
self.variance_epsilon = eps
|
||||||
|
|
||||||
|
def forward(self, hidden_states):
|
||||||
|
input_dtype = hidden_states.dtype
|
||||||
|
hidden_states = hidden_states.to(torch.float32)
|
||||||
|
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
||||||
|
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
||||||
|
return self.weight * hidden_states.to(input_dtype)
|
||||||
|
|
||||||
|
|
||||||
|
class NanbeigeMLP(nn.Module):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
hidden_size: int,
|
||||||
|
intermediate_size: int,
|
||||||
|
hidden_act: str,
|
||||||
|
quant_config: Optional[QuantizationConfig] = None,
|
||||||
|
prefix: str = "",
|
||||||
|
) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self.gate_up_proj = MergedColumnParallelLinear(
|
||||||
|
hidden_size,
|
||||||
|
[intermediate_size] * 2,
|
||||||
|
bias=False,
|
||||||
|
quant_config=quant_config,
|
||||||
|
prefix=add_prefix("gate_up_proj", prefix),
|
||||||
|
)
|
||||||
|
self.down_proj = RowParallelLinear(
|
||||||
|
intermediate_size,
|
||||||
|
hidden_size,
|
||||||
|
bias=False,
|
||||||
|
quant_config=quant_config,
|
||||||
|
prefix=add_prefix("down_proj", prefix),
|
||||||
|
)
|
||||||
|
if hidden_act != "silu":
|
||||||
|
raise ValueError(
|
||||||
|
f"Unsupported activation: {hidden_act}. Only silu is supported for now."
|
||||||
|
)
|
||||||
|
self.act_fn = SiluAndMul()
|
||||||
|
|
||||||
|
def forward(self, x, use_reduce_scatter: bool = False):
|
||||||
|
gate_up, _ = self.gate_up_proj(x)
|
||||||
|
x = self.act_fn(gate_up)
|
||||||
|
x, _ = self.down_proj(
|
||||||
|
x,
|
||||||
|
skip_all_reduce=use_reduce_scatter,
|
||||||
|
)
|
||||||
|
return x
|
||||||
|
|
||||||
|
|
||||||
|
class NanbeigeAttention(nn.Module):
|
||||||
|
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
config: NanbeigeConfig,
|
||||||
|
layer_id: Optional[int] = None,
|
||||||
|
quant_config: Optional[QuantizationConfig] = None,
|
||||||
|
prefix: str = "",
|
||||||
|
):
|
||||||
|
super().__init__()
|
||||||
|
self.config = config
|
||||||
|
self.layer_id = layer_id
|
||||||
|
tp_size = get_parallel().tp_size
|
||||||
|
|
||||||
|
self.attention_dropout = config.attention_dropout
|
||||||
|
self.hidden_size = config.hidden_size
|
||||||
|
|
||||||
|
self.total_num_heads = config.num_attention_heads
|
||||||
|
assert self.total_num_heads % tp_size == 0, (
|
||||||
|
"num_attention_heads must be divisible by tp_size."
|
||||||
|
)
|
||||||
|
self.num_heads = self.total_num_heads // tp_size
|
||||||
|
self.head_dim = getattr(
|
||||||
|
config, "head_dim", self.hidden_size // self.total_num_heads
|
||||||
|
)
|
||||||
|
|
||||||
|
self.total_num_kv_heads = config.num_key_value_heads
|
||||||
|
assert self.total_num_kv_heads >= tp_size, (
|
||||||
|
"num_key_value_heads must be greater than tp_size."
|
||||||
|
)
|
||||||
|
assert self.total_num_kv_heads % tp_size == 0, (
|
||||||
|
"num_key_value_heads must be divisible by tp_size."
|
||||||
|
)
|
||||||
|
self.num_kv_heads = config.num_key_value_heads // tp_size
|
||||||
|
|
||||||
|
self.q_size = self.num_heads * self.head_dim
|
||||||
|
self.kv_size = self.num_kv_heads * self.head_dim
|
||||||
|
|
||||||
|
self.max_position_embeddings = config.max_position_embeddings
|
||||||
|
self.rope_theta = config.rope_theta
|
||||||
|
self.is_causal = True
|
||||||
|
self.scaling = self.head_dim**-0.5
|
||||||
|
self.total_layers = config.num_hidden_layers
|
||||||
|
self.num_loops = config.num_loops
|
||||||
|
|
||||||
|
self.qkv_proj = QKVParallelLinear(
|
||||||
|
self.hidden_size,
|
||||||
|
self.head_dim,
|
||||||
|
self.total_num_heads,
|
||||||
|
self.total_num_kv_heads,
|
||||||
|
bias=False,
|
||||||
|
quant_config=quant_config,
|
||||||
|
prefix=add_prefix("qkv_proj", prefix),
|
||||||
|
)
|
||||||
|
|
||||||
|
self.o_proj = RowParallelLinear(
|
||||||
|
self.total_num_heads * self.head_dim,
|
||||||
|
self.hidden_size,
|
||||||
|
bias=False,
|
||||||
|
quant_config=quant_config,
|
||||||
|
prefix=add_prefix("o_proj", prefix),
|
||||||
|
)
|
||||||
|
|
||||||
|
self.attn = nn.ModuleList()
|
||||||
|
base_layer_id = layer_id
|
||||||
|
for loop_idx in range(self.num_loops):
|
||||||
|
layer_id = base_layer_id + loop_idx * self.total_layers
|
||||||
|
self.attn.append(
|
||||||
|
RadixAttention(
|
||||||
|
self.num_heads,
|
||||||
|
self.head_dim,
|
||||||
|
self.scaling,
|
||||||
|
num_kv_heads=self.num_kv_heads,
|
||||||
|
layer_id=layer_id,
|
||||||
|
quant_config=quant_config,
|
||||||
|
prefix=add_prefix("attn", prefix),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
self.rotary_emb = get_rope(
|
||||||
|
self.head_dim,
|
||||||
|
rotary_dim=self.head_dim,
|
||||||
|
max_position=self.max_position_embeddings,
|
||||||
|
base=self.rope_theta,
|
||||||
|
rope_scaling=self.config.rope_scaling,
|
||||||
|
)
|
||||||
|
|
||||||
|
def forward(
|
||||||
|
self,
|
||||||
|
positions: torch.Tensor,
|
||||||
|
hidden_states: torch.Tensor,
|
||||||
|
forward_batch: ForwardBatch,
|
||||||
|
loop_idx: int,
|
||||||
|
) -> torch.Tensor:
|
||||||
|
qkv, _ = self.qkv_proj(hidden_states)
|
||||||
|
q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
|
||||||
|
q, k = self.rotary_emb(positions, q, k)
|
||||||
|
attn_output = self.attn[loop_idx](q, k, v, forward_batch)
|
||||||
|
output, _ = self.o_proj(attn_output)
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
class NanbeigeDecoderLayer(nn.Module):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
config: NanbeigeConfig,
|
||||||
|
layer_id: int = 0,
|
||||||
|
quant_config: Optional[QuantizationConfig] = None,
|
||||||
|
prefix: str = "",
|
||||||
|
alt_stream: Optional[torch.cuda.Stream] = None,
|
||||||
|
) -> None:
|
||||||
|
super().__init__()
|
||||||
|
|
||||||
|
self.self_attn = NanbeigeAttention(
|
||||||
|
config=config,
|
||||||
|
layer_id=layer_id,
|
||||||
|
quant_config=quant_config,
|
||||||
|
prefix=add_prefix("self_attn", prefix),
|
||||||
|
)
|
||||||
|
|
||||||
|
self.mlp = NanbeigeMLP(
|
||||||
|
hidden_size=config.hidden_size,
|
||||||
|
intermediate_size=config.intermediate_size,
|
||||||
|
hidden_act=config.hidden_act,
|
||||||
|
quant_config=quant_config,
|
||||||
|
prefix=add_prefix("mlp", prefix),
|
||||||
|
)
|
||||||
|
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||||
|
self.post_attention_layernorm = RMSNorm(
|
||||||
|
config.hidden_size, eps=config.rms_norm_eps
|
||||||
|
)
|
||||||
|
|
||||||
|
def forward(
|
||||||
|
self,
|
||||||
|
positions: torch.Tensor,
|
||||||
|
hidden_states: torch.Tensor,
|
||||||
|
forward_batch: ForwardBatch,
|
||||||
|
loop_idx: int,
|
||||||
|
residual: Optional[torch.Tensor],
|
||||||
|
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||||
|
|
||||||
|
if residual is None:
|
||||||
|
residual = hidden_states
|
||||||
|
hidden_states = self.input_layernorm(hidden_states)
|
||||||
|
else:
|
||||||
|
hidden_states, residual = self.input_layernorm(hidden_states, residual)
|
||||||
|
hidden_states = self.self_attn(
|
||||||
|
positions=positions,
|
||||||
|
hidden_states=hidden_states,
|
||||||
|
forward_batch=forward_batch,
|
||||||
|
loop_idx=loop_idx,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Fully Connected
|
||||||
|
hidden_states, residual = self.post_attention_layernorm(hidden_states, residual)
|
||||||
|
hidden_states = self.mlp(hidden_states)
|
||||||
|
|
||||||
|
return hidden_states, residual
|
||||||
|
|
||||||
|
|
||||||
|
class NanbeigeModel(nn.Module):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
config: NanbeigeConfig,
|
||||||
|
quant_config: Optional[QuantizationConfig] = None,
|
||||||
|
prefix: str = "",
|
||||||
|
decoder_layer_type: type[nn.Module] = NanbeigeDecoderLayer,
|
||||||
|
alt_stream: Optional[torch.cuda.Stream] = None,
|
||||||
|
) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self.config = config
|
||||||
|
self.vocab_size = config.vocab_size
|
||||||
|
self.pp_group = get_pp_group()
|
||||||
|
pp_size = self.pp_group.world_size
|
||||||
|
assert pp_size == 1, (
|
||||||
|
"The NanbeigeModel only supports a pipeline parallelism (PP) value of 1."
|
||||||
|
)
|
||||||
|
|
||||||
|
if self.pp_group.is_first_rank:
|
||||||
|
self.embed_tokens = VocabParallelEmbedding(
|
||||||
|
config.vocab_size,
|
||||||
|
config.hidden_size,
|
||||||
|
quant_config=quant_config,
|
||||||
|
use_attn_tp_group=is_dp_attention_enabled(),
|
||||||
|
prefix=add_prefix("embed_tokens", prefix),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.embed_tokens = PPMissingLayer()
|
||||||
|
|
||||||
|
# Use the provided decoder layer type or default to NanbeigeDecoderLayer
|
||||||
|
decoder_layer_type = decoder_layer_type or NanbeigeDecoderLayer
|
||||||
|
self.layers, self.start_layer, self.end_layer = make_layers(
|
||||||
|
config.num_hidden_layers,
|
||||||
|
lambda idx, prefix: decoder_layer_type(
|
||||||
|
layer_id=idx,
|
||||||
|
config=config,
|
||||||
|
quant_config=quant_config,
|
||||||
|
prefix=prefix,
|
||||||
|
alt_stream=alt_stream,
|
||||||
|
),
|
||||||
|
pp_rank=self.pp_group.rank_in_group,
|
||||||
|
pp_size=self.pp_group.world_size,
|
||||||
|
prefix=add_prefix("layers", prefix),
|
||||||
|
)
|
||||||
|
if self.pp_group.is_last_rank:
|
||||||
|
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||||
|
else:
|
||||||
|
self.norm = PPMissingLayer(return_tuple=True)
|
||||||
|
|
||||||
|
# For EAGLE3 / DFLASH: capture *before* unrolled layer id (ids already +1'd).
|
||||||
|
self.layers_to_capture = []
|
||||||
|
|
||||||
|
def get_input_embedding(self, input_ids):
|
||||||
|
return self.embed_tokens(input_ids)
|
||||||
|
|
||||||
|
def forward(
|
||||||
|
self,
|
||||||
|
input_ids: torch.Tensor,
|
||||||
|
positions: torch.Tensor,
|
||||||
|
forward_batch: ForwardBatch,
|
||||||
|
input_embeds: torch.Tensor = None,
|
||||||
|
pp_proxy_tensors: Optional[PPProxyTensors] = None,
|
||||||
|
) -> Union[torch.Tensor, PPProxyTensors]:
|
||||||
|
if self.pp_group.is_first_rank:
|
||||||
|
if input_embeds is None:
|
||||||
|
hidden_states = self.embed_tokens(input_ids)
|
||||||
|
else:
|
||||||
|
hidden_states = input_embeds
|
||||||
|
residual = None
|
||||||
|
else:
|
||||||
|
assert pp_proxy_tensors is not None
|
||||||
|
hidden_states = pp_proxy_tensors["hidden_states"]
|
||||||
|
residual = pp_proxy_tensors["residual"]
|
||||||
|
|
||||||
|
aux_hidden_states = []
|
||||||
|
# Draft target_layer_ids are in unrolled depth space:
|
||||||
|
# logical_id = loop_idx * num_hidden_layers + physical_i
|
||||||
|
# e.g. num_hidden_layers=22, num_loops=2 → ids in [0, 44).
|
||||||
|
# DFLASH style: setter stores k+1; we capture before that unrolled step.
|
||||||
|
num_physical_layers = self.config.num_hidden_layers
|
||||||
|
for loop_idx in range(self.config.num_loops):
|
||||||
|
for i in range(self.start_layer, self.end_layer):
|
||||||
|
logical_id = loop_idx * num_physical_layers + i
|
||||||
|
if logical_id in self.layers_to_capture:
|
||||||
|
aux_hidden_states.append(
|
||||||
|
hidden_states + residual
|
||||||
|
if residual is not None
|
||||||
|
else hidden_states.clone()
|
||||||
|
)
|
||||||
|
layer = self.layers[i]
|
||||||
|
hidden_states, residual = layer(
|
||||||
|
positions,
|
||||||
|
hidden_states,
|
||||||
|
forward_batch,
|
||||||
|
loop_idx,
|
||||||
|
residual,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Match the reference HF semantics for Nanbeige "loop models":
|
||||||
|
# - At the end of each full loop (except the last), convert the
|
||||||
|
# (hidden_states, residual) representation into real hidden_states
|
||||||
|
# by applying the missing residual addition.
|
||||||
|
# - If skip_loop_final_norm=False, HF applies RMSNorm after each loop
|
||||||
|
# (including intermediate loops) before entering the next loop.
|
||||||
|
if loop_idx != self.config.num_loops - 1:
|
||||||
|
if residual is not None:
|
||||||
|
hidden_states = hidden_states + residual
|
||||||
|
residual = None
|
||||||
|
if not self.config.skip_loop_final_norm:
|
||||||
|
hidden_states = self.norm(hidden_states)
|
||||||
|
|
||||||
|
if not self.pp_group.is_last_rank:
|
||||||
|
return PPProxyTensors(
|
||||||
|
{
|
||||||
|
"hidden_states": hidden_states,
|
||||||
|
"residual": residual,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
if hidden_states.shape[0] != 0:
|
||||||
|
if residual is None:
|
||||||
|
hidden_states = self.norm(hidden_states)
|
||||||
|
else:
|
||||||
|
hidden_states, _ = self.norm(hidden_states, residual)
|
||||||
|
|
||||||
|
if len(aux_hidden_states) == 0:
|
||||||
|
return hidden_states
|
||||||
|
|
||||||
|
return hidden_states, aux_hidden_states
|
||||||
|
|
||||||
|
|
||||||
|
class NanbeigeForCausalLM(nn.Module):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
config: NanbeigeConfig,
|
||||||
|
quant_config: Optional[QuantizationConfig] = None,
|
||||||
|
prefix: str = "",
|
||||||
|
) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self.pp_group = get_pp_group()
|
||||||
|
self.config = config
|
||||||
|
self.quant_config = quant_config
|
||||||
|
self.model = NanbeigeModel(
|
||||||
|
config, quant_config=quant_config, prefix=add_prefix("model", prefix)
|
||||||
|
)
|
||||||
|
|
||||||
|
# handle the lm head on different pp ranks
|
||||||
|
if self.pp_group.is_last_rank:
|
||||||
|
if self.pp_group.world_size == 1 and config.tie_word_embeddings:
|
||||||
|
self.lm_head = self.model.embed_tokens
|
||||||
|
else:
|
||||||
|
self.lm_head = ParallelLMHead(
|
||||||
|
config.vocab_size,
|
||||||
|
config.hidden_size,
|
||||||
|
quant_config=quant_config,
|
||||||
|
prefix=add_prefix("lm_head", prefix),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# ranks other than the last rank will have a placeholder layer
|
||||||
|
self.lm_head = PPMissingLayer()
|
||||||
|
|
||||||
|
# perform weight tying for PP
|
||||||
|
if self.pp_group.world_size > 1 and config.tie_word_embeddings:
|
||||||
|
if self.pp_group.is_first_rank:
|
||||||
|
self.pp_group.send(
|
||||||
|
self.model.embed_tokens.weight, dst=self.pp_group.last_rank
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
emb_token_weight = self.pp_group.recv(
|
||||||
|
size=(config.vocab_size, config.hidden_size),
|
||||||
|
dtype=next(self.model.parameters()).dtype,
|
||||||
|
src=self.pp_group.first_rank,
|
||||||
|
)
|
||||||
|
self.lm_head.weight.copy_(emb_token_weight)
|
||||||
|
|
||||||
|
self.logits_processor = LogitsProcessor(config)
|
||||||
|
self.pooler = Pooler(pooling_type=PoolingType.LAST, normalize=True)
|
||||||
|
# For EAGLE3 support
|
||||||
|
self.capture_aux_hidden_states = False
|
||||||
|
|
||||||
|
def get_input_embedding(self, input_ids: torch.Tensor) -> torch.Tensor:
|
||||||
|
return self.model.get_input_embedding(input_ids)
|
||||||
|
|
||||||
|
def get_input_embeddings(self) -> nn.Embedding:
|
||||||
|
return self.model.embed_tokens
|
||||||
|
|
||||||
|
@torch.no_grad()
|
||||||
|
def forward(
|
||||||
|
self,
|
||||||
|
input_ids: torch.Tensor,
|
||||||
|
positions: torch.Tensor,
|
||||||
|
forward_batch: ForwardBatch,
|
||||||
|
input_embeds: torch.Tensor = None,
|
||||||
|
get_embedding: bool = False,
|
||||||
|
pp_proxy_tensors: Optional[PPProxyTensors] = None,
|
||||||
|
) -> torch.Tensor:
|
||||||
|
hidden_states = self.model(
|
||||||
|
input_ids,
|
||||||
|
positions,
|
||||||
|
forward_batch,
|
||||||
|
input_embeds,
|
||||||
|
pp_proxy_tensors=pp_proxy_tensors,
|
||||||
|
)
|
||||||
|
aux_hidden_states = None
|
||||||
|
if self.capture_aux_hidden_states:
|
||||||
|
hidden_states, aux_hidden_states = hidden_states
|
||||||
|
|
||||||
|
if self.pp_group.is_last_rank:
|
||||||
|
if not get_embedding:
|
||||||
|
return self.logits_processor(
|
||||||
|
input_ids,
|
||||||
|
hidden_states,
|
||||||
|
self.lm_head,
|
||||||
|
forward_batch,
|
||||||
|
aux_hidden_states,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
return self.pooler(hidden_states, forward_batch)
|
||||||
|
else:
|
||||||
|
return hidden_states
|
||||||
|
|
||||||
|
@property
|
||||||
|
def start_layer(self):
|
||||||
|
return self.model.start_layer
|
||||||
|
|
||||||
|
@property
|
||||||
|
def end_layer(self):
|
||||||
|
return self.model.end_layer
|
||||||
|
|
||||||
|
@torch.no_grad()
|
||||||
|
def forward_split_prefill(
|
||||||
|
self,
|
||||||
|
input_ids: torch.Tensor,
|
||||||
|
positions: torch.Tensor,
|
||||||
|
forward_batch: ForwardBatch,
|
||||||
|
split_interval: Tuple[int, int], # [start, end) 0-based
|
||||||
|
input_embeds: torch.Tensor = None,
|
||||||
|
):
|
||||||
|
assert False, "NanbeigeModel does not support split_prefill."
|
||||||
|
|
||||||
|
def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
|
||||||
|
stacked_params_mapping = [
|
||||||
|
# (param_name, shard_name, shard_id)
|
||||||
|
(".qkv_proj", ".q_proj", "q"),
|
||||||
|
(".qkv_proj", ".k_proj", "k"),
|
||||||
|
(".qkv_proj", ".v_proj", "v"),
|
||||||
|
(".gate_up_proj", ".up_proj", 1),
|
||||||
|
(".gate_up_proj", ".gate_proj", 0),
|
||||||
|
]
|
||||||
|
|
||||||
|
params_dict = dict(self.named_parameters())
|
||||||
|
for name, loaded_weight in weights:
|
||||||
|
layer_id = get_layer_id(name)
|
||||||
|
if (
|
||||||
|
layer_id is not None
|
||||||
|
and hasattr(self.model, "start_layer")
|
||||||
|
and (
|
||||||
|
layer_id < self.model.start_layer
|
||||||
|
or layer_id >= self.model.end_layer
|
||||||
|
)
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
if "rotary_emb.inv_freq" in name or "projector" in name:
|
||||||
|
continue
|
||||||
|
if self.config.tie_word_embeddings and "lm_head.weight" in name:
|
||||||
|
if self.pp_group.world_size > 1 and self.pp_group.is_last_rank:
|
||||||
|
# Handle pp weight tying here
|
||||||
|
# find the embed_tokens.weight in the weights
|
||||||
|
embed_token_weights = next(
|
||||||
|
filter(lambda x: x[0] == "model.embed_tokens.weight", weights)
|
||||||
|
)[1]
|
||||||
|
loaded_weight = embed_token_weights
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
|
||||||
|
for param_name, weight_name, shard_id in stacked_params_mapping:
|
||||||
|
if weight_name not in name:
|
||||||
|
continue
|
||||||
|
name = name.replace(weight_name, param_name)
|
||||||
|
# Skip loading extra bias for GPTQ models.
|
||||||
|
if name.endswith(".bias") and name not in params_dict:
|
||||||
|
continue
|
||||||
|
if name not in params_dict:
|
||||||
|
continue
|
||||||
|
param = params_dict[name]
|
||||||
|
weight_loader = param.weight_loader
|
||||||
|
weight_loader(param, loaded_weight, shard_id)
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
# Skip loading extra bias for GPTQ models.
|
||||||
|
if name.endswith(".bias") and name not in params_dict:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if name in params_dict.keys():
|
||||||
|
param = params_dict[name]
|
||||||
|
weight_loader = getattr(
|
||||||
|
param, "weight_loader", default_weight_loader
|
||||||
|
)
|
||||||
|
weight_loader(param, loaded_weight)
|
||||||
|
else:
|
||||||
|
logger.warning(f"Parameter {name} not found in params_dict")
|
||||||
|
|
||||||
|
def get_embed_and_head(self):
|
||||||
|
return self.model.embed_tokens.weight, self.lm_head.weight
|
||||||
|
|
||||||
|
def set_embed_and_head(self, embed, head):
|
||||||
|
del self.model.embed_tokens.weight
|
||||||
|
del self.lm_head.weight
|
||||||
|
self.model.embed_tokens.weight = embed
|
||||||
|
self.lm_head.weight = head
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
torch.cuda.synchronize()
|
||||||
|
|
||||||
|
def set_dflash_layers_to_capture(self, layer_ids: List[int]):
|
||||||
|
if not self.pp_group.is_last_rank:
|
||||||
|
return
|
||||||
|
|
||||||
|
if layer_ids is None:
|
||||||
|
raise ValueError(
|
||||||
|
"DFLASH requires explicit layer_ids for aux hidden capture."
|
||||||
|
)
|
||||||
|
|
||||||
|
self.capture_aux_hidden_states = True
|
||||||
|
# Unrolled ids: capture before step (k+1) == after HF-style layer k.
|
||||||
|
self.model.layers_to_capture = [val + 1 for val in layer_ids]
|
||||||
|
|
||||||
|
|
||||||
|
class NanbeigeForSequenceClassification(nn.Module):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
config: NanbeigeConfig,
|
||||||
|
quant_config: Optional[QuantizationConfig] = None,
|
||||||
|
prefix: str = "",
|
||||||
|
) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self.config = config
|
||||||
|
self.quant_config = quant_config
|
||||||
|
self.model = NanbeigeModel(
|
||||||
|
config, quant_config=quant_config, prefix=add_prefix("model", prefix)
|
||||||
|
)
|
||||||
|
self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False)
|
||||||
|
self.pooler = Pooler(pooling_type=PoolingType.LAST, normalize=False)
|
||||||
|
|
||||||
|
self.eos_token_id = config.eos_token_id
|
||||||
|
|
||||||
|
@torch.no_grad()
|
||||||
|
def forward(
|
||||||
|
self,
|
||||||
|
input_ids: torch.Tensor,
|
||||||
|
positions: torch.Tensor,
|
||||||
|
forward_batch: ForwardBatch,
|
||||||
|
input_embeds: torch.Tensor = None,
|
||||||
|
get_embedding: bool = True,
|
||||||
|
) -> EmbeddingPoolerOutput:
|
||||||
|
assert get_embedding, (
|
||||||
|
"NanbeigeForSequenceClassification is only used for embedding"
|
||||||
|
)
|
||||||
|
|
||||||
|
hidden_states = self.model(input_ids, positions, forward_batch, input_embeds)
|
||||||
|
logits = self.score(hidden_states)
|
||||||
|
pooled_logits = self.pooler(logits, forward_batch).embeddings
|
||||||
|
|
||||||
|
return EmbeddingPoolerOutput(pooled_logits)
|
||||||
|
|
||||||
|
def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
|
||||||
|
# Filter out lm_head weights of NanbeigeForCausalLM
|
||||||
|
filtered_weights = [
|
||||||
|
(name, w) for name, w in weights if not name.startswith("lm_head")
|
||||||
|
]
|
||||||
|
return NanbeigeForCausalLM.load_weights(self, filtered_weights)
|
||||||
|
|
||||||
|
|
||||||
|
EntryClass = [NanbeigeForCausalLM, NanbeigeForSequenceClassification]
|
||||||
@@ -2042,6 +2042,7 @@ class ReasoningParser:
|
|||||||
"minimax": Qwen3Detector,
|
"minimax": Qwen3Detector,
|
||||||
"minimax-append-think": MiniMaxAppendThinkDetector,
|
"minimax-append-think": MiniMaxAppendThinkDetector,
|
||||||
"minimax-m3": MiniMaxM3Detector,
|
"minimax-m3": MiniMaxM3Detector,
|
||||||
|
"nanbeige": Qwen3Detector,
|
||||||
"step3": DeepSeekR1Detector,
|
"step3": DeepSeekR1Detector,
|
||||||
"step3p5": DeepSeekR1Detector,
|
"step3p5": DeepSeekR1Detector,
|
||||||
"mistral": MistralDetector,
|
"mistral": MistralDetector,
|
||||||
|
|||||||
@@ -63,6 +63,7 @@ from sglang.srt.configs import (
|
|||||||
MultiModalityConfig,
|
MultiModalityConfig,
|
||||||
MuseGlimmerAssistantConfig,
|
MuseGlimmerAssistantConfig,
|
||||||
MuseGlimmerConfig,
|
MuseGlimmerConfig,
|
||||||
|
NanbeigeConfig,
|
||||||
NemotronH_Nano_Omni_Reasoning_V3_Config,
|
NemotronH_Nano_Omni_Reasoning_V3_Config,
|
||||||
NemotronH_Nano_VL_V2_Config,
|
NemotronH_Nano_VL_V2_Config,
|
||||||
NemotronHConfig,
|
NemotronHConfig,
|
||||||
@@ -131,6 +132,7 @@ _CONFIG_REGISTRY: Dict[str, Type[PretrainedConfig]] = {
|
|||||||
NemotronH_Nano_Omni_Reasoning_V3_Config,
|
NemotronH_Nano_Omni_Reasoning_V3_Config,
|
||||||
NemotronHConfig,
|
NemotronHConfig,
|
||||||
NemotronHPuzzleConfig,
|
NemotronHPuzzleConfig,
|
||||||
|
NanbeigeConfig,
|
||||||
DeepseekVLV2Config,
|
DeepseekVLV2Config,
|
||||||
Qwen3_5Config,
|
Qwen3_5Config,
|
||||||
Qwen3_5MoeConfig,
|
Qwen3_5MoeConfig,
|
||||||
|
|||||||
Reference in New Issue
Block a user