Manuscript Offprint
arXiv:2610.34961C-SafeGen: Certified Safe LLM Generation with Claim-Based Streaming Guardrails
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Abstract
Despite the remarkable capabilities of large language models (LLMs) across diverse applications, they remain vulnerable to generating content that violates safety regulations and policies. To mitigate these risks, LLMs undergo safety alignment; however, they can still be effectively jailbroken. Off-the-shelf guardrail models are commonly deployed to monitor generations, but these models primarily focus on detection rather than ensuring safe decoding of LLM outputs. Moreover, existing efforts lack rigorous safety guarantees, which are crucial for the universal deployment of LLMs and certifiable compliance with regulatory standards. In this paper, we propose a Claim-based Stream Decoding (CSD) algorithm coupled with a statistical risk guarantee framework using conformal analysis. Specifically, our CSD algorithm integrates a stream guardrail model to safeguard sequential claims generated by LLMs and incorporates a backtracking mechanism to revise claims flagged with high safety risks. We provide theoretical guarantees demonstrating that the CSD algorithm achieves the desired generation distribution subject to safety constraints. Furthermore, we introduce a generation risk certification framework and derive a high-probability upper bound on the safety risk of the proposed CSD algorithm. We prove that our method can asymptotically control safety risk to any desired level. Empirical evaluations demonstrate the effectiveness and efficiency of the CSD algorithm compared to state-of-the-art safety decoding approaches. Additionally, we validate the soundness and tightness of the derived safety risk upper bound using realistic data.
1 Introduction
Large language models (LLMs) [37, 29] have seen widespread adoption due to their remarkable capabilities in natural language understanding and generation. Open-source LLMs, such as DeepSeek-R1 [12], promote accessibility and transparency, fostering innovation across various applications. However, their openness also introduces substantial safety and security risks. Malicious actors can exploit open-source models by embedding backdoors [45] or crafting adversarial prompts to bypass safety constraints [50, 17], potentially leading to harmful generations. Such vulnerabilities pose real-world risks, including misinformation propagation, bias amplification, and security threats in autonomous systems [43]. These risks highlight the pressing need for rigorous safety guarantees in LLM generations, especially in high-stakes scenarios such as healthcare, finance, and policy-making.
Current approaches to mitigating unsafe LLM outputs are predominantly empirical and lack formal assurances. During the training phase, reinforcement learning from human feedback (RLHF) [30, 32] aims to align LLMs with human preferences and safety norms. However, RLHF is computationally expensive [16] and remains susceptible to adversarial attacks and jailbreak exploits [50]. At the inference phase, guardrail models [15, 25, 19, 33, 22, 47] attempt to filter unsafe responses, but they merely classify harmful content rather than proactively ensuring safe generation. Likewise, decoding-time interventions [44, 42, 48] modify token sampling strategies to reduce risk but lack theoretical safety guarantees. The absence of provable risk bounds limits the reliability of these empirical defenses, making them unsuitable for applications demanding strict safety assurances.
In this work, we introduce C-SafeGen, the first certification framework for bounding safety risks in LLM generations. C-SafeGen is model-agnostic, enabling its application to both open-source and closed-source LLMs in a black-box setting. We establish theoretical guarantees that, given a specific model configuration, C-SafeGen can compute high-probability upper bounds on safety risks under mild assumptions. Furthermore, C-SafeGen provides a principled mechanism to derive valid decoding configurations that ensure compliance with a specified risk threshold.
To complement this certification framework, we propose Certifiably Safe Claim-based Stream Decoding (CSD), a novel decoding algorithm that enforces provable safety constraints during generation. CSD dynamically adjusts token sampling strategies using KV-cache mechanisms and a guardrail model, ensuring fluency and coherence while maintaining certified safety bounds.
We validate C-SafeGen and CSD through extensive empirical evaluations on standard safety benchmarks. Our results demonstrate that C-SafeGen yields tight and reliable safety risk estimates, effectively bounding empirical risks with minimal gaps. Additionally, CSD significantly reduces unsafe generations while preserving high-quality outputs. These findings establish C-SafeGen and CSD as foundational tools for the deployment of provably safe LLMs in real-world applications.
Safety Decoding. Safety decoding techniques enforce constraints on token selection during generation, proactively mitigating unsafe outputs. Notable approaches include paraphrasing and retokenization defenses [16] against adversarial optimization attacks, as well as rewindable generation strategies like RAIN [21], which allow models to self-evaluate and modify unsafe outputs dynamically. Jailbreak resilience techniques have also been explored, including in-context demonstrations [41], system-prompt self-reminders [42], and contrastive decoding methods [44] that adjust token probability distributions to suppress adversarial prompts. While these approaches enhance LLM robustness, they lack formal guarantees on safety performance, making their efficacy difficult to quantify and validate across diverse deployment scenarios.
Conformal Prediction for Safety. Conformal prediction is a well-established statistical framework for constructing prediction sets with provable coverage guarantees [39, 38, 20, 46]. Recent advancements in conformal risk control [6, 3, 4, 31] extend these techniques to risk-sensitive applications by providing high-confidence upper bounds for black-box models under exchangeability assumptions. However, despite its success in risk-sensitive domains such as medical diagnostics and autonomous systems, conformal analysis has yet to be adapted for LLM safety certification. Our work bridges this gap by leveraging conformal techniques to construct provable safety risk bounds for LLMs, enabling rigorous certification frameworks applicable across both open-source and closed-source models.

