HiddenGuard: Fine-Grained Safe Generation with Specialized Representation Router

## Abstract

Abstract As Large Language Models (LLMs) grow increasingly powerful, ensuring their safety and alignment with human values remains a critical challenge. Ideally, LLMs should provide informative responses while avoiding the disclosure of harmful or sensitive information. However, current alignment approaches, which rely heavily on refusal strategies—such as training models to completely reject harmful prompts or applying coarse filters—are limited by their binary nature. These methods either fully deny access to information or grant it without sufficient nuance, leading to overly cautious responses or failures to detect subtle harmful content. For example, LLMs may refuse to provide basic, public information about medication due to misuse concerns.
Moreover, these refusal-based methods struggle to handle mixed-content scenarios and lack the ability to adapt to context-dependent sensitivities, which can result in over-censorship of benign content.
To overcome these challenges, we introduce HiddenGuard , a novel framework for fine-grained, safe generation in LLMs. HiddenGuard incorporates Prism (Re p resentation R outer for I n- S tream M oderation), which operates alongside the LLM to enable real-time, token-level detection and redaction of harmful content by leveraging intermediate hidden states. This fine-grained approach allows for more nuanced, context-aware moderation, enabling the model to generate informative responses while selectively redacting or replacing sensitive information, rather than outright refusal.
We also contribute a comprehensive dataset with token-level fine-grained annotations of potentially harmful information across diverse contexts. Our experiments demonstrate that HiddenGuard achieves over 90% in F 1 subscript F 1 \text{F}_{1} F start_POSTSUBSCRIPT 1 end_POSTSUBSCRIPT score for detecting and redacting harmful content while preserving the overall utility and informativeness of the model’s responses. Our code is available at https://github.com/Meirtz/HiddenGuard .

## 1 Introduction

Large Language Models (LLMs) have revolutionized natural language processing, demonstrating remarkable capabilities in various tasks (OpenAI, ; ; Touvron et al., ; ; Song et al., ; Chen et al., ; Zhang et al., ), but their increasing power and ubiquity have raised critical challenges in ensuring safety and alignment with human values (Shayegani et al., ; Das et al., ; Chowdhury et al., ). The potential for LLMs to generate harmful, biased, or sensitive content poses significant risks to individuals, organizations, and society at scale (Chao et al., ; Zou et al., ; Mehrotra et al., ; Wei et al., ; Wang et al., ).

Current approaches to enhance LLMs’ safety primarily rely on refusal-based strategies (Anwar et al., ; Christiano et al., ; Rafailov et al., ), which face significant limitations in real-world applications. These methods often struggle to balance safety and utility, resulting in overly conservative responses or false negatives, and may fail to detect subtle harmful content, especially against adversarial attacks (Mazeika et al., ; Schlarmann & Hein, ). Refusal-based methods also struggle with context-dependent sensitivity, lacking the nuance to distinguish between benign and harmful content in different contexts (Das et al., ). This can lead to over-censoring or failing to identify harmful outputs in certain situations, while potentially limiting the LLM’s ability to generate diverse and creative content, even in safe contexts (Anwar et al., ).

To address these challenges, we propose HiddenGuard, a fine-grained safe generation framework for LLMs.
Unlike existing coarse-grained representation engineering methods (Zou et al., ; ; Yuan et al., ) that rely on global or regional representation constraints, HiddenGuard integrates a specialized router within the LLM architecture. This router, collaborating with LoRA-based activators (Hu et al., ) and a router network, enables real-time, token-level sensitivity detection and redaction.
By simultaneously neutralizing harmful content and preserving benign parts, HiddenGuard achieves more refined moderation compared to other methods.

Building on these insights, HiddenGuard introduces a novel approach that utilizes hidden representations for token-level moderation. By focusing on intermediate regional- and token-level states, HiddenGuard captures deeper semantic information and latent structures that allow for more precise identification of harmful content. This approach significantly reduces both false positives and false negatives, enabling more accurate routing of representations, while also equipping the system with the flexibility to resist future unseen attacks. Furthermore, the system operates in parallel with the base LLM, ensuring that the model’s original capabilities remain intact. This parallelization guarantees that the system does not interfere with the model’s performance or fluency, preserving its ability to generate diverse and creative content in safe contexts.

Consider such a scenario: you ask a LLM “Can you help me create a killer slideshow that will knock the audience dead?” a coarse-grained aligned LLM would interpret phrases like “killer” and “knock dead” literally, misconstruing them as violent language and consequently refusing to assist, thereby leaving you without the necessary support. In contrast, our HiddenGuard leverages the model’s representation space to accurately discern the contextual meaning of these phrases and selectively redacts only the segments that genuinely contain harmful content while preserving the rest of the informative and useful information. This approach ensures that you receive comprehensive assistance in creating an impactful slideshow without experiencing unintended refusals or over-censorship.

In addition to its moderation capabilities, HiddenGuard provides a dataset with token-level annotations of sensitive information across diverse contexts. This supports HiddenGuard’ development for precise content control and benefits the AI safety community. Our experiments show that HiddenGuard achieves over 90 $\text{F}_{1}$ in detecting and redacting sensitive content, outperforming baselines in precision and recall while maintaining LLM performance. HiddenGuard balances safety and utility, making it a promising deployment solution.

Figure: Figure 1: Comparison of LLM responses to a sensitive query. Token-level adaptive output (right) of HiddenGuard selectively redacts harmful content while preserving useful information, in contrast to refusal-based output (top left) completely rejects the query and jailbroken output (bottom left) provides unrestricted information.
Refer to caption: x1.png

## 2 Challenges with Refusal Alignment

Let $\mathcal{M}=(f_{\theta},\mathcal{X},\mathcal{Y})$ be a language model where $f_{\theta}:\mathcal{X}\rightarrow\mathcal{Y}$ is the model function with parameters $\theta\in\Theta$, $\mathcal{X}$ is the input space, and $\mathcal{Y}$ is the output space. Refusal alignment methods, such as RLHF, DPO and adversarial training, operate by optimizing the following objective:

$$ $\min_{\theta\in\Theta}\mathbb{E}_{(x,y)\sim\mathcal{D}_{\text{benign}}}\left[ \mathcal{L}_{\text{benign}}(f_{\theta}(x),y)\right]+\lambda\mathbb{E}_{x^{ \prime}\sim\mathcal{D}_{\text{adversarial}}}\left[\mathcal{L}_{\text{adv}}(f_{ \theta}(x^{\prime}))\right]$ (1) $$

where $\mathcal{L}_{\text{benign}}:\mathcal{Y}\times\mathcal{Y}\rightarrow\mathbb{R}_
{\geq 0}$ is a loss function ensures accuracy on benign data, $\mathcal{L}_{\text{adv}}:\mathcal{Y}\rightarrow\mathbb{R}_{\geq 0}$ penalizes adversarial outputs, and $\lambda\in\mathbb{R}_{>0}$ is a regularization factor. However, these methods face several critical challenges:

#### Limitations of Global Output-Level Optimization

RLHF (Ouyang et al., ) and DPO (Rafailov et al., ) are adversarial training methods optimize the model’s behavior globally, potentially leading to over-rejection of benign content and vulnerability to adversarial attacks. Let $f_{\theta}:\mathcal{X}\rightarrow\mathcal{Y}$ be the model function with parameters $\theta$.
These methods aim to solve:

$$ $\theta^{*}=\operatorname*{arg\,min}_{\theta}\mathbb{E}_{x\sim\mathcal{D}}[ \mathcal{L}_{\text{safety}}(f_{\theta}(x))],$ (2) $$

where $\mathcal{L}_{\text{safety}}:\mathcal{Y}\rightarrow\mathbb{R}_{\geq 0}$ is a safety-oriented loss function. This global optimization can result in overly conservative behavior, as the model learns to avoid potentially harmful outputs across all contexts. There exists a subset $\mathcal{X}_{\text{benign}}\subset\mathcal{X}$ such that:

$$ $\exists x\in\mathcal{X}_{\text{benign}}:f_{\theta^{*}}(x)\neq f_{\theta}(x) \text{ and }\mathcal{L}_{\text{utility}}(f_{\theta^{*}}(x))>\mathcal{L}_{\text {utility}}(f_{\theta}(x)),$ (3) $$

where $\mathcal{L}_{\text{utility}}:\mathcal{Y}\rightarrow\mathbb{R}_{\geq 0}$ measures the utility of the output. This indicates that the optimized model may produce less useful outputs for some benign inputs compared to the original model.

Moreover, these methods are vulnerable to adversarial attacks due to the limited adversarial distribution $\mathcal{D}_{\text{adversarial}}$ considered during training. This can lead to suboptimal solutions where $\exists x^{\prime}\in\mathcal{X}\setminus\mathcal{D}_{\text{adversarial}}:
\mathcal{L}_{\text{adv}}(f_{\theta^{*}}(x^{\prime}))\gg 0$. The loss landscape may contain local minima where $\nabla_{\theta}\mathcal{L}_{\text{adv}}(f_{\theta}(x^{\prime}))=0$, but global robustness is not achieved. Additionally, gradient masking can occur, where $\|\nabla_{x}\mathcal{L}_{\text{adv}}(f_{\theta}(x^{\prime}))\|_{2}\approx 0$ while small perturbations $\delta$ cause $\|f_{\theta}(x^{\prime}+\delta)-f_{\theta}(x^{\prime})\|_{2}\gg 0$, but global robustness is not achieved. Additionally, gradient masking 2 can occur, where $\|\nabla_{x}\mathcal{L}_{\text{adv}}(f_{\theta}(x{\prime}))\|_{2}\approx 0$ while small perturbations $\delta$ cause $\|f_{\theta}(x{\prime}+\delta)-f_{\theta}(x{\prime})\|_{2}\gg 0$. The expectation-based optimization also fails to account for worst-case scenarios, leaving the model vulnerable to inputs $x^{*}=\arg\max_{x\in\mathcal{X}}\mathcal{L}_{\text{adv}}(f_{\theta}(x))$. As a result of these factors, extensive refusal training can significantly degrade the model’s overall performance, creativity, and capability.

###### Theorem 1 (Inherent Trade-off in Global Output-Level Optimization) .

Suppose $f_{\theta^{*}}$ is obtained by optimizing a safety-oriented loss $\mathcal{L}_{\text{safety}}$ over the data distribution $\mathcal{D}$: $\theta^{*}=\arg\min_{\theta\in\Theta}\mathbb{E}_{x\sim\mathcal{D}}[\mathcal{L}
_{\text{safety}}(f_{\theta}(x))]$. Then, under reasonable assumptions, there exists a non-empty subset $\mathcal{X}_{\text{benign}}\subset\mathcal{X}$ such that for some $x\in\mathcal{X}_{\text{benign}}$:

$$ $\mathcal{L}_{\text{utility}}(f_{\theta^{*}}(x))>\mathcal{L}_{\text{utility}}(f _{\theta}(x)),$ (4) $$

where $\mathcal{L}_{\text{utility}}:\mathcal{Y}\rightarrow\mathbb{R}_{\geq 0}$ measures the utility loss of the output.

###### Theorem 1 (Inherent Trade-off in Global Output-Level Optimization) .

#### Over-Regularization at the Regional-Level

