From 974061f9c9f01db159c78c9644534c1291f7a5d6 Mon Sep 17 00:00:00 2001 From: sushmanth reddy Date: Wed, 11 Nov 2026 16:04:22 +0530 Subject: [PATCH 1/7] Add Nanbeige4.2-3B starter template --- docs/source/en/_toctree.yml | 2 + docs/source/en/model_doc/nanbeige.md | 71 +++ src/transformers/models/__init__.py | 1 + src/transformers/models/auto/auto_mappings.py | 1 + src/transformers/models/auto/modeling_auto.py | 5 + src/transformers/models/nanbeige/__init__.py | 28 + .../models/nanbeige/configuration_nanbeige.py | 104 ++++ .../models/nanbeige/modeling_nanbeige.py | 498 ++++++++++++++++ .../models/nanbeige/modular_nanbeige.py | 87 +++ tests/models/nanbeige/__init__.py | 0 .../models/nanbeige/test_modeling_nanbeige.py | 563 ++++++++++++++++++ 11 files changed, 1360 insertions(+) create mode 100644 docs/source/en/model_doc/nanbeige.md create mode 100644 src/transformers/models/nanbeige/__init__.py create mode 100644 src/transformers/models/nanbeige/configuration_nanbeige.py create mode 100644 src/transformers/models/nanbeige/modeling_nanbeige.py create mode 100644 src/transformers/models/nanbeige/modular_nanbeige.py create mode 100644 tests/models/nanbeige/__init__.py create mode 100644 tests/models/nanbeige/test_modeling_nanbeige.py diff --git a/docs/source/en/_toctree.yml b/docs/source/en/_toctree.yml index 2928fb8e301b..3e776fb93e7e 100644 --- a/docs/source/en/_toctree.yml +++ b/docs/source/en/_toctree.yml @@ -849,6 +849,8 @@ title: MVP - local: model_doc/myt5 title: myt5 + - local: model_doc/nanbeige + title: Nanbeige - local: model_doc/nanochat title: NanoChat - local: model_doc/nemotron diff --git a/docs/source/en/model_doc/nanbeige.md b/docs/source/en/model_doc/nanbeige.md new file mode 100644 index 000000000000..7dce0571d05a --- /dev/null +++ b/docs/source/en/model_doc/nanbeige.md @@ -0,0 +1,71 @@ + + + +# Nanbeige + +## Overview + +The Nanbeige model was proposed in []() by . + + +The abstract from the paper is the following: + + + +Tips: + + + +This model was contributed by [INSERT YOUR HF USERNAME HERE](https://huggingface.co/). +The original code can be found [here](). + +## Usage examples + + + +## NanbeigeConfig + +[[autodoc]] NanbeigeConfig + +## NanbeigeForCausalLM + +[[autodoc]] NanbeigeForCausalLM + +## NanbeigeModel + +[[autodoc]] NanbeigeModel + - forward + +## NanbeigePreTrainedModel + +[[autodoc]] NanbeigePreTrainedModel + - forward + +## NanbeigeForSequenceClassification + +[[autodoc]] NanbeigeForSequenceClassification + +## NanbeigeForQuestionAnswering + +[[autodoc]] NanbeigeForQuestionAnswering + +## NanbeigeForTokenClassification + +[[autodoc]] NanbeigeForTokenClassification \ No newline at end of file diff --git a/src/transformers/models/__init__.py b/src/transformers/models/__init__.py index 4e925af57654..a26d554db8ab 100644 --- a/src/transformers/models/__init__.py +++ b/src/transformers/models/__init__.py @@ -342,6 +342,7 @@ from .musicgen_melody import * from .mvp import * from .myt5 import * + from .nanbeige import * from .nanochat import * from .nemotron import * from .nemotron3_5_asr import * diff --git a/src/transformers/models/auto/auto_mappings.py b/src/transformers/models/auto/auto_mappings.py index d122010ce176..8973e06e759a 100644 --- a/src/transformers/models/auto/auto_mappings.py +++ b/src/transformers/models/auto/auto_mappings.py @@ -472,6 +472,7 @@ ("musicgen_melody", "MusicgenMelodyConfig"), ("musicgen_melody_decoder", "MusicgenMelodyDecoderConfig"), ("mvp", "MvpConfig"), + ("nanbeige", "NanbeigeConfig"), ("nanochat", "NanoChatConfig"), ("nemo_speechlm", "Nemotron3_5TranscribeConfig"), ("nemotron", "NemotronConfig"), diff --git a/src/transformers/models/auto/modeling_auto.py b/src/transformers/models/auto/modeling_auto.py index aae94ec04625..77f62b592740 100644 --- a/src/transformers/models/auto/modeling_auto.py +++ b/src/transformers/models/auto/modeling_auto.py @@ -397,6 +397,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("musicgen", "MusicgenModel"), ("musicgen_melody", "MusicgenMelodyModel"), ("mvp", "MvpModel"), + ("nanbeige", "NanbeigeModel"), ("nanochat", "NanoChatModel"), ("nemo_speechlm", "Nemotron3_5TranscribeModel"), ("nemotron", "NemotronModel"), @@ -877,6 +878,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("musicgen", "MusicgenForCausalLM"), ("musicgen_melody", "MusicgenMelodyForCausalLM"), ("mvp", "MvpForCausalLM"), + ("nanbeige", "NanbeigeForCausalLM"), ("nanochat", "NanoChatForCausalLM"), ("nemotron", "NemotronForCausalLM"), ("nemotron_h", "NemotronHForCausalLM"), @@ -1544,6 +1546,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("mra", "MraForSequenceClassification"), ("mt5", "MT5ForSequenceClassification"), ("mvp", "MvpForSequenceClassification"), + ("nanbeige", "NanbeigeForSequenceClassification"), ("nemotron", "NemotronForSequenceClassification"), ("nomic_bert", "NomicBertForSequenceClassification"), ("nystromformer", "NystromformerForSequenceClassification"), @@ -1648,6 +1651,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("mra", "MraForQuestionAnswering"), ("mt5", "MT5ForQuestionAnswering"), ("mvp", "MvpForQuestionAnswering"), + ("nanbeige", "NanbeigeForQuestionAnswering"), ("nemotron", "NemotronForQuestionAnswering"), ("nystromformer", "NystromformerForQuestionAnswering"), ("opt", "OPTForQuestionAnswering"), @@ -1769,6 +1773,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("mpt", "MptForTokenClassification"), ("mra", "MraForTokenClassification"), ("mt5", "MT5ForTokenClassification"), + ("nanbeige", "NanbeigeForTokenClassification"), ("nemotron", "NemotronForTokenClassification"), ("nomic_bert", "NomicBertForTokenClassification"), ("nystromformer", "NystromformerForTokenClassification"), diff --git a/src/transformers/models/nanbeige/__init__.py b/src/transformers/models/nanbeige/__init__.py new file mode 100644 index 000000000000..c4607572e7dc --- /dev/null +++ b/src/transformers/models/nanbeige/__init__.py @@ -0,0 +1,28 @@ +# Copyright 2026 the HuggingFace 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. + +from typing import TYPE_CHECKING + +from ...utils import _LazyModule +from ...utils.import_utils import define_import_structure + + +if TYPE_CHECKING: + from .configuration_nanbeige import * + from .modeling_nanbeige import * +else: + import sys + + _file = globals()["__file__"] + sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__) diff --git a/src/transformers/models/nanbeige/configuration_nanbeige.py b/src/transformers/models/nanbeige/configuration_nanbeige.py new file mode 100644 index 000000000000..7ec0f5535f03 --- /dev/null +++ b/src/transformers/models/nanbeige/configuration_nanbeige.py @@ -0,0 +1,104 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/nanbeige/modular_nanbeige.py. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# modular_nanbeige.py file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# Copyright 2026 the HuggingFace 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. + + +from huggingface_hub.dataclasses import strict + +from ...configuration_utils import PreTrainedConfig +from ...modeling_rope_utils import RopeParameters +from ...utils import auto_docstring +from ...utils.type_validators import interval + + +@auto_docstring(checkpoint="meta-nanbeige/Nanbeige-2-7b-hf") +@strict +class NanbeigeConfig(PreTrainedConfig): + r""" + ```python + >>> from transformers import NanbeigeModel, NanbeigeConfig + + >>> # 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"] + # Default tensor parallel plan for base model `NanbeigeModel` + base_model_tp_plan = { + "layers.*.self_attn.q_proj": "colwise", + "layers.*.self_attn.k_proj": "colwise", + "layers.*.self_attn.v_proj": "colwise", + "layers.*.self_attn.o_proj": "rowwise", + "layers.*.mlp.gate_proj": "colwise", + "layers.*.mlp.up_proj": "colwise", + "layers.*.mlp.down_proj": "rowwise", + } + base_model_pp_plan = { + "embed_tokens": (["input_ids"], ["inputs_embeds"]), + "layers": (["hidden_states", "attention_mask"], ["hidden_states"]), + "norm": (["hidden_states"], ["hidden_states"]), + } + + vocab_size: int = 32000 + hidden_size: int = 4096 + intermediate_size: int = 11008 + num_hidden_layers: int = 32 + num_attention_heads: int = 32 + num_key_value_heads: int | None = None + hidden_act: str = "silu" + max_position_embeddings: int = 2048 + initializer_range: float = interval(min=0.0, max=1.0)(default=0.02) + rms_norm_eps: float = 1e-6 + use_cache: bool = True + pad_token_id: int | None = None + bos_token_id: int | None = 1 + eos_token_id: int | list[int] | None = 2 + pretraining_tp: int | None = 1 + tie_word_embeddings: bool = False + rope_parameters: RopeParameters | dict | None = None + attention_bias: bool = False + attention_dropout: int | float | None = 0.0 + mlp_bias: bool = False + head_dim: int | None = None + + def __post_init__(self, **kwargs): + if self.head_dim is None: + self.head_dim = self.hidden_size // self.num_attention_heads + if self.num_key_value_heads is None: + self.num_key_value_heads = self.num_attention_heads + + super().__post_init__(**kwargs) + + def validate_architecture(self): + """Part of `@strict`-powered validation. Validates the architecture of the config.""" + if self.hidden_size % self.num_attention_heads != 0: + raise ValueError( + f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention " + f"heads ({self.num_attention_heads})." + ) + + +__all__ = ["NanbeigeConfig"] diff --git a/src/transformers/models/nanbeige/modeling_nanbeige.py b/src/transformers/models/nanbeige/modeling_nanbeige.py new file mode 100644 index 000000000000..bc09eab4ee55 --- /dev/null +++ b/src/transformers/models/nanbeige/modeling_nanbeige.py @@ -0,0 +1,498 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/nanbeige/modular_nanbeige.py. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# modular_nanbeige.py file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# Copyright 2026 the HuggingFace 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. + +from collections.abc import Callable + +import torch +from torch import nn + +from ...activations import ACT2FN +from ...cache_utils import Cache, DynamicCache +from ...generation import GenerationMixin +from ...integrations import use_kernel_forward_from_hub, use_kernelized_func +from ...masking_utils import create_causal_mask +from ...modeling_layers import ( + GenericForQuestionAnswering, + GenericForSequenceClassification, + GenericForTokenClassification, + GradientCheckpointingLayer, +) +from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast +from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update +from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel, slice_logits_to_keep +from ...processing_utils import Unpack +from ...utils import TransformersKwargs, auto_docstring, can_return_tuple +from ...utils.generic import merge_with_config_defaults +from ...utils.output_capturing import capture_outputs +from .configuration_nanbeige import NanbeigeConfig + + +@use_kernel_forward_from_hub("RMSNorm") +class NanbeigeRMSNorm(nn.Module): + def __init__(self, hidden_size, eps: float = 1e-6) -> None: + """ + NanbeigeRMSNorm is equivalent to T5LayerNorm + """ + super().__init__() + self.weight = nn.Parameter(torch.ones(hidden_size)) + self.variance_epsilon = eps + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + 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) + + def extra_repr(self): + return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" + + +class NanbeigeRotaryEmbedding(nn.Module): + def __init__(self, config: NanbeigeConfig): + super().__init__() + self.max_seq_len_cached = config.max_position_embeddings + self.original_max_seq_len = config.max_position_embeddings + + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_default_rope_parameters + if self.rope_type != "default": + rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] + inv_freq, self.attention_scaling = rope_init_fn(self.config) + + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + + @staticmethod + def compute_default_rope_parameters(config: NanbeigeConfig, **kwargs) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + + attention_factor = 1.0 # Unused in this type of RoPE + # Compute the inverse frequencies + inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + return inv_freq, attention_factor + + @torch.no_grad() + @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) + def forward(self, x, position_ids): + freqs = position_ids[..., None].float() * self.inv_freq.to(device=x.device, dtype=torch.float) + emb = torch.cat((freqs, freqs), dim=-1) + cos = emb.cos() * self.attention_scaling + sin = emb.sin() * self.attention_scaling + + return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) + + +class NanbeigeMLP(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.hidden_size = config.hidden_size + self.intermediate_size = config.intermediate_size + self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) + self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) + self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias) + self.act_fn = ACT2FN[config.hidden_act] + + def forward(self, x): + down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) + return down_proj + + +def rotate_half(x): + """Rotates half the hidden dims of the input.""" + x1 = x[..., : x.shape[-1] // 2] + x2 = x[..., x.shape[-1] // 2 :] + return torch.cat((-x2, x1), dim=-1) + + +@use_kernel_forward_from_hub("rotary_pos_emb") +def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1): + """Applies Rotary Position Embedding to the query and key tensors. + + Args: + q (`torch.Tensor`): The query tensor. + k (`torch.Tensor`): The key tensor. + cos (`torch.Tensor`): The cosine part of the rotary embedding. + sin (`torch.Tensor`): The sine part of the rotary embedding. + unsqueeze_dim (`int`, *optional*, defaults to 1): + The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and + sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note + that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and + k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes + cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have + the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. + Returns: + `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. + """ + cos = cos.unsqueeze(unsqueeze_dim) + sin = sin.unsqueeze(unsqueeze_dim) + q_embed = (q * cos) + (rotate_half(q) * sin) + k_embed = (k * cos) + (rotate_half(k) * sin) + return q_embed, k_embed + + +def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: + """ + This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, + num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) + """ + batch, num_key_value_heads, slen, head_dim = hidden_states.shape + if n_rep == 1: + return hidden_states + hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) + return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) + + +def eager_attention_forward( + module: nn.Module, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: torch.Tensor | None, + scaling: float, + dropout: float = 0.0, + **kwargs: Unpack[TransformersKwargs], +): + key_states = repeat_kv(key, module.num_key_value_groups) + value_states = repeat_kv(value, module.num_key_value_groups) + + attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling + if attention_mask is not None: + attn_weights = attn_weights + attention_mask + + attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) + attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) + attn_output = torch.matmul(attn_weights, value_states) + attn_output = attn_output.transpose(1, 2).contiguous() + + return attn_output, attn_weights + + +@use_kernelized_func(apply_rotary_pos_emb) +class NanbeigeAttention(nn.Module): + """Multi-headed attention from 'Attention Is All You Need' paper""" + + def __init__(self, config: NanbeigeConfig, layer_idx: int): + super().__init__() + self.config = config + self.layer_idx = layer_idx + self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) + self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads + self.scaling = self.head_dim**-0.5 + self.attention_dropout = config.attention_dropout + self.is_causal = True + + self.q_proj = nn.Linear( + config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias + ) + self.k_proj = nn.Linear( + config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias + ) + self.v_proj = nn.Linear( + config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias + ) + self.o_proj = nn.Linear( + config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias + ) + + def forward( + self, + hidden_states: torch.Tensor, + position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, + attention_mask: torch.Tensor | None = None, + past_key_values: Cache | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple[torch.Tensor, torch.Tensor]: + input_shape = hidden_states.shape[:-1] + hidden_shape = (*input_shape, -1, self.head_dim) + + query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2) + key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2) + value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2) + + cos, sin = position_embeddings + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) + + if past_key_values is not None: + key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx) + + attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( + self.config._attn_implementation, eager_attention_forward + ) + + attn_output, attn_weights = attention_interface( + self, + query_states, + key_states, + value_states, + attention_mask, + dropout=0.0 if not self.training else self.attention_dropout, + scaling=self.scaling, + **kwargs, + ) + + attn_output = attn_output.reshape(*input_shape, -1).contiguous() + attn_output = self.o_proj(attn_output) + return attn_output, attn_weights + + +class NanbeigeDecoderLayer(GradientCheckpointingLayer): + def __init__(self, config: NanbeigeConfig, layer_idx: int): + super().__init__() + self.hidden_size = config.hidden_size + + self.self_attn = NanbeigeAttention(config=config, layer_idx=layer_idx) + + self.mlp = NanbeigeMLP(config) + self.input_layernorm = NanbeigeRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.post_attention_layernorm = NanbeigeRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + past_key_values: Cache | None = None, + use_cache: bool | None = False, + position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> torch.Tensor: + residual = hidden_states + hidden_states = self.input_layernorm(hidden_states) + # Self Attention + hidden_states, _ = self.self_attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + use_cache=use_cache, + position_embeddings=position_embeddings, + **kwargs, + ) + hidden_states = residual + hidden_states + + # Fully Connected + residual = hidden_states + hidden_states = self.post_attention_layernorm(hidden_states) + hidden_states = self.mlp(hidden_states) + hidden_states = residual + hidden_states + return hidden_states + + +@auto_docstring +class NanbeigePreTrainedModel(PreTrainedModel): + config: NanbeigeConfig + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = ["NanbeigeDecoderLayer"] + _skip_keys_device_placement = ["past_key_values"] + _supports_flash_attn = True + _supports_sdpa = True + _supports_flex_attn = True + + _can_compile_fullgraph = True + _supports_attention_backend = True + _can_record_outputs = { + "hidden_states": NanbeigeDecoderLayer, + "attentions": NanbeigeAttention, + } + + +@auto_docstring +class NanbeigeModel(NanbeigePreTrainedModel): + def __init__(self, config: NanbeigeConfig): + super().__init__(config) + self.padding_idx = config.pad_token_id + self.vocab_size = config.vocab_size + + self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) + self.layers = nn.ModuleList( + [NanbeigeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] + ) + self.norm = NanbeigeRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.rotary_emb = NanbeigeRotaryEmbedding(config=config) + self.gradient_checkpointing = False + + # Initialize weights and apply final processing + self.post_init() + + @merge_with_config_defaults + @capture_outputs + @auto_docstring + def forward( + self, + input_ids: torch.LongTensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + past_key_values: Cache | None = None, + inputs_embeds: torch.Tensor | None = None, + use_cache: bool | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> BaseModelOutputWithPast: + if (input_ids is None) ^ (inputs_embeds is not None): + raise ValueError("You must specify exactly one of input_ids or inputs_embeds") + + if inputs_embeds is None: + inputs_embeds: torch.Tensor = self.embed_tokens(input_ids) + + if use_cache and past_key_values is None: + past_key_values = DynamicCache(config=self.config) + + if position_ids is None: + past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 + position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens + position_ids = position_ids.unsqueeze(0) + + causal_mask = create_causal_mask( + config=self.config, + inputs_embeds=inputs_embeds, + attention_mask=attention_mask, + past_key_values=past_key_values, + position_ids=position_ids, + ) + + hidden_states = inputs_embeds + position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids) + + for decoder_layer in self.layers[: self.config.num_hidden_layers]: + hidden_states = decoder_layer( + hidden_states, + attention_mask=causal_mask, + position_embeddings=position_embeddings, + position_ids=position_ids, + past_key_values=past_key_values, + use_cache=use_cache, + **kwargs, + ) + + hidden_states = self.norm(hidden_states) + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=past_key_values, + ) + + +@auto_docstring +class NanbeigeForCausalLM(NanbeigePreTrainedModel, GenerationMixin): + _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} + _tp_plan = {"lm_head": "colwise_gather_output"} + _pp_plan = {"lm_head": (["hidden_states"], ["logits"])} + _fsdp_plan = {"lm_head": "keep_full_weight"} + + def __init__(self, config: NanbeigeConfig): + super().__init__(config) + self.model = NanbeigeModel(config) + self.vocab_size = config.vocab_size + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + @can_return_tuple + @auto_docstring + def forward( + self, + input_ids: torch.LongTensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + past_key_values: Cache | None = None, + inputs_embeds: torch.Tensor | None = None, + labels: torch.LongTensor | None = None, + use_cache: bool | None = None, + logits_to_keep: int | torch.Tensor = 0, + **kwargs: Unpack[TransformersKwargs], + ) -> CausalLMOutputWithPast: + r""" + Example: + + ```python + >>> from transformers import AutoTokenizer, NanbeigeForCausalLM + + >>> model = NanbeigeForCausalLM.from_pretrained("meta-nanbeige/Nanbeige-2-7b-hf") + >>> tokenizer = AutoTokenizer.from_pretrained("meta-nanbeige/Nanbeige-2-7b-hf") + + >>> prompt = "Hey, are you conscious? Can you talk to me?" + >>> inputs = tokenizer(prompt, return_tensors="pt") + + >>> # Generate + >>> generate_ids = model.generate(inputs.input_ids, max_length=30) + >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] + "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." + ```""" + outputs: BaseModelOutputWithPast = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + **kwargs, + ) + + hidden_states = outputs.last_hidden_state + hidden_states = slice_logits_to_keep(hidden_states, logits_to_keep) + logits = self.lm_head(hidden_states) + + loss = None + if labels is not None: + loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +class NanbeigeForSequenceClassification(GenericForSequenceClassification, NanbeigePreTrainedModel): + pass + + +class NanbeigeForQuestionAnswering(GenericForQuestionAnswering, NanbeigePreTrainedModel): + base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model` + + +class NanbeigeForTokenClassification(GenericForTokenClassification, NanbeigePreTrainedModel): + pass + + +__all__ = [ + "NanbeigeForCausalLM", + "NanbeigeModel", + "NanbeigePreTrainedModel", + "NanbeigeForSequenceClassification", + "NanbeigeForQuestionAnswering", + "NanbeigeForTokenClassification", +] diff --git a/src/transformers/models/nanbeige/modular_nanbeige.py b/src/transformers/models/nanbeige/modular_nanbeige.py new file mode 100644 index 000000000000..613fb1836a19 --- /dev/null +++ b/src/transformers/models/nanbeige/modular_nanbeige.py @@ -0,0 +1,87 @@ +# Copyright 2026 the HuggingFace 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. + +from ..llama.configuration_llama import LlamaConfig +from ..llama.modeling_llama import ( + LlamaAttention, + LlamaDecoderLayer, + LlamaForCausalLM, + LlamaForQuestionAnswering, + LlamaForSequenceClassification, + LlamaForTokenClassification, + LlamaMLP, + LlamaModel, + LlamaPreTrainedModel, + LlamaRMSNorm, + LlamaRotaryEmbedding, +) + + +class NanbeigeConfig(LlamaConfig): + pass + + +class NanbeigeRMSNorm(LlamaRMSNorm): + pass + + +class NanbeigeRotaryEmbedding(LlamaRotaryEmbedding): + pass + + +class NanbeigeMLP(LlamaMLP): + pass + + +class NanbeigeAttention(LlamaAttention): + pass + + +class NanbeigeDecoderLayer(LlamaDecoderLayer): + pass + + +class NanbeigePreTrainedModel(LlamaPreTrainedModel): + pass + + +class NanbeigeModel(LlamaModel): + pass + + +class NanbeigeForCausalLM(LlamaForCausalLM): + pass + + +class NanbeigeForSequenceClassification(LlamaForSequenceClassification): + pass + + +class NanbeigeForQuestionAnswering(LlamaForQuestionAnswering): + pass + + +class NanbeigeForTokenClassification(LlamaForTokenClassification): + pass + + +__all__ = [ + "NanbeigeConfig", + "NanbeigeForCausalLM", + "NanbeigeModel", + "NanbeigePreTrainedModel", + "NanbeigeForSequenceClassification", + "NanbeigeForQuestionAnswering", + "NanbeigeForTokenClassification", +] diff --git a/tests/models/nanbeige/__init__.py b/tests/models/nanbeige/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/models/nanbeige/test_modeling_nanbeige.py b/tests/models/nanbeige/test_modeling_nanbeige.py new file mode 100644 index 000000000000..ecdc0e5cb869 --- /dev/null +++ b/tests/models/nanbeige/test_modeling_nanbeige.py @@ -0,0 +1,563 @@ +# Copyright 2026 the HuggingFace 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. +"""Testing suite for the PyTorch LLaMA model.""" + +import unittest + +import pytest + +from transformers import AutoTokenizer, StaticCache, is_torch_available +from transformers.generation.configuration_utils import GenerationConfig +from transformers.testing_utils import ( + Expectations, + require_flash_attn, + require_torch, + require_torch_accelerator, + slow, + torch_device, +) + +from ...causal_lm_tester import CausalLMModelTest, CausalLMModelTester +from ...test_memory_cleanup_mixin import MemoryCleanupMixin + + +if is_torch_available(): + import torch + + from transformers import ( + AutoModelForCausalLM, + NanbeigeForCausalLM, + NanbeigeModel, + NanbeigeTokenizer, + StaticLayer, + ) + + +class NanbeigeModelTester(CausalLMModelTester): + if is_torch_available(): + base_model_class = NanbeigeModel + + +@require_torch +class NanbeigeModelTest(CausalLMModelTest, unittest.TestCase): + model_tester_class = NanbeigeModelTester + + # Need to use `0.8` instead of `0.9` for `test_cpu_offload` + # This is because we are hitting edge cases with the causal_mask buffer + model_split_percents = [0.5, 0.7, 0.8] + + # used in `test_torch_compile_for_training` + _torch_compile_train_cls = NanbeigeForCausalLM if is_torch_available() else None + + +@require_torch_accelerator +@slow +class NanbeigeIntegrationTest(MemoryCleanupMixin, unittest.TestCase): + def test_llama_3_1_hard(self): + """ + An integration test for llama 3.1. It tests against a long output to ensure the subtle numerical differences + from llama 3.1.'s RoPE can be detected + """ + expected_texts = Expectations( + { + ("rocm", (9, 4)): 'Tell me about the french revolution. The french revolution was a period of radical political and social upheaval in France that lasted from 1789 until 1799. It was a time of great change and upheaval, marked by the overthrow of the monarchy, the rise of the middle class, and the eventual establishment of the First French Republic.\nThe revolution began in 1789 with the Estates-General, a representative assembly that had not met since 1614. The Third Estate, which represented the common people, demanded greater representation and eventually broke away to form the National Assembly. This marked the beginning of the end of the absolute monarchy and the feudal system.\nThe National Assembly', + ("rocm", (9, 5)): 'Tell me about the french revolution. The french revolution was a period of radical social and political upheaval in France that lasted from 1789 until 1799. It was a time of great change and upheaval, marked by the overthrow of the monarchy, the rise of the middle class, and the eventual establishment of the First French Republic.\nThe revolution began in 1789 with the Estates-General, a representative assembly that had not met since 1614. The Third Estate, which represented the common people, demanded greater representation and eventually broke away to form the National Assembly. This marked the beginning of the end of the absolute monarchy and the rise of the middle class.\n', + ("cuda", 8): 'Tell me about the french revolution. The french revolution was a period of radical social and political upheaval in France that lasted from 1789 to 1799. It was a time of great change and upheaval, marked by the overthrow of the monarchy, the establishment of the First French Republic, and the Reign of Terror.\nThe French Revolution began in 1789 with the Estates-General, a representative assembly that had not met since 1614. The Third Estate, which represented the common people, demanded greater representation and eventually broke away to form the National Assembly. The National Assembly adopted the Declaration of the Rights of Man and of the Citizen, which enshrined the', + ("cuda", None): 'Tell me about the french revolution. The french revolution was a period of radical political and social upheaval in France that lasted from 1789 until 1799. It was a time of great change and upheaval, marked by the overthrow of the monarchy, the rise of the middle class, and the eventual establishment of the First French Republic.\nThe revolution began in 1789 with the Estates-General, a representative assembly that had not met since 1614. The Third Estate, which represented the common people, demanded greater representation and eventually broke away to form the National Assembly. The National Assembly adopted the Declaration of the Rights of Man and of the Citizen, which enshr', + ("tpu", None): 'Tell me about the french revolution. The french revolution was a period of radical social and political upheaval in France that lasted from 1789 until 1799. It was a time of great change and upheaval, marked by the overthrow of the monarchy, the rise of the middle class, and the eventual establishment of the First French Republic.\nThe revolution began in 1789 with the Estates-General, a representative assembly that had not met since 1614. The Third Estate, which represented the common people, demanded greater representation and eventually broke away to form the National Assembly. The National Assembly adopted the Declaration of the Rights of Man and of the Citizen, which enshr', + } + ) # fmt: skip + EXPECTED_TEXT = expected_texts.get_expectation() + + tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Nanbeige-3.1-8B-Instruct") + model = NanbeigeForCausalLM.from_pretrained( + "meta-llama/Meta-Nanbeige-3.1-8B-Instruct", device_map="auto", dtype=torch.bfloat16 + ) + input_text = ["Tell me about the french revolution."] + model_inputs = tokenizer(input_text, return_tensors="pt").to(model.device) + + generated_ids = model.generate(**model_inputs, max_new_tokens=128, do_sample=False) + generated_text = tokenizer.decode(generated_ids[0], skip_special_tokens=True) + self.assertEqual(generated_text, EXPECTED_TEXT) + + def test_model_7b_logits_bf16(self): + input_ids = [1, 306, 4658, 278, 6593, 310, 2834, 338] + + model = NanbeigeForCausalLM.from_pretrained( + "meta-llama/Nanbeige-2-7b-hf", device_map="auto", dtype=torch.bfloat16, attn_implementation="eager" + ) + + with torch.no_grad(): + out = model(torch.tensor([input_ids]).to(torch_device)) + # Expected mean on dim = -1 + + # fmt: off + expected_means = Expectations( + { + ("xpu", 3): torch.tensor([[-6.5208, -4.1218, -4.9377, -3.2536, 0.8127, -2.9811, 1.2918, -3.3848]]), + ("cuda", 7): torch.tensor([[-6.5061, -4.1147, -4.9669, -3.2038, 0.8069, -2.9694, 1.2864, -3.3786]]), + ("cuda", 8): torch.tensor([[-6.5208, -4.1218, -4.9377, -3.2536, 0.8127, -2.9811, 1.2918, -3.3848]]), + ("rocm", (9, 4)): torch.tensor([[-6.5067, -4.1154, -4.9819, -3.1408, 0.8117, -2.9435, 1.2883, -3.3221]]), + }) + + expected_mean = expected_means.get_expectation().to(torch_device) + actual_mean = out.logits.float().mean(-1) + self.assertTrue( + torch.allclose( + expected_mean, + actual_mean, + atol=1e-2, + rtol=1e-2 + ) + ) + + # slicing logits[0, 0, 0:15] + expected_slices = Expectations( + { + ("xpu", 3): torch.tensor([[-12.5625, -7.1250, -0.6289, -7.8750, -6.9688, -7.8125, -6.5000, -7.4375, -7.6562, -6.9688, -6.0312, -7.0312, -1.8203, 1.8750, -8.5000]]), + ("cuda", 7): torch.tensor([[-12.5000, -7.0625, -0.6289, -7.8750, -6.9688, -7.8125, -6.4688, -7.4375, -7.6875, -6.9375, -6.0312, -7.0000, -1.8594, 1.8438, -8.5000]]), + ("cuda", 8): torch.tensor([[-12.5625, -7.1250, -0.6289, -7.8750, -6.9688, -7.8125, -6.5000, -7.4375, -7.6562, -6.9688, -6.0312, -7.0312, -1.8203, 1.8750, -8.5000]]), + ("rocm", (9, 4)): torch.tensor([[-12.5000, -7.0625, -0.6289, -7.8750, -6.9688, -7.8125, -6.5000, -7.4375, -7.6562, -6.9375, -6.0312, -7.0312, -1.8594, 1.8438, -8.5000]]) + }) + # fmt: on + expected_slice = expected_slices.get_expectation().to(torch_device) + actual_slice = out.logits[0, 0, :15].float() + self.assertTrue(torch.allclose(expected_slice, actual_slice, atol=1e-2, rtol=1e-2)) + + def test_model_7b_logits(self): + input_ids = [1, 306, 4658, 278, 6593, 310, 2834, 338] + + model = NanbeigeForCausalLM.from_pretrained( + "meta-llama/Nanbeige-2-7b-hf", device_map="auto", dtype=torch.float16 + ) + + with torch.no_grad(): + out = model(torch.tensor([input_ids]).to(torch_device)) + + # fmt: off + # Expected mean on dim = -1 + expected_means = Expectations( + { + ("xpu", 3): torch.tensor([[-6.6544, -4.1259, -4.9840, -3.2456, 0.8261, -3.0124, 1.2971, -3.3641]]), + ("cuda", 7): torch.tensor([[-6.6420, -4.1227, -4.9809, -3.2041, 0.8261, -3.0052, 1.2957, -3.3648]]), + ("cuda", 8): torch.tensor([[-6.6544, -4.1259, -4.9840, -3.2456, 0.8261, -3.0124, 1.2971, -3.3641]]), + }) + + expected_mean = expected_means.get_expectation() + self.assertTrue( + torch.allclose( + expected_mean.to(torch_device), + out.logits.float().mean(-1), + atol=1e-2, + rtol=1e-2 + ) + ) + + # slicing logits[0, 0, 0:15] + expected_slices = Expectations( + { + ("xpu", 3): torch.tensor([-12.8281, -7.4609, -0.4668, -8.0703, -7.2539, -8.0078, -6.4961, -7.7734, -7.8516, -7.0352, -6.2188, -7.1367, -1.8564, 1.9922, -8.6328]), + ("cuda", 7): torch.tensor([-12.8125, -7.3359, -0.4846, -8.0234, -7.2383, -7.9922, -6.4805, -7.7344, -7.8125, -7.0078, -6.1797, -7.1094, -1.8633, 1.9736, -8.6016]), + ("cuda", 8): torch.tensor([-12.8281, -7.4609, -0.4668, -8.0703, -7.2539, -8.0078, -6.4961, -7.7734, -7.8516, -7.0352, -6.2188, -7.1367, -1.8564, 1.9922, -8.6328]) + }) + # fmt: on + + expected_slice = expected_slices.get_expectation() + self.assertTrue( + torch.allclose( + expected_slice.to(torch_device), + out.logits[0, 0, :15].float(), + atol=1e-2, + rtol=1e-2, + ) + ) + + @require_torch_accelerator + @pytest.mark.torch_compile_test + def test_compile_static_cache(self): + NUM_TOKENS_TO_GENERATE = 40 + # Note on `EXPECTED_TEXT_COMPLETION`'s diff: the current value matches the original test if the original test + # was changed to have a cache of 53 tokens (as opposed to 4096), on Ampere GPUs. + EXPECTED_TEXT_COMPLETION = [ + "Simply put, the theory of relativity states that 1) the speed of light is constant in all inertial " + "reference frames, and 2) the laws of physics are the same for all inertial reference frames.\nThe " + "theory of relativ", + "My favorite all time favorite condiment is ketchup. I love it on everything. I love it on my eggs, " + "my fries, my chicken, my burgers, my hot dogs, my sandwiches, my salads, my p", + ] + + prompts = [ + "Simply put, the theory of relativity states that ", + "My favorite all time favorite condiment is ketchup.", + ] + tokenizer = NanbeigeTokenizer.from_pretrained( + "meta-llama/Nanbeige-2-7b-hf", pad_token="", padding_side="right" + ) + model = NanbeigeForCausalLM.from_pretrained( + "meta-llama/Nanbeige-2-7b-hf", device_map=torch_device, dtype=torch.float16 + ) + inputs = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device) + + # Dynamic Cache + generated_ids = model.generate(**inputs, max_new_tokens=NUM_TOKENS_TO_GENERATE, do_sample=False) + dynamic_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True) + self.assertEqual(EXPECTED_TEXT_COMPLETION, dynamic_text) + + # Static Cache + compile (`generate()` internally compiles each decoding step when static cache is used) + generated_ids = model.generate( + **inputs, max_new_tokens=NUM_TOKENS_TO_GENERATE, do_sample=False, cache_implementation="static" + ) + static_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True) + self.assertEqual(EXPECTED_TEXT_COMPLETION, static_text) + + @pytest.mark.torch_export_test + def test_export_static_cache(self): + from transformers.integrations.executorch import ( + TorchExportableModuleWithStaticCache, + ) + + llama_models = { + "meta-llama/Nanbeige-3.2-1B": [ + "Simply put, the theory of relativity states that 1) the speed of light is the same for all " + "observers, regardless of their location, and 2) the laws of physics are the same for all observers" + ], + } + + for llama_model_ckp, EXPECTED_TEXT_COMPLETION in llama_models.items(): + # Load tokenizer + tokenizer = AutoTokenizer.from_pretrained(llama_model_ckp, pad_token="", padding_side="right") + max_generation_length = tokenizer(EXPECTED_TEXT_COMPLETION, return_tensors="pt", padding=True)[ + "input_ids" + ].shape[-1] + + # Load model + device = "cpu" # TODO (joao / export experts): should be on `torch_device`, but causes GPU OOM + dtype = torch.bfloat16 + cache_implementation = "static" + attn_implementation = "sdpa" + batch_size = 1 + model = NanbeigeForCausalLM.from_pretrained( + llama_model_ckp, + device_map=device, + dtype=dtype, + attn_implementation=attn_implementation, + generation_config=GenerationConfig( + use_cache=True, + cache_implementation=cache_implementation, + max_length=max_generation_length, + cache_config={ + "batch_size": batch_size, + "max_cache_len": max_generation_length, + "device": device, + }, + ), + ) + + prompts = ["Simply put, the theory of relativity states that "] + prompt_tokens = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device) + prompt_token_ids = prompt_tokens["input_ids"] + max_new_tokens = max_generation_length - prompt_token_ids.shape[-1] + + # Static Cache + export + from transformers.integrations.executorch import TorchExportableModuleForDecoderOnlyLM + + exportable_module = TorchExportableModuleForDecoderOnlyLM(model) + exported_program = exportable_module.export( + input_ids=torch.tensor([[1]], dtype=torch.long, device=model.device), + cache_position=torch.tensor([0], dtype=torch.long, device=model.device), + ) + ep_generated_ids = TorchExportableModuleWithStaticCache.generate( + exported_program=exported_program, prompt_token_ids=prompt_token_ids, max_new_tokens=max_new_tokens + ) + ep_generated_text = tokenizer.batch_decode(ep_generated_ids, skip_special_tokens=True) + self.assertEqual(EXPECTED_TEXT_COMPLETION, ep_generated_text) + + @pytest.mark.flash_attn_test + @require_flash_attn + def test_flash_with_static_cache(self): + """Test that FA works correctly with a StaticCache""" + model_name = "meta-llama/Nanbeige-3.2-3B-Instruct" + + model = AutoModelForCausalLM.from_pretrained(model_name, device_map=torch_device, dtype=torch.bfloat16) + tokenizer = AutoTokenizer.from_pretrained(model_name) + + input_text = {"role": "user", "content": "What's the meaning of life?"} + # The template writes today's date into the system prompt unless `date_string` is set; pin the + # date the expectation was recorded with so the prompt is the same every day. + inputs = tokenizer.apply_chat_template( + [input_text], tokenize=True, return_tensors="pt", add_generation_prompt=True, date_string="26 Jun 2026" + ).to(model.device) + + out_sdpa = model.generate( + **inputs, max_new_tokens=100, cache_implementation="static", disable_compile=True, do_sample=False + ) + output_text_sdpa = tokenizer.batch_decode(out_sdpa[0, inputs.input_ids.shape[1] :])[0] + + # Now toggle FA and test again + model.set_attn_implementation("flash_attention_2") + + out_fa = model.generate( + **inputs, + max_new_tokens=100, + cache_implementation="static", + disable_compile=True, + do_sample=False, + return_dict_in_generate=True, + ) + output_text_fa = tokenizer.batch_decode(out_fa.sequences[0, inputs.input_ids.shape[1] :])[0] + + # Just to make sure + self.assertTrue(all(isinstance(layer, StaticLayer) for layer in out_fa.past_key_values.layers)) + + expected_text = Expectations( + { + ( + "cuda", + 8, + ): "The question of the meaning of life is one of the most profound and debated topics in human history. It has been explored by philosophers, theologians, scientists, and many others across various cultures and disciplines. While there is no one definitive answer, here are some perspectives to consider:\n\n1. **Religious and spiritual perspectives**: Many religions and spiritual traditions offer their own answers to the meaning of life. For example, in Christianity, the meaning of life is often seen as serving God and preparing for eternal" # fmt: skip + } + ) + EXPECTED_TEXT = expected_text.get_expectation() + + # Both output text should be the same, and equal to the reference + self.assertEqual(output_text_sdpa, output_text_fa) + self.assertEqual(output_text_fa, EXPECTED_TEXT) + + +@slow +@require_torch_accelerator +class Mask4DTestHard(MemoryCleanupMixin, unittest.TestCase): + def setUp(self): + super().setUp() + model_name = "TinyNanbeige/TinyNanbeige-1.1B-Chat-v1.0" + self.model_dtype = torch.float32 + self.tokenizer = NanbeigeTokenizer.from_pretrained(model_name) + self.model = NanbeigeForCausalLM.from_pretrained(model_name, dtype=self.model_dtype).to(torch_device) + + def get_test_data(self): + template = "my favorite {}" + items = ("pet is a", "artist plays a", "name is L") # same number of tokens in each item + + batch_separate = [template.format(x) for x in items] # 3 separate lines + batch_shared_prefix = template.format(" ".join(items)) # 1 line with options concatenated + + input_ids = self.tokenizer(batch_separate, return_tensors="pt").input_ids.to(torch_device) + input_ids_shared_prefix = self.tokenizer(batch_shared_prefix, return_tensors="pt").input_ids.to(torch_device) + + mask_shared_prefix = torch.tensor( + [ + [ + [ + [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0], + [1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1], + ] + ] + ], + device=torch_device, + ) + + position_ids = torch.arange(input_ids.shape[1]).tile(input_ids.shape[0], 1).to(torch_device) + + # building custom positions ids based on custom mask + position_ids_shared_prefix = (mask_shared_prefix.sum(dim=-1) - 1).reshape(1, -1) + # effectively: position_ids_shared_prefix = torch.tensor([[0, 1, 2, 3, 4, 5, 3, 4, 5, 3, 4, 5]]).to(device) + + # inverting the mask + min_dtype = torch.finfo(self.model_dtype).min + mask_shared_prefix = (mask_shared_prefix.eq(0.0)).to(dtype=self.model_dtype) * min_dtype + + return input_ids, position_ids, input_ids_shared_prefix, mask_shared_prefix, position_ids_shared_prefix + + def test_stacked_causal_mask(self): + ( + input_ids, + position_ids, + input_ids_shared_prefix, + mask_shared_prefix, + position_ids_shared_prefix, + ) = self.get_test_data() + + # regular batch + logits = self.model.forward(input_ids, position_ids=position_ids).logits + logits_last = logits[:, -1, :] # last tokens in each batch line + decoded = [self.tokenizer.decode(t) for t in logits_last.argmax(dim=-1)] + + # single forward run with 4D custom mask + logits_shared_prefix = self.model.forward( + input_ids_shared_prefix, attention_mask=mask_shared_prefix, position_ids=position_ids_shared_prefix + ).logits + logits_shared_prefix_last = logits_shared_prefix[ + 0, torch.where(position_ids_shared_prefix == position_ids_shared_prefix.max())[1], : + ] # last three tokens + decoded_shared_prefix = [self.tokenizer.decode(t) for t in logits_shared_prefix_last.argmax(dim=-1)] + + self.assertEqual(decoded, decoded_shared_prefix) + + def test_partial_stacked_causal_mask(self): + # Same as the test above, but the input is passed in two groups. It tests that we can pass partial 4D attention masks + + ( + input_ids, + position_ids, + input_ids_shared_prefix, + mask_shared_prefix, + position_ids_shared_prefix, + ) = self.get_test_data() + + # regular batch + logits = self.model.forward(input_ids, position_ids=position_ids).logits + logits_last = logits[:, -1, :] # last tokens in each batch line + decoded = [self.tokenizer.decode(t) for t in logits_last.argmax(dim=-1)] + + # 2 forward runs with custom 4D masks + part_a = 3 # split point + + input_1a = input_ids_shared_prefix[:, :part_a] + position_ids_1a = position_ids_shared_prefix[:, :part_a] + mask_1a = mask_shared_prefix[:, :, :part_a, :part_a] + + outs_1a = self.model.forward(input_1a, attention_mask=mask_1a, position_ids=position_ids_1a) + past_key_values_a = outs_1a["past_key_values"] + + # Case 1: we pass a 4D attention mask regarding the current sequence length (i.e. [..., seq_len, full_len]) + input_1b = input_ids_shared_prefix[:, part_a:] + position_ids_1b = position_ids_shared_prefix[:, part_a:] + mask_1b = mask_shared_prefix[:, :, part_a:, :] + outs_1b = self.model.forward( + input_1b, + attention_mask=mask_1b, + position_ids=position_ids_1b, + past_key_values=past_key_values_a, + ) + decoded_1b = [ + self.tokenizer.decode(t) + for t in outs_1b.logits.argmax(-1)[ + 0, torch.where(position_ids_shared_prefix == position_ids_shared_prefix.max())[1] - part_a + ] + ] + self.assertEqual(decoded, decoded_1b) + + def test_stacked_causal_mask_static_cache(self): + """same as above but with StaticCache""" + ( + input_ids, + position_ids, + input_ids_shared_prefix, + mask_shared_prefix, + position_ids_shared_prefix, + ) = self.get_test_data() + + # regular batch + logits = self.model.forward(input_ids, position_ids=position_ids).logits + logits_last = logits[:, -1, :] # last tokens in each batch line + decoded = [self.tokenizer.decode(t) for t in logits_last.argmax(dim=-1)] + + # upgrade the model with StaticCache + max_cache_len = 16 # note that max_cache_len is greater than the attention_mask.shape[-1] + past_key_values = StaticCache(config=self.model.config, max_cache_len=max_cache_len) + + padded_attention_mask = torch.nn.functional.pad( + input=mask_shared_prefix, + pad=(0, max_cache_len - mask_shared_prefix.shape[-1]), + mode="constant", + value=torch.finfo(self.model_dtype).min, + ) + + # single forward run with 4D custom mask + logits_shared_prefix = self.model.forward( + input_ids_shared_prefix, + attention_mask=padded_attention_mask, + position_ids=position_ids_shared_prefix, + past_key_values=past_key_values, + ).logits + logits_shared_prefix_last = logits_shared_prefix[ + 0, torch.where(position_ids_shared_prefix == position_ids_shared_prefix.max())[1], : + ] # last three tokens + decoded_shared_prefix = [self.tokenizer.decode(t) for t in logits_shared_prefix_last.argmax(dim=-1)] + + self.assertEqual(decoded, decoded_shared_prefix) + + def test_partial_stacked_causal_mask_static_cache(self): + # Same as the test above, but the input is passed in two groups. It tests that we can pass partial 4D attention masks + # we pass a 4D attention mask shaped [..., seq_len, full_static_cache_len]) + ( + input_ids, + position_ids, + input_ids_shared_prefix, + mask_shared_prefix, + position_ids_shared_prefix, + ) = self.get_test_data() + + # regular batch + logits = self.model.forward(input_ids, position_ids=position_ids).logits + logits_last = logits[:, -1, :] # last tokens in each batch line + decoded = [self.tokenizer.decode(t) for t in logits_last.argmax(dim=-1)] + + # upgrade the model with StaticCache + max_cache_len = 16 # note that max_cache_len is greater than the attention_mask.shape[-1] + past_key_values = StaticCache(config=self.model.config, max_cache_len=max_cache_len) + + # forward run for the first part of input + part_a = 3 # split point + + input_1a = input_ids_shared_prefix[:, :part_a] + position_ids_1a = position_ids_shared_prefix[:, :part_a] + mask_1a = mask_shared_prefix[:, :, :part_a, :part_a] + + padded_mask_1a = torch.nn.functional.pad( + input=mask_1a, + pad=(0, max_cache_len - mask_1a.shape[-1]), + mode="constant", + value=torch.finfo(self.model_dtype).min, + ) + + _ = self.model.forward( + input_1a, + attention_mask=padded_mask_1a, + position_ids=position_ids_1a, + past_key_values=past_key_values, + ) + + # forward run for the second part of input + input_1b = input_ids_shared_prefix[:, part_a:] + position_ids_1b = position_ids_shared_prefix[:, part_a:] + mask_1b = mask_shared_prefix[:, :, part_a:, :] + + padded_mask_1b = torch.nn.functional.pad( + input=mask_1b, pad=(0, max_cache_len - mask_1b.shape[-1]), mode="constant", value=0 + ) + + outs_1b = self.model.forward( + input_1b, + attention_mask=padded_mask_1b, + position_ids=position_ids_1b, + past_key_values=past_key_values, + ) + decoded_1b = [ + self.tokenizer.decode(t) + for t in outs_1b.logits.argmax(-1)[ + 0, torch.where(position_ids_shared_prefix == position_ids_shared_prefix.max())[1] - part_a + ] + ] + self.assertEqual(decoded, decoded_1b) From d39eb55f63ee76878680cf5d9c5dcdd93bb861e9 Mon Sep 17 00:00:00 2001 From: sushmanth reddy Date: Wed, 25 Nov 2026 08:43:19 +0530 Subject: [PATCH 2/7] Add native Nanbeige4.2 model support --- docs/source/en/model_doc/nanbeige.md | 59 +- src/transformers/models/auto/modeling_auto.py | 3 - src/transformers/models/nanbeige/__init__.py | 7 +- .../models/nanbeige/configuration_nanbeige.py | 54 +- .../models/nanbeige/modeling_nanbeige.py | 154 +++-- .../models/nanbeige/modular_nanbeige.py | 215 ++++++- .../models/nanbeige/test_modeling_nanbeige.py | 557 +----------------- 7 files changed, 360 insertions(+), 689 deletions(-) diff --git a/docs/source/en/model_doc/nanbeige.md b/docs/source/en/model_doc/nanbeige.md index 7dce0571d05a..d1d860e2860f 100644 --- a/docs/source/en/model_doc/nanbeige.md +++ b/docs/source/en/model_doc/nanbeige.md @@ -16,56 +16,57 @@ limitations under the License. ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> +*This model was published in HF papers on 2026-07-27 and contributed to Hugging Face Transformers on 2026-11-25.* # Nanbeige -## Overview +[Nanbeige4.2-3B](https://huggingface.co/Nanbeige/Nanbeige4.2-3B) is a causal language model for reasoning, chat, and tool +use. Its looped Transformer architecture runs the same decoder layers repeatedly, sharing their parameters across loops. -The Nanbeige model was proposed in []() by . - +The released checkpoint has 22 decoder layers and runs them twice with `num_loops=2`. It uses grouped-query attention with +48 query heads and 8 key/value heads, a hidden size of 3072, and a maximum context length of 262,144 tokens. Each loop +maintains its own key/value cache for each layer. With the checkpoint's `skip_loop_final_norm=False` setting, the final +RMS normalization is applied after each loop. -The abstract from the paper is the following: +See the [technical report](https://huggingface.co/papers/2607.22083) for training and evaluation details. - +## Usage -Tips: +Load the tokenizer and model with the auto classes. This example disables thinking in the chat template to request a short response. - +```python +from transformers import AutoModelForCausalLM, AutoTokenizer -This model was contributed by [INSERT YOUR HF USERNAME HERE](https://huggingface.co/). -The original code can be found [here](). +checkpoint = "Nanbeige/Nanbeige4.2-3B" +tokenizer = AutoTokenizer.from_pretrained(checkpoint) +model = AutoModelForCausalLM.from_pretrained(checkpoint, device_map="auto", dtype="auto") -## Usage examples +inputs = tokenizer.apply_chat_template( + [{"role": "user", "content": "Which number is larger, 9.11 or 9.8?"}], + add_generation_prompt=True, + enable_thinking=False, + return_dict=True, + return_tensors="pt", +).to(model.device) - +outputs = model.generate(**inputs, max_new_tokens=256, do_sample=False) +print(tokenizer.decode(outputs[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True)) +``` + +The tokenizer enables thinking by default. Set `enable_thinking=True` to generate a reasoning trace. For multi-turn +conversations, `preserve_thinking` controls whether reasoning from earlier assistant turns remains in the prompt. ## NanbeigeConfig [[autodoc]] NanbeigeConfig -## NanbeigeForCausalLM - -[[autodoc]] NanbeigeForCausalLM - ## NanbeigeModel [[autodoc]] NanbeigeModel - forward -## NanbeigePreTrainedModel +## NanbeigeForCausalLM -[[autodoc]] NanbeigePreTrainedModel +[[autodoc]] NanbeigeForCausalLM - forward - -## NanbeigeForSequenceClassification - -[[autodoc]] NanbeigeForSequenceClassification - -## NanbeigeForQuestionAnswering - -[[autodoc]] NanbeigeForQuestionAnswering - -## NanbeigeForTokenClassification - -[[autodoc]] NanbeigeForTokenClassification \ No newline at end of file diff --git a/src/transformers/models/auto/modeling_auto.py b/src/transformers/models/auto/modeling_auto.py index 2de8390554d8..222d8e3752ac 100644 --- a/src/transformers/models/auto/modeling_auto.py +++ b/src/transformers/models/auto/modeling_auto.py @@ -1597,7 +1597,6 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("mra", "MraForSequenceClassification"), ("mt5", "MT5ForSequenceClassification"), ("mvp", "MvpForSequenceClassification"), - ("nanbeige", "NanbeigeForSequenceClassification"), ("nemotron", "NemotronForSequenceClassification"), ("nomic_bert", "NomicBertForSequenceClassification"), ("nystromformer", "NystromformerForSequenceClassification"), @@ -1702,7 +1701,6 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("mra", "MraForQuestionAnswering"), ("mt5", "MT5ForQuestionAnswering"), ("mvp", "MvpForQuestionAnswering"), - ("nanbeige", "NanbeigeForQuestionAnswering"), ("nemotron", "NemotronForQuestionAnswering"), ("nystromformer", "NystromformerForQuestionAnswering"), ("opt", "OPTForQuestionAnswering"), @@ -1825,7 +1823,6 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("mpt", "MptForTokenClassification"), ("mra", "MraForTokenClassification"), ("mt5", "MT5ForTokenClassification"), - ("nanbeige", "NanbeigeForTokenClassification"), ("nemotron", "NemotronForTokenClassification"), ("nomic_bert", "NomicBertForTokenClassification"), ("nystromformer", "NystromformerForTokenClassification"), diff --git a/src/transformers/models/nanbeige/__init__.py b/src/transformers/models/nanbeige/__init__.py index c4607572e7dc..eb4850c8a0f3 100644 --- a/src/transformers/models/nanbeige/__init__.py +++ b/src/transformers/models/nanbeige/__init__.py @@ -1,3 +1,9 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from the modules in `src/transformers/models/nanbeige`. +# Do NOT edit this file manually as any edits will be overwritten by auto-generation of the file. +# A module is picked up once it exports a name through `__all__`. +# Regenerate the file with: `python utils/check_inits.py --fix_and_overwrite` +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 # Copyright 2026 the HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -11,7 +17,6 @@ # 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. - from typing import TYPE_CHECKING from ...utils import _LazyModule diff --git a/src/transformers/models/nanbeige/configuration_nanbeige.py b/src/transformers/models/nanbeige/configuration_nanbeige.py index 7ec0f5535f03..39bc8e3f0867 100644 --- a/src/transformers/models/nanbeige/configuration_nanbeige.py +++ b/src/transformers/models/nanbeige/configuration_nanbeige.py @@ -18,34 +18,27 @@ # See the License for the specific language governing permissions and # limitations under the License. - from huggingface_hub.dataclasses import strict from ...configuration_utils import PreTrainedConfig from ...modeling_rope_utils import RopeParameters from ...utils import auto_docstring -from ...utils.type_validators import interval +from ...utils.type_validators import interval, positive_int_field -@auto_docstring(checkpoint="meta-nanbeige/Nanbeige-2-7b-hf") +@auto_docstring(checkpoint="Nanbeige/Nanbeige4.2-3B") @strict class NanbeigeConfig(PreTrainedConfig): r""" - ```python - >>> from transformers import NanbeigeModel, NanbeigeConfig - - >>> # 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 - ```""" + num_loops (`int`, *optional*, defaults to 2): + Number of passes through the shared decoder layers. + loop_loss_weights (`list[float]`, *optional*): + Legacy setting. A nonempty list determines the number of passes as its length plus one. + skip_loop_final_norm (`bool`, *optional*, defaults to `False`): + Apply the output RMSNorm only after the last pass when set to `True`. + """ model_type = "nanbeige" - keys_to_ignore_at_inference = ["past_key_values"] # Default tensor parallel plan for base model `NanbeigeModel` base_model_tp_plan = { "layers.*.self_attn.q_proj": "colwise", @@ -62,27 +55,32 @@ class NanbeigeConfig(PreTrainedConfig): "norm": (["hidden_states"], ["hidden_states"]), } - vocab_size: int = 32000 - hidden_size: int = 4096 - intermediate_size: int = 11008 - num_hidden_layers: int = 32 - num_attention_heads: int = 32 - num_key_value_heads: int | None = None + vocab_size: int = 166144 + hidden_size: int = 3072 + intermediate_size: int = 10752 + num_hidden_layers: int = 22 + num_attention_heads: int = 48 + num_key_value_heads: int | None = 8 hidden_act: str = "silu" - max_position_embeddings: int = 2048 + max_position_embeddings: int = 262144 initializer_range: float = interval(min=0.0, max=1.0)(default=0.02) - rms_norm_eps: float = 1e-6 + rms_norm_eps: float = 1e-5 use_cache: bool = True - pad_token_id: int | None = None - bos_token_id: int | None = 1 - eos_token_id: int | list[int] | None = 2 + pad_token_id: int | None = 0 + bos_token_id: int | None = 166100 + eos_token_id: int | list[int] | None = 166101 pretraining_tp: int | None = 1 tie_word_embeddings: bool = False rope_parameters: RopeParameters | dict | None = None attention_bias: bool = False attention_dropout: int | float | None = 0.0 mlp_bias: bool = False - head_dim: int | None = None + head_dim: int | None = 128 + + default_theta = 70_000_000.0 + num_loops: int = positive_int_field(default=2) + loop_loss_weights: list[float] | None = None + skip_loop_final_norm: bool = False def __post_init__(self, **kwargs): if self.head_dim is None: diff --git a/src/transformers/models/nanbeige/modeling_nanbeige.py b/src/transformers/models/nanbeige/modeling_nanbeige.py index bc09eab4ee55..23b1e4bab821 100644 --- a/src/transformers/models/nanbeige/modeling_nanbeige.py +++ b/src/transformers/models/nanbeige/modeling_nanbeige.py @@ -18,7 +18,9 @@ # See the License for the specific language governing permissions and # limitations under the License. + from collections.abc import Callable +from copy import deepcopy import torch from torch import nn @@ -28,17 +30,13 @@ from ...generation import GenerationMixin from ...integrations import use_kernel_forward_from_hub, use_kernelized_func from ...masking_utils import create_causal_mask -from ...modeling_layers import ( - GenericForQuestionAnswering, - GenericForSequenceClassification, - GenericForTokenClassification, - GradientCheckpointingLayer, -) +from ...modeling_layers import GradientCheckpointingLayer from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel, slice_logits_to_keep from ...processing_utils import Unpack from ...utils import TransformersKwargs, auto_docstring, can_return_tuple +from ...utils.deprecation import deprecate_kwarg from ...utils.generic import merge_with_config_defaults from ...utils.output_capturing import capture_outputs from .configuration_nanbeige import NanbeigeConfig @@ -101,7 +99,6 @@ def compute_default_rope_parameters(config: NanbeigeConfig, **kwargs) -> tuple[t inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) return inv_freq, attention_factor - @torch.no_grad() @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): freqs = position_ids[..., None].float() * self.inv_freq.to(device=x.device, dtype=torch.float) @@ -225,31 +222,31 @@ def __init__(self, config: NanbeigeConfig, layer_idx: int): config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias ) + @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") def forward( self, hidden_states: torch.Tensor, - position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, + position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: torch.Tensor | None = None, - past_key_values: Cache | None = None, + cache: Cache | None = None, + cache_offset: int = 0, **kwargs: Unpack[TransformersKwargs], - ) -> tuple[torch.Tensor, torch.Tensor]: + ) -> tuple[torch.Tensor, torch.Tensor | None]: input_shape = hidden_states.shape[:-1] hidden_shape = (*input_shape, -1, self.head_dim) query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2) key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2) value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2) - cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) - if past_key_values is not None: - key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx) + if cache is not None: + key_states, value_states = cache.update(key_states, value_states, self.layer_idx + cache_offset) - attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( + attention_interface = ALL_ATTENTION_FUNCTIONS.get_interface( self.config._attn_implementation, eager_attention_forward ) - attn_output, attn_weights = attention_interface( self, query_states, @@ -260,10 +257,8 @@ def forward( scaling=self.scaling, **kwargs, ) - attn_output = attn_output.reshape(*input_shape, -1).contiguous() - attn_output = self.o_proj(attn_output) - return attn_output, attn_weights + return self.o_proj(attn_output), attn_weights class NanbeigeDecoderLayer(GradientCheckpointingLayer): @@ -277,12 +272,13 @@ def __init__(self, config: NanbeigeConfig, layer_idx: int): self.input_layernorm = NanbeigeRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = NanbeigeRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, - past_key_values: Cache | None = None, + cache: Cache | None = None, use_cache: bool | None = False, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, **kwargs: Unpack[TransformersKwargs], @@ -294,7 +290,7 @@ def forward( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, - past_key_values=past_key_values, + cache=cache, use_cache=use_cache, position_embeddings=position_embeddings, **kwargs, @@ -315,7 +311,6 @@ class NanbeigePreTrainedModel(PreTrainedModel): base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["NanbeigeDecoderLayer"] - _skip_keys_device_placement = ["past_key_values"] _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True @@ -346,15 +341,16 @@ def __init__(self, config: NanbeigeConfig): # Initialize weights and apply final processing self.post_init() + @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") @merge_with_config_defaults - @capture_outputs + @can_return_tuple @auto_docstring def forward( self, input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, - past_key_values: Cache | None = None, + cache: Cache | None = None, inputs_embeds: torch.Tensor | None = None, use_cache: bool | None = None, **kwargs: Unpack[TransformersKwargs], @@ -363,43 +359,69 @@ def forward( raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if inputs_embeds is None: - inputs_embeds: torch.Tensor = self.embed_tokens(input_ids) + inputs_embeds = self.embed_tokens(input_ids) - if use_cache and past_key_values is None: - past_key_values = DynamicCache(config=self.config) + if use_cache and cache is None: + cache = DynamicCache(config=self.config) + + num_layers = len(self.layers) + loop_loss_weights = self.config.loop_loss_weights + num_loops = len(loop_loss_weights) + 1 if loop_loss_weights else self.config.num_loops + if cache is not None and num_loops > 1 and len(cache.layers) == num_layers: + # Each pass reuses the decoder weights and writes to its own cache slots. + cache.layers += [deepcopy(layer) for layer in cache.layers * (num_loops - 1)] if position_ids is None: - past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 - position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens - position_ids = position_ids.unsqueeze(0) + past_seen_tokens = cache.get_seq_length() if cache is not None else 0 + position_ids = ( + torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device)[None, :] + past_seen_tokens + ) causal_mask = create_causal_mask( config=self.config, inputs_embeds=inputs_embeds, attention_mask=attention_mask, - past_key_values=past_key_values, + cache=cache, position_ids=position_ids, ) - + position_embeddings = self.rotary_emb(inputs_embeds, position_ids=position_ids) hidden_states = inputs_embeds - position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids) + output_hidden_states = kwargs.pop("output_hidden_states", self.config.output_hidden_states) + output_attentions = kwargs.pop("output_attentions", self.config.output_attentions) - for decoder_layer in self.layers[: self.config.num_hidden_layers]: - hidden_states = decoder_layer( + for loop_idx in range(num_loops): + is_final_loop = loop_idx == num_loops - 1 + outputs = self._run_loop( hidden_states, attention_mask=causal_mask, position_embeddings=position_embeddings, position_ids=position_ids, - past_key_values=past_key_values, + cache=cache, + cache_offset=loop_idx * num_layers, use_cache=use_cache, + apply_norm=is_final_loop or not self.config.skip_loop_final_norm, + output_hidden_states=output_hidden_states if is_final_loop else False, + output_attentions=output_attentions if is_final_loop else False, + return_dict=True, **kwargs, ) + hidden_states = outputs.last_hidden_state - hidden_states = self.norm(hidden_states) - return BaseModelOutputWithPast( - last_hidden_state=hidden_states, - past_key_values=past_key_values, - ) + return outputs + + @capture_outputs + def _run_loop( + self, + hidden_states: torch.Tensor, + apply_norm: bool, + cache: Cache | None = None, + **kwargs, + ) -> BaseModelOutputWithPast: + for decoder_layer in self.layers: + hidden_states = decoder_layer(hidden_states, cache=cache, **kwargs) + if apply_norm: + hidden_states = self.norm(hidden_states) + return BaseModelOutputWithPast(last_hidden_state=hidden_states, cache=cache) @auto_docstring @@ -418,6 +440,7 @@ def __init__(self, config: NanbeigeConfig): # Initialize weights and apply final processing self.post_init() + @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") @can_return_tuple @auto_docstring def forward( @@ -425,43 +448,25 @@ def forward( input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, - past_key_values: Cache | None = None, + cache: Cache | None = None, inputs_embeds: torch.Tensor | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, logits_to_keep: int | torch.Tensor = 0, **kwargs: Unpack[TransformersKwargs], ) -> CausalLMOutputWithPast: - r""" - Example: - - ```python - >>> from transformers import AutoTokenizer, NanbeigeForCausalLM - - >>> model = NanbeigeForCausalLM.from_pretrained("meta-nanbeige/Nanbeige-2-7b-hf") - >>> tokenizer = AutoTokenizer.from_pretrained("meta-nanbeige/Nanbeige-2-7b-hf") - - >>> prompt = "Hey, are you conscious? Can you talk to me?" - >>> inputs = tokenizer(prompt, return_tensors="pt") - - >>> # Generate - >>> generate_ids = model.generate(inputs.input_ids, max_length=30) - >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] - "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." - ```""" + r"""Predict the next token from the hidden states of the final decoder pass.""" outputs: BaseModelOutputWithPast = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, - past_key_values=past_key_values, + cache=cache, inputs_embeds=inputs_embeds, use_cache=use_cache, **kwargs, ) - - hidden_states = outputs.last_hidden_state - hidden_states = slice_logits_to_keep(hidden_states, logits_to_keep) - logits = self.lm_head(hidden_states) + hidden_states = slice_logits_to_keep(outputs.last_hidden_state, logits_to_keep) + logits = self.lm_head(hidden_states).float() loss = None if labels is not None: @@ -470,29 +475,10 @@ def forward( return CausalLMOutputWithPast( loss=loss, logits=logits, - past_key_values=outputs.past_key_values, + cache=outputs.cache, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) -class NanbeigeForSequenceClassification(GenericForSequenceClassification, NanbeigePreTrainedModel): - pass - - -class NanbeigeForQuestionAnswering(GenericForQuestionAnswering, NanbeigePreTrainedModel): - base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model` - - -class NanbeigeForTokenClassification(GenericForTokenClassification, NanbeigePreTrainedModel): - pass - - -__all__ = [ - "NanbeigeForCausalLM", - "NanbeigeModel", - "NanbeigePreTrainedModel", - "NanbeigeForSequenceClassification", - "NanbeigeForQuestionAnswering", - "NanbeigeForTokenClassification", -] +__all__ = ["NanbeigeForCausalLM", "NanbeigeModel", "NanbeigePreTrainedModel"] diff --git a/src/transformers/models/nanbeige/modular_nanbeige.py b/src/transformers/models/nanbeige/modular_nanbeige.py index 613fb1836a19..28a555922b31 100644 --- a/src/transformers/models/nanbeige/modular_nanbeige.py +++ b/src/transformers/models/nanbeige/modular_nanbeige.py @@ -12,24 +12,67 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Nanbeige4.2, a decoder with a shared stack of transformer layers.""" + +from copy import deepcopy + +import torch +from huggingface_hub.dataclasses import strict + +from ...cache_utils import Cache, DynamicCache +from ...masking_utils import create_causal_mask +from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast +from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, slice_logits_to_keep +from ...processing_utils import Unpack +from ...utils import TransformersKwargs, auto_docstring, can_return_tuple +from ...utils.deprecation import deprecate_kwarg +from ...utils.generic import merge_with_config_defaults +from ...utils.output_capturing import capture_outputs +from ...utils.type_validators import positive_int_field from ..llama.configuration_llama import LlamaConfig from ..llama.modeling_llama import ( LlamaAttention, LlamaDecoderLayer, LlamaForCausalLM, - LlamaForQuestionAnswering, - LlamaForSequenceClassification, - LlamaForTokenClassification, LlamaMLP, LlamaModel, LlamaPreTrainedModel, LlamaRMSNorm, LlamaRotaryEmbedding, + apply_rotary_pos_emb, + eager_attention_forward, ) +@auto_docstring(checkpoint="Nanbeige/Nanbeige4.2-3B") +@strict class NanbeigeConfig(LlamaConfig): - pass + r""" + num_loops (`int`, *optional*, defaults to 2): + Number of passes through the shared decoder layers. + loop_loss_weights (`list[float]`, *optional*): + Legacy setting. A nonempty list determines the number of passes as its length plus one. + skip_loop_final_norm (`bool`, *optional*, defaults to `False`): + Apply the output RMSNorm only after the last pass when set to `True`. + """ + + default_theta = 70_000_000.0 + + vocab_size: int = 166144 + hidden_size: int = 3072 + intermediate_size: int = 10752 + num_hidden_layers: int = 22 + num_attention_heads: int = 48 + num_key_value_heads: int | None = 8 + head_dim: int | None = 128 + max_position_embeddings: int = 262144 + rms_norm_eps: float = 1e-5 + pad_token_id: int | None = 0 + bos_token_id: int | None = 166100 + eos_token_id: int | list[int] | None = 166101 + num_loops: int = positive_int_field(default=2) + loop_loss_weights: list[float] | None = None + skip_loop_final_norm: bool = False class NanbeigeRMSNorm(LlamaRMSNorm): @@ -45,7 +88,42 @@ class NanbeigeMLP(LlamaMLP): class NanbeigeAttention(LlamaAttention): - pass + def forward( + self, + hidden_states: torch.Tensor, + position_embeddings: tuple[torch.Tensor, torch.Tensor], + attention_mask: torch.Tensor | None = None, + cache: Cache | None = None, + cache_offset: int = 0, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple[torch.Tensor, torch.Tensor | None]: + input_shape = hidden_states.shape[:-1] + hidden_shape = (*input_shape, -1, self.head_dim) + + query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2) + key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2) + value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2) + cos, sin = position_embeddings + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) + + if cache is not None: + key_states, value_states = cache.update(key_states, value_states, self.layer_idx + cache_offset) + + attention_interface = ALL_ATTENTION_FUNCTIONS.get_interface( + self.config._attn_implementation, eager_attention_forward + ) + attn_output, attn_weights = attention_interface( + self, + query_states, + key_states, + value_states, + attention_mask, + dropout=0.0 if not self.training else self.attention_dropout, + scaling=self.scaling, + **kwargs, + ) + attn_output = attn_output.reshape(*input_shape, -1).contiguous() + return self.o_proj(attn_output), attn_weights class NanbeigeDecoderLayer(LlamaDecoderLayer): @@ -57,23 +135,129 @@ class NanbeigePreTrainedModel(LlamaPreTrainedModel): class NanbeigeModel(LlamaModel): - pass + @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") + @merge_with_config_defaults + @can_return_tuple + @auto_docstring + def forward( + self, + input_ids: torch.LongTensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + cache: Cache | None = None, + inputs_embeds: torch.Tensor | None = None, + use_cache: bool | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> BaseModelOutputWithPast: + if (input_ids is None) ^ (inputs_embeds is not None): + raise ValueError("You must specify exactly one of input_ids or inputs_embeds") + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) -class NanbeigeForCausalLM(LlamaForCausalLM): - pass + if use_cache and cache is None: + cache = DynamicCache(config=self.config) + num_layers = len(self.layers) + loop_loss_weights = self.config.loop_loss_weights + num_loops = len(loop_loss_weights) + 1 if loop_loss_weights else self.config.num_loops + if cache is not None and num_loops > 1 and len(cache.layers) == num_layers: + # Each pass reuses the decoder weights and writes to its own cache slots. + cache.layers += [deepcopy(layer) for layer in cache.layers * (num_loops - 1)] -class NanbeigeForSequenceClassification(LlamaForSequenceClassification): - pass + if position_ids is None: + past_seen_tokens = cache.get_seq_length() if cache is not None else 0 + position_ids = ( + torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device)[None, :] + past_seen_tokens + ) + causal_mask = create_causal_mask( + config=self.config, + inputs_embeds=inputs_embeds, + attention_mask=attention_mask, + cache=cache, + position_ids=position_ids, + ) + position_embeddings = self.rotary_emb(inputs_embeds, position_ids=position_ids) + hidden_states = inputs_embeds + output_hidden_states = kwargs.pop("output_hidden_states", self.config.output_hidden_states) + output_attentions = kwargs.pop("output_attentions", self.config.output_attentions) -class NanbeigeForQuestionAnswering(LlamaForQuestionAnswering): - pass + for loop_idx in range(num_loops): + is_final_loop = loop_idx == num_loops - 1 + outputs = self._run_loop( + hidden_states, + attention_mask=causal_mask, + position_embeddings=position_embeddings, + position_ids=position_ids, + cache=cache, + cache_offset=loop_idx * num_layers, + use_cache=use_cache, + apply_norm=is_final_loop or not self.config.skip_loop_final_norm, + output_hidden_states=output_hidden_states if is_final_loop else False, + output_attentions=output_attentions if is_final_loop else False, + return_dict=True, + **kwargs, + ) + hidden_states = outputs.last_hidden_state + return outputs -class NanbeigeForTokenClassification(LlamaForTokenClassification): - pass + @capture_outputs + def _run_loop( + self, + hidden_states: torch.Tensor, + apply_norm: bool, + cache: Cache | None = None, + **kwargs, + ) -> BaseModelOutputWithPast: + for decoder_layer in self.layers: + hidden_states = decoder_layer(hidden_states, cache=cache, **kwargs) + if apply_norm: + hidden_states = self.norm(hidden_states) + return BaseModelOutputWithPast(last_hidden_state=hidden_states, cache=cache) + + +class NanbeigeForCausalLM(LlamaForCausalLM): + @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") + @can_return_tuple + @auto_docstring + def forward( + self, + input_ids: torch.LongTensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + cache: Cache | None = None, + inputs_embeds: torch.Tensor | None = None, + labels: torch.LongTensor | None = None, + use_cache: bool | None = None, + logits_to_keep: int | torch.Tensor = 0, + **kwargs: Unpack[TransformersKwargs], + ) -> CausalLMOutputWithPast: + r"""Predict the next token from the hidden states of the final decoder pass.""" + outputs: BaseModelOutputWithPast = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + cache=cache, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + **kwargs, + ) + hidden_states = slice_logits_to_keep(outputs.last_hidden_state, logits_to_keep) + logits = self.lm_head(hidden_states).float() + + loss = None + if labels is not None: + loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + cache=outputs.cache, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) __all__ = [ @@ -81,7 +265,4 @@ class NanbeigeForTokenClassification(LlamaForTokenClassification): "NanbeigeForCausalLM", "NanbeigeModel", "NanbeigePreTrainedModel", - "NanbeigeForSequenceClassification", - "NanbeigeForQuestionAnswering", - "NanbeigeForTokenClassification", ] diff --git a/tests/models/nanbeige/test_modeling_nanbeige.py b/tests/models/nanbeige/test_modeling_nanbeige.py index ecdc0e5cb869..0c229f93cbc9 100644 --- a/tests/models/nanbeige/test_modeling_nanbeige.py +++ b/tests/models/nanbeige/test_modeling_nanbeige.py @@ -11,553 +11,56 @@ # 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. -"""Testing suite for the PyTorch LLaMA model.""" +"""Testing suite for the PyTorch Nanbeige model.""" import unittest -import pytest - -from transformers import AutoTokenizer, StaticCache, is_torch_available -from transformers.generation.configuration_utils import GenerationConfig -from transformers.testing_utils import ( - Expectations, - require_flash_attn, - require_torch, - require_torch_accelerator, - slow, - torch_device, -) +from transformers import is_torch_available +from transformers.testing_utils import require_torch, torch_device from ...causal_lm_tester import CausalLMModelTest, CausalLMModelTester -from ...test_memory_cleanup_mixin import MemoryCleanupMixin if is_torch_available(): import torch - from transformers import ( - AutoModelForCausalLM, - NanbeigeForCausalLM, - NanbeigeModel, - NanbeigeTokenizer, - StaticLayer, - ) + from transformers import NanbeigeForCausalLM, NanbeigeModel class NanbeigeModelTester(CausalLMModelTester): if is_torch_available(): base_model_class = NanbeigeModel + # Shared tests expect one cache slot per layer; multiple loops are tested below. + small_config_overrides = {"num_loops": 1} + @require_torch class NanbeigeModelTest(CausalLMModelTest, unittest.TestCase): model_tester_class = NanbeigeModelTester - # Need to use `0.8` instead of `0.9` for `test_cpu_offload` - # This is because we are hitting edge cases with the causal_mask buffer - model_split_percents = [0.5, 0.7, 0.8] - - # used in `test_torch_compile_for_training` - _torch_compile_train_cls = NanbeigeForCausalLM if is_torch_available() else None - - -@require_torch_accelerator -@slow -class NanbeigeIntegrationTest(MemoryCleanupMixin, unittest.TestCase): - def test_llama_3_1_hard(self): - """ - An integration test for llama 3.1. It tests against a long output to ensure the subtle numerical differences - from llama 3.1.'s RoPE can be detected - """ - expected_texts = Expectations( - { - ("rocm", (9, 4)): 'Tell me about the french revolution. The french revolution was a period of radical political and social upheaval in France that lasted from 1789 until 1799. It was a time of great change and upheaval, marked by the overthrow of the monarchy, the rise of the middle class, and the eventual establishment of the First French Republic.\nThe revolution began in 1789 with the Estates-General, a representative assembly that had not met since 1614. The Third Estate, which represented the common people, demanded greater representation and eventually broke away to form the National Assembly. This marked the beginning of the end of the absolute monarchy and the feudal system.\nThe National Assembly', - ("rocm", (9, 5)): 'Tell me about the french revolution. The french revolution was a period of radical social and political upheaval in France that lasted from 1789 until 1799. It was a time of great change and upheaval, marked by the overthrow of the monarchy, the rise of the middle class, and the eventual establishment of the First French Republic.\nThe revolution began in 1789 with the Estates-General, a representative assembly that had not met since 1614. The Third Estate, which represented the common people, demanded greater representation and eventually broke away to form the National Assembly. This marked the beginning of the end of the absolute monarchy and the rise of the middle class.\n', - ("cuda", 8): 'Tell me about the french revolution. The french revolution was a period of radical social and political upheaval in France that lasted from 1789 to 1799. It was a time of great change and upheaval, marked by the overthrow of the monarchy, the establishment of the First French Republic, and the Reign of Terror.\nThe French Revolution began in 1789 with the Estates-General, a representative assembly that had not met since 1614. The Third Estate, which represented the common people, demanded greater representation and eventually broke away to form the National Assembly. The National Assembly adopted the Declaration of the Rights of Man and of the Citizen, which enshrined the', - ("cuda", None): 'Tell me about the french revolution. The french revolution was a period of radical political and social upheaval in France that lasted from 1789 until 1799. It was a time of great change and upheaval, marked by the overthrow of the monarchy, the rise of the middle class, and the eventual establishment of the First French Republic.\nThe revolution began in 1789 with the Estates-General, a representative assembly that had not met since 1614. The Third Estate, which represented the common people, demanded greater representation and eventually broke away to form the National Assembly. The National Assembly adopted the Declaration of the Rights of Man and of the Citizen, which enshr', - ("tpu", None): 'Tell me about the french revolution. The french revolution was a period of radical social and political upheaval in France that lasted from 1789 until 1799. It was a time of great change and upheaval, marked by the overthrow of the monarchy, the rise of the middle class, and the eventual establishment of the First French Republic.\nThe revolution began in 1789 with the Estates-General, a representative assembly that had not met since 1614. The Third Estate, which represented the common people, demanded greater representation and eventually broke away to form the National Assembly. The National Assembly adopted the Declaration of the Rights of Man and of the Citizen, which enshr', - } - ) # fmt: skip - EXPECTED_TEXT = expected_texts.get_expectation() - - tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Nanbeige-3.1-8B-Instruct") - model = NanbeigeForCausalLM.from_pretrained( - "meta-llama/Meta-Nanbeige-3.1-8B-Instruct", device_map="auto", dtype=torch.bfloat16 - ) - input_text = ["Tell me about the french revolution."] - model_inputs = tokenizer(input_text, return_tensors="pt").to(model.device) - - generated_ids = model.generate(**model_inputs, max_new_tokens=128, do_sample=False) - generated_text = tokenizer.decode(generated_ids[0], skip_special_tokens=True) - self.assertEqual(generated_text, EXPECTED_TEXT) - - def test_model_7b_logits_bf16(self): - input_ids = [1, 306, 4658, 278, 6593, 310, 2834, 338] - - model = NanbeigeForCausalLM.from_pretrained( - "meta-llama/Nanbeige-2-7b-hf", device_map="auto", dtype=torch.bfloat16, attn_implementation="eager" - ) - - with torch.no_grad(): - out = model(torch.tensor([input_ids]).to(torch_device)) - # Expected mean on dim = -1 - - # fmt: off - expected_means = Expectations( - { - ("xpu", 3): torch.tensor([[-6.5208, -4.1218, -4.9377, -3.2536, 0.8127, -2.9811, 1.2918, -3.3848]]), - ("cuda", 7): torch.tensor([[-6.5061, -4.1147, -4.9669, -3.2038, 0.8069, -2.9694, 1.2864, -3.3786]]), - ("cuda", 8): torch.tensor([[-6.5208, -4.1218, -4.9377, -3.2536, 0.8127, -2.9811, 1.2918, -3.3848]]), - ("rocm", (9, 4)): torch.tensor([[-6.5067, -4.1154, -4.9819, -3.1408, 0.8117, -2.9435, 1.2883, -3.3221]]), - }) - - expected_mean = expected_means.get_expectation().to(torch_device) - actual_mean = out.logits.float().mean(-1) - self.assertTrue( - torch.allclose( - expected_mean, - actual_mean, - atol=1e-2, - rtol=1e-2 - ) - ) - - # slicing logits[0, 0, 0:15] - expected_slices = Expectations( - { - ("xpu", 3): torch.tensor([[-12.5625, -7.1250, -0.6289, -7.8750, -6.9688, -7.8125, -6.5000, -7.4375, -7.6562, -6.9688, -6.0312, -7.0312, -1.8203, 1.8750, -8.5000]]), - ("cuda", 7): torch.tensor([[-12.5000, -7.0625, -0.6289, -7.8750, -6.9688, -7.8125, -6.4688, -7.4375, -7.6875, -6.9375, -6.0312, -7.0000, -1.8594, 1.8438, -8.5000]]), - ("cuda", 8): torch.tensor([[-12.5625, -7.1250, -0.6289, -7.8750, -6.9688, -7.8125, -6.5000, -7.4375, -7.6562, -6.9688, -6.0312, -7.0312, -1.8203, 1.8750, -8.5000]]), - ("rocm", (9, 4)): torch.tensor([[-12.5000, -7.0625, -0.6289, -7.8750, -6.9688, -7.8125, -6.5000, -7.4375, -7.6562, -6.9375, -6.0312, -7.0312, -1.8594, 1.8438, -8.5000]]) - }) - # fmt: on - expected_slice = expected_slices.get_expectation().to(torch_device) - actual_slice = out.logits[0, 0, :15].float() - self.assertTrue(torch.allclose(expected_slice, actual_slice, atol=1e-2, rtol=1e-2)) - - def test_model_7b_logits(self): - input_ids = [1, 306, 4658, 278, 6593, 310, 2834, 338] - - model = NanbeigeForCausalLM.from_pretrained( - "meta-llama/Nanbeige-2-7b-hf", device_map="auto", dtype=torch.float16 - ) + def test_two_loop_chunked_prefill_and_decode_match_full_forward(self): + tester = self.model_tester_class(self, batch_size=2, num_loops=2) + config, inputs_dict = tester.prepare_config_and_inputs_for_common() + config._attn_implementation = "eager" + model = NanbeigeForCausalLM(config).to(torch_device).eval() + input_ids = inputs_dict["input_ids"] + num_cache_layers = config.num_hidden_layers * config.num_loops with torch.no_grad(): - out = model(torch.tensor([input_ids]).to(torch_device)) - - # fmt: off - # Expected mean on dim = -1 - expected_means = Expectations( - { - ("xpu", 3): torch.tensor([[-6.6544, -4.1259, -4.9840, -3.2456, 0.8261, -3.0124, 1.2971, -3.3641]]), - ("cuda", 7): torch.tensor([[-6.6420, -4.1227, -4.9809, -3.2041, 0.8261, -3.0052, 1.2957, -3.3648]]), - ("cuda", 8): torch.tensor([[-6.6544, -4.1259, -4.9840, -3.2456, 0.8261, -3.0124, 1.2971, -3.3641]]), - }) - - expected_mean = expected_means.get_expectation() - self.assertTrue( - torch.allclose( - expected_mean.to(torch_device), - out.logits.float().mean(-1), - atol=1e-2, - rtol=1e-2 - ) - ) - - # slicing logits[0, 0, 0:15] - expected_slices = Expectations( - { - ("xpu", 3): torch.tensor([-12.8281, -7.4609, -0.4668, -8.0703, -7.2539, -8.0078, -6.4961, -7.7734, -7.8516, -7.0352, -6.2188, -7.1367, -1.8564, 1.9922, -8.6328]), - ("cuda", 7): torch.tensor([-12.8125, -7.3359, -0.4846, -8.0234, -7.2383, -7.9922, -6.4805, -7.7344, -7.8125, -7.0078, -6.1797, -7.1094, -1.8633, 1.9736, -8.6016]), - ("cuda", 8): torch.tensor([-12.8281, -7.4609, -0.4668, -8.0703, -7.2539, -8.0078, -6.4961, -7.7734, -7.8516, -7.0352, -6.2188, -7.1367, -1.8564, 1.9922, -8.6328]) - }) - # fmt: on - - expected_slice = expected_slices.get_expectation() - self.assertTrue( - torch.allclose( - expected_slice.to(torch_device), - out.logits[0, 0, :15].float(), - atol=1e-2, - rtol=1e-2, - ) - ) - - @require_torch_accelerator - @pytest.mark.torch_compile_test - def test_compile_static_cache(self): - NUM_TOKENS_TO_GENERATE = 40 - # Note on `EXPECTED_TEXT_COMPLETION`'s diff: the current value matches the original test if the original test - # was changed to have a cache of 53 tokens (as opposed to 4096), on Ampere GPUs. - EXPECTED_TEXT_COMPLETION = [ - "Simply put, the theory of relativity states that 1) the speed of light is constant in all inertial " - "reference frames, and 2) the laws of physics are the same for all inertial reference frames.\nThe " - "theory of relativ", - "My favorite all time favorite condiment is ketchup. I love it on everything. I love it on my eggs, " - "my fries, my chicken, my burgers, my hot dogs, my sandwiches, my salads, my p", - ] - - prompts = [ - "Simply put, the theory of relativity states that ", - "My favorite all time favorite condiment is ketchup.", - ] - tokenizer = NanbeigeTokenizer.from_pretrained( - "meta-llama/Nanbeige-2-7b-hf", pad_token="", padding_side="right" - ) - model = NanbeigeForCausalLM.from_pretrained( - "meta-llama/Nanbeige-2-7b-hf", device_map=torch_device, dtype=torch.float16 - ) - inputs = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device) - - # Dynamic Cache - generated_ids = model.generate(**inputs, max_new_tokens=NUM_TOKENS_TO_GENERATE, do_sample=False) - dynamic_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True) - self.assertEqual(EXPECTED_TEXT_COMPLETION, dynamic_text) - - # Static Cache + compile (`generate()` internally compiles each decoding step when static cache is used) - generated_ids = model.generate( - **inputs, max_new_tokens=NUM_TOKENS_TO_GENERATE, do_sample=False, cache_implementation="static" - ) - static_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True) - self.assertEqual(EXPECTED_TEXT_COMPLETION, static_text) - - @pytest.mark.torch_export_test - def test_export_static_cache(self): - from transformers.integrations.executorch import ( - TorchExportableModuleWithStaticCache, - ) - - llama_models = { - "meta-llama/Nanbeige-3.2-1B": [ - "Simply put, the theory of relativity states that 1) the speed of light is the same for all " - "observers, regardless of their location, and 2) the laws of physics are the same for all observers" - ], - } - - for llama_model_ckp, EXPECTED_TEXT_COMPLETION in llama_models.items(): - # Load tokenizer - tokenizer = AutoTokenizer.from_pretrained(llama_model_ckp, pad_token="", padding_side="right") - max_generation_length = tokenizer(EXPECTED_TEXT_COMPLETION, return_tensors="pt", padding=True)[ - "input_ids" - ].shape[-1] - - # Load model - device = "cpu" # TODO (joao / export experts): should be on `torch_device`, but causes GPU OOM - dtype = torch.bfloat16 - cache_implementation = "static" - attn_implementation = "sdpa" - batch_size = 1 - model = NanbeigeForCausalLM.from_pretrained( - llama_model_ckp, - device_map=device, - dtype=dtype, - attn_implementation=attn_implementation, - generation_config=GenerationConfig( - use_cache=True, - cache_implementation=cache_implementation, - max_length=max_generation_length, - cache_config={ - "batch_size": batch_size, - "max_cache_len": max_generation_length, - "device": device, - }, - ), - ) - - prompts = ["Simply put, the theory of relativity states that "] - prompt_tokens = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device) - prompt_token_ids = prompt_tokens["input_ids"] - max_new_tokens = max_generation_length - prompt_token_ids.shape[-1] - - # Static Cache + export - from transformers.integrations.executorch import TorchExportableModuleForDecoderOnlyLM - - exportable_module = TorchExportableModuleForDecoderOnlyLM(model) - exported_program = exportable_module.export( - input_ids=torch.tensor([[1]], dtype=torch.long, device=model.device), - cache_position=torch.tensor([0], dtype=torch.long, device=model.device), - ) - ep_generated_ids = TorchExportableModuleWithStaticCache.generate( - exported_program=exported_program, prompt_token_ids=prompt_token_ids, max_new_tokens=max_new_tokens - ) - ep_generated_text = tokenizer.batch_decode(ep_generated_ids, skip_special_tokens=True) - self.assertEqual(EXPECTED_TEXT_COMPLETION, ep_generated_text) - - @pytest.mark.flash_attn_test - @require_flash_attn - def test_flash_with_static_cache(self): - """Test that FA works correctly with a StaticCache""" - model_name = "meta-llama/Nanbeige-3.2-3B-Instruct" - - model = AutoModelForCausalLM.from_pretrained(model_name, device_map=torch_device, dtype=torch.bfloat16) - tokenizer = AutoTokenizer.from_pretrained(model_name) - - input_text = {"role": "user", "content": "What's the meaning of life?"} - # The template writes today's date into the system prompt unless `date_string` is set; pin the - # date the expectation was recorded with so the prompt is the same every day. - inputs = tokenizer.apply_chat_template( - [input_text], tokenize=True, return_tensors="pt", add_generation_prompt=True, date_string="26 Jun 2026" - ).to(model.device) - - out_sdpa = model.generate( - **inputs, max_new_tokens=100, cache_implementation="static", disable_compile=True, do_sample=False - ) - output_text_sdpa = tokenizer.batch_decode(out_sdpa[0, inputs.input_ids.shape[1] :])[0] - - # Now toggle FA and test again - model.set_attn_implementation("flash_attention_2") - - out_fa = model.generate( - **inputs, - max_new_tokens=100, - cache_implementation="static", - disable_compile=True, - do_sample=False, - return_dict_in_generate=True, - ) - output_text_fa = tokenizer.batch_decode(out_fa.sequences[0, inputs.input_ids.shape[1] :])[0] - - # Just to make sure - self.assertTrue(all(isinstance(layer, StaticLayer) for layer in out_fa.past_key_values.layers)) - - expected_text = Expectations( - { - ( - "cuda", - 8, - ): "The question of the meaning of life is one of the most profound and debated topics in human history. It has been explored by philosophers, theologians, scientists, and many others across various cultures and disciplines. While there is no one definitive answer, here are some perspectives to consider:\n\n1. **Religious and spiritual perspectives**: Many religions and spiritual traditions offer their own answers to the meaning of life. For example, in Christianity, the meaning of life is often seen as serving God and preparing for eternal" # fmt: skip - } - ) - EXPECTED_TEXT = expected_text.get_expectation() - - # Both output text should be the same, and equal to the reference - self.assertEqual(output_text_sdpa, output_text_fa) - self.assertEqual(output_text_fa, EXPECTED_TEXT) - - -@slow -@require_torch_accelerator -class Mask4DTestHard(MemoryCleanupMixin, unittest.TestCase): - def setUp(self): - super().setUp() - model_name = "TinyNanbeige/TinyNanbeige-1.1B-Chat-v1.0" - self.model_dtype = torch.float32 - self.tokenizer = NanbeigeTokenizer.from_pretrained(model_name) - self.model = NanbeigeForCausalLM.from_pretrained(model_name, dtype=self.model_dtype).to(torch_device) - - def get_test_data(self): - template = "my favorite {}" - items = ("pet is a", "artist plays a", "name is L") # same number of tokens in each item - - batch_separate = [template.format(x) for x in items] # 3 separate lines - batch_shared_prefix = template.format(" ".join(items)) # 1 line with options concatenated - - input_ids = self.tokenizer(batch_separate, return_tensors="pt").input_ids.to(torch_device) - input_ids_shared_prefix = self.tokenizer(batch_shared_prefix, return_tensors="pt").input_ids.to(torch_device) - - mask_shared_prefix = torch.tensor( - [ - [ - [ - [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], - [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], - [1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0], - [1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0], - [1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0], - [1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0], - [1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0], - [1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1], - ] - ] - ], - device=torch_device, - ) - - position_ids = torch.arange(input_ids.shape[1]).tile(input_ids.shape[0], 1).to(torch_device) - - # building custom positions ids based on custom mask - position_ids_shared_prefix = (mask_shared_prefix.sum(dim=-1) - 1).reshape(1, -1) - # effectively: position_ids_shared_prefix = torch.tensor([[0, 1, 2, 3, 4, 5, 3, 4, 5, 3, 4, 5]]).to(device) - - # inverting the mask - min_dtype = torch.finfo(self.model_dtype).min - mask_shared_prefix = (mask_shared_prefix.eq(0.0)).to(dtype=self.model_dtype) * min_dtype - - return input_ids, position_ids, input_ids_shared_prefix, mask_shared_prefix, position_ids_shared_prefix - - def test_stacked_causal_mask(self): - ( - input_ids, - position_ids, - input_ids_shared_prefix, - mask_shared_prefix, - position_ids_shared_prefix, - ) = self.get_test_data() - - # regular batch - logits = self.model.forward(input_ids, position_ids=position_ids).logits - logits_last = logits[:, -1, :] # last tokens in each batch line - decoded = [self.tokenizer.decode(t) for t in logits_last.argmax(dim=-1)] - - # single forward run with 4D custom mask - logits_shared_prefix = self.model.forward( - input_ids_shared_prefix, attention_mask=mask_shared_prefix, position_ids=position_ids_shared_prefix - ).logits - logits_shared_prefix_last = logits_shared_prefix[ - 0, torch.where(position_ids_shared_prefix == position_ids_shared_prefix.max())[1], : - ] # last three tokens - decoded_shared_prefix = [self.tokenizer.decode(t) for t in logits_shared_prefix_last.argmax(dim=-1)] - - self.assertEqual(decoded, decoded_shared_prefix) - - def test_partial_stacked_causal_mask(self): - # Same as the test above, but the input is passed in two groups. It tests that we can pass partial 4D attention masks - - ( - input_ids, - position_ids, - input_ids_shared_prefix, - mask_shared_prefix, - position_ids_shared_prefix, - ) = self.get_test_data() - - # regular batch - logits = self.model.forward(input_ids, position_ids=position_ids).logits - logits_last = logits[:, -1, :] # last tokens in each batch line - decoded = [self.tokenizer.decode(t) for t in logits_last.argmax(dim=-1)] - - # 2 forward runs with custom 4D masks - part_a = 3 # split point - - input_1a = input_ids_shared_prefix[:, :part_a] - position_ids_1a = position_ids_shared_prefix[:, :part_a] - mask_1a = mask_shared_prefix[:, :, :part_a, :part_a] - - outs_1a = self.model.forward(input_1a, attention_mask=mask_1a, position_ids=position_ids_1a) - past_key_values_a = outs_1a["past_key_values"] - - # Case 1: we pass a 4D attention mask regarding the current sequence length (i.e. [..., seq_len, full_len]) - input_1b = input_ids_shared_prefix[:, part_a:] - position_ids_1b = position_ids_shared_prefix[:, part_a:] - mask_1b = mask_shared_prefix[:, :, part_a:, :] - outs_1b = self.model.forward( - input_1b, - attention_mask=mask_1b, - position_ids=position_ids_1b, - past_key_values=past_key_values_a, - ) - decoded_1b = [ - self.tokenizer.decode(t) - for t in outs_1b.logits.argmax(-1)[ - 0, torch.where(position_ids_shared_prefix == position_ids_shared_prefix.max())[1] - part_a - ] - ] - self.assertEqual(decoded, decoded_1b) - - def test_stacked_causal_mask_static_cache(self): - """same as above but with StaticCache""" - ( - input_ids, - position_ids, - input_ids_shared_prefix, - mask_shared_prefix, - position_ids_shared_prefix, - ) = self.get_test_data() - - # regular batch - logits = self.model.forward(input_ids, position_ids=position_ids).logits - logits_last = logits[:, -1, :] # last tokens in each batch line - decoded = [self.tokenizer.decode(t) for t in logits_last.argmax(dim=-1)] - - # upgrade the model with StaticCache - max_cache_len = 16 # note that max_cache_len is greater than the attention_mask.shape[-1] - past_key_values = StaticCache(config=self.model.config, max_cache_len=max_cache_len) - - padded_attention_mask = torch.nn.functional.pad( - input=mask_shared_prefix, - pad=(0, max_cache_len - mask_shared_prefix.shape[-1]), - mode="constant", - value=torch.finfo(self.model_dtype).min, - ) - - # single forward run with 4D custom mask - logits_shared_prefix = self.model.forward( - input_ids_shared_prefix, - attention_mask=padded_attention_mask, - position_ids=position_ids_shared_prefix, - past_key_values=past_key_values, - ).logits - logits_shared_prefix_last = logits_shared_prefix[ - 0, torch.where(position_ids_shared_prefix == position_ids_shared_prefix.max())[1], : - ] # last three tokens - decoded_shared_prefix = [self.tokenizer.decode(t) for t in logits_shared_prefix_last.argmax(dim=-1)] - - self.assertEqual(decoded, decoded_shared_prefix) - - def test_partial_stacked_causal_mask_static_cache(self): - # Same as the test above, but the input is passed in two groups. It tests that we can pass partial 4D attention masks - # we pass a 4D attention mask shaped [..., seq_len, full_static_cache_len]) - ( - input_ids, - position_ids, - input_ids_shared_prefix, - mask_shared_prefix, - position_ids_shared_prefix, - ) = self.get_test_data() - - # regular batch - logits = self.model.forward(input_ids, position_ids=position_ids).logits - logits_last = logits[:, -1, :] # last tokens in each batch line - decoded = [self.tokenizer.decode(t) for t in logits_last.argmax(dim=-1)] - - # upgrade the model with StaticCache - max_cache_len = 16 # note that max_cache_len is greater than the attention_mask.shape[-1] - past_key_values = StaticCache(config=self.model.config, max_cache_len=max_cache_len) - - # forward run for the first part of input - part_a = 3 # split point - - input_1a = input_ids_shared_prefix[:, :part_a] - position_ids_1a = position_ids_shared_prefix[:, :part_a] - mask_1a = mask_shared_prefix[:, :, :part_a, :part_a] - - padded_mask_1a = torch.nn.functional.pad( - input=mask_1a, - pad=(0, max_cache_len - mask_1a.shape[-1]), - mode="constant", - value=torch.finfo(self.model_dtype).min, - ) - - _ = self.model.forward( - input_1a, - attention_mask=padded_mask_1a, - position_ids=position_ids_1a, - past_key_values=past_key_values, - ) - - # forward run for the second part of input - input_1b = input_ids_shared_prefix[:, part_a:] - position_ids_1b = position_ids_shared_prefix[:, part_a:] - mask_1b = mask_shared_prefix[:, :, part_a:, :] - - padded_mask_1b = torch.nn.functional.pad( - input=mask_1b, pad=(0, max_cache_len - mask_1b.shape[-1]), mode="constant", value=0 - ) - - outs_1b = self.model.forward( - input_1b, - attention_mask=padded_mask_1b, - position_ids=position_ids_1b, - past_key_values=past_key_values, - ) - decoded_1b = [ - self.tokenizer.decode(t) - for t in outs_1b.logits.argmax(-1)[ - 0, torch.where(position_ids_shared_prefix == position_ids_shared_prefix.max())[1] - part_a - ] - ] - self.assertEqual(decoded, decoded_1b) + expected_logits = model(input_ids, use_cache=False).logits + outputs = model(input_ids[:, :2], use_cache=True) + logits = [outputs.logits] + self.assertEqual(len(outputs.cache.layers), num_cache_layers) + for layer_idx in range(num_cache_layers): + self.assertEqual(outputs.cache.get_seq_length(layer_idx), 2) + + outputs = model(input_ids[:, 2:4], cache=outputs.cache, use_cache=True) + logits.append(outputs.logits) + for position in range(4, input_ids.shape[1]): + outputs = model(input_ids[:, position : position + 1], cache=outputs.cache, use_cache=True) + logits.append(outputs.logits) + + torch.testing.assert_close(torch.cat(logits, dim=1), expected_logits, rtol=1e-4, atol=1e-4) + for layer_idx in range(num_cache_layers): + self.assertEqual(outputs.cache.get_seq_length(layer_idx), input_ids.shape[1]) From 169798945f9533b859c0296ae1f73fdc5c4c833d Mon Sep 17 00:00:00 2001 From: sushmanth reddy Date: Wed, 25 Nov 2026 08:59:05 +0530 Subject: [PATCH 3/7] Use the native Nanbeige cache API and test the released checkpoint --- .../models/nanbeige/modeling_nanbeige.py | 5 --- .../models/nanbeige/modular_nanbeige.py | 10 +++--- .../models/nanbeige/test_modeling_nanbeige.py | 35 +++++++++++++++++-- 3 files changed, 38 insertions(+), 12 deletions(-) diff --git a/src/transformers/models/nanbeige/modeling_nanbeige.py b/src/transformers/models/nanbeige/modeling_nanbeige.py index 23b1e4bab821..3e936b56b589 100644 --- a/src/transformers/models/nanbeige/modeling_nanbeige.py +++ b/src/transformers/models/nanbeige/modeling_nanbeige.py @@ -36,7 +36,6 @@ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel, slice_logits_to_keep from ...processing_utils import Unpack from ...utils import TransformersKwargs, auto_docstring, can_return_tuple -from ...utils.deprecation import deprecate_kwarg from ...utils.generic import merge_with_config_defaults from ...utils.output_capturing import capture_outputs from .configuration_nanbeige import NanbeigeConfig @@ -222,7 +221,6 @@ def __init__(self, config: NanbeigeConfig, layer_idx: int): config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias ) - @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") def forward( self, hidden_states: torch.Tensor, @@ -272,7 +270,6 @@ def __init__(self, config: NanbeigeConfig, layer_idx: int): self.input_layernorm = NanbeigeRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = NanbeigeRMSNorm(config.hidden_size, eps=config.rms_norm_eps) - @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") def forward( self, hidden_states: torch.Tensor, @@ -341,7 +338,6 @@ def __init__(self, config: NanbeigeConfig): # Initialize weights and apply final processing self.post_init() - @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") @merge_with_config_defaults @can_return_tuple @auto_docstring @@ -440,7 +436,6 @@ def __init__(self, config: NanbeigeConfig): # Initialize weights and apply final processing self.post_init() - @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") @can_return_tuple @auto_docstring def forward( diff --git a/src/transformers/models/nanbeige/modular_nanbeige.py b/src/transformers/models/nanbeige/modular_nanbeige.py index 28a555922b31..9ea334ebb23f 100644 --- a/src/transformers/models/nanbeige/modular_nanbeige.py +++ b/src/transformers/models/nanbeige/modular_nanbeige.py @@ -25,8 +25,7 @@ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, slice_logits_to_keep from ...processing_utils import Unpack from ...utils import TransformersKwargs, auto_docstring, can_return_tuple -from ...utils.deprecation import deprecate_kwarg -from ...utils.generic import merge_with_config_defaults +from ...utils.generic import merge_with_config_defaults, no_inherit_decorator from ...utils.output_capturing import capture_outputs from ...utils.type_validators import positive_int_field from ..llama.configuration_llama import LlamaConfig @@ -88,6 +87,7 @@ class NanbeigeMLP(LlamaMLP): class NanbeigeAttention(LlamaAttention): + @no_inherit_decorator def forward( self, hidden_states: torch.Tensor, @@ -127,7 +127,9 @@ def forward( class NanbeigeDecoderLayer(LlamaDecoderLayer): - pass + @no_inherit_decorator + def forward(self, **super_kwargs): + return super().forward(**super_kwargs) class NanbeigePreTrainedModel(LlamaPreTrainedModel): @@ -135,7 +137,6 @@ class NanbeigePreTrainedModel(LlamaPreTrainedModel): class NanbeigeModel(LlamaModel): - @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") @merge_with_config_defaults @can_return_tuple @auto_docstring @@ -219,7 +220,6 @@ def _run_loop( class NanbeigeForCausalLM(LlamaForCausalLM): - @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") @can_return_tuple @auto_docstring def forward( diff --git a/tests/models/nanbeige/test_modeling_nanbeige.py b/tests/models/nanbeige/test_modeling_nanbeige.py index 0c229f93cbc9..4040eece6a39 100644 --- a/tests/models/nanbeige/test_modeling_nanbeige.py +++ b/tests/models/nanbeige/test_modeling_nanbeige.py @@ -15,8 +15,8 @@ import unittest -from transformers import is_torch_available -from transformers.testing_utils import require_torch, torch_device +from transformers import AutoModelForCausalLM, AutoTokenizer, is_torch_available +from transformers.testing_utils import require_torch, require_torch_accelerator, slow, torch_device from ...causal_lm_tester import CausalLMModelTest, CausalLMModelTester @@ -39,6 +39,10 @@ class NanbeigeModelTester(CausalLMModelTester): class NanbeigeModelTest(CausalLMModelTest, unittest.TestCase): model_tester_class = NanbeigeModelTester + @unittest.skip("New model: `cache` only, no `past_key_values` BC") + def test_bc_cache_name_forward(self): + pass + def test_two_loop_chunked_prefill_and_decode_match_full_forward(self): tester = self.model_tester_class(self, batch_size=2, num_loops=2) config, inputs_dict = tester.prepare_config_and_inputs_for_common() @@ -64,3 +68,30 @@ def test_two_loop_chunked_prefill_and_decode_match_full_forward(self): torch.testing.assert_close(torch.cat(logits, dim=1), expected_logits, rtol=1e-4, atol=1e-4) for layer_idx in range(num_cache_layers): self.assertEqual(outputs.cache.get_seq_length(layer_idx), input_ids.shape[1]) + + +@slow +@require_torch_accelerator +class NanbeigeIntegrationTest(unittest.TestCase): + checkpoint = "Nanbeige/Nanbeige4.2-3B" + revision = "b82e54bd609793562a75cbf9337970a93369eab5" + + def test_bf16_generation(self): + tokenizer = AutoTokenizer.from_pretrained(self.checkpoint, revision=self.revision) + model = AutoModelForCausalLM.from_pretrained( + self.checkpoint, + revision=self.revision, + dtype=torch.bfloat16, + device_map=torch_device, + ) + self.assertIsInstance(model, NanbeigeForCausalLM) + inputs = tokenizer.apply_chat_template( + [{"role": "user", "content": "What is the capital of France? Answer with the city name."}], + add_generation_prompt=True, + enable_thinking=False, + return_dict=True, + return_tensors="pt", + ).to(model.device) + outputs = model.generate(**inputs, max_new_tokens=2, do_sample=False) + new_tokens = outputs[0, inputs["input_ids"].shape[1] :] + self.assertEqual(tokenizer.decode(new_tokens, skip_special_tokens=True), "Paris") From 622a4a019398bcb815a78e1c5e9e275671909fd4 Mon Sep 17 00:00:00 2001 From: sushmanth reddy Date: Wed, 25 Nov 2026 09:02:13 +0530 Subject: [PATCH 4/7] Use the default checkpoint revision in the Nanbeige slow test --- tests/models/nanbeige/test_modeling_nanbeige.py | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/tests/models/nanbeige/test_modeling_nanbeige.py b/tests/models/nanbeige/test_modeling_nanbeige.py index 4040eece6a39..1c04111b5ace 100644 --- a/tests/models/nanbeige/test_modeling_nanbeige.py +++ b/tests/models/nanbeige/test_modeling_nanbeige.py @@ -74,16 +74,10 @@ def test_two_loop_chunked_prefill_and_decode_match_full_forward(self): @require_torch_accelerator class NanbeigeIntegrationTest(unittest.TestCase): checkpoint = "Nanbeige/Nanbeige4.2-3B" - revision = "b82e54bd609793562a75cbf9337970a93369eab5" def test_bf16_generation(self): - tokenizer = AutoTokenizer.from_pretrained(self.checkpoint, revision=self.revision) - model = AutoModelForCausalLM.from_pretrained( - self.checkpoint, - revision=self.revision, - dtype=torch.bfloat16, - device_map=torch_device, - ) + tokenizer = AutoTokenizer.from_pretrained(self.checkpoint) + model = AutoModelForCausalLM.from_pretrained(self.checkpoint, dtype=torch.bfloat16, device_map=torch_device) self.assertIsInstance(model, NanbeigeForCausalLM) inputs = tokenizer.apply_chat_template( [{"role": "user", "content": "What is the capital of France? Answer with the city name."}], From b7646bdca044b65dd5ba3e72d67add0b41c86576 Mon Sep 17 00:00:00 2001 From: sushmanth reddy Date: Wed, 25 Nov 2026 09:28:43 +0530 Subject: [PATCH 5/7] Reuse the shared causal LM forward in Nanbeige --- .../models/nanbeige/modeling_nanbeige.py | 174 +++++++++--------- .../models/nanbeige/modular_nanbeige.py | 38 +--- 2 files changed, 94 insertions(+), 118 deletions(-) diff --git a/src/transformers/models/nanbeige/modeling_nanbeige.py b/src/transformers/models/nanbeige/modeling_nanbeige.py index 3e936b56b589..ed622bdd304b 100644 --- a/src/transformers/models/nanbeige/modeling_nanbeige.py +++ b/src/transformers/models/nanbeige/modeling_nanbeige.py @@ -41,89 +41,6 @@ from .configuration_nanbeige import NanbeigeConfig -@use_kernel_forward_from_hub("RMSNorm") -class NanbeigeRMSNorm(nn.Module): - def __init__(self, hidden_size, eps: float = 1e-6) -> None: - """ - NanbeigeRMSNorm is equivalent to T5LayerNorm - """ - super().__init__() - self.weight = nn.Parameter(torch.ones(hidden_size)) - self.variance_epsilon = eps - - def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: - 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) - - def extra_repr(self): - return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" - - -class NanbeigeRotaryEmbedding(nn.Module): - def __init__(self, config: NanbeigeConfig): - super().__init__() - self.max_seq_len_cached = config.max_position_embeddings - self.original_max_seq_len = config.max_position_embeddings - - self.config = config - - self.rope_type = self.config.rope_parameters["rope_type"] - rope_init_fn: Callable = self.compute_default_rope_parameters - if self.rope_type != "default": - rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] - inv_freq, self.attention_scaling = rope_init_fn(self.config) - - self.inv_freq = nn.Buffer(inv_freq, persistent=False) - self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) - - @staticmethod - def compute_default_rope_parameters(config: NanbeigeConfig, **kwargs) -> tuple[torch.Tensor, float]: - """ - Computes the inverse frequencies according to the original RoPE implementation - Args: - config ([`~transformers.PreTrainedConfig`]): - The model configuration. - Returns: - Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the - post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). - """ - base = config.rope_parameters["rope_theta"] - dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads - - attention_factor = 1.0 # Unused in this type of RoPE - # Compute the inverse frequencies - inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) - return inv_freq, attention_factor - - @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) - def forward(self, x, position_ids): - freqs = position_ids[..., None].float() * self.inv_freq.to(device=x.device, dtype=torch.float) - emb = torch.cat((freqs, freqs), dim=-1) - cos = emb.cos() * self.attention_scaling - sin = emb.sin() * self.attention_scaling - - return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) - - -class NanbeigeMLP(nn.Module): - def __init__(self, config): - super().__init__() - self.config = config - self.hidden_size = config.hidden_size - self.intermediate_size = config.intermediate_size - self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) - self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) - self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias) - self.act_fn = ACT2FN[config.hidden_act] - - def forward(self, x): - down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) - return down_proj - - def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] @@ -259,6 +176,43 @@ def forward( return self.o_proj(attn_output), attn_weights +@use_kernel_forward_from_hub("RMSNorm") +class NanbeigeRMSNorm(nn.Module): + def __init__(self, hidden_size, eps: float = 1e-6) -> None: + """ + NanbeigeRMSNorm is equivalent to T5LayerNorm + """ + super().__init__() + self.weight = nn.Parameter(torch.ones(hidden_size)) + self.variance_epsilon = eps + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + 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) + + def extra_repr(self): + return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" + + +class NanbeigeMLP(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.hidden_size = config.hidden_size + self.intermediate_size = config.intermediate_size + self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) + self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) + self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias) + self.act_fn = ACT2FN[config.hidden_act] + + def forward(self, x): + down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) + return down_proj + + class NanbeigeDecoderLayer(GradientCheckpointingLayer): def __init__(self, config: NanbeigeConfig, layer_idx: int): super().__init__() @@ -320,6 +274,52 @@ class NanbeigePreTrainedModel(PreTrainedModel): } +class NanbeigeRotaryEmbedding(nn.Module): + def __init__(self, config: NanbeigeConfig): + super().__init__() + self.max_seq_len_cached = config.max_position_embeddings + self.original_max_seq_len = config.max_position_embeddings + + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_default_rope_parameters + if self.rope_type != "default": + rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] + inv_freq, self.attention_scaling = rope_init_fn(self.config) + + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + + @staticmethod + def compute_default_rope_parameters(config: NanbeigeConfig, **kwargs) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + + attention_factor = 1.0 # Unused in this type of RoPE + # Compute the inverse frequencies + inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + return inv_freq, attention_factor + + @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) + def forward(self, x, position_ids): + freqs = position_ids[..., None].float() * self.inv_freq.to(device=x.device, dtype=torch.float) + emb = torch.cat((freqs, freqs), dim=-1) + cos = emb.cos() * self.attention_scaling + sin = emb.sin() * self.attention_scaling + + return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) + + @auto_docstring class NanbeigeModel(NanbeigePreTrainedModel): def __init__(self, config: NanbeigeConfig): @@ -450,7 +450,7 @@ def forward( logits_to_keep: int | torch.Tensor = 0, **kwargs: Unpack[TransformersKwargs], ) -> CausalLMOutputWithPast: - r"""Predict the next token from the hidden states of the final decoder pass.""" + r"""Return the final decoder pass's next-token logits in float32.""" outputs: BaseModelOutputWithPast = self.model( input_ids=input_ids, attention_mask=attention_mask, @@ -460,8 +460,10 @@ def forward( use_cache=use_cache, **kwargs, ) - hidden_states = slice_logits_to_keep(outputs.last_hidden_state, logits_to_keep) - logits = self.lm_head(hidden_states).float() + + hidden_states = outputs.last_hidden_state + hidden_states = slice_logits_to_keep(hidden_states, logits_to_keep) + logits = self.lm_head(hidden_states).float() # noqa: F821, F841 loss = None if labels is not None: diff --git a/src/transformers/models/nanbeige/modular_nanbeige.py b/src/transformers/models/nanbeige/modular_nanbeige.py index 9ea334ebb23f..bc0a53f70a89 100644 --- a/src/transformers/models/nanbeige/modular_nanbeige.py +++ b/src/transformers/models/nanbeige/modular_nanbeige.py @@ -22,7 +22,7 @@ from ...cache_utils import Cache, DynamicCache from ...masking_utils import create_causal_mask from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast -from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, slice_logits_to_keep +from ...modeling_utils import ALL_ATTENTION_FUNCTIONS from ...processing_utils import Unpack from ...utils import TransformersKwargs, auto_docstring, can_return_tuple from ...utils.generic import merge_with_config_defaults, no_inherit_decorator @@ -33,11 +33,8 @@ LlamaAttention, LlamaDecoderLayer, LlamaForCausalLM, - LlamaMLP, LlamaModel, LlamaPreTrainedModel, - LlamaRMSNorm, - LlamaRotaryEmbedding, apply_rotary_pos_emb, eager_attention_forward, ) @@ -74,18 +71,6 @@ class NanbeigeConfig(LlamaConfig): skip_loop_final_norm: bool = False -class NanbeigeRMSNorm(LlamaRMSNorm): - pass - - -class NanbeigeRotaryEmbedding(LlamaRotaryEmbedding): - pass - - -class NanbeigeMLP(LlamaMLP): - pass - - class NanbeigeAttention(LlamaAttention): @no_inherit_decorator def forward( @@ -234,30 +219,19 @@ def forward( logits_to_keep: int | torch.Tensor = 0, **kwargs: Unpack[TransformersKwargs], ) -> CausalLMOutputWithPast: - r"""Predict the next token from the hidden states of the final decoder pass.""" - outputs: BaseModelOutputWithPast = self.model( + r"""Return the final decoder pass's next-token logits in float32.""" + super().forward( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, cache=cache, inputs_embeds=inputs_embeds, + labels=labels, use_cache=use_cache, + logits_to_keep=logits_to_keep, **kwargs, ) - hidden_states = slice_logits_to_keep(outputs.last_hidden_state, logits_to_keep) - logits = self.lm_head(hidden_states).float() - - loss = None - if labels is not None: - loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) - - return CausalLMOutputWithPast( - loss=loss, - logits=logits, - cache=outputs.cache, - hidden_states=outputs.hidden_states, - attentions=outputs.attentions, - ) + logits = self.lm_head(hidden_states).float() # noqa: F821, F841 __all__ = [ From d5186bca659282c931dbca3a6851149cdc081d6d Mon Sep 17 00:00:00 2001 From: sushmanth reddy Date: Wed, 25 Nov 2026 09:38:10 +0530 Subject: [PATCH 6/7] Credit the Nanbeige contributor and verify the usage example --- docs/source/en/model_doc/nanbeige.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/source/en/model_doc/nanbeige.md b/docs/source/en/model_doc/nanbeige.md index d1d860e2860f..ddfac2a8540a 100644 --- a/docs/source/en/model_doc/nanbeige.md +++ b/docs/source/en/model_doc/nanbeige.md @@ -21,8 +21,9 @@ limitations under the License. # Nanbeige -[Nanbeige4.2-3B](https://huggingface.co/Nanbeige/Nanbeige4.2-3B) is a causal language model for reasoning, chat, and tool -use. Its looped Transformer architecture runs the same decoder layers repeatedly, sharing their parameters across loops. +[Nanbeige4.2-3B](https://huggingface.co/Nanbeige/Nanbeige4.2-3B) is a causal language model from Nanbeige Lab for +reasoning, chat, and tool use. Its looped Transformer architecture runs the same decoder layers repeatedly, sharing +their parameters across loops. The released checkpoint has 22 decoder layers and runs them twice with `num_loops=2`. It uses grouped-query attention with 48 query heads and 8 key/value heads, a hidden size of 3072, and a maximum context length of 262,144 tokens. Each loop @@ -31,6 +32,8 @@ RMS normalization is applied after each loop. See the [technical report](https://huggingface.co/papers/2607.22083) for training and evaluation details. +This model was contributed by [Sushmanth Reddy](https://github.com/sushmanthreddy). + ## Usage Load the tokenizer and model with the auto classes. This example disables thinking in the chat template to request a short response. @@ -43,19 +46,19 @@ tokenizer = AutoTokenizer.from_pretrained(checkpoint) model = AutoModelForCausalLM.from_pretrained(checkpoint, device_map="auto", dtype="auto") inputs = tokenizer.apply_chat_template( - [{"role": "user", "content": "Which number is larger, 9.11 or 9.8?"}], + [{"role": "user", "content": "What is the capital of France? Answer with the city name."}], add_generation_prompt=True, enable_thinking=False, return_dict=True, return_tensors="pt", ).to(model.device) -outputs = model.generate(**inputs, max_new_tokens=256, do_sample=False) +outputs = model.generate(**inputs, max_new_tokens=32, do_sample=False) print(tokenizer.decode(outputs[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True)) ``` -The tokenizer enables thinking by default. Set `enable_thinking=True` to generate a reasoning trace. For multi-turn -conversations, `preserve_thinking` controls whether reasoning from earlier assistant turns remains in the prompt. +The chat template enables thinking by default. In multi-turn conversations, set `preserve_thinking=True` to keep +reasoning from earlier assistant turns in the prompt. ## NanbeigeConfig From aa124f904448d60f6d5788db39abc1e14abe8c43 Mon Sep 17 00:00:00 2001 From: sushmanth reddy Date: Wed, 25 Nov 2026 09:50:13 +0530 Subject: [PATCH 7/7] Remove the Nanbeige logits lint suppression --- .../models/nanbeige/modeling_nanbeige.py | 6 ++---- .../models/nanbeige/modular_nanbeige.py | 21 ++++++++++++++----- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/src/transformers/models/nanbeige/modeling_nanbeige.py b/src/transformers/models/nanbeige/modeling_nanbeige.py index ed622bdd304b..6ec3e107eea7 100644 --- a/src/transformers/models/nanbeige/modeling_nanbeige.py +++ b/src/transformers/models/nanbeige/modeling_nanbeige.py @@ -460,10 +460,8 @@ def forward( use_cache=use_cache, **kwargs, ) - - hidden_states = outputs.last_hidden_state - hidden_states = slice_logits_to_keep(hidden_states, logits_to_keep) - logits = self.lm_head(hidden_states).float() # noqa: F821, F841 + hidden_states = slice_logits_to_keep(outputs.last_hidden_state, logits_to_keep) + logits = self.lm_head(hidden_states).float() loss = None if labels is not None: diff --git a/src/transformers/models/nanbeige/modular_nanbeige.py b/src/transformers/models/nanbeige/modular_nanbeige.py index bc0a53f70a89..6357f0400379 100644 --- a/src/transformers/models/nanbeige/modular_nanbeige.py +++ b/src/transformers/models/nanbeige/modular_nanbeige.py @@ -22,7 +22,7 @@ from ...cache_utils import Cache, DynamicCache from ...masking_utils import create_causal_mask from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast -from ...modeling_utils import ALL_ATTENTION_FUNCTIONS +from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, slice_logits_to_keep from ...processing_utils import Unpack from ...utils import TransformersKwargs, auto_docstring, can_return_tuple from ...utils.generic import merge_with_config_defaults, no_inherit_decorator @@ -220,18 +220,29 @@ def forward( **kwargs: Unpack[TransformersKwargs], ) -> CausalLMOutputWithPast: r"""Return the final decoder pass's next-token logits in float32.""" - super().forward( + outputs: BaseModelOutputWithPast = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, cache=cache, inputs_embeds=inputs_embeds, - labels=labels, use_cache=use_cache, - logits_to_keep=logits_to_keep, **kwargs, ) - logits = self.lm_head(hidden_states).float() # noqa: F821, F841 + hidden_states = slice_logits_to_keep(outputs.last_hidden_state, logits_to_keep) + logits = self.lm_head(hidden_states).float() + + loss = None + if labels is not None: + loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + cache=outputs.cache, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) __all__ = [