Research Preview · Kreasof AI

Polar Attention

Train short, infer long — a length-invariant replacement for softmax attention, with a Titans compression memory.
Kreasof AI Research
Kreasof AI · Independent AI Research Lab · Jakarta, Indonesia
100%75% 50%25%0% 2K4K8K 16K32K64K context length (eval) — trained at 2K train length Polar + Titans
Polar + Titans memory (ours) Softmax + Titans memory Polar, no memory Softmax, no memory

Needle-in-a-haystack retrieval accuracy as evaluation context grows to 32× the training length (2K→64K tokens). Polar Attention with the Titans memory stays flat above 90%; every other variant collapses toward chance. Identical 370M-parameter model, identical 1B-token training budget — only the attention recipe differs.

TL;DR. Softmax attention is not length-invariant: a model trained at a few thousand tokens dilutes and breaks far beyond that length. We introduce Polar Attention, which factors each query's result into a count-blind direction channel and a bounded magnitude channel — bounding the output at any length. Paired with a Titans gated-delta compression memory, a 370M model trained at 2K tokens holds retrieval accuracy above 90% out to 64K tokens and keeps perplexity monotonically improving with length, while softmax collapses.

Abstract

Length-invariant sequence mixing

Softmax scaled-dot-product attention is numerically stable but not length-invariant: as the key set grows, softmax mass spreads thinner, so a model trained at length T behaves differently at 32·T — it never learned to scale its computation with length, and "how many things matched" is entangled with "what matched" in a single normalized output. Borrowing the size-invariance of convolution, Polar Attention derives two channels from one temperature-sharpened softmax with a learned, extreme-value-corrected null sink: a unit-vector direction (size-invariant, count-blind) and a bounded magnitude read from the participation ratio of effective matches. The output stays bounded with infinite dynamic range at any context length, where softmax both dilutes and explodes.

Attention alone forces a tradeoff — a sliding window wins perplexity but is retrieval-blind, full attention preserves recall but leaks perplexity. We resolve it by attaching a Titans-style compression memory (a per-head gated-delta fast-weight store, in the Memory-as-Gate configuration) as an additive third channel: out = content + count + memory. The memory supplies the diffuse long-context perplexity gain; full polar plus a distractor objective supplies exact pinpoint retrieval. The combined stack is implemented across three numerically cross-verified pipelines — reference, training, and a paged inference engine — with a FlashAttention-style Triton kernel and a fused gated-delta kernel. We validate the design with a 120-cell factorial ablation over the attention core, regularizer, distractor, memory, and window axes.

Method

Three channels into the residual

Each attention layer writes out = content + count + memory. The first two come from one shared softmax; the third is a recurrent associative memory trained in-loop.

🧭

Direction — content

A unit vector over values: what was attended to. Projected to the sphere, it is invariant to how many keys matched and to total length. c = s / ‖s‖

📊

Magnitude — count

The participation ratio of effective matches, gated by a null-sink confidence and squashed by tanh(β·log1p) into [0,1) — bounded, ordered, length-invariant. 1K vs 1M matches stay distinguishable but bounded.

🧠

Memory — memory

A per-head linear memory updated by a gated delta rule (Titans / Gated DeltaNet). Self-stabilizing in norm across length; γ is a per-head horizon dial. A lossy gist that carries long-context perplexity.

The extreme-value-corrected null floor (+ slope·√log n) tracks the noise maximum so pure noise never reads as a match at long context; a length temperature (1 + softplus·log n) sharpens the softmax as context grows. A small distractor objective pushes random keys below the floor, widening the signal/noise margin — this is what buys exact retrieval far beyond the training length. The full derivation follows.

Intuition

See it move

Two animations for the two ideas: why polar stays bounded as context grows, and how the memory writes a token once and recalls it later.

Polar Attention — direction locks, magnitude saturates
context length 2K q keys (signal + noise) direction c (unit) softmax ‖out‖ 1.0 polar mag 0.66

As context grows toward 64×, softmax weight dilutes and its output norm blows up (red); polar locks the direction to a unit vector and keeps the magnitude bounded in [0,1) (green).

Titans Memory — gated-delta write & recall
token stream memory M (per head) readout r = M·q state norm (bounded)