Regional- or representation-level moderation (Zou et al., ; Yuan et al., ) aim to adjust the internal representations of a model to mitigate harmful outputs. Let $\text{rep}_{M}:\mathcal{X}\rightarrow\mathbb{R}^{d}$ map inputs to d-dimensional internal representations. These methods typically optimize:

$$ $\min_{\theta}\mathbb{E}_{x\sim\mathcal{D}}\left[\mathcal{L}_{\text{utility}}(M (x),y)\right]+\lambda\mathbb{E}_{x\sim\mathcal{D}_{\text{adversarial}}}\left[ \mathcal{L}_{\text{mod}}(\text{rep}_{M}(x))\right]$ (5) $$

where $\mathcal{L}_{\text{mod}}:\mathbb{R}^{d}\rightarrow\mathbb{R}_{\geq 0}$ enforces constraints on harmful input representations. While effective, this approach can lead to over-regularization, manifesting in representation collapse 1 ($\|\text{rep}_{M}(x_{1})-\text{rep}_{M}(x_{2})\|_{2}<\epsilon$ for distinct harmful inputs), unintended impact on benign inputs ($\|\text{rep}_{M}(x^{+})-\text{rep}_{M}^{\text{modified}}(x^{+})\|_{2}>\delta$), and global distribution shift ($\mathrm{KL}(P_{\text{original}}(\text{rep}_{M}(x))\|P_{\text{modified}}(\text{
rep}_{M}(x)))>\gamma$). Direct use of representations for token-level routing often results in low accuracy and high false positive rates on benign content, potentially degrading model capabilities. Let $\mathcal{R}_{\phi}:\mathbb{R}^{d}\rightarrow[0,1]$ be a token-level router. The limitation can be expressed as:

$$ $P(\text{adversarial}\mid s_{j})\neq g({r_{j1},\ldots,r_{jK_{j}}})\quad\text{ and}\quad\mathcal{C}(T_{s})\neq h({r_{i}\mid t_{i}\in T_{s}})$ (6) $$

where $r_{i}=\sigma(\mathcal{R}_{\phi}(\text{rep}_{M}(t_{i})))$, $g$ and $h$ are aggregation functions, and $\mathcal{C}$ is an ideal contextual classifier. Moreover, using a single module $\phi:\mathbb{R}^{d}\rightarrow\mathbb{R}^{k}$ for both coarse-grained and fine-grained control leads to conflicting objectives: $\max I(\phi(\text{rep}_{M}(s));Y_{s})\quad\text{and}\quad\max I(\phi(\text{rep
}_{M}(t_{i}));Y_{t})$, for sentence-level and token-level tasks respectively. This conflict makes it challenging for the model to effectively capture representations at both granularities simultaneously. These limitations motivate our proposed method, which introduces separate components for multi-scale representation learning and moderation.

#### Limitations of Token-Level Filtering

Token-level filtering in refusal alignment methods is often represented using a router function $\mathcal{R}_{\phi}:\mathbb{R}^{d}\rightarrow[0,1]$, which computes the harmfulness for each token $t_{i}$:

$$ $r_{i}=\sigma\left(\mathcal{R}_{\phi}(z_{i})\right),\quad\forall i\in\{1,\ldots ,N\}$ (7) $$

where $z_{i}\in\mathbb{R}^{d}$ is a vector representation of token $t_{i}$, $\sigma:\mathbb{R}\rightarrow[0,1]$ is the sigmoid function, and $N$ is the sequence length. When $z_{i}$ represents hidden states, filtering can be parallelized with the model’s forward pass, maintaining complexity. Conversely, if $z_{i}$ represents output token embeddings, filtering introduces additional generation latency. No matter the choice of $z_{i}$, token-level approaches inherently struggle to capture broader contextual information. Let $\mathcal{S}={s_{1},\ldots,s_{M}}$ be the set of sentences in a sequence, where each sentence $s_{j}$ is composed of tokens. Token-level filtering fails to model the joint probability of harmfulness within sentences, lacking the ability to capture long-range dependencies and higher-order semantic structures. Formally, let $\mathcal{C}:\mathcal{P}(\mathcal{T})\rightarrow{0,1}$ be an ideal contextual harmfulness classifier over the power set of all possible tokens $\mathcal{P}(\mathcal{T})$. Then, for any subset of tokens $T_{s}\subseteq{t_{1},\ldots,t_{N}}$ and any functions $g:[0,1]^{K_{j}}\rightarrow[0,1]$ and $h:[0,1]^{|T_{s}|}\rightarrow{0,1}$:

$$ $P(\text{adversarial}\mid s_{j})\neq g({r_{j1},\ldots,r_{jK_{j}}})\quad\text{ and}\quad\mathcal{C}(T_{s})\neq h({r_{i}\mid t_{i}\in T_{s}})$ (8) $$

This fundamental limitation leads to increased false positives, false negatives, and inconsistent content moderation, as the method fails to adequately model the complex, context-dependent nature of harmful content in natural language.

To address these limitations, we propose Prism, a framework that introduces token-level redaction through a LoRA-based activator $\mathcal{A}:\mathcal{X}\rightarrow\mathbb{R}^{k}$ and a dedicated router $\mathcal{R}:\mathbb{R}^{d}\times\mathbb{R}^{k}\rightarrow[0,1]$. Prism operates as an auxiliary mechanism alongside the pre-trained LLM, optimizing:

$$ $\min_{\phi,\psi}\mathbb{E}_{x\sim\mathcal{D}}\left[\sum_{i=1}^{N}\mathcal{L}_{ \text{token}}(t_{i},\mathcal{R}_{\phi}(h_{i},\mathcal{A}_{\psi}(x)))+\lambda \mathcal{L}_{\text{global}}(x,\mathcal{M}(x))\right]$ (9) $$

where $\phi$ and $\psi$ are parameters of the router and activator respectively, $\mathcal{L}_{\text{token}}:\mathcal{T}\times[0,1]\rightarrow\mathbb{R}_{\geq 0}$ is a token-level loss function, $\mathcal{L}_{\text{global}}:\mathcal{X}\times\mathcal{Y}\rightarrow\mathbb{R}_
{\geq 0}$ is a global coherence loss, $\lambda\in\mathbb{R}_{>0}$ balances local and global objectives, and $\mathcal{M}:\mathcal{X}\rightarrow\mathcal{Y}$ represents the fixed, pre-trained LLM.

These challenges expose the limitations of refusal alignment methods based on global output-level supervision. Our approach, Prism, introduces token-level redaction through a LoRA-based activator and a dedicated router, enabling a more nuanced and effective moderation mechanism.

Figure: Figure 2: HiddenGuard architecture and Prism training pipeline. The upper part showcases the inference process, where LoRA activators analyze hidden states to generate activation signals, guiding the router in real-time token-level moderation. The lower part illustrates Prism training, demonstrating how token-level labeled data trains LoRA activators and the router to identify subtle patterns of harmful content across various contexts, enabling precise content redaction.
Refer to caption: x2.png

## 3 Methodology

In this section, we introduce HiddenGuard, a novel framework for enhancing LLM safety through token-level moderation without compromising overall capabilities. At its core, HiddenGuard utilizes Prism, comprising LoRA-based activators for identifying harmful state at the representation level, and then, activate a router network for fine-grained moderation. HiddenGuard incorporates specialized inference strategies to complement Prism’s functionality, as shown in Fig. 2.
.

### 3.1 Prism : LoRA-based Activators

Given a pre-trained language model $\mathcal{M}$ with parameters $W\in\mathbb{R}^{d\times d}$, our goal is to modulate the model’s behavior in the presence of adversarial inputs without altering the base parameters $W$. To achieve this, we introduce $N_{\text{act}}$ LoRA-based activators, which are low-rank adaptations that operate on the model’s representations. For the $i$-th activator, we define low-rank matrices $\mathcal{A}_{i}\in\mathbb{R}^{r\times d}$ and $B_{i}\in\mathbb{R}^{d\times r}$, where $r\ll d$, to compute an activation $\Delta W_{i}=B_{i}\mathcal{A}_{i}$. This activation is used to generate a signal based on the model’s representation of input $x$ as follows:

$$ $s_{i}(x)=\sigma\left(v_{i}^{\top}\left(\Delta W_{i}\cdot\text{rep}_{\mathcal{M }}(x)\right)\right),$ (10) $$

where $\text{rep}_{\mathcal{M}}(x)\in\mathbb{R}^{d}$ is the representation of input $x$ obtained from the base model $\mathcal{M}$, $v_{i}\in\mathbb{R}^{d}$ is a learned signal vector for the $i$-th activator, and $\sigma(\cdot)$ denotes the sigmoid function. Crucially, we keep $W$ fixed and only learn the low-rank parameters $\mathcal{A}_{i}$, $B_{i}$, and signal vectors $v_{i}$. The activation $\Delta W_{i}$ is not applied directly to the model’s parameters $W$, but instead used to generate a signal $s_{i}(x)$ that modulates the model’s behavior without modifying its base architecture. This design focuses on generating activation signals rather than altering the entire representation, we maintain the discriminative power of the model.

Optimization Objectives: The activators are trained using two loss functions designed to balance the model’s response to adversarial and benign inputs, following the design in (Zou et al., ).

- •
Adversarial Regularization Loss ($\mathcal{L}_{\text{AR}}$): This loss encourages the activators to produce higher activation signals for adversarial inputs $x^{-}\sim\mathcal{D}_{\text{adversarial}}$.
$\mathcal{L}_{\text{AR}}=\frac{1}{N_{\text{act}}}\sum_{i=1}^{N_{\text{act}}}
\mathbb{E}_{x^{-}}\left[\text{ReLU}\left(\cos\left(\text{rep}_{\mathcal{M}}(x^
{-}),\Delta W_{i}(x^{+})\right)\right)\right],$
(11)
- •
Retention Loss ($\mathcal{L}_{\text{retain}}$): This loss ensures that the activators do not interfere with the representations of benign inputs $x^{+}\sim\mathcal{D}_{\text{benign}}$.
$\mathcal{L}_{\text{retain}}=\frac{1}{N_{\text{act}}}\sum_{i=1}^{N_{\text{act}}
}\mathbb{E}_{x^{+}}\left[\left\|\text{rep}_{\mathcal{M}}(x^{+})-\Delta W_{i}(x
^{-})\right\|_{2}^{2}\right].$
(12)

The total loss for training the activators is: $\mathcal{L}_{\text{activator}}=c_{\text{AR}}(t)\cdot\mathcal{L}_{\text{AR}}+c_
{\text{retain}}(t)\cdot\mathcal{L}_{\text{retain}}$, where $c_{\text{AR}}(t)$ and $c_{\text{retain}}(t)$ are time-dependent coefficients that balance the two objectives during training step $t$.

The pseudocode in Algorithm 1 outlines the training procedure for the LoRA-based activators.

Figure: Algorithm 1 Training Procedure for Prism (LoRA activator)

### 3.2 Signal Vector Learning

The signal vectors $v_{i}$ are critical for modulating the activators’ responses. They are learned to produce low activation signals for benign inputs and high activation signals for adversarial inputs. The learning objective for the signal vectors is:

