Nemotron-Labs-Audex-2B / checkpoint_folder_full /modeling_nemotron_dense.py
Arsh9210's picture
Added checkpoint_folder_full/modeling_nemotron_dense.py
9be9be6 verified
Raw
History Blame
14 kB
"""HuggingFace custom modeling for Nemotron-Dense (Cosmos 2B dense) checkpoints.
Loaded via `AutoModelForCausalLM.from_pretrained(..., trust_remote_code=True)`
using the `auto_map` field in `config.json`. RMSNorm + squared_relu MLP + GQA.
Uses transformers >=4.38 DynamicCache.update() API.
NemotronDenseConfig is a standalone PretrainedConfig (not a NemotronConfig
subclass) for version stability; recent transformers versions migrated
`rope_theta` into a `rope_parameters` dict on NemotronConfig, which breaks
direct attribute access. We follow the modern convention and use
`rope_parameters` exclusively; both the HF modeling code below and the vLLM
plugin read RoPE settings from this dict.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PretrainedConfig, PreTrainedModel
from transformers.activations import ACT2FN
from transformers.cache_utils import DynamicCache
from transformers.generation import GenerationMixin
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
class NemotronDenseConfig(PretrainedConfig):
model_type = "nemotron_dense"
def __init__(
self,
vocab_size=131072,
hidden_size=2048,
intermediate_size=9216,
num_hidden_layers=28,
num_attention_heads=16,
head_dim=128,
num_key_value_heads=8,
hidden_act="relu2",
max_position_embeddings=131072,
norm_eps=1e-5,
rope_parameters=None,
tie_word_embeddings=False,
**kwargs,
):
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.head_dim = head_dim
self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act
self.max_position_embeddings = max_position_embeddings
self.norm_eps = norm_eps
self.rope_parameters = rope_parameters or {
"rope_theta": 100000000.0,
"partial_rotary_factor": 1.0,
}
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
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)
class NemotronDenseRMSNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-5):
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states):
return F.rms_norm(hidden_states, self.weight.shape, self.weight, self.variance_epsilon)
class NemotronDenseRotaryEmbedding(nn.Module):
def __init__(self, dim, max_position_embeddings=131072, base=100000000.0, device=None):
super().__init__()
self.dim = dim
self.max_position_embeddings = max_position_embeddings
self.base = base
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
self.register_buffer("inv_freq", inv_freq, persistent=False)
def forward(self, x, position_ids):
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
position_ids_expanded = position_ids[:, None, :].float()
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
emb = torch.cat((freqs, freqs), dim=-1)
emb = emb.unsqueeze(1)
cos = emb.cos()
sin = emb.sin()
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
def rotate_half(x):
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None):
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
class NemotronDenseMLP(nn.Module):
def __init__(self, config):
super().__init__()
self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
self.act_fn = ACT2FN[config.hidden_act]
def forward(self, x):
return self.down_proj(self.act_fn(self.up_proj(x)))
class NemotronDenseAttention(nn.Module):
def __init__(self, config, layer_idx=None):
super().__init__()
self.layer_idx = layer_idx
self.hidden_size = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = getattr(config, "head_dim", None) or self.hidden_size // self.num_heads
self.num_key_value_heads = config.num_key_value_heads
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
self.q_proj = nn.Linear(self.hidden_size, self.num_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_heads * self.head_dim, self.hidden_size, bias=False)
self.rotary_emb = NemotronDenseRotaryEmbedding(
self.head_dim,
max_position_embeddings=config.max_position_embeddings,
base=config.rope_parameters["rope_theta"],
)
def forward(self, hidden_states, attention_mask=None, position_ids=None, past_key_values=None, use_cache=False, **kwargs):
bsz, q_len, _ = hidden_states.size()
query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
past_len = past_key_values.get_seq_length(self.layer_idx) if past_key_values is not None else 0
if position_ids is None:
position_ids = torch.arange(past_len, past_len + q_len, dtype=torch.long, device=hidden_states.device).unsqueeze(0)
cos, sin = self.rotary_emb(value_states, position_ids)
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)
kv_seq_len = key_states.shape[-2]
key_states = repeat_kv(key_states, self.num_key_value_groups)
value_states = repeat_kv(value_states, self.num_key_value_groups)
if attention_mask is not None:
if attention_mask.dim() == 2:
attention_mask = attention_mask[:, None, None, :kv_seq_len].to(torch.bool)
if q_len > 1:
causal = torch.tril(
torch.ones(q_len, kv_seq_len, dtype=torch.bool, device=hidden_states.device),
diagonal=kv_seq_len - q_len,
)
attention_mask = attention_mask & causal[None, None, :, :]
else:
attention_mask = attention_mask[:, :, :, :kv_seq_len]
is_causal = attention_mask is None and q_len > 1
attn_output = torch.nn.functional.scaled_dot_product_attention(
query_states, key_states, value_states,
attn_mask=attention_mask, dropout_p=0.0, is_causal=is_causal,
)
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
attn_output = self.o_proj(attn_output)
return attn_output, None
class NemotronDenseDecoderLayer(nn.Module):
def __init__(self, config, layer_idx=None):
super().__init__()
self.self_attn = NemotronDenseAttention(config, layer_idx=layer_idx)
self.mlp = NemotronDenseMLP(config)
self.input_layernorm = NemotronDenseRMSNorm(config.hidden_size, eps=config.norm_eps)
self.post_attention_layernorm = NemotronDenseRMSNorm(config.hidden_size, eps=config.norm_eps)
def forward(self, hidden_states, attention_mask=None, position_ids=None, past_key_values=None, use_cache=False, **kwargs):
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,
)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states
return hidden_states
class NemotronDenseModel(PreTrainedModel):
config_class = NemotronDenseConfig
base_model_prefix = "model"
def __init__(self, config: NemotronDenseConfig):
super().__init__(config)
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
self.layers = nn.ModuleList(
[NemotronDenseDecoderLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)]
)
self.norm = NemotronDenseRMSNorm(config.hidden_size, eps=config.norm_eps)
self.post_init()
def _init_weights(self, module):
if isinstance(module, NemotronDenseRotaryEmbedding):
inv_freq = 1.0 / (module.base ** (torch.arange(0, module.dim, 2, dtype=torch.int64).float() / module.dim))
try:
import transformers.initialization as init
init.copy_(module.inv_freq, inv_freq)
except (ImportError, AttributeError):
module.inv_freq.copy_(inv_freq)
def get_input_embeddings(self):
return self.embed_tokens
def set_input_embeddings(self, new_embeddings):
self.embed_tokens = new_embeddings
def forward(self, input_ids=None, attention_mask=None, position_ids=None, past_key_values=None, use_cache=None, return_dict=None, **kwargs):
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if use_cache and past_key_values is None:
past_key_values = DynamicCache()
hidden_states = self.embed_tokens(input_ids)
for decoder_layer in self.layers:
hidden_states = decoder_layer(
hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
)
hidden_states = self.norm(hidden_states)
if not return_dict:
return tuple(v for v in [hidden_states, past_key_values] if v is not None)
return BaseModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=past_key_values,
)
class NemotronDenseForCausalLM(PreTrainedModel, GenerationMixin):
config_class = NemotronDenseConfig
base_model_prefix = "model"
def __init__(self, config: NemotronDenseConfig):
super().__init__(config)
self.model = NemotronDenseModel(config)
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.post_init()
def forward(self, input_ids=None, attention_mask=None, position_ids=None, past_key_values=None, labels=None, use_cache=None, return_dict=None, **kwargs):
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
return_dict=return_dict,
**kwargs,
)
hidden_states = outputs[0]
logits = self.lm_head(hidden_states)
loss = None
if labels is not None:
shift_logits = logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
loss_fct = nn.CrossEntropyLoss()
loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
if not return_dict:
output = (logits,) + outputs[1:]
return ((loss,) + output) if loss is not None else output
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
)
def get_input_embeddings(self):
return self.model.get_input_embeddings()
def set_input_embeddings(self, new_embeddings):
return self.model.set_input_embeddings(new_embeddings)
def get_output_embeddings(self):
return self.lm_head
def set_output_embeddings(self, new_embeddings):
self.lm_head = new_embeddings
def get_decoder(self):
return self.model
def set_decoder(self, decoder):
self.model = decoder
# `prepare_inputs_for_generation` intentionally not overridden:
# transformers.GenerationMixin's default already handles next_sequence_length,
# inputs_embeds first-iteration injection, left-padded position_ids, compilable
# caches, and past_key_values forwarding. Inheriting it gets us all of those
# correctly without us having to keep our override in sync with HF.