Each token: the state M decays, then takes a rank-1 write. A needle is written once; a later query reads it back — while the state norm stays flat in length (self-stabilizing).

Schematic, built to convey the mechanism — not a live model. Animations pause off-screen and respect prefers-reduced-motion.

Derivation

The math, end to end

A single query \(i\) attends over keys \(j<n_i\) (causal, \(n_i=i+1\) visible keys). With QK-norm on \(q,k\), scores are \(\sigma_{ij}=(q_i\cdot k_j)/\sqrt{d_k}\). Two length-aware scalars per head do the work.

Polar Attention content + count

1 · Length temperature

Sharpens the softmax as context grows (Scalable-Softmax style), so weight does not spread thinner with more keys:

\[ \mathrm{temp}_i \;=\; 1 + \operatorname{softplus}(\text{len\_gain})\cdot \log n_i \]
2 · Extreme-value null floor

The logit of an off-by-one "null sink" key. The \(\sqrt{\log n}\) growth is load-bearing — the maximum of \(n\) noisy scores grows like \(\sqrt{2\ln n}\), so any fixed floor is eventually overtaken by noise:

\[ \mathrm{null}_i \;=\; \text{null\_base} + \operatorname{softplus}(\text{null\_slope})\cdot \sqrt{\log(n_i+1)} \]
3 · Direction channel — "what"

Append the null logit, softmax over real keys + sink, mix the values (plus a learned default \(v_{\text{null}}\)), project to the sphere:

\[ \begin{aligned} w_i &= \operatorname{softmax}\!\big([\,\mathrm{temp}_i\,\sigma_{i\bullet},\ \ \mathrm{temp}_i\,\mathrm{null}_i\,]\big) \\[2pt] s_i &= \textstyle\sum_j w_{ij}\,v_j \;+\; w_{iN}\,v_{\text{null}} \\[2pt] \mathbf{c_i} &= s_i/\lVert s_i\rVert \qquad\triangleright\ \text{unit vector, count-blind} \end{aligned} \]
4 · Magnitude channel — "how much"

Reuse the same weights. Renormalize over real keys, take the participation ratio (effective match count), gate by confidence, then bound with a saturating map:

\[ \begin{aligned} \hat w_{ij} &= w_{ij}\big/\textstyle\sum_k w_{ik} \\[2pt] n_{\text{eff}} &= 1\big/\textstyle\sum_j \hat w_{ij}^{\,2} \qquad\triangleright\ \text{inverse Simpson} \\[2pt] m_{\text{eff}} &= n_{\text{eff}}\,(1-w_{iN}) \\[2pt] \mathbf{mag_i} &= \tanh\!\big(\operatorname{softplus}(\text{mag\_}\beta)\cdot \operatorname{log1p}(m_{\text{eff}})\big)\in[0,1) \end{aligned} \]
5 · Assembly into the residual
\[ \mathbf{out} \;=\; \underbrace{W_o\big(\operatorname{reshape}(c)\cdot \sigma(\text{gate})\big)}_{\text{content}} \;+\; \underbrace{W_\mu(\mathrm{mag})}_{\text{count}} \]
6 · Length-invariance condition

The count is invariant in length when \(\text{len\_gain}\cdot\Delta \ge 1\) (\(\Delta\) = the QK margin between signal and noise): the temperature then suppresses each noise weight faster than \(n\) grows. End-to-end, the same key population at 1× and 64× yields identical \(c\) (cosine 1.0) and identical \(\mathrm{mag}\).

7 · Distractor objective (optional)

Random keys, pushed through the same \(k\) projection, must lose to the sink — this widens \(\Delta\) and is what buys retrieval far past train length:

\[ \mathcal{L}_{\text{align}} \;=\; \operatorname{mean}\ \operatorname{softmax}\!\big([\,\mathrm{temp}\cdot\sigma_{\text{rand}},\ \ \mathrm{temp}\cdot\mathrm{null}\,]\big)\big|_{\text{rand}} \]

Designed by falsification. An additive soft-count \(\sum\sigma(\sigma-\theta)\) leaks \(\mathcal{O}(N)\) (89× drift over a 1000× sweep); the participation ratio is flat. Raw \(\log(m)\) pushes the projection out of distribution — the bounded \(\tanh\!\cdot\operatorname{log1p}\) keeps it in range. A fixed null floor is overtaken by the noise maximum. The distractor alone collapses the count (floor \(\to\infty\)); the task loss is its counterweight.

