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 +313 -51
modeling_neollm.py
CHANGED
|
@@ -5,7 +5,8 @@ full attention augmented with optional Momentum, MEA, and LUCID operators,
|
|
| 5 |
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
|
|
|
|
| 9 |
Re-Positioning (Li et al., 2026), optional REPO-GRAPE contextual group
|
| 10 |
positioning (Li et al., 2026 + Zhang et al., 2026), optional GOAT-style
|
| 11 |
factorised attention log-priors (Litman & Guo, 2026), and optional StackMemory
|
|
@@ -58,6 +59,8 @@ References:
|
|
| 58 |
Axis of Scaling Law via Joint Token Self-Modulation." arXiv:2602.00800.
|
| 59 |
Spelling Bee Embeddings: Rabe, Clymo & Dong (2026). "Spelling Bee
|
| 60 |
Embeddings for Language Modeling." arXiv:2601.18030.
|
|
|
|
|
|
|
| 61 |
Context Re-Positioning: Li, Zhao, Cai & Sproat (2026). "REPO: Language
|
| 62 |
Models with Context Re-Positioning." arXiv:2512.14391.
|
| 63 |
GRAPE: Zhang et al. (2026). "Group Representational Position Encoding."
|
|
@@ -603,6 +606,8 @@ class AnalysisState:
|
|
| 603 |
.input_ids — original input token ids
|
| 604 |
.embeddings — token embeddings entering the decoder stack
|
| 605 |
.final_hidden_states — post-norm output entering lm_head
|
|
|
|
|
|
|
| 606 |
.generator — LeviathanGenerator internals (use_token_generator only)
|
| 607 |
.layers[i] — per-layer LayerAnalysis, indexed by layer_idx
|
| 608 |
.jtokm_aux_stats — raw per-layer load-balancing tuples (use_jtokm only)
|
|
@@ -633,6 +638,8 @@ class AnalysisState:
|
|
| 633 |
input_ids: Optional[torch.Tensor] = None
|
| 634 |
embeddings: Optional[torch.Tensor] = None
|
| 635 |
final_hidden_states: Optional[torch.Tensor] = None
|
|
|
|
|
|
|
| 636 |
|
| 637 |
generator: Optional[GeneratorAnalysis] = None
|
| 638 |
layers: Optional[List[LayerAnalysis]] = None
|
|
@@ -5498,6 +5505,38 @@ class NeoLLMDecoderLayer(GradientCheckpointingLayer):
|
|
| 5498 |
self.gpas_mlp = GPAS(config.hidden_size)
|
| 5499 |
self.current_layer_fan = None
|
| 5500 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5501 |
# ── StackMemory / STACKTRANS (Zhang et al., NeurIPS 2025) ────────
|
| 5502 |
# Optional differentiable hidden-state stack inserted between
|
| 5503 |
# Transformer layers. The stack is applied before this layer's
|
|
@@ -5601,6 +5640,25 @@ class NeoLLMDecoderLayer(GradientCheckpointingLayer):
|
|
| 5601 |
self.laurel_lr_A_mlp = None
|
| 5602 |
self.laurel_lr_B_mlp = None
|
| 5603 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5604 |
def apply_stack_memory(
|
| 5605 |
self,
|
| 5606 |
hidden_states: torch.Tensor,
|
|
@@ -5765,12 +5823,19 @@ class NeoLLMDecoderLayer(GradientCheckpointingLayer):
|
|
| 5765 |
output_attentions: Optional[bool] = False,
|
| 5766 |
repo_rope_args: Optional[Tuple[torch.Tensor, float]] = None,
|
| 5767 |
position_ids: Optional[torch.LongTensor] = None,
|
|
|
|
| 5768 |
**kwargs: Unpack[FlashAttentionKwargs],
|
| 5769 |
) -> Tuple:
|
| 5770 |
# ── Snapshot input ────────────────────────────────────────────────
|
| 5771 |
if layer_analysis is not None:
|
| 5772 |
layer_analysis.hidden_states_input = hidden_states.detach()
|
| 5773 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5774 |
# ── Attention Residuals: compute pre-attention input ──────────────
|
| 5775 |
# When active, the input to the attention sublayer is no longer the
|
| 5776 |
# raw hidden_states (accumulated residual) but a softmax-weighted
|
|
@@ -5803,6 +5868,18 @@ class NeoLLMDecoderLayer(GradientCheckpointingLayer):
|
|
| 5803 |
dca_k_input = None
|
| 5804 |
dca_v_input = None
|
| 5805 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5806 |
# ── Attention block ───────────────────────────────────────────────
|
| 5807 |
sn_pre = layer_analysis.seednorm_pre_attn if layer_analysis is not None else None
|
| 5808 |
|
|
@@ -5813,16 +5890,16 @@ class NeoLLMDecoderLayer(GradientCheckpointingLayer):
|
|
| 5813 |
# layer_idx > 0: keep the standard pre-norm Transformer flow exactly
|
| 5814 |
# as before.
|
| 5815 |
if self.input_layernorm is None:
|
| 5816 |
-
h_normed =
|
| 5817 |
if sn_pre is not None:
|
| 5818 |
# Analysis compatibility: mark the bypass as the observed
|
| 5819 |
# output without fabricating SeeDNorm internal gates/scales.
|
| 5820 |
-
sn_pre.output =
|
| 5821 |
if dca_k_input is not None:
|
| 5822 |
k_normed = dca_k_input
|
| 5823 |
v_normed = dca_v_input
|
| 5824 |
else:
|
| 5825 |
-
h_normed = _apply_norm(self.input_layernorm,
|
| 5826 |
if dca_k_input is not None:
|
| 5827 |
# DCA follows the paper's three independently-composed Q/K/V
|
| 5828 |
# streams while preserving NeoLLM's pre-norm convention by
|
|
@@ -5859,7 +5936,15 @@ class NeoLLMDecoderLayer(GradientCheckpointingLayer):
|
|
| 5859 |
# (attn_out + q_input), but the decoder block output later keeps the
|
| 5860 |
# attention branch as the residual base (ff_out + attn_out). Standard
|
| 5861 |
# and LAuReL paths remain unchanged when DCA is inactive.
|
| 5862 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5863 |
attn_aug = self._laurel_residual(
|
| 5864 |
residual_attn, hidden_states,
|
| 5865 |
self.laurel_rw_attn, self.laurel_lr_A_attn, self.laurel_lr_B_attn,
|
|
@@ -5889,9 +5974,19 @@ class NeoLLMDecoderLayer(GradientCheckpointingLayer):
|
|
| 5889 |
h_mlp = h_tilde
|
| 5890 |
residual_mlp = dca_final_residual if dca_final_residual is not None else h_tilde
|
| 5891 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5892 |
# ── MLP block ─────────────────────────────────────────────────────
|
| 5893 |
sn_post = layer_analysis.seednorm_post_attn if layer_analysis is not None else None
|
| 5894 |
-
h_normed2 = _apply_norm(self.post_attention_layernorm,
|
| 5895 |
h_lns2 = self.lns_mlp(h_normed2)
|
| 5896 |
if layer_analysis is not None:
|
| 5897 |
layer_analysis.lns_mlp_output = h_lns2.detach()
|
|
@@ -5933,17 +6028,29 @@ class NeoLLMDecoderLayer(GradientCheckpointingLayer):
|
|
| 5933 |
jtokm_a = layer_analysis.jtokm if layer_analysis is not None else None
|
| 5934 |
delta_r, aux_stats = self.jtokm(h_flat, z_flat, B_flat, analysis=jtokm_a)
|
| 5935 |
delta_r = delta_r.reshape(orig_shape)
|
| 5936 |
-
|
| 5937 |
-
gpas_mlp_a = layer_analysis.gpas_mlp if layer_analysis is not None else None
|
| 5938 |
-
hidden_states = self.gpas_mlp(mlp_aug + delta_r, analysis=gpas_mlp_a)
|
| 5939 |
else:
|
| 5940 |
-
|
| 5941 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5942 |
|
| 5943 |
if layer_analysis is not None:
|
| 5944 |
layer_analysis.hidden_states_output = hidden_states.detach()
|
| 5945 |
|
| 5946 |
outputs = (hidden_states,)
|
|
|
|
|
|
|
| 5947 |
if output_attentions:
|
| 5948 |
outputs += (attn_weights,)
|
| 5949 |
if aux_stats is not None:
|
|
@@ -6133,6 +6240,33 @@ class SpellingBeeEmbedding(nn.Module):
|
|
| 6133 |
dim=-1,
|
| 6134 |
) # [256, MAX_BYTES, d]
|
| 6135 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6136 |
# ── Forward ───────────────────────────────────────────────────────────────
|
| 6137 |
|
| 6138 |
def forward(
|
|
@@ -6147,35 +6281,11 @@ class SpellingBeeEmbedding(nn.Module):
|
|
| 6147 |
Returns:
|
| 6148 |
Spelling bee embeddings — same shape as token_embeds.
|
| 6149 |
"""
|
| 6150 |
-
# ── Step 1: build
|
| 6151 |
-
#
|
| 6152 |
-
|
| 6153 |
-
|
| 6154 |
-
# ── Step 2: build e_chars over vocab types, not occurrences ────────
|
| 6155 |
-
# token_bytes [V, MAX_BYTES]: byte value at each position per token.
|
| 6156 |
-
# pos_idx [MAX_BYTES]: column selector 0..MAX_BYTES-1.
|
| 6157 |
-
# rope_bytes[token_bytes, pos_idx[None, :], :] selects, for each
|
| 6158 |
-
# vocab token and each position, the RoPE-rotated embedding of that
|
| 6159 |
-
# byte at that position. Result [V, MAX_BYTES, d], then sum → [V, d].
|
| 6160 |
-
e_chars_vocab = rope_bytes[
|
| 6161 |
-
self.token_bytes, # [V, MAX_BYTES] — row index
|
| 6162 |
-
torch.arange(self.MAX_BYTES, device=rope_bytes.device), # [MAX_BYTES] — col index
|
| 6163 |
-
].sum(1) # [V, d]
|
| 6164 |
-
|
| 6165 |
-
# ── Step 3: apply precomputed 1/√byte_len per vocab type ────────────
|
| 6166 |
-
# No sqrt or division in the hot path — pure multiply.
|
| 6167 |
-
e_chars_vocab = e_chars_vocab * self.inv_sqrt_lens.unsqueeze(-1) # [V, d]
|
| 6168 |
-
|
| 6169 |
-
# ── Step 3b: LayerNorm over character embeddings (float32 for stability)
|
| 6170 |
-
# Mirrors reference impl (character_norm=True). Ensures E[‖e_chars‖²]
|
| 6171 |
-
# matches E[‖e_tok‖²] regardless of token byte-length distribution.
|
| 6172 |
-
e_chars_vocab = self.char_norm(e_chars_vocab.to(self.char_norm.weight.dtype)).to(token_embeds.dtype)
|
| 6173 |
-
|
| 6174 |
-
# ── Step 4: gather only the tokens present in this batch ────────────
|
| 6175 |
-
# This is the only B×S operation — a single embedding lookup.
|
| 6176 |
-
e_chars = e_chars_vocab[token_ids] # [B, S, d] or [N, d]
|
| 6177 |
|
| 6178 |
-
# ── Step
|
| 6179 |
return (token_embeds + e_chars) * 0.5
|
| 6180 |
|
| 6181 |
# ── Inference utility ─────────────────────────────────────────────────────
|
|
@@ -6206,13 +6316,111 @@ class SpellingBeeEmbedding(nn.Module):
|
|
| 6206 |
# Optionally free byte_emb parameters:
|
| 6207 |
# del model.model.spelling_bee
|
| 6208 |
"""
|
| 6209 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6210 |
e_chars_vocab = rope_bytes[
|
| 6211 |
-
|
| 6212 |
torch.arange(self.MAX_BYTES, device=rope_bytes.device),
|
| 6213 |
-
].sum(1) *
|
| 6214 |
-
e_chars_vocab = self.char_norm(
|
| 6215 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6216 |
|
| 6217 |
|
| 6218 |
class NeoLLMPreTrainedModel(PreTrainedModel):
|
|
@@ -6387,10 +6595,10 @@ class NeoLLMPreTrainedModel(PreTrainedModel):
|
|
| 6387 |
module.attn_res_query_attn.data.zero_()
|
| 6388 |
module.attn_res_query_mlp.data.zero_()
|
| 6389 |
|
| 6390 |
-
elif isinstance(module, SpellingBeeEmbedding):
|
| 6391 |
# byte_emb initialised identically to token embeddings: std=1/√d.
|
| 6392 |
-
# Ensures E[‖e_byte‖²] ≈ 1 at init, matching etok
|
| 6393 |
-
#
|
| 6394 |
d = module.byte_emb.embedding_dim
|
| 6395 |
nn.init.normal_(module.byte_emb.weight, mean=0.0, std=1.0 / math.sqrt(d))
|
| 6396 |
|
|
@@ -6429,6 +6637,13 @@ class NeoLLMModel(NeoLLMPreTrainedModel):
|
|
| 6429 |
|
| 6430 |
Setup: call ``model.model.spelling_bee.set_byte_table(tokenizer)``
|
| 6431 |
once after model init and before training (and after any .to(device)).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6432 |
"""
|
| 6433 |
|
| 6434 |
def __init__(self, config: NeoLLMConfig):
|
|
@@ -6464,6 +6679,17 @@ class NeoLLMModel(NeoLLMPreTrainedModel):
|
|
| 6464 |
else:
|
| 6465 |
self.spelling_bee = None
|
| 6466 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6467 |
self.layers = nn.ModuleList(
|
| 6468 |
[NeoLLMDecoderLayer(config, layer_idx)
|
| 6469 |
for layer_idx in range(config.num_hidden_layers)]
|
|
@@ -6635,11 +6861,36 @@ class NeoLLMModel(NeoLLMPreTrainedModel):
|
|
| 6635 |
# input_ids may be None when inputs_embeds was passed directly by the
|
| 6636 |
# caller; in that case SBE cannot run (no token_ids available) and is
|
| 6637 |
# silently skipped — consistent with the standard embedding bypass path.
|
|
|
|
| 6638 |
if self.spelling_bee is not None and input_ids is not None:
|
| 6639 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6640 |
|
| 6641 |
if analysis_state is not None:
|
| 6642 |
analysis_state.embeddings = inputs_embeds.detach()
|
|
|
|
|
|
|
|
|
|
| 6643 |
|
| 6644 |
if position_ids is None:
|
| 6645 |
position_ids = torch.arange(
|
|
@@ -6784,9 +7035,14 @@ class NeoLLMModel(NeoLLMPreTrainedModel):
|
|
| 6784 |
output_attentions=output_attentions,
|
| 6785 |
repo_rope_args=repo_rope_args,
|
| 6786 |
position_ids=position_ids,
|
|
|
|
| 6787 |
**kwargs,
|
| 6788 |
)
|
| 6789 |
hidden_states = layer_outputs[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6790 |
|
| 6791 |
# Update AttnRes partial sum — the new partial is the layer output
|
| 6792 |
if use_attn_res:
|
|
@@ -6796,17 +7052,19 @@ class NeoLLMModel(NeoLLMPreTrainedModel):
|
|
| 6796 |
if use_dca:
|
| 6797 |
dca_sources = dca_sources + [hidden_states]
|
| 6798 |
|
|
|
|
| 6799 |
if output_attentions:
|
| 6800 |
-
all_attentions = all_attentions + (layer_outputs[
|
|
|
|
| 6801 |
|
| 6802 |
# Collect JTok-M aux stats (last element if present)
|
| 6803 |
-
if self.config.use_jtokm and len(layer_outputs) >
|
| 6804 |
all_aux_stats.append(layer_outputs[-1])
|
| 6805 |
|
| 6806 |
# Collect VersatileFFN aux stats (second-to-last if jtokm also present,
|
| 6807 |
# or last if jtokm is absent). Only non-None during training.
|
| 6808 |
if getattr(self.config, "use_versatile_ffn", False):
|
| 6809 |
-
for item in layer_outputs[
|
| 6810 |
if isinstance(item, tuple) and len(item) == 3:
|
| 6811 |
# (p_sum, f_sum, N_tokens) signature
|
| 6812 |
all_aux_stats.append(("versatile", item))
|
|
@@ -6825,6 +7083,9 @@ class NeoLLMModel(NeoLLMPreTrainedModel):
|
|
| 6825 |
# ── Finalise analysis snapshot ─────────────────────────────────────
|
| 6826 |
if analysis_state is not None:
|
| 6827 |
analysis_state.final_hidden_states = hidden_states.detach()
|
|
|
|
|
|
|
|
|
|
| 6828 |
analysis_state.jtokm_aux_stats = all_aux_stats if self.config.use_jtokm else None
|
| 6829 |
analysis_state.attn_res_sources_final = (
|
| 6830 |
attn_res_sources if use_attn_res else None
|
|
@@ -7113,6 +7374,7 @@ __all__ = [
|
|
| 7113 |
"LeviathanGenerator",
|
| 7114 |
"LeviathanJTokM",
|
| 7115 |
"SpellingBeeEmbedding",
|
|
|
|
| 7116 |
"StackMemory",
|
| 7117 |
"FANLayer",
|
| 7118 |
"SeeDNorm",
|
|
|
|
| 5 |
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
|
| 9 |
+
YuriiFormer × Spelling Bee velocity seeding (Zimin et al., 2026), optional Context
|
| 10 |
Re-Positioning (Li et al., 2026), optional REPO-GRAPE contextual group
|
| 11 |
positioning (Li et al., 2026 + Zhang et al., 2026), optional GOAT-style
|
| 12 |
factorised attention log-priors (Litman & Guo, 2026), and optional StackMemory
|
|
|
|
| 59 |
Axis of Scaling Law via Joint Token Self-Modulation." arXiv:2602.00800.
|
| 60 |
Spelling Bee Embeddings: Rabe, Clymo & Dong (2026). "Spelling Bee
|
| 61 |
Embeddings for Language Modeling." arXiv:2601.18030.
|
| 62 |
+
YuriiFormer: Zimin, Polyanskiy & Rigollet (2026). "YuriiFormer:
|
| 63 |
+
A Suite of Nesterov-Accelerated Transformers." arXiv:2601.23236.
|
| 64 |
Context Re-Positioning: Li, Zhao, Cai & Sproat (2026). "REPO: Language
|
| 65 |
Models with Context Re-Positioning." arXiv:2512.14391.
|
| 66 |
GRAPE: Zhang et al. (2026). "Group Representational Position Encoding."
|
|
|
|
| 606 |
.input_ids — original input token ids
|
| 607 |
.embeddings — token embeddings entering the decoder stack
|
| 608 |
.final_hidden_states — post-norm output entering lm_head
|
| 609 |
+
.yurii_initial_velocity — V0 spelling velocity seed (when active)
|
| 610 |
+
.yurii_final_velocity — final velocity VL after decoder stack
|
| 611 |
.generator — LeviathanGenerator internals (use_token_generator only)
|
| 612 |
.layers[i] — per-layer LayerAnalysis, indexed by layer_idx
|
| 613 |
.jtokm_aux_stats — raw per-layer load-balancing tuples (use_jtokm only)
|
|
|
|
| 638 |
input_ids: Optional[torch.Tensor] = None
|
| 639 |
embeddings: Optional[torch.Tensor] = None
|
| 640 |
final_hidden_states: Optional[torch.Tensor] = None
|
| 641 |
+
yurii_initial_velocity: Optional[torch.Tensor] = None
|
| 642 |
+
yurii_final_velocity: Optional[torch.Tensor] = None
|
| 643 |
|
| 644 |
generator: Optional[GeneratorAnalysis] = None
|
| 645 |
layers: Optional[List[LayerAnalysis]] = None
|
|
|
|
| 5505 |
self.gpas_mlp = GPAS(config.hidden_size)
|
| 5506 |
self.current_layer_fan = None
|
| 5507 |
|
| 5508 |
+
# ── YuriiFormer × Spelling Bee velocity update ───────────────────
|
| 5509 |
+
# Cheap Nesterov + Lie--Trotter variant: same Attn/MLP oracle count as
|
| 5510 |
+
# the standard block, plus one threaded velocity state V_l. Scalars are
|
| 5511 |
+
# learned per layer and constrained at forward time.
|
| 5512 |
+
self.use_yurii_spelling_velocity = bool(
|
| 5513 |
+
getattr(config, "use_yurii_spelling_velocity", False)
|
| 5514 |
+
)
|
| 5515 |
+
if self.use_yurii_spelling_velocity:
|
| 5516 |
+
def _logit(p: float) -> float:
|
| 5517 |
+
p = min(max(float(p), 1e-6), 1.0 - 1e-6)
|
| 5518 |
+
return math.log(p / (1.0 - p))
|
| 5519 |
+
def _inv_softplus(x: float) -> float:
|
| 5520 |
+
x = max(float(x), 1e-6)
|
| 5521 |
+
return math.log(math.expm1(x))
|
| 5522 |
+
|
| 5523 |
+
mu0 = getattr(config, "yurii_mu_init", 0.50)
|
| 5524 |
+
beta0 = getattr(config, "yurii_beta_init", 0.90)
|
| 5525 |
+
gamma0 = getattr(config, "yurii_gamma_init", 1.00)
|
| 5526 |
+
self.yurii_mu_attn_raw = nn.Parameter(torch.tensor(_logit(mu0), dtype=torch.float32))
|
| 5527 |
+
self.yurii_beta_attn_raw = nn.Parameter(torch.tensor(_logit(beta0), dtype=torch.float32))
|
| 5528 |
+
self.yurii_gamma_attn_raw = nn.Parameter(torch.tensor(_inv_softplus(gamma0), dtype=torch.float32))
|
| 5529 |
+
self.yurii_mu_mlp_raw = nn.Parameter(torch.tensor(_logit(mu0), dtype=torch.float32))
|
| 5530 |
+
self.yurii_beta_mlp_raw = nn.Parameter(torch.tensor(_logit(beta0), dtype=torch.float32))
|
| 5531 |
+
self.yurii_gamma_mlp_raw = nn.Parameter(torch.tensor(_inv_softplus(gamma0), dtype=torch.float32))
|
| 5532 |
+
self.yurii_velocity_norm_attn = nn.LayerNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 5533 |
+
self.yurii_velocity_norm_mlp = nn.LayerNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 5534 |
+
else:
|
| 5535 |
+
self.yurii_mu_attn_raw = self.yurii_beta_attn_raw = self.yurii_gamma_attn_raw = None
|
| 5536 |
+
self.yurii_mu_mlp_raw = self.yurii_beta_mlp_raw = self.yurii_gamma_mlp_raw = None
|
| 5537 |
+
self.yurii_velocity_norm_attn = None
|
| 5538 |
+
self.yurii_velocity_norm_mlp = None
|
| 5539 |
+
|
| 5540 |
# ── StackMemory / STACKTRANS (Zhang et al., NeurIPS 2025) ────────
|
| 5541 |
# Optional differentiable hidden-state stack inserted between
|
| 5542 |
# Transformer layers. The stack is applied before this layer's
|
|
|
|
| 5640 |
self.laurel_lr_A_mlp = None
|
| 5641 |
self.laurel_lr_B_mlp = None
|
| 5642 |
|
| 5643 |
+
def _yurii_coefficients(self, slot: str, dtype: torch.dtype, device: torch.device):
|
| 5644 |
+
"""Return constrained YuriiFormer scalars for one substep."""
|
| 5645 |
+
if slot == "attn":
|
| 5646 |
+
mu_raw, beta_raw, gamma_raw = (
|
| 5647 |
+
self.yurii_mu_attn_raw,
|
| 5648 |
+
self.yurii_beta_attn_raw,
|
| 5649 |
+
self.yurii_gamma_attn_raw,
|
| 5650 |
+
)
|
| 5651 |
+
else:
|
| 5652 |
+
mu_raw, beta_raw, gamma_raw = (
|
| 5653 |
+
self.yurii_mu_mlp_raw,
|
| 5654 |
+
self.yurii_beta_mlp_raw,
|
| 5655 |
+
self.yurii_gamma_mlp_raw,
|
| 5656 |
+
)
|
| 5657 |
+
mu = torch.sigmoid(mu_raw).to(device=device, dtype=dtype)
|
| 5658 |
+
beta = torch.sigmoid(beta_raw).to(device=device, dtype=dtype)
|
| 5659 |
+
gamma = F.softplus(gamma_raw).to(device=device, dtype=dtype)
|
| 5660 |
+
return mu, beta, gamma
|
| 5661 |
+
|
| 5662 |
def apply_stack_memory(
|
| 5663 |
self,
|
| 5664 |
hidden_states: torch.Tensor,
|
|
|
|
| 5823 |
output_attentions: Optional[bool] = False,
|
| 5824 |
repo_rope_args: Optional[Tuple[torch.Tensor, float]] = None,
|
| 5825 |
position_ids: Optional[torch.LongTensor] = None,
|
| 5826 |
+
yurii_velocity: Optional[torch.Tensor] = None,
|
| 5827 |
**kwargs: Unpack[FlashAttentionKwargs],
|
| 5828 |
) -> Tuple:
|
| 5829 |
# ── Snapshot input ────────────────────────────────────────────────
|
| 5830 |
if layer_analysis is not None:
|
| 5831 |
layer_analysis.hidden_states_input = hidden_states.detach()
|
| 5832 |
|
| 5833 |
+
use_yurii = (
|
| 5834 |
+
self.use_yurii_spelling_velocity
|
| 5835 |
+
and yurii_velocity is not None
|
| 5836 |
+
)
|
| 5837 |
+
yurii_velocity_next = None
|
| 5838 |
+
|
| 5839 |
# ── Attention Residuals: compute pre-attention input ──────────────
|
| 5840 |
# When active, the input to the attention sublayer is no longer the
|
| 5841 |
# raw hidden_states (accumulated residual) but a softmax-weighted
|
|
|
|
| 5868 |
dca_k_input = None
|
| 5869 |
dca_v_input = None
|
| 5870 |
|
| 5871 |
+
# ── YuriiFormer attention lookahead ───────────────────────────────
|
| 5872 |
+
# Nesterov step: X_in = X + μ_a V. Only the oracle input is shifted;
|
| 5873 |
+
# the state update below still uses residual_attn as X.
|
| 5874 |
+
if use_yurii:
|
| 5875 |
+
mu_a, beta_a, gamma_a = self._yurii_coefficients(
|
| 5876 |
+
"attn", h_attn.dtype, h_attn.device
|
| 5877 |
+
)
|
| 5878 |
+
h_attn_oracle = h_attn + mu_a * yurii_velocity
|
| 5879 |
+
else:
|
| 5880 |
+
beta_a = gamma_a = None
|
| 5881 |
+
h_attn_oracle = h_attn
|
| 5882 |
+
|
| 5883 |
# ── Attention block ───────────────────────────────────────────────
|
| 5884 |
sn_pre = layer_analysis.seednorm_pre_attn if layer_analysis is not None else None
|
| 5885 |
|
|
|
|
| 5890 |
# layer_idx > 0: keep the standard pre-norm Transformer flow exactly
|
| 5891 |
# as before.
|
| 5892 |
if self.input_layernorm is None:
|
| 5893 |
+
h_normed = h_attn_oracle
|
| 5894 |
if sn_pre is not None:
|
| 5895 |
# Analysis compatibility: mark the bypass as the observed
|
| 5896 |
# output without fabricating SeeDNorm internal gates/scales.
|
| 5897 |
+
sn_pre.output = h_attn_oracle.detach()
|
| 5898 |
if dca_k_input is not None:
|
| 5899 |
k_normed = dca_k_input
|
| 5900 |
v_normed = dca_v_input
|
| 5901 |
else:
|
| 5902 |
+
h_normed = _apply_norm(self.input_layernorm, h_attn_oracle, analysis=sn_pre)
|
| 5903 |
if dca_k_input is not None:
|
| 5904 |
# DCA follows the paper's three independently-composed Q/K/V
|
| 5905 |
# streams while preserving NeoLLM's pre-norm convention by
|
|
|
|
| 5936 |
# (attn_out + q_input), but the decoder block output later keeps the
|
| 5937 |
# attention branch as the residual base (ff_out + attn_out). Standard
|
| 5938 |
# and LAuReL paths remain unchanged when DCA is inactive.
|
| 5939 |
+
if use_yurii:
|
| 5940 |
+
# V_{l+1/2} = LNv(β_a V_l + γ_a Attn_l(X_l + μ_a V_l))
|
| 5941 |
+
# X_{l+1/2} = X_l + V_{l+1/2}
|
| 5942 |
+
yurii_velocity_half = self.yurii_velocity_norm_attn(
|
| 5943 |
+
beta_a * yurii_velocity + gamma_a * hidden_states
|
| 5944 |
+
)
|
| 5945 |
+
attn_aug = residual_attn + yurii_velocity_half
|
| 5946 |
+
dca_final_residual = None
|
| 5947 |
+
elif self.use_laurel:
|
| 5948 |
attn_aug = self._laurel_residual(
|
| 5949 |
residual_attn, hidden_states,
|
| 5950 |
self.laurel_rw_attn, self.laurel_lr_A_attn, self.laurel_lr_B_attn,
|
|
|
|
| 5974 |
h_mlp = h_tilde
|
| 5975 |
residual_mlp = dca_final_residual if dca_final_residual is not None else h_tilde
|
| 5976 |
|
| 5977 |
+
# ── YuriiFormer MLP lookahead ───────────────────────────────────
|
| 5978 |
+
if use_yurii:
|
| 5979 |
+
mu_m, beta_m, gamma_m = self._yurii_coefficients(
|
| 5980 |
+
"mlp", h_mlp.dtype, h_mlp.device
|
| 5981 |
+
)
|
| 5982 |
+
h_mlp_oracle = h_mlp + mu_m * yurii_velocity_half
|
| 5983 |
+
else:
|
| 5984 |
+
beta_m = gamma_m = None
|
| 5985 |
+
h_mlp_oracle = h_mlp
|
| 5986 |
+
|
| 5987 |
# ── MLP block ─────────────────────────────────────────────────────
|
| 5988 |
sn_post = layer_analysis.seednorm_post_attn if layer_analysis is not None else None
|
| 5989 |
+
h_normed2 = _apply_norm(self.post_attention_layernorm, h_mlp_oracle, analysis=sn_post)
|
| 5990 |
h_lns2 = self.lns_mlp(h_normed2)
|
| 5991 |
if layer_analysis is not None:
|
| 5992 |
layer_analysis.lns_mlp_output = h_lns2.detach()
|
|
|
|
| 6028 |
jtokm_a = layer_analysis.jtokm if layer_analysis is not None else None
|
| 6029 |
delta_r, aux_stats = self.jtokm(h_flat, z_flat, B_flat, analysis=jtokm_a)
|
| 6030 |
delta_r = delta_r.reshape(orig_shape)
|
|
|
|
|
|
|
|
|
|
| 6031 |
else:
|
| 6032 |
+
delta_r = None
|
| 6033 |
+
|
| 6034 |
+
gpas_mlp_a = layer_analysis.gpas_mlp if layer_analysis is not None else None
|
| 6035 |
+
if use_yurii:
|
| 6036 |
+
# Treat JTok-M, when active, as an additive MLP-side oracle term.
|
| 6037 |
+
mlp_oracle = delta_m if delta_r is None else (delta_m + delta_r)
|
| 6038 |
+
yurii_velocity_next = self.yurii_velocity_norm_mlp(
|
| 6039 |
+
beta_m * yurii_velocity_half + gamma_m * mlp_oracle
|
| 6040 |
+
)
|
| 6041 |
+
hidden_states = self.gpas_mlp(h_tilde + yurii_velocity_next, analysis=gpas_mlp_a)
|
| 6042 |
+
else:
|
| 6043 |
+
if delta_r is not None:
|
| 6044 |
+
hidden_states = self.gpas_mlp(mlp_aug + delta_r, analysis=gpas_mlp_a)
|
| 6045 |
+
else:
|
| 6046 |
+
hidden_states = self.gpas_mlp(mlp_aug, analysis=gpas_mlp_a)
|
| 6047 |
|
| 6048 |
if layer_analysis is not None:
|
| 6049 |
layer_analysis.hidden_states_output = hidden_states.detach()
|
| 6050 |
|
| 6051 |
outputs = (hidden_states,)
|
| 6052 |
+
if use_yurii:
|
| 6053 |
+
outputs += (yurii_velocity_next,)
|
| 6054 |
if output_attentions:
|
| 6055 |
outputs += (attn_weights,)
|
| 6056 |
if aux_stats is not None:
|
|
|
|
| 6240 |
dim=-1,
|
| 6241 |
) # [256, MAX_BYTES, d]
|
| 6242 |
|
| 6243 |
+
def build_char_vocab(self, dtype: Optional[torch.dtype] = None) -> torch.Tensor:
|
| 6244 |
+
"""
|
| 6245 |
+
Build the original Spelling Bee character table ``S_x`` for all vocab ids.
|
| 6246 |
+
|
| 6247 |
+
Formula preserved from Rabe, Clymo & Dong (2026):
|
| 6248 |
+
S_x(t) = inv_sqrt_len(t) · Σ_i RoPE(B_x[b_i(t)], i)
|
| 6249 |
+
|
| 6250 |
+
This helper exists so the YuriiFormer velocity branch can reuse the
|
| 6251 |
+
original spelling table without duplicating or replacing the original
|
| 6252 |
+
Spelling Bee formula.
|
| 6253 |
+
"""
|
| 6254 |
+
rope_bytes = self._build_rope_bytes() # [256, MAX_BYTES, d]
|
| 6255 |
+
e_chars_vocab = rope_bytes[
|
| 6256 |
+
self.token_bytes,
|
| 6257 |
+
torch.arange(self.MAX_BYTES, device=rope_bytes.device),
|
| 6258 |
+
].sum(1) * self.inv_sqrt_lens.unsqueeze(-1) # [V, d]
|
| 6259 |
+
e_chars_vocab = self.char_norm(
|
| 6260 |
+
e_chars_vocab.to(self.char_norm.weight.dtype)
|
| 6261 |
+
)
|
| 6262 |
+
if dtype is not None:
|
| 6263 |
+
e_chars_vocab = e_chars_vocab.to(dtype)
|
| 6264 |
+
return e_chars_vocab
|
| 6265 |
+
|
| 6266 |
+
def chars(self, token_ids: torch.Tensor, dtype: Optional[torch.dtype] = None) -> torch.Tensor:
|
| 6267 |
+
"""Gather the original Spelling Bee character embedding ``S_x``."""
|
| 6268 |
+
return self.build_char_vocab(dtype=dtype)[token_ids]
|
| 6269 |
+
|
| 6270 |
# ── Forward ───────────────────────────────────────────────────────────────
|
| 6271 |
|
| 6272 |
def forward(
|
|
|
|
| 6281 |
Returns:
|
| 6282 |
Spelling bee embeddings — same shape as token_embeds.
|
| 6283 |
"""
|
| 6284 |
+
# ── Step 1: build and gather the original character summary S_x ──
|
| 6285 |
+
# Formula is unchanged: e_chars(t)=inv_sqrt_len(t)·Σ_i RoPE(B_x[b_i], i).
|
| 6286 |
+
e_chars = self.chars(token_ids, dtype=token_embeds.dtype) # [B,S,d] or [N,d]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6287 |
|
| 6288 |
+
# ── Step 2: mean with token embeddings ──────────────────────────────
|
| 6289 |
return (token_embeds + e_chars) * 0.5
|
| 6290 |
|
| 6291 |
# ── Inference utility ─────────────────────────────────────────────────────
|
|
|
|
| 6316 |
# Optionally free byte_emb parameters:
|
| 6317 |
# del model.model.spelling_bee
|
| 6318 |
"""
|
| 6319 |
+
e_chars_vocab = self.build_char_vocab(dtype=token_emb_weight.dtype)
|
| 6320 |
+
return (token_emb_weight + e_chars_vocab) * 0.5
|
| 6321 |
+
|
| 6322 |
+
|
| 6323 |
+
class YuriiSpellingBeeVelocityEmbedding(nn.Module):
|
| 6324 |
+
"""
|
| 6325 |
+
YuriiFormer × Spelling Bee velocity seed.
|
| 6326 |
+
|
| 6327 |
+
This module adds a cheap spelling-only velocity table for the
|
| 6328 |
+
Nesterov + Lie--Trotter YuriiFormer update while preserving the original
|
| 6329 |
+
Spelling Bee embedding formula.
|
| 6330 |
+
|
| 6331 |
+
Original Spelling Bee path, kept in ``SpellingBeeEmbedding``:
|
| 6332 |
+
|
| 6333 |
+
X_0(t) = 0.5 · (E_tok[t] + S_x(t))
|
| 6334 |
+
S_x(t) = inv_sqrt_len(t) · Σ_i RoPE(B_x[b_i(t)], i)
|
| 6335 |
+
|
| 6336 |
+
New velocity path:
|
| 6337 |
+
|
| 6338 |
+
S_v(t) = inv_sqrt_len(t) · Σ_i RoPE(B_v[b_i(t)], i)
|
| 6339 |
+
V_0(t) = λ_v · 0.5 · (S_x(t) + S_v(t))
|
| 6340 |
+
|
| 6341 |
+
Only ``B_v ∈ R^{256×d}`` is new. This replaces YuriiFormer's expensive
|
| 6342 |
+
full vocabulary velocity table ``V×d`` with a byte-level velocity seed.
|
| 6343 |
+
The byte table and length normalizer are reused from the original
|
| 6344 |
+
``SpellingBeeEmbedding`` instance, so training code only needs to call
|
| 6345 |
+
``model.model.spelling_bee.set_byte_table(tokenizer)`` as before.
|
| 6346 |
+
|
| 6347 |
+
References:
|
| 6348 |
+
Rabe, Clymo & Dong (2026). "Spelling Bee Embeddings for Language
|
| 6349 |
+
Modeling." arXiv:2601.18030.
|
| 6350 |
+
Zimin, Polyanskiy & Rigollet (2026). "YuriiFormer: A Suite of
|
| 6351 |
+
Nesterov-Accelerated Transformers." arXiv:2601.23236.
|
| 6352 |
+
"""
|
| 6353 |
+
|
| 6354 |
+
MAX_BYTES: int = 16
|
| 6355 |
+
|
| 6356 |
+
def __init__(self, config: "NeoLLMConfig"):
|
| 6357 |
+
super().__init__()
|
| 6358 |
+
d = config.hidden_size
|
| 6359 |
+
base = getattr(config, "rope_theta", 10000.0)
|
| 6360 |
+
self._rope_base = base
|
| 6361 |
+
self.byte_emb = nn.Embedding(256, d)
|
| 6362 |
+
self.char_norm = nn.LayerNorm(d)
|
| 6363 |
+
|
| 6364 |
+
def _build_rope_bytes(self) -> torch.Tensor:
|
| 6365 |
+
"""Build the static [256, MAX_BYTES, d] RoPE-encoded velocity-byte table."""
|
| 6366 |
+
w = self.byte_emb.weight
|
| 6367 |
+
half = w.shape[-1] // 2
|
| 6368 |
+
w1 = w[:, :half].unsqueeze(1)
|
| 6369 |
+
w2 = w[:, half:].unsqueeze(1)
|
| 6370 |
+
theta = 1.0 / (self._rope_base ** (
|
| 6371 |
+
torch.arange(0, half, dtype=torch.float32, device=w.device) * 2.0 / (half * 2)
|
| 6372 |
+
))
|
| 6373 |
+
pos = torch.arange(self.MAX_BYTES, dtype=torch.float32, device=w.device)
|
| 6374 |
+
freqs = torch.outer(pos, theta)
|
| 6375 |
+
cos = freqs.cos().to(w.dtype).unsqueeze(0)
|
| 6376 |
+
sin = freqs.sin().to(w.dtype).unsqueeze(0)
|
| 6377 |
+
return torch.cat(
|
| 6378 |
+
[w1 * cos - w2 * sin,
|
| 6379 |
+
w1 * sin + w2 * cos],
|
| 6380 |
+
dim=-1,
|
| 6381 |
+
)
|
| 6382 |
+
|
| 6383 |
+
def build_velocity_char_vocab(
|
| 6384 |
+
self,
|
| 6385 |
+
reference_spelling: SpellingBeeEmbedding,
|
| 6386 |
+
dtype: Optional[torch.dtype] = None,
|
| 6387 |
+
) -> torch.Tensor:
|
| 6388 |
+
"""Build the new spelling-velocity table ``S_v`` for every vocab id."""
|
| 6389 |
+
rope_bytes = self._build_rope_bytes()
|
| 6390 |
e_chars_vocab = rope_bytes[
|
| 6391 |
+
reference_spelling.token_bytes,
|
| 6392 |
torch.arange(self.MAX_BYTES, device=rope_bytes.device),
|
| 6393 |
+
].sum(1) * reference_spelling.inv_sqrt_lens.unsqueeze(-1)
|
| 6394 |
+
e_chars_vocab = self.char_norm(
|
| 6395 |
+
e_chars_vocab.to(self.char_norm.weight.dtype)
|
| 6396 |
+
)
|
| 6397 |
+
if dtype is not None:
|
| 6398 |
+
e_chars_vocab = e_chars_vocab.to(dtype)
|
| 6399 |
+
return e_chars_vocab
|
| 6400 |
+
|
| 6401 |
+
def forward(
|
| 6402 |
+
self,
|
| 6403 |
+
token_ids: torch.Tensor,
|
| 6404 |
+
reference_spelling: SpellingBeeEmbedding,
|
| 6405 |
+
dtype: Optional[torch.dtype] = None,
|
| 6406 |
+
reference_chars: Optional[torch.Tensor] = None,
|
| 6407 |
+
) -> torch.Tensor:
|
| 6408 |
+
"""
|
| 6409 |
+
Return ``0.5 · (S_x + S_v)`` gathered at ``token_ids``.
|
| 6410 |
+
|
| 6411 |
+
``S_x`` comes from the already-active Spelling Bee module and ``S_v``
|
| 6412 |
+
comes from this module's new byte table. When ``reference_chars`` is
|
| 6413 |
+
supplied by ``NeoLLMModel.forward``, the original SBE character summary
|
| 6414 |
+
is reused instead of recomputed, keeping the hot path cheap. The caller
|
| 6415 |
+
applies ``λ_v``.
|
| 6416 |
+
"""
|
| 6417 |
+
s_x = (
|
| 6418 |
+
reference_chars
|
| 6419 |
+
if reference_chars is not None
|
| 6420 |
+
else reference_spelling.chars(token_ids, dtype=dtype)
|
| 6421 |
+
)
|
| 6422 |
+
s_v = self.build_velocity_char_vocab(reference_spelling, dtype=dtype)[token_ids]
|
| 6423 |
+
return (s_x + s_v) * 0.5
|
| 6424 |
|
| 6425 |
|
| 6426 |
class NeoLLMPreTrainedModel(PreTrainedModel):
|
|
|
|
| 6595 |
module.attn_res_query_attn.data.zero_()
|
| 6596 |
module.attn_res_query_mlp.data.zero_()
|
| 6597 |
|
| 6598 |
+
elif isinstance(module, (SpellingBeeEmbedding, YuriiSpellingBeeVelocityEmbedding)):
|
| 6599 |
# byte_emb initialised identically to token embeddings: std=1/√d.
|
| 6600 |
+
# Ensures E[‖e_byte‖²] ≈ 1 at init, matching etok/spelling scale,
|
| 6601 |
+
# so α = sqrt(byte_len) is calibrated from step 0.
|
| 6602 |
d = module.byte_emb.embedding_dim
|
| 6603 |
nn.init.normal_(module.byte_emb.weight, mean=0.0, std=1.0 / math.sqrt(d))
|
| 6604 |
|
|
|
|
| 6637 |
|
| 6638 |
Setup: call ``model.model.spelling_bee.set_byte_table(tokenizer)``
|
| 6639 |
once after model init and before training (and after any .to(device)).
|
| 6640 |
+
|
| 6641 |
+
YuriiFormer × Spelling Bee velocity seed:
|
| 6642 |
+
When ``use_yurii_spelling_velocity=True``, the original SBE path still
|
| 6643 |
+
builds ``X_0 = 0.5·(E_tok + S_x)``. A second byte table builds ``S_v``
|
| 6644 |
+
and initializes ``V_0 = λ_v·0.5·(S_x + S_v)``. Decoder layers then use
|
| 6645 |
+
the Nesterov + Lie--Trotter update, the best OpenWebText loss variant in
|
| 6646 |
+
YuriiFormer while keeping the same one-attention/one-MLP oracle count.
|
| 6647 |
"""
|
| 6648 |
|
| 6649 |
def __init__(self, config: NeoLLMConfig):
|
|
|
|
| 6679 |
else:
|
| 6680 |
self.spelling_bee = None
|
| 6681 |
|
| 6682 |
+
use_yurii_spell_v = bool(getattr(config, "use_yurii_spelling_velocity", False))
|
| 6683 |
+
if use_yurii_spell_v:
|
| 6684 |
+
if self.spelling_bee is None:
|
| 6685 |
+
raise ValueError(
|
| 6686 |
+
"`use_yurii_spelling_velocity=True` requires an active "
|
| 6687 |
+
"SpellingBeeEmbedding instance. Set `use_spelling_bee_embeddings=True`."
|
| 6688 |
+
)
|
| 6689 |
+
self.yurii_spelling_velocity = YuriiSpellingBeeVelocityEmbedding(config)
|
| 6690 |
+
else:
|
| 6691 |
+
self.yurii_spelling_velocity = None
|
| 6692 |
+
|
| 6693 |
self.layers = nn.ModuleList(
|
| 6694 |
[NeoLLMDecoderLayer(config, layer_idx)
|
| 6695 |
for layer_idx in range(config.num_hidden_layers)]
|
|
|
|
| 6861 |
# input_ids may be None when inputs_embeds was passed directly by the
|
| 6862 |
# caller; in that case SBE cannot run (no token_ids available) and is
|
| 6863 |
# silently skipped — consistent with the standard embedding bypass path.
|
| 6864 |
+
sbe_chars = None
|
| 6865 |
if self.spelling_bee is not None and input_ids is not None:
|
| 6866 |
+
if self.yurii_spelling_velocity is not None:
|
| 6867 |
+
# Build S_x once and reuse it for both formulas:
|
| 6868 |
+
# X0 = 0.5 · (E_tok + S_x)
|
| 6869 |
+
# V0 = λ_v · 0.5 · (S_x + S_v)
|
| 6870 |
+
sbe_chars = self.spelling_bee.chars(input_ids, dtype=inputs_embeds.dtype)
|
| 6871 |
+
inputs_embeds = (inputs_embeds + sbe_chars) * 0.5
|
| 6872 |
+
else:
|
| 6873 |
+
inputs_embeds = self.spelling_bee(input_ids, inputs_embeds)
|
| 6874 |
+
|
| 6875 |
+
yurii_velocity = None
|
| 6876 |
+
if self.yurii_spelling_velocity is not None and input_ids is not None:
|
| 6877 |
+
# V0 = λ_v · 0.5 · (S_x + S_v), where S_x is the original
|
| 6878 |
+
# Spelling Bee character table and S_v is the new velocity table.
|
| 6879 |
+
yurii_velocity = self.yurii_spelling_velocity(
|
| 6880 |
+
input_ids,
|
| 6881 |
+
self.spelling_bee,
|
| 6882 |
+
dtype=inputs_embeds.dtype,
|
| 6883 |
+
reference_chars=sbe_chars,
|
| 6884 |
+
)
|
| 6885 |
+
yurii_velocity = yurii_velocity * float(
|
| 6886 |
+
getattr(self.config, "yurii_spelling_velocity_scale", 0.10)
|
| 6887 |
+
)
|
| 6888 |
|
| 6889 |
if analysis_state is not None:
|
| 6890 |
analysis_state.embeddings = inputs_embeds.detach()
|
| 6891 |
+
analysis_state.yurii_initial_velocity = (
|
| 6892 |
+
yurii_velocity.detach() if yurii_velocity is not None else None
|
| 6893 |
+
)
|
| 6894 |
|
| 6895 |
if position_ids is None:
|
| 6896 |
position_ids = torch.arange(
|
|
|
|
| 7035 |
output_attentions=output_attentions,
|
| 7036 |
repo_rope_args=repo_rope_args,
|
| 7037 |
position_ids=position_ids,
|
| 7038 |
+
yurii_velocity=yurii_velocity,
|
| 7039 |
**kwargs,
|
| 7040 |
)
|
| 7041 |
hidden_states = layer_outputs[0]
|
| 7042 |
+
_base_output_count = 1
|
| 7043 |
+
if yurii_velocity is not None:
|
| 7044 |
+
yurii_velocity = layer_outputs[1]
|
| 7045 |
+
_base_output_count = 2
|
| 7046 |
|
| 7047 |
# Update AttnRes partial sum — the new partial is the layer output
|
| 7048 |
if use_attn_res:
|
|
|
|
| 7052 |
if use_dca:
|
| 7053 |
dca_sources = dca_sources + [hidden_states]
|
| 7054 |
|
| 7055 |
+
_aux_start = _base_output_count
|
| 7056 |
if output_attentions:
|
| 7057 |
+
all_attentions = all_attentions + (layer_outputs[_base_output_count],)
|
| 7058 |
+
_aux_start += 1
|
| 7059 |
|
| 7060 |
# Collect JTok-M aux stats (last element if present)
|
| 7061 |
+
if self.config.use_jtokm and len(layer_outputs) > _aux_start:
|
| 7062 |
all_aux_stats.append(layer_outputs[-1])
|
| 7063 |
|
| 7064 |
# Collect VersatileFFN aux stats (second-to-last if jtokm also present,
|
| 7065 |
# or last if jtokm is absent). Only non-None during training.
|
| 7066 |
if getattr(self.config, "use_versatile_ffn", False):
|
| 7067 |
+
for item in layer_outputs[_aux_start:]:
|
| 7068 |
if isinstance(item, tuple) and len(item) == 3:
|
| 7069 |
# (p_sum, f_sum, N_tokens) signature
|
| 7070 |
all_aux_stats.append(("versatile", item))
|
|
|
|
| 7083 |
# ── Finalise analysis snapshot ─────────────────────────────────────
|
| 7084 |
if analysis_state is not None:
|
| 7085 |
analysis_state.final_hidden_states = hidden_states.detach()
|
| 7086 |
+
analysis_state.yurii_final_velocity = (
|
| 7087 |
+
yurii_velocity.detach() if yurii_velocity is not None else None
|
| 7088 |
+
)
|
| 7089 |
analysis_state.jtokm_aux_stats = all_aux_stats if self.config.use_jtokm else None
|
| 7090 |
analysis_state.attn_res_sources_final = (
|
| 7091 |
attn_res_sources if use_attn_res else None
|
|
|
|
| 7374 |
"LeviathanGenerator",
|
| 7375 |
"LeviathanJTokM",
|
| 7376 |
"SpellingBeeEmbedding",
|
| 7377 |
+
"YuriiSpellingBeeVelocityEmbedding",
|
| 7378 |
"StackMemory",
|
| 7379 |
"FANLayer",
|
| 7380 |
"SeeDNorm",
|