Figure 1: C-SafeGen comprises (I) a claim-based stream decoding algorithm (CSD) and (II) a safety risk certification framework. The CSD algorithm utilizes an off-the-shelf guardrail model G to monitor sequentially generated claims, flagging unsafe claims when they exceed a predefined threshold . When such an event occurs, the unsafe claim is backtracked and resampled. Additionally, CSD employs auxiliary safety decoding strategies to enable safe resampling if claim generation stagnates beyond a tolerance threshold . The safety risk certification framework provides two types of guarantees: (1) Given a CSD configuration , the generated output is guaranteed to achieve a conformal safety risk , as established in Theorem 1; (2) If the goal is to attain an expected safety risk , any CSD configuration within the set , as specified in Theorem 2, can ensure this objective.
3 C-SafeGen
In this section, we formalize the problem of ensuring safety in LLM generation through a rigorous certification framework. We introduce a safety guardrail model that assesses the risk of generated outputs and propose a SafeGen protocol to regulate the generation process. The core objective is to quantify and control the safety risk associated with LLM outputs by defining a risk function based on the guardrail model. To achieve this, we establish two levels of certification: (1) an upper bound on the safety risk for a given generation configuration and (2) a certified set of SafeGen configurations that maintain a specified nominal risk threshold. These guarantees provide a principled foundation for certifying the safety of LLM-generated content. We provide an overview in Figure 1.
3.1 Problem setup
Consider a fixed language model parameterized by , which maps the input text space to the generation text space . Specifically, given an input prompt , the language model defines a conditional probability distribution over possible output texts, denoted as .
To assess and regulate the safety of LLM-generated content, we introduce a fixed safety guardrail model , which maps input-output pairs to subsets of the safety category space (e.g., violence, sexual, group hate, safe). The guardrail model acts as a classifier that categorizes model outputs into predefined safety risk levels.
Safety Risk Function. To formally quantify the safety risk associated with an LLM generation given an input , we define a safety risk function based on the guardrail model :
This function assigns a risk value between 0 and 1, where a value closer to 1 indicates a higher likelihood that the generated output is unsafe, as determined by the guardrail model.
SafeGen Protocol. We define a exitSafeGen protocol as a randomized function parameterized by a generation configuration . Given an input , the protocol produces a generated output , adhering to specific decoding strategies and safety measures encapsulated in .
The expected safety risk for a given input x under the SafeGen protocol is formulated as:
This formulation captures the probability of generating an unsafe output under the specified generation configuration .
C-SafeGen provides two levels of safety risk certification: (1) Safety risk upper bound certification: Given a specific generation configuration , C-SafeGen establishes a high-confidence upper bound on the safety risk. (2) SafeGen configuration certification for nominal safety risk: Given a nominal risk threshold r, C-SafeGen identifies the set of generation configurations that ensure compliance with the specified safety risk level. These certifications enable robust safety evaluations of LLM outputs, facilitating safer and more controlled language generation processes.
3.2 Safety risk certification
In this part, we formulate the approaches to achieving the two levels of safety risk certification in two formal statements, respectively.
Theorem 1 (Safety risk upper bound certification). Given a SafeGen protocol with generation configuration , C-SafeGen guarantees that:
where the high-probability risk upper bound , the so-called conformal safety generation risk, is given by:
with as the partial inverse of , and as the inverse of binomial cumulative distribution function (CDF).
Remarks (Remark of Theorem 1). The upper bound on the safety risk provided by Theorem 1 is derived under a high-probability guarantee, ensuring that the true risk does not exceed with probability at least . This bound is computed using two distinct finite-sample-valid approaches: one based on the inversion of a likelihood-ratio function and another utilizing the binomial CDF. The combination of these two approaches ensures robustness in cases where one bound is tighter than the other, effectively balancing statistical efficiency and coverage.
Theorem 2 (SafeGen configuration certification for nominal safety risk). Given a nominal safety risk r, C-SafeGen can certify a configuration set such that each configuration in is guaranteed to keep the generation risk below . Namely,
where the valid SafeGen configuration set is given by family-wise error rate control with where is the p-value of the null hypothesis: (j index all feasible SafeGen config) and can be computed by finite-sample valid bounds as shown in Theorem 1.
Remarks (Remark of Theorem 2). Theorem 2 extends the safety certification from individual configurations to a set of SafeGen configurations while controlling the family-wise error rate (FWER). By leveraging hypothesis testing with valid p-values, the theorem constructs a confidence set that guarantees all configurations within it maintain risk below the nominal threshold . The use of family-wise error control, particularly through a summation constraint on , ensures that the overall probability of incorrectly certifying an unsafe configuration remains within the desired tolerance level .
We leave the complete proofs to Section A.
4 SafeGen via Claim-based streaming guardrail
4.1 CSD: Claim-Based Safe Decoding
Consider a fixed safety/hallucination guardrail model , which maps the joint input-output space to a set of predefined safety/hallucination categories (e.g., “violence,” “sexual,”
Algorithm 1 Claim-based stream decoding algorithm
Require: Input prompt x, output text length N, LLM , Claim critical point ClaimPoint( , ), Guardrail model G, Claim backtrack probability , safe resampling function SafeResample
1: 2: counter 0 3: for n = 1 to N do 4: if ClaimPoint(x, ) then 5: 6: else 7: end if 8: counter counter + 1 9: if Uniform(0, 1) < then 10: , continue 11: end if 12: if then 13: 14: else 15: 16: end if 17: end for 18: return
“group hate,” “safe”). Let be a language model parameterized by , defining a conditional distribution over the output space given an input prompt . That is, the model assigns probability mass to different outputs as .
Our goal is to develop a SafeGen protocol parameterized with that achieves minimal safety risk. Formally, we aim to:
where denotes the set of acceptable categories under the guardrail model (e.g., for a safety guardrail). This objective seeks the highest-likelihood output from that remains within the feasibility set imposed by G. While rejection sampling could be used to enforce this constraint, it is often computationally infeasible.
4.1.1 Claim-Based Decoding
To improve efficiency, we introduce a claim-based approach. Let be a claim partition model, which decomposes an output into a set of independent claims. This leads to a stronger decoding constraint:
This formulation ensures that every claim within y is individually verified against the guardrail model.
4.1.2 Claim Backtrack Probability Function
To control decoding efficiency and safety, we define the claim backtrack probability function:
where regulates the trade-off between decoding speed and adherence to the guardrail: strictly enforces Eq. equation 6. reduces to greedy decoding. Intermediate values provide a smoothed trade-off, considering both the consistency of and its overlap with .
4.1.3 Claim Critical Point Detection
Unlike prior methods that prompt LLMs to extract claims [27, 28], we propose an efficient structural approach based on termination indicators. We define a set of claim termination tokens (e.g., newline, period) and identify a claim boundary when any termination token's probability exceeds . To prevent excessive segmentation, we enforce a minimum claim length :
ClaimPoint(x, ) = .
(8)
This method ensures computational efficiency while maintaining robust claim detection.
4.1.4 Safe resampling for robust decoding
To enhance robustness and mitigate adversarial attacks, we introduce safe resampling techniques inspired by SmoothLLM [34]. Unlike prior approaches that insert high-perplexity substrings at inference time, we directly perturb the KV cache in the ongoing decoding process using: Random masking/permutation of hidden states, Gaussian noise injection into KV-cache representations, Structured perturbations for controlled diversity.
These techniques enhance sampling diversity while preserving alignment with the guardrail model.
4.1.5 Computational efficiency
To enhance computational efficiency, we implement a KV-cache mechanism for the guardrail model. Specifically, the key-value (KV) pairs corresponding to previously verified claims can be stored, allowing efficient backtracking without recomputing the entire sequence.
Formally, let denote the cached representations for the sequence , and define the backtracking operation as follows:
This ensures that upon backtracking, only the key-value pairs corresponding to the current claim are erased, while maintaining the cached representations for verified claims.
4.2 Analysis of CSD algorithm
Definition 1 (Restricted output distribution). Let be the distribution over feasible output space . Let be a guardrail model where 1 denotes desired output and 0 denotes undesired output. Let be a restricted output distribution of by guardrail with the formulation:
Remarks. The restricted output distribution represents the renormalized probability mass of the feasible output distribution , conditioned on the constraint imposed by the guardrail model . This ensures that only outputs classified as desired ( ) contribute to the final distribution. The denominator acts as a normalizing constant, ensuring that remains a valid probability distribution.
Definition 2 (Claim). An output claim is defined as a sequence of tokens that delivers complete semantics, which is judged by a claim discriminator . Specifically, , and , implicates that the sequence is a claim.
Remarks. The claim discriminator C plays a crucial role in identifying semantically complete claims within a sequence. The definition ensures that a claim is an isolated segment where the beginning and end are both recognized by C, while the intermediate segments do not form independent claims. This property is essential for structured generation and for enforcing guardrails at the claim level.
Assumption 4.1 (Claim risk cascade). Consider an output sequence o which consists of a sequence of N claims by claim discriminator We assume that the risk of prefix claims implicates the risk of output judged by guardrail :
Remarks. The claim risk cascade assumption formalizes the idea that the presence of an undesired claim in a sequence guarantees that the entire sequence is also undesired. This assumption aligns with the intuition that risks in intermediate steps propagate forward, affecting the final judgment by the guardrail model G. This is a conservative approach that simplifies analysis while ensuring safety in controlled generation.
Theorem 3 (Algorithm 1 recovers restricted output distribution). Under the claim risk cascade assumption as Assumption 4.1, if there exists at least one desired output judged by guardrail G, the output distribution of the claim-based decoding streaming algorithm in Algorithm 1 (without safe resampling) is identical to the restricted output distribution as Definition 1.
Remarks. This theorem establishes that the claim-based decoding streaming algorithm produces outputs that exactly match the restricted output distribution . The key condition for this result is

