Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
193 commits
Select commit Hold shift + click to select a range
69372f3
[None][feat] Request-carried KV-cache compression lengths
Hudayday Jul 15, 2026
8fc7cc9
[None][feat] General KV eviction primitives
Hudayday Jul 15, 2026
25db688
[None][feat] Port TriAttention onto the request-carried compression c…
Hudayday Jul 15, 2026
43c2efc
[None][fix] Keep RoPE unfused under KV-cache compression
Hudayday Jul 15, 2026
da8113c
[None][feat] Raise the CuTE-DSL top-k decode limit to 16384
Hudayday Jul 15, 2026
ec74781
[None][refactor] Decide speculative compatibility at the executor cal…
Hudayday Jul 16, 2026
9eec866
[None][refactor] Carry algorithm traits on a KV-cache compression mode
Hudayday Jul 16, 2026
befec91
Merge branch 'v3-branch' into v4-branch
Hudayday Jul 16, 2026
1ab4e5c
[None][perf] Port register-staged compaction and streamline TriAttention
Hudayday Jul 16, 2026
262cdbb
[None][chore] Trim the compression-mode docstring
Hudayday Jul 16, 2026
6cedd04
[None][chore] Trim the compression-mode docstring
Hudayday Jul 16, 2026
f22ca24
Merge branch 'v3-branch' into v4-branch
Hudayday Jul 16, 2026
51afc99
[None][chore] Describe the real compressed-token mechanism in the con…
Hudayday Jul 16, 2026
c4d80d3
[None][fix] Fail fast on speculative modes compression cannot support
Hudayday Jul 16, 2026
2813eb8
Merge branch 'v3-branch' into v4-branch
Hudayday Jul 16, 2026
8dab5cc
[None][fix] Fail fast on speculative modes compression cannot support
Hudayday Jul 16, 2026
cf1b3ad
[None][chore] Tighten the compression manager step-hook surface
Hudayday Jul 16, 2026
1cda810
[None][refactor] Tighten the KV-cache compression config surface
Hudayday Jul 16, 2026
10ffc1a
[None][chore] Regenerate the LLM args telemetry manifest
Hudayday Jul 16, 2026
cd94f76
[None][perf] Put score-kernel token tiles on the fastest grid axis
Hudayday Jul 16, 2026
0f128a0
[None][chore] Polish the batched compaction module
Hudayday Jul 16, 2026
23d654b
Merge branch 'main' of https://github.com/NVIDIA/TensorRT-LLM into v3…
Hudayday Jul 16, 2026
af3ec5c
Merge branch 'v3-branch' into v4-branch
Hudayday Jul 16, 2026
16cac99
[None][chore] Regenerate the LLM args telemetry manifest after the ma…
Hudayday Jul 16, 2026
fd0d761
[None][fix] Track the reworked speculative acceptance fields in the s…
Hudayday Jul 16, 2026
f6ade2c
Merge branch 'main' of https://github.com/NVIDIA/TensorRT-LLM into v4…
Hudayday Jul 17, 2026
213532d
[None][perf] Batch one eviction round across mixed prompt lengths
Hudayday Jul 17, 2026
3c7f3a2
[None][fix] Update the compact-layers instantiation macro signature
Hudayday Jul 17, 2026
f88c95d
[None][fix] Order destination_bases before the optional layer indices
Hudayday Jul 17, 2026
31e55fc
[None][refactor] Replace per-shape eviction caches with one resident …
Hudayday Jul 17, 2026
dc1107e
[None][chore] Empty the TriAttention package __init__ like the framew…
Hudayday Jul 17, 2026
0097566
[None][fix] Pass the move-index head stride to the compact kernel exp…
Hudayday Jul 17, 2026
ef5dd55
[None][chore] Name the compaction entry points for what they physical…
Hudayday Jul 17, 2026
9cd3fdf
[None][chore] Fold the frozen Triton kernel call into the kernels module
Hudayday Jul 17, 2026
9de7766
[None][fix] Catch the score-buffer tests up with the resident-buffer …
Hudayday Jul 17, 2026
165e03b
[None][chore] Drop the device-normalization helper
Hudayday Jul 17, 2026
b4070f8
[None][chore] Call the CuTE top-k operation directly
Hudayday Jul 17, 2026
201978e
[None][refactor] Make the keep-set selectors CUDA-only
Hudayday Jul 17, 2026
b5a0365
[None][chore] Drop the unused checked entry of the top-k finalizer
Hudayday Jul 17, 2026
32c8bb9
[None][chore] Order the kernels module along the eviction pipeline
Hudayday Jul 17, 2026
1ed3f59
[None][chore] Name the tie-settling kernel by its position after the …
Hudayday Jul 17, 2026
6d2d3de
[None][chore] House the prepared kernel launchers with their kernels
Hudayday Jul 17, 2026
ec4998c
Merge branch 'main' of https://github.com/NVIDIA/TensorRT-LLM into v4…
Hudayday Jul 17, 2026
bbb907a
[None][refactor] Gather every kernel warmup into one module with one …
Hudayday Jul 17, 2026
0782732
[None][perf] Carry the move offsets on the staged metadata table
Hudayday Jul 17, 2026
c7ca77b
[None][chore] Catch the page-table staging test up with the offsets-c…
Hudayday Jul 17, 2026
5933089
[None][refactor] Drop the kernel warmup machinery and dispatch directly
Hudayday Jul 17, 2026
04a7ad5
[None][fix] Keep score launches on the staging CUDA stream
Hudayday Jul 17, 2026
f4a895e
[None][fix] Bind the SWA compact family to the staged move offsets
Hudayday Jul 17, 2026
1e035c6
[None][fix] Skip the steady-generation fast prepare under KV compression
Hudayday Jul 18, 2026
a6bf4ea
[None][perf] Cut TriAttention score kernel time 1.5x via launch shape…
Hudayday Jul 18, 2026
87484da
[None][perf] Move TriAttention scoring to a folded CUDA op (4.4x scor…
Hudayday Jul 19, 2026
aba7609
[None][chore] Trim redundant TriAttention code and dedupe test fixtures
Hudayday Jul 20, 2026
6e0417f
[None][perf] Add pipelined bf16 KV-compact fast path behind a tempora…
Hudayday Jul 20, 2026
af786d3
[None][perf] Make the pipelined compact kernel the default bf16 path
Hudayday Jul 20, 2026
661c857
[None][chore] Merge latest main (KV cache compression framework merge…
Hudayday Jul 20, 2026
ae3be22
[None][perf] port TriAttention CuTe score kernel onto the rebuilt sco…
Hudayday Jul 20, 2026
ae8ed95
[None][perf] tabulate TriAttention mean-score phases at init, rotate …
Hudayday Jul 20, 2026
9e67032
[None][perf] fuse TriAttention keep-set settle and move-source packing
Hudayday Jul 20, 2026
538dcb9
[None][fix] Version-adapt CuTe sqrt and restore score kernel register…
Hudayday Jul 20, 2026
d72bb15
[None][fix] Map the CuTe sqrt shim onto cutlass 4.5 fastmath
Hudayday Jul 20, 2026
7233212
[None][perf] rotate TriAttention mean score coefficients in the score…
Hudayday Jul 20, 2026
accceea
[None][chore] Move the tie-settlement reference kernel into its unit …
Hudayday Jul 21, 2026
6e24355
[None][chore] Retire the register-staging sparse-KV compaction fallback
Hudayday Jul 21, 2026
6eff0e9
[None][chore] Fold the never-tuned offset ladder bound into a constant
Hudayday Jul 21, 2026
4de5227
[None][chore] Move the cohort-tail test helper into the test conftest
Hudayday Jul 21, 2026
c8c6bd7
[None][feat] Generalize the CuTe score kernel to 32-token pages
Hudayday Jul 21, 2026
a3c0053
[None][feat] Extend the CuTe score kernel to 64-frequency, GQA-group-…
Hudayday Jul 21, 2026
104f1c1
[None][chore] Log when the CuTe score path engages
Hudayday Jul 21, 2026
9c0cf95
[None][test] Migrate compaction fixtures to the shipped bf16 geometry
Hudayday Jul 21, 2026
727ae54
[None][chore] Warn when the opt-in CuTe score cannot engage
Hudayday Jul 21, 2026
2012bde
[None][feat] Make the CuTe DSL kernel the only TriAttention score path
Hudayday Jul 21, 2026
dbaccb8
[None][chore] Drop year-only diffs against main
Hudayday Jul 21, 2026
5013e99
[None][feat] Fuse settle+pack and gather mean phases from a position …
Hudayday Jul 21, 2026
1b3cd45
[None][fix] Clamp gathered phase rows and keep table construction dev…
Hudayday Jul 21, 2026
2b3e973
[None][chore] Drop a stale kernel-name reference from the fused pack …
Hudayday Jul 21, 2026
294176f
[None][feat] Integrate the fused score+stats+union pipeline (opt-in, …
Hudayday Jul 21, 2026
c5795bb
[None][fix] Decode staged page ids in the fused score kernel
Hudayday Jul 21, 2026
448db53
[None][perf] Bucket the score scratch by cohort need and widen its ba…
Hudayday Jul 21, 2026
78b7444
[None][feat] Generalize the fused score kernel to 32-token pages
Hudayday Jul 21, 2026
b86594e
[None][feat] Extend the fused score kernel to 64 frequencies and GQA …
Hudayday Jul 21, 2026
3936daf
[None][feat] Read the fused score window start from per-request metadata
Hudayday Jul 21, 2026
623df3d
[None][feat] Retire the split union scoring path
Hudayday Jul 21, 2026
56498df
[None][feat] Retire the single-shot CuTe score kernel
Hudayday Jul 22, 2026
be073ed
[None][fix] Fold 64-bit score offsets into the union finalizer's tail…
Hudayday Jul 22, 2026
98bab8b
[None][fix] Skip top-k sentinel lanes in the settle threshold gather
Hudayday Jul 22, 2026
2f03cd9
[None][chore] Carry the due count on an ungated eviction-round NVTX r…
Hudayday Jul 22, 2026
f0d756d
[None][perf] Emit the approximate FTZ square root in the fused score …
Hudayday Jul 22, 2026
2faf34f
Merge upstream main at 128d020489 into v4-branch
Hudayday Jul 22, 2026
6da91b6
[None][chore] Trim narration comments and drop dead score-runner wrap…
Hudayday Jul 22, 2026
346eb1a
[None][test] Slim TriAttention unit suite: torch oracles, table-drive…
Hudayday Jul 22, 2026
f21f1dd
[None][refactor] Flatten keep-set selector hierarchy into direct kern…
Hudayday Jul 22, 2026
a05be27
[None][refactor] Straight-line the eviction round flow
Hudayday Jul 22, 2026
90664ff
[None][refactor] Trust the pipeline: delete in-flow re-validation and…
Hudayday Jul 22, 2026
66fe91d
[None][chore] Kernel comment clarity + one-value scaffolding removal
Hudayday Jul 22, 2026
c80d714
[None][test] Collapse corner grids and mock-theater to representative…
Hudayday Jul 22, 2026
bb506ce
[None][fix] Reject generation requests that skipped on_request_init
Hudayday Jul 23, 2026
aa026ff
[None][refactor] Build the eviction cohort where its values are born
Hudayday Jul 23, 2026
0bee387
[None][refactor] Lock the fused dense pack on and drop the compiled-s…
Hudayday Jul 23, 2026
6c4381d
[None][doc] Align the README with the shipped defaults and contracts
Hudayday Jul 23, 2026
563d1cd
[None][test] Retire mock legs and duplicate grids ruled out with the …
Hudayday Jul 23, 2026
95d79f7
[None][refactor] Rename TriAttention top_B to budget (official name, …
Hudayday Jul 23, 2026
30b4cb3
[None][fix] Resolve RoPE tables via the transformers 5.5 rope_paramet…
Hudayday Jul 23, 2026
d475bf9
[None][refactor] Hoist compaction to package level and inline the rou…
Hudayday Jul 23, 2026
a0b90d4
[None][chore] Zero-risk clarity pass from the findings ledger (knife …
Hudayday Jul 23, 2026
78aab7d
[None][refactor] Codegen-identical dedup batch + scaffolding kills (k…
Hudayday Jul 23, 2026
4f22db1
[None][refactor] Framework census F-batch: compaction contract + hook…
Hudayday Jul 23, 2026
c136453
[None][test] Test tranche 3: dedupe scaffolding and fold duplicate gu…
Hudayday Jul 23, 2026
4542815
[None][refactor] Straighten init_eviction_buffers: one construction p…
Hudayday Jul 23, 2026
14d622e
[None][refactor] Fold runner compile ritual and single-heir helpers
Hudayday Jul 23, 2026
16ddb74
[None][perf] Host-work census batch: per-step and per-round dispatch …
Hudayday Jul 23, 2026
d069359
[None][refactor] Fold the eight raw-band TMA copy rituals into one tr…
Hudayday Jul 23, 2026
4c39809
[None][chore] Restore the draft-cache property and short hook docstrings
Hudayday Jul 23, 2026
3f28019
[None][chore] Revert the config-time normalize_scores validator to th…
Hudayday Jul 23, 2026
af1909e
[None][test] Test tranche 3 wave 2: merges, narration trims, official…
Hudayday Jul 23, 2026
0b959b2
[None][chore] Trim docstrings and comments to upstream brevity
Hudayday Jul 23, 2026
6d8047e
[None][chore] One-line the branch-added comments outside the compress…
Hudayday Jul 23, 2026
2caf43c
[None][perf] Cache launch-path from_dlpack wraps per persistent buffe…
Hudayday Jul 23, 2026
16f34c9
[None][perf] Stage cohort metadata with in-place numpy row writes (kn…
Hudayday Jul 23, 2026
71bbedc
[None][refactor] Inline the mean-phase table wrappers into their call…
Hudayday Jul 23, 2026
3a7c019
[None][chore] Compress docstrings to one or two lines
Hudayday Jul 23, 2026
a321e33
[None][refactor] Collapse init parameter transport; compaction become…
Hudayday Jul 23, 2026
b423dbc
[None][perf] Size the score-only raw-K smem by its single-buffer stag…
Hudayday Jul 23, 2026
9cb7af7
[None][refactor] Fission the fused settle+pack kernel: decision settl…
Hudayday Jul 23, 2026
b83f80c
[None][refactor] Remove the single-value pin_prefill and count_prompt…
Hudayday Jul 23, 2026
a611ebd
[None][refactor] One round owner: merge stage, run, and consume; dele…
Hudayday Jul 23, 2026
21add9c
[None][perf] Persist the per-head gather index; refresh only its base…
Hudayday Jul 23, 2026
4de514a
[None][perf] Settle reads per-request prompt offsets; drop the per-ro…
Hudayday Jul 23, 2026
5da7989
[None][perf] Launch eviction rounds at the active cohort size (knife …
Hudayday Jul 23, 2026
470acde
[None][chore] Return one named plane bundle; no anonymous tuple unpac…
Hudayday Jul 23, 2026
da7065e
[None][chore] Parameter-hygiene sweep: cluster, rename, and close orp…
Hudayday Jul 23, 2026
d604fa1
[None][refactor] P0 closure: dead fields, duplicate guards, per-round…
Hudayday Jul 23, 2026
82c4893
[None][fix] Bind the settle-stats epsilon as a constexpr default; Tri…
Hudayday Jul 23, 2026
df979c8
[None][refactor] P1 owner consolidation: canonical pool ids, opaque c…
Hudayday Jul 23, 2026
d2c119f
[None][refactor] Move the mean-phase table builder into its owner module
Hudayday Jul 23, 2026
f9615bb
[None][test] Test tranche 4: post-restructure orphan leg, matrix sque…
Hudayday Jul 23, 2026
53268b3
[None][refactor] Constructor takes the whole config; drop the Base pr…
Hudayday Jul 23, 2026
368fa8c
[None][refactor] Dissolve the runner shell and the bufs bag; TriAtten…
Hudayday Jul 23, 2026
e7819dd
[None][chore] Reflow the compression config docstring for the legacy …
Hudayday Jul 23, 2026
e04902c
[None][test] Final backstop: drop the config tautology and reflection…
Hudayday Jul 23, 2026
9a99caf
[None][refactor] Fold the launch-record grouping into init as one fam…
Hudayday Jul 23, 2026
702954a
[None][refactor] Delete the construction-time V2 compatibility valida…
Hudayday Jul 23, 2026
216ffb1
[None][refactor] Resolve manager-lifetime layer facts at construction…
Hudayday Jul 23, 2026
fe11a3d
[None][chore] Trim regrown narration comments to the banner bar (knif…
Hudayday Jul 23, 2026
2c5ef37
[None][refactor] One source of truth for calibration/copy state; merg…
Hudayday Jul 23, 2026
f5e9c62
[None][refactor] Buffer build reads the layout's own maps; direct bui…
Hudayday Jul 23, 2026
c5efed4
[None][refactor] Compaction grouping drops its anachronisms; one owne…
Hudayday Jul 23, 2026
7539fcd
[None][refactor] Drop the dead epilogue parameter and host alias twin…
Hudayday Jul 23, 2026
4877392
[None][test] Trim the draft-contract acceptance test to its live asse…
Hudayday Jul 23, 2026
aa9e0e8
[None][chore] Trim comments to plain functional descriptions (knife 40)
Hudayday Jul 24, 2026
be747b6
[None][chore] Drop the block-offset gather check wall and dead debug …
Hudayday Jul 24, 2026
ae0e190
[None][refactor] Order TriAttention by lifecycle and slim the compact…
Hudayday Jul 24, 2026
9b676a6
[None][refactor] Give compaction a single-cache typed plan builder
Hudayday Jul 24, 2026
7b28954
[None][refactor] Flatten compaction launches into CompactionParams
Hudayday Jul 24, 2026
a2614bf
[None][refactor] Make CompactionParams a frozen dataclass
Hudayday Jul 24, 2026
ff8bb73
[None][refactor] Fill CompactionParams progressively
Hudayday Jul 24, 2026
b57e20b
Merge commit '75b39d4368204267e70fc3daadaf1820d1fc99ed' into v4-branch
Hudayday Jul 24, 2026
18c9695
[None][chore] Order compaction params below the pack kernel
Hudayday Jul 24, 2026
cd50a4e
[None][chore] Simplify the compaction kernel comments
Hudayday Jul 24, 2026
1bad4ac
[None][chore] Sync review remediation from compaction PR branch
Hudayday Jul 24, 2026
597ac68
[None][fix] Close three eviction-runtime lifetime gaps: score-capacit…
Hudayday Jul 24, 2026
a626ae0
[None][refactor] Straighten the eviction control plane into one trans…
Hudayday Jul 25, 2026
c87378c
[None][chore] Fail fast on rope and model-config loading; drop the im…
Hudayday Jul 25, 2026
bccdc8d
[None][refactor] Close the resident-state names: one compiled-score m…
Hudayday Jul 25, 2026
e6d2cb7
[None][perf] Reduce score windows straight from the scratch and write…
Hudayday Jul 25, 2026
1a32167
[None][fix] Slice the score calibration to this rank's attention head…
Hudayday Jul 25, 2026
5b532d9
[None][fix] Restore the exact global union under TP: gather rank unio…
Hudayday Jul 25, 2026
faba603
[None][chore] Align TriAttention kernel-boundary names to the module …
Hudayday Jul 26, 2026
0d68666
[None][chore] Drop the per-round pool-drift poll and legacy rope conf…
Hudayday Jul 26, 2026
77017bc
[None][doc] Note that the native compact op derives batch from tensor…
Hudayday Jul 27, 2026
cb0101b
[None][fix] Validate the decision-row layout at the compaction API bo…
Hudayday Jul 27, 2026
bb89ca1
[None][test] Preserve compaction tests in TriAttention stack
Hudayday Jul 27, 2026
395e9c8
[None][chore] Keep TriAttention cleanup inside its PR boundary
Hudayday Jul 27, 2026
36090b8
[None][chore] Simplify TriAttention eviction runtime
Hudayday Jul 27, 2026
1a0a26e
Simplify TriAttention eviction flow
Hudayday Jul 28, 2026
418c660
[None][refactor] simplify TriAttention eviction runtime
Hudayday Jul 28, 2026
597f417
Merge commit '5ac225960070e4688a2fc4cfffaaee57fb166c74' into v4-branch
Hudayday Jul 28, 2026
1c309dd
fix: align TriAttention selection buffers
Hudayday Jul 28, 2026
3e3fc88
style: use relative TriAttention imports
Hudayday Jul 28, 2026
66fe4e8
style: make TriAttention imports consistently relative
Hudayday Jul 28, 2026
dadffc8
[None][refactor] Simplify TriAttention runtime flow
Hudayday Jul 28, 2026
ae6c2c5
Merge remote-tracking branch 'nvidia/main' into v4-branch
Hudayday Jul 28, 2026
e72af06
[None][chore] Format TriAttention sources
Hudayday Jul 28, 2026
d3e379e
[None][test] Align TriAttention fixtures with KV cache V2
Hudayday Jul 28, 2026
5bf4f3a
[None][fix] Correct TriAttention union tail stores
Hudayday Jul 28, 2026
ad35f62
[None][refactor] Encapsulate TriAttention Triton kernel launches
Hudayday Jul 30, 2026
333e7bf
[None][refactor] Centralize KV-cache compression capabilities
Hudayday Jul 30, 2026
693dcba
Merge latest main into kvcache-v2-triattention-no-engine
Hudayday Jul 31, 2026
39d5078
[None][fix] Gate TriAttention on SM100-family GPUs
Hudayday Jul 31, 2026
8f11102
[None][chore] Apply TriAttention factory formatting
Hudayday Jul 31, 2026
7561378
Merge latest main into kvcache-v2-triattention-no-engine
Hudayday Aug 1, 2026
aee6c52
Merge latest main into kvcache-v2-triattention-no-engine
Hudayday Aug 1, 2026
a27a55c
[None][refactor] Rename TriAttention compression manager
Hudayday Aug 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions cpp/tensorrt_llm/batch_manager/kvCacheManagerV2Utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#include "tensorrt_llm/common/memoryUtils.h"
#include <cassert>
#include <cstdio>
#include <cstring>
#include <cuda.h>
#include <fcntl.h>
#include <memory>
Expand Down Expand Up @@ -217,6 +218,40 @@ at::Tensor IndexMapper::getCopyIndex(
return copyIndex_.slice(0, 0, numSeqs);
}

void IndexMapper::gatherKBlockOffsets(at::Tensor const& source, at::Tensor destination,
std::vector<LlmRequest::RequestIdType> const& requestIds, SizeType32 numBlocks)
{
std::vector<int64_t> sourceRowsByRequest;
sourceRowsByRequest.reserve(requestIds.size());
for (auto const requestId : requestIds)
{
sourceRowsByRequest.push_back(static_cast<int64_t>(getIndex(requestId)) * maxBeamWidth_);
}

auto const* sourceData = source.data_ptr<int32_t>();
auto* destinationData = destination.data_ptr<int32_t>();
auto const sourceRows = source.size(1);
auto const sourcePlanes = source.size(2);
auto const sourceBlocks = source.size(3);
auto const destinationRows = destination.size(1);
auto const destinationPlanes = destination.size(2);
auto const destinationBlocks = destination.size(3);
auto const copyBytes = static_cast<size_t>(numBlocks) * sizeof(int32_t);

for (int64_t pool = 0; pool < source.size(0); ++pool)
{
for (size_t destinationRow = 0; destinationRow < sourceRowsByRequest.size(); ++destinationRow)
{
auto const sourceRow = sourceRowsByRequest[destinationRow];
auto const sourceOffset = ((pool * sourceRows + sourceRow) * sourcePlanes) * sourceBlocks;
auto const destinationOffset
= ((pool * destinationRows + static_cast<int64_t>(destinationRow)) * destinationPlanes)
* destinationBlocks;
std::memcpy(destinationData + destinationOffset, sourceData + sourceOffset, copyBytes);
}
}
Comment thread
Hudayday marked this conversation as resolved.
}

IndexMapper::IndexMapper(SizeType32 maxBatchSize, SizeType32 maxBeamWidth)
: maxBeamWidth_(maxBeamWidth)
{
Expand Down
6 changes: 5 additions & 1 deletion cpp/tensorrt_llm/batch_manager/kvCacheManagerV2Utils.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* SPDX-FileCopyrightText: Copyright (c) 2022-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-FileCopyrightText: Copyright (c) 2022-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
Expand Down Expand Up @@ -72,6 +72,10 @@ class IndexMapper
at::Tensor getCopyIndex(
std::vector<LlmRequest::RequestIdType> const& requestIds, SizeType32 numContext, SizeType32 beamWidth);

//! Gathers each request's beam-0 K block offsets into a host snapshot.
void gatherKBlockOffsets(at::Tensor const& source, at::Tensor destination,
std::vector<LlmRequest::RequestIdType> const& requestIds, SizeType32 numBlocks);

/// Number of sequences currently tracked (i.e. active IndexMapper slots).
[[nodiscard]] SizeType32 size() const noexcept
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ void KVCacheManagerV2UtilsBindings::initBindings(nb::module_& module)
.def("get_index", &IndexMapper::getIndex)
.def("remove_sequence", &IndexMapper::removeSequence)
.def("get_copy_index", &IndexMapper::getCopyIndex)
.def("gather_k_block_offsets", &IndexMapper::gatherKBlockOffsets, nb::arg("source"), nb::arg("destination"),
nb::arg("request_ids"), nb::arg("num_blocks"))
.def("size", &IndexMapper::size)
.def("num_free_slots", &IndexMapper::numFreeSlots);

Expand Down
125 changes: 125 additions & 0 deletions examples/kv_cache_compression/triattention.md
Comment thread
lfr-0531 marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# TriAttention KV-Cache Compression

This document describes enabling TriAttention KV-cache compression in TensorRT-LLM.

TriAttention is a training-free, decode-time KV-cache eviction method for long-context LLM inference. During generation it periodically scores the cached tokens by a trigonometric importance measure derived from offline per-head query statistics (calibration), keeps the most important `budget` tokens, and physically compacts the cache — reducing KV-cache memory so more sequences fit on a GPU at once.

For technical details see the paper [TriAttention](https://arxiv.org/abs/2604.04921) and the official implementation [github.com/WeianMao/triattention](https://github.com/WeianMao/triattention).

## Overview

TriAttention runs entirely in the generation phase and reuses the standard dense attention kernel over the compacted cache:

1. **Calibration (offline, one-time per model).** The importance score needs each attention head's mean and magnitude of the pre-RoPE query, gathered over a small calibration corpus. **TensorRT-LLM does not compute calibration** — you produce it once with the official tool and pass the resulting `.pt` file. TensorRT-LLM loads and converts it when the compression manager is created.
2. **Periodic eviction (during generation).** Every `beta` confirmed generation tokens, once a sequence is over budget, TriAttention scores the evictable decode region, selects `budget` decode tokens to keep, preserves the prompt, and physically compacts the KV cache down to that set. A speculative iteration may confirm multiple tokens; crossing multiple periods in one update is coalesced into one eviction.

TriAttention is integrated into TensorRT-LLM as a KV-cache compression manager on top of the `KVCacheManagerV2`. Scoring runs on CuTe DSL (SM100) and Triton kernels; compaction is a native CUDA kernel.

## Support Matrix

* NVIDIA B200 (SM100; the current validated target)
* Paged KV Cache (`KVCacheManagerV2`)
* PyTorch backend

**Notes:**
1. TriAttention supports KV-cache block reuse. V2 reuses the committed prompt prefix, while TriAttention preserves that prefix and compacts only the generation suffix.
2. TriAttention requires the V2 KV-cache manager (`use_kv_cache_manager_v2=True`).
3. TriAttention does not compute calibration. Bring the official tool's calibration `.pt`; see [Calibration](#calibration).
4. The current SWA path covers models such as GPT-OSS whose V2 pools remain full length and whose attention kernel applies the window. Native sliding-eviction layouts such as Gemma 4, SSM/hybrid pools, and MLA caches are not supported.
5. Speculative decoding is supported for one-model MTP and EAGLE3 with `eviction_mode="union"`. Tensor parallelism beyond TP1, attention DP, and disaggregated serving have not yet been validated end to end.

## Calibration

The calibration file is produced once per model with the official tool, then reused for every inference run with that model.

Generate the calibration file for your model with the official repository (for
example `qwen3-8b-calibration.pt` for Qwen3-8B), keep it anywhere on disk, and
point `calibration_path` at it:

```bash
# Clone + install the official tool
git clone https://github.com/WeianMao/triattention.git
cd triattention && pip install -e .

# Calibrate (writes the official {metadata, stats} .pt)
python3 scripts/calibrate.py \
--model <path_to_model> \
--input data/calibration_text.txt \
--output <model>_calibration.pt \
--max-length 32768 \
--device cuda
```

TensorRT-LLM accepts that file directly: it reads the official `{metadata, stats}` layout and derives the model's RoPE tables from the model config, then converts everything to its runtime schema at load. (An already-converted flat `.pt` is also accepted.)

## Usage

To enable TriAttention, pass a `TriAttentionKvCacheCompressionConfig` (the eviction knobs + the calibration file) to the `LLM` constructor. TriAttention is a pure compression method — there is **no** sparse-attention config and no custom attention backend; decode runs the model's standard attention over the compacted cache.

### Python API

```python
from tensorrt_llm import LLM, SamplingParams
from tensorrt_llm.llmapi import (KvCacheConfig,
TriAttentionKvCacheCompressionConfig)

# 1. Configure the eviction manager + point it at the calibration file.
compression_config = TriAttentionKvCacheCompressionConfig(
budget=2048, # tokens kept at each eviction (prompt is kept on top)
beta=64, # eviction period, in confirmed generation tokens
eviction_mode="union",
calibration_path="/path/to/qwen3-8b-calibration.pt", # official tool's output
model_path="<path_to_model>", # used to derive the RoPE tables
)

# 2. TriAttention needs the V2 KV-cache manager and supports block reuse.
kv_config = KvCacheConfig(enable_block_reuse=True, use_kv_cache_manager_v2=True)

llm = LLM(
model="<path_to_model>",
backend="pytorch",
kv_cache_compression_config=compression_config,
kv_cache_config=kv_config,
)

# 3. Generate
prompts = ["To be or not to be, that is the question."]
sampling_params = SamplingParams(max_tokens=128)
outputs = llm.generate(prompts, sampling_params)
```

### Usage with `trtllm-bench` and `trtllm-serve`

Pass the configs via `--config config.yaml`. The field names match the Python configs:

```yaml
backend: pytorch
kv_cache_compression_config:
algorithm: triattention
budget: 2048
beta: 64
eviction_mode: union
calibration_path: /path/to/qwen3-8b-calibration.pt
model_path: <path_to_model>
kv_cache_config:
enable_block_reuse: true
use_kv_cache_manager_v2: true
```

```bash
trtllm-eval --model <path_to_model> --config config.yaml longbench_v2 --max_output_length 1024 ...
```

## Configuration Arguments

`TriAttentionKvCacheCompressionConfig` controls the compression ratio and the eviction algorithm:

* **`budget`** (int, default=2048): Tokens kept at each eviction. Prompt tokens are always preserved on top of this. Smaller `budget` → more compression.
* **`beta`** (int, default=128): Eviction period, in confirmed generation tokens (the upstream `divide_length`). Speculative acceptance advances the counter by `1 + accepted_draft_tokens`; at most one eviction is coalesced per final update.
* **`eviction_mode`** (str, default=`union`): Which token set each eviction keeps.
* `union`: union of each KV head's top-B, re-ranked by the per-token max score. Matches the official base setting.
* `per_head`: each KV head keeps its own set, shared across layers (mean of per-layer maxima).
* `per_layer_perhead`: each head keeps its own set, fully independent per layer.
* **`normalize_scores`** (bool, default=True): Z-normalize each head's scores over the decode region before selection (upstream default). `union` eviction always z-normalizes: `False` is overridden to `True` with a warning.
* **`calibration_path`** (str): Path to the calibration `.pt` from the official tool. Required — TensorRT-LLM does not compute calibration.
* **`model_path`** (str): Checkpoint path, used to derive the model's RoPE tables when converting the official calibration file and to classify kernel-masked sliding-window (SWA) layers from the model config.
29 changes: 0 additions & 29 deletions tensorrt_llm/_torch/kv_cache_compression/interface.py

This file was deleted.

Empty file.
Loading
Loading