Trim README to intro + quick start
Browse files6 unmodified lines7891011121314151 unmodified line17181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892906 unmodified lines---# MSA: Memory Sparse Attention*A scalable, end-to-end trainable latent-memory framework for 100M-token contexts***Anonymous code release for peer review.**| | ||---|---|1 unmodified line| Model weights | [`Anoy123423123/MSA-4B`](https://huggingface.co/Anoy123423123/MSA-4B) || Benchmark data | [`Anoy123423123/MSA-RAG-BENCHMARKS`](https://huggingface.co/datasets/Anoy123423123/MSA-RAG-BENCHMARKS) |Jump to [**Quick Start**](#-quick-start) to reproduce the reported numbers.## π AbstractLong-term memory is essential for general intelligence, yet the **full attention** bottleneck constrains most LLMs' **effective context length** to **128Kβ1M**. Existing attempts β hybrid linear attention, fixed-size state memory (e.g., RNNs), and external storage like **RAG/agents** β either suffer rapid precision decay and latency growth at extreme scales, lack end-to-end differentiability or dynamic memory maintenance, or require complex pipelines. We present **Memory Sparse Attention (MSA)**: an **end-to-end trainable, scalable sparse latent-state memory** framework. Core ideas include:- **Scalable sparse attention** + **document-wise RoPE** (parallel/global) achieving **near-linear complexity** in both training and inference;- **KV cache compression** with a **Memory Parallel** inference engine to deliver **100M token** throughput on **2ΓA800** GPUs;- **Memory Interleave** for multi-round, multi-hop reasoning across scattered memory segments.On long-context QA and NIAH (Needle-in-a-Haystack) benchmarks, **MSA** surpasses same-backbone RAG, best-of-breed RAG stacks, and leading long-context models. Across an unprecedented **16Kβ100M token** range, MSA shows **< 9%** degradation, suggesting a practical path to **decouple memory capacity from reasoning**.> **Scaling from 16Kβ100M tokens**: MSA fuses top-k selection with sparse attention to remain end-to-end differentiable while allowing document decoupling at inference. On MS MARCO, MSA sustains **<9%** degradation and exhibits strong extrapolation.## β¨ Key Contributions- **Memory-Sparse Attention (MSA)**: an **end-to-end trainable**, **scalable sparse attention** layer with **document-wise RoPE**, realizing **O(L)** complexity and **<9%** degradation from **16Kβ100M tokens**.- **KV cache compression + Memory Parallel**: tiered storage (GPU-resident routing keys, CPU content K/V), distributed scoring, and on-demand transfers to enable **100M-token** inference on **2ΓA800**.- **Memory Interleave**: adaptive alternating "generative retrieval β context expansion β generation," significantly boosting **multi-hop** reasoning across documents.- **Comprehensive evaluation**: MSA outperforms same-backbone RAG, best-of-breed RAG pipelines, and top long-context models on long-context QA and NIAH, showing superior **stability** and **accuracy** at scale.---## π§© Overall Design### ArchitectureMSA integrates **retrieval and generation** into a single differentiable loop. Document latent states (**K/V/Kα΅£**) are **chunk-mean pooled** for compression. A **router projector** computes relevance via cosine similarity (mean-pooled over heads, then token-wise max), selects **Topβk documents**, then concatenates their **compressed K/V** with the query's local **K/V** for autoregressive decoding. Routing applies only to **upper layers**; lower layers keep **independent document processing** for hierarchical alignment.- **Parallel (document-wise) RoPE**: Each document resets positions from 0, preventing position drift between **train-short** and **infer-long**, enabling 64k training to extrapolate to 100M.- **Global RoPE (active context)**: The query's starting index is **offset by k** (Topβk retrieved blocks), preserving causal ordering: *background β query β generation*.Implemented in [`src/msa/memory_sparse_attention.py`](./src/msa/memory_sparse_attention.py) and [`src/msa/model.py`](./src/msa/model.py).---### Inference PipelineMSA uses a **three-stage** pipeline:1. **Global Memory Encoding (offline)**: forward over the corpus to cache chunk-pooled **(KΜ, VΜ, KΜα΅£)**.2. **Online Routing & Context Assembly**: project query to **Qα΅£**, match with **KΜα΅£** to pick **Topβk**, then load only the selected **KΜ/VΜ** and concatenate with local context.3. **Sparse Generation**: autoregress over the **sparse context**.**Memory Parallel** shards **KΜα΅£** across GPUs (query broadcast β local scoring β global reduce). Content **KΜ/VΜ** stays in host DRAM and is **asynchronously fetched** when selectedβbalancing **VRAM** and **throughput** for **100M-token** deployment.Implemented in [`src/msa_service.py`](./src/msa_service.py) (`MSAEngine`, memory-parallel bucketing) and [`src/prefill.py`](./src/prefill.py) (stage-1 encoding).---## π Results> **Setup**> **QA**: 9 datasets (MS MARCO v1, NQ, DuReader, TriviaQA(10M), NarrativeQA, PopQA, 2WikiMultiHopQA, HotpotQA, MuSiQue), memory banks **277Kβ10M tokens**, metric: **LLM judge (0β5)**.> **NIAH (RULER)**: 8 subtasks, **32Kβ1M tokens**, report average accuracy.> **Backbone**: Qwen3β4BβInstructβ2507. Compare to same-backbone RAG and best-of-breed RAG stacks (KaLMv2 + large generators, optional reranker).### Table 1: MSA vs same-backbone RAG (Qwen3β4B)**Summary**: Average **3.760**, improving over standard RAG (**+16.0%**), RAG+rerank (**+11.5%**), and HippoRAG2 (**+14.8%**) using their best@k; MSA leads on all but NarrativeQA within the same-backbone group.| Dataset | Tokens | Qwen3-4B R@1 | R@5 | R@10 | Qwen3-4B (RR) R@1 | R@5 | R@10 | HippoRAG2 R@1 | R@5 | R@10 | MSA (adaptive) ||---------|--------|--------------|------|-------|----------------------|------|-------|------------------|------|--------|----------------|| MS MARCO v1 | 7.34M | 2.893 | 3.011 | 3.005 | 2.934 | <u>3.032</u> | 3.017 | 2.676 | 3.005 | 3.019 | **4.141** || Natural Questions | 1.47M | 3.452 | 3.374 | 3.297 | <u>3.494</u> | 3.408 | 3.385 | 3.338 | 3.389 | 3.374 | **3.545** || DuReader | 277K | 3.726 | 3.579 | 3.594 | <u>3.848</u> | 3.618 | 3.607 | 2.941 | 3.485 | 3.415 | **4.155** || TriviaQA (10M) | 10M | 4.133 | 4.414 | 4.273 | 4.313 | 4.375 | 4.391 | 4.188 | <u>4.430</u> | 4.367 | **4.621** || NarrativeQA | 538K | 1.611 | 2.567 | 2.860 | **3.638** | 3.492 | <u>3.536</u> | 1.959 | 2.628 | 2.655 | 3.395 || PopQA | 1.18M | 2.959 | 3.273 | 3.299 | <u>3.315</u> | 3.264 | 3.266 | 3.111 | 3.249 | 3.249 | **3.433** || 2WikiMultiHopQA | 722K | 1.065 | 3.055 | 3.136 | 1.187 | 3.057 | 3.159 | 1.045 | 3.180 | <u>3.330</u> | **4.280** || HotpotQA | 1.35M | 2.252 | 3.582 | 3.787 | 2.642 | 3.990 | <u>4.022</u> | 3.230 | 3.770 | 3.970 | **4.061** || MuSiQue | 1.41M | 0.936 | 1.752 | 1.928 | 1.144 | 1.960 | 1.965 | 1.020 | 1.907 | <u>2.095</u> | **2.211** || **Average** | β | 2.559 | 3.179 | 3.242 | 2.946 | 3.355 | <u>3.372</u> | 2.612 | 3.227 | 3.275 | **3.760** |*Table 1: Same-backbone RAG vs MSA (@1/@5/@10 vs MSA @adaptive)*---### Table 2: MSA vs best-of-breed RAG (large backbones)**Summary**: Against **KaLMv2+Qwen3β235B** and **KaLMv2+Llamaβ3.3β70B** (w/ and w/o reranking), MSA achieves the best score on **4/9** datasets and an average **3.760**, with relative gains of **+7.2%**, **+5.0%**, **+10.7%**, and **+5.4%** over the strongest configurations respectively. Gaps on a few datasets (e.g., MuSiQue) are largely attributable to parameter-count and intrinsic reasoning capacity.| Dataset | KaLMv2 + Qwen3β235B R@1 | R@5 | R@10 | Qwen3β235B (RR) R@1 | R@5 | R@10 | KaLMv2 + Llamaβ3.3 R@1 | R@5 | R@10 | Llamaβ3.3 (RR) R@1 | R@5 | R@10 | MSA (adaptive) ||---------|---------------------------|------|-------|--------------------------|------|-------|------------------------------|------|--------|-------------------------|------|--------|----------------|| MS MARCO v1 | 2.846 | <u>3.028</u> | 3.027 | 2.886 | 3.020 | 2.995 | 2.649 | 2.904 | 2.919 | 2.881 | 2.955 | 2.952 | **4.141** || Natural Questions | <u>3.711</u> | 3.670 | 3.694 | 3.621 | 3.610 | 3.645 | 3.675 | 3.674 | 3.662 | **3.756** | 3.665 | 3.647 | 3.545 || DuReader | 4.044 | 3.991 | 3.978 | 3.973 | 3.932 | 3.891 | <u>4.051</u> | 3.846 | 3.742 | 3.967 | 3.776 | 3.780 | **4.155** || TriviaQA (10M) | 4.367 | 4.656 | 4.578 | 4.492 | 4.320 | 4.555 | 4.273 | **4.740** | <u>4.719</u> | 4.547 | 4.703 | 4.695 | 4.621 || NarrativeQA | 1.413 | 2.130 | 2.427 | 3.212 | **3.427** | 3.375 | 1.290 | 2.123 | 2.382 | 3.150 | 3.263 | 3.317 | <u>3.395</u> || PopQA | 2.810 | 3.347 | <u>3.396</u> | 3.268 | 3.380 | 3.376 | 2.787 | 3.298 | 3.305 | 3.337 | 3.384 | 3.362 | **3.433** || 2WikiMultiHopQA | 2.646 | 3.579 | 3.582 | 1.855 | 3.381 | <u>3.583</u> | 1.339 | 3.263 | 3.445 | 1.651 | 3.332 | 3.541 | **4.280** || HotpotQA | 3.497 | 4.090 | **4.225** | 3.341 | 4.141 | 4.194 | 3.070 | 3.896 | 4.127 | 3.428 | 4.145 | <u>4.203</u> | 4.061 || MuSiQue | 1.988 | 2.462 | **2.647** | 1.801 | 2.522 | 2.605 | 1.704 | 2.317 | 2.258 | 1.895 | 2.462 | <u>2.614</u> | 2.211 || **Average** | 3.036 | 3.439 | 3.506 | 3.161 | 3.526 | <u>3.580</u> | 2.760 | 3.340 | 3.396 | 3.179 | 3.521 | 3.568 | **3.760** |*Table 2: SOTA RAG stacks (strong retriever + large generator + optional reranker) vs MSA*---### RULER NIAH stability (32Kβ1M)**Summary**: MSA maintains **94.84%** at **1M tokens**. The unmodified backbone collapses beyond **128K** (down to **24.69% @1M**). Hybrid linear-attention long-context models degrade noticeably at **β₯128K/256K**. External-memory agents (e.g., RLβMemoryAgentβ14B) remain stable but are weaker in **absolute accuracy** and show steeper decay than MSA.---## Implementation Notes- **Training**: 158.95B-token continuous pretraining with **auxiliary routing loss**, followed by two-stage SFT (**8kβ64k** curriculum).- **Ablations** (paper Table 4): curriculum extension, Memory Interleave, continuous pretraining, and injecting original text all contribute substantially; removing them causes **5%β37%** drops depending on task.- **Training cost**: MSA's near-linear complexity shows up directly in wall-clock time β full attention grows quadratically with context length while MSA stays close to linear.---## π Quick Start> This section is self-contained. [**QUICK_START.md**](./QUICK_START.md) additionally documents a> prebuilt `flash-attn` wheel, which avoids a slow source build.### Requirements| | ||---|---|| OS | Linux, x86-64 || Python | 3.12 (tested on 3.12.9) || CUDA | 12.x || GPUs | **8Γ 80GB** for the default benchmark suite; **2Γ 80GB (A800)** is enough for the `ms_100M` 100M-token setting via Memory Parallel || Disk | ~9 GB for weights + ~0.6 GB for benchmark data |`transformers` **must** be exactly `4.51.3` β the attention implementation targets that API and will notload on 4.52+ or on 5.x. The other pins in `requirements.txt` are the versions everything was tested with.### 1. Get the code```bashpip install -U "huggingface_hub==0.31.4"# If you are behind a mirror, uncomment the next line:# export HF_ENDPOINT=https://hf-mirror.comhuggingface-cli download Anoy123423123/MSA-Code --repo-type=model --local-dir MSAcd MSA```> `git clone https://huggingface.co/Anoy123423123/MSA-Code` works too.### 2. Install dependencies```bashconda create -n msa python=3.12 -yconda activate msapip install -r requirements.txt````flash-attn` is installed separately because it needs `--no-build-isolation`:```bashpip install flash-attn==2.7.4.post1 --no-build-isolation```Verify:```bashpython -c "import torch, transformers, flash_attn, pynvml; print(torch.__version__, transformers.__version__, flash_attn.__version__)"# expected: 2.6.0 4.51.3 2.7.4.post1```### 3. Download the model weights```bashhuggingface-cli download --resume-download Anoy123423123/MSA-4B --local-dir ckpt/MSA-4B```This is the path `scripts/run_benchmarks.sh` expects (`model_path=ckpt/MSA-4B`). ~9 GB.### 4. Benchmark dataNothing to do β benchmark files are fetched on first use from[`Anoy123423123/MSA-RAG-BENCHMARKS`](https://huggingface.co/datasets/Anoy123423123/MSA-RAG-BENCHMARKS)into `./data/<benchmark>/`. Each benchmark is two pickle files: `mdata_*.pkl` (memory corpus) and`qdata_*.pkl` (queries). ~0.6 GB for everything; `ms_100M` alone is 440 MB.### 5. Run inference```bashbash scripts/run_benchmarks.sh eval_benchmark```Results land in `src/evaluation/outputs/eval_benchmark/` β one `.log` and one `.json` per benchmark βand retrieval precision metrics are printed as each benchmark finishes.Check the top of `scripts/run_benchmarks.sh` first:```bashexport CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 # defaults to 8 GPUsmodel_path=ckpt/MSA-4B```The `benchmarks` array holds `name:batch_size` entries. **Batch size must be scaled together with theGPU count**: the memory corpus is partitioned into one bucket per visible GPU, so the defaults belowassume 8 GPUs.| Category | Benchmark | Default batch size ||---|---|---|| Multi-hop QA | `2wikimultihopqa`, `hotpotqa`, `musique` | 16 || Single-hop QA | `nature_questions`, `triviaqa_06M` | 16 || Single-hop QA (large corpus) | `triviaqa_10M` | 2 || HippoRAG | `hipporag_narrative`, `hipporag_popqa` | 16 || Passage retrieval / multilingual | `msmarco_v1`, `dureader` | 16 || Length scaling (100M tokens) | `ms_100M` | 16 |`ms_100M` and `triviaqa_06M` are commented out by default β uncomment them to reproduce thelength-scaling results. `ms_100M` is the 100M-token setting and is by far the heaviest run.### 6. Score the answersAnswer quality is graded by an LLM judge served through OpenRouter:```bashexport OPENROUTER_API_KEY=<your key> # or edit scripts/calculate_llm_score.shbash scripts/calculate_llm_score.sh eval_benchmark```The argument must match the log directory name from step 5.---## Project Structure```βββ scripts/β βββ run_benchmarks.sh # Run inference on benchmarksβ βββ calculate_llm_score.sh # LLM-based answer evaluationβ βββ resave_model.sh # Convert base model to MSA formatβββ src/βββ msa/ # Core MSA implementationβ βββ configuration_msa.py # MSA model configurationβ βββ memory_sparse_attention.py # MemorySparseAttention layerβ βββ model.py # MSAForCausalLM / MSAModelβ βββ generate.py # Generation logicβββ config/β βββ memory_config.py # GenerateConfig, ModelConfig, MemoryConfigβββ evaluation/β βββ llm_judge.py # LLM-based evaluation metricsβββ app/β βββ benchmark.py # Benchmark runnerβββ utils/ # GPU workers, caching, templates, etc.βββ msa_service.py # Multi-GPU inference engine (MSAEngine)βββ prefill.py # Stage 1 prefill workerβββ benchmarks.py # Benchmark registry & specsβββ types.py # Core type definitions```---## Troubleshooting| Symptom | Cause / fix ||---|---|| `KeyError` / `AttributeError` while loading the model | Wrong `transformers` version. It must be exactly `4.51.3`. || `import pynvml` fails or NVML calls are missing | The `pynvml` module here comes from `nvidia-ml-py`. If the separate, deprecated `pynvml` distribution is also installed it shadows the module: `pip uninstall -y pynvml && pip install nvidia-ml-py==12.575.51`. || CUDA OOM | Lower the per-benchmark `batch_size` in `scripts/run_benchmarks.sh`, or reduce the GPU count together with the batch size. || `flash_attn` import error | The wheel must match your torch / Python / CUDA combination. Build from source with `--no-build-isolation`. || Benchmark data download stalls | Set `export HF_ENDPOINT=https://hf-mirror.com` and retry; partial files resume. |---## CitationCitation details are withheld during anonymous peer review.## License6 unmodified lines789101112131415161 unmodified line181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091106 unmodified lines---# MSA: Memory Sparse Attention*A scalable, end-to-end trainable latent-memory framework for 100M-token contexts.***Anonymous code release for peer review.** This repository contains the inference and evaluation codeused to produce the reported benchmark results.| | ||---|---|1 unmodified line| Model weights | [`Anoy123423123/MSA-4B`](https://huggingface.co/Anoy123423123/MSA-4B) || Benchmark data | [`Anoy123423123/MSA-RAG-BENCHMARKS`](https://huggingface.co/datasets/Anoy123423123/MSA-RAG-BENCHMARKS) |## RequirementsLinux x86-64, Python 3.12, CUDA 12.x. **8Γ 80GB GPUs** for the default benchmark suite; the 100M-token`ms_100M` setting runs on **2Γ A800** via Memory Parallel. ~9 GB disk for weights, ~0.6 GB for data.`transformers` must be exactly **4.51.3** β the attention implementation targets that API and will notload on 4.52+ or 5.x. The other pins in `requirements.txt` are the tested versions.## Quick Start**1. Get the code**```bashpip install -U "huggingface_hub==0.31.4"# export HF_ENDPOINT=https://hf-mirror.com # uncomment if you need a mirrorhuggingface-cli download Anoy123423123/MSA-Code --repo-type=model --local-dir MSAcd MSA```**2. Install**```bashconda create -n msa python=3.12 -y && conda activate msapip install -r requirements.txtpip install flash-attn==2.7.4.post1 --no-build-isolation````flash-attn` is separate because it needs `--no-build-isolation`. To skip the slow source build, see theprebuilt wheel in [QUICK_START.md](./QUICK_START.md). Verify:```bashpython -c "import torch, transformers, flash_attn, pynvml; print(torch.__version__, transformers.__version__, flash_attn.__version__)"# expected: 2.6.0 4.51.3 2.7.4.post1```**3. Download the weights**```bashhuggingface-cli download --resume-download Anoy123423123/MSA-4B --local-dir ckpt/MSA-4B```This is the path `scripts/run_benchmarks.sh` expects (`model_path=ckpt/MSA-4B`).**4. Run inference**```bashbash scripts/run_benchmarks.sh eval_benchmark```Benchmark data is fetched automatically on first use into `./data/`. Results land in`src/evaluation/outputs/eval_benchmark/` as one `.log` and one `.json` per benchmark.**5. Score the answers**```bashexport OPENROUTER_API_KEY=<your key>bash scripts/calculate_llm_score.sh eval_benchmark```The argument must match the log directory name from step 4.## BenchmarksConfigured in the `benchmarks` array at the top of `scripts/run_benchmarks.sh` as `name:batch_size`:`2wikimultihopqa` `hotpotqa` `musique` `nature_questions` `triviaqa_06M` `triviaqa_10M``hipporag_narrative` `hipporag_popqa` `msmarco_v1` `dureader` `ms_100M``ms_100M` (the 100M-token setting) and `triviaqa_06M` are commented out by default.**Batch size must be scaled with your GPU count** β the memory corpus is partitioned into one bucket pervisible GPU, and the defaults assume the 8 GPUs in `CUDA_VISIBLE_DEVICES`.## Notes| Symptom | Fix ||---|---|| Errors loading the model | `transformers` must be exactly `4.51.3`. || `import pynvml` fails | The module comes from `nvidia-ml-py`; the separate deprecated `pynvml` distribution shadows it. `pip uninstall -y pynvml && pip install nvidia-ml-py==12.575.51` || CUDA OOM | Lower `batch_size` in `scripts/run_benchmarks.sh`. || Data download stalls | `export HF_ENDPOINT=https://hf-mirror.com` and retry; partial files resume. |See [QUICK_START.md](./QUICK_START.md) for the project layout and the prebuilt `flash-attn` wheel.## CitationWithheld during anonymous peer review.## License
README.md+39-219