(a) AdvBench – Llama-3.1-8B

(b) AdvBench – Llama-3.1-13B

(c) JailbreakBench – Llama-3.1-8B

(d) JailbreakBench – Llama-3.1-13B
Figure 2: Evaluation of conformal safety risk (upper bound from Theorem 1) and empirical safety risk (mean risk on sampled test sets) across two benchmarks—AdvBench and JailbreakBench—using Llama-3.1 models (8B and 13B) with ShieldGemma-9B as the guardrail. Results show that (1) conformal risk bounds are valid and tight; and (2) our CSD method consistently achieves the lowest safety risk. Note: Grey bars result from overlapping dots.
the existence of at least one feasible sequence that satisfies the guardrail G. The theorem is significant because it ensures that the decoding algorithm does not introduce biases or distortions beyond those imposed by the guardrail, thereby preserving the original probability structure of the restricted output space.
5 Evaluation
5.1 Evaluation setup
Dataset & Models. As AdvBench [50] and JailbreakBench [8] are widely used for evaluating LLM safety [23, 9, 26], we adopt it as our primary evaluation dataset.
For text generation, we consider LLMs Llama-3.1-8B, and Llama-3.1-13B as inference models. Additionally, we append adversarial suffixes to the user query to jailbreak the model, creating a more challenging safety evaluation scenario. These adversarial suffixes are optimized using the GCG attack [50] on the corresponding inference model as target models.
Metrics. Without specification, we employ LlamaGuard3-8B [10] as the guardrail model G and use the unsafety probability predicted by it as the safety risk function . Additionally, we also consider ShieldGemma-9B as guardrail models for guardrail comparisons.
Baselines. We consider four baselines for safe generation: (1) Vanilla generation, using a temperature of 1.0; (2) Self-reminder safety prompt (Reminder) [42], which incorporates a system safety prompt and an additional reminder prompt after the user query to encourage safer generation; (3) Safety-Opt [48], which optimizes a soft safety prompt prefix to guide the model toward safer response patterns; (4) Best-of-N [35], which selects the safest response from a set of 10 generated outputs; and (5) SafeDecoding (SafeDec) [44], which uses a safety-aware contrastive decoding strategy for LLMs to generate helpful and harmless responses to user queries.