Titans Memory memory

Each head carries a matrix memory \(M\in\mathbb{R}^{d_v\times d_k}\) — a fast-weight key→value store — reusing the layer's \(q,k,v\) plus two data-dependent scalar gates per head.

1 · Gates
\[ \begin{aligned} \gamma_t &= \sigma(W_\gamma x_t + b_\gamma) \qquad\triangleright\ \text{retention},\ b\!:3.9\!\to\!\approx\!0.98 \\[2pt] \beta_t &= \sigma(W_\beta x_t + b_\beta) \qquad\triangleright\ \text{write strength}\to 0.5 \end{aligned} \]
2 · Gated-delta recurrence

The Titans neural memory (momentum \(\eta=0\)) reparametrizes exactly to the Gated DeltaNet recurrence. FLA's convention is canonical — decay-first, undecayed write, self-inclusive readout:

\[ \begin{aligned} M_t &= \gamma_t\,M_{t-1}\,(I-\beta_t\,k_t k_t^{\top}) + \beta_t\,v_t k_t^{\top} \\[2pt] r_t &= M_t\,q_t \qquad\triangleright\ \text{readout after the write} \end{aligned} \]
3 · Per-step view
\[ \begin{aligned} M &\leftarrow \gamma_t M &&\triangleright\ \text{decay first} \\[2pt] \mathrm{pred} &= M k_t &&\triangleright\ \text{predict on decayed state} \\[2pt] M &\leftarrow M + \beta_t(v_t-\mathrm{pred})k_t^{\top} &&\triangleright\ \text{delta write} \\[2pt] r_t &= M q_t &&\triangleright\ \text{self-inclusive read} \end{aligned} \]
4 · Readout assembly

Pulled back into polar's discipline before it enters the residual (zero-init \(\mathrm{proj}\) → enabling the branch is a safe no-op at step 0):

\[ \mathbf{mem} \;=\; \operatorname{proj}\!\big(\operatorname{RMSNorm}(r)\cdot \sigma(\operatorname{gate}(x))\big) \]
Finding 1 · Keys must be unit-norm

The delta rule's per-step eigenvalue along the key is \(\gamma\,(1-\beta\lVert k\rVert^2)\). Polar's RMS-norm gives \(\lVert k\rVert^2=d_k\) → eigenvalue \(\approx-7\) → the state diverges (oracle blew up to \(\sim\!10^{57}\)). L2-normalized keys give \(\gamma(1-\beta)\in(0,1)\) — stable.

Finding 2 · \(\gamma\) is a horizon dial, not a safety gate

The delta memory self-stabilizes: state-norm is flat in \(N\) (256→16384) even at \(\gamma=1\), because the \((I-\beta k k^{\top})\) key-replacement converges toward the least-squares solution \(M\approx V K^{+}\) (capacity \(\sim d_k\)). So \(\gamma\) is learned per-head: some heads hold \(\gamma\approx1\) for distant recall, others \(\gamma<1\) for recency.

Division of labor. The linear memory is a lossy gist (capacity \(\sim d_k\)) — it carries diffuse long-context perplexity but cannot exact-recall a planted needle. Full polar + the distractor does the pinpoint retrieval. The recurrence has a closed chunkwise-parallel form so it trains in-loop at ~6–9% MFU overhead (fused FLA / Triton kernel).

Full write-ups with verification (float64 gradcheck, bit-exact train↔reference↔inference parity): POLAR_ATTENTION.md · TITANS_MEMORY.md.

Systems

The machinery

The architecture lives in three implementations that are kept numerically identical: a pure-PyTorch reference oracle, an optimized training path (FP16/FP8 matmuls, Muon), and a paged inference engine. Every layer is cross-checked, so a new variant is safe to ship the moment parity holds.

TRAINING FP16/FP8 · Muon REFERENCE pure-PyTorch oracle INFERENCE paged engine verify.py · atol 1e-4 · 30/30 CPU · 30/30 CUDA (L4)

FlashAttention-style kernel

