KitsuVp commited on
Commit
bc229ba
·
verified ·
1 Parent(s): 7edd49e

Update modeling_neollm.py

Browse files
Files changed (1) hide show
  1. modeling_neollm.py +245 -3
modeling_neollm.py CHANGED
@@ -6,8 +6,9 @@ Gated Attention (Qiu et al., 2025) combined with Affine-Scaled Attention
6
  (Bae et al., 2026), an optional Leviathan continuous token embedding
7
  generator, an optional Leviathan-JTok-M token-indexed modulation module,
8
  optional Spelling Bee Embeddings (Rabe et al., 2026), optional Context
9
- Re-Positioning (Li et al., 2026), and optional REPO-GRAPE contextual group
10
- positioning (Li et al., 2026 + Zhang et al., 2026).
 
11
 
12
  Attention stack (orthogonal, all active simultaneously when enabled):
13
  1. Gated Attention (use_gated_attention implicit via q_proj gate chunk):
@@ -58,6 +59,8 @@ References:
58
  Models with Context Re-Positioning." arXiv:2512.14391.
59
  GRAPE: Zhang et al. (2026). "Group Representational Position Encoding."
60
  arXiv:2512.07805 / ICLR 2026.
 
 
61
  """
62
 
63
  import math
@@ -80,7 +83,7 @@ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_u
80
  from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
81
  from transformers.processing_utils import Unpack
82
  from transformers.utils import TransformersKwargs, logging
83
- from .configuration_neollm import NeoLLMConfig
84
 
85
  from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
86
  torch._dynamo.config.capture_scalar_outputs = True
@@ -1493,6 +1496,156 @@ class FANLayer(nn.Module):
1493
  return torch.cat([cos_p, sin_p, g], dim=-1)
1494
 
1495
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1496
  class LNS(nn.Module):
1497
  """
1498
  LayerNorm Scaling: applies 1/√ℓ to suppress variance growth with depth.
@@ -4496,6 +4649,13 @@ class NeoLLMDecoderLayer(GradientCheckpointingLayer):
4496
  self.gpas_mlp = GPAS(config.hidden_size)
4497
  self.current_layer_fan = None
4498
 
 
 
 
 
 
 
 
4499
  if self.use_jtokm:
4500
  self.jtokm = LeviathanJTokM(config, layer_idx)
4501
  else:
@@ -4579,6 +4739,29 @@ class NeoLLMDecoderLayer(GradientCheckpointingLayer):
4579
  self.laurel_lr_A_mlp = None
4580
  self.laurel_lr_B_mlp = None