(a) AdvBench – Llama-3.1-8B

(b) AdvBench – Llama-3.1-13B

(c) JailbreakBench – Llama-3.1-8B

(d) JailbreakBench – Llama-3.1-13B
Figure 3: Evaluation of SafeGen configurations with nominal safety risk 0.10 (Theorem 2). Valid configurations remain below the nominal risk, and larger backtrack thresholds yield lower and more stable risks. Note: The grey bar results from overlapping grey dots.
5.2 Safety risk upper bound certification
Figure 2 presents a comparative evaluation of conformal safety risk (theoretical upper bound) and empirical safety risk (mean observed risk) across six SafeGen methods on two safety benchmarks, AdvBench and JailbreakBench, using Llama-3.1 models (8B and 13B) with ShieldGemma-9B as the guardrail. Across all settings, we observe that CSD consistently achieves the lowest safety risks—both conformal and empirical—indicating its superior capability in reducing unsafe generations under formal guarantees. The conformal risk bounds are generally tight, validating the reliability of the theoretical risk estimation across different methods and model sizes. Notably, methods such as SafeDec and Safety-Opt also reduce risk substantially compared to the vanilla baseline, but fail to match the low-risk performance of CSD. The trend persists across both model scales and benchmarks, underscoring the robustness of CSD's improvements in safety under adversarial and jailbreak-style attacks.
In addition to method-wise comparisons, the results also reveal consistent trends across model sizes. Specifically, the larger model (Llama-3.1-13B) does not uniformly outperform the smaller 8B variant in safety risk reduction. In some cases—such as under Reminder and Best-of-N—the 13B model exhibits slightly higher safety risk than the 8B model, suggesting that scaling up model size alone does not guarantee improved safety under adversarial or conformal evaluation. This highlights the importance of method design (e.g., CSD) over sheer model capacity in achieving reliable and provably safe generations.
5.3 SafeGen configuration certification for nominal safety risk
Figure 3 illustrates the validity of SafeGen configurations as certified by Theorem 2, and investigates how the backtrack threshold affects the empirical safety risk across different benchmarks and model sizes. The dashed green line indicates the nominal safety risk bound (set to 0.10), while the grey markers represent empirical safety risks under varying values of . We highlight three main observations: (1) Certified safety guarantees hold across all settings. For every evaluated configuration, the empirical safety risks remain strictly below the nominal risk threshold, confirming the high-probability validity guaranteed by Theorem 2. This supports the theoretical soundness of the certification framework across both AdvBench and JailbreakBench. (2) Higher leads to lower safety risk. Across all plots, increasing the backtrack threshold consistently reduces empirical safety risk. This trend is consistent for both Llama-3.1-8B and Llama-3.1-13B, demonstrating that SafeGen with a higher allows more cautious decoding behavior and safer outputs. (3) Risk stability improves with larger . We also observe a reduction in the variability of empirical safety risk as increases. This indicates that larger thresholds not only yield safer generations but also improve the reliability and consistency of safety performance across different test samples.
These results demonstrate that SafeGen provides strong empirical and theoretical safety guarantees, with all evaluated configurations maintaining risks below the specified nominal bound. Adjusting the backtrack threshold is an effective mechanism to improve both the magnitude and stability of safety risk, and can be tuned independently of model scale. Together, these findings underscore the importance of principled decoding strategies—such as SafeGen—for deploying LLMs in safety-critical applications.
5.4 Safety vs. decoding efficiency
Figure 4 compares the runtime per instance (grey bars) and the mean safety risk (purple bars) for different SafeGen methods: Best-of-N, CSD, and CSD+KV Cache. The results provide insights into the trade-offs between computational efficiency and safety performance. We have the following observations: (1) Best-of-N incurs the highest runtime, exceeding 40 seconds per instance, while also exhibiting the highest mean safety risk. This indicates that generating multiple completions and selecting the safest one is computationally expensive without significantly improving safety. (2) CSD achieves a substantial reduction in runtime (approximately 7 seconds per instance) while also lowering the mean safety risk compared to Best-of-N. This demonstrates the efficiency of the CSD method in balancing safety and speed. (3) CSD+KV Cache further reduces the runtime (below 5 seconds per instance) while maintaining a similar mean safety risk to CSD. This highlights the effectiveness of KV caching in accelerating SafeGen methods without compromising safety.
The results indicate that CSD+KV Cache provides the best trade-off between efficiency and safety, significantly reducing