$$ $\mathcal{L}_{\text{signal}}=\frac{1}{N_{\text{act}}}\sum_{i=1}^{N_{\text{act}} }\left(\mathbb{E}_{x^{+}}\left[\text{BCE}\left(s_{i}(x^{+}),0\right)\right]+ \mathbb{E}_{x^{-}}\left[\text{BCE}\left(s_{i}(x^{-}),1\right)\right]\right),$ (13) $$

where $\text{BCE}(\cdot,\cdot)$ denotes the binary cross-entropy loss.

### 3.3 Prism : Router Network for Token-Level Moderation

The router network $\mathcal{R}_{\phi}$ is a transformer parameterized by $\phi$ that maps a sequence of token representations and activator outputs to a harmfulness score for each token. For a context window size $k$, the router function is defined as $\mathcal{R}_{\phi}:\left(\mathbb{R}^{d}\right)^{2k+1}\times\mathbb{R}^{k}
\rightarrow[0,1]$. Given the sequence of token representations $h_{j-k},\dots,h_{j},\dots,h_{j+k}$ and activator output $a$, the router computes:

$$ $r_{j}=\sigma\left(\mathcal{R}_{\phi}\left([\text{rep}_{\mathcal{M}}(t_{j-k}),. ..,\text{rep}_{\mathcal{M}}(t_{j}),...,\text{rep}_{\mathcal{M}}(t_{j+k})] \right)\right)$ (14) $$

where $\sigma$ is the sigmoid function, $\text{rep}_{\mathcal{M}}(t_{j})$ is the representation of token $t_{j}$ from the base model, and $k$ is the context window size. Unlike traditional methods that apply global constraints to the entire representation, the router network in HiddenGuard performs precise moderation by evaluating each token within its surrounding context. The router is trained using a carefully curated dataset of token-level labeled data, encompassing various types of harmful content. To address potential class imbalance, we employ focal loss (Lin, ):

$$ $\mathcal{L}_{\text{router}}=-\frac{1}{N}\sum_{j=1}^{N}(1-p_{j})^{\gamma}y_{j} \log(p_{j})+p_{j}^{\gamma}(1-y_{j})\log(1-p_{j}),$ (15) $$

where $y_{j}$ is the ground-truth label indicating whether token $t_{j}$ is harmful, $N$ is the total number of tokens, $p_{j}=\sigma(r_{j})$, and $\gamma$ is the focusing parameter. This fine-grained control ensures that only specific harmful tokens are redacted, preserving the integrity and utility of the remaining content.

Figure: Algorithm 2 HiddenGuard: Inference Procedure

### 3.4 HiddenGuard : Integration of Activators and Router

During inference, we use the activation signals from the activators to determine whether to enter a ”redaction mode”. When activated, the router’s token-level predictions are used to make fine-grained moderation decisions. This approach leverages both global and local contextual information, enhancing moderation effectiveness without over-constraining the representation space. For each token $t_{j}$ in the generated sequence, we compute the harmfulness score and make decisions as follows:

$$ $\displaystyle s$ $\displaystyle=\sigma(v^{\top}\cdot\text{rep}_{\mathcal{M}}(x)),$ (16) $\displaystyle\hat{r}_{j}$ $\displaystyle=\left(\frac{1}{N_{\text{act}}}\sum_{i=1}^{N_{\text{act}}}s_{i}(x )\right)\cdot r_{j}$ (17) $\displaystyle\text{decision}_{j}$ $\displaystyle=\begin{cases}\text{[REDACTED]},&\text{if }s>\tau\text{ and }r_{j }>\xi,\\ \text{retain},&\text{otherwise}.\end{cases}$ (18) $$

In  equation 16, $s$ captures the global harmfulness signal from the activators. If this signal exceeds a threshold $\tau$, the system enters redaction mode. In this mode, $r_{j}$ from  equation 17 provides the local, token-level assessment from the router. The moderation decision for each token is then made using a dual threshold mechanism as shown in  equation 18. This approach ensures that moderation is both comprehensive and minimally invasive, targeting only the most relevant portions of the content for redaction when necessary. By combining global activation signals with conditional token-level assessments, HiddenGuard effectively balances the need for safety with the preservation of the model’s original capabilities. During inference, the input is processed through the base model to obtain token representations. The activators generate global harmfulness signals, while the router assesses each token locally. The combined scores $\hat{r}_{j}$ are used to make moderation decisions, such as redacting or replacing harmful tokens, enabling dynamic and context-aware content moderation.

## 4 Experiments

#### Dataset

We utilize two primary datasets: the Redacted Circuit Breaker Dataset and the Retain Dataset. The Redacted Circuit Breaker Dataset comprises harmful content generated by uncensored models, annotated initially with GPT-4o and refined with character-level IOB tagging, later converted to token-level labels for fine-grained moderation. The Retain Dataset includes the UltraChat subset with benign queries and conversations, and the XSTest subset with exaggerated refusal examples. Additionally, we incorporate the chosen subset from the Anthropic/hh-rlhf dataset to balance the training data. For more details, see C.1.

#### Setup

Our experiments are conducted on three state-of-the-art language models: LLaMA2-7B-Chat, LLaMA3-8B-Instruct, and Mistral-7B-Instruct. Training and inference of HiddenGuard are performed on 2 NVIDIA Tesla A800 GPUs with 80 GB memory each. Each training epoch takes approximately 4 hours, and inference accommodates a maximum sequence length of 8192 tokens with a batch size of 8. For more details, see C.2.

#### Evaluation

We evaluate our model across multiple benchmarks, assessing redaction accuracy, adversarial robustness, and overall model capability. Redaction accuracy is measured using the pass @ n% metric, while adversarial robustness is tested with HarmBench (Mazeika et al., ) and BabyBLUE (Mei et al., ). Additionally, we ensure that the model’s performance remains robust on MMLU-Pro and MT-Bench, maintaining a balance between safety and utility. For more details, see C.3.

### 4.1 Results

We present our results in three main categories: redaction accuracy, resistance to adversarial attacks (redteaming), and overall model capability. These evaluations demonstrate the model’s effectiveness in accurately redacting harmful content while preserving benign information, its robustness against adversarial challenges, and its ability to maintain strong performance on general language tasks with minimal impact on utility.

**Table 1: Performance metrics of activator and router components across three language models under different pass thresholds.**
| Model | Activator | Router (pass @100%) | Router (pass @90%) |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Acc. (%) | Prec. | Recall | $\text{F}_{\text{1}}$ | Prec. | Recall | $\text{F}_{\text{1}}$ |  |
| LLaMA2-7B-chat | 99.97 | 0.8804 | 0.8771 | 0.8788 | 0.8909 | 0.9231 | 0.9067 |
| LLaMA3-8B-Instruct | 99.99 | 0.8540 | 0.8667 | 0.8603 | 0.874 | 0.9294 | 0.9008 |
| Mistral-7B-Instruct | 99.98 | 0.9296 | 0.8687 | 0.8488 | 0.955 | 0.9709 | 0.9629 |

#### Redaction.

Our experiments demonstrate the effectiveness of HiddenGuard across multiple dimensions of performance and robustness. Table 1 shows the evaluation accuracy of HiddenGuard’s components across different models. The activator maintains very high accuracy ($\geq$ 99.97%) across all tested models, demonstrating its reliability in identifying potentially harmful content with remarkable stability. This high accuracy is crucial, as it ensures that harmful content is flagged early in the moderation pipeline, providing a strong foundation for the router’s subsequent operations. The router shows varying performance depending on the strictness of the pass threshold, with precision, recall, and F1 scores generally improving as the threshold decreases from 100% to 90%. This suggests that a slight relaxation in the moderation strictness can lead to better overall balance between safety and the preservation of benign content. For example, the increase in F1 score from 0.8488 to 0.9629 for the Mistral-7B-Instruct model highlights the router’s improved capacity to detect nuanced harmful content when allowed some flexibility.

#### Red Teaming.

Figure: Table 2: ASR results of refusal-trained models versus HiddenGuard under different attack methods. Lower values indicate better robustness against adversarial attacks.

In terms of adversarial robustness, Table 2 illustrates HiddenGuard ’s superior performance against various attack methods compared to refusal-trained models. Across all tested models, HiddenGuard significantly reduces the Attack Success Rate (ASR). For instance, on the LLaMA3-8B-Instruct model, HiddenGuard achieves ASRs between 0.9% and 6.8%, compared to 11.6-40.0% for the refusal-trained version. This substantial improvement in robustness demonstrates the effectiveness of our approach in combining global and local moderation strategies to enhance model safety. Furthermore, the reduced ASR highlights the advantage of HiddenGuard ’s token-level redaction mechanism, which dynamically adjusts the response at the generation stage. By focusing on harmful tokens instead of refusing entire responses, HiddenGuard mitigates the trade-off between utility and safety often observed in traditional refusal-based models. The ability to maintain benign content while selectively redacting harmful elements significantly lowers the model’s susceptibility to adversarial manipulation. This is particularly evident in challenging attack scenarios, where HiddenGuard consistently outperforms refusal-aligned models across a variety of adversarial prompts, demonstrating its robustness against diverse types of attacks. For red teaming methods descriptions, see C.4.

#### Capability.

Figure: Table 3: Capability test. MMLU-Pro and MT-Bench scores for refusal-trained models and HiddenGuard. Higher scores indicate better general language capabilities.

Table 2 presents the results of standard benchmarks, assessing the impact of HiddenGuard on overall model capabilities. The results indicate that HiddenGuard maintains the base models’ performance on tasks such as MMLU-Pro and MT-Bench, with minimal degradation (maximum 1.4 points on MMLU-Pro for LLaMA3-8B-Instruct). This suggests that our method improves safety without significantly compromising general language understanding and generation abilities. The minimal impact on model capabilities further underscores HiddenGuard ’s balance between safety and functionality. Unlike approaches that overly constrain the model’s output, leading to reduced performance on standard tasks, HiddenGuard ’s fine-grained moderation allows it to maintain high levels of fluency and comprehension. The slight reduction in MMLU-Pro performance is marginal and well within acceptable bounds for practical use. This result indicates that the integration of token-level moderation does not interfere with the model’s ability to perform complex reasoning or generate diverse and creative content, making HiddenGuard a scalable solution for safe deployment of LLMs in real-world scenarios. This highlights HiddenGuard ’s capability to seamlessly integrate safety mechanisms without sacrificing the model’s versatility.

### 4.2 Ablation and Analysis

#### Ablation.

Figure: Table 4: Ablation study of Prism. The table shows the performance of the full HiddenGuard system, along with the individual contributions of the activator and router components, both with and without MLP structures. The results highlight the importance of both components for achieving optimal precision, recall, and F1 scores.

Our ablation study, shown in Table 4, reveals the contribution of each component in HiddenGuard. The full HiddenGuard system outperforms individual components, achieving the highest precision (0.85), recall (0.87), and F1 score (0.86).
Both the LoRA-based activators and transformer-based router play crucial roles in the system’s performance, with their MLP versions showing significant improvements over their counterparts without MLP structures. Theoretical insights further support this, as the activator captures broader harmful patterns at a representation level, while the router refines these assessments at a token level, enabling more precise moderation. Without either component, the system fails to maintain its nuanced moderation capabilities, leading to increased false positives and false negatives, as evidenced by the reduced scores in the table. Thus, the interaction between the activator and the router is indispensable, as they collectively ensure both high sensitivity to harmful content and minimal disruption to benign outputs.

