← 开源

Reuse the KV cache after mid-context edits in video LLMs (M-RoPE): 1.7–1.8x faster rebuilds, 96–97% answer agreement. arXiv 2611.18718

Python
增长势头
+024 小时新增 Star0.0%
344
Star
0
Fork
0
贡献者
创建于 2026-11-23 · 更新于 2026-12-05 · 今日第 24824 名
README

SCR-VL: Editable Video Context with Mid-Context KV-Cache Reuse

Edit the middle of a long-video context and rebuild its KV cache 1.7–1.8x faster than full recomputation (up to 2.3x when every surviving segment is relocated), with the same answer on 96–97% of questions on Qwen2.5-VL-7B. Also tested on Qwen3-VL-8B Instruct and Thinking. A vLLM 0.34 port (vllm_plugin/) cuts the time to first token after an edit by 1.5–1.7x against a full prefill on the same engine (see Serving with vLLM).

(a) Rebuild latency after a mid-context edit on Qwen2.5-VL-7B, full recomputation vs. SCR-VL; "agree" is how often both give the same answer. (b) Relocating more surviving segments saves more compute at a higher divergence from full recomputation (90-question answer-free study).

Code and aggregated results for the paper Editable Video Context: Mid-Context KV-Cache Reuse for Context-Managing Video LLMs by Dayu Wang* (NTU, Baidu) and Shasha Xu* (PKU), *equal contribution. The paper PDF built from this repository is paper/main.pdf.

How it works

A long video is held in the context as a list of timestamped segments. The model watches a sparse version, names the segments it needs, and the context is edited in the middle: those segments are re-decoded at 4x frame rate and others are deleted. Rebuilding the KV cache after such an edit normally means recomputing everything after the first changed token. SCR-VL avoids that for video LLMs with M-RoPE:

  • When a segment moves as a whole, its temporal, height and width positions all shift by the same offset Δ, so one rotation of the cached keys moves it. This is exact at layer 0 (relative error 3e-3 in bf16, one bf16 step) and is asserted per segment at run time.
  • A content-hashed cache of vision-encoder outputs removes ViT work for every surviving segment.
  • It works on Qwen2.5-VL-7B, Qwen3-VL-8B Instruct and Thinking, and passes the same correctness tests on Qwen3-VL-30B-A3B (MoE).

Results

Qwen2.5-VL-7B, model-chosen edit, SCR-VL with K=6 vs. full recomputation of the edited context (HuggingFace transformers, SDPA, one A800-80GB):

Benchmark Questions Answer agreement with full Prefill tokens saved Rebuild latency
V-NIAH (20–60 min synthetic needle) 720 97.4% 30% 7.20 s → 4.26 s (1.7x)
V-NIAH, FlashAttention-2 720 97.4% 30% 3.43 s → 1.88 s (1.8x)
Video-MME long 180 96.1% 32% 6.30 s → 3.46 s (1.8x)
LongVideoBench, videos ≥ 20 min 276 97.1% 32% 6.23 s → 3.49 s (1.8x)

Relocating every surviving segment instead of the 6 largest saves 63% of prefill tokens and runs 1.98x faster than full recomputation (2.29x with FlashAttention-2), at a higher divergence from full recomputation (probe KL 0.024 vs. 0.008). This comes from the answer-free harness on a 90-question V-NIAH sample (paper, Appendix D).

The edited context itself is valuable: densifying the segment that contains the needle raises V-NIAH accuracy from 52.2% to 96.9%. The models' own segment choice does not reach that (49.6%), and appending the densified segments instead of editing in place is a strong, cheap baseline at a 32K budget. The paper reports these negative results in full. All numbers come from results/summary.csv through scripts/make_tables.py; none is typed by hand.

Install

Python 3.10, PyTorch 2.7 (CUDA 12.6 wheels), one 80 GB GPU for the 7–8B models. Two environments are needed because Qwen2.5-VL and Qwen3-VL require different transformers versions.

