Text Generation
Transformers
Safetensors
PyTorch
English
Spanish
neollm
causal-lm
research
dpo
conversational
custom_code
Instructions to use KitsuVp/NeoLLM-Instruct-DPO with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use KitsuVp/NeoLLM-Instruct-DPO with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="KitsuVp/NeoLLM-Instruct-DPO", 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-Instruct-DPO", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use KitsuVp/NeoLLM-Instruct-DPO with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "KitsuVp/NeoLLM-Instruct-DPO" # 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-Instruct-DPO", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/KitsuVp/NeoLLM-Instruct-DPO
- SGLang
How to use KitsuVp/NeoLLM-Instruct-DPO 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-Instruct-DPO" \ --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-Instruct-DPO", "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-Instruct-DPO" \ --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-Instruct-DPO", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use KitsuVp/NeoLLM-Instruct-DPO with Docker Model Runner:
docker model run hf.co/KitsuVp/NeoLLM-Instruct-DPO
Download configuration_neollm.py from KitsuVp/NeoLLM-Instruct-DPO: direct link, hf CLI and curl.
- Browser
- Download file 109 kB
-
https://huggingface.co/KitsuVp/NeoLLM-Instruct-DPO/resolve/main/configuration_neollm.py
- Command line
-
hf download hf://KitsuVp/NeoLLM-Instruct-DPO/configuration_neollm.py
-
curl -L -o configuration_neollm.py https://huggingface.co/KitsuVp/NeoLLM-Instruct-DPO/resolve/main/configuration_neollm.py
109 kB
# ==================== configuration_neollm.py ====================
import math
from numbers import Integral
from transformers.configuration_utils import PretrainedConfig
from transformers.modeling_rope_utils import rope_config_validation
from transformers.utils import logging
logger = logging.get_logger(__name__)
class NeoLLMConfig(PretrainedConfig):
r"""
Configuration class for the NeoLLM model architecture.
Instantiates a NeoLLM model according to the specified arguments, defining the
full architecture including attention mechanisms, normalization, periodicity
modeling, an optional Leviathan continuous token embedding generator (LEV
layer, Batley & Saha 2026), and optional Spelling Bee character-level
embedding augmentation.
Configuration objects inherit from :class:`~transformers.PretrainedConfig` and
can be used to control the model outputs. Read the documentation from
:class:`~transformers.PretrainedConfig` for more information.
Args:
vocab_size (:obj:`int`, *optional*, defaults to 200005):
Vocabulary size of the NeoLLM model. Defines the number of different
tokens that can be represented by the ``input_ids``.
hidden_size (:obj:`int`, *optional*, defaults to 512):
Dimensionality of the hidden representations.
intermediate_size (:obj:`int`, *optional*, defaults to 1536):
Dimensionality of the MLP feed-forward intermediate representations.
num_hidden_layers (:obj:`int`, *optional*, defaults to 12):
Number of decoder Transformer layers.
num_attention_heads (:obj:`int`, *optional*, defaults to 8):
Number of query attention heads per layer.
num_key_value_heads (:obj:`int`, *optional*, defaults to 2):
Number of key/value attention heads (GQA). Must divide
``num_attention_heads`` evenly.
hidden_act (:obj:`str`, *optional*, defaults to ``"xielu"``):
Non-linear activation function used in the MLP layers.
max_position_embeddings (:obj:`int`, *optional*, defaults to 32768):
Maximum sequence length supported by the positional encoding.
initializer_range (:obj:`float`, *optional*, defaults to 0.02):
Standard deviation of the truncated-normal weight initializer.
rms_norm_eps (:obj:`float`, *optional*, defaults to 1e-6):
Epsilon for RMS normalization layers.
tie_word_embeddings (:obj:`bool`, *optional*, defaults to ``False``):
Whether to share weights between the input embedding matrix and the
output language-model head. Automatically forced to ``False`` when
``use_token_generator=True``, because the generator produces input
representations via a learned smooth surface and the output head must
remain an independent dense projection.
ntp_loss_backend (:obj:`str`, *optional*, defaults to ``"cce"``):
Backend used for the main next-token-prediction loss. ``"cce"`` uses
Cut Cross Entropy through ``linear_cross_entropy(..., shift=1)``.
``"liger"`` uses Liger Kernel's fused linear cross entropy with an
explicit shift equivalent to ``shift=1``. The two backends are
mutually exclusive at runtime. Copy-Paste, when enabled, computes
its mixed objective instead of either backend's NTP loss.
use_liger_kernel (:obj:`bool`, *optional*, defaults to ``False``):
Convenience flag for ``ntp_loss_backend="liger"``. When enabled,
the model does not call the CCE loss path for NTP.
cce_loss_impl (:obj:`str`, *optional*, defaults to ``"cce_kahan_full_c"``):
CCE implementation used when ``ntp_loss_backend="cce"``. The default
keeps the conservative Kahan/full-classifier-gradient path used for
pretraining from scratch.
use_mile_loss (:obj:`bool`, *optional*, defaults to ``True``):
Enable MiLe Loss (Su et al., 2026, arXiv:2310.19531). MiLe
reweights token losses with detached, mean-normalized predictive-
entropy weights. Copy-Paste derives those weights from the mixed
distribution using CCE's sparse statistics on CUDA.
use_copy_paste (:obj:`bool`, *optional*, defaults to ``False``):
Add the Copy-Paste LM head (Godey and Artzi, arXiv:2610.19247).
Its learned copy gate and sink mix vocabulary predictions with a
causal distribution over observed input tokens. CUDA training uses
CCE's sparse Copy-Paste path; CPU uses a bounded Torch reference.
MiLe uses mixture entropy; mu-loss remains a regularizer on the
ordinary vocabulary matrix. Inference still returns dense logits.
mile_loss_gamma (:obj:`float`, *optional*, defaults to ``1.0``):
Non-negative exponent applied to MiLe's ``1 + entropy`` weight.
use_mu_loss (:obj:`bool`, *optional*, defaults to ``True``):
Enable the output-embedding centering regularizer from Stollenwerk
et al. (2026, arXiv:2601.02031). CCE uses its extension; the
Copy-Paste path computes the regularizer directly in Torch.
mu_loss_lambda (:obj:`float`, *optional*, defaults to ``1e-4``):
Non-negative coefficient in ``L_mu = lambda * ||mean(C)||^2``.
use_meap (:obj:`bool`, *optional*, defaults to ``False``):
Enable Mask-Enhanced Autoregressive Prediction during training only
(Zhuang et al., 2026, arXiv:2502.07490). Labels and attention masks
remain clean; only selected input token IDs are replaced.
meap_mask_ratio (:obj:`float`, *optional*, defaults to ``0.15``):
Fraction of eligible input positions replaced in each sequence.
meap_mask_token_id (:obj:`int`, *optional*):
Dedicated reserved token ID used only as the MEAP replacement.
Required when MEAP is enabled; it must be inside the vocabulary and
distinct from PAD/BOS/EOS. Its final trainable representation is
independent from dense embeddings, Leviathan, and Spelling Bee.
meap_seed (:obj:`int`, *optional*, defaults to ``0``):
Base 32-bit seed. The Trainer derives a distinct deterministic seed
for each microstep and distributed process.
meap_implementation (:obj:`str`, *optional*, defaults to ``"triton"``):
MEAP implementation, either ``"triton"`` or the reference
``"torch"`` path.
meap_exclude_last (:obj:`bool`, *optional*, defaults to ``True``):
Exclude the last valid input, which has no shifted target, before
structural eligibility filters are applied.
meap_protect_structural_tokens (:obj:`bool`, *optional*, defaults to ``True``):
Preserve configured PAD, BOS, EOS and the dedicated MEAP mask ID
during corruption. EOS may be a single ID or a list of IDs.
meap_exclude_mask_from_copy (:obj:`bool`, *optional*, defaults to ``True``):
During MEAP training, exclude artificial mask positions from the
Copy-Paste source distribution. Clean targets remain unchanged.
copy_paste_lexical_keys (:obj:`bool`, *optional*, defaults to ``False``):
Add a low-rank projection of each observed token embedding to its
patch-context key. This has an effect only when Copy-Paste and
patch training with K>1 are both active. The rank is derived from
the hidden size, with no batch- or sequence-specific setting.
liger_loss_accum_dtype (:obj:`str`, *optional*, defaults to ``"float32"``):
Accumulator dtype passed to Liger FLCE for weight/bias gradient
accumulation. ``"float32"`` is the stability-first setting for BF16
pretraining; use ``None``/``"none"`` to keep Liger's default behavior
and accumulate in the original dtype.
rope_theta (:obj:`float`, *optional*, defaults to 10000.0):
Base period for Rotary Position Embeddings (RoPE).
rope_scaling (:obj:`dict`, *optional*):
Dictionary containing the RoPE scaling configuration. Must contain at
least the key ``"rope_type"`` (or ``"type"``). Validated by
:func:`~transformers.modeling_rope_utils.rope_config_validation`.
partial_rotary_factor (:obj:`float`, *optional*, defaults to 0.25):
Fraction of each attention head's dimension to rotate with RoPE.
attention_bias (:obj:`bool`, *optional*, defaults to ``False``):
Whether to add a bias term to Q, K, V, and output projections.
attention_dropout (:obj:`float`, *optional*, defaults to 0.1):
Dropout probability applied to attention weights during training.
use_vha_attention (:obj:`bool`, *optional*, defaults to ``False``):
Factorize query projections into virtual heads and apply a low-rank
residual head mix (Ding et al., arXiv:2610.17959). For Hq query
heads and Hkv KV heads, the G=Hq/Hkv physical query/gate heads are
shared across KV groups and expanded to Hq virtual heads; the
postmix rank is max(1, G//2). The configured KV count is unchanged.
Hkv=2 gives the paper's halving of physical query heads; other KV
counts use the same group-specific factorization. Enabling this
option changes checkpoint parameter shapes.
use_hola_memory (:obj:`bool`, *optional*, defaults to ``False``):
Enable the FA2-compatible HOLA-derived episodic memory read path for
the IHA seq-expand branch. This is not a second attention branch: it
prepends a fixed-size selected KV memory to each FlashAttention-2
chunk and reads memory/current tokens inside one softmax. The write
policy uses a compile-friendly value-innovation proxy because the
stock FlashAttention-2 kernel does not expose the pre-dropout
accumulators required for the exact HOLA committed-residual score.
hola_memory_size (:obj:`int`, *optional*, defaults to 64):
Number of real-token episodes kept per layer/chunk when
``use_hola_memory=True``. Each episode stores all IHA pseudo-slots.
hola_chunk_size (:obj:`int`, *optional*, defaults to 256):
Number of original tokens processed per HOLA memory chunk. The
memory is frozen while a chunk is processed and updated between
chunks, preserving causality with standard FlashAttention-2 masks.
hola_logit_bias_init (:obj:`float`, *optional*, defaults to -2.0):
Initial additive logit prior for memory entries in the augmented
FA2 subspace. Negative values make the model start close to the
baseline attention and learn to use memory gradually.
hola_rms_gamma_init (:obj:`float`, *optional*, defaults to 1.0):
Initial RMSNorm-Ξ³ scale for the memory-read query/key subspace.
hola_score_eps (:obj:`float`, *optional*, defaults to 1e-6):
Numerical epsilon for the HOLA-derived value-innovation score.
head_dim (:obj:`int`, *optional*, defaults to 64):
Dimensionality of each attention head.
use_linear_attention (:obj:`bool`, *optional*):
Set ``False`` to force full attention, or ``True`` to require a
linear layer. ``None`` enables it automatically when the selected
type or explicit layer list contains a linear layer; this also
preserves configurations saved before this switch was added.
linear_attention_type (:obj:`str`, *optional*, defaults to ``"none"``):
Default layer type: ``"none"``, ``"ckda"`` or ``"gdn2"``.
linear_attention_full_attention_every (:obj:`int`, *optional*, defaults to 4):
Insert a full-attention layer at this interval and at the final
layer when the depth is greater than one. A one-layer model uses
the requested linear type.
linear_attention_layer_types (:obj:`list`, *optional*):
Explicitly set one ``"full"``, ``"ckda"`` or ``"gdn2"`` per layer;
this overrides the default type and interval.
linear_attention_num_heads, linear_attention_head_dim (:obj:`int`, *optional*):
Default to the model's attention geometry when ``None``.
linear_attention_expand_v, linear_attention_conv_size:
Value-width expansion and short-convolution width, defaulting to
1.0 and 4. Output dropout uses the shared ``dropout_rate``.
linear_attention (:obj:`dict`, *optional*):
Backward-compatible saved group. Its supplied keys override the
corresponding flat constructor defaults; the effective group is
saved with the model. CKDA uses the signed-gate ComplexKDA FLA
fork; GDN2 uses its GatedDeltaNet2 FLA layer. If the corresponding
FLA kernels are unavailable, a warning announces a slower,
potentially more memory-intensive PyTorch eager reference.
REPO/RoPE, XSA, momentum, IHA and FAN attention are properties of
the full-attention layers, not silently added to the linear mixer.
Linear layers do not expose pairwise attention matrices; their
``output_attentions`` entry is None. DAGFormer Q/K/V routing cannot
currently be combined with these linear layers.
use_momentum_attention (:obj:`bool`, *optional*, defaults to ``True``):
Enable post-RoPE Momentum Attention: applies a causal first-difference
shear to Q and K before the dot-product score computation.
momentum_gamma (:obj:`float`, *optional*, defaults to 0.10):
Mixing coefficient for the Momentum Attention shear. Ignored when
``use_momentum_attention=False``.
use_mea_attention (:obj:`bool`, *optional*, defaults to ``True``):
Enable Multi-head Explicit Attention (MEA), which applies a learned
head-level linear composition over K and V initialized as identity,
allowing inter-head interaction to emerge freely from step 0.
mea_component_key_value_heads (:obj:`int`, *optional*):
Number of component K/V heads used by MEA. Defaults to
``num_key_value_heads`` when ``None``.
mea_groupnorm_eps (:obj:`float`, *optional*, defaults to 1e-6):
Epsilon for the GQA-grouped MEA output normalisation.
use_lucid_attention (:obj:`bool`, *optional*, defaults to ``False``):
Enable LUCID attention: applies a lower-triangular solve to
precondition the value states using the causal key-key similarity
matrix in RKHS, decorrelating keys to reduce attentional noise in
long-context settings (Duvvuri et al., 2026).
lucid_attention_eps (:obj:`float`, *optional*, defaults to 1e-6):
Epsilon for RMS key normalization inside the LUCID preconditioner.
use_affine_scaled_attention (:obj:`bool`, *optional*, defaults to ``False``):
Enable Affine-Scaled Attention (Bae et al., 2026). Applies an
input-dependent per-head scaling factor Ξ± and a moving-average bias Ξ²
directly to the softmax-normalized attention weights before the
weighted sum with V:
[Ξ±(X) Β· softmax(QKα΅/βdk) + Ξ²(X)] V
This relaxes the unit-sum constraint of softmax, reduces first-token
bias, increases attention entropy, and promotes head diversity.
Orthogonal to Gated Attention: the gate modulates the post-SDPA
output, while Affine-Scaled modulates the softmax weights directly.
Only active in eager attention mode (flash kernels do not expose
intermediate softmax weights).
affine_momentum (:obj:`float`, *optional*, defaults to 0.9):
EMA momentum coefficient Ο for the running average Ξ±_ma used to
compute the bias term Ξ²(X) = (Ξ±_ma β Ξ±(X)) / N. Controls the
trade-off between the running estimate and the current batch
statistic. Ignored when ``use_affine_scaled_attention=False``.
use_xsa (:obj:`bool`, *optional*, defaults to ``False``):
Enable Exclusive Self Attention (Zhai, 2026). After the SDPA output
is computed, removes from each head's output the component that falls
along the direction of the token's own value vector, forcing the
attention layer to carry only contextual information orthogonal to
self-position.
Two paths depending on active components:
- **MEA active or LUCID active**: ``v_ref`` is the value vector
after MEA mixing and after LUCID preconditioning β the vector that
actually participated in the SDPA aggregation.
- **MEA and LUCID inactive**: ``v_ref`` is the raw value projection
β standard XSA as described in the paper.
Applied after MEAHeadRMSNorm and before the Gated Attention gate.
Gains increase with sequence length.
xsa_eps (:obj:`float`, *optional*, defaults to 1e-6):
Epsilon for the denominator of the XSA projection to prevent
division by zero: ``βv_refβΒ² + xsa_eps``. Ignored when
``use_xsa=False``.
use_msar (:obj:`bool`, *optional*, defaults to ``False``):
Enable Block Multi-Stream Attention Residuals (arXiv:2610.13630).
It may be combined with SiameseNorm; the hybrid adds an MSAR read
of the shared unscaled branch history to the normalized X/Y sum,
before its existing optional shared input norm. No extra
normalization or user parameter is introduced by the combination.
This is an architectural adaptation, not a configuration tested in
the MSAR paper. Other residual topologies, GPAS, FAN residual and
DAGFormer remain exclusive. Single-stream summaries are retained;
causal views and independent depth reads are reconstructed per branch.
use_ldm (:obj:`bool`, *optional*, defaults to ``False``):
Enable Linear Depth Memory (RLS per token and feature group). Group
count follows the attention head geometry automatically, and the
key and controller dimensions follow the paper's small-width recipe.
SiameseNorm can be combined with LDM through a shared history of
unscaled branch outputs; this hybrid is an architectural adaptation.
Other alternative residual flows remain mutually exclusive.
msar_block_branches (:obj:`int` or ``None``, optional):
Number of attention/MLP branches per block. ``None`` derives a
size from the total number of attention/MLP branches, aiming for
roughly eight contiguous blocks; block boundaries may fall between
attention and MLP. An explicit value is preserved as supplied.
msar_kernel_sizes (:obj:`tuple`, optional):
Causal depthwise widths; the paper uses ``(4, 8, 12)``.
msar_backend (:obj:`str`, optional):
``auto`` uses Triton on CUDA and Torch on CPU; ``torch`` selects
the fully differentiable reference for validation.
use_stack_memory (:obj:`bool`, *optional*, defaults to ``False``):
Enable the StackMemory / STACKTRANS hidden-state stack between
decoder layers (Zhang et al., NeurIPS 2025). The module keeps the
standard attention path intact and applies differentiable soft
``push``, ``pop`` and ``no-op`` stack updates to the layer input
before the attention block.
stack_d_model (:obj:`int`, *optional*, defaults to ``32``):
Low-rank stack width ``d_s`` used by StackMemory. Hidden states are
projected ``hidden_size β stack_d_model`` before stack operations
and projected back afterwards.
num_mem_heads (:obj:`int`, *optional*, defaults to ``8``):
Number of independent stack heads. Must divide ``stack_d_model``.
stack_slots (:obj:`int`, *optional*, defaults to ``16``):
Number of slots kept by each differentiable stack head.
stack_memory_cache_size (:obj:`int`, *optional*, defaults to ``2048``):
Cache length kept for parity with the released StackTrans source.
The default training path keeps this cache disabled.
stack_entropy_loss_weight (:obj:`float`, *optional*, defaults to ``0.001``):
Weight ``lambda_St`` for the StackTrans action-entropy regularizer.
When StackMemory is active, training adds
``lambda_St * mean(H(push, pop, noop))`` across valid tokens,
memory heads, and decoder layers. Set to ``0.0`` to monitor the
entropy without applying it to the objective.
fan_ratio (:obj:`float`, *optional*, defaults to 0.125):
Ratio controlling the periodic-dimension size in FANformer attention.
The transformed representation has dimension
``hidden_size * (1 + fan_ratio)``.
fan_ratio_ffn (:obj:`float`, *optional*, defaults to 0.0625):
Ratio controlling the periodic-dimension size in FANformer MLP
layers. Set to half of ``fan_ratio`` to model complementary
periodicities in the feature space.
dropout_rate (:obj:`float`, *optional*, defaults to 0.1):
General dropout probability for attention outputs and MLP states.
use_learnable_multipliers (:obj:`bool`, *optional*, defaults to ``True``):
Enable Learnable Multipliers on the matrix layers where the
Velikanov et al. placement recommends them. When ``True``, the
model keeps row multipliers on ``q_proj`` and MLP ``gate_proj``,
row+column multipliers on dense ``o_proj`` and MLP ``down_proj``,
and no extra multipliers on ``k_proj``, ``v_proj`` or ``up_proj``.
When ``False``, those multiplier parameters are not instantiated
and the wrapped linear layers behave as ordinary ``nn.Linear``
modules.
use_embedding_multipliers (:obj:`bool`, *optional*, defaults to ``True``):
Add vocabulary-row and hidden-channel multipliers to the standard
``nn.Embedding`` matrix, matching the Learnable Multipliers paper's
recommendation for embeddings. This flag is effective only when
``use_learnable_multipliers=True``, ``use_token_generator=False``
and ``tie_word_embeddings=False``. It is intentionally disabled for
tied input/output embeddings and for the Leviathan generator path so
it does not break parameter sharing or wrap a non-matrix generator.
use_lns (:obj:`bool`, *optional*, defaults to ``False``):
Instantiate and apply LayerNorm Scaling in decoder layers. When
``False``, no LNS modules are constructed and the corresponding
path is identity.
use_gpas (:obj:`bool`, *optional*, defaults to ``False``):
Instantiate and apply GPAS at decoder residual junctions. When
``False``, no GPAS modules or parameters are constructed.
use_siamesenorm (:obj:`bool`, *optional*, defaults to ``False``):
Enable SiameseNorm as a two-stream residual topology using RMSNorm
only. When ``True``, decoder layers instantiate the SiameseNorm RMS
stream norms instead of the standard decoder pre-norm modules.
use_dagformer (:obj:`bool`, *optional*, defaults to ``False``):
Add causal, signed depth routing for Q/K/V and residual reads.
Requires JTok and JTok-M disabled; preserves the embedding producer.
dagformer (:obj:`dict`, *optional*):
Grouped overrides: predictor_dim=256, predictor_layers=2,
predictor_heads=4, local_dim=128, input_source="tokens".
input_source="embeddings" shares the composed backbone embeddings,
including Leviathan when active, instead of a separate token table.
Kernel shapes derive from actual tensors; no batch tuning required.
siamese_normalized_input (:obj:`bool`, *optional*, defaults to ``True``):
Apply an additional RMSNorm to the fused SiameseNorm input before
the shared Attention and MLP blocks. This corresponds to the
normalized-input mechanism used by the strongest SiameseNorm
variant.
siamese_depth_scaling (:obj:`bool`, *optional*, defaults to ``True``):
Store the X stream as ``sqrt(2 * (layer_idx + 1)) * RMSNorm(X) +
update`` after each shared sublayer, following the official
SiameseNorm post/pre implementation. Y receives the shared update.
siamese_attn_x_scale_init (:obj:`float`, *optional*, defaults to ``1.0``):
Initial value for the learnable elementwise scale applied to the
bounded stream in the SiameseNorm attention input.
use_embedding_input_norm (:obj:`bool`, *optional*, defaults to ``True``):
Controls only the first pre-attention normalisation applied to the
raw embedding stream. When ``True``, layer 0 instantiates and applies
``nn.RMSNorm``. When ``False``, layer 0
does not instantiate that input-normalisation module, so raw token
embeddings enter the first attention block directly. All deeper
decoder layers keep their normal pre-norm flow unchanged.
use_token_generator (:obj:`bool`, *optional*, defaults to ``False``):
Replace the discrete vocabulary embedding lookup table with a
**Leviathan** continuous token generator (Batley & Saha, 2026).
When enabled:
- ``tie_word_embeddings`` is forced to ``False``.
- ``model.embed_tokens`` is replaced by ``model.token_generator``
(:class:`LeviathanGenerator`).
- The input-embedding parameter budget scales as
``O(k Β· βV^{1/k}β Β· d_seed)`` instead of ``O(V Β· D)``.
- The output head stays fully untied (``lm_head``), with a total
parameter overhead below 0.2% at 1.2B scale.
See :class:`LeviathanGenerator` in ``modeling_neollm.py``.
generator_d_seed (:obj:`int`, *optional*, defaults to 128):
Dimensionality of the latent seed space ``zΜ β [0,1]^{d_seed}``,
also used as the per-dimension input to each generator head's
B-spline expansion.
generator_num_modes (:obj:`int`, *optional*, defaults to 8):
Number of independent per-head generator modes. Each mode has its
own preprocessing (Dense without bias + LayerNorm + sigmoid(x/2)),
its own learnable per-dimension scale, its own delta-parameterized
spline weights ``1 + wd_i``, and its own output projection. Head
outputs are summed to form the embedding.
generator_num_knots (:obj:`int`, *optional*, defaults to 16):
Number of B-spline knot points ``ΞΊ`` on ``[0, 1]``. The quadratic
basis is explicitly normalized across the knot dimension after
evaluation. ``16`` matches the Leviathan paper default (ΞΊ = 16).
generator_spline_degree (:obj:`int`, *optional*, defaults to 2):
Polynomial degree of the B-spline basis. Kept for documentation;
the closed-form KHRONOS quadratic kernel is used in practice.
generator_k (:obj:`int`, *optional*, defaults to 3):
Number of coordinate dimensions for latent compositional indexing.
generator_krank (:obj:`int`, *optional*, defaults to 64):
Output rank of each per-head KHRONOS tensor-product kernel inside
the Leviathan generator. Each of the ``generator_num_modes`` heads
produces a vector of this dimensionality via the tensor-product
aggregation, which is then projected independently to
``hidden_size`` via ``head_out[i]``. ``64`` matches the author
clarification for ``wd_i`` with shape ``(128, 32, 64)``. Lower
values, such as ``32``, are valid memory-saving variants but are
not the full paper-faithful default. Ignored when
``use_token_generator=False``.
use_jtok (:obj:`bool`, *optional*, defaults to ``False``):
Enable the continuous Leviathan-JTok plugin. This flag requires
``use_token_generator=True`` because JTok receives its shared
token coordinate from the compositional Leviathan seed. Each
decoder layer evaluates one continuous B-spline surface and
applies ``Delta_m * (1 + scaler * Norm(surface))`` to its MLP
update. This is a continuous NeoLLM adaptation of JTok, not the
original paper's dense ``V x D`` token table.
use_jtokm (:obj:`bool`, *optional*, defaults to ``False``):
Upgrade an active JTok plugin to continuous JTok-M. It requires
both ``use_jtok=True`` and ``use_token_generator=True``. A
pre-attention RMS-normalized state selects ``jtok_top_k`` of
``jtok_num_experts`` surfaces with Sigmoid+TopK, and the selected
normalized mixture is added to the MLP update with the paper's
``1/sqrt(2L)`` depth scale. Training also adds the compact
load-balancing objective from Yang et al., Appendix B.
jtok_num_modes (:obj:`int`, *optional*, defaults to ``4``):
Number of separable spline modes per continuous JTok surface.
jtok_num_experts (:obj:`int`, *optional*, defaults to ``5``):
Number of continuous surfaces used by JTok-M. Plain JTok uses one
surface regardless of this value.
jtok_top_k (:obj:`int`, *optional*, defaults to ``2``):
Number of JTok-M surfaces selected per token; must satisfy
``1 <= jtok_top_k <= jtok_num_experts``.
jtok_norm_eps (:obj:`float`, *optional*, defaults to ``1e-6``):
Epsilon for JTok/JTok-M RMS and L2 normalization operations.
jtok_aux_loss_weight (:obj:`float`, *optional*, defaults to ``1e-4``):
Weight of the JTok-M load-balancing objective. It is ignored in
plain JTok mode. The Torch implementation keeps the expected
probability term differentiable and uses ``T * K`` in the hard
utilization denominator.
jtok_kernel_backend (:obj:`str`, *optional*, defaults to ``"torch"``):
Runtime-only JTok/JTok-M dispatch selector. ``"torch"`` keeps the
reference PyTorch implementation (and is the backward-compatible
default); ``"triton"`` strictly requires the compatible CCE
JTok/JTok-M adapter. This selector changes no parameters,
buffers, tokenizer behavior, compiler policy, or training math,
and old configuration files that omit it continue to use
``"torch"``.
use_spelling_bee_embeddings (:obj:`bool`, *optional*, defaults to ``False``):
Augment token embeddings with character-level byte information
(Rabe, Clymo & Dong, 2026).
Each token's UTF-8 encoding (up to 16 bytes) is embedded through a
shared ``nn.Embedding(256, d)`` table. Byte embeddings are
position-encoded with RoPE using intra-token byte positions (not
sequence positions), averaged over the fixed 16 byte slots, then
averaged with the standard token embedding:
.. math::
e_{\\text{bee}}(t) = \\frac{1}{2}\\left(e_{\\text{tok}}(t) +
\\frac{1}{16}\\sum_{i=1}^{16}
\\text{RoPE}(e_{\\text{byte}}[b_i], i)\\right)
The active configuration follows the reference fixed-length mean.
A separate theoretical variant would mask padded positions and use
``1 / sqrt(|t|)`` over valid bytes; it is intentionally not active
in this training configuration.
Adds ``256 Γ hidden_size`` parameters (β0.13M for d=512).
Zero inference overhead when ``bake_inference_table()`` is called
after training.
Compatible with all four combinations of ``use_token_generator``
and ``use_spelling_bee_embeddings``.
**Setup required**: call
``model.model.spelling_bee.set_byte_table(tokenizer)`` once after
model instantiation (handled automatically by ``setup_model`` in
``train.py``).
Reference: Rabe, Clymo & Dong (2026). *Spelling Bee Embeddings for
Language Modeling.* arXiv:2601.18030.
use_hadamard_o_proj (:obj:`bool`, *optional*, defaults to ``False``):
Replace the dense ``W_O β R^{dΓd}`` output projection in every
multi-head attention block with a fixed WalshβHadamard Transform
followed by a learnable per-channel affine rescaling
``Ξ± β FWHT(x)/βd + Ξ²``.
The WHT is a parameter-free orthogonal matrix whose singular values
are all identically 1, so the effective condition number is
``ΞΊ = 1`` by construction and cannot grow during training. This
directly addresses the high-ΞΊ pathology (ΞΊ up to 10^5) observed in
the dense ``o_proj`` matrices, which causes FP8 per-tensor
quantisation to lose low-magnitude directions entirely.
Parameter reduction: replaces ``dΒ²`` weights with ``2d``
(``Ξ±`` and ``Ξ²``), saving β25% of attention parameters per block.
Requires ``hidden_size`` to be a power of 2 (512 β, 1024 β,
768 β).
Reference: Aggarwal & Kumar (2026). *Rethinking Attention Output
Projection: Structured Hadamard Transforms for Efficient
Transformers.* arXiv:2603.08343.
use_repo (:obj:`bool`, *optional*, defaults to ``False``):
Enable Context Re-Positioning (REPO) in attention layers at or
above ``repo_start_layer`` (Li et al., 2026).
REPO replaces the fixed linear position indices ``0β¦L-1`` fed to
RoPE with continuous, data-dependent positions ``z_i = f_Ο(h_i)``
learned end-to-end. The attention score between tokens ``i`` and
``j`` becomes:
.. math::
A^{\\text{REPO}}_{i,j} = q_i^\\top\\, g_\\theta(z_j - z_i)\\, k_j
where ``g_ΞΈ`` is the standard RoPE rotation and ``z_i`` is
predicted from the hidden state ``h_i`` by a lightweight SwiGLU
sub-layer ``f_Ο``:
.. math::
r_i = \\text{Swish}(h_i W_g) \\odot (h_i W_c), \\quad
z_i^{(h)} = r_i w_z^{(h)}
``W_g, W_c \\in \\mathbb{R}^{d \\times d_p}`` are shared across
all query heads within a layer; ``w_z^{(h)} \\in \\mathbb{R}^{d_p}``
is learned independently per head. The assigned positions are
real-valued and unconstrained β the model may learn constant
(NoPE-like), monotonic (RoPE-like), or hybrid patterns as needed.
Lower layers (``layer_idx < repo_start_layer``) retain the
standard integer RoPE positions because they primarily capture
surface-level, locally-dependent features that benefit less from
re-positioning (Li et al., 2026, Β§3).
Overhead: +0.9% parameters; inference latency negligible.
repo_start_layer (:obj:`int`, *optional*, defaults to
``num_hidden_layers // 3``):
Index of the first decoder layer to which REPO is applied.
Layers ``[0, repo_start_layer)`` continue to use standard
integer RoPE positions. Must satisfy
``0 <= repo_start_layer < num_hidden_layers``.
Ignored when ``use_repo=False``.
repo_d_p (:obj:`int`, *optional*, defaults to
``hidden_size // 8``):
Dimensionality of the intermediate position representation
``r_i \\in \\mathbb{R}^{d_p}`` inside ``f_Ο``. The paper sets
``d_p = d/8`` on the assumption that positional information
is less rich than the full hidden representation. Ignored
when ``use_repo=False``.
use_repo_grape (:obj:`bool`, *optional*, defaults to ``False``):
Enable the proposed REPO-GRAPE positional operator. This reuses
the REPO coordinate module ``f_Ο`` and replaces the RoPE action
with a GRAPE-M action using a learned per-head/per-plane angular
spectrum:
.. math::
u_i^{(h)} = z_i^{(h)}, \\quad
\\theta_{h,r}=\\theta^0_r\\exp(s_{h,r})
When enabled, REPO-GRAPE activates the REPO coordinate path at
``repo_start_layer`` even if ``use_repo=False``. Lower layers keep
standard integer RoPE.
use_goat (:obj:`bool`, *optional*, defaults to ``True``):
Replace RoPE, REPO, REPO-GRAPE and the separate REPO-GOAT prior
with GOAT attention in every full-attention layer (Litman & Guo,
2026). Set ``use_repo``, ``use_repo_grape`` and
``use_repo_goat_prior`` to ``False`` when enabling it; incompatible
combinations raise an error rather than silently changing the model.
In hybrid models, GOAT applies only to full-attention layers;
CKDA/GDN2 retain their own recurrence and causal convolution without
GOAT or NeoLLM's full-attention RoPE. HOLA memory is not supported
with GOAT. IHA expands positional IDs to the pseudo-slot axis.
The Fourier relative prior and key-only sink bias enter Q/K logits
without constructing a quadratic bias matrix. Their coefficients
are shared within each GQA KV-head group. Nine channels of each Q/K
head are reserved for four relative modes and the sink; the rest
carry content, and V keeps its full width. Query scaling reproduces
the authors' logits under standard attention scaling. Frequencies use
base 10000 and eight absolute modes; absolute feature normalization
uses the configured training context. The seeded prior follows the
authors' shared sink MLP and positive recency slope initialization.
NeoLLM projections, normalization and optional attention operators
remain active; this is not the authors' complete model architecture.
Earlier expanded-head GOAT checkpoints have a different sink
parameterization and cannot be treated as equivalent weights.
goat_kernel_backend (:obj:`str`, *optional*, defaults to ``"auto"``):
``"auto"`` uses fused Triton packing for supported CUDA BF16
FlashAttention inputs with FP32 Q/K, BF16 V and no IHA; other
devices, dtypes and IHA use the PyTorch reference. ``"torch"``
always uses the reference. The BF16 conversion is the one already
required at the FlashAttention boundary. This selector adds no
parameters or optimizer state and does not choose a compilation
mode or disable CUDA graphs. Performance depends on the workload.
use_laurel (:obj:`bool`, *optional*, defaults to ``False``):
Enable the Learned Augmented Residual Layer (LAUREL) framework
(Menghani, Kumar & Kumar, ICML 2025). LAUREL generalises the
canonical residual connection:
.. math::
x_{i+1} = \\alpha \\cdot f(x_i) + g(x_i)
where :math:`g` is a learned linear function operating on the
residual stream. Applied independently to both the attention
and MLP sublayers of every decoder layer.
At least one of ``use_laurel_rw`` or ``use_laurel_lr`` must be
``True`` when this flag is active; both may be active
simultaneously, producing the combined **LAUREL-RW+LR** variant
(paper eq. 5).
Incompatible with ``use_attn_res=True`` β both methods modify
the residual stream and their interaction is undefined.
Reference: Menghani, G., Kumar, R. & Kumar, S. (2025).
*LAUREL: Learned Augmented Residual Layer.* ICML 2025.
use_laurel_rw (:obj:`bool`, *optional*, defaults to ``True``):
Enable the **LAUREL-RW** (Residual Weights) variant. Assigns
independent learned scalars :math:`\\alpha, \\beta` to the
sublayer output and residual respectively:
.. math::
x_{i+1} = \\alpha_s \\cdot f(x_i) + \\beta_s \\cdot x_i
:math:`\\alpha_s, \\beta_s = \\text{softmax}([\\tilde{\\alpha},
\\tilde{\\beta}])` so that they are non-negative and sum to 1,
preventing unbounded growth (paper Β§2.1). Adds **2 parameters
per sublayer** (4 per decoder layer).
When combined with ``use_laurel_lr=True`` (LAUREL-RW+LR,
paper eq. 5):
.. math::
x_{i+1} = \\alpha_s \\cdot f(x_i)
+ \\beta_s \\cdot (B A x_i + x_i)
Ignored when ``use_laurel=False``.
use_laurel_lr (:obj:`bool`, *optional*, defaults to ``False``):
Enable the **LAUREL-LR** (Low-Rank) variant. Augments the
residual with a rank-``laurel_lr_rank`` correction:
.. math::
x_{i+1} = f(x_i) + B A x_i + x_i
where :math:`A \\in \\mathbb{R}^{D \\times r}` and
:math:`B \\in \\mathbb{R}^{r \\times D}` are learnable matrices
(paper eq. 3). :math:`A` is initialised with column-orthogonal
values :math:`A_{i,j} = 1/\\sqrt{rD}` if :math:`i \\bmod r = j`
else 0; :math:`B` is initialised to zero β matching the LoRA
convention and ensuring the residual starts as identity
(paper Β§3.3). Adds **2Β·rΒ·D parameters per sublayer**
(4Β·rΒ·D per decoder layer).
Ignored when ``use_laurel=False``.
laurel_lr_rank (:obj:`int`, *optional*, defaults to ``32``):
Rank ``r`` of the low-rank matrices in LAUREL-LR. The paper
recommends :math:`r \\in \\{32, 48, 64\\}` for LLMs
(paper Β§3.3). Ignored when ``use_laurel=False`` or
``use_laurel_lr=False``.
use_tweo (:obj:`bool`, *optional*, defaults to ``False``):
Enable Transformers Without Extreme Outliers (TWEO), a
training-only activation regularizer from Liang et al. (2026).
TWEO adds a scaled :math:`L_p` penalty over the final output
activations of every Transformer block:
.. math::
L_{total} = L_{task} + \lambda L_{TWEO}, \quad
L_{TWEO} = \frac{1}{L}\sum_l
\mathbb{E}\left[\left(\frac{|A^{(l)}|}
{\tau + \epsilon}\right)^p\right]
This is non-invasive: no architecture, inference path, or
quantization backend is changed. It is intended for FP8/low-bit
training runs where extreme activation outliers are harmful.
tweo_loss_weight (:obj:`float`, *optional*, defaults to ``0.01``):
Weight :math:`\lambda` applied to the TWEO regularizer. The paper
uses ``0.01`` in its experiments, optionally with schedule control
outside the model.
tweo_tau (:obj:`float`, *optional*, defaults to ``3.0``):
Soft activation magnitude scale :math:`\tau`. The paper reports
robust results for :math:`\tau \in [2, 5]` and defaults to ``3``.
tweo_power (:obj:`float`, *optional*, defaults to ``4.0``):
Power :math:`p` for the non-linear TWEO penalty. ``4`` preserves
small activations while sharply penalizing extreme outliers.
tweo_eps (:obj:`float`, *optional*, defaults to ``1e-6``):
Numerical stability epsilon added to the TWEO denominator.
use_nitp_temporal (:obj:`bool`, *optional*, defaults to ``False``):
Instantiate the causal NITP temporal-transition extension. The
module is a separate bias-free multiplicative residual updater and
does not reuse ``NextLatDynamicsModel``. At every rollout step it
conditions on the detached NITP prediction of the next shallow
state, :math:`\operatorname{sg}(P_{\mathrm{NITP}}(\hat h_t))`,
never on the real future token embedding. The condition uses the
centered signed gate :math:`\tanh(W_z\bar z)`, which can
attenuate, activate, or reverse contextual update features. With
``W_z=0`` the update vanishes, so the transition cannot learn a
non-trivial condition-independent path. It also preserves
``F(0, z)=0``. The branch predicts
:math:`\hat h_{t+1}^L`, may be composed for
``nitp_temporal_horizon`` causal rollout steps, and never
materializes vocabulary logits.
nitp_temporal_apply_loss (:obj:`bool`, *optional*, defaults to ``True``):
When ``True``, add the weighted temporal state and identification
losses to the model loss. When ``False``, keep the transition
parameters instantiated and compute all temporal metrics under
``torch.no_grad()``, allowing a monitoring-only NTP+NITP baseline.
nitp_temporal_horizon (:obj:`int`, *optional*, defaults to ``4``):
Number :math:`W` of autonomous NITP-conditioned latent rollout steps.
nitp_temporal_dynamics_weight (:obj:`float`, *optional*, defaults to ``1.0``):
Weight applied to the average Smooth-L1 alignment between each
predicted final state and the stop-gradient real final state at
the same temporal offset.
nitp_temporal_identification_weight (:obj:`float`, *optional*, defaults to ``0.1``):
Weight applied to the symmetric listwise temporal-identification
objective over a local :math:`W\times W` joint-signature matrix.
The score keeps two conceptual halves, geometry and frozen-weight
NITP content. Geometry is an equal-norm concatenation of direct
accumulated-displacement cosine :math:`A` and a relational angular
profile cosine :math:`R` computed against every real future in the
local window. The resulting fixed score is
:math:`S=\tfrac14 A+\tfrac14 R+\tfrac12 Z`. Thus a rollout that
makes every step parallel is penalized only when the target
trajectory itself has distinguishable angular structure. No
direct diversity penalty, extra module, batch negative, vocabulary
projection, permutation in the trainable loss, or tunable mixing
coefficient is introduced.
nitp_temporal_intermediate_size (:obj:`int`, *optional*):
Intermediate width of the context proposal and detached NITP-condition
paths. ``None`` resolves to ``2 * hidden_size``. At
``hidden_size=512`` this branch adds ``2,098,176`` parameters, in
addition to the NITP projector.
nitp_temporal_similarity_temperature (:obj:`float`, *optional*, defaults to ``0.1``):
Temperature applied to joint-signature similarities before the
listwise temporal-identification softmax.
nitp_temporal_target_temperature (:obj:`float`, *optional*, defaults to ``0.5``):
Temperature controlling temporal label smoothing. Smaller values
make the correct diagonal step more nearly one-hot, while retaining
limited tolerance for genuinely similar adjacent states.
Constraints:
- ``use_spelling_bee_embeddings=True`` requires calling
``model.model.spelling_bee.set_byte_table(tokenizer)`` before
training (handled automatically by ``setup_model``).
- ``repo_start_layer`` must satisfy
``0 <= repo_start_layer < num_hidden_layers`` when
``use_repo=True``, ``use_repo_grape=True`` or
``use_repo_goat_prior=True``.
- At most one residual-flow mechanism may be active, except the
explicit ``use_stack_memory=True`` + ``use_siamesenorm=True`` pair.
- When ``use_laurel=True``, at least one of ``use_laurel_rw`` or
``use_laurel_lr`` must be ``True``.
- ``stack_d_model`` must be divisible by ``num_mem_heads`` when
``use_stack_memory=True``.
- ``use_nitp_temporal=True`` requires ``use_nitp=True``.
Examples::
>>> from configuration_neollm import NeoLLMConfig
>>> from modeling_neollm import NeoLLMForCausalLM
>>> # Standard dense-embedding model
>>> config = NeoLLMConfig(use_token_generator=False,
... tie_word_embeddings=True)
>>> model = NeoLLMForCausalLM(config)
>>> # Full attention stack
>>> config_full = NeoLLMConfig(
... use_affine_scaled_attention=True,
... use_xsa=True,
... use_lucid_attention=True,
... )
>>> model_full = NeoLLMForCausalLM(config_full)
>>> # Leviathan generator (LEV layer, untied output head)
>>> config_lev = NeoLLMConfig(
... use_token_generator=True,
... tie_word_embeddings=False,
... )
>>> # REPO: context re-positioning from layer 4 onward (default for 12 layers)
>>> config_repo = NeoLLMConfig(
... use_repo=True,
... # repo_start_layer defaults to num_hidden_layers // 3 = 4
... # repo_d_p defaults to hidden_size // 8 = 64
... )
>>> # Proposed REPO-GRAPE-M: REPO coordinates + learned GRAPE spectrum
>>> config_repo_grape = NeoLLMConfig(
... use_repo_grape=True,
... )
>>> # REPO-GRAPE-M + GOAT-style factorised log-prior
>>> config_repo_grape_goat = NeoLLMConfig(
... use_repo_grape=True,
... use_repo_goat_prior=True,
... repo_goat_num_frequencies=3,
... )
References:
Bae, J. et al. (2026). *Affine-Scaled Attention: Towards Flexible and
Stable Transformer Attention.* arXiv:2602.23057.
Duvvuri, S. et al. (2026). *LUCID: Attention with Preconditioned
Representations.* arXiv:2602.10410.
Zhai, S. (2026). *Exclusive Self Attention.* arXiv:2603.09078.
Batley, R. T. & Saha, S. (2026). *A Separable Architecture for Continuous
Token Representation in Language Models.* arXiv:2601.22040.
Robinson, M. et al. (2025). *Token Embeddings Violate the Manifold
Hypothesis.* arXiv:2504.01002.
Rabe, M. N., Clymo, J. & Dong, Z. (2026). *Spelling Bee Embeddings for
Language Modeling.* arXiv:2601.18030.
Li, H., Zhao, T., Cai, D. & Sproat, R. (2026). *REPO: Language Models
with Context Re-Positioning.* arXiv:2512.14391.
Zhang, Y. et al. (2026). *Group Representational Position Encoding.*
ICLR 2026 / arXiv:2512.07805.
Litman, E. & Guo, G. (2026). *You Need Better Attention Priors.*
arXiv:2601.15380.
Menghani, G., Kumar, R. & Kumar, S. (2025). *LAUREL: Learned Augmented
Residual Layer.* ICML 2025. arXiv:2411.07501.
"""
model_type = "neollm"
keys_to_ignore_at_inference = []
def __init__(
self,
vocab_size=64402,
hidden_size=512,
intermediate_size=1536,
num_hidden_layers=12,
num_attention_heads=8,
num_key_value_heads=4,
hidden_act="xielu",
max_position_embeddings=32768,
initializer_range=0.02,
rms_norm_eps=1e-6,
tie_word_embeddings=False,
# ββ Main NTP loss backend: CCE or Liger FLCE βββββββββββββββββββββ
ntp_loss_backend="cce",
use_liger_kernel=False,
cce_loss_impl="cce_kahan_full_c",
use_copy_paste=False,
# ββ Optional extended-CCE objectives and MEAP input corruption ββββ
use_mile_loss=True,
mile_loss_gamma=1.0,
use_mu_loss=True,
mu_loss_lambda=1e-4,
# Must remain disabled in the no-argument configuration. Transformers
# constructs ``NeoLLMConfig()`` while saving to determine class defaults;
# training enables MEAP explicitly together with its mask token ID.
use_meap=False,
meap_mask_ratio=0.15,
meap_mask_token_id=None,
meap_seed=0,
meap_implementation="triton",
meap_exclude_last=True,
meap_protect_structural_tokens=True,
meap_exclude_mask_from_copy=True,
copy_paste_lexical_keys=False,
liger_loss_accum_dtype="float32",
rope_theta=10000.0,
rope_scaling=None,
partial_rotary_factor=0.25,
attention_bias=False,
attention_dropout=0.1,
use_vha_attention=False,
# ββ HOLA-derived episodic memory for FlashAttention-2 βββββββββββββ
use_hola_memory=False,
hola_memory_size=64,
hola_chunk_size=256,
hola_logit_bias_init=-2.0,
hola_rms_gamma_init=1.0,
hola_score_eps=1e-6,
head_dim=64,
linear_attention=None, # Saved option group; user controls are at the end of this signature.
use_momentum_attention=True,
momentum_gamma=0.10,
use_mea_attention=False,
mea_component_key_value_heads=None,
mea_groupnorm_eps=1e-6,
use_lucid_attention=False,
lucid_attention_eps=1e-6,
use_affine_scaled_attention=False,
affine_momentum=0.9,
use_xsa=True,
xsa_eps=1e-6,
# ββ Directional Routing (Taylor, 2026) ββββββββββββββββββββββββββββ
use_directional_routing=False,
directional_routing_k=4,
directional_routing_temp=3.0,
# ββ Attention Residuals (Kimi Team, 2026) βββββββββββββββββββββββββ
use_attn_res=False,
attn_res_num_blocks=4,
# MSAR may also be paired with the existing SiameseNorm residual flow.
use_msar=True,
use_ldm=False,
msar_block_branches=None, # auto: approximately eight depth blocks
msar_kernel_sizes=(4, 8, 12),
msar_backend="auto", # Triton on CUDA, Torch on CPU; "torch" is a reference
# ββ StackMemory / STACKTRANS (Zhang et al., NeurIPS 2025) βββββββ
use_stack_memory=False,
stack_d_model=24, # H * d_s = 4 * 6
num_mem_heads=4, # H = 4
stack_slots=16, # S = 16
stack_memory_cache_size=2048,
stack_entropy_loss_weight=1e-3,
# ββ ResFormer cross-layer FAN residual (He et al., 2023) βββββββββ
use_fan_residual=False,
fan_ratio=0.125,
fan_ratio_ffn=0.0625,
dropout_rate=0.1,
# ββ Learnable Multipliers (Velikanov et al., 2026) βββββββββββββββββ
use_learnable_multipliers=True,
use_embedding_multipliers=False,
# ββ Normalization controls ββββββββββββββββββββββββββββββββββββββββ
use_lns=True,
use_gpas=False,
use_siamesenorm=True,
use_dagformer=False,
dagformer=None,
siamese_normalized_input=True,
siamese_depth_scaling=True,
siamese_attn_x_scale_init=1.0,
# ββ Embedding input normalization βββββββββββββββββββββββββββββββββ
use_embedding_input_norm=True,
# ββ Leviathan continuous token generator ββββββββββββββββββββββββββ
use_token_generator=True,
generator_d_seed=128,
generator_num_modes=8,
generator_num_knots=16,
generator_spline_degree=2,
generator_k=3,
generator_krank=64,
# ββ Leviathan-JTok / JTok-M continuous modulation βββββββββββββββββ
use_jtok=True,
use_jtokm=True,
jtok_num_modes=4,
jtok_num_experts=5,
jtok_top_k=2,
jtok_norm_eps=1e-6,
jtok_aux_loss_weight=1e-4,
jtok_kernel_backend="triton",
# ββ Hadamard output projection (Aggarwal & Kumar, 2026) βββββββββββ
use_hadamard_o_proj=True,
# ββ PolyNorm exclusivity ββββββββββββββββββββββββββββββββββββββββββ
polynorm_exclusive=False,
# ββ Spelling Bee Embeddings (Rabe et al., 2026) βββββββββββββββββββ
use_spelling_bee_embeddings=False,
# ββ Context Re-Positioning (Li et al., 2026) ββββββββββββββββββββββ
# GOAT's mutually exclusive keyword-only `use_goat` flag is below,
# next to the linear-attention options, to preserve positional callers.
use_repo=True,
repo_start_layer=None,
repo_d_p=None,
use_repo_grape=True,
use_repo_goat_prior=False,
repo_goat_num_frequencies=3,
repo_goat_sink_decay=4.0,
# ββ LAuReL: Learned Augmented Residual Layer (Menghani et al., 2025) β
use_laurel=False,
use_laurel_rw=False,
use_laurel_lr=False,
laurel_lr_rank=32,
# ββ TWEO: Transformers Without Extreme Outliers (Liang et al., 2026)
use_tweo=True,
tweo_loss_weight=0.01,
tweo_tau=3.0,
tweo_power=4.0,
tweo_eps=1e-6,
# ββ NITP: Next Implicit Token Prediction (Zhang et al., 2026) βββββ
use_nitp=True,
nitp_target_layer=None,
nitp_loss_weight=1.0,
nitp_projector_intermediate_size=None,
# ββ NITP temporal transition / identification extension ββββββββββ
# This is deliberately a NITP-side module, not the existing NextLat
# implementation. It learns the causal latent update
# z_{t+1} = stopgrad(P_NITP(h_t^L))
# (h_t^L, z_{t+1}) -> h_{t+1}^L
# and recursively recomputes z from every predicted state.
# `nitp_temporal_apply_loss=False` keeps the module instantiated and
# computes every diagnostic metric, but does not add its objective to
# the model loss. This is the requested monitoring-only ablation.
use_nitp_temporal=False,
nitp_temporal_apply_loss=False,
nitp_temporal_horizon=4,
nitp_temporal_dynamics_weight=1.0,
nitp_temporal_identification_weight=0.1,
nitp_temporal_intermediate_size=None,
nitp_temporal_similarity_temperature=0.1,
nitp_temporal_target_temperature=0.5,
# ββ NextLat: Next-Latent Prediction (Teoh et al., 2026) βββββββββββ
use_nextlat=False,
nextlat_horizon=1,
nextlat_mse_weight=1.0,
nextlat_kl_weight=1.0,
nextlat_dynamics_proj_factor=1.0,
# ββ Interleaved Head Attention (Duvvuri et al., 2026) βββββββββββββ
use_iha=False,
iha_num_pseudo_heads=2, # P=2 β 2Γ2=4 patrones por head
iha_local_global_pattern="LLLLG", # 4 locales + 1 global (paper Β§5.1)
iha_sliding_window=None, # auto = context // (2*P^2), independent of padding
iha_global_layers_use_iha=False, # False replica el paper: la capa G es global estΓ‘ndar, sin IHA
# ββ CKDA / GDN2 linear attention ββββββββββββββββββββββββββββββββββ
# Keyword-only to preserve positional compatibility with old configs.
*,
use_goat=False,
goat_kernel_backend="auto",
use_linear_attention=True, # None: infer; False: disable; True: require linear layers
linear_attention_type="ckda", # "none", "ckda", or "gdn2"
linear_attention_full_attention_every=3, # 2 linear + 1 full with 12 layers
linear_attention_layer_types=None, # Optional per-layer list overrides type and interval
linear_attention_num_heads=None, # None: inherit num_attention_heads
linear_attention_head_dim=None, # None: inherit the model's head_dim
linear_attention_expand_v=1.0, # Value-head width / linear head_dim
linear_attention_conv_size=4, # Causal short-convolution width
# ββ SFT/DPO structural protection (opt-in, pretraining-off) βββββββ
meap_structural_token_ids=None,
meap_protect_chat_headers=False,
meap_protect_ignored_labels=False,
copy_exclude_structural_tokens=False,
copy_exclude_token_ids=None,
copy_exclude_chat_headers=False,
copy_chat_im_start_token_id=6,
copy_chat_im_end_token_id=7,
copy_chat_newline_token_id=708,
**kwargs,
):
# ββ Main NTP loss backend βββββββββββββββββββββββββββββββββββββββββ
ntp_loss_backend = str(ntp_loss_backend).strip().lower()
if use_liger_kernel:
ntp_loss_backend = "liger"
elif ntp_loss_backend == "liger":
use_liger_kernel = True
elif ntp_loss_backend != "cce":
raise ValueError(
"`ntp_loss_backend` must be either 'cce' or 'liger'. "
f"Got {ntp_loss_backend!r}."
)
if not str(cce_loss_impl).strip():
raise ValueError("`cce_loss_impl` must be a non-empty string.")
if (use_mile_loss or use_mu_loss) and ntp_loss_backend != "cce":
raise ValueError(
"MiLe and mu-loss require `ntp_loss_backend='cce'`; they are "
"not implemented by the Liger loss backend."
)
if not math.isfinite(float(mile_loss_gamma)) or mile_loss_gamma < 0.0:
raise ValueError(
f"`mile_loss_gamma` must be finite and >= 0, got {mile_loss_gamma}."
)
if not math.isfinite(float(mu_loss_lambda)) or mu_loss_lambda < 0.0:
raise ValueError(
f"`mu_loss_lambda` must be finite and >= 0, got {mu_loss_lambda}."
)
if not math.isfinite(float(meap_mask_ratio)) or not 0.0 <= meap_mask_ratio <= 1.0:
raise ValueError(
f"`meap_mask_ratio` must be finite and in [0, 1], got {meap_mask_ratio}."
)
if use_meap and meap_mask_token_id is None:
raise ValueError("`meap_mask_token_id` is required when `use_meap=True`.")
if meap_mask_token_id is not None:
meap_mask_token_id = int(meap_mask_token_id)
if not 0 <= meap_mask_token_id < int(vocab_size):
raise ValueError(
"`meap_mask_token_id` must be inside the configured vocabulary."
)
if use_meap:
reserved_for_model = {
token_id
for value in (
kwargs.get("pad_token_id"),
kwargs.get("bos_token_id"),
kwargs.get("eos_token_id"),
)
for token_id in (value if isinstance(value, (list, tuple)) else (value,))
if token_id is not None
}
if meap_mask_token_id in reserved_for_model:
raise ValueError(
"`meap_mask_token_id` must differ from PAD, BOS, and EOS."
)
if not isinstance(meap_seed, int) or not 0 <= meap_seed <= 0xFFFFFFFF:
raise ValueError("`meap_seed` must be an integer in [0, 2**32 - 1].")
meap_implementation = str(meap_implementation).strip().lower()
if meap_implementation not in {"triton", "torch"}:
raise ValueError("`meap_implementation` must be 'triton' or 'torch'.")
_valid_liger_accum_dtypes = {
None,
"",
"none",
"null",
"auto",
"default",
"original",
"float32",
"fp32",
"float",
"torch.float32",
"bfloat16",
"bf16",
"torch.bfloat16",
"float16",
"fp16",
"half",
"torch.float16",
}
if (
liger_loss_accum_dtype is not None
and str(liger_loss_accum_dtype).strip().lower()
not in _valid_liger_accum_dtypes
):
raise ValueError(
"`liger_loss_accum_dtype` must be one of None/'none', "
"'float32'/'fp32', 'bfloat16'/'bf16', or 'float16'/'fp16'. "
f"Got {liger_loss_accum_dtype!r}."
)
# ββ Generator / tying consistency βββββββββββββββββββββββββββββββββ
if use_token_generator and tie_word_embeddings:
logger.warning(
"`use_token_generator=True` is incompatible with "
"`tie_word_embeddings=True`. "
"Automatically setting `tie_word_embeddings=False`. "
"The continuous generator replaces the discrete lookup table "
"with a learned smooth surface, so input and output parameters "
"are always structurally decoupled."
)
tie_word_embeddings = False
# ββ Leviathan-JTok activation contract βββββββββββββββββββββββββββ
if use_jtok and not use_token_generator:
raise ValueError(
"`use_jtok=True` requires `use_token_generator=True`; "
"JTok consumes the shared Leviathan token coordinate."
)
if use_jtokm and not use_jtok:
raise ValueError(
"`use_jtokm=True` requires `use_jtok=True`; enable the base "
"continuous JTok modulation first."
)
if int(jtok_num_modes) < 1:
raise ValueError("`jtok_num_modes` must be >= 1.")
if int(jtok_num_experts) < 1:
raise ValueError("`jtok_num_experts` must be >= 1.")
if int(jtok_top_k) < 1 or int(jtok_top_k) > int(jtok_num_experts):
raise ValueError(
"`jtok_top_k` must satisfy 1 <= jtok_top_k <= jtok_num_experts."
)
if float(jtok_norm_eps) <= 0.0:
raise ValueError("`jtok_norm_eps` must be > 0.")
if float(jtok_aux_loss_weight) < 0.0:
raise ValueError("`jtok_aux_loss_weight` must be >= 0.")
jtok_kernel_backend = str(jtok_kernel_backend).strip().lower()
if jtok_kernel_backend not in {"torch", "triton"}:
raise ValueError(
"`jtok_kernel_backend` must be either `torch` or `triton`."
)
# ββ Embedding multiplier applicability βββββββββββββββββββββββββββββ
if use_embedding_multipliers:
if not use_learnable_multipliers:
logger.warning(
"`use_embedding_multipliers=True` is inactive because "
"`use_learnable_multipliers=False`. No embedding multiplier "
"parameters will be instantiated."
)
elif use_token_generator:
logger.warning(
"`use_embedding_multipliers=True` is inactive because "
"`use_token_generator=True` replaces the standard embedding "
"matrix with LeviathanGenerator."
)
elif tie_word_embeddings:
logger.warning(
"`use_embedding_multipliers=True` is inactive because "
"`tie_word_embeddings=True`; embedding multipliers would "
"break clean input/output parameter sharing."
)
if use_goat and (use_repo or use_repo_grape or use_repo_goat_prior):
raise ValueError(
"`use_goat=True` cannot be combined with `use_repo`, "
"`use_repo_grape`, or `use_repo_goat_prior`. Set all three "
"to False; GOAT replaces standard RoPE automatically."
)
if use_goat and use_hola_memory:
raise ValueError("`use_goat=True` does not yet support `use_hola_memory=True`.")
# ββ REPO: resolve defaults and validate βββββββββββββββββββββββββββ
# repo_start_layer defaults to num_hidden_layers // 3, matching the
# paper's 1/3-of-depth heuristic (Li et al., 2026, Β§3).
# repo_d_p defaults to hidden_size // 8, matching the paper's
# assumption that positional information is less rich than the full
# hidden representation (Li et al., 2026, Β§3.2).
if repo_start_layer is None:
repo_start_layer = num_hidden_layers // 3
if repo_d_p is None:
repo_d_p = hidden_size // 8
if (use_repo or use_repo_grape or use_repo_goat_prior) and not (
0 <= repo_start_layer < num_hidden_layers
):
raise ValueError(
f"`repo_start_layer` must satisfy "
f"0 <= repo_start_layer < num_hidden_layers, "
f"got repo_start_layer={repo_start_layer}, "
f"num_hidden_layers={num_hidden_layers}."
)
# ββ REPO-GOAT prior: validate factorised prior dimensions βββββββββ
if use_repo_goat_prior:
if repo_goat_num_frequencies < 0:
raise ValueError(
f"`repo_goat_num_frequencies` must be >= 0, "
f"got {repo_goat_num_frequencies}."
)
if repo_goat_sink_decay <= 0.0:
raise ValueError(
f"`repo_goat_sink_decay` must be > 0, got {repo_goat_sink_decay}."
)
_repo_goat_prior_dim = 2 * int(repo_goat_num_frequencies) + 2
if (head_dim + _repo_goat_prior_dim) % 8 != 0:
logger.warning(
"`use_repo_goat_prior=True` appends %d prior channels to "
"head_dim=%d, giving internal attention dim=%d. Some "
"FlashAttention builds prefer dimensions divisible by 8; "
"the default repo_goat_num_frequencies=3 gives +8.",
_repo_goat_prior_dim,
head_dim,
head_dim + _repo_goat_prior_dim,
)
# ββ SiameseNorm: RMS-only topology by construction ββββββββββββββββ
# ββ IHA / MEA compatibility βββββββββββββββββββββββββββββββββββββββ
# The implementation keeps both modules in-place:
# IHA acts first on Q/K/V component heads.
# MEA then applies its [H_comp, H_kv] mixing independently inside
# each IHA pseudo-slot on K/V.
# This preserves IHA's pseudo-head structure and the GQA ratio
# (H_q*P) / (H_kv*P) = H_q / H_kv without moving other attention ops.
if use_iha and iha_num_pseudo_heads < 1:
raise ValueError(
f"`iha_num_pseudo_heads` must be >= 1, got {iha_num_pseudo_heads}."
)
if use_iha:
_iha_pattern = str(iha_local_global_pattern).upper().strip()
if not _iha_pattern:
raise ValueError(
"`iha_local_global_pattern` must not be empty when `use_iha=True`."
)
_bad_iha_pattern_chars = sorted(set(_iha_pattern) - {"L", "G"})
if _bad_iha_pattern_chars:
raise ValueError(
"`iha_local_global_pattern` only accepts 'L' and 'G'. "
f"Got invalid characters: {_bad_iha_pattern_chars}."
)
# ββ Residual-flow mechanism mutex βββββββββββββββββββββββββββββββββ
# AttnRes and LAuReL compete directly with residual topology.
# StackMemory and MSAR may separately be paired with SiameseNorm. The
# hybrid keeps the X/Y updates and reads MSAR's shared branch history.
_residual_flow_flags = {
"use_laurel": bool(use_laurel),
"use_attn_res": bool(use_attn_res),
"use_stack_memory": bool(use_stack_memory),
"use_siamesenorm": bool(use_siamesenorm),
"use_msar": bool(use_msar),
"use_ldm": bool(use_ldm),
}
_active_residual_flow = [
name for name, enabled in _residual_flow_flags.items() if enabled
]
allow_stack_siamese = (
bool(use_stack_memory)
and bool(use_siamesenorm)
and not bool(use_laurel)
and not bool(use_attn_res)
and not bool(use_msar)
and not bool(use_ldm)
)
allow_msar_siamese = (
bool(use_msar) and bool(use_siamesenorm)
and not bool(use_stack_memory) and not bool(use_laurel)
and not bool(use_attn_res)
and not bool(use_ldm)
)
allow_ldm_siamese = (
bool(use_ldm) and bool(use_siamesenorm)
and not any((use_stack_memory, use_laurel, use_attn_res, use_msar))
)
if len(_active_residual_flow) > 1 and not (allow_stack_siamese or allow_msar_siamese or allow_ldm_siamese):
raise ValueError(
"Enable at most one residual-flow mechanism among "
"`use_laurel`, `use_attn_res`, `use_stack_memory`, "
"`use_siamesenorm`, `use_msar`, and `use_ldm`, except the explicit "
"`use_stack_memory` + `use_siamesenorm` and "
"`use_msar` + `use_siamesenorm` and `use_ldm` + `use_siamesenorm` pairs. "
f"Active flags: {_active_residual_flow}."
)
# MSAR owns the residual path: reject other residual contributors too.
if use_msar and (use_gpas or use_fan_residual or use_dagformer):
raise ValueError(
"`use_msar=True` cannot be combined with `use_gpas`, "
"`use_fan_residual`, or `use_dagformer`."
)
if use_ldm and (use_gpas or use_fan_residual or use_dagformer):
raise ValueError(
"`use_ldm=True` cannot be combined with `use_gpas`, "
"`use_fan_residual`, or `use_dagformer`."
)
if msar_block_branches is None:
# Branch granularity counts attention and MLP independently. Do not
# round to whole decoder layers: e.g. 24 branches / 8 = 3.
msar_block_branches = max(1, math.ceil(2 * num_hidden_layers / 8))
if isinstance(msar_block_branches, bool) or not isinstance(msar_block_branches, int) or msar_block_branches < 1:
raise ValueError("`msar_block_branches` must be a positive integer.")
if (not isinstance(msar_kernel_sizes, (tuple, list)) or not msar_kernel_sizes
or any(isinstance(k, bool) or not isinstance(k, int) or k < 1 for k in msar_kernel_sizes)):
raise ValueError("`msar_kernel_sizes` must contain positive integer widths.")
if msar_backend not in ("auto", "torch"):
raise ValueError("`msar_backend` must be 'auto' or 'torch'.")
# ββ LAuReL: sub-flag consistency ββββββββββββββββββββββββββββββββββ
if use_laurel and not use_laurel_rw and not use_laurel_lr:
raise ValueError(
"`use_laurel=True` requires at least one sub-variant to be active. "
"Set `use_laurel_rw=True` and/or `use_laurel_lr=True`."
)
# ββ TWEO: resolve paper-faithful defaults and validate ββββββββββββ
# Liang et al. (2026) regularize final output activations from all
# Transformer blocks with mean((abs(A) / (tau + eps)) ** p). The paper
# uses tau=3, p=4, lambda=0.01 and leaves scheduling of lambda(t) to
# the training loop.
if tweo_loss_weight < 0.0:
raise ValueError(
f"`tweo_loss_weight` must be >= 0, got {tweo_loss_weight}."
)
if tweo_tau <= 0.0:
raise ValueError(f"`tweo_tau` must be > 0, got {tweo_tau}.")
if tweo_power <= 0.0:
raise ValueError(f"`tweo_power` must be > 0, got {tweo_power}.")
if tweo_eps < 0.0:
raise ValueError(f"`tweo_eps` must be >= 0, got {tweo_eps}.")
# ββ NITP: resolve paper-faithful defaults and validate ββββββββββββ
# Zhang et al. (2026) select a shallow contextualized target layer
# around 20% of total depth, use cosine loss, stop-gradient targets,
# and a SwiGLU projector with intermediate dimension 4d.
# Current caveat: NITP is retained as a separate option, but the
# CCE + torch.compile CUDA Graph Trees path reproduced an overwritten
# graph-output error when NITP shares final hidden states with CCE.
if nitp_target_layer is None:
nitp_target_layer = max(1, int(round(num_hidden_layers * 0.2)))
if not (1 <= int(nitp_target_layer) <= num_hidden_layers):
raise ValueError(
f"`nitp_target_layer` must satisfy "
f"1 <= nitp_target_layer <= num_hidden_layers, "
f"got nitp_target_layer={nitp_target_layer}, "
f"num_hidden_layers={num_hidden_layers}."
)
if nitp_loss_weight < 0.0:
raise ValueError(
f"`nitp_loss_weight` must be >= 0, got {nitp_loss_weight}."
)
if nitp_projector_intermediate_size is None:
nitp_projector_intermediate_size = 4 * hidden_size
if int(nitp_projector_intermediate_size) <= 0:
raise ValueError(
"`nitp_projector_intermediate_size` must be positive, "
f"got {nitp_projector_intermediate_size}."
)
# ββ NITP temporal transition / identification ββββββββββββββββββββ
# The extension is intentionally anchored to the active NITP branch:
# it reuses NITP's final hidden states, shallow target states and
# projector for diagnostics, but owns a separate SwiGLU transition
# module so enabling it genuinely increases the parameter count.
if use_nitp_temporal and not use_nitp:
raise ValueError(
"`use_nitp_temporal=True` requires `use_nitp=True` because "
"the temporal branch is defined as an extension of NITP."
)
if int(nitp_temporal_horizon) < 1:
raise ValueError(
"`nitp_temporal_horizon` must be >= 1, "
f"got {nitp_temporal_horizon}."
)
if nitp_temporal_dynamics_weight < 0.0:
raise ValueError(
"`nitp_temporal_dynamics_weight` must be >= 0, "
f"got {nitp_temporal_dynamics_weight}."
)
if nitp_temporal_identification_weight < 0.0:
raise ValueError(
"`nitp_temporal_identification_weight` must be >= 0, "
f"got {nitp_temporal_identification_weight}."
)
if nitp_temporal_intermediate_size is None:
# For d=512 this resolves to 1024. The conditioned
# multiplicative transition adds 4dm + 2d = 2,098,176 trainable
# parameters, including the two affine RMSNorm scales.
nitp_temporal_intermediate_size = 2 * hidden_size
if int(nitp_temporal_intermediate_size) <= 0:
raise ValueError(
"`nitp_temporal_intermediate_size` must be positive, "
f"got {nitp_temporal_intermediate_size}."
)
if nitp_temporal_similarity_temperature <= 0.0:
raise ValueError(
"`nitp_temporal_similarity_temperature` must be > 0, "
f"got {nitp_temporal_similarity_temperature}."
)
if nitp_temporal_target_temperature <= 0.0:
raise ValueError(
"`nitp_temporal_target_temperature` must be > 0, "
f"got {nitp_temporal_target_temperature}."
)
# ββ NextLat: resolve paper-faithful defaults and validate βββββββββ
# Teoh et al. train a latent dynamics model p_psi(h_t, x_{t+1}) to
# recursively predict final-layer hidden states with Smooth L1 and KL
# supervision over a teacher-forced horizon d.
# Current caveat: the objective is usable in eager mode with CCE, but
# CCE + torch.compile CUDA Graph Trees reproduced the same overwritten
# graph-output error seen with NITP because both auxiliary branches
# share final hidden states with the CCE path.
if int(nextlat_horizon) < 1:
raise ValueError(f"`nextlat_horizon` must be >= 1, got {nextlat_horizon}.")
if nextlat_mse_weight < 0.0:
raise ValueError(
f"`nextlat_mse_weight` must be >= 0, got {nextlat_mse_weight}."
)
if nextlat_kl_weight < 0.0:
raise ValueError(
f"`nextlat_kl_weight` must be >= 0, got {nextlat_kl_weight}."
)
if nextlat_dynamics_proj_factor <= 0.0:
raise ValueError(
"`nextlat_dynamics_proj_factor` must be > 0, "
f"got {nextlat_dynamics_proj_factor}."
)
# ββ StackMemory: source-code shape constraints ββββββββββββββββββββ
if use_stack_memory:
if stack_d_model <= 0:
raise ValueError(f"`stack_d_model` must be > 0, got {stack_d_model}.")
if num_mem_heads <= 0:
raise ValueError(f"`num_mem_heads` must be > 0, got {num_mem_heads}.")
if stack_slots <= 0:
raise ValueError(f"`stack_slots` must be > 0, got {stack_slots}.")
if stack_d_model % num_mem_heads != 0:
raise ValueError(
f"`stack_d_model` must be divisible by `num_mem_heads`, "
f"got stack_d_model={stack_d_model}, num_mem_heads={num_mem_heads}."
)
if (
not math.isfinite(float(stack_entropy_loss_weight))
or float(stack_entropy_loss_weight) < 0.0
):
raise ValueError(
"`stack_entropy_loss_weight` must be finite and >= 0, "
f"got {stack_entropy_loss_weight}."
)
# Keep one compact, serializable group of options. Unspecified geometry
# follows the actual model rather than a particular training batch.
linear_options = {
"type": linear_attention_type,
"full_attention_every": linear_attention_full_attention_every,
"layer_types": linear_attention_layer_types,
"num_heads": linear_attention_num_heads,
"head_dim": linear_attention_head_dim,
"expand_v": linear_attention_expand_v,
"conv_size": linear_attention_conv_size,
}
if linear_attention is not None:
if not isinstance(linear_attention, dict):
raise ValueError("`linear_attention` must be a dictionary or None.")
unknown = set(linear_attention) - set(linear_options)
if unknown:
raise ValueError(f"Unknown linear_attention options: {sorted(unknown)}")
linear_options.update(linear_attention)
kind = linear_options["type"]
if not isinstance(kind, str) or kind not in {"none", "ckda", "gdn2"}:
raise ValueError("linear_attention.type must be 'none', 'ckda' or 'gdn2'.")
every = linear_options["full_attention_every"]
if isinstance(every, bool) or not isinstance(every, Integral) or every <= 0:
raise ValueError("linear_attention.full_attention_every must be a positive integer.")
layers = linear_options["layer_types"]
if layers is not None:
if not isinstance(layers, (list, tuple)) or len(layers) != num_hidden_layers:
raise ValueError("linear_attention.layer_types must have one entry per decoder layer.")
if any(not isinstance(layer, str) or layer not in {"full", "ckda", "gdn2"} for layer in layers):
raise ValueError("Each linear_attention.layer_types entry must be 'full', 'ckda' or 'gdn2'.")
linear_options["layer_types"] = list(layers)
if use_linear_attention is not None and not isinstance(use_linear_attention, bool):
raise ValueError("use_linear_attention must be True, False, or None.")
requested_linear = (any(layer != "full" for layer in layers) if layers is not None
else kind != "none")
if use_linear_attention is True and not requested_linear:
raise ValueError("use_linear_attention=True requires a CKDA or GDN2 layer.")
has_linear = requested_linear and use_linear_attention is not False
if has_linear and layers is None and num_hidden_layers > 1 and every == 1:
raise ValueError("full_attention_every=1 would leave no linear layers; disable linear attention instead.")
if has_linear:
if use_dagformer:
raise ValueError("DAGFormer Q/K/V routing is not implemented for CKDA/GDN2 layers.")
linear_heads = (num_attention_heads if linear_options["num_heads"] is None
else linear_options["num_heads"])
linear_head_dim = (head_dim if linear_options["head_dim"] is None
else linear_options["head_dim"])
for name, value in (("num_heads", linear_heads), ("head_dim", linear_head_dim),
("conv_size", linear_options["conv_size"])):
if isinstance(value, bool) or not isinstance(value, Integral) or value <= 0:
raise ValueError(f"linear_attention.{name} must be a positive integer.")
expansion = float(linear_options["expand_v"])
if not math.isfinite(expansion) or expansion <= 0 or round(linear_head_dim * expansion) < 1 or not math.isclose(
linear_head_dim * expansion, round(linear_head_dim * expansion), rel_tol=0, abs_tol=1e-8
):
raise ValueError("linear_attention.expand_v must produce a positive integral value-head dimension.")
linear_options["expand_v"] = expansion
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
# ββ Core Transformer ββββββββββββββββββββββββββββββββββββββββββββββ
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
if use_vha_attention and (
isinstance(num_attention_heads, bool) or not isinstance(num_attention_heads, Integral)
or isinstance(num_key_value_heads, bool) or not isinstance(num_key_value_heads, Integral)
or num_attention_heads <= 0 or num_key_value_heads <= 0
or num_attention_heads % num_key_value_heads != 0
):
raise ValueError("VHA requires positive query/KV head counts, with KV heads dividing query heads.")
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
# ββ Main NTP loss backend βββββββββββββββββββββββββββββββββββββββββ
self.ntp_loss_backend = ntp_loss_backend
self.use_liger_kernel = bool(use_liger_kernel)
self.cce_loss_impl = str(cce_loss_impl).strip()
self.use_copy_paste = bool(use_copy_paste)
self.use_mile_loss = bool(use_mile_loss)
self.mile_loss_gamma = float(mile_loss_gamma)
self.use_mu_loss = bool(use_mu_loss)
self.mu_loss_lambda = float(mu_loss_lambda)
self.use_meap = bool(use_meap)
self.meap_mask_ratio = float(meap_mask_ratio)
self.meap_mask_token_id = (
None if meap_mask_token_id is None else int(meap_mask_token_id)
)
self.meap_seed = int(meap_seed)
self.meap_implementation = meap_implementation
self.meap_exclude_last = bool(meap_exclude_last)
self.meap_protect_structural_tokens = bool(meap_protect_structural_tokens)
self.meap_exclude_mask_from_copy = bool(meap_exclude_mask_from_copy)
self.copy_paste_lexical_keys = bool(copy_paste_lexical_keys)
self.liger_loss_accum_dtype = liger_loss_accum_dtype
# ββ Positional encoding βββββββββββββββββββββββββββββββββββββββββββ
self.rope_theta = rope_theta
self.rope_scaling = rope_scaling
self.partial_rotary_factor = partial_rotary_factor
# ββ Attention βββββββββββββββββββββββββββββββββββββββββββββββββββββ
self.attention_bias = attention_bias
self.attention_dropout = attention_dropout
self.use_vha_attention = bool(use_vha_attention)
# ββ HOLA-derived episodic memory for FlashAttention-2 βββββββββββββ
self.use_hola_memory = bool(use_hola_memory)
self.hola_memory_size = int(hola_memory_size)
self.hola_chunk_size = int(hola_chunk_size)
self.hola_logit_bias_init = float(hola_logit_bias_init)
self.hola_rms_gamma_init = float(hola_rms_gamma_init)
self.hola_score_eps = float(hola_score_eps)
self.head_dim = head_dim
# Preserve None as the legacy auto mode so explicit False survives HF's
# config diff serialization even when a linear schedule is retained.
self.use_linear_attention = use_linear_attention
self.linear_attention = linear_options
self.use_momentum_attention = use_momentum_attention
self.momentum_gamma = momentum_gamma
self.use_mea_attention = use_mea_attention
self.mea_component_key_value_heads = (
num_key_value_heads
if mea_component_key_value_heads is None
else int(mea_component_key_value_heads)
)
self.mea_groupnorm_eps = mea_groupnorm_eps
self.use_lucid_attention = use_lucid_attention
self.lucid_attention_eps = lucid_attention_eps
self.use_affine_scaled_attention = use_affine_scaled_attention
self.affine_momentum = affine_momentum
self.use_xsa = use_xsa
self.xsa_eps = xsa_eps
# ββ Directional Routing βββββββββββββββββββββββββββββββββββββββββββ
self.use_directional_routing = use_directional_routing
self.directional_routing_k = directional_routing_k
self.directional_routing_temp = directional_routing_temp
# ββ Attention Residuals βββββββββββββββββββββββββββββββββββββββββββ
# use_attn_res=True: replace fixed residual accumulation with learned
# depth-wise softmax attention over preceding layer outputs.
# attn_res_num_blocks=0: Full AttnRes β all previous layer outputs
# are kept as sources (N grows to num_hidden_layers+1).
# attn_res_num_blocks=4: Block AttnRes β 4 block summaries maximum,
# block_size = num_hidden_layers // 4 = 3 layers per block.
# Memory cost: O(num_blocks Γ batch Γ seq Γ hidden) instead of
# O(num_layers Γ batch Γ seq Γ hidden).
self.use_msar = bool(use_msar)
self.use_ldm = bool(use_ldm)
# Follow the paper's value width = attention head width, even when
# num_attention_heads * head_dim differs from hidden_size. For an
# incompatible width choose the closest divisor without padding values.
divisors = (g for g in range(1, hidden_size + 1) if hidden_size % g == 0)
self.ldm_groups = min(divisors,
key=lambda g: (abs(hidden_size // g - head_dim),
abs(g - num_attention_heads)))
self.ldm_key_dim = min(8, hidden_size // self.ldm_groups)
self.ldm_hidden_dim = min(32, hidden_size)
self.msar_block_branches = msar_block_branches
self.msar_kernel_sizes = tuple(msar_kernel_sizes)
self.msar_backend = msar_backend
self.use_attn_res = use_attn_res
self.attn_res_num_blocks = attn_res_num_blocks
# ββ StackMemory / STACKTRANS ββββββββββββββββββββββββββββββββββββββ
self.use_stack_memory = use_stack_memory
self.stack_d_model = stack_d_model
self.num_mem_heads = num_mem_heads
self.stack_slots = stack_slots
self.stack_memory_cache_size = stack_memory_cache_size
self.stack_entropy_loss_weight = float(stack_entropy_loss_weight)
rope_config_validation(self)
# ββ FANformer periodicity βββββββββββββββββββββββββββββββββββββββββ
self.use_fan_residual = use_fan_residual
self.fan_ratio = fan_ratio
self.fan_ratio_ffn = fan_ratio_ffn
# ββ Regularization ββββββββββββββββββββββββββββββββββββββββββββββββ
self.dropout_rate = dropout_rate
# ββ Learnable Multipliers βββββββββββββββββββββββββββββββββββββββββ
self.use_learnable_multipliers = use_learnable_multipliers
self.use_embedding_multipliers = use_embedding_multipliers
# ββ Normalization controls ββββββββββββββββββββββββββββββββββββββββ
self.use_lns = bool(use_lns)
self.use_gpas = bool(use_gpas)
self.use_siamesenorm = bool(use_siamesenorm)
self.use_dagformer = bool(use_dagformer)
if use_dagformer and (use_jtok or use_jtokm):
raise ValueError("DAGFormer requires use_jtok=False and use_jtokm=False; choose one method.")
dag_defaults = dict(predictor_dim=256, predictor_layers=2, predictor_heads=4,
local_dim=128, input_source="tokens")
if dagformer is not None:
if not isinstance(dagformer, dict) or set(dagformer) - set(dag_defaults):
raise ValueError("dagformer accepts predictor_dim, predictor_layers, predictor_heads, local_dim and input_source")
dag_defaults.update(dagformer)
if (not isinstance(dag_defaults["input_source"], str)
or dag_defaults["input_source"] not in {"tokens", "embeddings"}):
raise ValueError("dagformer.input_source must be tokens or embeddings")
if (any(type(value) is not int or value < 1 for key,value in dag_defaults.items() if key != "input_source")
or dag_defaults["predictor_dim"] % dag_defaults["predictor_heads"]):
raise ValueError("DAGFormer dimensions must be positive and predictor_dim divisible by heads")
self.dagformer = dag_defaults
self.siamese_normalized_input = bool(siamese_normalized_input)
self.siamese_depth_scaling = bool(siamese_depth_scaling)
self.siamese_attn_x_scale_init = float(siamese_attn_x_scale_init)
# ββ Embedding input normalization βββββββββββββββββββββββββββββββββ
# True preserves the previous layer-0 pre-norm path, using the active
# norm implementation:
# embeddings -> RMSNorm -> LNS -> attention.
# False removes that first input-norm module entirely, so raw embeddings
# enter the first attention block and the layer-0 input-norm parameters
# are not counted; layers >= 1 keep their pre-norm unchanged.
self.use_embedding_input_norm = use_embedding_input_norm
# ββ Leviathan generator βββββββββββββββββββββββββββββββββββββββββββ
self.use_token_generator = use_token_generator
self.generator_d_seed = generator_d_seed
self.generator_num_modes = generator_num_modes
self.generator_num_knots = generator_num_knots
self.generator_spline_degree = generator_spline_degree
self.generator_k = generator_k
self.generator_krank = generator_krank
# ββ Leviathan-JTok / JTok-M continuous modulation ββββββββββββββββ
self.use_jtok = bool(use_jtok)
self.use_jtokm = bool(use_jtokm)
self.jtok_num_modes = int(jtok_num_modes)
self.jtok_num_experts = int(jtok_num_experts)
self.jtok_top_k = int(jtok_top_k)
self.jtok_norm_eps = float(jtok_norm_eps)
self.jtok_aux_loss_weight = float(jtok_aux_loss_weight)
# Runtime dispatch only. No parameter/buffer is created and old
# config.json files missing this field default to the Torch path.
self.jtok_kernel_backend = jtok_kernel_backend
# ββ Hadamard output projection (Aggarwal & Kumar, 2026) βββββββββββ
self.use_hadamard_o_proj = use_hadamard_o_proj
# ββ PolyNorm exclusivity ββββββββββββββββββββββββββββββββββββββββββ
self.polynorm_exclusive = polynorm_exclusive
# ββ Spelling Bee Embeddings (Rabe et al., 2026) βββββββββββββββββββ
self.use_spelling_bee_embeddings = use_spelling_bee_embeddings
# ββ Context Re-Positioning (Li et al., 2026) ββββββββββββββββββββββ
self.use_repo = use_repo
self.use_goat = bool(use_goat)
self.goat_kernel_backend = str(goat_kernel_backend).strip().lower()
if self.goat_kernel_backend not in {"auto", "torch"}:
raise ValueError("`goat_kernel_backend` must be 'auto' or 'torch'.")
self.repo_start_layer = repo_start_layer
self.repo_d_p = repo_d_p
self.use_repo_grape = use_repo_grape
self.use_repo_goat_prior = use_repo_goat_prior
self.repo_goat_num_frequencies = int(repo_goat_num_frequencies)
self.repo_goat_sink_decay = float(repo_goat_sink_decay)
# ββ LAuReL: Learned Augmented Residual Layer (Menghani et al., 2025) β
self.use_laurel = use_laurel
self.use_laurel_rw = use_laurel_rw
self.use_laurel_lr = use_laurel_lr
self.laurel_lr_rank = laurel_lr_rank
# ββ TWEO: Transformers Without Extreme Outliers ββββββββββββββββββ
self.use_tweo = bool(use_tweo)
self.tweo_loss_weight = float(tweo_loss_weight)
self.tweo_tau = float(tweo_tau)
self.tweo_power = float(tweo_power)
self.tweo_eps = float(tweo_eps)
# ββ NITP: Next Implicit Token Prediction βββββββββββββββββββββββββ
self.use_nitp = bool(use_nitp)
self.nitp_target_layer = int(nitp_target_layer)
self.nitp_loss_weight = float(nitp_loss_weight)
self.nitp_projector_intermediate_size = int(nitp_projector_intermediate_size)
# ββ NITP temporal transition / identification ββββββββββββββββββββ
self.use_nitp_temporal = bool(use_nitp_temporal)
self.nitp_temporal_apply_loss = bool(nitp_temporal_apply_loss)
self.nitp_temporal_horizon = int(nitp_temporal_horizon)
self.nitp_temporal_dynamics_weight = float(
nitp_temporal_dynamics_weight
)
self.nitp_temporal_identification_weight = float(
nitp_temporal_identification_weight
)
self.nitp_temporal_intermediate_size = int(
nitp_temporal_intermediate_size
)
self.nitp_temporal_similarity_temperature = float(
nitp_temporal_similarity_temperature
)
self.nitp_temporal_target_temperature = float(
nitp_temporal_target_temperature
)
# ββ NextLat: Next-Latent Prediction ββββββββββββββββββββββββββββββ
self.use_nextlat = bool(use_nextlat)
self.nextlat_horizon = int(nextlat_horizon)
self.nextlat_mse_weight = float(nextlat_mse_weight)
self.nextlat_kl_weight = float(nextlat_kl_weight)
self.nextlat_dynamics_proj_factor = float(nextlat_dynamics_proj_factor)
# ββ Interleaved Head Attention (Duvvuri et al., 2026) βββββββββββββ
# use_iha=True: enables learned cross-head mixing of Q, K, V.
# iha_num_pseudo_heads (P): number of pseudo-heads per original head.
# P=1: lightweight cross-head linear mixing, fully shape-preserving,
# compatible with all other attention flags.
# P>1: full IHA with pseudo-head expansion and collapse.
# If MEA is active, MEA composes K/V independently inside each
# pseudo-slot after IHA, so both remain compatible.
# iha_local_global_pattern: paper Sec. 5.1 / Appendix C schedule.
# "LLLLG" β 4 local IHA layers + 1 global transport layer per cycle.
# 'L' always means local IHA with sliding-window compensation.
# 'G' means global full-sequence attention. By default, 'G' is
# standard non-IHA attention to match the paper's FLOP argument:
# 4Β·O(HNΒ²d/2)+1Β·O(HNΒ²d). Set iha_global_layers_use_iha=True
# only for the more expensive ablation where global layers also
# use full IHA, whose attention cost scales as O(HPΒ²NΒ²d).
# Applied only when P>1 (P=1 never needs FLOP compensation).
# iha_sliding_window: window size W for local-IHA layers.
# None β auto = N/(2PΒ²) with N = actual sequence length at forward time
# (paper Sec. 5.1 / Appendix C exact recipe).
# int β use the provided explicit window size as-is.
# iha_global_layers_use_iha:
# False β paper-faithful default: G layers do not instantiate or run
# IHA parameters, so they are ordinary global attention layers.
# True β G layers instantiate and run global IHA over the expanded
# sequence; useful only as an explicit high-cost ablation.
# Init: identity (IHA β‘ MHA at step 0, Theorem 2 inclusion proof).
self.use_iha = use_iha
self.iha_num_pseudo_heads = iha_num_pseudo_heads
self.iha_local_global_pattern = iha_local_global_pattern
self.iha_sliding_window = iha_sliding_window
self.iha_global_layers_use_iha = bool(iha_global_layers_use_iha)
# ββ SFT/DPO structural protection (opt-in, pretraining-off) βββββββ
self.meap_structural_token_ids = (
None
if meap_structural_token_ids is None
else tuple(int(token_id) for token_id in meap_structural_token_ids)
)
self.meap_protect_chat_headers = bool(meap_protect_chat_headers)
self.meap_protect_ignored_labels = bool(meap_protect_ignored_labels)
self.copy_exclude_structural_tokens = bool(copy_exclude_structural_tokens)
self.copy_exclude_token_ids = (
None
if copy_exclude_token_ids is None
else tuple(int(token_id) for token_id in copy_exclude_token_ids)
)
self.copy_exclude_chat_headers = bool(copy_exclude_chat_headers)
self.copy_chat_im_start_token_id = int(copy_chat_im_start_token_id)
self.copy_chat_im_end_token_id = int(copy_chat_im_end_token_id)
self.copy_chat_newline_token_id = int(copy_chat_newline_token_id)
self.auto_map = {
"AutoConfig": "configuration_neollm.NeoLLMConfig",
"AutoModel": "modeling_neollm.NeoLLMModel",
"AutoModelForCausalLM": "modeling_neollm.NeoLLMForCausalLM",
}
@classmethod
def from_dict(cls, config_dict, **kwargs):
"""Keep saved models stable when constructor defaults change later."""
config_dict = dict(config_dict)
if config_dict.get("model_type") == cls.model_type and "use_linear_attention" not in config_dict:
previous_options = {
"type": "none", "full_attention_every": 4, "layer_types": None,
"num_heads": None, "head_dim": None, "expand_v": 1.0, "conv_size": 4,
}
if "linear_attention" in config_dict:
# Older hybrid configs used these defaults even if their saved
# group was partial; do not inherit newly edited init defaults.
if isinstance(config_dict["linear_attention"], dict):
previous_options.update(config_dict["linear_attention"])
config_dict["linear_attention"] = previous_options
config_dict["use_linear_attention"] = None
elif not any(key.startswith("linear_attention_") for key in config_dict):
# Models predating hybrid attention used full attention only.
config_dict["use_linear_attention"] = False
config_dict["linear_attention"] = previous_options
return super().from_dict(config_dict, **kwargs)
def attention_type_for_layer(self, layer_idx):
"""Resolve the saved hybrid schedule without adding model parameters."""
options = self.linear_attention
if self.use_linear_attention is False:
return "full"
if options["layer_types"] is not None:
return options["layer_types"][layer_idx]
kind = options["type"]
if kind == "none":
return "full"
if self.num_hidden_layers == 1:
return kind
if (layer_idx + 1) % options["full_attention_every"] == 0 or layer_idx == self.num_hidden_layers - 1:
return "full"
return kind
__all__ = ["NeoLLMConfig"]
# ==================== configuration_neollm.py ====================
import math
from numbers import Integral
from transformers.configuration_utils import PretrainedConfig
from transformers.modeling_rope_utils import rope_config_validation
from transformers.utils import logging
logger = logging.get_logger(__name__)
class NeoLLMConfig(PretrainedConfig):
r"""
Configuration class for the NeoLLM model architecture.
Instantiates a NeoLLM model according to the specified arguments, defining the
full architecture including attention mechanisms, normalization, periodicity
modeling, an optional Leviathan continuous token embedding generator (LEV
layer, Batley & Saha 2026), and optional Spelling Bee character-level
embedding augmentation.
Configuration objects inherit from :class:`~transformers.PretrainedConfig` and
can be used to control the model outputs. Read the documentation from
:class:`~transformers.PretrainedConfig` for more information.
Args:
vocab_size (:obj:`int`, *optional*, defaults to 200005):
Vocabulary size of the NeoLLM model. Defines the number of different
tokens that can be represented by the ``input_ids``.
hidden_size (:obj:`int`, *optional*, defaults to 512):
Dimensionality of the hidden representations.
intermediate_size (:obj:`int`, *optional*, defaults to 1536):
Dimensionality of the MLP feed-forward intermediate representations.
num_hidden_layers (:obj:`int`, *optional*, defaults to 12):
Number of decoder Transformer layers.
num_attention_heads (:obj:`int`, *optional*, defaults to 8):
Number of query attention heads per layer.
num_key_value_heads (:obj:`int`, *optional*, defaults to 2):
Number of key/value attention heads (GQA). Must divide
``num_attention_heads`` evenly.
hidden_act (:obj:`str`, *optional*, defaults to ``"xielu"``):
Non-linear activation function used in the MLP layers.
max_position_embeddings (:obj:`int`, *optional*, defaults to 32768):
Maximum sequence length supported by the positional encoding.
initializer_range (:obj:`float`, *optional*, defaults to 0.02):
Standard deviation of the truncated-normal weight initializer.
rms_norm_eps (:obj:`float`, *optional*, defaults to 1e-6):
Epsilon for RMS normalization layers.
tie_word_embeddings (:obj:`bool`, *optional*, defaults to ``False``):
Whether to share weights between the input embedding matrix and the
output language-model head. Automatically forced to ``False`` when
``use_token_generator=True``, because the generator produces input
representations via a learned smooth surface and the output head must
remain an independent dense projection.
ntp_loss_backend (:obj:`str`, *optional*, defaults to ``"cce"``):
Backend used for the main next-token-prediction loss. ``"cce"`` uses
Cut Cross Entropy through ``linear_cross_entropy(..., shift=1)``.
``"liger"`` uses Liger Kernel's fused linear cross entropy with an
explicit shift equivalent to ``shift=1``. The two backends are
mutually exclusive at runtime. Copy-Paste, when enabled, computes
its mixed objective instead of either backend's NTP loss.
use_liger_kernel (:obj:`bool`, *optional*, defaults to ``False``):
Convenience flag for ``ntp_loss_backend="liger"``. When enabled,
the model does not call the CCE loss path for NTP.
cce_loss_impl (:obj:`str`, *optional*, defaults to ``"cce_kahan_full_c"``):
CCE implementation used when ``ntp_loss_backend="cce"``. The default
keeps the conservative Kahan/full-classifier-gradient path used for
pretraining from scratch.
use_mile_loss (:obj:`bool`, *optional*, defaults to ``True``):
Enable MiLe Loss (Su et al., 2026, arXiv:2310.19531). MiLe
reweights token losses with detached, mean-normalized predictive-
entropy weights. Copy-Paste derives those weights from the mixed
distribution using CCE's sparse statistics on CUDA.
use_copy_paste (:obj:`bool`, *optional*, defaults to ``False``):
Add the Copy-Paste LM head (Godey and Artzi, arXiv:2610.19247).
Its learned copy gate and sink mix vocabulary predictions with a
causal distribution over observed input tokens. CUDA training uses
CCE's sparse Copy-Paste path; CPU uses a bounded Torch reference.
MiLe uses mixture entropy; mu-loss remains a regularizer on the
ordinary vocabulary matrix. Inference still returns dense logits.
mile_loss_gamma (:obj:`float`, *optional*, defaults to ``1.0``):
Non-negative exponent applied to MiLe's ``1 + entropy`` weight.
use_mu_loss (:obj:`bool`, *optional*, defaults to ``True``):
Enable the output-embedding centering regularizer from Stollenwerk
et al. (2026, arXiv:2601.02031). CCE uses its extension; the
Copy-Paste path computes the regularizer directly in Torch.
mu_loss_lambda (:obj:`float`, *optional*, defaults to ``1e-4``):
Non-negative coefficient in ``L_mu = lambda * ||mean(C)||^2``.
use_meap (:obj:`bool`, *optional*, defaults to ``False``):
Enable Mask-Enhanced Autoregressive Prediction during training only
(Zhuang et al., 2026, arXiv:2502.07490). Labels and attention masks
remain clean; only selected input token IDs are replaced.
meap_mask_ratio (:obj:`float`, *optional*, defaults to ``0.15``):
Fraction of eligible input positions replaced in each sequence.
meap_mask_token_id (:obj:`int`, *optional*):
Dedicated reserved token ID used only as the MEAP replacement.
Required when MEAP is enabled; it must be inside the vocabulary and
distinct from PAD/BOS/EOS. Its final trainable representation is
independent from dense embeddings, Leviathan, and Spelling Bee.
meap_seed (:obj:`int`, *optional*, defaults to ``0``):
Base 32-bit seed. The Trainer derives a distinct deterministic seed
for each microstep and distributed process.
meap_implementation (:obj:`str`, *optional*, defaults to ``"triton"``):