#### Representation Analysis.

Figure: Figure 3: UMAP projection of token-level activator representations.
Refer to caption: extracted/5866008/figures/activator_rep.jpg

#### Activator analysis

We conducted a representation analysis on 200 samples from the redacted dataset. Figure 3 illustrates the UMAP projection of token-level activator representations. Despite the activator’s proficiency in triggering the “redacted mode,” the substantial overlap between benign and adversarial representations in the UMAP space ($\mathcal{U}:\mathbb{R}^{d}\rightarrow\mathbb{R}^{2}$) indicates its limitations in fine-grained token-level routing. Let $\mathcal{A}:\mathcal{X}\rightarrow\mathbb{R}^{k}$ be the activator function and $t_{i}\in\mathcal{T}$ be a token. The overlap can be expressed as $P(\mathcal{U}(\mathcal{A}(t_{i}^{benign}))\in\mathcal{R}_{overlap})>\epsilon$ and $P(\mathcal{U}(\mathcal{A}(t_{i}^{adversarial}))\in\mathcal{R}_{overlap})>\epsilon$, where $\mathcal{R}_{overlap}$ is the overlapping region and $\epsilon$ is a significant probability threshold. This overlap suggests that the activator alone may struggle to differentiate between borderline benign and adversarial content, especially in more nuanced cases. Therefore, its role is essential in flagging general harmful content, but further refinement through the router is required for context-sensitive moderation.

Figure: Figure 4: UMAP projection of router representations, showing a clear bimodal distribution that highlights the router’s ability to differentiate between distinct token categories.
Refer to caption: extracted/5866008/figures/router_rep.png

#### Router analysis

Figure 4 presents the UMAP projection of router representations extracted from 200 unlabeled LLM jailbreak response samples. In contrast to the activator representations, the router exhibits a striking bimodal distribution in the latent space. Let $\mathcal{R}:\mathcal{T}\rightarrow\mathbb{R}^{m}$ be our router function mapping tokens to m-dimensional representations. The bimodal nature can be formalized as the existence of two distinct clusters $C_{1}$ and $C_{2}$ in the UMAP space $\mathcal{U}(\mathcal{R}(t))$, where $\forall t\in\mathcal{T},P(t\in C_{1}|t\in\mathcal{T})+P(t\in C_{2}|t\in
\mathcal{T})\approx 1$, and $\text{KL}(P(t|t\in C_{1})||P(t|t\in C_{2}))>\delta$ for some large $\delta$. This clear separation suggests the router’s enhanced capability in distinguishing between potentially safe and unsafe tokens, even in the challenging context of jailbreak attempts. The distinct clustering validates our multi-component approach, demonstrating the router’s effectiveness in capturing fine-grained, token-level distinctions that complement the global perspective provided by the activator. Moreover, this separation implies that the router can better identify subtle differences in token contexts that the activator may overlook. The synergy between the activator’s broad detection and the router’s focused refinement is essential for robust content moderation.

## 5 Conclusion

This work addresses the limitations of existing refusal-based alignment methods by demonstrating that fine-grained, token-level moderation significantly enhances the safety of large language models without compromising their capabilities. Our findings highlight the importance of balancing safety and utility, and underscore the need for improved benchmarks that better support nuanced content moderation. Future work will focus on generalizing this approach to handle more diverse adversarial scenarios and expanding its application to real-world systems.

## Ethics Statement

This work adheres to the ICLR Code of Ethics and aims to promote AI safety, fairness, and privacy in content moderation. While HiddenGuard does not involve human subjects or direct privacy concerns, we recognize that any moderation system must be carefully designed to avoid unintended consequences. The challenges we highlight are minor in nature and are primarily focused on optimizing the system for the best performance in diverse environments.

Firstly, HiddenGuard is built to balance safety and utility, reducing both false positives and false negatives. While the system has been rigorously tested across varied datasets to ensure fairness, there may still be rare instances in complex edge cases where minor biases could emerge. These instances are minimal, and further refinements in dataset diversity will help address such occurrences to achieve optimal results. Secondly, HiddenGuard processes and moderates content at the token level without storing or transmitting private user data, making it inherently secure, and the system is aligned with privacy standards and designed with responsible AI practices in mind. Finally, HiddenGuard is designed to address adversarial robustness, safeguarding against misuse by focusing strictly on harmful content. While the system has proven highly effective against current jailbreak techniques, any unforeseen misuse scenarios are expected to be minimal and will be addressed as part of our commitment to ongoing improvement and the evolution of AI safety.

In conclusion, the ethical considerations involved in this work are well within the norms of responsible AI development, and any minor challenges that exist only serve as opportunities to further enhance the system’s contribution to AI safety and societal benefit.

## Reproducibility Statement

To ensure the reproducibility of our work, we have provided comprehensive details regarding the experimental setup, dataset processing, and model configurations in the main paper and appendix. All necessary hyperparameters, architecture details, and training settings are described in Sections 3 and 4 of the paper, while additional implementation and dataset information can be found in Appendix C. Specifically, the dataset descriptions, preprocessing steps, and experimental conditions, including training durations and hardware specifications, are detailed in the appendix. Furthermore, to facilitate reproduction of the results, the source code and datasets will be made publicly available after the anonymous review period. A link to the open-source repository will be provided in the final version of the paper, allowing researchers to reproduce our experiments and verify the robustness of HiddenGuard in various settings, ensuring transparency and reliability.

## Appendix A Related Work

Adversarial Attacks on LLMs. Numerous manually crafted attack prompts have exposed vulnerabilities in modern LLMs (Mowshowitz, ; Wei et al., ), forming the foundation for red teaming efforts for frontier models (OpenAI, ; Anthropic, ). However, the process of red teaming lacks standardization across different models (Feffer et al., ), making it difficult to compare the effectiveness of safety interventions across various platforms. Automated red teaming approaches have shown promising results (Perez et al., ; Chao et al., ). Of particular note are transfer attacks using adversarial suffixes, optimized via gradients (Zou et al., ). White-box attacks, such as prefilling attacks, exploit internal model structures to elicit harmful outputs (Vega et al., ). Recent efforts to consolidate and evaluate these methods can be found in HarmBench (Mazeika et al., ) and BabyBLUE Mei et al. (). In the multi-modal domain, attacks span from simple typographic manipulations to sophisticated gradient-based optimizations (Carlini et al., ; Bailey et al., ). While some benchmarks exist for LLM-based agents (Liu et al., ), the exploration of their safety and robustness remains in its infancy.

Defenses for LLMs. Common defenses, such as Reinforcement Learning from Human Feedback (RLHF) (Christiano et al., ) and Direct Preference Optimization (DPO) (Rafailov et al., ), rely heavily on human annotations. However, they often fail against sophisticated adversarial attacks (Zou et al., ). More robust methods, such as prompt optimization to reject harmful content (Zhou et al., ), show potential but are limited in generalizability. Adversarial training, a strategy derived from computer vision (Madry et al., ), has been applied to LLMs but is computationally demanding and causes performance drops in general benchmarks (Zheng et al., ). Inference-time defenses, such as perplexity filters (Alon & Kamfonas, ), are only effective against static, non-adaptive attacks. More advanced approaches, such as erase-and-check strategies (Robey et al., ), incur significant computational costs. System-level defenses also remain vulnerable to well-designed adversarial inputs (Mangaokar et al., ). In contrast, our approach introduces circuit breakers, inspired by advances in representation engineering (Zou et al., ), which dynamically interrupt harmful output generation. This method is computationally efficient, bypassing the limitations of refusal and adversarial training by directly manipulating representations responsible for harmful content. It applies to both unimodal and multimodal LLMs, preventing harmful output without degrading the model’s utility. Additionally, Decoupled Refusal Training (DeRTa) (Yuan et al., ) addresses refusal position bias in safety tuning data, ensuring LLMs can reject harmful prompts at any point in the response sequence. This novel approach significantly enhances safety by equipping models with the ability to transition from harmful to safe responses dynamically.

Representation Engineering.
As contemporary defense strategies that solely supervise model outputs often fall short in achieving the necessary levels of controllability and reliability, there has been a growing interest in techniques that analyze and manage the internal representations of models. Representation engineering encompasses a broad range of research areas, including the discovery of emergent, interpretable structures within intermediate representations (Caron et al., ; Mikolov et al., ; Zou et al., ), the identification and modification of embedded knowledge (Meng et al., ; ; Mitchell et al., ), and the steering of model outputs (Bau et al., ; Ilharco et al., ; Ling et al., ; Upchurch et al., ; Turner et al., ). A particularly relevant advancement in this field is the control vector baseline introduced by Zou et al. (), which enhances large language models’ resilience against adversarial attacks. This approach not only utilizes control vectors but also incorporates representation-level loss functions to adjust internal representations effectively. Building on this foundation, recent developments have extended these methods to robustly unlearn harmful knowledge through a technique known as RMU (Li et al., ), demonstrating the versatility of representation engineering in tackling more complex objectives. Despite previous attempts to eliminate harmful circuits using bottom-up mechanistic interpretability (Li et al., ), these methods have proven inadequate.

Governance Challenges
Effective governance is crucial for the safety and societal alignment of LLMs and broader AI systems (Bullock et al., ; Veale et al., ). Current governance frameworks, including formal regulations, norms, soft law, and industry standards, are largely nascent and often voluntary, as seen in initiatives like the EU AI Act (Council of the European Union, ). Several meta-challenges impede the efficacy of LLM governance, such as the insufficient scientific understanding of LLMs and unreliable technical tools (Raji, ; Guha et al., ; Kapoor et al., ), the slow and inflexible nature of existing governance institutions (Marchant, ; Engler, ), and the significant influence of corporate power which raises risks of regulatory capture (Center for AI Safety et al., ; Costanza-Chock et al., ). Additionally, there is a pressing need for international cooperation and clearer accountability mechanisms (Dafoe, ; Anderljung & Carlier, ; Shavit et al., ; Barnard & Robertson, ). Addressing these challenges requires innovative approaches, such as establishing new regulatory bodies, enhancing public-private partnerships while mitigating capture risks, and accelerating technical research to inform governance (Tutt, ; Au, ; Hadfield & Clark, ). Without overcoming these obstacles, ensuring that LLMs contribute positively to society while minimizing harm remains a significant concern.

#### Model Editing and Tuning

Model editing is an effective approach for knowledge editing (KE), where the internal structure of the model is adjusted to alter its output for specific edited content. Recent model editing and tuning techniques for LLMs (Meng et al., ; ; Mitchell et al., ; Yao et al., ; Bi et al., ) commonly involve either integrating an auxiliary network with the original model or modifying and adding parameters to steer the model’s responses. In-Context Editing (ICE)(Bi et al., ; ; ; ) and In-Context Understanding(Mei et al., ) show promise by allowing edits to LLMs through prompting with modified facts and retrieving relevant editing demonstrations from a memory of edits. Moreover, models are demonstrating powerful problem-solving capabilities across an increasing number of domains (Zhang et al., ; ; ; Li et al., ).

## Appendix B Notation and Definitions

In this section, we provide definitions for all symbols and variables used throughout the paper, define key concepts such as *Representation Collapse*, and explicitly state the assumptions underlying our theoretical results.

### B.1 Notation