4581
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4582
  def _attn_res(
4583
  self,
4584
  sources: list,
@@ -5254,6 +5437,22 @@ class NeoLLMPreTrainedModel(PreTrainedModel):
5254
  module.scaler.data.fill_(1.0)
5255
  # router: parent handles via normal init
5256
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5257
  elif isinstance(module, NeoLLMDecoderLayer):
5258
  # AttnRes pseudo-queries: MUST be initialized to zero.
5259
  # Zero initialization ensures uniform attention weights at step 0
@@ -5333,6 +5532,26 @@ class NeoLLMModel(NeoLLMPreTrainedModel):
5333
  self.gradient_checkpointing = False
5334
  self.first_layer_fan = None if getattr(config, "use_fan_residual", True) else False
5335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5336
  self.post_init()
5337
 
5338
  def get_input_embeddings(self):
@@ -5475,6 +5694,23 @@ class NeoLLMModel(NeoLLMPreTrainedModel):
5475
  all_attentions = () if output_attentions else None
5476
  all_aux_stats = []
5477
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5478
  position_embeddings = self.rotary_emb(hidden_states, position_ids)
5479
  self.first_layer_fan = None if getattr(self.config, "use_fan_residual", True) else False
5480
 
@@ -5551,6 +5787,11 @@ class NeoLLMModel(NeoLLMPreTrainedModel):
5551
  layer_analysis.layer_idx = layer_idx
5552
  analysis_state.layers.append(layer_analysis)
5553
 
 
 
 
 
 
5554
  layer_outputs = decoder_layer(
5555
  hidden_states,
5556
  position_embeddings=position_embeddings,
@@ -5889,6 +6130,7 @@ __all__ = [
5889
  "LeviathanGenerator",
5890
  "LeviathanJTokM",
5891
  "SpellingBeeEmbedding",
 
5892
  "FANLayer",
5893
  "SeeDNorm",
5894
  "ScalarMultiplier",
 
6
  (Bae et al., 2026), an optional Leviathan continuous token embedding
7
  generator, an optional Leviathan-JTok-M token-indexed modulation module,
8
  optional Spelling Bee Embeddings (Rabe et al., 2026), optional Context
9
+ Re-Positioning (Li et al., 2026), optional REPO-GRAPE contextual group
10
+ positioning (Li et al., 2026 + Zhang et al., 2026), and optional StackMemory
11
+ (Zhang et al., NeurIPS 2025).
12
 
13
  Attention stack (orthogonal, all active simultaneously when enabled):
14
  1. Gated Attention (use_gated_attention implicit via q_proj gate chunk):
 
59
  Models with Context Re-Positioning." arXiv:2512.14391.
60
  GRAPE: Zhang et al. (2026). "Group Representational Position Encoding."
61
  arXiv:2512.07805 / ICLR 2026.
62
+ StackMemory / STACKTRANS: Zhang et al. (2025). "Recursive Transformer:
63
+ Boosting Reasoning Ability with State Stack." NeurIPS 2025.
64
  """
65
 
66
  import math
 
83
  from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
84
  from transformers.processing_utils import Unpack
85
  from transformers.utils import TransformersKwargs, logging
86
+ from configuration_neollm import NeoLLMConfig
87
 
88
  from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
89
  torch._dynamo.config.capture_scalar_outputs = True
 
1496
  return torch.cat([cos_p, sin_p, g], dim=-1)
1497
 
1498
 
1499
+ class StackMemory(nn.Module):
1500
+ """
1501
+ Differentiable hidden-state stack used by STACKTRANS.
1502
+
1503
+ This implementation follows the released StackTrans source operator:
1504
+ hidden states are first projected down to a low-rank stack space, split
1505
+ into multiple memory heads, updated by soft push/pop/no-op probabilities,
1506
+ read through query-over-stack attention, projected back to the model
1507
+ dimension, and added residually to the input stream.
1508
+
1509
+ Shapes:
1510
+ hidden_states: [B, S, D]
1511
+ stack: [B, H, K, d_s/H]
1512
+ mask: [B, H, K]
1513
+
1514
+ where ``H = num_mem_heads``, ``K = stack_slots``, and
1515
+ ``d_s = stack_d_model``.
1516
+ """
1517
+
1518
+ def __init__(self, config: "NeoLLMConfig"):
1519
+ super().__init__()
1520
+ self.config = config
1521
+ self.num_mem_heads = config.num_mem_heads
1522
+ self.stack_slots = config.stack_slots
1523
+
1524
+ self.head_dim = config.stack_d_model // self.num_mem_heads
1525
+
1526
+ self.down_proj = nn.Linear(config.hidden_size, config.stack_d_model)
1527
+ self.up_proj = nn.Linear(config.stack_d_model, config.hidden_size)
1528
+ self.action_head = nn.Linear(config.stack_d_model, 3 * self.num_mem_heads)
1529
+ self.gate_proj = nn.Linear(self.head_dim, 1)
1530
+ self.res_weight = nn.Parameter(torch.ones(1))
1531
+
1532
+ self.cache_size = getattr(config, "stack_memory_cache_size", 2048)
1533
+ self.cache_position = 0
1534
+ self.enable_cache = False
1535
+
1536
+ def reset_cache(self):
1537
+ self.cache_position = 0
1538
+
1539
+ def _vectorized_update(self, stack, mask, actions, k_values):
1540
+ batch_size, seq_len = actions.shape[:2]
1541
+
1542
+ stack = stack.unsqueeze(1).expand(-1, seq_len, -1, -1, -1)
1543
+ mask = mask.unsqueeze(1).expand(-1, seq_len, -1, -1)
1544
+
1545
+ push_stack = torch.cat([
1546
+ k_values.unsqueeze(3),
1547
+ stack[:, :, :, :-1]
1548
+ ], dim=3)
1549
+ push_mask = torch.cat([
1550
+ torch.ones_like(mask[:, :, :, :1]),
1551
+ mask[:, :, :, :-1]
1552
+ ], dim=3)
1553
+
1554
+ pop_stack = torch.cat([
1555
+ stack[:, :, :, 1:],
1556
+ torch.zeros_like(stack[:, :, :, :1])
1557
+ ], dim=3)
1558
+ pop_mask = torch.cat([
1559
+ mask[:, :, :, 1:],
1560
+ torch.zeros_like(mask[:, :, :, :1])
1561
+ ], dim=3)
1562
+
1563
+ action_weights = actions.unsqueeze(-1).unsqueeze(-1)
1564
+ stacks = torch.stack([push_stack, pop_stack, stack], dim=3)
1565
+ masks = torch.stack([push_mask, pop_mask, mask], dim=3)
1566
+
1567
+ new_stack = (stacks * action_weights).sum(dim=3)
1568
+ new_mask = (masks * action_weights.squeeze(-1)).sum(dim=3)
1569
+
1570
+ return new_stack, new_mask
1571
+
1572
+ def forward(self, hidden_states, stack, mask):
1573
+ batch_size, seq_len, _ = hidden_states.shape
1574
+ new_hidden_states = self.down_proj(hidden_states)
1575
+
1576
+ action_logits = self.action_head(new_hidden_states) / math.sqrt(self.head_dim)
1577
+ actions = F.softmax(
1578
+ action_logits.view(batch_size, seq_len, self.num_mem_heads, 3),
1579
+ dim=-1
1580
+ )
1581
+
1582
+ k_values = new_hidden_states.view(
1583
+ batch_size, seq_len, self.num_mem_heads, self.head_dim
1584
+ )
1585
+
1586
+ new_stack, new_mask = self._vectorized_update(stack, mask, actions, k_values)
1587
+
1588
+ gate_scores = self.gate_proj(new_stack).squeeze(-1)
1589
+ gate_weights = F.softmax(gate_scores + (1 - new_mask) * -80.0, dim=-1)
1590
+
1591
+ memory_output = (new_stack * gate_weights.unsqueeze(-1)).sum(dim=3)
1592
+ memory_output = memory_output.view(batch_size, seq_len, -1)
1593
+
1594
+ memory_output = self.up_proj(memory_output)
1595
+
1596
+ output = memory_output * self.res_weight + hidden_states
1597
+
1598
+ if self.training and self.enable_cache:
1599
+ self._update_cache(k_values.detach(), actions.detach())
1600
+
1601
+ return output, new_stack[:, -1], new_mask[:, -1]
1602
+
1603
+ def _update_cache(self, k_values, actions):
1604
+ seq_len = k_values.shape[1]
1605
+ if self.cache_position + seq_len <= self.cache_size:
1606
+ self.k_cache[self.cache_position:self.cache_position + seq_len] = k_values[0]
1607
+ self.action_cache[self.cache_position:self.cache_position + seq_len] = actions[0]
1608
+ self.cache_position += seq_len
1609
+ else:
1610
+ self.reset_cache()
1611
+
1612
+ def step(self, hidden_state, stack, mask):
1613
+ if not self.enable_cache:
1614
+ return self.forward(hidden_state.unsqueeze(1), stack, mask)
1615
+
1616
+ if self.cache_position > 0:
1617
+ cached_k = self.k_cache[:self.cache_position]
1618
+ cached_actions = self.action_cache[:self.cache_position]
1619
+
1620
+ k_values = torch.cat([cached_k.unsqueeze(0), hidden_state], dim=1)
1621
+ actions = torch.cat([
1622
+ cached_actions.unsqueeze(0),
1623
+ self.action_head(hidden_state).softmax(dim=-1)
1624
+ ], dim=1)
1625
+ else:
1626
+ k_values = hidden_state
1627
+ actions = self.action_head(hidden_state).softmax(dim=-1)
1628
+
1629
+ new_stack, new_mask = self._vectorized_update(
1630
+ stack.unsqueeze(1),
1631
+ mask.unsqueeze(1),
1632
+ actions.unsqueeze(0),
1633
+ k_values.unsqueeze(0)
1634
+ )
1635
+
1636
+ gate_scores = self.gate_proj(new_stack).squeeze(-1)
1637
+ gate_weights = F.softmax(gate_scores + (1 - new_mask) * -80.0, dim=-1)
1638
+ memory_output = (new_stack * gate_weights.unsqueeze(-1)).sum(dim=3)
1639
+
1640
+ self._update_cache(k_values, actions)
1641
+
1642
+ return (
1643
+ memory_output.squeeze(0) * self.res_weight + hidden_state,
1644
+ new_stack.squeeze(0),
1645
+ new_mask.squeeze(0)
1646
+ )
1647
+
1648
+
1649
  class LNS(nn.Module):
1650
  """
1651
  LayerNorm Scaling: applies 1/√ℓ to suppress variance growth with depth.
 
4649
  self.gpas_mlp = GPAS(config.hidden_size)
4650
  self.current_layer_fan = None
4651
 
4652
+ # ── StackMemory / STACKTRANS (Zhang et al., NeurIPS 2025) ────────
4653
+ # Optional differentiable hidden-state stack inserted between
4654
+ # Transformer layers. The stack is applied before this layer's
4655
+ # attention block, matching the released StackTrans source flow.
4656
+ self.use_stack_memory = getattr(config, "use_stack_memory", False)
4657
+ self.stack_memory = StackMemory(config) if self.use_stack_memory else None
4658
+
4659
  if self.use_jtokm:
4660
  self.jtokm = LeviathanJTokM(config, layer_idx)
4661
  else:
 
4739
  self.laurel_lr_A_mlp = None
4740
  self.laurel_lr_B_mlp = None
4741
 
4742
+ def apply_stack_memory(
4743
+ self,
4744
+ hidden_states: torch.Tensor,
4745
+ stack_memory: Optional[torch.Tensor],
4746
+ stack_memory_mask: Optional[torch.Tensor],
4747
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor]]:
4748
+ """
4749
+ Apply this layer's differentiable StackMemory module before attention.
4750
+
4751
+ The memory tensors are owned by ``NeoLLMModel.forward`` and threaded
4752
+ across decoder layers, reproducing the StackTrans pattern where a
4753
+ hidden-state stack sits between standard Transformer layers while the
4754
+ attention implementation remains unchanged.
4755
+ """
4756
+ if (not self.use_stack_memory) or self.stack_memory is None:
4757
+ return hidden_states, stack_memory, stack_memory_mask
4758
+ if stack_memory is None or stack_memory_mask is None:
4759
+ raise ValueError(
4760
+ "StackMemory is enabled, but stack_memory/stack_memory_mask "
4761
+ "were not initialized by NeoLLMModel.forward."
4762
+ )
4763
+ return self.stack_memory(hidden_states, stack_memory, stack_memory_mask)
4764
+
4765
  def _attn_res(
4766
  self,
4767
  sources: list,
 
5437
  module.scaler.data.fill_(1.0)
5438
  # router: parent handles via normal init
5439
 
5440
+ elif isinstance(module, StackMemory):
5441
+ nn.init.normal_(module.down_proj.weight, mean=0.0, std=self.config.initializer_range)
5442
+ nn.init.normal_(module.up_proj.weight, mean=0.0, std=self.config.initializer_range)
5443
+ nn.init.normal_(module.action_head.weight, mean=0.0, std=self.config.initializer_range)
5444
+ nn.init.normal_(module.gate_proj.weight, mean=0.0, std=self.config.initializer_range)
5445
+
5446
+ if module.down_proj.bias is not None:
5447
+ nn.init.zeros_(module.down_proj.bias)
5448
+ if module.up_proj.bias is not None:
5449
+ nn.init.zeros_(module.up_proj.bias)
5450
+ if module.action_head.bias is not None:
5451
+ nn.init.zeros_(module.action_head.bias)
5452
+ if module.gate_proj.bias is not None:
5453
+ nn.init.zeros_(module.gate_proj.bias)
5454
+
5455
+ module.res_weight.data.fill_(1.0)
5456
  elif isinstance(module, NeoLLMDecoderLayer):
5457
  # AttnRes pseudo-queries: MUST be initialized to zero.
5458
  # Zero initialization ensures uniform attention weights at step 0
 
5532
  self.gradient_checkpointing = False
5533
  self.first_layer_fan = None if getattr(config, "use_fan_residual", True) else False
5534
 
5535
+ # ── StackMemory base state ────────────────────────────────────────
5536
+ # Keep the empty stack as model-owned non-trainable state, matching
5537
+ # the released StackTrans flow where forward starts from a detached
5538
+ # base memory before threading the updated stack through the layers.
5539
+ if getattr(config, "use_stack_memory", False):
5540
+ stack_head_dim = config.stack_d_model // config.num_mem_heads
5541
+ self.register_buffer(
5542
+ "memory",
5543
+ torch.zeros(1, config.num_mem_heads, config.stack_slots, stack_head_dim),
5544
+ persistent=False,
5545
+ )
5546
+ self.register_buffer(
5547
+ "memory_mask",
5548
+ torch.zeros(1, config.num_mem_heads, config.stack_slots),
5549
+ persistent=False,
5550
+ )
5551
+ else:
5552
+ self.memory = None
5553
+ self.memory_mask = None
5554
+
5555
  self.post_init()
5556
 
5557
  def get_input_embeddings(self):
 
5694
  all_attentions = () if output_attentions else None
5695
  all_aux_stats = []
5696
 
5697
+ # ── StackMemory state ─────────────────────────────────────────────
5698
+ # Same source-level idea as StackTrans:
5699
+ # memory = self.memory.detach()[:b]
5700
+ # memory_mask = self.memory_mask.detach()[:b]
5701
+ # Here the base buffer has batch size 1 and is expanded locally so no
5702
+ # module attribute is created or reassigned inside torch.compile.
5703
+ use_stack_memory = getattr(self.config, "use_stack_memory", False)
5704
+ if use_stack_memory:
5705
+ batch_size = hidden_states.shape[0]
5706
+ stack_memory = self.memory.detach().to(dtype=hidden_states.dtype).expand(
5707
+ batch_size, -1, -1, -1
5708
+ )
5709
+ stack_memory_mask = self.memory_mask.detach().expand(batch_size, -1, -1)
5710
+ else:
5711
+ stack_memory = None
5712
+ stack_memory_mask = None
5713
+
5714
  position_embeddings = self.rotary_emb(hidden_states, position_ids)
5715
  self.first_layer_fan = None if getattr(self.config, "use_fan_residual", True) else False
5716
 
 
5787
  layer_analysis.layer_idx = layer_idx
5788
  analysis_state.layers.append(layer_analysis)
5789
 
5790
+ if use_stack_memory:
5791
+ hidden_states, stack_memory, stack_memory_mask = decoder_layer.apply_stack_memory(
5792
+ hidden_states, stack_memory, stack_memory_mask
5793
+ )
5794
+
5795
  layer_outputs = decoder_layer(
5796
  hidden_states,
5797
  position_embeddings=position_embeddings,
 
6130
  "LeviathanGenerator",
6131
  "LeviathanJTokM",
6132
  "SpellingBeeEmbedding",
6133
+ "StackMemory",
6134
  "FANLayer",
6135
  "SeeDNorm",
6136
  "ScalarMultiplier",