Text Generation
Transformers
Safetensors
PyTorch
English
neollm
causal-lm
research
bf16
attention
normalization
conversational
custom_code
Instructions to use KitsuVp/NeoLLM with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use KitsuVp/NeoLLM with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="KitsuVp/NeoLLM", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("KitsuVp/NeoLLM", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use KitsuVp/NeoLLM with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "KitsuVp/NeoLLM" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "KitsuVp/NeoLLM", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/KitsuVp/NeoLLM
- SGLang
How to use KitsuVp/NeoLLM with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "KitsuVp/NeoLLM" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "KitsuVp/NeoLLM", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "KitsuVp/NeoLLM" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "KitsuVp/NeoLLM", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use KitsuVp/NeoLLM with Docker Model Runner:
docker model run hf.co/KitsuVp/NeoLLM
Update modeling_neollm.py
Browse files1 unmodified line23456781 unmodified line10111213141516171819202122232425270 unmodified lines2962972982993003013023 unmodified lines3063073083093103113124 unmodified lines317318319320321322101 unmodified lines42442542642742842943055 unmodified lines486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518114 unmodified lines6336346356366376386396406416426436446456466476486497 unmodified lines6576586596606616626631 unmodified line6656666676686696706716726736743 unmodified lines6786796806816826836846856866876883 unmodified lines6926936946956966976986997007017027037047057067077087097107117127137147151 unmodified line7177187197207217227237247257267277287297307317327337347357366 unmodified lines7437447457467477486 unmodified lines7557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298306 unmodified lines83783883984084184284324 unmodified lines86886987087187287387487587687712 unmodified lines8908918928938948958968978988999009019021 unmodified line9049059069079089099103 unmodified lines91491591691791891947 unmodified lines9679689699709719729739749759769773 unmodified lines98198298398498598698758 unmodified lines1046104710481049105010511 unmodified line"""NeoLLM Model with FANformer Integration in both Attention and FFN, Dropout Regularization,SeeDNorm (Self-Rescaled Dynamic Normalization), ResFormer Value Residual Learning,and Learnable Multipliers for enhanced scale adaptation and information flow through deep layers.Updated to include:- Fourier Analysis Network (FAN) layer for effective periodicity modeling in attention (relational space)- FAN layer in FFN for featural periodicity modeling (complementary coverage)1 unmodified line- Dropout regularization at strategic locations- ResFormer: Feature residual connections from first layer (applied before projections)- Learnable Multipliers: Frees weight matrix scale from WD-noise equilibrium for data-adaptive scaling- Full Attention only (linear attention removed)"""import mathfrom typing import Any, Callable, Optional, Union, Tupleimport torchimport torch.nn.functional as Ffrom torch import nnfrom cut_cross_entropy import linear_cross_entropyfrom transformers.activations import ACT2FNfrom transformers.generation import GenerationMixin270 unmodified linesNormalized and dynamically scaled tensor of same shape"""x_for_dynamic = F.dropout(x, p=self.dropout_input)rescale_factor = torch.tanh(torch.sum(x_for_dynamic * self.beta,dim=-1, keepdim=True))3 unmodified lines# Apply RMS normalization on ORIGINAL input (not dropped version)x_normalized = self._rms_norm(x.float())x_normalized = F.dropout(x_normalized, p=self.dropout_hidden)# Apply dynamic scalingoutput = x_normalized * dynamic_scale.float()4 unmodified linesreturn (f"dim={self.dim}, eps={self.eps}, "f"dropout_input={self.dropout_input}, dropout_hidden={self.dropout_hidden}")class NeoLLMRotaryEmbedding(nn.Module):inv_freq: torch.Tensor # fix linting for `register_buffer`101 unmodified linesResFormer feature residual connections, and Learnable Multipliers for enhancedinformation flow and scale adaptation.ResFormer enhancement: Applies learnable feature residual connections from the first layerBEFORE QKV projections: H'_fan_n = λ_1 * H_fan_1 + λ_2 * H_fan_nLearnable Multipliers placement (from "Learnable Multipliers" paper Appendix C):55 unmodified linesself.dropout = nn.Dropout(config.dropout_rate)# ResFormer: learnable feature residual parameters (initialized to 0.5)self.lambda_1 = nn.Parameter(torch.tensor(0.5)) # Weight for H_fan_1 (first layer features)self.lambda_2 = nn.Parameter(torch.tensor(0.5)) # Weight for H_fan_n (current layer features)def forward(self,hidden_states: torch.Tensor,position_embeddings: tuple[torch.Tensor, torch.Tensor],attention_mask: Optional[torch.Tensor],first_layer_fan: Optional[torch.Tensor] = None,**kwargs: Unpack[FlashAttentionKwargs],) -> tuple[torch.Tensor, Optional[torch.Tensor], torch.Tensor]:input_shape = hidden_states.shape[:-1]# Apply FANformer transformation firsthidden_states_fan = self.fan_layer(hidden_states)# ResFormer: Apply feature residual connection BEFORE projections# This ensures dimensional compatibility across all layer typesif first_layer_fan is not None:hidden_states_fan = self.lambda_1 * first_layer_fan + self.lambda_2 * hidden_states_fan# Store current FAN features for potential use as first_layer_fan in subsequent layerscurrent_layer_fan = hidden_states_fan.clone()hidden_shape = (*input_shape, -1, self.head_dim)# Use FAN-transformed features (with residual applied) for projections# Q projection with learnable row multipliersquery_states, gate = torch.chunk(self.q_proj(hidden_states_fan).view(*input_shape, -1, self.head_dim * 2), 2, dim=-1114 unmodified lineshidden = self.dropout(hidden)return self.down_proj(hidden)class NeoLLMDecoderLayer(GradientCheckpointingLayer):"""Decoder layer with standard residual connections.Arquitectura:1. Pre-norm (SeeDNorm) → LNS scaling → Self-Attention con ResFormer y Learnable Multipliers2. Standard Residual Connection (suma simple)3. GPAS activation scaling4. Pre-norm (SeeDNorm) → LNS scaling → MLP con FANformer y Learnable Multipliers5. Standard Residual Connection (suma simple)6. GPAS activation scaling"""def __init__(self, config: NeoLLMConfig, layer_idx: int):7 unmodified lines# MLP with FANformer integration and learnable multipliersself.mlp = NeoLLMMLP(config)# SeeDNorm for input and post-attention normalization (replaces RMSNorm)self.input_layernorm = SeeDNorm(config.hidden_size, eps=config.rms_norm_eps)self.post_attention_layernorm = SeeDNorm(config.hidden_size, eps=config.rms_norm_eps)1 unmodified lineself.lns_attn = LNS(layer_idx)self.lns_mlp = LNS(layer_idx)# GPAS (Gradient-Preserving Activation Scaling) - applied after residual connectionsself.gpas_attn = GPAS(config.hidden_size)self.gpas_mlp = GPAS(config.hidden_size)# ResFormer: storage for current layer's FAN featuresself.current_layer_fan = None3 unmodified linesposition_embeddings: tuple[torch.Tensor, torch.Tensor],attention_mask: Optional[torch.Tensor] = None,first_layer_fan: Optional[torch.Tensor] = None,output_attentions: Optional[bool] = False,**kwargs: Unpack[FlashAttentionKwargs],) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]:# ============================================================# Attention Block with standard residual connection# ============================================================residual = hidden_states3 unmodified lines# Apply LNS scaling after normalizationhidden_states = self.lns_attn(hidden_states)# Self Attention with ResFormer feature residual connections and learnable multipliers# We capture attn_weights here instead of ignoring themhidden_states, attn_weights, self.current_layer_fan = self.self_attn(hidden_states=hidden_states,attention_mask=attention_mask,position_embeddings=position_embeddings,first_layer_fan=first_layer_fan,**kwargs,)# Standard residual connectionhidden_states = residual + hidden_states# Apply GPAS after attention residual connectionhidden_states = self.gpas_attn(hidden_states)# ============================================================# MLP Block with standard residual connection# ============================================================residual = hidden_stateshidden_states = self.post_attention_layernorm(hidden_states)1 unmodified line# Apply LNS scaling after normalizationhidden_states = self.lns_mlp(hidden_states)# MLP now includes FAN transformation and learnable multipliers internallyhidden_states = self.mlp(hidden_states)# Standard residual connectionhidden_states = residual + hidden_states# Apply GPAS after MLP residual connectionhidden_states = self.gpas_mlp(hidden_states)outputs = (hidden_states,)if output_attentions:outputs += (attn_weights,)return outputsclass NeoLLMPreTrainedModel(PreTrainedModel):6 unmodified lines- FANLayer (Fourier Analysis Network)- SeeDNorm (Self-Rescaled Dynamic Normalization)- Learnable Multipliers (ScalarMultiplier, VectorMultiplier)"""config: NeoLLMConfigbase_model_prefix = "model"6 unmodified linesdef _init_weights(self, module):"""Initialize weights for all custom modules in NeoLLM.Strategy:- Standard layers (Linear, Embedding): handled by parent class- Custom modules: specialized initialization per component- Learnable Multipliers: initialized to 1.0 for identity transformation"""super()._init_weights(module)if isinstance(module, NeoLLMAttention):# ResFormer: initialize lambda parameters for full attention# Lambda values control the interpolation between first layer and current layer features# Starting at 0.5 provides balanced contribution from both sourcesif hasattr(module, 'lambda_1'):module.lambda_1.data.fill_(0.5)if hasattr(module, 'lambda_2'):module.lambda_2.data.fill_(0.5)elif isinstance(module, GPAS):# Initialize GPAS alpha to 0 as per paper# This starts with no activation scaling, allowing the model to learn graduallymodule.alpha.data.fill_(0.0)elif isinstance(module, FANLayer):# FANLayer initialization is handled within the class __init__# Uses normal initialization with std=0.02 for weightspasselif isinstance(module, SeeDNorm):# SeeDNorm initialization (parameters already initialized correctly in __init__):# gamma (γ) initialized to 1 (static scaling component, like RMSNorm)# beta (β) initialized to 0 (self-rescaling starts disabled)# alpha (α) initialized to 1 (dynamic modulation at full strength)passelif isinstance(module, (ScalarMultiplier, VectorMultiplier)):# Learnable Multipliers: initialize to 1.0 for identity transformation# This allows the model to start from the standard behavior and learn# scale adaptations from data without initial biasif hasattr(module, 'multiplier'):module.multiplier.data.fill_(1.0)class NeoLLMModel(NeoLLMPreTrainedModel):"""NeoLLM base model with transformer decoder architecture.Note on embeddings and weight tying: This model uses weight tying betweenembed_tokens and lm_head (shared weights). Following "Learnable Multipliers"paper analysis, we do NOT add multipliers to embeddings because:1. Weight tying creates conflicting gradient paths: multipliers would scalegradients from embedding lookup but not from lm_head projection, causingthe multiplier to receive incomplete optimization signals.2. The paper explicitly warns against multipliers in lm_head (creates shortcutsfor learning marginal token distribution), and with weight tying thisrestriction propagates to embeddings.3. Compensating mechanisms provide scale adaptation immediately after embedding:- First layer attention has multipliers in Q/O projections- FANformer transforms the representation space- SeeDNorm provides input-dependent dynamic scaling- ResFormer propagates first-layer features with learnable scaling"""def __init__(self, config: NeoLLMConfig):super().__init__(config)# Standard embedding without learnable multipliers# Due to weight tying with lm_head, multipliers would create# conflicting optimization dynamics (see class docstring)self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)# Each layer creates its own components (no shared parameters)6 unmodified linesself.rotary_emb = NeoLLMRotaryEmbedding(config=config)self.gradient_checkpointing = False# ResFormer: storage for first layer's FAN features (H_fan_1)self.first_layer_fan = None# Initialize weights and apply final processing24 unmodified linesraise ValueError("You must specify exactly one of input_ids or inputs_embeds")if inputs_embeds is None:# Standard embedding lookup without multipliers# Scale adaptation occurs in subsequent layers via:# (1) First layer attention multipliers, (2) FANformer transformation,# (3) SeeDNorm dynamic scaling, (4) ResFormer feature propagationinputs_embeds = self.embed_tokens(input_ids)if position_ids is None:12 unmodified linesall_hidden_states = () if output_hidden_states else Noneall_attentions = () if output_attentions else None# create position embeddings to be shared across the decoder layersposition_embeddings = self.rotary_emb(hidden_states, position_ids)# ResFormer: reset first_layer_fan at the start of each forward passself.first_layer_fan = Nonefor decoder_layer in self.layers[: self.config.num_hidden_layers]:if output_hidden_states:all_hidden_states = all_hidden_states + (hidden_states,)1 unmodified linehidden_states,position_embeddings=position_embeddings,attention_mask=causal_mask,first_layer_fan=self.first_layer_fan, # Pass H_fan_1 to all layersoutput_attentions=output_attentions,**kwargs,)3 unmodified linesif output_attentions:all_attentions = all_attentions + (layer_outputs[1],)# ResFormer: capture H_fan_1 from the first layerif self.first_layer_fan is None and hasattr(decoder_layer, 'current_layer_fan'):self.first_layer_fan = decoder_layer.current_layer_fan47 unmodified lines"""Causal Language Model with NeoLLM architecture.Note on LM head: Following "Learnable Multipliers" paper recommendations,the output projection (lm_head) does NOT include learnable multipliers because:1. The preceding RMSNorm (self.model.norm) already acts as column multipliers2. Adding row multipliers to lm_head can create shortcuts where the modellearns marginal token distribution without updating internal features"""_tied_weights_keys = ["lm_head.weight"]3 unmodified linesself.vocab_size = config.vocab_size# LM head without learnable multipliers (standard linear layer)# Preceding norm layer provides sufficient scale adaptationself.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)self.post_init()58 unmodified lines"ScalarMultiplier","VectorMultiplier","LinearWithMultipliers",]# Register the configuration and model for AutoClass support1 unmodified line23456789101 unmodified line1213141516171819202122232425262728293031270 unmodified lines3023033043053063073083 unmodified lines3123133143153163173184 unmodified lines323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511101 unmodified lines61361461561661761861955 unmodified lines675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717114 unmodified lines8328338348358368378388398408418428438448458468478488498507 unmodified lines8588598608618628638641 unmodified line8668678688698708718728738748758768778788798803 unmodified lines8848858868878888898908918928938948958968978988999009019029039049059069079089099109113 unmodified lines9159169179189199209219229239249259269279289299309319329339349359369371 unmodified line9399409419429439449459469479489499509519529539549559569579589599609619629639649656 unmodified lines9729739749759769779786 unmodified lines98598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110426 unmodified lines104910501051105210531054105510561057105824 unmodified lines10831084108510861087108812 unmodified lines1101110211031104110511061107110811091110111111121113111411151 unmodified line1117111811191120112111221123112411253 unmodified lines112911301131113211331134113511361137113847 unmodified lines11861187118811891190119111921193119411953 unmodified lines11991200120112021203120458 unmodified lines12631264126512661267126812691 unmodified line"""NeoLLM Model with FANformer Integration in both Attention and FFN, Dropout Regularization,SeeDNorm (Self-Rescaled Dynamic Normalization), ResFormer Value Residual Learning,Learnable Multipliers for enhanced scale adaptation and information flow through deep layers,and StackMemory for hierarchical pattern modeling.Updated to include:- Fourier Analysis Network (FAN) layer for effective periodicity modeling in attention (relational space)- FAN layer in FFN for featural periodicity modeling (complementary coverage)1 unmodified line- Dropout regularization at strategic locations- ResFormer: Feature residual connections from first layer (applied before projections)- Learnable Multipliers: Frees weight matrix scale from WD-noise equilibrium for data-adaptive scaling- StackMemory: Differentiable hidden state stack for modeling Chomsky hierarchy grammars- Full Attention only (linear attention removed)"""import mathfrom typing import Any, Callable, Optional, Union, Tuple, Listimport torchimport torch.nn.functional as Ffrom torch import nnfrom cut_cross_entropy import linear_cross_entropyimport torch.nn.functional as Ffrom torch.utils.checkpoint import checkpointfrom typing import Optional, Tuplefrom transformers.activations import ACT2FNfrom transformers.generation import GenerationMixin270 unmodified linesNormalized and dynamically scaled tensor of same shape"""x_for_dynamic = F.dropout(x, p=self.dropout_input, training=self.training)rescale_factor = torch.tanh(torch.sum(x_for_dynamic * self.beta,dim=-1, keepdim=True))3 unmodified lines# Apply RMS normalization on ORIGINAL input (not dropped version)x_normalized = self._rms_norm(x.float())x_normalized = F.dropout(x_normalized, p=self.dropout_hidden, training=self.training)# Apply dynamic scalingoutput = x_normalized * dynamic_scale.float()4 unmodified linesreturn (f"dim={self.dim}, eps={self.eps}, "f"dropout_input={self.dropout_input}, dropout_hidden={self.dropout_hidden}")# ==================== STACK MEMORY MODULE ====================class StackMemory(nn.Module):"""Differentiable Hidden State Stack for modeling Chomsky hierarchy grammars.From "Improving Formal Reasoning of Transformer with State Stack":Implements a multi-head differentiable stack with soft push, pop, and no-op operations.Each head maintains its own stack and mask, which are updated based on learned actionprobabilities. Global reading is performed via query-over-stack attention.This module is inserted between Transformer layers to augment information flow withstack-like memory operations, enabling the model to better capture hierarchical andrecursive patterns characteristic of regular expressions and context-free grammars.Note: StackMemory uses standard nn.Linear to maintain architecturalindependence and avoid introducing additional complexity in the memory operations.Args:config: Model configuration containing stack-related hyperparameters"""def __init__(self, config: NeoLLMConfig):super().__init__()self.config = configself.num_stack_heads = getattr(config, 'num_stack_heads', 4)self.stack_slots = getattr(config, 'stack_slots', 24)self.stack_d_model = getattr(config, 'stack_d_model', 128)self.head_dim = self.stack_d_model // self.num_stack_heads# Dimension reduction projections for efficiency# Uses standard nn.Linearself.down_proj = nn.Linear(config.hidden_size, self.stack_d_model, bias=False)self.up_proj = nn.Linear(self.stack_d_model, config.hidden_size, bias=False)# Action prediction: generates push/pop/no-op probabilities for each headself.action_head = nn.Linear(self.stack_d_model, 3 * self.num_stack_heads, bias=True)# Query projection for global reading (one per head)self.gate_proj = nn.Linear(self.head_dim, 1, bias=False)# Residual weight for gating stack contributionself.res_weight = nn.Parameter(torch.ones(1))def _vectorized_update(self,stack: torch.Tensor,mask: torch.Tensor,actions: torch.Tensor,k_values: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:"""Vectorized stack update mechanism applying soft push/pop/no-op operations.Implements the differentiable stack operations from the paper:- Push: shifts all elements down and places k_values at top- Pop: shifts all elements up and removes top- No-op: maintains current stack stateArgs:stack: Current stack state [batch, seq, num_heads, stack_slots, head_dim]mask: Current stack mask [batch, seq, num_heads, stack_slots]actions: Action probabilities [batch, seq, num_heads, 3] (push/pop/no-op)k_values: New values to push [batch, seq, num_heads, head_dim]Returns:Tuple of (updated_stack, updated_mask)"""batch_size, seq_len = actions.shape[:2]# Expand stack and mask along sequence dimension for parallel processingstack = stack.unsqueeze(1).expand(-1, seq_len, -1, -1, -1)mask = mask.unsqueeze(1).expand(-1, seq_len, -1, -1)# Generate pushed stack: new value at top, shift others downpush_stack = torch.cat([k_values.unsqueeze(3), # New value at position 0stack[:, :, :, :-1] # Shift existing elements down], dim=3)push_mask = torch.cat([torch.ones_like(mask[:, :, :, :1]),mask[:, :, :, :-1]], dim=3)# Generate popped stack: shift all up, zero at bottompop_stack = torch.cat([stack[:, :, :, 1:],torch.zeros_like(stack[:, :, :, :1])], dim=3)pop_mask = torch.cat([mask[:, :, :, 1:],torch.zeros_like(mask[:, :, :, :1])], dim=3)# Combine operations weighted by action probabilitiesaction_weights = actions.unsqueeze(-1).unsqueeze(-1) # [batch, seq, heads, 3, 1, 1]stacks = torch.stack([push_stack, pop_stack, stack], dim=3) # [batch, seq, heads, 3, slots, dim]masks = torch.stack([push_mask, pop_mask, mask], dim=3) # [batch, seq, heads, 3, slots]# Weighted combination of all operationsnew_stack = (stacks * action_weights).sum(dim=3)new_mask = (masks * action_weights.squeeze(-1)).sum(dim=3)return new_stack, new_maskdef forward(self,hidden_states: torch.Tensor,stack: Optional[torch.Tensor] = None,mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:"""Apply differentiable stack operations to hidden states.Args:hidden_states: Input hidden states [batch, seq, hidden_size]stack: Previous stack state [batch, num_heads, stack_slots, head_dim] or Nonemask: Previous stack mask [batch, num_heads, stack_slots] or NoneReturns:Tuple of (output_hidden_states, updated_stack, updated_mask)"""batch_size, seq_len, _ = hidden_states.shapedevice = hidden_states.device# Initialize stack and mask if not providedif stack is None:stack = torch.zeros(batch_size, self.num_stack_heads, self.stack_slots, self.head_dim,device=device, dtype=hidden_states.dtype)if mask is None:mask = torch.zeros(batch_size, self.num_stack_heads, self.stack_slots,device=device, dtype=hidden_states.dtype)# Project to lower dimension for efficiencynew_hidden_states = self.down_proj(hidden_states)# Generate action probabilities: [batch, seq, num_heads, 3]action_logits = self.action_head(new_hidden_states) / math.sqrt(self.head_dim)actions = F.softmax(action_logits.view(batch_size, seq_len, self.num_stack_heads, 3),dim=-1)# Prepare values to push (split into heads)k_values = new_hidden_states.view(batch_size, seq_len, self.num_stack_heads, self.head_dim)# Update stack and mask using vectorized operationsnew_stack, new_mask = self._vectorized_update(stack, mask, actions, k_values)# Global reading via query-over-stack attention# Apply mask before attention computationmasked_stack = new_stack * new_mask.unsqueeze(-1)# Compute attention scores for each headgate_scores = self.gate_proj(masked_stack).squeeze(-1) # [batch, seq, heads, slots]# Mask out invalid positions (add large negative value)gate_scores = gate_scores + (1 - new_mask) * -1e9# Softmax to get attention weightsgate_weights = F.softmax(gate_scores, dim=-1)# Weighted sum over stack slotsmemory_output = (new_stack * gate_weights.unsqueeze(-1)).sum(dim=3)memory_output = memory_output.view(batch_size, seq_len, -1)# Project back to original dimensionmemory_output = self.up_proj(memory_output)# Gated residual connectionoutput = memory_output * self.res_weight + hidden_states# Return output and updated stack state (use last timestep's state)return output, new_stack[:, -1], new_mask[:, -1]# ==================== ROTARY EMBEDDING ====================class NeoLLMRotaryEmbedding(nn.Module):inv_freq: torch.Tensor # fix linting for `register_buffer`101 unmodified linesResFormer feature residual connections, and Learnable Multipliers for enhancedinformation flow and scale adaptation.ResFormer enhancement: Applies learnable feature residual connections from first layerBEFORE QKV projections: H'_fan_n = λ_1 * H_fan_1 + λ_2 * H_fan_nLearnable Multipliers placement (from "Learnable Multipliers" paper Appendix C):55 unmodified linesself.dropout = nn.Dropout(config.dropout_rate)# ResFormer: learnable feature residual parameters (initialized to 0.5)self.lambda_1 = nn.Parameter(torch.tensor(0.5)) # Weight for H_fan_1self.lambda_2 = nn.Parameter(torch.tensor(0.5)) # Weight for H_fan_ndef forward(self,hidden_states: torch.Tensor,position_embeddings: tuple[torch.Tensor, torch.Tensor],attention_mask: Optional[torch.Tensor] = None,first_layer_fan: Optional[torch.Tensor] = None,**kwargs: Unpack[FlashAttentionKwargs],) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor]]:"""Forward pass with ResFormer feature residual connections.Args:hidden_states: Current layer input [batch, seq, hidden_size]position_embeddings: Tuple of (cos, sin) for RoPEattention_mask: Causal attention maskfirst_layer_fan: First layer FAN features (for ResFormer)Returns:Tuple of (attn_output, attn_weights, current_layer_fan)"""input_shape = hidden_states.shape[:-1]# Apply FANformer transformationhidden_states_fan = self.fan_layer(hidden_states)# ResFormer: Apply feature residual connection BEFORE projectionsif first_layer_fan is not None:hidden_states_fan = self.lambda_1 * first_layer_fan + self.lambda_2 * hidden_states_fan# Store current FAN features for ResFormercurrent_layer_fan = hidden_states_fan.clone()hidden_shape = (*input_shape, -1, self.head_dim)# Q projection with learnable row multipliersquery_states, gate = torch.chunk(self.q_proj(hidden_states_fan).view(*input_shape, -1, self.head_dim * 2), 2, dim=-1114 unmodified lineshidden = self.dropout(hidden)return self.down_proj(hidden)class NeoLLMDecoderLayer(GradientCheckpointingLayer):"""Decoder layer with standard residual connections and optional StackMemory.Architecture:1. Pre-norm (SeeDNorm) → LNS scaling → Self-Attention with ResFormer and Learnable Multipliers2. Standard Residual Connection3. GPAS activation scaling4. Pre-norm (SeeDNorm) → LNS scaling → MLP with FANformer and Learnable Multipliers5. Standard Residual Connection6. GPAS activation scaling7. Optional: StackMemory module"""def __init__(self, config: NeoLLMConfig, layer_idx: int):7 unmodified lines# MLP with FANformer integration and learnable multipliersself.mlp = NeoLLMMLP(config)# SeeDNorm for input and post-attention normalizationself.input_layernorm = SeeDNorm(config.hidden_size, eps=config.rms_norm_eps)self.post_attention_layernorm = SeeDNorm(config.hidden_size, eps=config.rms_norm_eps)1 unmodified lineself.lns_attn = LNS(layer_idx)self.lns_mlp = LNS(layer_idx)# GPAS (Gradient-Preserving Activation Scaling)self.gpas_attn = GPAS(config.hidden_size)self.gpas_mlp = GPAS(config.hidden_size)# StackMemory: Differentiable hidden state stackself.use_stack = getattr(config, 'use_stack', False)if self.use_stack:self.stack_memory = StackMemory(config)# ResFormer: storage for current layer's FAN featuresself.current_layer_fan = None3 unmodified linesposition_embeddings: tuple[torch.Tensor, torch.Tensor],attention_mask: Optional[torch.Tensor] = None,first_layer_fan: Optional[torch.Tensor] = None,stack_state: Optional[torch.Tensor] = None,stack_mask: Optional[torch.Tensor] = None,output_attentions: Optional[bool] = False,**kwargs: Unpack[FlashAttentionKwargs],) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor], Optional[torch.Tensor], Optional[torch.Tensor]]:"""Forward pass with ResFormer and optional StackMemory.Args:hidden_states: Current layer input [batch, seq, hidden_size]position_embeddings: Tuple of (cos, sin) for RoPEattention_mask: Causal attention maskfirst_layer_fan: First layer FAN features (for ResFormer)stack_state: StackMemory state (optional)stack_mask: StackMemory mask (optional)output_attentions: Whether to return attention weightsReturns:Tuple of (hidden_states, attn_weights, stack_state, stack_mask)"""# ============================================================# Attention Block with Standard Residual Connection# ============================================================residual = hidden_states3 unmodified lines# Apply LNS scaling after normalizationhidden_states = self.lns_attn(hidden_states)# Self Attention with ResFormerattn_output, attn_weights, self.current_layer_fan = self.self_attn(hidden_states=hidden_states,position_embeddings=position_embeddings,attention_mask=attention_mask,first_layer_fan=first_layer_fan,**kwargs,)# Standard Residual Connectionhidden_states = residual + attn_output# Apply GPAS after residual connectionhidden_states = self.gpas_attn(hidden_states)# ============================================================# MLP Block with Standard Residual Connection# ============================================================residual = hidden_stateshidden_states = self.post_attention_layernorm(hidden_states)1 unmodified line# Apply LNS scaling after normalizationhidden_states = self.lns_mlp(hidden_states)# MLP with FANformermlp_output = self.mlp(hidden_states)# Standard Residual Connectionhidden_states = residual + mlp_output# Apply GPAS after residual connectionhidden_states = self.gpas_mlp(hidden_states)# ============================================================# Stack Memory Module# ============================================================if self.use_stack:hidden_states, stack_state, stack_mask = self.stack_memory(hidden_states, stack_state, stack_mask)if self.use_stack:return (hidden_states, attn_weights, stack_state, stack_mask)else:return (hidden_states, attn_weights, None, None)class NeoLLMPreTrainedModel(PreTrainedModel):6 unmodified lines- FANLayer (Fourier Analysis Network)- SeeDNorm (Self-Rescaled Dynamic Normalization)- Learnable Multipliers (ScalarMultiplier, VectorMultiplier)- StackMemory (Differentiable Hidden State Stack)"""config: NeoLLMConfigbase_model_prefix = "model"6 unmodified linesdef _init_weights(self, module):"""Initialize weights for all custom modules in NeoLLM."""super()._init_weights(module)if isinstance(module, NeoLLMAttention):if hasattr(module, 'lambda_1'):module.lambda_1.data.fill_(0.5)if hasattr(module, 'lambda_2'):module.lambda_2.data.fill_(0.5)elif isinstance(module, GPAS):module.alpha.data.fill_(0.0)elif isinstance(module, (ScalarMultiplier, VectorMultiplier)):if hasattr(module, 'multiplier'):module.multiplier.data.fill_(1.0)elif isinstance(module, StackMemory):std = self.config.initializer_range if hasattr(self.config, 'initializer_range') else 0.02if hasattr(module, 'down_proj'):module.down_proj.weight.data.normal_(mean=0.0, std=std)if hasattr(module, 'up_proj'):module.up_proj.weight.data.normal_(mean=0.0, std=std)if hasattr(module, 'action_head'):module.action_head.weight.data.normal_(mean=0.0, std=std)if module.action_head.bias is not None:module.action_head.bias.data.zero_()if hasattr(module, 'gate_proj'):module.gate_proj.weight.data.normal_(mean=0.0, std=std)if hasattr(module, 'res_weight'):module.res_weight.data.fill_(1.0)class NeoLLMModel(NeoLLMPreTrainedModel):"""NeoLLM base model with transformer decoder architecture.Uses ResFormer for first-layer feature propagation with standard residual connectionsand optional StackMemory for hierarchical pattern modeling.Note on embeddings and weight tying: This model uses weight tying betweenembed_tokens and lm_head (shared weights). Following "Learnable Multipliers"paper analysis, we do NOT add multipliers to embeddings because:1. Weight tying creates conflicting gradient paths2. The paper explicitly warns against multipliers in lm_head3. Compensating mechanisms provide scale adaptation immediately after embedding"""def __init__(self, config: NeoLLMConfig):super().__init__(config)# Standard embedding without learnable multipliersself.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)# Each layer creates its own components (no shared parameters)6 unmodified linesself.rotary_emb = NeoLLMRotaryEmbedding(config=config)self.gradient_checkpointing = False# Configurationself.use_stack = getattr(config, 'use_stack', False)# ResFormer: storage for first layer's FAN featuresself.first_layer_fan = None# Initialize weights and apply final processing24 unmodified linesraise 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 position_ids is None:12 unmodified linesall_hidden_states = () if output_hidden_states else Noneall_attentions = () if output_attentions else None# Create position embeddings to be shared across the decoder layersposition_embeddings = self.rotary_emb(hidden_states, position_ids)# ResFormer with first-layer feature propagationself.first_layer_fan = Nonestack_state = Nonestack_mask = Nonefor decoder_layer in self.layers:if output_hidden_states:all_hidden_states = all_hidden_states + (hidden_states,)1 unmodified linehidden_states,position_embeddings=position_embeddings,attention_mask=causal_mask,first_layer_fan=self.first_layer_fan,stack_state=stack_state,stack_mask=stack_mask,output_attentions=output_attentions,**kwargs,)3 unmodified linesif output_attentions:all_attentions = all_attentions + (layer_outputs[1],)if self.use_stack:stack_state = layer_outputs[2]stack_mask = layer_outputs[3]# ResFormer: capture H_fan_1 from the first layerif self.first_layer_fan is None and hasattr(decoder_layer, 'current_layer_fan'):self.first_layer_fan = decoder_layer.current_layer_fan47 unmodified lines"""Causal Language Model with NeoLLM architecture.Supports ResFormer with standard residuals and optional StackMemory.Note on LM head: Following "Learnable Multipliers" paper recommendations,the output projection (lm_head) does NOT include learnable multipliers."""_tied_weights_keys = ["lm_head.weight"]3 unmodified linesself.vocab_size = config.vocab_size# LM head without learnable multipliers (standard linear layer)self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)self.post_init()58 unmodified lines"ScalarMultiplier","VectorMultiplier","LinearWithMultipliers","StackMemory",]# Register the configuration and model for AutoClass support
modeling_neollm.py+313-95