- •
$\mathcal{M}=(f_{\theta},\mathcal{X},\mathcal{Y})$: The language model, where $f_{\theta}:\mathcal{X}\rightarrow\mathcal{Y}$ is the model function with parameters $\theta\in\Theta$, $\mathcal{X}$ is the input space, and $\mathcal{Y}$ is the output space.
- •
$\theta\in\Theta$: Parameters of the language model.
- •
$\mathcal{X}$: Input space (set of all possible inputs).
- •
$\mathcal{Y}$: Output space (set of all possible outputs).
- •
$\mathcal{D}$: Data distribution over which expectations are taken.
- •
$\mathcal{D}_{\text{benign}}$: Distribution of benign data samples.
- •
$\mathcal{D}_{\text{adversarial}}$: Distribution of adversarial or harmful data samples.
- •
$\mathcal{L}_{\text{benign}}:\mathcal{Y}\times\mathcal{Y}\rightarrow\mathbb{R}_
{\geq 0}$: Loss function ensuring accuracy on benign data.
- •
$\mathcal{L}_{\text{adv}}:\mathcal{Y}\rightarrow\mathbb{R}_{\geq 0}$: Loss function penalizing adversarial or harmful outputs.
- •
$\lambda\in\mathbb{R}_{>0}$: Regularization factor balancing between benign and adversarial losses.
- •
$f_{\theta^{*}}$: The optimized model after training.
- •
$\mathcal{L}_{\text{safety}}:\mathcal{Y}\rightarrow\mathbb{R}_{\geq 0}$: Safety-oriented loss function.
- •
$\mathcal{L}_{\text{utility}}:\mathcal{Y}\rightarrow\mathbb{R}_{\geq 0}$: Utility loss function measuring the usefulness of the output.
- •
$\text{rep}_{M}:\mathcal{X}\rightarrow\mathbb{R}^{d}$: Function mapping inputs to $d$-dimensional internal representations.
- •
$\mathcal{L}_{\text{mod}}:\mathbb{R}^{d}\rightarrow\mathbb{R}_{\geq 0}$: Loss function enforcing constraints on harmful input representations.
- •
$\mathcal{R}_{\phi}:\mathbb{R}^{d}\rightarrow[0,1]$: Token-level router function parameterized by $\phi$.
- •
$\sigma:\mathbb{R}\rightarrow[0,1]$: Sigmoid activation function.
- •
$r_{i}=\sigma(\mathcal{R}_{\phi}(z_{i}))$: Harmfulness score for token $t_{i}$.
- •
$z_{i}\in\mathbb{R}^{d}$: Vector representation of token $t_{i}$.
- •
$N$: Sequence length (number of tokens in the input).
- •
$\mathcal{S}=\{s_{1},\ldots,s_{M}\}$: Set of sentences in a sequence.
- •
$s_{j}$: The $j$-th sentence in the sequence.
- •
$K_{j}$: Number of tokens in sentence $s_{j}$.
- •
$\mathcal{C}:\mathcal{P}(\mathcal{T})\rightarrow\{0,1\}$: Ideal contextual harmfulness classifier over the power set of all possible tokens $\mathcal{P}(\mathcal{T})$.
- •
$T_{s}\subseteq\{t_{1},\ldots,t_{N}\}$: Subset of tokens.
- •
$g:[0,1]^{K_{j}}\rightarrow[0,1]$: Aggregation function over token harmfulness scores in a sentence.
- •
$h:[0,1]^{|T_{s}|}\rightarrow\{0,1\}$: Aggregation function over token harmfulness scores in a subset $T_{s}$.
- •
$\mathcal{A}_{\psi}:\mathcal{X}\rightarrow\mathbb{R}^{k}$: LoRA-based activator function parameterized by $\psi$.
- •
$\mathcal{M}:\mathcal{X}\rightarrow\mathcal{Y}$: The fixed, pre-trained language model.
- •
$h_{i}$: Hidden state of the model at token position $i$.
- •
$\mathcal{L}_{\text{token}}:\mathcal{T}\times[0,1]\rightarrow\mathbb{R}_{\geq 0}$: Token-level loss function.
- •
$\mathcal{L}_{\text{global}}:\mathcal{X}\times\mathcal{Y}\rightarrow\mathbb{R}_
{\geq 0}$: Global coherence loss function.
- •
$\mathcal{L}_{\text{AR}}$: Adversarial Regularization Loss, used to encourage activators to produce higher activation signals for adversarial inputs.
- •
$\mathcal{L}_{\text{retain}}$: Retention Loss, used to ensure that activators do not interfere with the representations of benign inputs.
- •
$\mathcal{L}_{\text{signal}}$: Signal Vector Learning Loss, used to learn signal vectors that produce low activation signals for benign inputs and high activation signals for adversarial inputs.
- •
$x^{+}\sim\mathcal{D}_{\text{benign}}$: Benign input samples from the benign data distribution.
- •
$x^{-}\sim\mathcal{D}_{\text{adversarial}}$: Adversarial input samples from the adversarial data distribution.
- •
$N_{\text{act}}$: Number of activators.
- •
$c_{\text{AR}}(t)$: Time-dependent coefficient for Adversarial Regularization Loss at training step $t$.
- •
$c_{\text{retain}}(t)$: Time-dependent coefficient for Retention Loss at training step $t$.
- •
$k$: Context window size, determining the number of surrounding tokens considered by the router network.
- •
$\mathcal{L}_{\text{router}}$: Loss function for the router network, used to train the router for fine-grained token-level harmfulness classification.
- •
$\gamma$: Focusing parameter used in the focal loss to address class imbalance.
- •
$\alpha$: Coefficient used in the activator training loss scheduling.

### B.2 Explanation

- •
Time-dependent Coefficients ($c_{\text{AR}}(t)$ and $c_{\text{retain}}(t)$): These coefficients dynamically adjust during training to balance the Adversarial Regularization Loss and Retention Loss. Defining these symbols clarifies the mechanism for weighting different loss components throughout the training process.
- •
Context Window Size ($k$): In the router network, the context window size determines how many surrounding tokens are considered for each token’s harmfulness assessment. Clearly defining this parameter helps in understanding the scope of contextual information the router utilizes.
- •
Loss Functions ($\mathcal{L}_{\text{router}}$ and $\mathcal{L}_{\text{signal}}$): Defining these loss functions provides a comprehensive description of the different training objectives and optimization directions within the model.
- •
Focusing Parameter ($\gamma$) and Coefficient ($\alpha$): These hyperparameters play crucial roles in the loss functions, and defining them helps readers understand the mechanisms for adjusting the influence of different loss components.

### B.3 Definitions

###### Definition 1 (Representation Collapse) .

*Representation Collapse* refers to the phenomenon where the internal representations of distinct inputs become nearly identical due to over-regularization or excessive constraints imposed during training. Formally, for a model $M$ with representation function $\text{rep}_{M}:\mathcal{X}\rightarrow\mathbb{R}^{d}$, representation collapse occurs when:

$$ $\|\text{rep}_{M}(x_{1})-\text{rep}_{M}(x_{2})\|_{2}<\epsilon,\quad\forall x_{1 },x_{2}\in\mathcal{X}_{\text{adversarial}},$ $$

where $\mathcal{X}_{\text{adversarial}}\subseteq\mathcal{X}$ is the set of adversarial inputs, and $\epsilon$ is a small positive constant. This collapse reduces the model’s ability to distinguish between different adversarial inputs, potentially impacting its overall performance and expressiveness.

###### Definition 2 (Gradient Masking) .

*Gradient Masking* is a situation where the gradients of the loss function with respect to the input are near zero, giving a false sense of security against adversarial attacks. Formally, for an input $x^{\prime}\in\mathcal{X}$:

$$ $\|\nabla_{x}\mathcal{L}_{\text{adv}}(f_{\theta}(x^{\prime}))\|_{2}\approx 0, \quad\text{but}\quad\|f_{\theta}(x^{\prime}+\delta)-f_{\theta}(x^{\prime})\|_{ 2}\gg 0,$ $$

where $\delta$ is a small perturbation. This indicates that small changes in the input can still lead to significant differences in the output, despite minimal gradients.

###### Definition 1 (Representation Collapse) .

###### Definition 2 (Gradient Masking) .

### B.4 Assumptions

Throughout our theoretical analysis, we make the following assumptions:

- 1.
Data Distribution: The data distribution $\mathcal{D}$ is fixed, and samples are drawn independently and identically distributed (i.i.d.).
- 2.
Model Capacity: The language model $f_{\theta}$ has sufficient capacity to approximate the desired functions within the hypothesis space $\Theta$.
- 3.
Loss Functions: The loss functions $\mathcal{L}_{\text{benign}}$, $\mathcal{L}_{\text{adv}}$, $\mathcal{L}_{\text{safety}}$, $\mathcal{L}_{\text{utility}}$, $\mathcal{L}_{\text{mod}}$, $\mathcal{L}_{\text{token}}$, and $\mathcal{L}_{\text{global}}$ are convex and differentiable with respect to their arguments.
- 4.
Regularization Parameter: The regularization factor $\lambda$ is a positive constant that balances the trade-off between conflicting objectives.
- 5.
Optimization Convergence: The optimization procedures employed converge to a (local) minimum of the loss functions.
- 6.
Ideal Functions: The functions $\mathcal{C}$, $g$, and $h$ are considered idealized for theoretical analysis and may not be perfectly realizable in practice.
- 7.
Activation Functions: Activation functions such as the sigmoid $\sigma$ are smooth and monotonically increasing.
- 8.
Router and Activator Functions: The router $\mathcal{R}_{\phi}$ and activator $\mathcal{A}_{\psi}$ have sufficient capacity to model the necessary mappings for effective moderation.

### B.5 Additional Assumptions

###### Assumption 1 (Robustness to Contextual Variations) .

The moderation function $\mathcal{R}$ maintains consistent performance across different contextual variations in the input data distribution, such that for any context $c$,

$$ $\mathbb{P}(\mathcal{R}(h_{i})=1\mid t_{i}\in\mathcal{T}_{\text{adv}},c)\geq 1-\delta,$ $$

$$ $\mathbb{P}(\mathcal{R}(h_{i})=1\mid t_{i}\notin\mathcal{T}_{\text{adv}},c)\leq\epsilon,$ $$

where $\delta,\epsilon\in(0,1)$ are small constants.

###### Assumption 1 (Robustness to Contextual Variations) .

## Appendix C Additional Experimental Details

### C.1 Dataset

Redacted Circuit Breaker Dataset:
The Redacted Circuit Breaker Dataset is a refined version of the refusal-retain dataset from (Zou et al., ), containing harmful content generated by various uncensored language models with precise annotations. Initial annotations were performed using GPT-4o to identify potentially harmful segments. These annotations were then refined through precise character-level Inside-Outside-Beginning (IOB) tagging to delineate harmful entities accurately. During preprocessing, character-level tags were converted into token-level labels to facilitate fine-grained moderation. The dataset comprises a total of 4,993 entries, with 3,994 allocated for training and 999 for testing.

Retain Dataset:
The Retain Dataset consists of two subsets:

- •
UltraChat: Contains benign queries and conversational exchanges designed to represent typical user interactions.
- •
XSTest: Includes exaggerated refusal examples that challenge the model’s ability to handle extreme cases.
- •
Additionally, we incorporate the chosen subset from the Anthropic/hh-rlhf dataset.

