ddshif/TALA
关于
TALA (Token-Anchored Latent Attention) shares token-derived KV memory across layers, with looped, non-loop, and sliding-window variants.
人工智能与机器学习可以做什么
- Share more, learn better. Full-stack Base sharing lowers validation NLL from 2.982 to 2.941 and reduces KV storage by about 44% compared with layer-private Bases at fixed latent widths in the 12-layer, four-recursion study.
- Three TALA variants. Looped TALA runs four recursions with full history. Non-loop TALA shares the Base across a single pass through the layers. Looped TALA+SWA uses the full first-recursion history and a 64-token local window in later recursions.
实测星标增长
- 24小时
- 正在收集历史
- 7天
- 正在收集历史
- 15天
- 正在收集历史
- 1个月
- 正在收集历史
各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。
README.md
原文TALA: Token-Anchored Latent Attention
Breaking the KV Cache Bottleneck in Looped Transformers with Shared Token Latents
Paper (arXiv) · Read on alphaXiv · Hugging Face Papers · Project Page · Quick start · Reproduction
Could Transformers be repeatedly encoding information that only needs to be represented once?
Looped Transformers scale computational depth by reusing model weights. Yet standard attention stores a separate KV history for every layer execution. A 12-layer model run for four recursions therefore keeps 48 KV histories.
Starting from this problem, we discovered that progressively expanding the sharing scope of a KV Base latent improves validation quality while reducing cache storage. The best tested design derives a single shared Base directly from the token embedding, before contextual attention, and makes it available to every layer and recursion.
TALA combines this globally shared token representation with compact stage-specific latents. Each physical layer decodes both into keys and values and adds their contributions before one causal softmax. TALA derives the Base from the existing token embedding table.
Highlights
- Share more, learn better. Full-stack Base sharing lowers validation NLL from 2.982 to 2.941 and reduces KV storage by about 44% compared with layer-private Bases at fixed latent widths in the 12-layer, four-recursion study.
- Three TALA variants. Looped TALA runs four recursions with full history. Non-loop TALA shares the Base across a single pass through the layers. Looped TALA+SWA uses the full first-recursion history and a 64-token local window in later recursions.
Use and reproduce · Quick start · Python API · Formal configurations · Evaluation · Repository scope · Citation and license
A counterintuitive discovery
Our learned cross-recursion KV mixing experiment finds substantial reuse of early memories under simulated storage pressure, while intermediate memories remain useful. This motivates a shared Base plus a compact Stage for each computation. All four diagnostic banks remain physically stored.
Expanding the Base-sharing span from one layer to the full 12-layer stack improves NLL and reduces the cache, with the Base and Stage widths held fixed. The strongest tested configuration writes the Base before any contextual attention.
Architecture
For source position $j$, physical layer $\ell$, and recursion $r$, a token-derived Base is shared across the whole network, while a compact Stage depends on the current hidden state (Eq. 13).
b_j=W_B^{DKV}h_j^{(0)},\qquad s_{\ell,j}^{(r)}=W_{\ell,S}^{DKV}h_{\ell,j}^{(r)}.
Each physical layer decodes the Base and Stage and adds their content contributions at the same source position (Eq. 14).
\begin{aligned}
k_{\ell,j}^{C,(r)}&=W_{\ell,B}^{UK}b_j+W_{\ell,S}^{UK}s_{\ell,j}^{(r)},\\
v_{\ell,j}^{C,(r)}&=W_{\ell,B}^{UV}b_j+W_{\ell,S}^{UV}s_{\ell,j}^{(r)}.
\end{aligned}
Layer-specific readouts let different layers retrieve distinct features from the same Base. Evolving queries and Stage latents refine retrieval and content at each execution. Projection weights are shared across recursions in the default model, but each execution retains its own Stage history. In the full-history variant, content and positional scores enter one causal softmax. A global–local TALA+SWA variant is also evaluated. See architecture notes.
TALA model variants
The three released checkpoints use a 4,096-token context. CS9 and NIAH6 are mean percentages over nine zero-shot language benchmarks and six 4K RULER retrieval tasks, respectively.
| Model | Recursions | Attention | Validation NLL ↓ | CS9 ↑ | NIAH6 ↑ |
|---|---|---|---|---|---|
| Looped TALA | 4 | Full history | 2.511 | 51.31 | 80.74 |
| Non-loop TALA | 1 | Full history | 2.582 | 48.19 | 75.81 |
| Looped TALA+SWA | 4 | Global history and 64-token local window | 2.505 | 51.91 | 78.01 |
The paper reports the scores in Tables 2 and 15 and describes the evaluation protocols.
Why does sharing help?
A source token's identity remains stable even as its contextual representations evolve. Our analysis suggests the Base takes on reusable token-specific matching functions, leaving the Stage less reliant on repeating them. At fixed KV capacity in the non-loop experiments, token-prototype matching-score variance in the Stage falls from 0.352 to 0.162 as capacity moves from the Stage to the Base. Whether this specialization causes the quality gains remains an open question.
Engram, Per-Layer Embeddings, and Memory Attention also make token-dependent information explicitly accessible. In TALA, the existing token embeddings provide the source for the shared memory.
Repository scope
The repository contains model, training, and evaluation code, result-free paper configurations, and the figures and main tables from arXiv v1. The v1 results bundle includes 92 scaling endpoints, selected aggregate task scores and trajectories, and scripts to regenerate figures from those values. Raw training logs, per-example outputs, internal reports and paper source remain outside this release.
The TALA Research Models collection hosts the three Apache-2.0 checkpoints. Each model card includes reference CPU generation instructions.
Paper sweeps share a common training stack and use resolved JSON configurations.
Installation
The validated environment is Python 3.12, PyTorch 2.9.1, CUDA 13.0, and NVIDIA A100 80 GB. PyTorch 2.5 or newer is required for FlexAttention.
python -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install -e .
python -m pip install -e '.[dev,data,analysis,evaluation]'
python -m pytest -q
The reference backend runs without custom CUDA extensions. The optimized path
uses torch.nn.attention.flex_attention and torch.compile; its first step
includes compilation. There is no private wheel or internal package dependency.
Quick start
Inspect a small TALA model:
tala-count-resources configs/examples/tiny_tala.json
Create a deterministic packed-document fixture and run four real CUDA optimizer steps, including BF16, FlexAttention, WSD, checkpointing, and resume state:
python scripts/make_tiny_packed_data.py \
--output data/quickstart --context 64 --sequences 32 --vocab-size 257
torchrun --standalone --nproc-per-node=1 scripts/train.py \
--config configs/examples/tiny_tala.json \
--data-manifest data/quickstart/dataset.json \
--output-dir outputs/quickstart \
--backend flex --max-steps 4 \
--global-batch-size 2 --micro-batch-size 2 \
--save-every 2 --log-every 1
The tiny run validates the software path; it is not a reproduction of a paper result.
Python API
import torch
from tala import TALAConfig, build_model
cfg = TALAConfig(
vocab_size=257,
num_layers=2,
hidden_size=128,
num_heads=2,
head_dim=64,
position_dim=32,
ffn_hidden_size=512,
recursions=4,
context_length=64,
group_span=2,
base_width=64,
stage_widths=(16, 16, 16, 16),
tied_stage=True,
backend="flex", # use "reference" for the readable oracle
)
model = build_model(cfg).cuda()
input_ids = torch.randint(1, cfg.vocab_size, (1, 64), device="cuda")
segment_ids = torch.cat((torch.zeros(32), torch.ones(32))).long()[None].cuda()
position_ids = torch.arange(32).repeat(2)[None].cuda()
labels = torch.roll(input_ids, -1, dims=1)
labels[:, (31, 63)] = -100 # document boundary and last target
with torch.autocast("cuda", dtype=torch.bfloat16):
loss = model(input_ids, segment_ids, position_ids, labels=labels)
loss.backward()
Core implementation locations:
tala/models/attention/tala.py: Base + Stage TALA.tala/models/attention/tala_swa.py: selected global-local TALA+SWA.tala/models/components.py: reference, SDPA, and compiled FlexAttention.tala/models/loop_transformer.py: tied physical stack, Update Norm, final-loop objective.tala/models/variants/: non-loop and cross-layer baselines.
Formal configurations
Resolved paper configurations are directly accepted by the trainer. A dry run parses the full configuration and constructs the model on the meta device:
tala-train \
--config configs/paper/fixed_depth/resolved/tala_l18_20b.json \
--backend flex --dry-run
The same file can launch training. Data and output paths are explicit CLI arguments; the public configuration never hard-codes an internal filesystem:
torchrun --standalone --nproc-per-node=8 scripts/train.py \
--config configs/paper/fixed_depth/resolved/tala_l18_20b.json \
--data-manifest /path/to/fineweb_edu_gpt2_packed/dataset.json \
--output-dir outputs/tala_l18_20b \
--backend flex
For multi-node training, launch the same command with standard torchrun
--nnodes, --node-rank, --master-addr, and --master-port arguments. The
trainer derives gradient accumulation from global_batch_size / (world_size * micro_batch_size) and fails if it is not integral.
To change model scale or the memory organization, edit the resolved model
fields (layers, loops, hidden_size, heads, base_width, Stage widths,
group_size, and local_window). Configuration validation rejects inconsistent
head dimensions, group spans, tied Stage widths, or unsupported combinations.
Training semantics
The production runtime provides:
- deterministic sequence-addressable packed documents with position reset;
- same-document causal masking and next-token loss masking;
- final-recursion next-token prediction and loop Update Normalization;
- BF16 autocast with FP32 token cross-entropy;
- DDP,
no_syncgradient accumulation, exact global valid-token normalization; - fused AdamW with norm/bias weight-decay exclusions and gradient clipping;
- warmup-stable-decay scheduling;
- atomic full-state checkpoints with model, optimizer, RNG, and data cursor;
- strict resume and machine-readable metrics.
Data preparation
The GPT-2/FineWeb-Edu streaming tokenizer and document-aware packer is available as a public entry point:
python scripts/prepare_fineweb_edu.py \
--input-dir /path/to/fineweb_edu_parquet \
--output-dir data/fineweb_edu_gpt2_packed \
--sequences 4882816 --context-length 4096 --shuffle-seed 20261027
--sequences counts packed sequences, not optimizer updates; size it for the
actual number of sequences consumed by the training recipe. The command uses
GPT-2 tokenization, writes explicit document-start flags, resets position IDs
at document boundaries, masks cross-document targets, and records the final
row permutation. See docs/data_preparation.md.
The original paper used a frozen FineWeb-Edu stream; the corpus and its exact
order are not distributed in this release.
Evaluation
scripts/evaluate.py performs token-weighted packed-document validation with
BF16 forward, FP32 per-token NLL, FP64 aggregation, and optional distributed
execution:
torchrun --standalone --nproc-per-node=8 scripts/evaluate.py \
--config configs/paper/fixed_depth/resolved/tala_l18_20b.json \
--checkpoint outputs/tala_l18_20b/checkpoint-step-00038147.pt \
--data-manifest /path/to/dataset.json \
--output-dir outputs/tala_l18_20b/dev
The public lm-evaluation-harness adapter runs the paper's zero-shot Commonsense9 contract and the six RULER/NIAH tasks at 4096 context:
tala-evaluate-tasks \
--config configs/paper/fixed_depth/resolved/tala_l18_20b.json \
--checkpoint outputs/tala_l18_20b/checkpoint-step-00038147.pt \
--suite commonsense9 --output outputs/tala_l18_20b/commonsense9.json
tala-evaluate-tasks \
--config configs/paper/fixed_depth/resolved/tala_l18_20b.json \
--checkpoint outputs/tala_l18_20b/checkpoint-step-00038147.pt \
--suite ruler6 --include-path /path/to/audited/ruler_task_yaml \
--output outputs/tala_l18_20b/ruler6.json
The interface requires lm_eval==0.4.13, zero-shot evaluation, the registered
metrics and documented sample expectations. Exact paper comparisons also
require the corresponding task YAML, prompt and sample revisions. See
docs/evaluation.md.
Persistent-memory accounting
For full-history TALA, let $L$ be the number of physical layers, $G$ the Base-sharing group span, and $R$ the number of recursions. The Base, Stage, and positional widths are $B$, $S$, and $d_p$. Each BF16 scalar takes $\eta=2$ bytes. With context length $T$, persistent KV bytes per token are
\frac{M_{\mathrm{model}}}{T}
= \eta \left(\frac{L}{G} B + L R S + L d_p\right).
This is logical persistent state, not peak HBM. Training activations, allocator
reservation, and temporary decoded K/V are excluded. TALA+SWA uses the
context-dependent fixed-window accounting implemented in
tala/accounting/resources.py.
Reproducing paper experiments
configs/paper/ contains result-free resolved configurations for scaling,
fixed-depth training, recursion-depth and compression studies, sharing-span
experiments, architecture ablations, and non-loop comparisons. The mechanism
analysis programs analysis/soft_bank.py,
analysis/functional_specialization.py, and analysis/context_window.py
accept user-generated sufficient statistics; the original statistics are
intentionally absent. See
docs/paper_reproduction.md for the mapping from
experiment categories to commands and expected artifacts.
Repository structure
tala/models/ model and attention implementations
tala/training/ DDP/BF16 runtime, WSD, checkpointing
tala/data/ packed-document stream and tiny fixture support
tala/evaluation/ evaluation interfaces
tala/accounting/ parameter, FLOP, and logical-KV accounting
configs/examples/ runnable small configurations
configs/paper/ result-free resolved paper configurations
scripts/ portable train/evaluate/data entry points
analysis/ result-input analysis programs (no original data)
docs/ architecture and reproduction documentation
docs/media/ paper figures and bilingual explainers
tests/ reference and configuration regression tests
Reproducibility boundary
The release code has been checked against the original TALA implementation using identical weights and packed inputs, and the optimized backend has been compared against the reference backend. Such short tests establish local training-path equivalence; they do not prove bitwise identity after a complete 20B-position run. Hardware, corpus ordering, and library versions can also introduce expected numerical variation.
Citation and license
Cite the arXiv preprint. GitHub also exposes the citation from CITATION.cff.
@misc{zheng2026sharedtokenlatents,
title = {Breaking the {KV} Cache Bottleneck in Looped Transformers with Shared Token Latents},
author = {Dehong Zheng and Tong Zhu and Yunkai Chai and Xiaoyang Chen and
Zefeng He and Zhe Xu and Xuyang Hu and Xinyu Zhang and
Zongliang Wu and Zhongzhi Zhang and Yafu Li and Yu Cheng},
year = {2026},
eprint = {2611.39694},
archivePrefix = {arXiv},
primaryClass = {cs.CL},
url = {https://arxiv.org/abs/2611.39694}
}
The TALA source code, configurations, and documentation in this repository are licensed under the Apache License 2.0. External dependencies, datasets, model weights, and evaluation assets are governed by their respective terms. See Third-party notices.
探索相关项目
加载中…


