Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/source/en/_toctree.yml
Original file line number Diff line number Diff line change
Expand Up @@ -861,6 +861,8 @@
title: MVP
- local: model_doc/myt5
title: myt5
- local: model_doc/nanbeige
title: Nanbeige

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
title: Nanbeige
title: Nanbeige4.2

- local: model_doc/nanochat
title: NanoChat
- local: model_doc/nemotron
Expand Down
75 changes: 75 additions & 0 deletions docs/source/en/model_doc/nanbeige.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<!--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.


⚠️ 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

[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
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.

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.

```python
from transformers import AutoModelForCausalLM, AutoTokenizer

checkpoint = "Nanbeige/Nanbeige4.2-3B"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModelForCausalLM.from_pretrained(checkpoint, device_map="auto", dtype="auto")

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=32, do_sample=False)
print(tokenizer.decode(outputs[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True))
```

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.
Comment on lines +1 to +61

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
<!--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.
⚠️ 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
[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
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.
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.
```python
from transformers import AutoModelForCausalLM, AutoTokenizer
checkpoint = "Nanbeige/Nanbeige4.2-3B"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModelForCausalLM.from_pretrained(checkpoint, device_map="auto", dtype="auto")
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=32, do_sample=False)
print(tokenizer.decode(outputs[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True))
```
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.
<!--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.
⚠️ Note that this file is in Markdown but contains 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-24.*
# Nanbeige4.2
[Nanbeige4.2-3B](https://huggingface.co/Nanbeige/Nanbeige4.2-3B) is a looped language model from [Nanbeige](https://huggingface.co/Nanbeige), described in its [technical report](https://huggingface.co/papers/2607.22083). It is a [Llama](./llama) decoder whose 22 layers run twice per forward pass, with shared weights. The final norm runs after each loop, and each loop has its own key-value cache, so the cache holds `num_loops * num_hidden_layers` layers.
```python
from transformers import AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("Nanbeige/Nanbeige4.2-3B")
model = AutoModelForCausalLM.from_pretrained("Nanbeige/Nanbeige4.2-3B", device_map="auto")
messages = [{"role": "user", "content": "Which number is bigger, 9.11 or 9.8?"}]
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True)
output = model.generate(**inputs.to(model.device), max_new_tokens=512)
print(tokenizer.decode(output[0][inputs["input_ids"].shape[1] :], skip_special_tokens=True))
```
## Notes
- `output_hidden_states` and `output_attentions` return one entry per decoder layer call: `1 + num_loops * num_hidden_layers` hidden states and `num_loops * num_hidden_layers` attentions. The remote code on the Hub returns the last loop only.
- Continuous batching (`generate_batch`) is not supported.


## NanbeigeConfig

[[autodoc]] NanbeigeConfig

## NanbeigeModel

[[autodoc]] NanbeigeModel
- forward

## NanbeigeForCausalLM

[[autodoc]] NanbeigeForCausalLM
- forward
1 change: 1 addition & 0 deletions src/transformers/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,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 *
Expand Down
1 change: 1 addition & 0 deletions src/transformers/models/auto/auto_mappings.py
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,7 @@
("musicgen_melody", "MusicgenMelodyConfig"),
("musicgen_melody_decoder", "MusicgenMelodyDecoderConfig"),
("mvp", "MvpConfig"),
("nanbeige", "NanbeigeConfig"),
("nanochat", "NanoChatConfig"),
("nemo_speechlm", "Nemotron3_5TranscribeConfig"),
("nemotron", "NemotronConfig"),
Expand Down
2 changes: 2 additions & 0 deletions src/transformers/models/auto/modeling_auto.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin):
("musicgen", "MusicgenModel"),
("musicgen_melody", "MusicgenMelodyModel"),
("mvp", "MvpModel"),
("nanbeige", "NanbeigeModel"),
("nanochat", "NanoChatModel"),
("nemo_speechlm", "Nemotron3_5TranscribeModel"),
("nemotron", "NemotronModel"),
Expand Down Expand Up @@ -917,6 +918,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin):
("musicgen", "MusicgenForCausalLM"),
("musicgen_melody", "MusicgenMelodyForCausalLM"),
("mvp", "MvpForCausalLM"),
("nanbeige", "NanbeigeForCausalLM"),
("nanochat", "NanoChatForCausalLM"),
("nemotron", "NemotronForCausalLM"),
("nemotron_h", "NemotronHForCausalLM"),
Expand Down
33 changes: 33 additions & 0 deletions src/transformers/models/nanbeige/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# 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");
# 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__)
102 changes: 102 additions & 0 deletions src/transformers/models/nanbeige/configuration_nanbeige.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# 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, positive_int_field

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
from ...utils.type_validators import interval, positive_int_field
from ...utils.type_validators import interval



@auto_docstring(checkpoint="Nanbeige/Nanbeige4.2-3B")
@strict
class NanbeigeConfig(PreTrainedConfig):
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`.
"""
Comment on lines +34 to +39

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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`.
"""
Number of times the decoder layers run per forward pass, with shared weights. The final norm runs after
every loop, and every loop has its own key-value cache.
```python
>>> from transformers import NanbeigeModel, NanbeigeConfig
>>> # Initializing a Nanbeige4.2-3B style configuration
>>> configuration = NanbeigeConfig()
>>> # Initializing a model from the Nanbeige4.2-3B style configuration
>>> model = NanbeigeModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""


model_type = "nanbeige"
# 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 = 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 = 262144
initializer_range: float = interval(min=0.0, max=1.0)(default=0.02)
rms_norm_eps: float = 1e-5
use_cache: bool = True
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 = 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
Comment on lines +79 to +83

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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
default_theta = 70_000_000.0
num_loops: int = 2


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})."
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
)
)
if self.num_loops < 1:
raise ValueError(f"`num_loops` ({self.num_loops}) must be at least 1.")
@property
def total_num_hidden_layers(self) -> int:
"""Number of decoder layer calls per forward pass."""
return self.num_loops * self.num_hidden_layers



__all__ = ["NanbeigeConfig"]
Loading