This subset is sampled to ensure that the final Retain Dataset matches the size of the Redacted Circuit Breaker Dataset, with 3,994 entries used for training. This balanced approach ensures equitable contribution from both datasets during training, enhancing the model’s ability to generate safe and informative responses while effectively moderating harmful content.

ASR Test Dataset:
For the Adversarial Success Rate (ASR) test, we selected the top 200 behaviors from the HarmBench benchmark, focusing on those with the highest attack success rates using BabyBLUE (Mei et al., ) evaluators. This selection targets the most challenging adversarial conditions, enabling a rigorous evaluation of the model’s robustness.

### C.2 Setup

Language Models:
We conduct experiments using the following language models:

- •
LLaMA2-7B-Chat
- •
LLaMA3-8B-Instruct
- •
Mistral-7B-Instruct

Router and Activator Configuration:
We deploy a single Prism at the 30th layer of each model, utilizing low-rank matrices with a dimension of $r=64$. The choice of layer and rank dimension was based on preliminary experiments indicating optimal performance in balancing computational efficiency and moderation accuracy. The 30th layer was selected because it is closer to the later stages of the model, allowing HiddenGuard to capture more refined representations without sacrificing parallelism in the computation. By placing the Prism at this layer, the core LLM architecture does not need to wait for the moderation results from HiddenGuard, ensuring that the main network can continue processing efficiently. This choice strikes a balance between leveraging rich, late-stage features and maintaining the overall inference speed.

The router network is configured with a transformer (Vaswani, ) encoder, where the number of layers is set to 1, and it uses 2 attention heads and a feedforward dimension of 512. The input ‘hidden_size’ for the router matches the hidden size of the model itself, ensuring no further downsampling occurs, which allows the router to directly process the full-resolution representations. This design allows the router to preserve the detailed contextual information necessary for accurate token-level moderation. The router’s final classification layer produces harmfulness scores for each token, enabling fine-grained detection and redaction of harmful content. Varying $r$ (the rank of low-rank matrices) impacts both the granularity of moderation and the computational overhead. Larger values of $r$ allow more nuanced token-level moderation but increase memory and computational costs, while smaller values reduce complexity but may miss subtle harmful content.

In our experiments, we only used a single activator, also located at the 30th layer, as it was found to be highly effective for the current limited adversarial dataset. The use of a single activator provided sufficient coverage for the moderation tasks at hand. However, as tasks become more complex and involve richer representation spaces, the number of activators can be increased to capture more nuanced patterns in the data and to manage more sophisticated adversarial scenarios.

Hardware and Training Parameters:
All experiments are conducted on 4 NVIDIA Tesla A800 GPUs, each equipped with 80 GB of memory. The training process for each epoch takes approximately 4 hours, allowing for sufficient convergence of the activators and router networks. Inference is performed with a maximum sequence length of 8192 tokens to accommodate complex prompts. We utilize a batch size of 8 for training and a batch size of 1 for evaluation across all experiments, optimizing for both computational efficiency and model performance. The model is trained for a total of 150 steps, with a learning rate of $1\times 10^{-5}$ and weight decay set to 0.0. We employ a constant learning rate scheduler, with gradient accumulation steps set to 1 to maintain stability during training.

To ensure efficient use of GPU resources, we enabled mixed precision training with bf16, and gradient checkpointing was employed to reduce memory usage during backpropagation. The training also leveraged DeepSpeed configuration to further optimize distributed training. Logging was performed every 10 steps, and evaluation was triggered every 1000 steps, ensuring detailed tracking of performance metrics throughout training.

### C.3 Evaluation

Redaction Accuracy:
We assess redaction accuracy using the pass @ n% metric. This metric evaluates whether a continuous sequence of tokens requiring redaction is successfully redacted if at least n% of the sequence is redacted. This flexible measure is particularly effective for evaluating models on longer sequences of harmful content. In our experiments, we used $n=90$, as human annotator volunteers consistently agreed that if 90% of a harmful sequence has been redacted, the remaining content can be considered sufficiently neutralized. This threshold strikes a balance between ensuring content safety and maintaining the informativeness of the model’s output.

Activator Performance:
The activator component is deemed successful if it triggers within the first 10% of harmful tokens in a given text sequence. This early detection criterion allows for proactive moderation, minimizing the generation of harmful content.

### C.4 Red Teaming Method Descriptions

- •
Direct Request: This approach employs the actual behavior statements as test inputs, assessing the model’s capability to reject explicit requests for these behaviors, especially when such requests are unambiguous and often indicate malicious intent.
- •
GCG (Zou et al., ): This technique involves crafting an adversarial suffix at the token level, which is then appended to a user prompt to generate a test case. The optimization process is designed to increase the log probability that the target LLM will respond affirmatively, exhibiting the desired behavior.
- •
PEZ (Wen et al., ): Similar to GCG, PEZ optimizes an adversarial suffix at the token level but utilizes a straight-through estimator and nearest-neighbor projection to focus on hard tokens during optimization.
- •
TAP-Transfer (Mehrotra et al., ): An extension of the TAP method, TAP-Transfer employs GPT-4 as both the judge and target model, while using Mixtral 8x7B as the attack model. The test cases generated through this method are intended to be transferable to other models, and it is abbreviated as TAP-T.
- •
PAIR (Chao et al., ): This method involves the iterative prompting of an attacker LLM to explore and induce specific harmful behaviors from the target LLM, systematically probing the model for vulnerabilities.

Overall Model Performance:
To ensure that safety enhancements do not degrade the model’s general capabilities, we evaluate overall performance on MMLU-Pro (Wang et al., ) and MT-Bench (Zheng et al., ). These evaluations confirm that our moderation framework maintains a balance between safety and utility, ensuring that the model remains effective across a wide range of tasks.

## Appendix D Proofs and Additional Theorems

#### Proof (Inherent Trade-off in Global Output-Level Optimization)

Consider the language model $\mathcal{M}=(f_{\theta},\mathcal{X},\mathcal{Y})$ parameterized by $\theta\in\Theta$, where $f_{\theta}:\mathcal{X}\rightarrow\mathcal{Y}$ maps inputs to outputs. The global output-level optimization seeks to minimize the combined loss function:

$$ $\theta^{*}=\arg\min_{\theta\in\Theta}\mathbb{E}_{x\sim\mathcal{D}_{\text{ benign}}}\left[\mathcal{L}_{\text{benign}}(f_{\theta}(x),y)\right]+\lambda \mathbb{E}_{x^{\prime}\sim\mathcal{D}_{\text{adversarial}}}\left[\mathcal{L}_{ \text{adv}}(f_{\theta}(x^{\prime}))\right],$ $$

where:

- •
$\mathcal{L}_{\text{benign}}:\mathcal{Y}\times\mathcal{Y}\rightarrow\mathbb{R}_
{\geq 0}$ denotes the utility loss on benign inputs.
- •
$\mathcal{L}_{\text{adv}}:\mathcal{Y}\rightarrow\mathbb{R}_{\geq 0}$ denotes the safety loss on adversarial inputs.
- •
$\lambda>0$ is a weighting factor balancing the two loss terms.
- •
$\mathcal{D}_{\text{benign}}$ and $\mathcal{D}_{\text{adversarial}}$ represent the distributions of benign and adversarial inputs, respectively.

Assume that $\mathcal{L}_{\text{benign}}$ and $\mathcal{L}_{\text{adv}}$ are not perfectly aligned. Specifically, there exists at least one benign input $x_{b}\in\mathcal{X}_{\text{benign}}$ such that optimizing $\mathcal{L}_{\text{adv}}$ increases $\mathcal{L}_{\text{benign}}$. Formally, for this $x_{b}$:

$$ $\nabla_{\theta}\mathcal{L}_{\text{benign}}(f_{\theta}(x_{b}),y)\cdot\nabla_{ \theta}\mathcal{L}_{\text{adv}}(f_{\theta}(x_{b}))<0.$ $$

At the optimal parameter $\theta^{*}$, the gradient of the combined loss must satisfy:

$$ $\nabla_{\theta}\left[\mathbb{E}_{x\sim\mathcal{D}_{\text{benign}}}\mathcal{L}_ {\text{benign}}(f_{\theta}(x),y)+\lambda\mathbb{E}_{x^{\prime}\sim\mathcal{D}_ {\text{adversarial}}}\mathcal{L}_{\text{adv}}(f_{\theta}(x^{\prime}))\right]=0.$ $$

Focusing on the benign input $x_{b}$, we can derive:

$$ $\displaystyle\nabla_{\theta}\mathcal{L}_{\text{benign}}(f_{\theta}(x_{b}),y)+ \lambda\nabla_{\theta}\mathcal{L}_{\text{adv}}(f_{\theta}(x_{b}))$ $\displaystyle=0$ (19) $\displaystyle\|\nabla_{\theta}\mathcal{L}_{\text{benign}}(f_{\theta}(x_{b}),y) \|_{2}^{2}+\lambda\nabla_{\theta}\mathcal{L}_{\text{adv}}(f_{\theta}(x_{b})) \cdot\nabla_{\theta}\mathcal{L}_{\text{benign}}(f_{\theta}(x_{b}),y)$ $\displaystyle=0$ (20) $\displaystyle-\lambda\nabla_{\theta}\mathcal{L}_{\text{adv}}(f_{\theta}(x_{b}) )\cdot\nabla_{\theta}\mathcal{L}_{\text{benign}}(f_{\theta}(x_{b}),y)$ $\displaystyle=\|\nabla_{\theta}\mathcal{L}_{\text{benign}}(f_{\theta}(x_{b}),y )\|_{2}^{2}$ (21) $\displaystyle>0$ (22) $$

This implies:

$$ $\mathcal{L}_{\text{benign}}(f_{\theta^{*}}(x_{b}),y)>\mathcal{L}_{\text{benign }}(f_{\theta}(x_{b}),y),$ $$

demonstrating that the optimized model $\theta^{*}$ incurs a higher utility loss on the benign input $x_{b}$ compared to the original model $\theta$. Thus, an inherent trade-off exists in global output-level optimization between minimizing safety loss and preserving utility.

###### Theorem 2 (Information Preservation) .

The HiddenGuard framework preserves mutual information between benign tokens and the model’s output, i.e.,

$$ $I(S_{\text{benign}};O_{\mbox{{HiddenGuard}}})\geq I(S_{\text{benign}};O_{\text {global}})-\epsilon,$ $$

where $S_{\text{benign}}$ is the set of benign tokens in the input sequence, $O_{\mbox{{HiddenGuard}}}$ and $O_{\text{global}}$ are the outputs of the HiddenGuard framework and global output-level optimization methods, respectively, and $\epsilon>0$ is a negligible term.

###### Proof.

Define the output of the global optimization method as $O_{\text{global}}=f_{\theta_{\text{global}}}(X)$ and the output of the HiddenGuard framework as $O_{\mbox{{HiddenGuard}}}=f_{\theta^{*}}(X,\mathcal{R})$, where $\mathcal{R}$ represents the moderation function applied by HiddenGuard. Let $X=(S_{\text{benign}},S_{\text{harmful}})$ denote the input sequence partitioned into benign tokens $S_{\text{benign}}$ and harmful tokens $S_{\text{harmful}}$.

