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 files- modeling_neollm.py +231 -10
modeling_neollm.py
CHANGED
|
@@ -509,6 +509,39 @@ class LAuReLAnalysis:
|
|
| 509 |
lr_delta_norm_mlp: Optional[float] = None # ‖BAx‖₂ from LR path, MLP sublayer
|
| 510 |
|
| 511 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 512 |
@dataclass
|
| 513 |
class LayerAnalysis:
|
| 514 |
"""
|
|
@@ -538,6 +571,7 @@ class LayerAnalysis:
|
|
| 538 |
|
| 539 |
# Optional components (None when inactive)
|
| 540 |
jtokm: Optional[JTokMAnalysis] = None # if use_jtokm
|
|
|
|
| 541 |
attn_res: Optional[AttnResAnalysis] = None # if use_attn_res
|
| 542 |
laurel: Optional[LAuReLAnalysis] = None # if use_laurel
|
| 543 |
|
|
@@ -4162,21 +4196,35 @@ class NeoLLMAttention(nn.Module):
|
|
| 4162 |
attn_analysis: Optional[AttentionAnalysis] = None,
|
| 4163 |
repo_rope_args: Optional[Tuple[torch.Tensor, float]] = None,
|
| 4164 |
position_ids: Optional[torch.LongTensor] = None,
|
|
|
|
| 4165 |
**kwargs: Unpack[FlashAttentionKwargs],
|
| 4166 |
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor]]:
|
| 4167 |
input_shape = hidden_states.shape[:-1]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4168 |
|
| 4169 |
fan_a = attn_analysis.fan if attn_analysis is not None else None
|
| 4170 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4171 |
if self.use_fan_residual and first_layer_fan is not None:
|
| 4172 |
-
|
| 4173 |
-
|
|
|
|
|
|
|
| 4174 |
|
| 4175 |
query_shape = (*input_shape, self.config.num_attention_heads, self.head_dim)
|
| 4176 |
kv_shape = (*input_shape, self.num_mea_component_heads, self.head_dim)
|
| 4177 |
|
| 4178 |
q_raw, gate = torch.chunk(
|
| 4179 |
-
self.q_proj(
|
| 4180 |
2, dim=-1,
|
| 4181 |
)
|
| 4182 |
gate = gate.reshape(*input_shape, -1)
|
|
@@ -4186,8 +4234,8 @@ class NeoLLMAttention(nn.Module):
|
|
| 4186 |
attn_analysis.gate_raw = gate.detach()
|
| 4187 |
|
| 4188 |
q = self.q_norm(q_raw.view(query_shape)).transpose(1, 2)
|
| 4189 |
-
k = self.k_norm(self.k_proj(
|
| 4190 |
-
v = self.v_proj(
|
| 4191 |
|
| 4192 |
if attn_analysis is not None:
|
| 4193 |
attn_analysis.q_post_norm = q.detach()
|
|
@@ -5177,6 +5225,93 @@ class NeoLLMMLP(nn.Module):
|
|
| 5177 |
return result
|
| 5178 |
|
| 5179 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5180 |
class NeoLLMDecoderLayer(GradientCheckpointingLayer):
|
| 5181 |
"""
|
| 5182 |
Decoder layer with standard residual connections, optional JTok-M injection.
|
|
@@ -5236,6 +5371,19 @@ class NeoLLMDecoderLayer(GradientCheckpointingLayer):
|
|
| 5236 |
self.use_stack_memory = getattr(config, "use_stack_memory", False)
|
| 5237 |
self.stack_memory = StackMemory(config) if self.use_stack_memory else None
|
| 5238 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5239 |
if self.use_jtokm:
|
| 5240 |
self.jtokm = LeviathanJTokM(config, layer_idx)
|
| 5241 |
else:
|
|
@@ -5476,6 +5624,7 @@ class NeoLLMDecoderLayer(GradientCheckpointingLayer):
|
|
| 5476 |
first_layer_fan: Optional[torch.Tensor] = None,
|
| 5477 |
z_tilde: Optional[torch.Tensor] = None,
|
| 5478 |
B_vals: Optional[torch.Tensor] = None,
|
|
|
|
| 5479 |
attn_res_sources: Optional[list] = None,
|
| 5480 |
attn_res_partial: Optional[torch.Tensor] = None,
|
| 5481 |
layer_analysis: Optional[LayerAnalysis] = None,
|
|
@@ -5506,6 +5655,20 @@ class NeoLLMDecoderLayer(GradientCheckpointingLayer):
|
|
| 5506 |
h_attn = hidden_states
|
| 5507 |
residual_attn = hidden_states
|
| 5508 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5509 |
# ── Attention block ───────────────────────────────────────────────
|
| 5510 |
sn_pre = layer_analysis.seednorm_pre_attn if layer_analysis is not None else None
|
| 5511 |
|
|
@@ -5521,15 +5684,29 @@ class NeoLLMDecoderLayer(GradientCheckpointingLayer):
|
|
| 5521 |
# Analysis compatibility: mark the bypass as the observed
|
| 5522 |
# output without fabricating SeeDNorm internal gates/scales.
|
| 5523 |
sn_pre.output = h_attn.detach()
|
|
|
|
|
|
|
|
|
|
| 5524 |
else:
|
| 5525 |
h_normed = self.input_layernorm(h_attn, analysis=sn_pre)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5526 |
|
| 5527 |
h_lns = self.lns_attn(h_normed)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5528 |
if layer_analysis is not None:
|
| 5529 |
layer_analysis.lns_attn_output = h_lns.detach()
|
| 5530 |
|
| 5531 |
hidden_states, attn_weights, self.current_layer_fan = self.self_attn(
|
| 5532 |
hidden_states=h_lns,
|
|
|
|
| 5533 |
attention_mask=attention_mask,
|
| 5534 |
position_embeddings=position_embeddings,
|
| 5535 |
first_layer_fan=first_layer_fan,
|
|
@@ -5544,9 +5721,10 @@ class NeoLLMDecoderLayer(GradientCheckpointingLayer):
|
|
| 5544 |
|
| 5545 |
gpas_attn_a = layer_analysis.gpas_attn if layer_analysis is not None else None
|
| 5546 |
# ── Residual junction (attention sublayer) ────────────────────────
|
| 5547 |
-
#
|
| 5548 |
-
#
|
| 5549 |
-
#
|
|
|
|
| 5550 |
if self.use_laurel:
|
| 5551 |
attn_aug = self._laurel_residual(
|
| 5552 |
residual_attn, hidden_states,
|
|
@@ -5554,8 +5732,10 @@ class NeoLLMDecoderLayer(GradientCheckpointingLayer):
|
|
| 5554 |
analysis=layer_analysis.laurel if layer_analysis is not None else None,
|
| 5555 |
slot="attn",
|
| 5556 |
)
|
|
|
|
| 5557 |
else:
|
| 5558 |
attn_aug = residual_attn + hidden_states
|
|
|
|
| 5559 |
h_tilde = self.gpas_attn(attn_aug, analysis=gpas_attn_a)
|
| 5560 |
|
| 5561 |
if layer_analysis is not None:
|
|
@@ -5573,7 +5753,7 @@ class NeoLLMDecoderLayer(GradientCheckpointingLayer):
|
|
| 5573 |
residual_mlp = h_tilde
|
| 5574 |
else:
|
| 5575 |
h_mlp = h_tilde
|
| 5576 |
-
residual_mlp = h_tilde
|
| 5577 |
|
| 5578 |
# ── MLP block ─────────────────────────────────────────────────────
|
| 5579 |
sn_post = layer_analysis.seednorm_post_attn if layer_analysis is not None else None
|
|
@@ -6087,6 +6267,10 @@ class NeoLLMModel(NeoLLMPreTrainedModel):
|
|
| 6087 |
decoder layer, replacing fixed residual accumulation with learned
|
| 6088 |
depth-wise softmax attention (Kimi Team, 2026, arXiv:2603.15031).
|
| 6089 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6090 |
Spelling Bee Embeddings (Rabe et al., 2026, arXiv:2601.18030):
|
| 6091 |
``use_spelling_bee_embeddings`` is independent of the Leviathan flag:
|
| 6092 |
SBE is applied post-embedding regardless of which path produced the
|
|
@@ -6168,6 +6352,24 @@ class NeoLLMModel(NeoLLMPreTrainedModel):
|
|
| 6168 |
else:
|
| 6169 |
self.embed_tokens = value
|
| 6170 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6171 |
def _build_layer_analysis(self, layer_idx: int = 0) -> LayerAnalysis:
|
| 6172 |
"""
|
| 6173 |
Construct a LayerAnalysis with sub-objects pre-allocated for every
|
|
@@ -6207,6 +6409,7 @@ class NeoLLMModel(NeoLLMPreTrainedModel):
|
|
| 6207 |
gpas_attn = GPASAnalysis(),
|
| 6208 |
gpas_mlp = GPASAnalysis(),
|
| 6209 |
jtokm = JTokMAnalysis() if cfg.use_jtokm else None,
|
|
|
|
| 6210 |
attn_res = AttnResAnalysis() if getattr(cfg, "use_attn_res", False) else None,
|
| 6211 |
laurel = LAuReLAnalysis() if getattr(cfg, "use_laurel", False) else None,
|
| 6212 |
)
|
|
@@ -6345,6 +6548,14 @@ class NeoLLMModel(NeoLLMPreTrainedModel):
|
|
| 6345 |
else None
|
| 6346 |
)
|
| 6347 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6348 |
# ── Attention Residuals state ──────────────────────────────────────
|
| 6349 |
# Full AttnRes (attn_res_num_blocks=0): sources grows by one entry per
|
| 6350 |
# decoder layer — all previous outputs are kept, max N=num_layers+1.
|
|
@@ -6399,6 +6610,8 @@ class NeoLLMModel(NeoLLMPreTrainedModel):
|
|
| 6399 |
hidden_states, stack_memory, stack_memory_mask
|
| 6400 |
)
|
| 6401 |
|
|
|
|
|
|
|
| 6402 |
layer_outputs = decoder_layer(
|
| 6403 |
hidden_states,
|
| 6404 |
position_embeddings=position_embeddings,
|
|
@@ -6406,6 +6619,7 @@ class NeoLLMModel(NeoLLMPreTrainedModel):
|
|
| 6406 |
first_layer_fan=self.first_layer_fan,
|
| 6407 |
z_tilde=z_tilde,
|
| 6408 |
B_vals=B_vals,
|
|
|
|
| 6409 |
attn_res_sources=attn_res_sources,
|
| 6410 |
attn_res_partial=attn_res_partial if use_attn_res else None,
|
| 6411 |
layer_analysis=layer_analysis,
|
|
@@ -6420,6 +6634,10 @@ class NeoLLMModel(NeoLLMPreTrainedModel):
|
|
| 6420 |
if use_attn_res:
|
| 6421 |
attn_res_partial = hidden_states
|
| 6422 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6423 |
if output_attentions:
|
| 6424 |
all_attentions = all_attentions + (layer_outputs[1],)
|
| 6425 |
|
|
@@ -6766,6 +6984,9 @@ __all__ = [
|
|
| 6766 |
"VersatileFFNAnalysis",
|
| 6767 |
"JTokMAnalysis",
|
| 6768 |
"AttnResAnalysis",
|
|
|
|
|
|
|
|
|
|
| 6769 |
"GeneratorAnalysis",
|
| 6770 |
"IHAAnalysis",
|
| 6771 |
]
|
|
|
|
| 509 |
lr_delta_norm_mlp: Optional[float] = None # ‖BAx‖₂ from LR path, MLP sublayer
|
| 510 |
|
| 511 |
|
| 512 |
+
@dataclass
|
| 513 |
+
class DCAAnalysis:
|
| 514 |
+
"""
|
| 515 |
+
Internals of the DeepCrossAttention (DCA) GRN-v3 composer for one
|
| 516 |
+
decoder layer.
|
| 517 |
+
|
| 518 |
+
DCA builds three independent GRN-v3 instances over the selected stack of
|
| 519 |
+
previous layer outputs and returns separate q/k/v input streams for the
|
| 520 |
+
underlying attention block. Populated only when ``use_dca=True`` and
|
| 521 |
+
analysis mode is active.
|
| 522 |
+
|
| 523 |
+
Shapes:
|
| 524 |
+
selected_sources: [Y, B, S, D] where Y is the selected depth stack.
|
| 525 |
+
*_aggregate_logits: [Y, B, S] input-dependent scalar component σ(wᵀG_y).
|
| 526 |
+
*_bias_snapshot: [Y, D] dimension-dependent GRN-v3 bias b_y.
|
| 527 |
+
*_input: [B, S, D] composed attention input stream.
|
| 528 |
+
"""
|
| 529 |
+
selected_source_count: Optional[int] = None
|
| 530 |
+
selected_sources: Optional[torch.Tensor] = None
|
| 531 |
+
|
| 532 |
+
q_aggregate_logits: Optional[torch.Tensor] = None
|
| 533 |
+
k_aggregate_logits: Optional[torch.Tensor] = None
|
| 534 |
+
v_aggregate_logits: Optional[torch.Tensor] = None
|
| 535 |
+
|
| 536 |
+
q_bias_snapshot: Optional[torch.Tensor] = None
|
| 537 |
+
k_bias_snapshot: Optional[torch.Tensor] = None
|
| 538 |
+
v_bias_snapshot: Optional[torch.Tensor] = None
|
| 539 |
+
|
| 540 |
+
q_input: Optional[torch.Tensor] = None
|
| 541 |
+
k_input: Optional[torch.Tensor] = None
|
| 542 |
+
v_input: Optional[torch.Tensor] = None
|
| 543 |
+
|
| 544 |
+
|
| 545 |
@dataclass
|
| 546 |
class LayerAnalysis:
|
| 547 |
"""
|
|
|
|
| 571 |
|
| 572 |
# Optional components (None when inactive)
|
| 573 |
jtokm: Optional[JTokMAnalysis] = None # if use_jtokm
|
| 574 |
+
dca: Optional[DCAAnalysis] = None # if use_dca
|
| 575 |
attn_res: Optional[AttnResAnalysis] = None # if use_attn_res
|
| 576 |
laurel: Optional[LAuReLAnalysis] = None # if use_laurel
|
| 577 |
|
|
|
|
| 4196 |
attn_analysis: Optional[AttentionAnalysis] = None,
|
| 4197 |
repo_rope_args: Optional[Tuple[torch.Tensor, float]] = None,
|
| 4198 |
position_ids: Optional[torch.LongTensor] = None,
|
| 4199 |
+
key_value_states: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 4200 |
**kwargs: Unpack[FlashAttentionKwargs],
|
| 4201 |
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor]]:
|
| 4202 |
input_shape = hidden_states.shape[:-1]
|
| 4203 |
+
if key_value_states is None:
|
| 4204 |
+
key_states = hidden_states
|
| 4205 |
+
value_states = hidden_states
|
| 4206 |
+
else:
|
| 4207 |
+
key_states, value_states = key_value_states
|
| 4208 |
|
| 4209 |
fan_a = attn_analysis.fan if attn_analysis is not None else None
|
| 4210 |
+
h_fan_q = self.fan_layer(hidden_states, analysis=fan_a)
|
| 4211 |
+
if key_value_states is None:
|
| 4212 |
+
h_fan_k = h_fan_q
|
| 4213 |
+
h_fan_v = h_fan_q
|
| 4214 |
+
else:
|
| 4215 |
+
h_fan_k = self.fan_layer(key_states, analysis=None)
|
| 4216 |
+
h_fan_v = self.fan_layer(value_states, analysis=None)
|
| 4217 |
if self.use_fan_residual and first_layer_fan is not None:
|
| 4218 |
+
h_fan_q = self.lambda_1 * first_layer_fan + self.lambda_2 * h_fan_q
|
| 4219 |
+
h_fan_k = self.lambda_1 * first_layer_fan + self.lambda_2 * h_fan_k
|
| 4220 |
+
h_fan_v = self.lambda_1 * first_layer_fan + self.lambda_2 * h_fan_v
|
| 4221 |
+
current_layer_fan = h_fan_q.clone()
|
| 4222 |
|
| 4223 |
query_shape = (*input_shape, self.config.num_attention_heads, self.head_dim)
|
| 4224 |
kv_shape = (*input_shape, self.num_mea_component_heads, self.head_dim)
|
| 4225 |
|
| 4226 |
q_raw, gate = torch.chunk(
|
| 4227 |
+
self.q_proj(h_fan_q).view(*input_shape, self.config.num_attention_heads, self.head_dim * 2),
|
| 4228 |
2, dim=-1,
|
| 4229 |
)
|
| 4230 |
gate = gate.reshape(*input_shape, -1)
|
|
|
|
| 4234 |
attn_analysis.gate_raw = gate.detach()
|
| 4235 |
|
| 4236 |
q = self.q_norm(q_raw.view(query_shape)).transpose(1, 2)
|
| 4237 |
+
k = self.k_norm(self.k_proj(h_fan_k).view(kv_shape)).transpose(1, 2)
|
| 4238 |
+
v = self.v_proj(h_fan_v).view(kv_shape).transpose(1, 2)
|
| 4239 |
|
| 4240 |
if attn_analysis is not None:
|
| 4241 |
attn_analysis.q_post_norm = q.detach()
|
|
|
|
| 5225 |
return result
|
| 5226 |
|
| 5227 |
|
| 5228 |
+
class DCAInputGRN(nn.Module):
|
| 5229 |
+
"""
|
| 5230 |
+
GRN-v3 composer used by DeepCrossAttention for one of Q, K or V.
|
| 5231 |
+
|
| 5232 |
+
Given a selected stack of previous layer outputs
|
| 5233 |
+
G ∈ R^{Y×B×S×D},
|
| 5234 |
+
it computes
|
| 5235 |
+
h = Σ_y G_y ⊙ (b_y + σ(wᵀ RMSNorm(G_y)))
|
| 5236 |
+
with b ∈ R^{Y×D} and w ∈ R^D.
|
| 5237 |
+
|
| 5238 |
+
This is the input-dependent GRN-v3 mechanism from DCA, specialized to a
|
| 5239 |
+
single output stream. DCA uses three independent copies for Q, K and V.
|
| 5240 |
+
"""
|
| 5241 |
+
def __init__(self, dim: int, num_layers: int, activation: Optional[nn.Module] = None):
|
| 5242 |
+
super().__init__()
|
| 5243 |
+
if num_layers <= 0:
|
| 5244 |
+
raise ValueError(f"DCAInputGRN requires num_layers > 0, got {num_layers}.")
|
| 5245 |
+
self.dim = int(dim)
|
| 5246 |
+
self.num_layers = int(num_layers)
|
| 5247 |
+
self.norm = nn.RMSNorm(dim)
|
| 5248 |
+
self.to_aggregate = nn.Linear(dim, 1, bias=False)
|
| 5249 |
+
self.activation = activation if activation is not None else nn.ReLU()
|
| 5250 |
+
self.bias = nn.Parameter(torch.ones(num_layers, dim))
|
| 5251 |
+
nn.init.normal_(self.to_aggregate.weight, std=1e-2)
|
| 5252 |
+
|
| 5253 |
+
def forward(
|
| 5254 |
+
self,
|
| 5255 |
+
tokens_across_depth: torch.Tensor,
|
| 5256 |
+
analysis_prefix: Optional[str] = None,
|
| 5257 |
+
analysis: Optional[DCAAnalysis] = None,
|
| 5258 |
+
) -> torch.Tensor:
|
| 5259 |
+
if tokens_across_depth.shape[0] != self.num_layers:
|
| 5260 |
+
raise ValueError(
|
| 5261 |
+
f"DCAInputGRN expected {self.num_layers} selected source layers, "
|
| 5262 |
+
f"got {tokens_across_depth.shape[0]}."
|
| 5263 |
+
)
|
| 5264 |
+
normed = self.norm(tokens_across_depth) # [Y,B,S,D]
|
| 5265 |
+
logits = self.activation(self.to_aggregate(normed)).squeeze(-1) # [Y,B,S]
|
| 5266 |
+
weights = logits.unsqueeze(-1) + self.bias[:, None, None, :] # [Y,B,S,D]
|
| 5267 |
+
out = (tokens_across_depth * weights).sum(dim=0) # [B,S,D]
|
| 5268 |
+
|
| 5269 |
+
if analysis is not None and analysis_prefix is not None:
|
| 5270 |
+
if analysis_prefix == "q":
|
| 5271 |
+
analysis.q_aggregate_logits = logits.detach()
|
| 5272 |
+
analysis.q_bias_snapshot = self.bias.detach()
|
| 5273 |
+
analysis.q_input = out.detach()
|
| 5274 |
+
elif analysis_prefix == "k":
|
| 5275 |
+
analysis.k_aggregate_logits = logits.detach()
|
| 5276 |
+
analysis.k_bias_snapshot = self.bias.detach()
|
| 5277 |
+
analysis.k_input = out.detach()
|
| 5278 |
+
elif analysis_prefix == "v":
|
| 5279 |
+
analysis.v_aggregate_logits = logits.detach()
|
| 5280 |
+
analysis.v_bias_snapshot = self.bias.detach()
|
| 5281 |
+
analysis.v_input = out.detach()
|
| 5282 |
+
return out
|
| 5283 |
+
|
| 5284 |
+
|
| 5285 |
+
class DeepCrossAttentionComposer(nn.Module):
|
| 5286 |
+
"""
|
| 5287 |
+
DCA q/k/v input composer for one decoder layer.
|
| 5288 |
+
|
| 5289 |
+
The DCA paper states that each decoder block uses three independent GRN-v3
|
| 5290 |
+
instances over the same stack of previous layer outputs, producing the Q, K
|
| 5291 |
+
and V input streams. This module implements that composition only; the
|
| 5292 |
+
underlying attention operator remains NeoLLMAttention.
|
| 5293 |
+
"""
|
| 5294 |
+
def __init__(self, dim: int, num_layers: int):
|
| 5295 |
+
super().__init__()
|
| 5296 |
+
self.num_layers = int(num_layers)
|
| 5297 |
+
self.q_grn = DCAInputGRN(dim, num_layers)
|
| 5298 |
+
self.k_grn = DCAInputGRN(dim, num_layers)
|
| 5299 |
+
self.v_grn = DCAInputGRN(dim, num_layers)
|
| 5300 |
+
|
| 5301 |
+
def forward(
|
| 5302 |
+
self,
|
| 5303 |
+
tokens_across_depth: torch.Tensor,
|
| 5304 |
+
analysis: Optional[DCAAnalysis] = None,
|
| 5305 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 5306 |
+
if analysis is not None:
|
| 5307 |
+
analysis.selected_source_count = int(tokens_across_depth.shape[0])
|
| 5308 |
+
analysis.selected_sources = tokens_across_depth.detach()
|
| 5309 |
+
q_input = self.q_grn(tokens_across_depth, analysis_prefix="q", analysis=analysis)
|
| 5310 |
+
k_input = self.k_grn(tokens_across_depth, analysis_prefix="k", analysis=analysis)
|
| 5311 |
+
v_input = self.v_grn(tokens_across_depth, analysis_prefix="v", analysis=analysis)
|
| 5312 |
+
return q_input, k_input, v_input
|
| 5313 |
+
|
| 5314 |
+
|
| 5315 |
class NeoLLMDecoderLayer(GradientCheckpointingLayer):
|
| 5316 |
"""
|
| 5317 |
Decoder layer with standard residual connections, optional JTok-M injection.
|
|
|
|
| 5371 |
self.use_stack_memory = getattr(config, "use_stack_memory", False)
|
| 5372 |
self.stack_memory = StackMemory(config) if self.use_stack_memory else None
|
| 5373 |
|
| 5374 |
+
# ── DeepCrossAttention (Heddes et al., ICML 2025) ─────────────────
|
| 5375 |
+
# DCA replaces the single residual-stream input to attention with
|
| 5376 |
+
# three GRN-v3-composed streams for Q, K and V. The selected depth
|
| 5377 |
+
# stack is built in NeoLLMModel.forward using the paper's efficient
|
| 5378 |
+
# first/input + intermediate-sum + last-k scheme.
|
| 5379 |
+
self.use_dca = getattr(config, "use_dca", False)
|
| 5380 |
+
self.dca_past_layers_k = int(getattr(config, "dca_past_layers_k", 2))
|
| 5381 |
+
if self.use_dca:
|
| 5382 |
+
dca_num_sources = min(self.layer_idx + 1, self.dca_past_layers_k + 2)
|
| 5383 |
+
self.dca_composer = DeepCrossAttentionComposer(config.hidden_size, dca_num_sources)
|
| 5384 |
+
else:
|
| 5385 |
+
self.dca_composer = None
|
| 5386 |
+
|
| 5387 |
if self.use_jtokm:
|
| 5388 |
self.jtokm = LeviathanJTokM(config, layer_idx)
|
| 5389 |
else:
|
|
|
|
| 5624 |
first_layer_fan: Optional[torch.Tensor] = None,
|
| 5625 |
z_tilde: Optional[torch.Tensor] = None,
|
| 5626 |
B_vals: Optional[torch.Tensor] = None,
|
| 5627 |
+
dca_sources: Optional[torch.Tensor] = None,
|
| 5628 |
attn_res_sources: Optional[list] = None,
|
| 5629 |
attn_res_partial: Optional[torch.Tensor] = None,
|
| 5630 |
layer_analysis: Optional[LayerAnalysis] = None,
|
|
|
|
| 5655 |
h_attn = hidden_states
|
| 5656 |
residual_attn = hidden_states
|
| 5657 |
|
| 5658 |
+
# ── DCA: compose Q/K/V residual streams from previous layer outputs ──
|
| 5659 |
+
dca_key_value_states = None
|
| 5660 |
+
dca_final_residual = None
|
| 5661 |
+
if self.use_dca and dca_sources is not None:
|
| 5662 |
+
dca_a = layer_analysis.dca if layer_analysis is not None else None
|
| 5663 |
+
q_input, k_input, v_input = self.dca_composer(dca_sources, analysis=dca_a)
|
| 5664 |
+
h_attn = q_input
|
| 5665 |
+
residual_attn = q_input
|
| 5666 |
+
dca_k_input = k_input
|
| 5667 |
+
dca_v_input = v_input
|
| 5668 |
+
else:
|
| 5669 |
+
dca_k_input = None
|
| 5670 |
+
dca_v_input = None
|
| 5671 |
+
|
| 5672 |
# ── Attention block ───────────────────────────────────────────────
|
| 5673 |
sn_pre = layer_analysis.seednorm_pre_attn if layer_analysis is not None else None
|
| 5674 |
|
|
|
|
| 5684 |
# Analysis compatibility: mark the bypass as the observed
|
| 5685 |
# output without fabricating SeeDNorm internal gates/scales.
|
| 5686 |
sn_pre.output = h_attn.detach()
|
| 5687 |
+
if dca_k_input is not None:
|
| 5688 |
+
k_normed = dca_k_input
|
| 5689 |
+
v_normed = dca_v_input
|
| 5690 |
else:
|
| 5691 |
h_normed = self.input_layernorm(h_attn, analysis=sn_pre)
|
| 5692 |
+
if dca_k_input is not None:
|
| 5693 |
+
# DCA follows the paper's three independently-composed Q/K/V
|
| 5694 |
+
# streams while preserving NeoLLM's pre-norm convention by
|
| 5695 |
+
# applying the same layer input normaliser to each stream.
|
| 5696 |
+
k_normed = self.input_layernorm(dca_k_input, analysis=None)
|
| 5697 |
+
v_normed = self.input_layernorm(dca_v_input, analysis=None)
|
| 5698 |
|
| 5699 |
h_lns = self.lns_attn(h_normed)
|
| 5700 |
+
if dca_k_input is not None:
|
| 5701 |
+
k_lns = self.lns_attn(k_normed)
|
| 5702 |
+
v_lns = self.lns_attn(v_normed)
|
| 5703 |
+
dca_key_value_states = (k_lns, v_lns)
|
| 5704 |
if layer_analysis is not None:
|
| 5705 |
layer_analysis.lns_attn_output = h_lns.detach()
|
| 5706 |
|
| 5707 |
hidden_states, attn_weights, self.current_layer_fan = self.self_attn(
|
| 5708 |
hidden_states=h_lns,
|
| 5709 |
+
key_value_states=dca_key_value_states,
|
| 5710 |
attention_mask=attention_mask,
|
| 5711 |
position_embeddings=position_embeddings,
|
| 5712 |
first_layer_fan=first_layer_fan,
|
|
|
|
| 5721 |
|
| 5722 |
gpas_attn_a = layer_analysis.gpas_attn if layer_analysis is not None else None
|
| 5723 |
# ── Residual junction (attention sublayer) ────────────────────────
|
| 5724 |
+
# DCA paper flow: q_input is included in the feed-forward input
|
| 5725 |
+
# (attn_out + q_input), but the decoder block output later keeps the
|
| 5726 |
+
# attention branch as the residual base (ff_out + attn_out). Standard
|
| 5727 |
+
# and LAuReL paths remain unchanged when DCA is inactive.
|
| 5728 |
if self.use_laurel:
|
| 5729 |
attn_aug = self._laurel_residual(
|
| 5730 |
residual_attn, hidden_states,
|
|
|
|
| 5732 |
analysis=layer_analysis.laurel if layer_analysis is not None else None,
|
| 5733 |
slot="attn",
|
| 5734 |
)
|
| 5735 |
+
dca_final_residual = None
|
| 5736 |
else:
|
| 5737 |
attn_aug = residual_attn + hidden_states
|
| 5738 |
+
dca_final_residual = hidden_states if self.use_dca else None
|
| 5739 |
h_tilde = self.gpas_attn(attn_aug, analysis=gpas_attn_a)
|
| 5740 |
|
| 5741 |
if layer_analysis is not None:
|
|
|
|
| 5753 |
residual_mlp = h_tilde
|
| 5754 |
else:
|
| 5755 |
h_mlp = h_tilde
|
| 5756 |
+
residual_mlp = dca_final_residual if dca_final_residual is not None else h_tilde
|
| 5757 |
|
| 5758 |
# ── MLP block ─────────────────────────────────────────────────────
|
| 5759 |
sn_post = layer_analysis.seednorm_post_attn if layer_analysis is not None else None
|
|
|
|
| 6267 |
decoder layer, replacing fixed residual accumulation with learned
|
| 6268 |
depth-wise softmax attention (Kimi Team, 2026, arXiv:2603.15031).
|
| 6269 |
|
| 6270 |
+
When use_dca=True, the model maintains a stack of previous decoder outputs
|
| 6271 |
+
and each layer composes q/k/v input streams with DCA GRN-v3 over the selected
|
| 6272 |
+
first/input + intermediate-sum + last-k depth sources.
|
| 6273 |
+
|
| 6274 |
Spelling Bee Embeddings (Rabe et al., 2026, arXiv:2601.18030):
|
| 6275 |
``use_spelling_bee_embeddings`` is independent of the Leviathan flag:
|
| 6276 |
SBE is applied post-embedding regardless of which path produced the
|
|
|
|
| 6352 |
else:
|
| 6353 |
self.embed_tokens = value
|
| 6354 |
|
| 6355 |
+
def _select_dca_sources(self, dca_sources: List[torch.Tensor]) -> torch.Tensor:
|
| 6356 |
+
"""
|
| 6357 |
+
Select the DCA depth stack using the efficient k-DCA scheme.
|
| 6358 |
+
|
| 6359 |
+
For small depths all previous outputs are kept. Once the stack grows,
|
| 6360 |
+
use the paper's memory-efficient form:
|
| 6361 |
+
[model input, sum(intermediate outputs), last k outputs]
|
| 6362 |
+
so the GRN sees at most k+2 source tensors while preserving a direct
|
| 6363 |
+
path from the model input and the most recent layer outputs.
|
| 6364 |
+
"""
|
| 6365 |
+
k = int(getattr(self.config, "dca_past_layers_k", 2))
|
| 6366 |
+
if len(dca_sources) <= k + 2:
|
| 6367 |
+
selected = dca_sources
|
| 6368 |
+
else:
|
| 6369 |
+
intermediate = torch.stack(dca_sources[1:-k], dim=0).sum(dim=0)
|
| 6370 |
+
selected = [dca_sources[0], intermediate] + dca_sources[-k:]
|
| 6371 |
+
return torch.stack(selected, dim=0)
|
| 6372 |
+
|
| 6373 |
def _build_layer_analysis(self, layer_idx: int = 0) -> LayerAnalysis:
|
| 6374 |
"""
|
| 6375 |
Construct a LayerAnalysis with sub-objects pre-allocated for every
|
|
|
|
| 6409 |
gpas_attn = GPASAnalysis(),
|
| 6410 |
gpas_mlp = GPASAnalysis(),
|
| 6411 |
jtokm = JTokMAnalysis() if cfg.use_jtokm else None,
|
| 6412 |
+
dca = DCAAnalysis() if getattr(cfg, "use_dca", False) else None,
|
| 6413 |
attn_res = AttnResAnalysis() if getattr(cfg, "use_attn_res", False) else None,
|
| 6414 |
laurel = LAuReLAnalysis() if getattr(cfg, "use_laurel", False) else None,
|
| 6415 |
)
|
|
|
|
| 6548 |
else None
|
| 6549 |
)
|
| 6550 |
|
| 6551 |
+
# ── DeepCrossAttention source stack ────────────────────────────────
|
| 6552 |
+
# DCA keeps previous decoder outputs as a depth stack and each layer
|
| 6553 |
+
# selects [input, intermediate-sum, last-k] before its GRN-v3 q/k/v
|
| 6554 |
+
# composer. This is mutually exclusive with AttnRes, LAuReL and
|
| 6555 |
+
# StackMemory at config-validation time.
|
| 6556 |
+
use_dca = getattr(self.config, "use_dca", False)
|
| 6557 |
+
dca_sources = [hidden_states] if use_dca else None
|
| 6558 |
+
|
| 6559 |
# ── Attention Residuals state ──────────────────────────────────────
|
| 6560 |
# Full AttnRes (attn_res_num_blocks=0): sources grows by one entry per
|
| 6561 |
# decoder layer — all previous outputs are kept, max N=num_layers+1.
|
|
|
|
| 6610 |
hidden_states, stack_memory, stack_memory_mask
|
| 6611 |
)
|
| 6612 |
|
| 6613 |
+
dca_layer_sources = self._select_dca_sources(dca_sources) if use_dca else None
|
| 6614 |
+
|
| 6615 |
layer_outputs = decoder_layer(
|
| 6616 |
hidden_states,
|
| 6617 |
position_embeddings=position_embeddings,
|
|
|
|
| 6619 |
first_layer_fan=self.first_layer_fan,
|
| 6620 |
z_tilde=z_tilde,
|
| 6621 |
B_vals=B_vals,
|
| 6622 |
+
dca_sources=dca_layer_sources,
|
| 6623 |
attn_res_sources=attn_res_sources,
|
| 6624 |
attn_res_partial=attn_res_partial if use_attn_res else None,
|
| 6625 |
layer_analysis=layer_analysis,
|
|
|
|
| 6634 |
if use_attn_res:
|
| 6635 |
attn_res_partial = hidden_states
|
| 6636 |
|
| 6637 |
+
# Update DCA depth stack with the completed decoder block output.
|
| 6638 |
+
if use_dca:
|
| 6639 |
+
dca_sources = dca_sources + [hidden_states]
|
| 6640 |
+
|
| 6641 |
if output_attentions:
|
| 6642 |
all_attentions = all_attentions + (layer_outputs[1],)
|
| 6643 |
|
|
|
|
| 6984 |
"VersatileFFNAnalysis",
|
| 6985 |
"JTokMAnalysis",
|
| 6986 |
"AttnResAnalysis",
|
| 6987 |
+
"DCAAnalysis",
|
| 6988 |
+
"DeepCrossAttentionComposer",
|
| 6989 |
+
"DCAInputGRN",
|
| 6990 |
"GeneratorAnalysis",
|
| 6991 |
"IHAAnalysis",
|
| 6992 |
]
|