git clone https://github.com/dayuwang401/SCR-VL && cd SCR-VL
python3.10 -m venv .venvs/vctx  && .venvs/vctx/bin/pip install -r env/requirements_vctx.txt    # Qwen2.5-VL, transformers 4.51.3
python3.10 -m venv .venvs/vctx3 && .venvs/vctx3/bin/pip install -r env/requirements_vctx3.txt  # Qwen3-VL, transformers 4.57.1
# optional, for the FlashAttention-2 runs: pip install flash-attn==2.8.0.post2 --no-build-isolation

Download the weights into models/ (or point VCTX_MODELS elsewhere):

huggingface-cli download Qwen/Qwen2.5-VL-7B-Instruct --revision cc594898137f460bfe9f0759e9844b3ce807cfb5 --local-dir models/Qwen2.5-VL-7B-Instruct
huggingface-cli download Qwen/Qwen3-VL-8B-Instruct   --revision 0c351dd01ed87e9c1b53cbc748cba10e6187ff3b --local-dir models/Qwen3-VL-8B-Instruct
huggingface-cli download Qwen/Qwen3-VL-8B-Thinking   --revision 92f3c4b4feadd3a016ef468d103bb5f58b2a2c6b --local-dir models/Qwen3-VL-8B-Thinking

Always source one of the env scripts first. They set $PY, the model and the venv's own cuDNN on LD_LIBRARY_PATH.

Script Model
env.sh Qwen2.5-VL-7B-Instruct
env3.sh Qwen3-VL-8B-Instruct
env3t.sh Qwen3-VL-8B-Thinking (answers with an empty think block)
env3moe.sh Qwen3-VL-30B-A3B-Thinking

Check correctness first

source env.sh;  CUDA_VISIBLE_DEVICES=0 $PY -m pytest -q tests      # GPU tests need the model; CPU-only tests run anywhere
source env3.sh; CUDA_VISIBLE_DEVICES=0 $PY -m pytest -q tests/test_correctness.py

tests/test_correctness.py checks per-segment position consistency, layer-0 key exactness after the rotation, no-edit equivalence, prefix exactness, and that deleting only the last segment makes SCR-VL equal prefix reuse bit for bit. The measured numbers are written to results/test_numbers*.json.

Data

No video is redistributed. Build everything under data/ from the original sources, after source env.sh.

V-NIAH haystacks. Three public-domain films from the Internet Archive (Public Domain Mark 1.0): anna-christie-1930-greta-garbo-english, disraeli_1929_202506 and bulldog-drummond_1929_202506. Save them as data/haystack/{anna_christie_1930,disraeli_1929,bulldog_drummond_1929}.mp4, then decode 2 fps frame banks:

for f in anna_christie_1930 disraeli_1929 bulldog_drummond_1929; do
  $PY scripts/build_bank.py data/haystack/$f.mp4 data/bank/$f.npy; done            # 448x308

The needle cards and questions are generated deterministically from seed 0 by vctx/tasks/vniah.py.

Video-MME long (first 60 long videos by YouTube id, HF lmms-lab/Video-MME, academic research use):