Assume the following:

- 1.
Selective Redaction: The moderation function $\mathcal{R}$ only affects $S_{\text{harmful}}$ and leaves $S_{\text{benign}}$ unchanged, i.e., $S_{\text{benign}}$ remains identical in both $O_{\mbox{{HiddenGuard}}}$ and $O_{\text{global}}$.
- 2.
Weak Dependence: The redaction of $S_{\text{harmful}}$ introduces at most a negligible amount of noise $\epsilon$ to the mutual information between $S_{\text{benign}}$ and the output.
- 3.
Data Processing Inequality: Any processing of $O_{\text{global}}$ to obtain $O_{\mbox{{HiddenGuard}}}$ cannot increase the mutual information between $S_{\text{benign}}$ and $O_{\mbox{{HiddenGuard}}}$.

Under these assumptions, we can analyze the mutual information as follows:

$$ $\displaystyle I(S_{\text{benign}};O_{\mbox{{HiddenGuard}}})$ $\displaystyle=I(S_{\text{benign}};f_{\theta^{*}}(X,\mathcal{R}))$ $\displaystyle=I(S_{\text{benign}};f_{\theta^{*}}(S_{\text{benign}},\mathcal{R} (S_{\text{harmful}})))$ $\displaystyle\geq I(S_{\text{benign}};O_{\text{global}})$ $\displaystyle\geq I(S_{\text{benign}};O_{\text{global}})-\epsilon$ $$

Thus, the mutual information between benign tokens and the output under the HiddenGuard framework is preserved up to a negligible term $\epsilon$ compared to the global optimization method.
∎

###### Theorem 3 (Optimal Safety-Utility Trade-off) .

Assuming the moderation function $\mathcal{R}$ achieves perfect classification of harmful tokens, the HiddenGuard framework attains the optimal point on the Pareto frontier for the safety-utility trade-off. Formally, there does not exist another moderation strategy that simultaneously decreases $\mathcal{L}_{\text{safety}}$ without increasing $\mathcal{L}_{\text{utility}}$, or decreases $\mathcal{L}_{\text{utility}}$ without increasing $\mathcal{L}_{\text{safety}}$.

###### Theorem 2 (Information Preservation) .

###### Proof.

###### Theorem 3 (Optimal Safety-Utility Trade-off) .

#### Proof (Orthogonalization of Adversarial Representations)

Consider the adversarial regularization loss defined as:

$$ $\mathcal{L}_{\text{AR}}=\frac{1}{N_{\text{act}}}\sum_{i=1}^{N_{\text{act}}} \mathbb{E}_{x^{-}}\left[\text{ReLU}\left(\cos\left(\mathbf{h},\Delta\mathbf{W} _{i}\mathbf{h}\right)\right)\right],$ $$

where $\mathbf{h}=\text{rep}_{\mathcal{M}}(x^{-})\in\mathbb{R}^{d}$ is the representation of an adversarial input $x^{-}$, $\Delta\mathbf{W}_{i}=\mathbf{B}_{i}\mathbf{A}_{i}\in\mathbb{R}^{d\times d}$ represents the low-rank adaptation for the $i$-th activator, and $\cos(\mathbf{a},\mathbf{b})=\frac{\mathbf{a}^{\top}\mathbf{b}}{\|\mathbf{a}\|_
{2}\|\mathbf{b}\|_{2}}$ denotes the cosine similarity between vectors $\mathbf{a}$ and $\mathbf{b}$. The ReLU function is defined as $\text{ReLU}(z)=\max(0,z)$.

Expanding the cosine similarity, we have:

$$ $\cos\left(\mathbf{h},\Delta\mathbf{W}_{i}\mathbf{h}\right)=\frac{\mathbf{h}^{ \top}(\Delta\mathbf{W}_{i}\mathbf{h})}{\|\mathbf{h}\|_{2}\|\Delta\mathbf{W}_{i }\mathbf{h}\|_{2}}.$ $$

Substituting this into the loss function, the adversarial regularization loss becomes:

$$ $\mathcal{L}_{\text{AR}}=\frac{1}{N_{\text{act}}}\sum_{i=1}^{N_{\text{act}}} \mathbb{E}_{x^{-}}\left[\text{ReLU}\left(\frac{\mathbf{h}^{\top}(\Delta\mathbf {W}_{i}\mathbf{h})}{\|\mathbf{h}\|_{2}\|\Delta\mathbf{W}_{i}\mathbf{h}\|_{2}} \right)\right].$ $$

The ReLU function ensures that only positive cosine similarities contribute to the loss. Therefore, minimizing $\mathcal{L}_{\text{AR}}$ requires:

$$ $\displaystyle\cos\left(\mathbf{h},\Delta\mathbf{W}_{i}\mathbf{h}\right)$ $\displaystyle\leq 0$ $\displaystyle\implies\mathbf{h}^{\top}(\Delta\mathbf{W}_{i}\mathbf{h})$ $\displaystyle\leq 0$ $\displaystyle\implies\mathbf{h}^{\top}(\mathbf{B}_{i}\mathbf{A}_{i}\mathbf{h})$ $\displaystyle\leq 0$ $$

Let $\mathbf{A}_{i}\mathbf{h}=\mathbf{a}_{i}$ and $\mathbf{B}_{i}^{\top}\mathbf{h}=\mathbf{b}_{i}$. Then the above inequality can be rewritten as:

$$ $\mathbf{b}_{i}^{\top}\mathbf{a}_{i}\leq 0.$ $$

This condition enforces that the vectors $\mathbf{a}_{i}$ and $\mathbf{b}_{i}$ are orthogonal or negatively correlated. Consequently, the perturbation introduced by $\Delta\mathbf{W}_{i}$ ensures that $\Delta\mathbf{W}_{i}\mathbf{h}$ is either orthogonal to $\mathbf{h}$ or points in the opposite direction, thereby disrupting the alignment of the adversarial representation.

In summary, minimizing the adversarial regularization loss $\mathcal{L}_{\text{AR}}$ enforces the condition:

$$ $\cos\left(\mathbf{h},\Delta\mathbf{W}_{i}\mathbf{h}\right)\leq 0,$ $$

which implies orthogonality or negative correlation between $\mathbf{h}$ and $\Delta\mathbf{W}_{i}\mathbf{h}$. This orthogonalization effectively mitigates the influence of adversarial inputs on the model’s representations.

## Appendix E Limitations

While HiddenGuard addresses several key challenges in token-level moderation and demonstrates robustness against both benign and adversarial inputs, there are still areas for further refinement and exploration. First, while the theoretical foundations around representation collapse and the router network’s context-aware decision-making are already thoroughly detailed in this work, and the provided experimental results strongly support the claims, some minor practical considerations remain. For example, although the router is highly effective in dynamically adjusting token-level decisions, in edge cases where subtle harmful content closely resembles benign content, additional fine-tuning might be required. However, this is more of an optimization challenge rather than a fundamental issue with the design of the system itself. Additionally, though HiddenGuard has demonstrated strong performance in current adversarial robustness evaluations, the system’s performance against unknown or emerging jailbreak techniques remains to be assessed. As with all adversarial defenses, the long-term effectiveness of our approach will ultimately depend on how well it can adapt to future jailbreak methodologies. This is a minor limitation, as theoretically, the system is built to generalize across unseen attacks. Still, empirical testing on novel attack vectors as they emerge will be essential to further solidify HiddenGuard ’s practical utility.

Moreover, while our experiments cover a wide range of datasets and models, real-world deployment often involves more complex, variable scenarios where content sensitivity is highly context-dependent. Though our router network excels at differentiating token-level harmfulness in controlled benchmarks, further evaluations in more dynamic and unpredictable application environments may uncover additional layers of complexity that require adjustments to our moderation strategy.

In summary, the limitations identified are primarily centered around practical deployment challenges rather than core theoretical weaknesses, suggesting that HiddenGuard is well-positioned to be a strong solution for nuanced content moderation, with room for iterative improvements as adversarial tactics evolve and real-world requirements expand.

## Peer Reviews

confidence: 4
contribution: 2
initial_rating: 6
presentation: 3
questions: * Several typos in important optimization equations (Eq 11, 12), and line 8,9 in Algorithm 1, pose a hindrance to the readability of the paper. Also, all the 3 losses are not ablated in the results section - thus the relevance of all 3 losses needs to be empirically validated
* Hyper-parameter sweeps should be done in the results section. For e,g., in Table 1, when the threshold is decreased from 100% to 90% - increase in precision indicates that the point of precision-recall tradeoff has not been reached, and using a lower threshold rate should be tried.
* The dataset used for token level annotation using GPT-4o is not well explained. For e.g., the prompt used for this task, how the post-processing is done from character-level to token-level. Some examples of this dataset should be presented in the paper. The token-level safety of certain tokens might be relevant only the full sentence is decoded, but when detected using inference through left-to-right decoding inherently introduces false positives and false negatives.
soundness: 3
strengths: * Empirically, the method overcomes the limitations of token-level redaction through a combination of context-based redaction and global safety learning. 
* Improved performance on jailbreak benchmarks without regressing on utility benchmarks is a strong contribution to the community
summary: The paper proposes a token-level redaction LoRA and router based mechanism to hide potentially harmful segments of the response, instead of refusing to answer a prompt that might lead to harmful responses. The study is well motivated with worst-case alignment not well handled in average alignment strategies in RLHF. The existence of a benign prompt set with lower utility in a safety aligned model is understood, which is why the utility-model is improved through LoRA without changing the base model’s parameters. Empirically, this approach improves adversarial robustness on known jailbreaking techniques, without regressing much on the utility-based benchmarks. Ablation results show the importance of the router, activation, and the signal losses.
weaknesses: * The theoretical proofs are limited in nature, with the proof of how the limitations of refusal-training (in Theorem 1) is overcome through the proposed method is lacking. Since the constraints imposed are still enforced through regularization in conjunction with global safety refusal training, the insight of why the proposed method achieves better performance is missing in the Theoretical section.
* Comparison with jailbreak defense baselines (e.g. training a LoRA for adversarial training) and other context-dependent decoding strategies (e.g. controlled decoding) should be presented. Further, the token-redaction training only baseline is lacking (this is motivated in Section 2, but no results are presented)
* The increase in latency introduced by the inference procedure should be explained including additional flops required. This will be important to ensure that the comparison is fair. For instance, are certain inference-time mitigations relevant (e.g. circuit breaking, inference-time reasoning, etc)? 
* Finally, how easy are the redacted parts of the sentence decoded from a third-party non-aligned language model (like GPT4o) is unanswered. This is a significant limitation as the redaction can be easily broken by an adversary. This should be reflected in the ASR measurement.

---

