FrontiersMind/Nandi-Mini-150M-Instruct
52162
1# ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ2# This file was automatically generated from src/transformers/models/nandi/modular_nandi.py.3# Do NOT edit this file manually as any edits will be overwritten by the generation of4# the file from the modular. If any change should be done, please apply the change to the5# modular_nandi.py file directly. One of our CI enforces this.6# ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ7# Copyright 2026 The HuggingFace Inc. team. All rights reserved.8#9# Licensed under the Apache License, Version 2.0 (the "License");10# you may not use this file except in compliance with the License.11# You may obtain a copy of the License at12#13# http://www.apache.org/licenses/LICENSE-2.014#15# Unless required by applicable law or agreed to in writing, software16# distributed under the License is distributed on an "AS IS" BASIS,17# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.18# See the License for the specific language governing permissions and19# limitations under the License.20 21from collections.abc import Callable22 23import torch24import torch.nn as nn25 26from transformers.activations import ACT2FN27from transformers.cache_utils import Cache, DynamicCache, DynamicLayer28from transformers.generation import GenerationMixin29from transformers.integrations import use_kernel_forward_from_hub30from transformers.masking_utils import create_causal_mask31from transformers.modeling_layers import GradientCheckpointingLayer32from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast33from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update34from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel35from transformers.processing_utils import Unpack36from transformers.utils import TransformersKwargs, auto_docstring37from transformers.utils.deprecation import deprecate_kwarg38from transformers.utils.generic import can_return_tuple, merge_with_config_defaults39from transformers.utils.output_capturing import capture_outputs40from .configuration_nandi import NandiConfig41 42 43@use_kernel_forward_from_hub("RMSNorm")44class NandiRMSNorm(nn.Module):45 def __init__(self, hidden_size, eps=1e-6):46 super().__init__()47 self.weight = nn.Parameter(torch.ones(hidden_size))48 self.variance_epsilon = eps49 50 def forward(self, hidden_states):51 input_dtype = hidden_states.dtype52 hidden_states = hidden_states.to(torch.float32)53 variance = hidden_states.pow(2).mean(-1, keepdim=True)54 hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)55 return self.weight * hidden_states.to(input_dtype)56 57 def extra_repr(self):58 return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"59 60 61class NandiRotaryEmbedding(nn.Module):62 inv_freq: torch.Tensor63 64 def __init__(self, config: NandiConfig, device=None):65 super().__init__()66 self.max_seq_len_cached = config.max_position_embeddings67 self.original_max_seq_len = config.max_position_embeddings68 69 self.config = config70 self.rope_type = self.config.rope_parameters.get("rope_type", "default")71 rope_init_fn: Callable = self.compute_default_rope_parameters72 if self.rope_type != "default":73 rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]74 inv_freq, self.attention_scaling = rope_init_fn(self.config, device)75 76 self.register_buffer("inv_freq", inv_freq, persistent=False)77 self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)78 79 @staticmethod80 def compute_default_rope_parameters(81 config: NandiConfig | None = None,82 device: torch.device | None = None,83 seq_len: int | None = None,84 ) -> tuple[torch.Tensor, float]:85 del seq_len86 base = config.rope_parameters["rope_theta"]87 dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads88 attention_factor = 1.089 inv_freq = 1.0 / (90 base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)91 )92 return inv_freq, attention_factor93 94 @torch.no_grad()95 @dynamic_rope_update96 def forward(self, x, position_ids):97 inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)98 position_ids_expanded = position_ids[:, None, :].float()99 100 device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"101 with torch.autocast(device_type=device_type, enabled=False):102 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)103 emb = torch.cat((freqs, freqs), dim=-1)104 cos = emb.cos() * self.attention_scaling105 sin = emb.sin() * self.attention_scaling106 107 return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)108 109 110def rotate_half(x):111 """Rotates half the hidden dims of the input."""112 x1 = x[..., : x.shape[-1] // 2]113 x2 = x[..., x.shape[-1] // 2 :]114 return torch.cat((-x2, x1), dim=-1)115 116 117def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):118 del position_ids119 cos = cos.unsqueeze(unsqueeze_dim)120 sin = sin.unsqueeze(unsqueeze_dim)121 q_embed = (q * cos) + (rotate_half(q) * sin)122 k_embed = (k * cos) + (rotate_half(k) * sin)123 return q_embed, k_embed124 125 126def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:127 batch, num_key_value_heads, slen, head_dim = hidden_states.shape128 if n_rep == 1:129 return hidden_states130 hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)131 return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)132 133 134def eager_attention_forward(135 module: nn.Module,136 query: torch.Tensor,137 key: torch.Tensor,138 value: torch.Tensor,139 attention_mask: torch.Tensor | None,140 scaling: float,141 dropout: float = 0.0,142 **kwargs: Unpack[TransformersKwargs],143):144 del kwargs145 key_states = repeat_kv(key, module.num_key_value_groups)146 value_states = repeat_kv(value, module.num_key_value_groups)147 148 attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling149 if attention_mask is not None:150 causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]151 attn_weights = attn_weights + causal_mask152 153 attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)154 attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)155 attn_output = torch.matmul(attn_weights, value_states)156 attn_output = attn_output.transpose(1, 2).contiguous()157 158 return attn_output, attn_weights159 160 161class NandiAttention(nn.Module):162 def __init__(self, config: NandiConfig, layer_idx: int):163 super().__init__()164 self.config = config165 self.layer_idx = layer_idx166 self.head_dim = config.head_dim167 self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads168 self.scaling = self.head_dim**-0.5169 self.attention_dropout = config.attention_dropout170 self.is_causal = True171 172 self.q_proj = nn.Linear(173 config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias174 )175 self.k_proj = nn.Linear(176 config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias177 )178 self.v_proj = nn.Linear(179 config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias180 )181 self.o_proj = nn.Linear(182 config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias183 )184 185 @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")186 def forward(187 self,188 hidden_states: torch.Tensor,189 position_embeddings: tuple[torch.Tensor, torch.Tensor],190 attention_mask: torch.Tensor | None,191 past_key_values: Cache | None = None,192 **kwargs: Unpack[TransformersKwargs],193 ) -> tuple[torch.Tensor, torch.Tensor]:194 input_shape = hidden_states.shape[:-1]195 hidden_shape = (*input_shape, -1, self.head_dim)196 197 query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)198 key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)199 value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)200 201 cos, sin = position_embeddings202 query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)203 204 if past_key_values is not None:205 key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)206 207 attention_interface: Callable = eager_attention_forward208 if self.config._attn_implementation != "eager":209 attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]210 211 attn_output, attn_weights = attention_interface(212 self,213 query_states,214 key_states,215 value_states,216 attention_mask,217 dropout=0.0 if not self.training else self.attention_dropout,218 scaling=self.scaling,219 **kwargs,220 )221 222 attn_output = attn_output.reshape(*input_shape, -1).contiguous()223 attn_output = self.o_proj(attn_output)224 return attn_output, attn_weights225 226 227class NandiMLP(nn.Module):228 def __init__(self, config):229 super().__init__()230 self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.mlp_bias)231 self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.mlp_bias)232 self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.mlp_bias)233 self.act_fn = ACT2FN[config.hidden_act]234 235 def forward(self, x):236 return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))237 238 239class NandiDecoderLayer(GradientCheckpointingLayer):240 def __init__(self, config: NandiConfig, layer_idx: int):241 super().__init__()242 self.hidden_size = config.hidden_size243 self.self_attn = NandiAttention(config=config, layer_idx=layer_idx)244 self.mlp = NandiMLP(config)245 self.input_layernorm = NandiRMSNorm(config.hidden_size, eps=config.rms_norm_eps)246 self.post_attention_layernorm = NandiRMSNorm(config.hidden_size, eps=config.rms_norm_eps)247 248 @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")249 def forward(250 self,251 hidden_states: torch.Tensor,252 attention_mask: torch.Tensor | None = None,253 position_ids: torch.LongTensor | None = None,254 past_key_values: Cache | None = None,255 use_cache: bool | None = False,256 position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,257 **kwargs: Unpack[TransformersKwargs],258 ) -> torch.Tensor:259 residual = hidden_states260 hidden_states = self.input_layernorm(hidden_states)261 262 hidden_states, _ = self.self_attn(263 hidden_states=hidden_states,264 attention_mask=attention_mask,265 position_ids=position_ids,266 past_key_values=past_key_values,267 use_cache=use_cache,268 position_embeddings=position_embeddings,269 **kwargs,270 )271 hidden_states = residual + hidden_states272 273 residual = hidden_states274 hidden_states = self.post_attention_layernorm(hidden_states)275 hidden_states = self.mlp(hidden_states)276 hidden_states = residual + hidden_states277 return hidden_states278 279 280class _VirtualLayerCache:281 """Proxy that shifts cache layer indices by `offset` to give each repeat its own virtual slots."""282 283 def __init__(self, cache: Cache, offset: int):284 self._cache = cache285 self._offset = offset286 287 def __getattr__(self, name):288 return getattr(self._cache, name)289 290 def update(self, key_states, value_states, layer_idx, cache_kwargs=None):291 virtual_idx = layer_idx + self._offset292 # grow the backing cache if generate() pre-allocated fewer slots than needed293 while len(self._cache.layers) <= virtual_idx:294 self._cache.layers.append(DynamicLayer())295 return self._cache.update(key_states, value_states, virtual_idx, cache_kwargs)296 297 def get_seq_length(self, layer_idx: int = 0) -> int:298 return self._cache.get_seq_length(layer_idx + self._offset)299 300 301@auto_docstring302class NandiPreTrainedModel(PreTrainedModel):303 config: NandiConfig304 base_model_prefix = "model"305 supports_gradient_checkpointing = True306 _no_split_modules = ["NandiDecoderLayer"]307 _skip_keys_device_placement = ["past_key_values"]308 _supports_flash_attn = True309 _supports_sdpa = True310 _supports_flex_attn = True311 _can_compile_fullgraph = True312 _supports_attention_backend = True313 _can_record_outputs = {314 "hidden_states": NandiDecoderLayer,315 "attentions": NandiAttention,316 }317 318 def __init__(self, config: NandiConfig):319 super().__init__(config)320 321 322@auto_docstring323class NandiModel(NandiPreTrainedModel):324 def __init__(self, config: NandiConfig):325 super().__init__(config)326 self.padding_idx = config.pad_token_id327 self.vocab_size = config.vocab_size328 embedding_dim = config.embedding_rank if config.factorized_embedding else config.hidden_size329 330 self.embed_tokens = nn.Embedding(config.vocab_size, embedding_dim, self.padding_idx)331 self.embedding_proj = (332 nn.Linear(config.embedding_rank, config.hidden_size, bias=False) if config.factorized_embedding else None333 )334 self.layers = nn.ModuleList(335 [NandiDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]336 )337 self.norm = NandiRMSNorm(config.hidden_size, eps=config.rms_norm_eps)338 self.rotary_emb = NandiRotaryEmbedding(config=config)339 self.gradient_checkpointing = False340 341 self.post_init()342 343 @merge_with_config_defaults344 @capture_outputs345 @auto_docstring346 def forward(347 self,348 input_ids: torch.LongTensor | None = None,349 attention_mask: torch.Tensor | None = None,350 position_ids: torch.LongTensor | None = None,351 past_key_values: Cache | None = None,352 inputs_embeds: torch.FloatTensor | None = None,353 use_cache: bool | None = None,354 **kwargs: Unpack[TransformersKwargs],355 ) -> BaseModelOutputWithPast:356 if (input_ids is None) ^ (inputs_embeds is not None):357 raise ValueError("You must specify exactly one of input_ids or inputs_embeds")358 359 if inputs_embeds is None:360 inputs_embeds = self.embed_tokens(input_ids)361 362 if self.embedding_proj is not None:363 inputs_embeds = self.embedding_proj(inputs_embeds)364 365 repeats = self.config.layer_sharing_repeats if self.config.layer_sharing else 1366 367 if use_cache and past_key_values is None:368 # Use lazy DynamicCache (no config) so it grows to accommodate369 # num_hidden_layers * repeats virtual slots for layer-sharing.370 past_key_values = DynamicCache()371 372 if position_ids is None:373 past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0374 position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens375 position_ids = position_ids.unsqueeze(0)376 377 causal_mask = create_causal_mask(378 config=self.config,379 inputs_embeds=inputs_embeds,380 attention_mask=attention_mask,381 past_key_values=past_key_values,382 position_ids=position_ids,383 )384 385 hidden_states = inputs_embeds386 position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)387 388 for decoder_layer in self.layers[: self.config.num_hidden_layers]:389 for repeat_idx in range(repeats):390 # Each repeat gets its own virtual cache slots offset by num_hidden_layers,391 # so repeat 0 uses slots 0..N-1 and repeat 1 uses slots N..2N-1, etc.392 repeat_cache = (393 _VirtualLayerCache(past_key_values, repeat_idx * self.config.num_hidden_layers)394 if (past_key_values is not None and repeat_idx > 0)395 else past_key_values396 )397 hidden_states = decoder_layer(398 hidden_states,399 attention_mask=causal_mask,400 position_embeddings=position_embeddings,401 position_ids=position_ids,402 past_key_values=repeat_cache,403 use_cache=use_cache,404 **kwargs,405 )406 407 hidden_states = self.norm(hidden_states)408 return BaseModelOutputWithPast(409 last_hidden_state=hidden_states,410 past_key_values=past_key_values,411 )412 413 414@auto_docstring415class NandiForCausalLM(NandiPreTrainedModel, GenerationMixin):416 _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}417 _tp_plan = {"lm_head": "colwise_gather_output"}418 _pp_plan = {419 "lm_head_proj": (["hidden_states"], ["hidden_states"]),420 "lm_head": (["hidden_states"], ["logits"]),421 }422 423 def __init__(self, config):424 super().__init__(config)425 self.model = NandiModel(config)426 self.vocab_size = config.vocab_size427 428 lm_head_in_features = config.embedding_rank if config.factorized_embedding else config.hidden_size429 self.lm_head_proj = (430 nn.Linear(config.hidden_size, config.embedding_rank, bias=False) if config.factorized_embedding else None431 )432 self.lm_head = nn.Linear(lm_head_in_features, config.vocab_size, bias=False)433 434 self.post_init()435 436 @can_return_tuple437 @auto_docstring438 def forward(439 self,440 input_ids: torch.LongTensor | None = None,441 attention_mask: torch.Tensor | None = None,442 position_ids: torch.LongTensor | None = None,443 past_key_values: Cache | None = None,444 inputs_embeds: torch.FloatTensor | None = None,445 labels: torch.LongTensor | None = None,446 use_cache: bool | None = None,447 logits_to_keep: int | torch.Tensor = 0,448 **kwargs: Unpack[TransformersKwargs],449 ) -> CausalLMOutputWithPast:450 outputs: BaseModelOutputWithPast = self.model(451 input_ids=input_ids,452 attention_mask=attention_mask,453 position_ids=position_ids,454 past_key_values=past_key_values,455 inputs_embeds=inputs_embeds,456 use_cache=use_cache,457 **kwargs,458 )459 460 hidden_states = outputs.last_hidden_state461 if self.lm_head_proj is not None:462 hidden_states = self.lm_head_proj(hidden_states)463 464 slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep465 logits = self.lm_head(hidden_states[:, slice_indices, :])466 467 loss = None468 if labels is not None:469 loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)470 471 return CausalLMOutputWithPast(472 loss=loss,473 logits=logits,474 past_key_values=outputs.past_key_values,475 hidden_states=outputs.hidden_states,476 attentions=outputs.attentions,477 )478 479 480__all__ = ["NandiPreTrainedModel", "NandiModel", "NandiForCausalLM"]481 