$PY scripts/fetch_videomme.py 60
mkdir -p data/videomme/bank; for v in data/videomme/videos/*.mp4; do
  $PY scripts/build_bank.py $v data/videomme/bank/$(basename $v .mp4).npy 1.0 252 448; done

LongVideoBench (HF longvideobench/LongVideoBench, gated, CC BY-NC-SA 4.0). Accept the terms on HuggingFace and export HF_TOKEN. We use all 276 validation questions whose video is at least 20 minutes long (92 videos), without subtitles:

mkdir -p data/lvb && cd data/lvb
huggingface-cli download longvideobench/LongVideoBench lvb_val.json --repo-type dataset --local-dir .
python -c "import json; d=[x for x in json.load(open('lvb_val.json')) if x['duration']>=1200]
json.dump([x['id'] for x in d], open('selected_ids.json','w'))
open('patterns.txt','w').write(''.join(f'*{v}\n' for v in sorted({x['video_path'] for x in d})))"
huggingface-cli download longvideobench/LongVideoBench --repo-type dataset --include "videos.tar.part.*" --local-dir .
cat videos.tar.part.* | tar -x --wildcards -T patterns.txt && cd ../..
mkdir -p data/lvb/bank; for v in data/lvb/videos/*.mp4; do
  $PY scripts/build_bank.py $v data/lvb/bank/$(basename $v .mp4).npy 1.0 252 448; done

Run the experiments

Every script resumes: questions already in results/<tag>_shard*.jsonl are skipped. Shard across GPUs with --shard i --num-shards N.

source env.sh
$PY scripts/run_vniah.py  --shard 0 --num-shards 1 --n-per-cell 80 --tag vniah                  # V-NIAH, 720 questions
$PY scripts/run_vniah.py  --shard 0 --num-shards 1 --init-frames 16 --dense-frames 64 --ablate-every 1000000 --tag vniah64k
VCTX_ATTN=flash_attention_2 $PY scripts/run_vniah.py --shard 0 --num-shards 1 --tag vniah_fa2
$PY scripts/run_append.py --shard 0 --num-shards 1 --tag append                                 # edit-append control
$PY scripts/run_longqa.py --shard 0 --num-shards 1 --tag videomme                               # Video-MME
$PY scripts/run_longqa.py --dataset lvb --shard 0 --num-shards 1 --tag lvb                      # LongVideoBench
source env3.sh    # Qwen3-VL-8B: same scripts with tags q3vl_vniah / q3vl_videomme / q3vl_lvb
source env3t.sh   # Qwen3-VL-8B-Thinking: tags q3vlt_*

Then regenerate results/summary.csv, every table, every figure and the PDF:

bash scripts/build_paper.sh                  # uses tectonic if on PATH, otherwise pdflatex + bibtex
SKIP_RESULTS=1 bash scripts/build_paper.sh   # compile only, from the committed paper/numbers.tex and paper/tables/

Benchmark harness

python -m vctx.cli runs the same pipeline as a two-track harness with frozen splits (--mode sample or full), per-question trajectories and leaderboards. See AGENTS.md for the rules.

python -m vctx.cli list        # tasks, sample sizes, registered edit policies and rebuilders
# edit track: better context-edit rules, rebuild frozen to the exact prefix path, accuracy only
python -m vctx.cli edit  --task vniah --mode sample --policy v0 --save-traj
# infra track: better KV rebuilds, edit frozen, answer-free fidelity vs. full recomputation plus cost
python -m vctx.cli trace      --task vniah --mode sample --pattern v0
python -m vctx.cli infra-eval --task vniah --mode sample --pattern v0 --rebuilder scr:K=6,r=0 --rebuilder scr_all:r=0 --rebuilder prefix --repeats 2
python -m vctx.cli summarize
  • New edit policy: add a module under vctx/edit/policies/ with @register. example_neighbors.py and tests/edit/test_example_policy.py are a complete template. Included policies: v0 (the paper's rule), v0_think, noop, example_neighbors, scan, coarse2fine, propose_verify, think_vote.
  • New rebuild algorithm: register f(engine, old_state, new_blocks, **params) -> (state, logits, stats) in vctx/infra/contrib.py and rank it with infra-eval (docs/infra/EVAL.md). Included: full, prefix, scr, scr_all, and boundary-repair and ordering variants (scr_tailrepair, scr_visrepair, scr_vistail, scr_protect, scr_early, scr_late, scr_small).

Serving with vLLM

vllm_plugin/ runs SCR-VL inside stock vLLM 0.34.0 through --scheduler-cls and a KV connector, without patching vLLM. Install, configuration and environment variables are in vllm_plugin/README.md. In short:

python3.12 -m venv .venvs/vllm && .venvs/vllm/bin/pip install vllm==0.34.0 matplotlib pandas
.venvs/vllm/bin/pip install -e vllm_plugin && export PYTHONPATH=$PWD
.venvs/vllm/bin/python vllm_plugin/scripts/verify_install.py        # VERIFY OK
python -m scr_vl_vllm --model Qwen/Qwen2.5-VL-7B-Instruct --port 10000   # OpenAI server; or vllm.LLM(...) offline
LLM(model=path, block_size=16, enable_prefix_caching=False, limit_mm_per_prompt={"video": 40},
    scheduler_cls="scr_vl_vllm.scheduler.SCRScheduler",
    kv_transfer_config={"kv_connector": "SCRConnector",
                        "kv_connector_module_path": "scr_vl_vllm.connector", "kv_role": "kv_both"})
SamplingParams(..., extra_args={"scr_session": "<conversation id>"})   # server: "vllm_xargs": {"scr_session": ...}

Speed. Turn-2 time to first token after a mid-context edit (32 × 8-frame V-NIAH segments; 1–3 segments densified to 16 frames, the other even segments deleted; SCRVL_K=6), one request at a time on one A800-80GB, median of 12 cases, vllm_plugin/scripts/bench_speedup.py. Engine is GPU time from scheduling to the first token; wall adds CPU-side input processing. Full prefill is the same edited prompt in a fresh session on the same SCR engine, so it shares the warm vision-encoder cache and isolates the LLM-side saving; prefix caching is stock vLLM APC (reuse up to the first edited token); no reuse is stock vLLM.

Model Turn-2 tokens SCR-VL engine / wall Full prefill Prefix caching No reuse
Qwen2.5-VL-7B 13,955 0.665 s / 0.740 s 0.990 s (1.49x) / 1.001 s 1.073 s (1.61x) / 1.128 s 1.553 s (2.34x) / 1.839 s
Qwen3-VL-8B-Instruct 11,884 0.560 s / 0.642 s 0.976 s (1.74x) / 0.991 s 0.964 s (1.72x) / 1.030 s 1.178 s (2.10x) / 1.482 s

Speed-ups are on engine time; the wall-clock ratios are 1.35x / 1.52x / 2.49x and 1.54x / 1.60x / 2.31x.

Fidelity. On the real pipeline (model-chosen edit, policy v0; 4 questions per benchmark, 8 sampled trajectories each at T = 0.7, SCR and session-less full prefill run with the same seed), the sampled answers agree on 95.8% (Qwen2.5-VL-7B), 100% (Qwen3-VL-8B-Instruct) and 99.0% (Qwen3-VL-8B-Thinking, empty think block) of trajectories; the median KL of the first answer token is 6.4e-3, 4.5e-5 and 2.8e-4. SCR was engaged (KL > 0, no fallback) on 95, 91 and 94 of 96 trajectories. With thinking enabled the long sampled reasoning amplifies bf16-level differences and agreement drops to 83% at a first-token KL of 1.1e-4. These are smoke-scale numbers; full-set pass@k is in progress.

Layout

vctx/            engine.py (Qwen2.5-VL rebuild paths), engine3.py (Qwen3-VL / MoE), kvops.py (M-RoPE key shift),
                 positions.py, segments.py, vitcache.py, policy.py, runtime.py, tasks/, bench/, edit/, infra/, splits/, cli.py
tests/           correctness tests (GPU) and harness tests (CPU)
scripts/         experiment entry points, summary/table/figure generators, build_paper.sh
results/         summary.csv, infra-eval leaderboard, correctness-test numbers, environment record
paper/           LaTeX source; every number is a macro in paper/numbers.tex generated from results/
docs/infra/      rebuild-track guide and the answer-free evaluation protocol
vllm_plugin/     vLLM 0.34 port: scr_vl_vllm/ (scheduler, KV connector, M-RoPE re-rotation), scripts/, tests/

Per-question records are not released, because they contain Video-MME and LongVideoBench questions and answers.

Citation

@article{wang2026editable,
  title   = {Editable Video Context: Mid-Context KV-Cache Reuse for Context-Managing Video LLMs},
  author  = {Wang, Dayu and Xu, Shasha},
  journal = {arXiv preprint arXiv:2611.18718},
  year    = {2026}
}

License

Code: Apache-2.0. Datasets and model weights keep their own licenses (paper, Table 11).

排名相邻

AI Rank iPhone 版

随时追踪 AI 模型榜单

在 App Store 下载