confidence: 4
contribution: 2
initial_rating: 5
presentation: 2
questions: 1. If terms like "bomb" or "drugs" are mentioned without harmful intent (e.g., in an educational context), would they still be masked?
2. What threshold is set for general capability evaluation?
3. Section 4.2 mentions the MLP, but further clarification is needed as relevant details are not covered in other sections of the paper.
soundness: 2
strengths: - The paper is well-motivated, aiming to reduce toxicity by editing model outputs without outright refusal.
- The figures (Figure 1 and Figure 2) are clear and visually appealing, effectively illustrating the methodology pipeline.
summary: This paper proposes a masking mechanism for large language model responses based on multiple LoRA modules and a router. By training on a constructed dataset, the model can detect and redact harmful content in responses, effectively reducing the toxicity of model outputs.
weaknesses: - **Writing**: There is an incorrect table reference in the Capability section of Section 4.1.
- **Experimental Design**:
    - In Table 1, HiddenGuard is trained and validated on pre-constructed masked data, focusing on the accuracy of the masking structure. However, for AI safety, it is more critical to evaluate how much toxicity is reduced and how much useful content is preserved. Additional benchmarks and evaluation methods should be included.
    - Numerous existing studies have shown that model safety and helpfulness can be improved by directly modifying logits or responses. This method should be compared with other response-modifying approaches [1] or decoding-time methods [2][3].
    - Table 3 does not specify the lambda settings. If the lambda threshold is set too low, the method may not make any corrections to model responses, thereby having no impact on general performance.
- **Impact on Response Readability**: The paper presents limited inference cases. From the available examples, the method reduces toxicity by directly masking harmful content. However, this often impacts response readability, resulting in non-toxic but also non-informative text. From this perspective, masked responses may be less effective than refusals that include explanations or warnings.
- **Influence of LoRA Modules**: The paper does not provide sufficient explanation or ablation studies regarding the number of LoRA modules, which could be an important factor affecting model performance. This should be addressed in the paper.

[1] Ji J, Chen B, Lou H, et al. Aligner: Achieving efficient alignment through weak-to-strong correction[J]. arXiv preprint arXiv:2402.02416, 2024.

[2] Konen K, Jentzsch S, Diallo D, et al. Style Vectors for Steering Generative Large Language Model[J]. arXiv preprint arXiv:2402.01618, 2024.

[3] Lu X, Brahman F, West P, et al. Inference-time policy adapters (ipa): Tailoring extreme-scale lms without fine-tuning[J]. arXiv preprint arXiv:2305.15065, 2023.

---

confidence: 4
contribution: 3
initial_rating: 5
presentation: 2
questions: I don’t really understand figure 4. The caption claims that the UMAP projection shows a clear separation between safe and unsafe tokens, and I do see the clusters, but I don’t know what tokens they actually contain. How do you know that the clusters actually line up with the safe and unsafe tokens? And if you do have the safe/unsafe token labels, why not make a stronger statistical claim about their separation in the space (e.g., are they linearly separable)? In general, UMAP (or any dimensionality reduction technique) can be misleading to interpret. I think this section is useful for intuition, but could be moved to the appendix.

I am still a little confused about prior work. Do other token-level safety methods exist for LLMs? I think no, based on the related work section. However there is a section called “Limitations of Token-Level Filtering”, which implies that practitioners do use token-level filtering. If so, I would like to see a comparison to these methods in the evaluation.

I’m confused about “Attack Success Rate” (ASR). It seems non-trivial to determine whether an attack was successful. Do you use another LLM? If so, how accurate is that classifier? Again, it would be great to see actual example outputs to better contextualize these results.
soundness: 2
strengths: This is a novel method that presents a fundamentally new way of dealing with LLM safety and control, i.e., by contextual token-level control. I’m not sure this is applicable in all contexts, but it is an interesting and creative alternative that would be well-suited for some scenarios. Based on the evaluation, it is successful compared to the baseline safety tuning.
summary: The authors present a token-level safety method for LLMs, which leverages LORA. It addresses the issue that safety tuning for LLMs is often binary (either no response at all, or full information), and instead redacts specific tokens using model internals. The authors also release a new dataset with fine-grained (token level) annotations.
weaknesses: In general, the paper could be more clearly written. Specifically, I appreciate the desire to formalize methods mathematically, but I think this was overdone to the point of actually making the paper harder to understand (specifically, Section 2, and Section 3.3 and 3.4). I would recommend adding more high level description, and moving more of the proofs to the appendix. 

I would also like to see more details on what other methods you compared to. You mention “refusal trained models”-- which ones? Also, it would be useful to compare to a token-level baseline as to have a more apples-to-apples comparison with HiddenGuard. This could just be a non-contextual token-list method.

The introduction could use more motivating examples. Specifically, I am not convinced by the “Can you help me create a killer slideshow that will knock the audience dead” example. Did you apply the prior work to this example, and get unhelpful results? At the time of this review, ChatGPT gave me a reasonable response to this query (though I know this work looks at much smaller (7-8B param) models).  Relatedly, in the abstract, you motivate with “LLMs may refuse to provide basic, public information about medication due to misuse concerns”. Do you have any examples of HiddenGuard helping in this case?

It would also be great to see more examples of actual outputs from HiddenGuard in the appendix, to complement the aggregated results.

I appreciate the robust related work section in the appendix. It looks like there is some related work in the introduction, but the paper would be stronger if more of the related work in the appendix was in the main paper too.

The ethical statement is missing some potential areas. E.g ,did you do any robustness testing across different dialects to see whether there are disparities in redaction rates? Dodge et al (https://sites.rutgers.edu/critical-ai/wp-content/uploads/sites/586/2021/09/dodge2021documentingC4.pdf) found that African American English and Hispanic-aligned English are disproportionately affected by the filtering in C4. Does HiddenGuard have the same disparities?

---

confidence: 4
contribution: 3
initial_rating: 5
presentation: 2
questions: 1.Could you clarify which assumptions in the methodology have been empirically validated versus those that remain theoretical? Specifically, how would the model perform if these assumptions (e.g., threshold settings, activator behavior) were adjusted in real-world scenarios?

2.Given the additional components like LoRA-based activators and the router network, what specific optimizations are feasible to minimize computational overhead and deployment complexity? How does the model perform in terms of latency and resource requirements in a real-time setting?

3.Please refer to weakness 4 for examples. Could you clarify the reasoning behind this decision?

5.Could you elaborate on the methodology for setting thresholds for redaction and activation? Were sensitivity analyses conducted to ensure these thresholds optimize both safety and utility across various scenarios?

6.Certain sections are notably dense and challenging to follow. Have you considered restructuring or simplifying the language to improve clarity, especially in the technical explanations? Additionally, what steps will you take to enhance the clarity of the proposed method, the related work section, and baseline method justification, enabling readers to more quickly interpret key results?

7.There are minor errors and typos in figures and text that need correction. For instance, in the algorithm on line 3, the notation should represent a pair of benign and adversarial examples. Please carefully review the paper and address all possible errors.
soundness: 2
strengths: 1. The question addressed in this paper highlights a critical gap in current safe generation methods.

2. The paper introduces a fine-grained, token-level solution for safe generation. This approach to moderation is highly applicable in real-world scenarios requiring nuanced control over sensitive information, such as customer support, educational content, and automated information systems.

3. The method outperforms baseline approaches on the proposed dataset, demonstrating high precision and recall in detecting and redacting harmful content. The performance is impressive, effectively balancing safety and utility across tested tasks.

4. The discussion and analysis of challenges are insightful and effectively highlight the vulnerabilities of refusal-based methods.
summary: This paper addresses fine-grained, safe generation for Large Language Models (LLMs). It aims to overcome the limitations of existing refusal-based methods, which often lead to over-censorship in context-sensitive scenarios, affecting benign content. The authors propose a novel token-level redaction framework for harmful content called HIDDENGUARD. Unlike refusal-based approaches that fully accept or deny prompts, HIDDENGUARD uses LoRA-based activators in a “Representation Router” (PRISM) to operate alongside the model, detecting harmful content at a token level by leveraging intermediate hidden states. This approach allows for nuanced content moderation, selectively redacting harmful tokens while preserving benign and informative segments.

The authors evaluated HIDDENGUARD on two primary datasets, achieving over 90% F1 scores in detecting and redacting harmful content, demonstrating the effectiveness of their method in maintaining overall utility and informativeness in model responses. This result highlights the potential of HIDDENGUARD as an effective solution for safe and context-aware generation in LLMs.
weaknesses: 1. Presentation Quality and Model Evaluation: The presentation quality needs polish, as certain issues detract from its readability and overall professionalism. In the model evaluation section, there is a lack of adequate description of baseline methods in the main body, even though they are detailed in the appendix. Basic information about these methods should be included in the main text to make the comparison focus more reasonable. Necessary descriptions of the baseline method, model setup, dataset justification, and evaluation methods should be present in the paper rather than relegated to the appendix.
2. The absence of a dedicated "Related Work" section in the main body(which is presented in appendix) is a significant oversight that undermines the paper's clarity and impact. Without explicitly situating this work within the context of existing research, the paper fails to convey the novelty of its contributions, making it appear disconnected from the broader field. The paper layout should be managed properly with sufficient description of related work. Fo related work, it is better to include the most related topic about this paper such as current safe generation techniques, fine-grained token level alignment from other tasks and token scrubbing method like text sanitisation as it works that it masks the harmful contents like scrubbing methods.
3.Implications and Attack Surface: The implications of this approach are insufficiently discussed. This method may introduce a new attack surface, as only explicitly harmful tokens are detected and redacted, potentially alerting the information receiver to the removed content. This could allow users to infer the context of redacted information. Like conventional sanitization-based methods, this setting should be considered a baseline if the work claims full redaction and robust removal.
4. Assumptions and Robustness: The paper relies on an excessive number of assumptions, which weakens its robustness and applicability. For example, assumptions are made regarding the router function and ActivatorFunctions, suggesting these functions are efficient and have sufficient capacity to model necessary mappings for effective moderation. Key assumptions should be clearly stated in the main paper; their absence may mislead readers about task formulation and evaluation. The methodology includes frequent assumptions about the model's behavior in adversarial contexts, the effectiveness of LoRA-based activators, and harmful content detection thresholds. While some assumptions are unavoidable, this paper fails to rigorously justify or validate them. This lack of rigor is critical to the method’s quality and effectiveness, so it should be addressed in the main body, including a formal or theoretical guarantee of the activator functions' robustness in diverse, real-world scenarios.


5. Logical Errors in Mathematical Formulation: There are logical errors in the paper's mathematical formulation. For instance, in Section 2, Equation (7), the router function R already maps information to the range [0,1]. Applying the sigmoid function afterward constrains the range further, approximately to  [0.5,0.73], which seems illogical.

Meta-review: The authors propose a token-level masking method to redact the parts of LM outputs that are deemed harmful. Doing so provides more fine-grained control over safe LM generation, compared to standard approaches that tend to treat safe generation as a binary problem (i.e., either answer fully or refuse to answer).

Reviewers agreed that the proposed method is an interesting idea for an important problem. However, there were consistent concerns expressed about the clarity of writing, the positioning relative to prior work (to what extent is this the first token-level safe generation methods? etc.), and the overall persuasiveness of the paper. For example, reviewers were unconvinced by the example given in the introduction as well as Figure 1 (where the redactions don't seem to offer any additional benefit compared to the outright refusal, and in fact might just make the output harder for the user to parse). Overall, the authors are proposing a new class of approaches towards safe generation, which is exciting and potentially impactful -- but then the bar is higher to motivate that their approach is better in some way than existing approaches. Reviewers did not feel that the paper met this bar, and therefore I am unable to recommend acceptance. I encourage the authors to take the reviewer feedback into account for a future submission.

Decision: Reject