huggingface/transformers · #49463
Add Kolibri 1
docs/source/en/_toctree.yml2 + / 0 −
@@ -737,6 +737,8 @@ title: jina_embeddings_v3 - local: model_doc/kimi_linear title: KimiLinear+ - local: model_doc/kolibri1+ title: Kolibri1 - local: model_doc/laguna title: Laguna - local: model_doc/leddocs/source/en/model_doc/kolibri1.mdadded48 + / 0 −
@@ -0,0 +1,48 @@+<!--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 contributed to Hugging Face Transformers on 2026-10-12.*++# Kolibri1++[Kolibri 1](https://huggingface.co/Aleph-Alpha/Kolibri-1) is Aleph Alpha's mixture-of-experts reasoning model with a focus on German and English. Each of its 50 layers routes every token to 6 of 384 experts with sigmoid routing and adds one shared expert. Four sliding-window attention layers alternate with one full-attention layer, and RoPE is applied only in the sliding-window layers.++```python+from transformers import AutoModelForCausalLM, AutoTokenizer++tokenizer = AutoTokenizer.from_pretrained("Aleph-Alpha/Kolibri-1-BF16")+model = AutoModelForCausalLM.from_pretrained("Aleph-Alpha/Kolibri-1-BF16", device_map="auto")++messages = [{"role": "user", "content": "Erkläre kurz, was ein Mixture-of-Experts-Modell ist."}]+inputs = tokenizer.apply_chat_template(+ messages, add_generation_prompt=True, return_tensors="pt", return_dict=True+).to(model.device)+outputs = model.generate(**inputs, max_new_tokens=256)+print(tokenizer.decode(outputs[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True))+```++## Kolibri1Config++[[autodoc]] Kolibri1Config++## Kolibri1Model++[[autodoc]] Kolibri1Model+ - forward++## Kolibri1ForCausalLM++[[autodoc]] Kolibri1ForCausalLM+ - forwardsrc/transformers/conversion_mapping.py7 + / 0 −
@@ -1965,6 +1965,13 @@ def _build_checkpoint_conversion_mapping(): mapping["exaone_moe"] = mapping["qwen2_moe"].copy() mapping["exaone_moe"] += [WeightRenaming("mlp.e_score_correction_bias", "mlp.gate.e_score_correction_bias")] + mapping["kolibri1"] = mapping["qwen2_moe"].copy()+ mapping["kolibri1"] += [+ WeightRenaming("moe.router.expert_bias", "mlp.gate.e_score_correction_bias"),+ WeightRenaming("post_attn_norm", "post_self_attn_layernorm"),+ WeightRenaming("post_ffn_norm", "post_mlp_layernorm"),+ ]+ mapping["mimo_v2_flash"] = mapping["qwen2_moe"].copy() mapping["mimo_v2_flash"] += [ WeightRenaming("self_attn.attention_sink_bias", "self_attn.sinks"),src/transformers/models/__init__.py1 + / 0 −
@@ -247,6 +247,7 @@ from .jina_embeddings_v3 import * from .kimi_k25 import * from .kimi_linear import *+ from .kolibri1 import * from .kosmos2 import * from .kosmos2_5 import * from .kyutai_speech_to_text import *src/transformers/models/auto/auto_mappings.py1 + / 0 −
@@ -347,6 +347,7 @@ ("kimi_k25", "Kimi_K25Config"), ("kimi_k25_vision", "Kimi_K25VisionConfig"), ("kimi_linear", "KimiLinearConfig"),+ ("kolibri1", "Kolibri1Config"), ("kosmos-2", "Kosmos2Config"), ("kosmos-2.5", "Kosmos2_5Config"), ("kosmos_2_5_text_model", "Kosmos2_5TextConfig"),src/transformers/models/auto/modeling_auto.py2 + / 0 −
@@ -289,6 +289,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("kimi_k25", "Kimi_K25Model"), ("kimi_k25_vision", "Kimi_K25VisionModel"), ("kimi_linear", "KimiLinearModel"),+ ("kolibri1", "Kolibri1Model"), ("kosmos-2", "Kosmos2Model"), ("kosmos-2.5", "Kosmos2_5Model"), ("kyutai_speech_to_text", "KyutaiSpeechToTextModel"),@@ -806,6 +807,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("jamba", "JambaForCausalLM"), ("jetmoe", "JetMoeForCausalLM"), ("kimi_linear", "KimiLinearForCausalLM"),+ ("kolibri1", "Kolibri1ForCausalLM"), ("laguna", "LagunaForCausalLM"), ("lfm2", "Lfm2ForCausalLM"), ("lfm2_moe", "Lfm2MoeForCausalLM"),src/transformers/models/kolibri1/__init__.pyadded33 + / 0 −
@@ -0,0 +1,33 @@+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨+# This file was automatically generated from the modules in `src/transformers/models/kolibri1`.+# 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 Inc. 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_kolibri1 import *+ from .modeling_kolibri1 import *+else:+ import sys++ _file = globals()["__file__"]+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)src/transformers/models/kolibri1/configuration_kolibri1.pyadded112 + / 0 −
@@ -0,0 +1,112 @@+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨+# This file was automatically generated from src/transformers/models/kolibri1/modular_kolibri1.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_kolibri1.py file directly. One of our CI enforces this.+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨+# Copyright 2026 The HuggingFace Inc. 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+++@auto_docstring(checkpoint="Aleph-Alpha/Kolibri-1")+@strict+class Kolibri1Config(PreTrainedConfig):+ r"""+ ```python+ >>> from transformers import Kolibri1Model, Kolibri1Config++ >>> configuration = Kolibri1Config()+ >>> model = Kolibri1Model(configuration)+ >>> configuration = model.config+ ```+ """++ model_type = "kolibri1"+ keys_to_ignore_at_inference = ["past_key_values"]++ attribute_map = {+ "num_experts": "num_local_experts",+ }+ 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.q_norm": "replicated_with_grad_allreduce",+ "layers.*.self_attn.k_norm": "replicated_with_grad_allreduce",+ "layers.*.self_attn.o_proj": "rowwise",+ "layers.*.mlp.experts.gate_up_proj": "packed_colwise",+ "layers.*.mlp.experts.down_proj": "rowwise",+ "layers.*.mlp.experts": "moe_tp_experts",+ "layers.*.mlp.shared_experts.gate_proj": "colwise",+ "layers.*.mlp.shared_experts.up_proj": "colwise",+ "layers.*.mlp.shared_experts.down_proj": "rowwise",+ }+ # Token dispatch by default, so `ep_size` can exceed `tp_size` (bounded by `num_key_value_heads`)+ base_model_ep_plan = {+ "layers.*.mlp.experts.gate_up_proj": "grouped_gemm",+ "layers.*.mlp.experts.down_proj": "grouped_gemm",+ "layers.*.mlp.experts": "ep_dispatch_experts",+ }+ 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 = 128000+ hidden_size: int = 2560+ num_hidden_layers: int = 50+ num_attention_heads: int = 48+ num_key_value_heads: int = 4+ hidden_act: str = "silu"+ max_position_embeddings: int = 262144+ initializer_range: float = 0.02+ rms_norm_eps: float = 1e-6+ use_cache: bool = True+ tie_word_embeddings: bool = False+ rope_parameters: RopeParameters | dict | None = None+ sliding_window: int | None = 513+ attention_dropout: float | int = 0.0+ moe_intermediate_size: int = 512+ num_experts_per_tok: int = 6+ num_experts: int = 384+ norm_topk_prob: bool = False+ output_router_logits: bool = False+ pad_token_id: int | None = None+ bos_token_id: int | None = None+ eos_token_id: int | list[int] | None = None+ head_dim: int = 128+ shared_expert_intermediate_size: int = 512+ layer_types: list[str] | None = None++ def __post_init__(self, **kwargs):+ if self.layer_types is None:+ self.layer_types = [+ "full_attention" if (i + 1) % 5 == 0 else "sliding_attention" for i in range(self.num_hidden_layers)+ ]+ super().__post_init__(**kwargs)++ def validate_architecture(self):+ super().validate_architecture()+ if "sliding_attention" in self.layer_types and (self.sliding_window is None or self.sliding_window <= 0):+ raise ValueError(f"Sliding-attention layers need a positive `sliding_window`, got {self.sliding_window}.")+++__all__ = ["Kolibri1Config"]src/transformers/models/kolibri1/modeling_kolibri1.pyadded599 + / 0 −
@@ -0,0 +1,599 @@+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨+# This file was automatically generated from src/transformers/models/kolibri1/modular_kolibri1.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_kolibri1.py file directly. One of our CI enforces this.+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨+# Copyright 2026 The HuggingFace Inc. 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+import torch.nn.functional as F+from torch import nn++from ... import initialization as init+from ...activations import ACT2FN+from ...cache_utils import Cache, DynamicCache+from ...generation import GenerationMixin+from ...integrations import use_experts_implementation, use_kernel_forward_from_hub+from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask+from ...modeling_flash_attention_utils import FlashAttentionKwargs+from ...modeling_layers import GradientCheckpointingLayer+from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel+from ...processing_utils import Unpack+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torch_greater_or_equal+from ...utils.generic import merge_with_config_defaults+from ...utils.output_capturing import OutputRecorder, capture_outputs+from .configuration_kolibri1 import Kolibri1Config+++@use_kernel_forward_from_hub("RMSNorm")+class Kolibri1RMSNorm(nn.Module):+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:+ """+ Kolibri1RMSNorm 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}"+++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+++class Kolibri1Attention(nn.Module):+ def __init__(self, config: Kolibri1Config, layer_idx: int):+ super().__init__()+ self.config = config+ self.layer_idx = layer_idx+ self.num_attention_heads = config.num_attention_heads+ self.num_key_value_heads = config.num_key_value_heads+ self.hidden_size = config.hidden_size+ 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.attention_dropout = config.attention_dropout+ self.is_causal = True+ self.scaling = self.head_dim**-0.5+ self.sliding_window = config.sliding_window+ layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None+ self.is_sliding = layer_type == "sliding_attention"++ self.q_proj = nn.Linear(self.hidden_size, self.num_attention_heads * self.head_dim, bias=False)+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)+ self.o_proj = nn.Linear(self.num_attention_heads * self.head_dim, self.hidden_size, bias=False)++ self.q_norm = Kolibri1RMSNorm(self.head_dim, eps=config.rms_norm_eps)+ self.k_norm = Kolibri1RMSNorm(self.head_dim, eps=config.rms_norm_eps)++ def forward(+ self,+ hidden_states: torch.Tensor,+ position_embeddings: tuple[torch.Tensor, torch.Tensor],+ attention_mask: torch.Tensor | None = None,+ past_key_values: Cache | None = None,+ **kwargs: Unpack[TransformersKwargs],+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[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)++ # We use QK-norm+ query_states = self.q_norm(query_states)+ key_states = self.k_norm(key_states)++ cos, sin = position_embeddings+ # We use global NoPE for hybrid attention model+ if self.sliding_window is None or self.is_sliding:+ 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,+ sliding_window=self.sliding_window if self.is_sliding else None,+ **kwargs,+ )++ attn_output = attn_output.reshape(*input_shape, -1).contiguous()+ attn_output = self.o_proj(attn_output)+ return attn_output, attn_weights+++class Kolibri1MLP(nn.Module):+ def __init__(self, config, intermediate_size=None):+ super().__init__()+ self.config = config+ self.hidden_size = config.hidden_size+ self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)+ 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+++@use_experts_implementation+class Kolibri1Experts(nn.Module):+ """Collection of expert weights stored as 3D tensors."""++ def __init__(self, config):+ super().__init__()+ self.num_experts = config.num_experts+ self.hidden_dim = config.hidden_size+ self.intermediate_dim = config.moe_intermediate_size+ self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_dim))+ self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, self.intermediate_dim))+ self.act_fn = ACT2FN[config.hidden_act]++ def forward(+ self,+ hidden_states: torch.Tensor,+ top_k_index: torch.Tensor,+ top_k_weights: torch.Tensor,+ ) -> torch.Tensor:+ final_hidden_states = torch.zeros_like(hidden_states)+ with torch.no_grad():+ expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts + 1)+ expert_mask = expert_mask.permute(2, 1, 0)+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()++ for expert_idx in expert_hit:+ expert_idx = expert_idx[0]+ if expert_idx == self.num_experts:+ continue+ top_k_pos, token_idx = torch.where(expert_mask[expert_idx])+ current_state = hidden_states[token_idx]+ gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)+ current_hidden_states = self.act_fn(gate) * up+ current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])+ current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]+ final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))++ return final_hidden_states+++class Kolibri1TopKRouter(nn.Module):+ def __init__(self, config):+ super().__init__()+ self.top_k = config.num_experts_per_tok+ self.num_experts = config.num_experts+ self.norm_topk_prob = config.norm_topk_prob+ self.hidden_dim = config.hidden_size+ self.weight = nn.Parameter(torch.zeros(self.num_experts, self.hidden_dim))+ self.e_score_correction_bias = nn.Buffer(torch.zeros(self.num_experts))++ def forward(self, hidden_states):+ hidden_states = hidden_states.reshape(-1, self.hidden_dim)+ if (+ hidden_states.is_cuda+ and hidden_states.dtype == self.weight.dtype+ and not torch.is_grad_enabled()+ and is_torch_greater_or_equal("2.8.0")+ ):+ # Faster inference (e.g. in vLLM): fp32 logits from a bf16 GEMM instead of an fp32 one.+ # `out_dtype` is CUDA-only, has no autograd and needs matching dtypes+ router_logits = torch.mm(hidden_states, self.weight.t(), out_dtype=torch.float32)+ else:+ router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))+ router_indices = torch.topk(router_logits + self.e_score_correction_bias, self.top_k, dim=-1)[1]+ router_scores = router_logits.gather(1, router_indices).sigmoid()+ if self.norm_topk_prob:+ router_scores = router_scores / router_scores.sum(dim=-1, keepdim=True)+ return router_logits, router_scores, router_indices+++class Kolibri1SparseMoeBlock(nn.Module):+ """+ A mixed expert module containing shared experts.+ """++ def __init__(self, config: Kolibri1Config):+ super().__init__()+ self.config = config+ self.experts = Kolibri1Experts(config)+ self.gate = Kolibri1TopKRouter(config)+ self.shared_experts = Kolibri1MLP(config, intermediate_size=config.shared_expert_intermediate_size)++ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:+ residuals = hidden_states+ orig_shape = hidden_states.shape+ _, topk_weights, topk_indices = self.gate(hidden_states)+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])+ hidden_states = self.experts(hidden_states, topk_indices, topk_weights).view(*orig_shape)+ hidden_states = hidden_states + self.shared_experts(residuals)+ return hidden_states+++class Kolibri1DecoderLayer(GradientCheckpointingLayer):+ def __init__(self, config: Kolibri1Config, layer_idx: int):+ super().__init__()+ self.hidden_size = config.hidden_size+ self.self_attn = Kolibri1Attention(config=config, layer_idx=layer_idx)+ self.mlp = Kolibri1SparseMoeBlock(config)+ self.input_layernorm = Kolibri1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)+ self.post_attention_layernorm = Kolibri1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)+ self.post_self_attn_layernorm = Kolibri1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)+ self.post_mlp_layernorm = Kolibri1RMSNorm(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[FlashAttentionKwargs],+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:+ residual = hidden_states+ hidden_states = self.input_layernorm(hidden_states)++ 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 = self.post_self_attn_layernorm(hidden_states)+ hidden_states = residual + hidden_states++ residual = hidden_states+ hidden_states = self.post_attention_layernorm(hidden_states)+ hidden_states = self.mlp(hidden_states)+ hidden_states = self.post_mlp_layernorm(hidden_states)+ hidden_states = residual + hidden_states+ return hidden_states+++@auto_docstring+class Kolibri1PreTrainedModel(PreTrainedModel):+ config: Kolibri1Config+ base_model_prefix = "model"+ supports_gradient_checkpointing = True+ _no_split_modules = ["Kolibri1DecoderLayer"]+ _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 = {+ "router_logits": OutputRecorder(Kolibri1TopKRouter, index=0),+ "hidden_states": Kolibri1DecoderLayer,+ "attentions": Kolibri1Attention,+ }+ _keep_in_fp32_modules_strict = ["e_score_correction_bias"]++ @torch.no_grad()+ def _init_weights(self, module):+ super()._init_weights(module)+ std = self.config.initializer_range+ if isinstance(module, Kolibri1Experts):+ init.normal_(module.gate_up_proj, mean=0.0, std=std)+ init.normal_(module.down_proj, mean=0.0, std=std)+ elif isinstance(module, Kolibri1TopKRouter):+ init.normal_(module.weight, mean=0.0, std=std)+ if isinstance(module, Kolibri1TopKRouter):+ init.zeros_(module.e_score_correction_bias)+++class Kolibri1RotaryEmbedding(nn.Module):+ def __init__(self, config: Kolibri1Config):+ 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: Kolibri1Config, **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)+++@auto_docstring+class Kolibri1Model(Kolibri1PreTrainedModel):+ def __init__(self, config: Kolibri1Config):+ 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(+ [Kolibri1DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]+ )+ self.norm = Kolibri1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)+ self.rotary_emb = Kolibri1RotaryEmbedding(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.FloatTensor | None = None,+ use_cache: bool | None = None,+ **kwargs: Unpack[TransformersKwargs],+ ) -> MoeModelOutputWithPast:+ 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)++ 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)++ # It may already have been prepared by e.g. `generate`+ if not isinstance(causal_mask_mapping := attention_mask, dict):+ # Prepare mask arguments+ mask_kwargs = {+ "config": self.config,+ "inputs_embeds": inputs_embeds,+ "attention_mask": attention_mask,+ "past_key_values": past_key_values,+ "position_ids": position_ids,+ }+ # Create the masks+ causal_mask_mapping = {+ "full_attention": create_causal_mask(**mask_kwargs),+ "sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),+ }++ hidden_states = inputs_embeds+ position_embeddings = self.rotary_emb(hidden_states, position_ids)++ for i, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):+ hidden_states = decoder_layer(+ hidden_states,+ attention_mask=causal_mask_mapping[self.config.layer_types[i]],+ position_ids=position_ids,+ past_key_values=past_key_values,+ use_cache=use_cache,+ position_embeddings=position_embeddings,+ **kwargs,+ )++ hidden_states = self.norm(hidden_states)+ return MoeModelOutputWithPast(+ last_hidden_state=hidden_states,+ past_key_values=past_key_values if use_cache else None,+ )+++@auto_docstring+class Kolibri1ForCausalLM(Kolibri1PreTrainedModel, 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):+ super().__init__(config)+ self.model = Kolibri1Model(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.FloatTensor | None = None,+ labels: torch.LongTensor | None = None,+ use_cache: bool | None = None,+ logits_to_keep: int | torch.Tensor = 0,+ **kwargs: Unpack[TransformersKwargs],+ ) -> MoeCausalLMOutputWithPast:+ r"""+ Example:++ ```python+ >>> from transformers import AutoTokenizer, Kolibri1ForCausalLM++ >>> model = Kolibri1ForCausalLM.from_pretrained("Aleph-Alpha/Kolibri-1")+ >>> tokenizer = AutoTokenizer.from_pretrained("Aleph-Alpha/Kolibri-1")++ >>> prompt = "Hey, are you conscious? Can you talk to me?"+ >>> inputs = tokenizer(prompt, return_tensors="pt")++ >>> # 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]+ ```"""+ outputs: MoeModelOutputWithPast = 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+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep+ logits = self.lm_head(hidden_states[:, slice_indices, :])++ loss = None+ if labels is not None:+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)++ return MoeCausalLMOutputWithPast(+ loss=loss,+ logits=logits,+ past_key_values=outputs.past_key_values,+ hidden_states=outputs.hidden_states,+ attentions=outputs.attentions,+ router_logits=outputs.router_logits,+ )+++__all__ = ["Kolibri1ForCausalLM", "Kolibri1Model", "Kolibri1PreTrainedModel"]src/transformers/models/kolibri1/modular_kolibri1.pyadded196 + / 0 −
@@ -0,0 +1,196 @@+# Copyright 2026 The HuggingFace Inc. 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.++import torch+import torch.nn.functional as F+from huggingface_hub.dataclasses import strict+from torch import nn++from ... import initialization as init+from ...configuration_utils import PreTrainedConfig+from ...utils import auto_docstring, is_torch_greater_or_equal+from ..deepseek_v3.modeling_deepseek_v3 import DeepseekV3ForCausalLM, DeepseekV3MoE+from ..exaone4.modeling_exaone4 import Exaone4Attention+from ..glm4.modeling_glm4 import Glm4DecoderLayer+from ..qwen2_moe.modeling_qwen2_moe import Qwen2MoeModel+from ..qwen3_moe.configuration_qwen3_moe import Qwen3MoeConfig+from ..qwen3_moe.modeling_qwen3_moe import (+ Qwen3MoeExperts,+ Qwen3MoeMLP,+ Qwen3MoePreTrainedModel,+ Qwen3MoeTopKRouter,+)+++@auto_docstring(checkpoint="Aleph-Alpha/Kolibri-1")+@strict+class Kolibri1Config(Qwen3MoeConfig):+ r"""+ ```python+ >>> from transformers import Kolibri1Model, Kolibri1Config++ >>> configuration = Kolibri1Config()+ >>> model = Kolibri1Model(configuration)+ >>> configuration = model.config+ ```+ """++ model_type = "kolibri1"+ 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.q_norm": "replicated_with_grad_allreduce",+ "layers.*.self_attn.k_norm": "replicated_with_grad_allreduce",+ "layers.*.self_attn.o_proj": "rowwise",+ "layers.*.mlp.experts.gate_up_proj": "packed_colwise",+ "layers.*.mlp.experts.down_proj": "rowwise",+ "layers.*.mlp.experts": "moe_tp_experts",+ "layers.*.mlp.shared_experts.gate_proj": "colwise",+ "layers.*.mlp.shared_experts.up_proj": "colwise",+ "layers.*.mlp.shared_experts.down_proj": "rowwise",+ }+ # Token dispatch by default, so `ep_size` can exceed `tp_size` (bounded by `num_key_value_heads`)+ base_model_ep_plan = {+ "layers.*.mlp.experts.gate_up_proj": "grouped_gemm",+ "layers.*.mlp.experts.down_proj": "grouped_gemm",+ "layers.*.mlp.experts": "ep_dispatch_experts",+ }++ vocab_size: int = 128000+ hidden_size: int = 2560+ num_hidden_layers: int = 50+ num_attention_heads: int = 48+ head_dim: int = 128+ max_position_embeddings: int = 262144+ sliding_window: int | None = 513+ moe_intermediate_size: int = 512+ shared_expert_intermediate_size: int = 512+ num_experts_per_tok: int = 6+ num_experts: int = 384+ layer_types: list[str] | None = None++ intermediate_size = AttributeError()+ use_sliding_window = AttributeError()+ decoder_sparse_step = AttributeError()+ mlp_only_layers = AttributeError()+ attention_bias = AttributeError()+ router_aux_loss_coef = AttributeError()++ def __post_init__(self, **kwargs):+ if self.layer_types is None:+ self.layer_types = [+ "full_attention" if (i + 1) % 5 == 0 else "sliding_attention" for i in range(self.num_hidden_layers)+ ]+ PreTrainedConfig.__post_init__(self, **kwargs)++ def validate_architecture(self):+ PreTrainedConfig.validate_architecture(self)+ if "sliding_attention" in self.layer_types and (self.sliding_window is None or self.sliding_window <= 0):+ raise ValueError(f"Sliding-attention layers need a positive `sliding_window`, got {self.sliding_window}.")+++class Kolibri1Attention(Exaone4Attention):+ def __init__(self, config: Kolibri1Config, layer_idx: int):+ super().__init__(config, layer_idx)+ del self.sliding_window_pattern+++class Kolibri1MLP(Qwen3MoeMLP):+ pass+++class Kolibri1Experts(Qwen3MoeExperts):+ pass+++class Kolibri1TopKRouter(Qwen3MoeTopKRouter):+ def __init__(self, config):+ super().__init__(config)+ self.e_score_correction_bias = nn.Buffer(torch.zeros(self.num_experts))++ def forward(self, hidden_states):+ hidden_states = hidden_states.reshape(-1, self.hidden_dim)+ if (+ hidden_states.is_cuda+ and hidden_states.dtype == self.weight.dtype+ and not torch.is_grad_enabled()+ and is_torch_greater_or_equal("2.8.0")+ ):+ # Faster inference (e.g. in vLLM): fp32 logits from a bf16 GEMM instead of an fp32 one.+ # `out_dtype` is CUDA-only, has no autograd and needs matching dtypes+ router_logits = torch.mm(hidden_states, self.weight.t(), out_dtype=torch.float32)+ else:+ router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))+ router_indices = torch.topk(router_logits + self.e_score_correction_bias, self.top_k, dim=-1)[1]+ router_scores = router_logits.gather(1, router_indices).sigmoid()+ if self.norm_topk_prob:+ router_scores = router_scores / router_scores.sum(dim=-1, keepdim=True)+ return router_logits, router_scores, router_indices+++class Kolibri1SparseMoeBlock(DeepseekV3MoE):+ def __init__(self, config: Kolibri1Config):+ super().__init__(config)+ self.gate = Kolibri1TopKRouter(config)+ self.shared_experts = Kolibri1MLP(config, intermediate_size=config.shared_expert_intermediate_size)+++class Kolibri1DecoderLayer(Glm4DecoderLayer):+ def __init__(self, config: Kolibri1Config, layer_idx: int):+ super().__init__(config, layer_idx)+ self.mlp = Kolibri1SparseMoeBlock(config)+++class Kolibri1PreTrainedModel(Qwen3MoePreTrainedModel):+ _keep_in_fp32_modules_strict = ["e_score_correction_bias"]++ @torch.no_grad()+ def _init_weights(self, module):+ super()._init_weights(module)+ if isinstance(module, Kolibri1TopKRouter):+ init.zeros_(module.e_score_correction_bias)+++class Kolibri1Model(Qwen2MoeModel):+ pass+++class Kolibri1ForCausalLM(DeepseekV3ForCausalLM):+ def forward(self, **super_kwargs):+ r"""+ Example:++ ```python+ >>> from transformers import AutoTokenizer, Kolibri1ForCausalLM++ >>> model = Kolibri1ForCausalLM.from_pretrained("Aleph-Alpha/Kolibri-1")+ >>> tokenizer = AutoTokenizer.from_pretrained("Aleph-Alpha/Kolibri-1")++ >>> prompt = "Hey, are you conscious? Can you talk to me?"+ >>> inputs = tokenizer(prompt, return_tensors="pt")++ >>> # 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]+ ```"""+ return super().forward(**super_kwargs)+++__all__ = [+ "Kolibri1Config",+ "Kolibri1ForCausalLM",+ "Kolibri1Model",+ "Kolibri1PreTrainedModel",+]tests/models/kolibri1/__init__.pyadded0 + / 0 −
GitHub publishes no diff for this file. View it on GitHub ↗
tests/models/kolibri1/test_modeling_kolibri1.pyadded152 + / 0 −
@@ -0,0 +1,152 @@+# Copyright 2026 The HuggingFace Inc. 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 Kolibri1 model."""++import unittest++from huggingface_hub.errors import StrictDataclassClassValidationError++from transformers import AutoTokenizer, is_torch_available+from transformers.testing_utils import (+ Expectations,+ require_torch,+ require_torch_accelerator_memory,+ require_torch_gpu,+ 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 Kolibri1Config, Kolibri1ForCausalLM, Kolibri1Model+++class Kolibri1ModelTester(CausalLMModelTester):+ if is_torch_available():+ base_model_class = Kolibri1Model++ def __init__(self, parent):+ super().__init__(parent=parent)+ self.layer_types = ["sliding_attention", "full_attention"]+++@require_torch+class Kolibri1ModelTest(CausalLMModelTest, unittest.TestCase):+ model_tester_class = Kolibri1ModelTester++ def test_sliding_window_required(self):+ with self.assertRaises(StrictDataclassClassValidationError):+ Kolibri1Config(sliding_window=None)++ def test_no_load_balancing_loss(self):+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()+ model = Kolibri1ForCausalLM(config).to(torch_device).eval()+ input_ids = input_dict["input_ids"]++ with torch.no_grad():+ plain = model(input_ids, labels=input_ids)+ with_router_logits = model(input_ids, labels=input_ids, output_router_logits=True)++ self.assertIsNone(with_router_logits.aux_loss)+ self.assertEqual(len(with_router_logits.router_logits), config.num_hidden_layers)+ torch.testing.assert_close(with_router_logits.loss, plain.loss)++ @require_torch_gpu+ def test_router_with_activations_in_another_dtype(self):+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()+ model = Kolibri1ForCausalLM(config).to(torch_device, torch.bfloat16).eval()+ inputs_embeds = model.get_input_embeddings()(input_dict["input_ids"]).float()++ with torch.no_grad(), torch.autocast(torch_device, dtype=torch.bfloat16):+ logits = model(inputs_embeds=inputs_embeds).logits++ self.assertFalse(logits.isnan().any())+++@slow+@require_torch_accelerator_memory(memory=180)+class Kolibri1IntegrationTest(MemoryCleanupMixin, unittest.TestCase):+ TEST_MODEL_ID = "Aleph-Alpha/Kolibri-1-BF16"++ @classmethod+ def setUpClass(cls):+ super().setUpClass()+ # Dropped again by the mixin's `tearDownClass`.+ cls.model = None++ @classmethod+ def get_model(cls):+ if cls.model is None:+ cls.model = Kolibri1ForCausalLM.from_pretrained(+ cls.TEST_MODEL_ID, device_map="auto", experts_implementation="eager"+ )+ return cls.model++ def generate_reply(self, content, max_new_tokens):+ tokenizer = AutoTokenizer.from_pretrained(self.TEST_MODEL_ID)+ model = self.get_model()+ inputs = tokenizer.apply_chat_template(+ [{"role": "user", "content": content}],+ add_generation_prompt=True,+ enable_thinking=False,+ return_tensors="pt",+ return_dict=True,+ ).to(model.device)+ with torch.no_grad():+ generated_ids = model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False)+ return tokenizer.decode(generated_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True)++ def test_model_logits(self):+ input_ids = [452, 22090, 493, 1678, 2459]+ model = self.get_model()+ input_ids = torch.tensor([input_ids]).to(model.device)+ with torch.no_grad():+ out = model(input_ids).logits.float().cpu()++ # fmt: off+ EXPECTED_MEAN = Expectations(+ {+ ("cuda", None): torch.tensor([[-3.6648, -4.0749, -3.8838, -4.3631, -3.9150]]),+ }+ ).get_expectation()+ EXPECTED_SLICE = Expectations(+ {+ ("cuda", None): torch.tensor(+ [-2.0000, -7.0938, -8.3750, -9.5000, -8.6875, -8.6875, -8.9375, -7.9062, -4.7188, 1.8594]+ ),+ }+ ).get_expectation()+ # fmt: on+ torch.testing.assert_close(out.mean(-1), EXPECTED_MEAN, atol=1e-2, rtol=1e-2)+ torch.testing.assert_close(out[0, 0, :10], EXPECTED_SLICE, atol=1e-2, rtol=1e-2)++ def test_model_generation(self):+ EXPECTED_TEXT = (+ "Ein Mixture-of-Experts-Modell ist ein neuronales Netz, das aus mehreren spezialisierten Experten "+ "besteht, von denen bei jeder Vorhersage nur ein kleiner Teil aktiviert wird, um Effizienz und "+ "Skalierbarkeit zu erhöhen."+ )+ text = self.generate_reply("Erkläre in einem Satz, was ein Mixture-of-Experts-Modell ist.", 40)+ self.assertEqual(EXPECTED_TEXT, text)++ def test_model_recall_beyond_sliding_window(self):+ filler = "Der Himmel ist blau. Das Gras ist grün. Die Sonne scheint. " * 150+ prompt = f"Merke dir: Der Geheimcode lautet 4721.\n\n{filler}\nWie lautet der Geheimcode? Antworte nur mit der Zahl."+ text = self.generate_reply(prompt, 10)+ self.assertEqual("4721", text)