Figure 4: Evaluation of decoding runtime and mean safety risk for the strongest baseline Best-of-N, our proposed SafeGen protocol CSD, and CSD with KV cache. CSD achieves a better efficiency-safety tradeoff than Best-of-N. KV cache preserves safety while significantly reducing decoding time.
computational cost while maintaining low safety risk. Best-of-N, despite being a simple approach, is highly inefficient, making it impractical for real-time applications. These findings emphasize the importance of optimizing SafeGen methods for both speed and reliability.
6 Conclusion
The rapid adoption of open-source LLMs underscores the urgent need for rigorous safety guarantees in their generations, particularly in high-stakes applications. Existing empirical defenses, including RLHF, guardrails, and decoding-time interventions, lack formal assurances, limiting their reliability against adversarial exploits. To address this gap, we introduced C-SafeGen, a model-agnostic certification framework that provides theoretical risk bounds and enables the enforcement of provable safety constraints. Complemented by our novel CSD decoding algorithm, C-SafeGen ensures both safety and fluency in generated text. Empirical evaluations confirm the efficacy of our approach, demonstrating its potential as a robust foundation for the deployment of provably safe LLMs.
Acknowledgements
This work is partially supported by DARPA Cooperative Agreement HR00112520013, the National Science Foundation under grant No. 1910100, No. 2046726, NSF AI Institute ACTION No. IIS-2229876, DARPA TIAMAT No. 80321, the National Aeronautics and Space Administration (NASA) under grant No. 80NSSC20M0229, ARL Grant W911NF-23-2-0137, Alfred P. Sloan Fellowship, the research grant from eBay, AI Safety Fund, Virtue AI, and Schmidt Science.
References
[1] Ai content moderation by microsoft azure. https://azure.microsoft.com/en-us/products/ai-services/ai-content-safety.
[2] Detoxify by unitary ai. https://github.com/unitaryai/detoxify.
[3] Anastasios N Angelopoulos, Stephen Bates, Emmanuel J Candès, Michael I Jordan, and Lihua Lei. Learn then test: Calibrating predictive algorithms to achieve risk control. arXiv preprint arXiv:2110.01052, 2021.
[4] Anastasios N Angelopoulos, Stephen Bates, Adam Fisch, Lihua Lei, and Tal Schuster. Conformal risk control. arXiv preprint arXiv:2208.02814, 2022.
[5] Luke Bates and Iryna Gurevych. Like a good nearest neighbor: Practical content moderation with sentence transformers. arXiv e-prints, pages arXiv–2302, 2023.
[6] Stephen Bates, Anastasios Angelopoulos, Lihua Lei, Jitendra Malik, and Michael Jordan. Distribution-free, risk-controlling prediction sets. Journal of the ACM (JACM), 68(6):1–34, 2021.
[7] Vidmantas Bentkus. On hoeffding's inequalities. 2004.
[8] Patrick Chao, Edoardo Debenedetti, Alexander Robey, Maksym Andriushchenko, Francesco Croce, Vikash Sehwag, Edgar Dobriban, Nicolas Flammarion, George J. Pappas, Florian Tramèr, Hamed Hassani, and Eric Wong. Jailbreakbench: An open robustness benchmark for jailbreaking large language models. In NeurIPS Datasets and Benchmarks Track, 2024.
[9] Patrick Chao, Alexander Robey, Edgar Dobriban, Hamed Hassani, George J Pappas, and Eric Wong. Jailbreaking black box large language models in twenty queries. arXiv preprint arXiv:2310.08419, 2023.
[10] Abhimanyu Dubey, Abhinav Jauhri, Abhinav Pandey, Abhishek Kadian, Ahmad Al-Dahle, Aiesha Letman, Akhil Mathur, Alan Schelten, Amy Yang, Angela Fan, et al. The llama 3 herd of models. arXiv preprint arXiv:2407.21783, 2024.
[11] Shaona Ghosh, Prasoon Varshney, Erick Galinkin, and Christopher Parisien. Aegis: Online adaptive ai content safety moderation with ensemble of llm experts. arXiv preprint arXiv:2404.05993, 2024.
[12] Daya Guo, Dejian Yang, Haowei Zhang, Junxiao Song, Ruoyu Zhang, Runxin Xu, Qihao Zhu, Shirong Ma, Peiyi Wang, Xiao Bi, et al. Deepseek-r1: Incentivizing reasoning capability in llms via reinforcement learning. arXiv preprint arXiv:2501.12948, 2025.
[13] Wassily Hoeffding. Probability inequalities for sums of bounded random variables. The collected works of Wassily Hoeffding, pages 409–426, 1994.
[14] Sture Holm. A simple sequentially rejective multiple test procedure. Scandinavian journal of statistics, pages 65–70, 1979.
[15] Hakan Inan, Kartikeya Upasani, Jianfeng Chi, Rashi Rungta, Krithika Iyer, Yuning Mao, Michael Tontchev, Qing Hu, Brian Fuller, Davide Testuggine, et al. Llama guard: Llm-based input-output safeguard for human-ai conversations. arXiv preprint arXiv:2312.06674, 2023.
[16] Neel Jain, Avi Schwarzschild, Yuxin Wen, Gowthami Somepalli, John Kirchenbauer, Ping-yeh Chiang, Micah Goldblum, Aniruddha Saha, Jonas Geiping, and Tom Goldstein. Baseline defenses for adversarial attacks against aligned language models. arXiv preprint arXiv:2309.00614, 2023.
[17] Mintong Kang, Chejian Xu, and Bo Li. Advwave: Stealthy adversarial jailbreak attack against large audio-language models. arXiv preprint arXiv:2412.08608, 2024.
[18] Deepak Kumar, Yousef AbuHashem, and Zakir Durumeric. Watch your language: Investigating content moderation with large language models. arXiv preprint arXiv:2309.14517, 2024.
[19] Alyssa Lees, Vinh Q Tran, Yi Tay, Jeffrey Sorensen, Jai Gupta, Donald Metzler, and Lucy Vasserman. A new generation of perspective api: Efficient multilingual character-level transformers. In Proceedings of the 28th ACM SIGKDD Conference on Knowledge Discovery and Data Mining, pages 3197–3207, 2022.
[20] Jing Lei, James Robins, and Larry Wasserman. Distribution-free prediction sets. Journal of the American Statistical Association, 108(501):278–287, 2013.
[21] Yuhui Li, Fangyun Wei, Jinjing Zhao, Chao Zhang, and Hongyang Zhang. Rain: Your language models can align themselves without finetuning. arXiv preprint arXiv:2309.07124, 2023.
[22] Zi Lin, Zihan Wang, Yongqi Tong, Yangkun Wang, Yuxin Guo, Yujia Wang, and Jingbo Shang. Toxicchat: Unveiling hidden challenges of toxicity detection in real-world user-ai conversation. arXiv preprint arXiv:2310.17389, 2023.
[23] Xiaogeng Liu, Nan Xu, Muhao Chen, and Chaowei Xiao. Autodan: Generating stealthy jailbreak prompts on aligned large language models. arXiv preprint arXiv:2310.04451, 2023.
[24] Huan Ma, Changqing Zhang, Huazhu Fu, Peilin Zhao, and Bingzhe Wu. Adapting large language models for content moderation: Pitfalls in data engineering and supervised fine-tuning. arXiv preprint arXiv:2310.03400, 2023.
[25] Todor Markov, Chong Zhang, Sandhini Agarwal, Florentine Eloundou Nekoul, Theodore Lee, Steven Adler, Angela Jiang, and Lilian Weng. A holistic approach to undesired content detection in the real world. In Proceedings of the AAAI Conference on Artificial Intelligence, volume 37, pages 15009–15018, 2023.
[26] Anay Mehrotra, Manolis Zampetakis, Paul Kassianik, Blaine Nelson, Hyrum Anderson, Yaron Singer, and Amin Karbasi. Tree of attacks: Jailbreaking black-box llms automatically. arXiv preprint arXiv:2312.02119, 2023.
[27] Christopher Mohri and Tatsunori Hashimoto. Language models with conformal factuality guarantees. arXiv preprint arXiv:2402.10978, 2024.
[28] Jingwei Ni, Minjing Shi, Dominik Stammbach, Mrinmaya Sachan, Elliott Ash, and Markus Leippold. Afacta: Assisting the annotation of factual claim detection with reliable llm annotators. arXiv preprint arXiv:2402.11073, 2024.
[29] OpenAI, :, Josh Achiam, Steven Adler, Sandhini Agarwal, Lama Ahmad, Ilge Akkaya, Florencia Leoni Aleman, Diogo Almeida, Janko Altenschmidt, Sam Altman, Shyamal Anadkat, Red Avila, Igor Babuschkin, Suchir Balaji, Valerie Balcom, Paul Baltescu, Haiming Bao, Mo Bavarian, Jeff Belgium, Irwan Bello, Jake Berdine, Gabriel Bernadett-Shapiro, Christopher Berner, Lenny Bogdonoff, Oleg Boiko, Madelaine Boyd, Anna-Luisa Brakman, Greg Brockman, Tim Brooks, Miles Brundage, Kevin Button, Trevor Cai, Rosie Campbell, Andrew Cann, Brittany Carey, Chelsea Carlson, Rory Carmichael, Brooke Chan, Che Chang, Fotis Chantzis, Derek Chen, Sully Chen, Ruby Chen, Jason Chen, Ben Chess, Chester Cho, Casey Chu, Hyung Won Chung, Dave Cummings, Jeremiah Currier, Yunxing Dai, Cory Decareaux, Thomas Degry, Noah Deutsch, Damien Deville, Arka Dhar, David Dohan, Steve Dowling, Sheila Dunning, Adrien Ecoffet, Atty Eleti, Tyna Eloundou, David Farhi, Liam Fedus, Niko Felix, Simón Posada Fishman, Juston Forte, Isabella Fulford, Leo Gao, Elie Georges, Christian Gibson, Vik Goel, Tarun Gogineni, Gabriel Goh, Rapha Gontijo-Lopes, Jonathan Gordon, Morgan Grafstein, Scott Gray, Ryan Greene, Joshua Gross, Shixiang Shane Gu, Yufei
Guo, Chris Hallacy, Jesse Han, Jeff Harris, Yuchen He, Mike Heaton, Johannes Heidecke, Chris Hesse, Alan Hickey, Wade Hickey, Peter Hoeschele, Brandon Houghton, Kenny Hsu, Shengli Hu, Xin Hu, Joost Huizinga, Shantanu Jain, Shawn Jain, Joanne Jang, Angela Jiang, Roger Jiang, Haozhun Jin, Denny Jin, Shino Jomoto, Billie Jonn, Heewoo Jun, Tomer Kaftan, Łukasz Kaiser, Ali Kamali, Ingmar Kanitscheider, Nitish Shirish Keskar, Tabarak Khan, Logan Kilpatrick, Jong Wook Kim, Christina Kim, Yongjik Kim, Hendrik Kirchner, Jamie Kiros, Matt Knight, Daniel Kokotajlo, Łukasz Kondraciuk, Andrew Kondrich, Aris Konstantinidis, Kyle Kosic, Gretchen Krueger, Vishal Kuo, Michael Lampe, Ikai Lan, Teddy Lee, Jan Leike, Jade Leung, Daniel Levy, Chak Ming Li, Rachel Lim, Molly Lin, Stephanie Lin, Mateusz Litwin, Theresa Lopez, Ryan Lowe, Patricia Lue, Anna Makanju, Kim Malfacini, Sam Manning, Todor Markov, Yaniv Markovski, Bianca Martin, Katie Mayer, Andrew Mayne, Bob McGrew, Scott Mayer McKinney, Christine McLeavey, Paul McMillan, Jake McNeil, David Medina, Aalok Mehta, Jacob Menick, Luke Metz, Andrey Mishchenko, Pamela Mishkin, Vinnie Monaco, Evan Morikawa, Daniel Mossing, Tong Mu, Mira Murati, Oleg Murk, David Mély, Ashvin Nair, Reiichiro Nakano, Rajeev Nayak, Arvind Neelakantan, Richard Ngo, Hyeonwoo Noh, Long Ouyang, Cullen O'Keefe, Jakub Pachocki, Alex Paino, Joe Palermo, Ashley Pantuliano, Giambattista Parascandolo, Joel Parish, Emy Parparita, Alex Passos, Mikhail Pavlov, Andrew Peng, Adam Perelman, Filipe de Avila Belbute Peres, Michael Petrov, Henrique Ponde de Oliveira Pinto, Michael, Pokorny, Michelle Pokrass, Vitchyr Pong, Tolly Powell, Alethea Power, Boris Power, Elizabeth Proehl, Raul Puri, Alec Radford, Jack Rae, Aditya Ramesh, Cameron Raymond, Francis Real, Kendra Rimbach, Carl Ross, Bob Rotsted, Henri Roussez, Nick Ryder, Mario Saltarelli, Ted Sanders, Shibani Santurkar, Girish Sastry, Heather Schmidt, David Schnurr, John Schulman, Daniel Selsam, Kyla Sheppard, Toki Sherbakov, Jessica Shieh, Sarah Shoker, Pranav Shyam, Szymon Sidor, Eric Sigler, Maddie Simens, Jordan Sitkin, Katarina Slama, Ian Sohl, Benjamin Sokolowsky, Yang Song, Natalie Staudacher, Felipe Petroski Such, Natalie Summers, Ilya Sutskever, Jie Tang, Nikolas Tezak, Madeleine Thompson, Phil Tillet, Amin Tootoonchian, Elizabeth Tseng, Preston Tuggle, Nick Turley, Jerry Tworek, Juan Felipe Cerón Uribe, Andrea Vallone, Arun Vijayvergiya, Chelsea Voss, Carroll Wainwright, Justin Jay Wang, Alvin Wang, Ben Wang, Jonathan Ward, Jason Wei, CJ Weinmann, Akila Welihinda, Peter Welinder, Jiayi Weng, Lilian Weng, Matt Wiethoff, Dave Willner, Clemens Winter, Samuel Wolrich, Hannah Wong, Lauren Workman, Sherwin Wu, Jeff Wu, Michael Wu, Kai Xiao, Tao Xu, Sarah Yoo, Kevin Yu, Qiming Yuan, Wojciech Zaremba, Rowan Zellers, Chong Zhang, Marvin Zhang, Shengjia Zhao, Tianhao Zheng, Juntang Zhuang, William Zhuk, and Barret Zoph. Gpt-4 technical report, 2023.
[30] Long Ouyang, Jeffrey Wu, Xu Jiang, Diogo Almeida, Carroll Wainwright, Pamela Mishkin, Chong Zhang, Sandhini Agarwal, Katarina Slama, Alex Ray, et al. Training language models to follow instructions with human feedback. Advances in neural information processing systems, 35:27730–27744, 2022.
[31] Victor Quach, Adam Fisch, Tal Schuster, Adam Yala, Jae Ho Sohn, Tommi S Jaakkola, and Regina Barzilay. Conformal language modeling. arXiv preprint arXiv:2306.10193, 2023.
[32] Rafael Rafailov, Archit Sharma, Eric Mitchell, Christopher D Manning, Stefano Ermon, and Chelsea Finn. Direct preference optimization: Your language model is secretly a reward model. Advances in Neural Information Processing Systems, 36, 2024.
[33] Traian Rebedea, Razvan Dinu, Makesh Sreedhar, Christopher Parisien, and Jonathan Cohen. Nemo guardrails: A toolkit for controllable and safe llm applications with programmable rails. arXiv preprint arXiv:2310.10501, 2023.
[34] Alexander Robey, Eric Wong, Hamed Hassani, and George J Pappas. Smoothllm: Defending large language models against jailbreaking attacks. arXiv preprint arXiv:2310.03684, 2023.
[35] Hanshi Sun, Momin Haider, Ruiqi Zhang, Huitao Yang, Jiahao Qiu, Ming Yin, Mengdi Wang, Peter Bartlett, and Andrea Zanette. Fast best-of-n decoding via speculative rejection. arXiv preprint arXiv:2410.20290, 2024.
[36] Fei Tan, Yifan Hu, Kevin Yen, and Changwei Hu. Bert-beta: A proactive probabilistic approach to text moderation. arXiv preprint arXiv:2109.08805, 2021.
[37] Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier Martinet, Marie-Anne Lachaux, Timothée Lacroix, Baptiste Rozière, Naman Goyal, Eric Hambro, Faisal Azhar, et al. Llama: Open and efficient foundation language models. arXiv preprint arXiv:2302.13971, 2023.
[38] Vladimir Vovk, Alexander Gammerman, and Glenn Shafer. Algorithmic learning in a random world, volume 29. Springer, 2005.
[39] Volodya Vovk, Alexander Gammerman, and Craig Saunders. Machine-learning applications of algorithmic randomness. 1999.
[40] Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Fei Xia, Ed Chi, Quoc V Le, Denny Zhou, et al. Chain-of-thought prompting elicits reasoning in large language models. Advances in neural information processing systems, 35:24824–24837, 2022.
[41] Zeming Wei, Yifei Wang, Ang Li, Yichuan Mo, and Yisen Wang. Jailbreak and guard aligned language models with only few in-context demonstrations. arXiv preprint arXiv:2310.06387, 2023.
[42] Yueqi Xie, Jingwei Yi, Jiawei Shao, Justin Curl, Lingjuan Lyu, Qifeng Chen, Xing Xie, and Fangzhao Wu. Defending chatgpt against jailbreak attack via self-reminders. Nature Machine Intelligence, 5(12):1486–1496, 2023.
[43] Chejian Xu, Mintong Kang, Jiawei Zhang, Zeyi Liao, Lingbo Mo, Mengqi Yuan, Huan Sun, and Bo Li. Advweb: Controllable black-box attacks on vlm-powered web agents. arXiv preprint arXiv:2410.17401, 2024.
[44] Zhangchen Xu, Fengqing Jiang, Luyao Niu, Jinyuan Jia, Bill Yuchen Lin, and Radha Poovendran. Safedecoding: Defending against jailbreak attacks via safety-aware decoding. arXiv preprint arXiv:2402.08983, 2024.
[45] Wenkai Yang, Xiaohan Bi, Yankai Lin, Sishuo Chen, Jie Zhou, and Xu Sun. Watch out for your agents! investigating backdoor threats to llm-based agents. arXiv preprint arXiv:2402.11208, 2024.
[46] Yachong Yang and Arun Kumar Kuchibhotla. Finite-sample efficient conformal prediction. arXiv preprint arXiv:2104.13871, 2021.
[47] Zhuowen Yuan, Zidi Xiong, Yi Zeng, Ning Yu, Ruoxi Jia, Dawn Song, and Bo Li. Rigorllm: Resilient guardrails for large language models against undesired content. arXiv preprint arXiv:2403.13031, 2024.
[48] Chujie Zheng, Fan Yin, Hao Zhou, Fandong Meng, Jie Zhou, Kai-Wei Chang, Minlie Huang, and Nanyun Peng. Prompt-driven llm safeguarding via directed representation optimization. arXiv preprint arXiv:2401.18018, 2024.
[49] Xuhui Zhou. Challenges in automated debiasing for toxic language detection. University of Washington, 2020.
[50] Andy Zou, Zifan Wang, J Zico Kolter, and Matt Fredrikson. Universal and transferable adversarial attacks on aligned language models. arXiv preprint arXiv:2307.15043, 2023.
A Omitted proofs
A.1 Proof of Theorem 1
Proof of Theorem 1. The proof sketch follows [3]. Since the risk function is upper bounded by 1, we can apply a tighter version of Hoeffding's inequality [13] for :
Also, applying Bentkus inequality [7], we have:
Combining Equations (12) and (13), we have:
Or equivalently, given uncertainty , we have:
which leads to the following by formulating an inverse function:
A.2 Proof of Theorem 2
Proof of Theorem 2. The proof follows [14]. We consider independent hypothesis test corresponding to the Null hypothesis. By the Bonferroni method, each test is performed at a significance level of . Therefore, The probability of not making a Type I error in a single test is . The probability of making no Type I error in all tests is . The probability of making at least one Type I error (i.e., FWER) is the complement of making no Type I errors, which is . Therefore, we prove that the familywise error rate is for Bonferroni correction. Thus, going back to the risk guarantee, we conclude the proof.
A.3 Proof of Theorem 3
Proof of Theorem 3. Let the output distribution by Algorithm 1 be . To show the result, we need to show that for any output sequence , .
We consider the following scenarios respectively: (1) this is an invalid output by the guardrail model: ; (2) this a valid output: .
Scenario (1): . According to CCD algorithm, such an undesired claim would always be associated with 1.0 backtrack probability in Line 4 of Algorithm 1, and thus we have . On the other hand, according to Equation (10), we always have when . Therefore, we have when .
Scenario (2): . In this scenario, we basically would like to validate that the backtrack mechanism in Lines 7-9 of Algorithm 1 does not distort the distribution.
Part (a): To show that, we first validate that the support of output distribution by CCD is identical to that of the restricted output distribution.
For any valid support in the restricted output distribution , there always exists an unrisky claim decoding path. We consider this simple claim decoding path . Since the complete output sequence o is unrisky, then each claim prefix would also be unrisky (otherwise violating the claim risk cascade assumption). Therefore, this claim decoding path is a valid instantiation of CCD algorithm.
Considering the reverse direction, for any valid support output y by CCD algorithm, it is obvious that given the acceptance of the last claim, and thus, this output is also a valid support of the restricted output distribution .
Part (b): Then, we will prove that for any valid support such that and , we have .
For ease of notation, we notate , which is a normalization factor in Equation (10). Then following the chain rule, we can compute as:
Since y is a desired output (i.e., ), each claim prefix is also desired according to the risk cascade assumption in Assumption 4.1. Then we have:
Then we analyze the point mass of output y by the CCD algorithm . We can formulate the decoding path of CCD algorithm that leads to output y as , where denotes a sequence of backtracked risky claims at time step .
Then we prove a key invariability property that
We can derive as the following:
For ease of notation, let and , then we have:
Therefore, we have:
15
☐
B Discussion and Limitation
The C-SafeGen framework is able to safeguard LLMs' practical deployment and applications against ethical and societal concerns. Existing research shows that the responses of LLMs can be biased towards some demographic groups and not be aligned with human ethics. With C-SafeGen, we can define a bias/ethics risk function and control the generation risk below a desired level. The risk guarantee provided by C-SafeGen enhances the use of LLMs, addressing societal issues and regulatory infringements. We do not expect any negative societal consequences for our work.
While C-SafeGen provides formal guarantees under mild assumptions, it currently relies on the availability of reliable external classifiers or risk estimators to define the safety risk function. The effectiveness of the certification heavily depends on the quality and coverage of these components, which may be incomplete or biased in practice. Additionally, C-SafeGen operates in a black-box setting and does not account for internal model behaviors or hidden representations that might influence safety. Finally, although C-SafeGen bounds risk on the evaluation distribution, distributional shifts at deployment time (e.g., novel user queries or emerging adversarial strategies) may compromise safety, highlighting the need for future extensions toward adaptive or online certification mechanisms.