A fused Triton kernel streams the polar reduction with query- and key-blocking — fully O(block) memory on tensor cores. The count channel needs one extra streamed accumulator Q2 = Σexp(·)² for the participation ratio, rescaled by α² on every online-softmax max update. The backward keeps a cheap per-query preamble in PyTorch and runs only the two O(T²) matmul loops as Triton.

7–27× faster · ~5× less memory vs. the PyTorch paths (L4)
🔌

Paged inference engine

Paged KV cache with prefix caching; centralized per-sequence state tables hold the conv states and the Titans memory (per-head M, fp32, FLA [K,V] layout). Prefill runs FLA's fused chunk_gated_delta_rule; decode runs a GQA-grouped paged kernel plus an in-place gated-delta step — one state read+write per token, CUDA-graph capturable.

19,270 tok/s decode @ bs=512 (L4) · state ~512 KB/seq/layer

Verification first

Every reduction is established against a token-by-token oracle: float64 gradcheck on the streaming polar autograd and the gated-delta recurrence, then train == reference bit-exact in the default config. The same per-layer and end-to-end checks route through the Triton kernels on GPU. Nothing merges until parity holds.

156 parity / gradcheck / integration tests green
verify.py 30/30 CPU + 30/30 CUDA test_polar_kernel.py 104/104 test_integration.py 21/21 verify_titans / mag / window fp64 gradcheck train ↔ reference bit-exact

The torch.compile saga. FLA's gated-delta kernel is a custom autograd function that graph-breaks at every memory layer under torch.compile — a ~2× time / ~2× peak-RAM regression, since the memory's FLOPs are only ~5% of the model (overhead, not compute). Wrapping it as two opaque custom ops (FLA_CUSTOM_OP=1) with register_fake shapes restores fusion and recomputes activations in the backward — bringing the real cost down to ~6–9% MFU.

Results

Train at 2K, evaluate to 64K

370M parameters (16 layers, 12 gated-conv + 4 attention), ~1B tokens of FineWeb-Edu, sequence length 2K. Every cell evaluates at full context. The winning recipe is polar + memory (no window, no distractor, baseline regularizer).

Needle retrieval accuracy

ContextPolar+TitansSoftmax (NoPE)+TitansRoPE+TitansPolar onlySoftmax (NoPE) onlyRoPE only
2K (1×)91%98%74%96%98%43%
8K (4×)93%94%29%15%28%4%
16K (8×)98%85%9%8%8%0%
32K (16×)96%48%0%3%3%0%
64K (32×)93%16%0%0%1%0%

Clean-document perplexity

ContextPolar+TitansSoftmax (NoPE)+TitansRoPE+TitansPolar onlySoftmax (NoPE) onlyRoPE only
2K (1×)2.702.662.812.832.762.85
8K (4×)2.442.392.743.322.672.78
16K (8×)2.282.292.793.532.972.85
32K (16×)2.142.292.823.603.383.07
64K (32×)1.962.342.863.603.713.36

Polar + Titans is the only recipe whose perplexity improves monotonically as context grows (2.70→1.96 across a 32× sweep) while retrieval stays flat. Softmax holds early then collapses past ~16×; RoPE collapses even faster. Polar without the memory loses long-context perplexity. Convergence and quality rank Polar+Titans > Softmax+Titans > RoPE+Titans > Polar-only at ~6–9% MFU overhead.

The Ablation

A 120-cell factorial, fully browsable

Five regularizers × distractor on/off × memory on/off × window on/off × three attention cores (polar, softmax/nope, rope) — with a second batch adding wall attention. Every cell: clean & junk perplexity and needle accuracy at six lengths, plus MFU and wall-clock — in one interactive dashboard.

120
cells in the grid
120
completed so far
6
eval lengths / cell
32×
max extrapolation
Open the interactive dashboard →

Cite

BibTeX

@misc{kreasof2026polar,
  title  = {Polar Attention: Length-Invariant Sequence Mixing with Compression Memory},
  author = {Kreasof AI Research},
  year   = {2026},
  note   = {Research preview},
  url    = {https://github.com/kreasof-ai/atma}
}

A full technical report is in preparation. Documentation: Polar Attention · Titans Memory · Atma overview.