审计与调整 kNNGuard 以适应长上下文提示词
摘要
本文对 kNNGuard(一种无需训练、基于激活的护栏机制)进行了评估,发现其性能在长上下文提示下显著下降,随后提出了三种改进方案——长度路由双库、长上下文嵌入和跨步窗口池化——显著恢复了其在内容审核和 RAG 幻觉检测任务中的 AUROC。
查看缓存全文
缓存时间: 2026/11/23 09:24
# Auditing and Adapting kNNGuard for Long-Context Prompts
Source: [https://arxiv.org/html/2611.27084](https://arxiv.org/html/2611.27084)
###### Abstract
Training\-free activation guardrails such askNNGuard\[[1](https://arxiv.org/html/2611.27084#bib.bib1)\]score prompts by comparing last\-token LLM hidden states \(the Layer Ensemble branch,kNNGuard LE\) and sentence embeddings \(all\-MiniLM\-L6\-v2,Embedding\-kNN\) against a small reference bank \(n=50n=50examples per class\), combining the two branches into a Fused Ensemble \(kNNGuard FE\)\.
While effective on short inputs \(≤256\\leq 256tokens\), standardkNNGuarddegrades substantially on long inputs \(\>1000\>1000tokens\): averaged acrossQwen3\.5\-4BandGemma\-4\-E4B\-it,kNNGuard LEAUROC drops from0\.7420\.742\(0\.7770\.777and0\.7060\.706\) to0\.5540\.554\(0\.5870\.587and0\.5210\.521\) on Content Harm Moderation \(Aegis\-2\.0\), and from0\.9940\.994\(0\.9950\.995and0\.9920\.992\) to0\.5560\.556\(0\.5980\.598and0\.5130\.513\) on RAG Hallucination Detection \(HaluBench\)\. We trace this degradation to three causes: \(1\) hidden\-state drift as sequence length increases\[[14](https://arxiv.org/html/2611.27084#bib.bib2)\], \(2\) hard 256\-token truncation inMiniLM, and \(3\) signal dilution when a long document is compressed into a single final\-token vector\. We then evaluate three training\-free adaptations: aLength\-Routed Dual Bank, a long\-context embedding model \(Qwen3\-Embedding\-0\.6B\), andStrided Window Poolingacross intermediate token positions\. On Content Harm Moderation, dual\-bank routing and strided window pooling raise long\-contextkNNGuard LEAUROC from0\.5540\.554to0\.828\\mathbf\{0\.828\}\(\+0\.274\+0\.274AUROC\) and fusedkNNGuard FEAUROC from0\.7210\.721to0\.886\\mathbf\{0\.886\}\(\+0\.164\+0\.164AUROC\) with no latency overhead from bank routing\. On RAG Hallucination Detection, where the guardrail must verify logical consistency between a generated answer and a retrieved passage, sentence\-embeddingkkNN remains near random chance across all lengths, while length\-matched LLM hidden states \(kNNGuard LE\) recover medium\-length detection \(AUROC=0\.853\\text\{AUROC\}=0\.853\) but remain limited on\>1000\>1000\-token passages \(AUROC=0\.607\\text\{AUROC\}=0\.607\) due to final\-token dilution over long contexts\.
## 1Introduction
As Large Language Models \(LLMs\) are deployed in retrieval\-augmented generation \(RAG\)\[[16](https://arxiv.org/html/2611.27084#bib.bib27)\], long\-document analysis\[[4](https://arxiv.org/html/2611.27084#bib.bib9)\], and multi\-paragraph moderation pipelines\[[25](https://arxiv.org/html/2611.27084#bib.bib10)\], guardrails must screen inputs and outputs spanning thousands of tokens without adding high latency or retraining costs\.
Most production guardrails are separate open\-weight LLMs \(typically 7B to 12B parameters\) that have been fine\-tuned on labeled safety or hallucination datasets to act as classifiers\. Recent examples includeLlama Guard 4\[[20](https://arxiv.org/html/2611.27084#bib.bib8)\],Llama Nemotron Safety Guard V2\[[9](https://arxiv.org/html/2611.27084#bib.bib5)\],Llama Nemotron Topic Guard\[[27](https://arxiv.org/html/2611.27084#bib.bib34)\],Qwen3Guard\[[33](https://arxiv.org/html/2611.27084#bib.bib31)\],Granite Guardian\[[23](https://arxiv.org/html/2611.27084#bib.bib32)\], andLynx\[[24](https://arxiv.org/html/2611.27084#bib.bib4)\]\. While accurate on their training distributions, running a dedicated classifier LLM adds inference latency to every request, and changing a safety policy requires collecting new training data and fine\-tuning the model again\.
To avoid fine\-tuning a separate classifier, Abdelfattah et al\.\[[1](https://arxiv.org/html/2611.27084#bib.bib1)\]recently introducedkNNGuard, a training\-free guardrail based on nearest\-neighbor retrieval in activation space\[[15](https://arxiv.org/html/2611.27084#bib.bib14)\]and hidden\-state probing\[[34](https://arxiv.org/html/2611.27084#bib.bib11),[2](https://arxiv.org/html/2611.27084#bib.bib13),[19](https://arxiv.org/html/2611.27084#bib.bib12)\]\. For each task,kNNGuardcaches representations for a small reference bank of5050negative \(allowed\) and5050positive \(rejected\) prompts\.
At inference time, it classifies a new input in a single forward pass by combining two nearest\-neighbor risk scores: one computed from the LLM’s last\-token hidden states across multiple transformer layers, and one computed from a lightweight sentence encoder \(all\-MiniLM\-L6\-v2\[[26](https://arxiv.org/html/2611.27084#bib.bib6),[30](https://arxiv.org/html/2611.27084#bib.bib23)\]\), selecting whichever branch is more confident\.
Despite strong performance on standard benchmarks,kNNGuard’s design implicitly assumes short inputs \(≤256\\leq 256tokens\)\. In this work, we audit howkNNGuardbehaves as input length scales from under256256tokens to over64006400tokens across two benchmarks: Content Harm Moderation \(nvidia/Aegis\-AI\-Content\-Safety\-Dataset\-2\.0\[[9](https://arxiv.org/html/2611.27084#bib.bib5)\]\) and RAG Hallucination Detection \(PatronusAI/HaluBench\[[24](https://arxiv.org/html/2611.27084#bib.bib4)\]\), evaluated onQwen/Qwen3\.5\-4B\[[31](https://arxiv.org/html/2611.27084#bib.bib24)\]andgoogle/gemma\-4\-E4B\-it\[[29](https://arxiv.org/html/2611.27084#bib.bib25)\]\.
We show that standardkNNGuarddegrades on long inputs for three concrete reasons:
1. 1\.Reference\-Bank Length Mismatch:Kale and Vishwanath\[[14](https://arxiv.org/html/2611.27084#bib.bib2)\]recently showed that the distribution of last\-token hidden states shifts systematically as sequence lengthTTincreases, because self\-attention layers aggregate over a growing number of context tokens\. When the reference bank contains only short prompts \(≤256\\leq 256tokens\), long test queries \(\>1000\>1000tokens\) land in a shifted region of activation space, causing the LLM activation branch \(kNNGuard LE\) AUROC to drop toward random chance \(0\.5130\.513–0\.5980\.598\)\.
2. 2\.Hard Truncation and Limits of Sentence Embeddings:The defaultall\-MiniLM\-L6\-v2\[[30](https://arxiv.org/html/2611.27084#bib.bib23)\]encoder truncates inputs at256256tokens\. In RAG hallucination detection \(HaluBench\), where each input places the retrieved passage before the question and the answer to be verified, a256256\-token limit cuts off the question and answer on over60%60\\%of medium\-length inputs \(257257–10001000tokens\) and100%100\\%of long inputs \(\>1000\>1000tokens\)\. Moreover, as we show in Section[5](https://arxiv.org/html/2611.27084#S5), even when truncation is completely removed using a long\-context embedder or256256\-token chunking, sentence\-embeddingkkNN remains near random chance \(≈0\.46\\approx 0\.46–0\.560\.56AUROC\) on RAG hallucination detection because logical consistency between an answer and a passage is too fine\-grained to be captured by static text embeddings\.
3. 3\.Single\-Vector Signal Dilution:Compressing a multi\-thousand\-token document into a single final\-token vector𝐡\(ℓ\)\[−1\]\\mathbf\{h\}^\{\(\\ell\)\}\[\-1\]dilutes localized unsafe statements or single\-sentence factual contradictions buried inside a mostly benign passage\[[18](https://arxiv.org/html/2611.27084#bib.bib16)\]\.
### Our Contributions
To isolate the effect of each failure mode and adaptkNNGuardto long contexts without fine\-tuning, we make the following contributions:
- •Long\-Context Audit ofkNNGuard:Using the Area Under the ROC Curve \(AUROC\), we evaluate standardkNNGuardacross short \(≤256\\leq 256tokens\), medium \(257257–10001000tokens\), and long \(\>1000\>1000tokens\) inputs onAegis\-2\.0andHaluBench, showing thatkNNGuard LEAUROC falls from0\.7060\.706–0\.7770\.777to0\.5210\.521–0\.5870\.587on content moderation and from0\.9920\.992–0\.9950\.995to0\.5130\.513–0\.5980\.598on RAG hallucination detection\.
- •Length\-Routed Dual Reference Bank:We introduce a dual\-bank routing mechanism that switches between a short reference bank \(≤256\\leq 256tokens\) and a long reference bank \(\>256\>256tokens\) based on the input token countTTwith no latency overhead\. On long content moderation queries \(Aegis\-2\.0\), dual\-bank routing liftskNNGuard LEAUROC from0\.5540\.554to0\.7220\.722and fusedkNNGuard FEAUROC from0\.7210\.721to0\.886\\mathbf\{0\.886\}, while keeping short\-prompt accuracy unchanged\.
- •Long\-Context Embedding Replacement:We replaceMiniLMwithQwen/Qwen3\-Embedding\-0\.6B\[[32](https://arxiv.org/html/2611.27084#bib.bib7)\]\(which supports up to3276832768tokens via Rotary Positional Embeddings\[[28](https://arxiv.org/html/2611.27084#bib.bib15)\]\), eliminating answer truncation on long inputs and improving short\-context safety AUROC onGemma\-4\-E4B\-itfrom0\.7460\.746to0\.7900\.790\.
- •Strided Window Pooling:Instead of relying only on a single end\-of\-sequence vector for a long prompt, we score the prompt across256256\-token windows \(reading out the LLM hidden state at every256256\-th token during the single prefill pass forkNNGuard LE, and encoding256256\-token text chunks for the embedding branch\) and aggregate window scores viaTop\-2 Meanpooling\. This boosts long\-contextkNNGuard LEAUROC onAegis\-2\.0from0\.7220\.722to0\.828\\mathbf\{0\.828\}\(0\.8370\.837onQwen3\.5\-4Band0\.8180\.818onGemma\-4\-E4B\-it\)\. Finally, we show why reference\-bank adaptation recovers medium\-length RAG hallucination detection \(LE AUROC=0\.853\\text\{LE AUROC\}=0\.853,FE AUROC=0\.837\\text\{FE AUROC\}=0\.837\) while sentence\-embeddingkkNN remains near random chance \(AUROC≈0\.46\\text\{AUROC\}\\approx 0\.46–0\.560\.56\) across all context lengths\.
## 2Related Work and Preliminaries
### 2\.1Related Work
#### Fine\-Tuned Guardrail Classifiers
Programmable guardrail toolkits such asNeMo Guardrails\[[25](https://arxiv.org/html/2611.27084#bib.bib10)\]and fine\-tuned safety models \(Llama Guard 4\[[20](https://arxiv.org/html/2611.27084#bib.bib8)\],Llama Nemotron Safety Guard V2\[[9](https://arxiv.org/html/2611.27084#bib.bib5)\],Llama Nemotron Topic Guard\[[27](https://arxiv.org/html/2611.27084#bib.bib34)\],Granite Guardian\[[23](https://arxiv.org/html/2611.27084#bib.bib32)\], andQwen3Guard\[[33](https://arxiv.org/html/2611.27084#bib.bib31)\]\) treat content moderation as a supervised classification task trained on large labeled corpora\.
Similarly, RAG hallucination detection has relied on natural language inference \(NLI\) benchmarks such asTRUE\[[11](https://arxiv.org/html/2611.27084#bib.bib28)\]or fine\-tuned evaluator LLMs such asLynx\[[24](https://arxiv.org/html/2611.27084#bib.bib4)\]andGranite Guardian\[[23](https://arxiv.org/html/2611.27084#bib.bib32)\]that check whether a generated answer is supported by a source document\. While accurate on their training domains, fine\-tuned classifier LLMs require collecting new training data and retraining whenever the target policy or domain changes\.
#### Hidden\-State Probing and Training\-FreekkNN Guardrails
To avoid the latency and retraining cost of a separate classifier LLM, recent work inspects the internal hidden states of the target LLM itself\[[34](https://arxiv.org/html/2611.27084#bib.bib11)\]\. Classifiers trained on intermediate layer activations have been used to detect factual errors\[[2](https://arxiv.org/html/2611.27084#bib.bib13),[19](https://arxiv.org/html/2611.27084#bib.bib12)\], steer models away from unsafe outputs at inference time \(SafeSwitch\[[10](https://arxiv.org/html/2611.27084#bib.bib33)\]\), and detect indirect prompt injections\[[6](https://arxiv.org/html/2611.27084#bib.bib26)\]\.
Non\-parametrickkNN search over hidden states\[[15](https://arxiv.org/html/2611.27084#bib.bib14)\]avoids training even a linear probe, forming the basis of single\-pass guardrails such asSALLIE\[[3](https://arxiv.org/html/2611.27084#bib.bib3)\]andkNNGuard\[[1](https://arxiv.org/html/2611.27084#bib.bib1)\]\. However, Kale and Vishwanath\[[14](https://arxiv.org/html/2611.27084#bib.bib2)\]recently showed that hidden\-state probes are sensitive to sequence\-length shifts, and Dubanowska et al\.\[[8](https://arxiv.org/html/2611.27084#bib.bib29)\]found that activation\-based hallucination detectors degrade under distribution shifts, motivating long\-form RAG detectors such asFACTUM\[[5](https://arxiv.org/html/2611.27084#bib.bib30)\]and our long\-context audit ofkNNGuard\.
### 2\.2kNNGuardArchitecture
Following Abdelfattah et al\.\[[1](https://arxiv.org/html/2611.27084#bib.bib1)\], each task domaindduses a labeled reference bankℬ\(d\)=\{\(xi,yi\)\}i=12n\\mathcal\{B\}^\{\(d\)\}=\\\{\(x\_\{i\},y\_\{i\}\)\\\}\_\{i=1\}^\{2n\}containingnnnegative \(yi=0y\_\{i\}=0\) andnnpositive \(yi=1y\_\{i\}=1\) examples, partitioned into index setsC0=\{i:yi=0\}C\_\{0\}=\\\{i:y\_\{i\}=0\\\}andC1=\{i:yi=1\}C\_\{1\}=\\\{i:y\_\{i\}=1\\\}\. For the LLM activation branch, each raw inputxxis prepended with a domain\-specific system prompt to formx~\\tilde\{x\}, instructing the LLM to classify negative \(allowed\) inputs ason\-topic\(y=0y=0\) and positive \(rejected\) inputs asoff\-topic\(y=1y=1\)\.
#### Layer\-Ensemble Activation Branch \(kNNGuard LE\)
Given an LLM withLLtransformer decoder layers,kNNGuard LE\(*Layer Ensemble*\) selectsMMevenly spaced layers indexed byℓ∈\{1,…,M\}\\ell\\in\\\{1,\\dots,M\\\}along the depth of the network\. For each reference promptx~i\\tilde\{x\}\_\{i\}, let𝐡i\(ℓ\)∈ℝD\\mathbf\{h\}\_\{i\}^\{\(\\ell\)\}\\in\\mathbb\{R\}^\{D\}denote its last\-token hidden state at sampled layerℓ\\ell\. We first standardize𝐡i\(ℓ\)\\mathbf\{h\}\_\{i\}^\{\(\\ell\)\}elementwise across theDDhidden dimensions using the bank mean𝝁bank\(ℓ\)\\boldsymbol\{\\mu\}\_\{\\text\{bank\}\}^\{\(\\ell\)\}and standard deviation𝝈bank\(ℓ\)\\boldsymbol\{\\sigma\}\_\{\\text\{bank\}\}^\{\(\\ell\)\}computed over all2n2nbank examples at layerℓ\\ell:
𝝁bank\(ℓ\)=12n∑i=12n𝐡i\(ℓ\),𝝈bank\(ℓ\)=12n∑i=12n\(𝐡i\(ℓ\)−𝝁bank\(ℓ\)\)2,𝐡~i\(ℓ\)=𝐡i\(ℓ\)−𝝁bank\(ℓ\)𝝈bank\(ℓ\)\.\\boldsymbol\{\\mu\}\_\{\\text\{bank\}\}^\{\(\\ell\)\}=\\frac\{1\}\{2n\}\\sum\_\{i=1\}^\{2n\}\\mathbf\{h\}\_\{i\}^\{\(\\ell\)\},\\quad\\boldsymbol\{\\sigma\}\_\{\\text\{bank\}\}^\{\(\\ell\)\}=\\sqrt\{\\frac\{1\}\{2n\}\\sum\_\{i=1\}^\{2n\}\\left\(\\mathbf\{h\}\_\{i\}^\{\(\\ell\)\}\-\\boldsymbol\{\\mu\}\_\{\\text\{bank\}\}^\{\(\\ell\)\}\\right\)^\{2\}\},\\quad\\tilde\{\\mathbf\{h\}\}\_\{i\}^\{\(\\ell\)\}=\\frac\{\\mathbf\{h\}\_\{i\}^\{\(\\ell\)\}\-\\boldsymbol\{\\mu\}\_\{\\text\{bank\}\}^\{\(\\ell\)\}\}\{\\boldsymbol\{\\sigma\}\_\{\\text\{bank\}\}^\{\(\\ell\)\}\}\.\(1\)Each standardized bank vector is then divided by its L2 norm to obtain a unit vector𝐳^i\(ℓ\)=𝐡~i\(ℓ\)/‖𝐡~i\(ℓ\)‖2\\hat\{\\mathbf\{z\}\}\_\{i\}^\{\(\\ell\)\}=\\tilde\{\\mathbf\{h\}\}\_\{i\}^\{\(\\ell\)\}/\\\|\\tilde\{\\mathbf\{h\}\}\_\{i\}^\{\(\\ell\)\}\\\|\_\{2\}\.
Let𝝁0\(ℓ\)\\boldsymbol\{\\mu\}\_\{0\}^\{\(\\ell\)\}and𝝁1\(ℓ\)\\boldsymbol\{\\mu\}\_\{1\}^\{\(\\ell\)\}denote the mean standardized activation vectors of the negative \(C0C\_\{0\}\) and positive \(C1C\_\{1\}\) bank subsets at layerℓ\\ell\. To measure how well layerℓ\\ellseparates the two classes, we compute its Fisher discriminant ratioJℓJ\_\{\\ell\}:
Jℓ=BℓWℓ,Bℓ=‖𝝁1\(ℓ\)−𝝁0\(ℓ\)‖22,Wℓ=∑c∈\{0,1\}1\|Cc\|∑i∈Cc‖𝐡~i\(ℓ\)−𝝁c\(ℓ\)‖22,J\_\{\\ell\}=\\frac\{B\_\{\\ell\}\}\{W\_\{\\ell\}\},\\quad B\_\{\\ell\}=\\\|\\boldsymbol\{\\mu\}\_\{1\}^\{\(\\ell\)\}\-\\boldsymbol\{\\mu\}\_\{0\}^\{\(\\ell\)\}\\\|\_\{2\}^\{2\},\\quad W\_\{\\ell\}=\\sum\_\{c\\in\\\{0,1\\\}\}\\frac\{1\}\{\|C\_\{c\}\|\}\\sum\_\{i\\in C\_\{c\}\}\\\|\\tilde\{\\mathbf\{h\}\}\_\{i\}^\{\(\\ell\)\}\-\\boldsymbol\{\\mu\}\_\{c\}^\{\(\\ell\)\}\\\|\_\{2\}^\{2\},\(2\)and assign layer weights via a softmax across theMMsampled layers,αℓ=exp\(Jℓ\)/∑m=1Mexp\(Jm\)\\alpha\_\{\\ell\}=\\exp\(J\_\{\\ell\}\)/\\sum\_\{m=1\}^\{M\}\\exp\(J\_\{m\}\)\.
At inference time, for a new inputx~\\tilde\{x\}with layer\-ℓ\\elllast\-token activation𝐪\(ℓ\)∈ℝD\\mathbf\{q\}^\{\(\\ell\)\}\\in\\mathbb\{R\}^\{D\}, we apply the same bank standardization𝐪~\(ℓ\)=\(𝐪\(ℓ\)−𝝁bank\(ℓ\)\)/𝝈bank\(ℓ\)\\tilde\{\\mathbf\{q\}\}^\{\(\\ell\)\}=\(\\mathbf\{q\}^\{\(\\ell\)\}\-\\boldsymbol\{\\mu\}\_\{\\text\{bank\}\}^\{\(\\ell\)\}\)/\\boldsymbol\{\\sigma\}\_\{\\text\{bank\}\}^\{\(\\ell\)\}and divide by its L2 norm to obtain the unit query vector𝐪^\(ℓ\)=𝐪~\(ℓ\)/‖𝐪~\(ℓ\)‖2\\hat\{\\mathbf\{q\}\}^\{\(\\ell\)\}=\\tilde\{\\mathbf\{q\}\}^\{\(\\ell\)\}/\\\|\\tilde\{\\mathbf\{q\}\}^\{\(\\ell\)\}\\\|\_\{2\}\. We then compute the cosine distancedi\(ℓ\)=1−\(𝐳^i\(ℓ\)\)⊤𝐪^\(ℓ\)d\_\{i\}^\{\(\\ell\)\}=1\-\(\\hat\{\\mathbf\{z\}\}\_\{i\}^\{\(\\ell\)\}\)^\{\\top\}\\hat\{\\mathbf\{q\}\}^\{\(\\ell\)\}to each bank examplei∈\{1,…,2n\}i\\in\\\{1,\\dots,2n\\\}\. Let𝒩k\(ℓ\)\(x\)⊂\{1,…,2n\}\\mathcal\{N\}\_\{k\}^\{\(\\ell\)\}\(x\)\\subset\\\{1,\\dots,2n\\\}denote the indices of thekkbank examples with the smallest cosine distancesdi\(ℓ\)d\_\{i\}^\{\(\\ell\)\}, with inverse\-distance weightswi\(ℓ\)=1/di\(ℓ\)w\_\{i\}^\{\(\\ell\)\}=1/d\_\{i\}^\{\(\\ell\)\}:
sℓ\(x\)=∑i∈𝒩k\(ℓ\)\(x\)wi\(ℓ\)yi∑i∈𝒩k\(ℓ\)\(x\)wi\(ℓ\),sact\(x\)=∑ℓ=1Mαℓsℓ\(x\)\.s\_\{\\ell\}\(x\)=\\frac\{\\sum\_\{i\\in\\mathcal\{N\}\_\{k\}^\{\(\\ell\)\}\(x\)\}w\_\{i\}^\{\(\\ell\)\}y\_\{i\}\}\{\\sum\_\{i\\in\\mathcal\{N\}\_\{k\}^\{\(\\ell\)\}\(x\)\}w\_\{i\}^\{\(\\ell\)\}\},\\quad s\_\{\\text\{act\}\}\(x\)=\\sum\_\{\\ell=1\}^\{M\}\\alpha\_\{\\ell\}s\_\{\\ell\}\(x\)\.\(3\)Intuitively,sact\(x\)∈\[0,1\]s\_\{\\text\{act\}\}\(x\)\\in\[0,1\]aggregates evidence across theMMlayers into a single risk score: within each layerℓ\\ell, thekknearest bank neighbors vote on the query’s class with weights inversely proportional to their distance from the query \(so closer neighbors carry more weight\), and the layer scoressℓ\(x\)s\_\{\\ell\}\(x\)are weighted byαℓ\\alpha\_\{\\ell\}so that layers with stronger class separation have greater influence\.
#### Embedding Branch and Fused Ensemble \(kNNGuard FE\)
The embedding branch \(Embedding\-kNN\) runs the same single\-spacekkNN scoring using vectors from an external sentence encoder rather than LLM hidden states\. Specifically, we encode the raw reference prompts\{xi\}i=12n\\\{x\_\{i\}\\\}\_\{i=1\}^\{2n\}\(without the LLM system prompt\) into L2\-normalized vectors inℝN\\mathbb\{R\}^\{N\}to form the embedding reference bank\. At inference time, a test queryxxis encoded with the same sentence encoder and scored against itskknearest cosine\-distance neighbors in this embedding bank using inverse\-distance weights \(as insℓ\(x\)s\_\{\\ell\}\(x\)in Equation \(3\), without layer weighting since the encoder outputs a single vector per input\) to obtainsemb\(x\)s\_\{\\text\{emb\}\}\(x\)\.
The*Fused Ensemble*\(kNNGuard FE\) combinessact\(x\)s\_\{\\text\{act\}\}\(x\)andsemb\(x\)s\_\{\\text\{emb\}\}\(x\)using each branch’s distance from the midpoint,cb\(x\)=\|sb\(x\)−0\.5\|c\_\{b\}\(x\)=\|s\_\{b\}\(x\)\-0\.5\|forb∈\{act,emb\}b\\in\\\{\\text\{act\},\\text\{emb\}\\\}, and the confidence gapΔ\(x\)=\|cact\(x\)−cemb\(x\)\|\\Delta\(x\)=\|c\_\{\\text\{act\}\}\(x\)\-c\_\{\\text\{emb\}\}\(x\)\|\. When one branch is more confident by at least a marginγ\\gamma, Winner\-Takes\-All selects that branch; otherwise the two scores are blended proportionally:
sFE\(x\)=\{sargmaxbcb\(x\)\(x\),ifΔ\(x\)\>γ,cact\(x\)sact\(x\)\+cemb\(x\)semb\(x\)cact\(x\)\+cemb\(x\),otherwise\.s\_\{\\text\{FE\}\}\(x\)=\\begin\{cases\}s\_\{\\arg\\max\_\{b\}c\_\{b\}\(x\)\}\(x\),&\\text\{if \}\\Delta\(x\)\>\\gamma,\\\\ \\frac\{c\_\{\\text\{act\}\}\(x\)s\_\{\\text\{act\}\}\(x\)\+c\_\{\\text\{emb\}\}\(x\)s\_\{\\text\{emb\}\}\(x\)\}\{c\_\{\\text\{act\}\}\(x\)\+c\_\{\\text\{emb\}\}\(x\)\},&\\text\{otherwise\}\.\\end\{cases\}\(4\)Rather than choosing an arbitrary decision threshold to convertsact\(x\)s\_\{\\text\{act\}\}\(x\),semb\(x\)s\_\{\\text\{emb\}\}\(x\), andsFE\(x\)s\_\{\\text\{FE\}\}\(x\)into binary predictions, we evaluate the continuous risk scores directly across all operating points using the Area Under the Receiver Operating Characteristic curve \(AUROC\)\. Throughout our experiments, we follow the hyperparameter settings of Abdelfattah et al\.\[[1](https://arxiv.org/html/2611.27084#bib.bib1)\]\(n=50n=50examples per class per bank,M=9M=9evenly spaced layers,k=13k=13nearest neighbors, and confidence marginγ=0\.1\\gamma=0\.1\), usingall\-MiniLM\-L6\-v2\(N=384N=384\) when replicating the standardkNNGuardbaseline\.
### 2\.3Target Models and Guardrail Benchmarks
We evaluate two 4B open\-weight models in nativeBF16precision without weight quantization:Qwen/Qwen3\.5\-4B\[[31](https://arxiv.org/html/2611.27084#bib.bib24)\]\(L=32L=32layers, hidden dimensionD=2560D=2560\) andgoogle/gemma\-4\-E4B\-it\[[29](https://arxiv.org/html/2611.27084#bib.bib25)\]\(L=42L=42layers,D=2560D=2560\)\. We evaluate two guardrail benchmarks:
- •Domain 1 \(Content Harm Moderation\):nvidia/Aegis\-AI\-Content\-Safety\-Dataset\-2\.0\[[9](https://arxiv.org/html/2611.27084#bib.bib5)\], which was also evaluated inkNNGuard\[[1](https://arxiv.org/html/2611.27084#bib.bib1)\]and covers hate speech, violence, self\-harm, harassment, and regulated advice\.
- •Domain 2 \(RAG Hallucination Detection\):PatronusAI/HaluBench\[[24](https://arxiv.org/html/2611.27084#bib.bib4)\], consisting of\(passage,question,answer\)\(\\texttt\{passage\},\\texttt\{question\},\\texttt\{answer\}\)triplets drawn from six QA and hallucination benchmarks \(HaluEval\[[17](https://arxiv.org/html/2611.27084#bib.bib19)\],DROP\[[7](https://arxiv.org/html/2611.27084#bib.bib21)\],PubMedQA\[[13](https://arxiv.org/html/2611.27084#bib.bib20)\],RAGTruth\[[22](https://arxiv.org/html/2611.27084#bib.bib17)\],FinanceBench\[[12](https://arxiv.org/html/2611.27084#bib.bib18)\], andCOVID\-QA\[[21](https://arxiv.org/html/2611.27084#bib.bib22)\]\), where each triplet is labeledPASS\(y=0y=0, the answer is supported by the passage\) orFAIL\(y=1y=1, the answer contains unsupported or contradicted claims\)\.
For each benchmark, both the reference banks and the held\-out evaluation buckets \(Short:≤256\\leq 256tokens;Medium:257257–10001000tokens;Long:\>1000\>1000tokens\) are drawn from the benchmark’s examples using strict disjoint partitioning:
- •InAegis\-2\.0, which provides officialtrain,validation, andtestsplits, we sample all reference banks strictly from thetrainsplit and build the evaluation buckets from thetestandvalidationsplits \(plus held\-out\>1000\>1000\-tokentrainprompts not selected for any bank\)\. To guard against near\-duplicate prompts across splits, we also remove any evaluation prompt that matches a bank prompt exactly or shares its first200200characters\.
- •InHaluBench, which is released as a single split where multiple questions often share the same source passage, we partition the dataset by unique source passage: we sample the short reference bank \(≤256\\leq 256tokens\) from100100unique passages inHaluEvaland the long reference bank \(\>512\>512tokens\) from100100unique passages inPubMedQAandRAGTruth, and then exclude every example inHaluBenchthat shares a passage or question with either bank before forming the three evaluation buckets\.
## 3Empirical Audit: Diagnosing Long\-Context Degradation
We first build the standard short\-context reference banksℬshortsafety\\mathcal\{B\}\_\{\\text\{short\}\}^\{\\text\{safety\}\}andℬshorthalu\\mathcal\{B\}\_\{\\text\{short\}\}^\{\\text\{halu\}\}\(n=50n=50per class,≤256\\leq 256tokens\) and evaluate them on held\-outShort\(≤256\\leq 256tokens,N=300N=300\),Medium\(257257–10001000tokens,N=260N=260–300300\), andLong\(\>1000\>1000tokens, up to64596459tokens,N=248N=248–300300\) test buckets\. Throughout our evaluation, we report the LLM activation branch \(kNNGuard LE\) alongside the Fused Ensemble \(kNNGuard FE\) for two reasons: \(1\) on content moderation \(Aegis\-2\.0\), inspectingFEalone masks a severe long\-context collapse in the LLM activation branch because the256256\-token prefix embedding partially buffers the fused score, and \(2\) on RAG hallucination detection \(HaluBench\), we find that the embedding branch actively harms the fused ensemble once the reference bank is adapted, makingkNNGuard LEalone stronger thankNNGuard FE\.
Table 1:Length\-segmented AUROC of standardkNNGuard LEandkNNGuard FE\(built from short≤256\\leq 256\-token banksℬshort\(d\)\\mathcal\{B\}\_\{\\text\{short\}\}^\{\(d\)\}\) across native prompt\-length regimes\.Figure 1:Long\-context AUROC degradation \(averaged acrossQwen3\.5\-4BandGemma\-4\-E4B\-it\) acrossShort\(≤256\\leq 256\),Medium\(257257–10001000\), andLong\(\>1000\>1000\) test\-query length buckets when using the standard short reference bankℬshort\(d\)\\mathcal\{B\}\_\{\\text\{short\}\}^\{\(d\)\}, forkNNGuard LE\(LLM hidden states\),Embedding\-kNN\(MiniLM\-256\), and fusedkNNGuard FE\.#### Empirical Collapse Across Length Regimes
As shown in Table[1](https://arxiv.org/html/2611.27084#S3.T1)and Figure[1](https://arxiv.org/html/2611.27084#S3.F1), standardkNNGuardachieves strong ranking accuracy when test inputs match the short length of the reference bank\. OnShort\(≤256\\leq 256tokens\) inputs,kNNGuard FEreaches0\.8100\.810AUROC onQwen3\.5\-4Band0\.7460\.746AUROC onGemma\-4\-E4B\-itfor Content Safety, and0\.9950\.995AUROC and0\.9920\.992AUROC onHaluBench\.
However, when the same short bankℬshort\(d\)\\mathcal\{B\}\_\{\\text\{short\}\}^\{\(d\)\}is used to scoreMediumandLonginputs, the LLM activation branch \(kNNGuard LE\) degrades severely:
- •OnContent Safety \(Aegis\-2\.0\),kNNGuard LEAUROC falls from0\.777→0\.736→0\.5870\.777\\to 0\.736\\to 0\.587onQwen3\.5\-4Band from0\.706→0\.628→0\.5210\.706\\to 0\.628\\to 0\.521\(near random chance\) onGemma\-4\-E4B\-it\. By contrast, theMiniLM\-256embedding branch retains high AUROC on long safety prompts \(0\.8110\.811and0\.7580\.758\), partially buffering the fused ensemble \(FEAUROC drops only from0\.810→0\.7550\.810\\to 0\.755onQwen3\.5\-4Band0\.746→0\.6870\.746\\to 0\.687onGemma\-4\-E4B\-it\)\. Direct inspection of per\-chunk embeddings onAegis\-2\.0 Longexplains why: harmful topic signal is present across the entire prompt \(the first, middle, and final256256\-token chunks achieve0\.8270\.827,0\.8340\.834, and0\.8080\.808embedding AUROC onQwen3\.5\-4B, and0\.8530\.853,0\.8750\.875, and0\.8470\.847onGemma\-4\-E4B\-it\), and becauseMiniLM\-256truncates every long test prompt to its first256256tokens, it compares a256256\-token query prefix against a≤256\\leq 256\-token bank without suffering from a sequence\-length mismatch\.
- •OnRAG Hallucination Detection \(HaluBench\), whereMiniLM\-256performs near random chance across all lengths \(0\.4600\.460–0\.5580\.558AUROC, including0\.5130\.513–0\.5230\.523onShortinputs where no truncation occurs\), the collapse of the LLM activation branch directly pulls down the fused ensemble:kNNGuard FEAUROC falls from0\.995→0\.724→0\.5980\.995\\to 0\.724\\to 0\.598onQwen3\.5\-4Band from0\.992→0\.692→0\.5170\.992\\to 0\.692\\to 0\.517onGemma\-4\-E4B\-it\.
#### Why Both Branches Fail on Long Inputs
Inspecting the two branches separately explains the breakdown:
1. 1\.LLM Hidden\-State Length Shift:Standardizing long queries with the mean and standard deviation ofℬshort\(d\)\\mathcal\{B\}\_\{\\text\{short\}\}^\{\(d\)\}introduces a large representation offset asTTgrows\[[14](https://arxiv.org/html/2611.27084#bib.bib2)\]\. OnHaluBench, the average layer\-wise cosine similarity between the short bank’s negative mean vector𝝁0short\\boldsymbol\{\\mu\}\_\{0\}^\{\\text\{short\}\}and the mean vector of held\-out negative queries in each length bucket drops from0\.8400\.840\(Short\) to0\.1790\.179\(Medium\) and0\.2550\.255\(Long\) onQwen3\.5\-4B, and from0\.9100\.910\(Short\) to0\.0630\.063\(Medium\) and0\.2480\.248\(Long\) onGemma\-4\-E4B\-it\. At the same time, the meank=13k=13nearest\-neighbor cosine distance increases from0\.706→0\.8690\.706\\to 0\.869\(Qwen3\.5\-4B\) and0\.676→0\.8420\.676\\to 0\.842\(Gemma\-4\-E4B\-it\)\.
2. 2\.MiniLMTruncation Blindness:EachHaluBenchprompt is structured as: Passage:⟨retrieved context⟩Question:⟨query⟩Answer:⟨response⟩,\\texttt\{Passage: \}\\langle\\text\{retrieved context\}\\rangle\\quad\\texttt\{Question: \}\\langle\\text\{query\}\\rangle\\quad\\texttt\{Answer: \}\\langle\\text\{response\}\\rangle,\(5\)placing the question and answer after the retrieved passage\. The token index whereQuestion:begins exceedsMiniLM’s256256\-token limit on61\.0%61\.0\\%\(Qwen3\.5\-4B\) to66\.0%66\.0\\%\(Gemma\-4\-E4B\-it\) ofMediuminputs and100\.0%\\mathbf\{100\.0\\%\}ofLonginputs, cutting off the question and answer before encoding \(MiniLM\-256Long AUROC is0\.4600\.460–0\.4990\.499\)\.
## 4Training\-Free Long\-Context Adaptations
To address these failure mechanisms without model fine\-tuning, we evaluate three modular, training\-free adaptations:
### 4\.1Length\-Routed Dual Reference Banks
Because last\-token hidden states shift systematically as sequence length increases, forcing a single short reference bankℬshort\(d\)\\mathcal\{B\}\_\{\\text\{short\}\}^\{\(d\)\}\(≤256\\leq 256tokens\) to score long queries distorts both the per\-layer standardization step and nearest\-neighbor retrieval\. To include long\-context examples in the reference bank without collecting more thann=50n=50examples per class per bank, we compare two strategies:
- •Mixed\-Length Bank \(ℬmixed\(d\)\\mathcal\{B\}\_\{\\text\{mixed\}\}^\{\(d\)\}\):A single100100\-example reference bank combining2525short \(≤256\\leq 256tokens\) and2525long \(\>512\>512tokens\) examples per class\. While simple, pooling short and long prompts into a single bank computes a single standardization mean𝝁bank\(ℓ\)\\boldsymbol\{\\mu\}\_\{\\text\{bank\}\}^\{\(\\ell\)\}and standard deviation𝝈bank\(ℓ\)\\boldsymbol\{\\sigma\}\_\{\\text\{bank\}\}^\{\(\\ell\)\}across two shifted activation clusters, blurring class separation on short inputs\.
- •Length\-Routed Dual Bank \(ℬshort\(d\),ℬlong\(d\)\\mathcal\{B\}\_\{\\text\{short\}\}^\{\(d\)\},\\mathcal\{B\}\_\{\\text\{long\}\}^\{\(d\)\}\):Alongside the short bankℬshort\(d\)\\mathcal\{B\}\_\{\\text\{short\}\}^\{\(d\)\}\(n=50n=50per class,≤256\\leq 256tokens\), we pre\-compute a separateLong\-Context Reference Bankℬlong\(d\)\\mathcal\{B\}\_\{\\text\{long\}\}^\{\(d\)\}\(n=50n=50per class sampled from\>512\>512\-token training prompts inAegis\-2\.0and\>512\>512\-token unique passages inHaluBench\)\. Each bank maintains its own standardization parameters\(𝝁bank\(ℓ\),𝝈bank\(ℓ\)\)\(\\boldsymbol\{\\mu\}\_\{\\text\{bank\}\}^\{\(\\ell\)\},\\boldsymbol\{\\sigma\}\_\{\\text\{bank\}\}^\{\(\\ell\)\}\)and layer weightsαℓshort\\alpha\_\{\\ell\}^\{\\text\{short\}\}vs\.αℓlong\\alpha\_\{\\ell\}^\{\\text\{long\}\}\. At inference time, as soon as the query is tokenized \(T=\|input\_ids\|T=\|\\texttt\{input\\\_ids\}\|\), we route the query to the length\-matched bank: ℬactive\(d\)\(x\)=\{ℬshort\(d\),ifT≤256,ℬlong\(d\),ifT\>256\.\\mathcal\{B\}\_\{\\text\{active\}\}^\{\(d\)\}\(x\)=\\begin\{cases\}\\mathcal\{B\}\_\{\\text\{short\}\}^\{\(d\)\},&\\text\{if \}T\\leq 256,\\\\ \\mathcal\{B\}\_\{\\text\{long\}\}^\{\(d\)\},&\\text\{if \}T\>256\.\\end\{cases\}\(6\)
This routing adds no latency overhead, requires no extra forward passes, keeps the short and long activation distributions separate rather than averaging their statistics in a single bank, and preserves100%100\\%of short\-prompt performance\.
### 4\.2Long\-Context Embedding Replacement
To eliminateMiniLM’s256256\-token truncation blindness while maintaining a lightweight embedding branch, we replaceall\-MiniLM\-L6\-v2withQwen/Qwen3\-Embedding\-0\.6B\[[32](https://arxiv.org/html/2611.27084#bib.bib7)\], which produces10241024\-dimensional embeddings \(N=1024N=1024\) and supports up to3276832768tokens natively\. Because every prompt in our benchmarks fits well within this context window \(up to64596459tokens\), the embedding branch encodes the full prompt without truncation\.
### 4\.3Strided Window Pooling
Even when the reference bank is length\-matched \(ℬlong\(d\)\\mathcal\{B\}\_\{\\text\{long\}\}^\{\(d\)\}\) and both branches process allTTtokens, compressing a20002000\-to\-60006000token prompt into a single end\-of\-sequence vector dilutes localized unsafe statements or single\-sentence factual contradictions buried inside a long benign context\.
To recover localized signal without running multiple LLM forward passes, we score long prompts at a256256\-token granularity according to each branch’s attention mechanism:
- •LLM Activation Branch \(kNNGuard LE\):Because decoder\-only LLMs use causal \(left\-to\-right\) self\-attention, a single prefill pass over the fullTT\-token prompt already computes intermediate representations at every token position\. We read out the hidden states at every256256\-th token \(t∈\{256,512,…,T\}t\\in\\\{256,512,\\dots,T\\\}, i\.e\., the last token of each cumulative256256\-token prefix\) across theM=9M=9selected layers and score each position againstℬactive\(d\)\(x\)\\mathcal\{B\}\_\{\\text\{active\}\}^\{\(d\)\}\(x\)\.
- •Embedding Branch \(Embedding\-kNN\):Because the sentence encoder \(Qwen3\-Embedding\-0\.6B\) outputs a single vector per input text, we split the prompt into sliding windows of roughly256256tokens with a6464\-token overlap \(so that statements straddling a boundary are not cut in half\) and score each chunk against the embedding bank\. OnHaluBench, we apply this sliding window to the retrievedPassageand append theQuestionandAnswerto every passage chunk \(which easily fits withinQwen3\-Embedding\-0\.6B’s context window\) so that each chunk embedding includes both the passage segment and the answer being verified\.
For both branches, we aggregate the window\-level risk scores into a single branch score \(sact\(x\)s\_\{\\text\{act\}\}\(x\)andsemb\(x\)s\_\{\\text\{emb\}\}\(x\)\) usingTop\-2 Meanpooling \(averaging the two highest\-scoring windows, or taking the single window score whenW=1W=1\)\. Averaging the top two windows captures localized high\-risk segments while being less sensitive to single\-window outliers than taking the raw maximum across windows; the resulting branch scoressact\(x\)s\_\{\\text\{act\}\}\(x\)andsemb\(x\)s\_\{\\text\{emb\}\}\(x\)are then combined via Equation \(4\)\.
## 5Experimental Results and Ablation Study
Table[2](https://arxiv.org/html/2611.27084#S5.T2)\(with Figure[2](https://arxiv.org/html/2611.27084#S5.F2)\) and Table[3](https://arxiv.org/html/2611.27084#S5.T3)report our progressive ablation study on theLong\(\>1000\>1000\-token\) andMedium\(257257–10001000\-token\) evaluation buckets across both domains, reportingkNNGuard LE,Embedding\-kNN, andkNNGuard FEAUROC with95%95\\%bootstrap confidence intervals\.
Table 2:Progressive ablation study onLong\(\>1000\>1000\-token\) inputs averaged acrossQwen3\.5\-4BandGemma\-4\-E4B\-it\.Table 3:Progressive ablation study onMedium\(257257–10001000\-token\) inputs averaged acrossQwen3\.5\-4BandGemma\-4\-E4B\-it\.Figure 2:Long\-context \(\>1000\>1000tokens\) AUROC and95%95\\%bootstrap confidence intervals \(averaged acrossQwen3\.5\-4BandGemma\-4\-E4B\-it\) ofkNNGuard LE\(LLM hidden states\) andkNNGuard FE\(fused ensemble\) across training\-free adaptations on Content Safety \(Aegis\-2\.0\) and RAG Hallucination \(HaluBench\)\.#### Finding 1: Length\-Matched Banks and Window Pooling Restore Long\-Context Safety Ranking
OnContent Safety \(Aegis\-2\.0\), each adaptation progressively improves ranking accuracy across both theLong\(Table[2](https://arxiv.org/html/2611.27084#S5.T2), Figure[2](https://arxiv.org/html/2611.27084#S5.F2)\) andMedium\(Table[3](https://arxiv.org/html/2611.27084#S5.T3)\) buckets without model fine\-tuning:
- •Reference\-Bank Adaptation:Replacing the short bank with aMixed\-Length Banksubstantially improves bothkNNGuard LEandkNNGuard FEon long and medium inputs, but slightly degrades short\-prompt AUROC \(0\.810→0\.7910\.810\\to 0\.791onQwen3\.5\-4Band0\.746→0\.7000\.746\\to 0\.700onGemma\-4\-E4B\-it\) because short and long activations are pooled into a single standardization distribution\. TheLength\-Routed Dual Bankavoids this tradeoff, achieving the highest fusedkNNGuard FEAUROC on bothLong\(Table[2](https://arxiv.org/html/2611.27084#S5.T2)\) andMedium\(Table[3](https://arxiv.org/html/2611.27084#S5.T3)\) safety prompts while preserving100%100\\%of short\-prompt performance\.
- •Full\-Sequence vs\. Windowed Pooling:In the\+ Qwen3\-Embedding\-0\.6Bconfiguration of Table[2](https://arxiv.org/html/2611.27084#S5.T2), encoding an entire\>1000\>1000\-token safety prompt into a single vector slightly reducesEmbedding\-kNNAUROC compared toMiniLM\-256’s256256\-token prefix, becauseMiniLM\-256truncates both the reference bank and test queries to the exact same256256\-token length whereas full\-sequenceQwen3\-Embedding\-0\.6Bcompares\>512\>512\-token bank prompts against10001000–64596459token test prompts compressed into one vector\. AddingStrided Window Pooling\(\+ Strided Window Poolingin Tables[2](https://arxiv.org/html/2611.27084#S5.T2)and[3](https://arxiv.org/html/2611.27084#S5.T3)\) resolves single\-vector dilution for both branches and delivers the largest gain for the LLM activation branch \(kNNGuard LEreaches its peak AUROC on bothLongandMediumsafety prompts\), withTop\-2 Meanoutperforming rawMaxpooling onLonginputs \(0\.8280\.828vs\.0\.8150\.815LEAUROC and0\.8530\.853vs\.0\.8340\.834FEAUROC\)\.
#### Finding 2: Why Hallucination Detection Diverges Between Embeddings and LLM Hidden States
ComparingHaluBenchagainstAegis\-2\.0in Tables[2](https://arxiv.org/html/2611.27084#S5.T2)and[3](https://arxiv.org/html/2611.27084#S5.T3)reveals a sharp contrast between the sentence\-embedding branch and the LLM hidden\-state branch:
- •Sentence\-EmbeddingkkNN Fails Across All Context Lengths on Hallucination Detection:WhileEmbedding\-kNNseparates safe and unsafe prompts effectively onAegis\-2\.0, it remains near random chance \(≈0\.47\\approx 0\.47–0\.550\.55AUROC\) across*every*length bucket and configuration onHaluBench\(Tables[2](https://arxiv.org/html/2611.27084#S5.T2)and[3](https://arxiv.org/html/2611.27084#S5.T3)\), even when256256\-token truncation is completely removed via full\-sequenceQwen3\-Embedding\-0\.6Bor QA\-anchored256256\-token chunking \(and even onShort≤256\\leq 256\-token prompts where no truncation occurs\)\. Detecting a hallucination depends on verifying logical consistency across tokens between theAnswerand thePassage, which is too fine\-grained to be captured bykkNN similarity over static sentence embeddings\. As a result, fusing the uninformative embedding branch withkNNGuard LEactively degradeskNNGuard FEonHaluBenchwheneverLEis above chance\.
- •LLM Hidden States \(kNNGuard LE\) Succeed on Short and Medium Passages but Dilute on\>1000\>1000\-Token Passages:Unlike the external sentence encoder, the LLM processes the verification system prompt via self\-attention across thePassage,Question, andAnswer\. Consequently,kkNN over the LLM’s final\-token hidden states \(kNNGuard LE\) achieves near\-perfect separation onShortinputs \(≤256\\leq 256tokens, Table[1](https://arxiv.org/html/2611.27084#S3.T1)\) and recovers strong accuracy onMediuminputs \(257257–10001000tokens\) once longer examples are included in the Mixed\-Length Bank \(LE AUROC=0\.853\\text\{LE AUROC\}=0\.853, Table[3](https://arxiv.org/html/2611.27084#S5.T3); the Mixed\-Length Bank outperforms the Dual Bank here because medium inputs span the257257–512512token transition between the short and long banks\)\. OnLong\(\>1000\>1000\-token\) passages \(Table[2](https://arxiv.org/html/2611.27084#S5.T2)\), however, theLength\-Routed Dual Bankyields only a modest improvement forkNNGuard LE\(0\.556→0\.6070\.556\\to 0\.607\), andStrided Window PoolingreducesLEAUROC \(0\.5620\.562\): because theAnswerbeing verified sits at the very end of the prompt \(Equation \(5\)\), intermediate LLM hidden states read out att=256,512,…t=256,512,\\dotsprecede theAnswerand cannot evaluate its consistency, while at the final tokent=Tt=T, compressing a multi\-thousand\-token passage into a single hidden\-state vector leaves too weak a signal forkkNN over100100reference vectors\.
## 6Discussion, Limitations, and Conclusion
#### Practical Deployment Recommendations
Our findings yield three practical guidelines for deploying training\-free activation guardrails:
1. 1\.Deploy a Length\-Routed Dual Bank by default:Maintaining a separate long\-context reference bank alongside the short bank is simple to deploy, adds no runtime overhead, and substantially improves medium\- and long\-context content moderation \(Tables[2](https://arxiv.org/html/2611.27084#S5.T2)and[3](https://arxiv.org/html/2611.27084#S5.T3)\) with no downsides on short prompts\.
2. 2\.Use Strided Window Pooling for long\-context content moderation:Sampling intermediate hidden states every256256tokens during the single prefill pass provides the strongest long\-context activation performance \(kNNGuard LE\) onAegis\-2\.0\(Table[2](https://arxiv.org/html/2611.27084#S5.T2)\) without requiring additional LLM forward passes\.
3. 3\.Disable Embedding\-kkNN for RAG hallucination detection:BecausekkNN over static sentence embeddings cannot verify logical consistency between an answer and a source passage, RAG hallucination guardrails should rely on the LLM activation branch \(kNNGuard LE\) with length\-matched banks rather than embedding fusion\.
#### Limitations and Conclusion
Our evaluation focuses on two 4B open\-weight model families \(Qwen3\.5\-4BandGemma\-4\-E4B\-it\) and two guardrail benchmarks up to6\.56\.5K tokens\.
While length\-routed dual banks and strided window pooling restore long\-context content moderation onAegis\-2\.0\(0\.8280\.828LEAUROC,0\.8860\.886FEAUROC\) and medium\-context hallucination detection onHaluBench\(0\.8240\.824–0\.8820\.882LEAUROC\), extending training\-freekkNN guardrails to multi\-thousand\-token financial and medical RAG verification will require representations that directly capture passage\-to\-answer consistency beyond static reference banks\.
## References
- \[1\]M\. Abdelfattah, H\. Nasiri, and P\. Garraghan\(2026\)KNNGuard: turning llm hidden activations into a training\-free configurable guardrail\.External Links:2607\.02072,[Link](https://arxiv.org/abs/2607.02072)Cited by:[§1](https://arxiv.org/html/2611.27084#S1.p3.1),[1st item](https://arxiv.org/html/2611.27084#S2.I1.i1.p1.1),[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx2.p2.1),[§2\.2](https://arxiv.org/html/2611.27084#S2.SS2.SSSx2.p2.2),[§2\.2](https://arxiv.org/html/2611.27084#S2.SS2.p1.1),[Abstract](https://arxiv.org/html/2611.27084#abstract1.1)\.
- \[2\]A\. Azaria and T\. Mitchell\(2023\)The internal state of an llm knows when it’s lying\.External Links:2304\.13734,[Link](https://arxiv.org/abs/2304.13734)Cited by:[§1](https://arxiv.org/html/2611.27084#S1.p3.1),[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx2.p1.1)\.
- \[3\]G\. Azov, O\. Rivlin, and G\. Shtar\(2026\)SALLIE: generation\-free hidden\-state detection of jailbreaks and prompt injections across text and vision\.External Links:2604\.06247,[Link](https://arxiv.org/abs/2604.06247)Cited by:[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx2.p2.1)\.
- \[4\]Y\. Bai, X\. Lv, J\. Zhang, H\. Lyu, J\. Tang, Z\. Huang, Z\. Du, X\. Liu, A\. Zeng, L\. Hou, Y\. Dong, J\. Tang, and J\. Li\(2023\)LongBench: a bilingual, multitask benchmark for long context understanding\.External Links:2308\.14508,[Link](https://arxiv.org/abs/2308.14508)Cited by:[§1](https://arxiv.org/html/2611.27084#S1.p1.1)\.
- \[5\]M\. Dassen, R\. Kotula, K\. Murray, A\. Yates, D\. Lawrie, E\. Kayi, J\. Mayfield, and K\. Duh\(2026\)FACTUM: mechanistic detection of citation hallucination in long\-form rag\.External Links:2601\.05866,[Link](https://arxiv.org/abs/2601.05866)Cited by:[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx2.p2.1)\.
- \[6\]J\. Dong, Y\. Liu, M\. Zhang, N\. Deng, P\. Xu, X\. Zhang, T\. Zhang, J\. Zhang, and H\. Qiu\(2026\)Your agentic llms secretly encode indirect prompt\-injection exposure in hidden states\.External Links:2608\.02657,[Link](https://arxiv.org/abs/2608.02657)Cited by:[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx2.p1.1)\.
- \[7\]D\. Dua, Y\. Wang, P\. Dasigi, G\. Stanovsky, S\. Singh, and M\. Gardner\(2019\)DROP: a reading comprehension benchmark requiring discrete reasoning over paragraphs\.External Links:1903\.00161,[Link](https://arxiv.org/abs/1903.00161)Cited by:[2nd item](https://arxiv.org/html/2611.27084#S2.I1.i2.p1.1)\.
- \[8\]Z\. Dubanowska, M\. Żelaszczyk, M\. Brzozowski, P\. Mandica, and M\. Karpowicz\(2025\)Representation\-based broad hallucination detectors fail to generalize out of distribution\.External Links:2509\.19372,[Link](https://arxiv.org/abs/2509.19372)Cited by:[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx2.p2.1)\.
- \[9\]S\. Ghosh, P\. Varshney, M\. N\. Sreedhar, A\. Padmakumar, T\. Rebedea, J\. R\. Varghese, and C\. Parisien\(2025\)Aegis2\.0: a diverse ai safety dataset and risks taxonomy for alignment of llm guardrails\.External Links:2501\.09004,[Link](https://arxiv.org/abs/2501.09004)Cited by:[§1](https://arxiv.org/html/2611.27084#S1.p2.1),[§1](https://arxiv.org/html/2611.27084#S1.p5.1),[1st item](https://arxiv.org/html/2611.27084#S2.I1.i1.p1.1),[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx1.p1.1)\.
- \[10\]P\. Han, C\. Qian, X\. Chen, Y\. Zhang, H\. Ji, and D\. Zhang\(2025\)SafeSwitch: steering unsafe llm behavior via internal activation signals\.External Links:2502\.01042,[Link](https://arxiv.org/abs/2502.01042)Cited by:[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx2.p1.1)\.
- \[11\]O\. Honovich, R\. Aharoni, J\. Herzig, H\. Taitelbaum, D\. Kukliansy, V\. Cohen, T\. Scialom, I\. Szpektor, A\. Hassidim, and Y\. Matias\(2022\)TRUE: re\-evaluating factual consistency evaluation\.External Links:2204\.04991,[Link](https://arxiv.org/abs/2204.04991)Cited by:[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx1.p2.1)\.
- \[12\]P\. Islam, A\. Kannappan, D\. Kiela, R\. Qian, N\. Scherrer, and B\. Vidgen\(2023\)FinanceBench: a new benchmark for financial question answering\.External Links:2311\.11944,[Link](https://arxiv.org/abs/2311.11944)Cited by:[2nd item](https://arxiv.org/html/2611.27084#S2.I1.i2.p1.1)\.
- \[13\]Q\. Jin, B\. Dhingra, Z\. Liu, W\. W\. Cohen, and X\. Lu\(2019\)PubMedQA: a dataset for biomedical research question answering\.External Links:1909\.06146,[Link](https://arxiv.org/abs/1909.06146)Cited by:[2nd item](https://arxiv.org/html/2611.27084#S2.I1.i2.p1.1)\.
- \[14\]K\. Kale and S\. Vishwanath\(2026\)Prompt\-injection probes learn the conversation, not just the injection\.External Links:2610\.18408,[Link](https://arxiv.org/abs/2610.18408)Cited by:[item 1](https://arxiv.org/html/2611.27084#S1.I1.i1.p1.1),[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx2.p2.1),[item 1](https://arxiv.org/html/2611.27084#S3.I2.i1.p1.1),[Abstract](https://arxiv.org/html/2611.27084#abstract1.2)\.
- \[15\]U\. Khandelwal, O\. Levy, D\. Jurafsky, L\. Zettlemoyer, and M\. Lewis\(2019\)Generalization through memorization: nearest neighbor language models\.External Links:1911\.00172,[Link](https://arxiv.org/abs/1911.00172)Cited by:[§1](https://arxiv.org/html/2611.27084#S1.p3.1),[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx2.p2.1)\.
- \[16\]P\. Lewis, E\. Perez, A\. Piktus, F\. Petroni, V\. Karpukhin, N\. Goyal, H\. Küttler, M\. Lewis, W\. Yih, T\. Rocktäschel, S\. Riedel, and D\. Kiela\(2020\)Retrieval\-augmented generation for knowledge\-intensive nlp tasks\.External Links:2005\.11401,[Link](https://arxiv.org/abs/2005.11401)Cited by:[§1](https://arxiv.org/html/2611.27084#S1.p1.1)\.
- \[17\]J\. Li, X\. Cheng, W\. X\. Zhao, J\. Nie, and J\. Wen\(2023\)HaluEval: a large\-scale hallucination evaluation benchmark for large language models\.External Links:2305\.11747,[Link](https://arxiv.org/abs/2305.11747)Cited by:[2nd item](https://arxiv.org/html/2611.27084#S2.I1.i2.p1.1)\.
- \[18\]N\. F\. Liu, K\. Lin, J\. Hewitt, A\. Paranjape, M\. Bevilacqua, F\. Petroni, and P\. Liang\(2023\)Lost in the middle: how language models use long contexts\.External Links:2307\.03172,[Link](https://arxiv.org/abs/2307.03172)Cited by:[item 3](https://arxiv.org/html/2611.27084#S1.I1.i3.p1.1)\.
- \[19\]S\. Marks and M\. Tegmark\(2023\)The geometry of truth: emergent linear structure in large language model representations of true/false datasets\.External Links:2310\.06824,[Link](https://arxiv.org/abs/2310.06824)Cited by:[§1](https://arxiv.org/html/2611.27084#S1.p3.1),[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx2.p1.1)\.
- \[20\]Meta AI\(2025\)Llama guard 4 \(12b\): native multimodal safety classifier\.Note:[https://huggingface\.co/meta\-llama/Llama\-Guard\-4\-12B](https://huggingface.co/meta-llama/Llama-Guard-4-12B)External Links:[Link](https://huggingface.co/meta-llama/Llama-Guard-4-12B)Cited by:[§1](https://arxiv.org/html/2611.27084#S1.p2.1),[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx1.p1.1)\.
- \[21\]T\. Möller, A\. Reina, R\. Jayakumar, and M\. Pietsch\(2020\)COVID\-qa: a question answering dataset for covid\-19\.InProceedings of the 1st Workshop on NLP for COVID\-19 at ACL 2020,External Links:[Link](https://aclanthology.org/2020.nlpcovid19-acl.18/)Cited by:[2nd item](https://arxiv.org/html/2611.27084#S2.I1.i2.p1.1)\.
- \[22\]C\. Niu, Y\. Wu, J\. Zhu, S\. Xu, K\. Shum, R\. Zhong, J\. Song, and T\. Zhang\(2023\)RAGTruth: a hallucination corpus for developing trustworthy retrieval\-augmented language models\.External Links:2401\.00396,[Link](https://arxiv.org/abs/2401.00396)Cited by:[2nd item](https://arxiv.org/html/2611.27084#S2.I1.i2.p1.1)\.
- \[23\]I\. Padhi, M\. Nagireddy, G\. Cornacchia, S\. Chaudhury, T\. Pedapati, P\. Dognin, K\. Murugesan, E\. Miehling,et al\.\(2024\)Granite guardian\.External Links:2412\.07724,[Link](https://arxiv.org/abs/2412.07724)Cited by:[§1](https://arxiv.org/html/2611.27084#S1.p2.1),[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx1.p1.1),[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx1.p2.1)\.
- \[24\]S\. S\. Ravi, B\. Mielczarek, A\. Kannappan, D\. Kiela, and R\. Qian\(2024\)Lynx: an open source hallucination evaluation model\.External Links:2407\.08488,[Link](https://arxiv.org/abs/2407.08488)Cited by:[§1](https://arxiv.org/html/2611.27084#S1.p2.1),[§1](https://arxiv.org/html/2611.27084#S1.p5.1),[2nd item](https://arxiv.org/html/2611.27084#S2.I1.i2.p1.1),[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx1.p2.1)\.
- \[25\]T\. Rebedea, R\. Dinu, M\. Sreedhar, C\. Parisien, and J\. Cohen\(2023\)NeMo guardrails: a toolkit for controllable and safe llm applications with programmable rails\.External Links:2310\.10501,[Link](https://arxiv.org/abs/2310.10501)Cited by:[§1](https://arxiv.org/html/2611.27084#S1.p1.1),[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx1.p1.1)\.
- \[26\]N\. Reimers and I\. Gurevych\(2019\)Sentence\-bert: sentence embeddings using siamese bert\-networks\.InProceedings of the 2019 Conference on Empirical Methods in Natural Language Processing \(EMNLP\),External Links:[Link](https://arxiv.org/abs/1908.10084)Cited by:[§1](https://arxiv.org/html/2611.27084#S1.p4.1)\.
- \[27\]M\. N\. Sreedhar, T\. Rebedea, S\. Ghosh, J\. Zeng, and C\. Parisien\(2024\)CantTalkAboutThis: aligning language models to stay on topic in dialogues\.External Links:2404\.03820,[Link](https://arxiv.org/abs/2404.03820)Cited by:[§1](https://arxiv.org/html/2611.27084#S1.p2.1),[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx1.p1.1)\.
- \[28\]J\. Su, Y\. Lu, S\. Pan, A\. Murtadha, B\. Wen, and Y\. Liu\(2021\)RoFormer: enhanced transformer with rotary position embedding\.External Links:2104\.09864,[Link](https://arxiv.org/abs/2104.09864)Cited by:[3rd item](https://arxiv.org/html/2611.27084#S1.I2.i3.p1.1)\.
- \[29\]G\. Team, A\. Kamath, J\. Ferret, S\. Pathak, N\. Vieillard, R\. Merhej, S\. Perrin,et al\.\(2025\)Gemma 3 technical report\.External Links:2503\.19786,[Link](https://arxiv.org/abs/2503.19786)Cited by:[§1](https://arxiv.org/html/2611.27084#S1.p5.1),[§2\.3](https://arxiv.org/html/2611.27084#S2.SS3.p1.1)\.
- \[30\]W\. Wang, F\. Wei, L\. Dong, H\. Bao, N\. Yang, and M\. Zhou\(2020\)MiniLM: deep self\-attention distillation for task\-agnostic compression of pre\-trained transformers\.External Links:2002\.10957,[Link](https://arxiv.org/abs/2002.10957)Cited by:[item 2](https://arxiv.org/html/2611.27084#S1.I1.i2.p1.1),[§1](https://arxiv.org/html/2611.27084#S1.p4.1)\.
- \[31\]A\. Yang, A\. Li, B\. Yang, B\. Zhang, B\. Hui, B\. Zheng, B\. Yu, C\. Gao, C\. Huang, C\. Lv, C\. Zheng, D\. Liu, F\. Zhou, F\. Huang, J\. Zhou, J\. Lin,et al\.\(2025\)Qwen3 technical report\.External Links:2505\.09388,[Link](https://arxiv.org/abs/2505.09388)Cited by:[§1](https://arxiv.org/html/2611.27084#S1.p5.1),[§2\.3](https://arxiv.org/html/2611.27084#S2.SS3.p1.1)\.
- \[32\]Y\. Zhang, M\. Li, D\. Long, X\. Zhang, H\. Lin, B\. Yang, P\. Xie, A\. Yang, D\. Liu, J\. Lin, F\. Huang, and J\. Zhou\(2025\)Qwen3 embedding: advancing text embedding and reranking through foundation models\.External Links:2506\.05176,[Link](https://arxiv.org/abs/2506.05176)Cited by:[3rd item](https://arxiv.org/html/2611.27084#S1.I2.i3.p1.1),[§4\.2](https://arxiv.org/html/2611.27084#S4.SS2.p1.1)\.
- \[33\]H\. Zhao, C\. Yuan, F\. Huang, X\. Hu, Y\. Zhang, A\. Yang, B\. Yu, D\. Liu, J\. Zhou, J\. Lin,et al\.\(2025\)Qwen3Guard technical report\.External Links:2510\.14276,[Link](https://arxiv.org/abs/2510.14276)Cited by:[§1](https://arxiv.org/html/2611.27084#S1.p2.1),[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx1.p1.1)\.
- \[34\]A\. Zou, L\. Phan, S\. Chen, J\. Campbell, P\. Guo, R\. Ren, A\. Pan, X\. Yin, M\. Mazeika, A\. Dombrowski, S\. Goel, N\. Li, M\. J\. Byun, Z\. Wang, A\. Mallen, S\. Basart, S\. Koyejo, D\. Song, M\. Fredrikson, J\. Z\. Kolter, and D\. Hendrycks\(2023\)Representation engineering: a top\-down approach to ai transparency\.External Links:2310\.01405,[Link](https://arxiv.org/abs/2310.01405)Cited by:[§1](https://arxiv.org/html/2611.27084#S1.p3.1),[§2\.1](https://arxiv.org/html/2611.27084#S2.SS1.SSSx2.p1.1)\.相似文章
ContextGuard:语言模型中上下文学习的结构化自我审计
介绍ContextGuard,一个结构化自我审计框架,通过将模型自我评估分解为确认和不确定类别并应用针对性修订来改进语言模型上下文学习。在CL-Bench基准测试中,Qwen3.5-4B的任务解决率从9.64%提升至13.85%。
OpenGuardrails: 一个开源的上下文感知AI护栏平台
OpenGuardrails 是一个面向AI安全的开源平台,通过统一模型提供上下文感知的内容安全与操纵检测(例如提示注入、越狱),以及一个独立的NER管道用于数据泄露识别。它在安全基准测试上取得了最先进的性能,并支持私有化、企业级部署。
KG-Guard: 基于图的幻觉检测方法用于知识库问答
KG-Guard是一个轻量级的基于图的框架,用于检测基于LLM的知识库问答中的幻觉。它将LLM视为黑盒,使用图编码器与MLP分类器来识别幻觉答案节点,在参数少得多的前提下优于基线方法。
明辨守护:学习为多模态安全实施干预
该论文提出了 JudiAct,这是一种多模态安全防护模型,可在允许、警告、审核和拒绝等操作中做出选择,而非一概拒绝。论文还推出了 JudiBench 基准和包含 20,126 条审核记录的训练语料库。与其 4B 骨干模型相比,JudiAct 的 Macro-F1 提升了超过 28 个百分点,并将 MM-SafetyBench 上的攻击成功率从 40.78% 降至 25.30%。
X3Guard:一个 1.5 亿参数的提示词防护模型
Axiomic Labs 发布了 X3Guard-150M,这是一个紧凑的 1.5 亿参数提示词防护模型,基于 GPT-X3-150M 微调而来,可对提示词的有害性以及对抗性风险(越狱/提示词注入)进行评分,在危害检测基准上超越了 Llama Guard 和 gpt-oss-safeguard-20B 等规模大得多的模型。