Skip to content

Add Nanbeige4.2-3B - #50608

Open
sushmanthreddy wants to merge 8 commits into
huggingface:mainfrom
sushmanthreddy:nainbeige
Open

sushmanthreddy wants to merge 8 commits into
huggingface:mainfrom
sushmanthreddy:nainbeige

Conversation

@sushmanthreddy

@sushmanthreddy sushmanthreddy commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #47667

This PR adds native Transformers support for Nanbeige/Nanbeige4.2-3B. The modular implementation reuses Llama’s decoder components and runs the same 22 layers twice, with separate KV cache entries for each pass. The published checkpoint loads directly through AutoModelForCausalLM without weight conversion.

Validation

  • The local CPU suite passed 164 tests with slow tests enabled, including the two-pass cache test.
  • The published BF16 checkpoint passed the slow generation test on MPS using the default auto loader.
  • make style passed.
🤖 mlinter review state

@github-actions

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: auto, nanbeige

@github-actions github-actions Bot left a comment

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.

Model linter — first pass

transformers-mlinter found 1 item(s) in the model files this PR touches. These are structural conventions a maintainer would otherwise flag by hand.

This is automated and advisory — it does not block merging.

rule count what it checks
TRF035 1 Model files must not silence the linter with # noqa.

@sushmanthreddy

sushmanthreddy commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @Cyrilvallez and @ArthurZucker, if either of you has time, could you take a look at the decoder loop and KV cache handling in this PR?

This adds native Nanbeige4.2 support using create_causal_mask, which addresses the deprecated mask dependency discussed in #51124. I followed #50585 for the cache API and Dory (#50099) for the per-pass cache slots and chunked decoding test. The slow BF16 generation test passed locally.

Thanks!

@sushmanthreddy sushmanthreddy changed the title [WIP] Add Nanbeige4.2-3B Add Nanbeige4.2-3B Nov 25, 2026

@lucamotz lucamotz left a comment

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.

Thanks for your work! Would be great if we could move forward with this. Have left my current draft of the implementation here as a review

tests/exporters/test_export.py
@@ -506,6 +506,10 @@ EXPORT_SKIPS: dict[str, dict[str, str]] = {
         "HieraForImageClassification": "Same OpenVINO all-dynamic-axes Hiera-backbone guard as `HieraModel`.",
         "HieraForPreTraining": "Same OpenVINO all-dynamic-axes Hiera-backbone guard as `HieraModel`.",
     },
+    # Every backend, static-cache generate variants only (a `generation_config` requesting a static cache).
+    "static-cache": {
+        "NanbeigeForCausalLM": "`copy.deepcopy` of the cache layers appended in `forward` fails on fake tensors.",
+    },
     # OpenVINO, static-cache generate variants only (a `generation_config` requesting a static cache).
     "openvino.static-cache": {
         "MiniMaxM3SparseForConditionalGeneration": (

- 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

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

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.

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

Comment on lines +34 to +39
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`.
"""

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
```"""

Comment on lines +79 to +83

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

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

logits_to_keep: int | torch.Tensor = 0,
**kwargs: Unpack[TransformersKwargs],
) -> CausalLMOutputWithPast:
r"""Return the final decoder pass's next-token logits in float32."""

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
r"""Return the final decoder pass's next-token logits in float32."""
r"""
Example:
```python
>>> from transformers import AutoTokenizer, NanbeigeForCausalLM
>>> model = NanbeigeForCausalLM.from_pretrained("Nanbeige/Nanbeige4.2-3B")
>>> tokenizer = AutoTokenizer.from_pretrained("Nanbeige/Nanbeige4.2-3B")
>>> 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
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs, max_new_tokens=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
```"""

Comment on lines +463 to +464
hidden_states = slice_logits_to_keep(outputs.last_hidden_state, logits_to_keep)
logits = self.lm_head(hidden_states).float()

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
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)

)


__all__ = ["NanbeigeForCausalLM", "NanbeigeModel", "NanbeigePreTrainedModel"]

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
__all__ = ["NanbeigeForCausalLM", "NanbeigeModel", "NanbeigePreTrainedModel"]
__all__ = ["NanbeigePreTrainedModel", "NanbeigeModel", "NanbeigeForCausalLM"]

Comment on lines +16 to +21
import unittest

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

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
import unittest
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
import copy
import unittest
from transformers import AutoTokenizer, is_torch_available
from transformers.testing_utils import Expectations, require_torch, require_torch_accelerator, slow, torch_device
from ...causal_lm_tester import CausalLMModelTest, CausalLMModelTester
from ...test_memory_cleanup_mixin import MemoryCleanupMixin

Comment on lines +34 to +91
# 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

@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()
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():
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])


@slow
@require_torch_accelerator
class NanbeigeIntegrationTest(unittest.TestCase):
checkpoint = "Nanbeige/Nanbeige4.2-3B"

def test_bf16_generation(self):
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."}],
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")

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
# 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
@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()
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():
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])
@slow
@require_torch_accelerator
class NanbeigeIntegrationTest(unittest.TestCase):
checkpoint = "Nanbeige/Nanbeige4.2-3B"
def test_bf16_generation(self):
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."}],
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")
small_config_overrides = {
"num_loops": 2,
# hidden states are recorded for the embeddings and at every layer call (2 layers, 2 loops)
"expected_num_hidden_layers": 2 * 2 + 1,
}
@require_torch
class NanbeigeModelTest(CausalLMModelTest, unittest.TestCase):
model_tester_class = NanbeigeModelTester
@unittest.skip("Attentions are returned per layer call: the layers run once per loop")
def test_attention_outputs(self):
pass
def _check_cache_for_generate(self, batch_size, cache, seq_length, config):
# Each loop has its own copy of the cache layers, appended after the first loop's
self.assertEqual(len(cache), config.num_loops * config.num_hidden_layers)
for start in range(0, len(cache), config.num_hidden_layers):
loop_cache = copy.copy(cache)
loop_cache.layers = cache.layers[start : start + config.num_hidden_layers]
super()._check_cache_for_generate(batch_size, loop_cache, seq_length, config)
@slow
@require_torch_accelerator
class NanbeigeIntegrationTest(MemoryCleanupMixin, unittest.TestCase):
checkpoint = "Nanbeige/Nanbeige4.2-3B"
def test_bf16_generation(self):
tokenizer = AutoTokenizer.from_pretrained(self.checkpoint)
model = NanbeigeForCausalLM.from_pretrained(self.checkpoint, dtype=torch.bfloat16, device_map=torch_device)
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
).to(torch_device)
output = model.generate(**inputs, max_new_tokens=24, do_sample=False)
text = tokenizer.decode(output[0, inputs["input_ids"].shape[1] :])
expected_text = Expectations(
{(None, None): 'We are asked: "Which number is bigger, 9.11 or 9.8?" This seems straightforward'}
).get_expectation()
self.assertEqual(text, expected_text)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add native Transformers support for Nanbeige4.2-3B

2 participants