Preprint
Article

This version is not peer-reviewed.

Bayesian NeMo Guardrails: Deterministic Posterior-Predictive Inference and Risk-Constrained Decisions

Submitted:

26 November 2026

Posted:

27 November 2026

You are already at the latest version

Abstract
Programmable guardrails offer a mechanism for constraining large-language-model applications, but a collection of detector scores does not by itself specify an uncertainty-aware decision. We formulate guardrail evaluation as posterior-predictive Bayesian risk estimation followed by a Bayes-loss decision and explicit deterministic admissibility gates. The statistical model is Bernoulli logistic regression equipped with a proper Gaussian prior: the posterior is nonconjugate, and the target decision integrates over the parameter posterior rather than substituting a point estimate. Two deterministic approximation schemes are considered. The first obtains the unique posterior mode and local curvature, projects the Gaussian Laplace approximation onto a scalar decision direction, and evaluates the resulting logistic–normal expectation by one-dimensional Gauss–Hermite quadrature. The second, intended for low-dimensional calibrators, evaluates a self-normalized Gauss–Hermite rule whose weights correct the Gaussian reference density by the original non-Gaussian posterior. We establish posterior log-concavity, curvature bounds, the scalar reduction, the corrected-quadrature identity, a ratio error bound, explicit decision regions for asymmetric loss with abstention, and approximation-induced decision-regret bounds. Safety vetoes and an external guardrail engine are modeled as restrictions on release, not as probabilistic evidence that can be overridden. The resulting software design supports NVIDIA NeMo LLMRails and IORails without modifying their core engines. The main treatment is mathematical; the software interfaces, synthetic demonstration, and verified integration scope appear in an appendix after the references. No real-world risk calibration or end-to-end RAG safety guarantee is claimed.
Keywords: 
;  ;  ;  ;  ;  ;  

1. Introduction

Guardrails for generative language systems intervene at the boundary between untrusted requests, retrieved evidence, model-produced content, and application policy. A detector can assign a score to a prompt, but a score is neither an automatic policy decision nor, without calibration, the probability of a violation. The problem becomes sharper when several detectors are combined, decision errors have asymmetric consequences, and an uncertain response may be better withheld for review than automatically allowed or blocked. The NeMo Guardrails ecosystem supplies programmable infrastructure for imposing such constraints (Rebedea et al., 2023); the present work concerns the mathematical decision layer that can be composed with that infrastructure.
A natural discriminative construction introduces a binary event H representing a well-defined policy violation and a vector x of trusted detector scores. Calibration data should then determine a predictive risk P ( H = 1 ∣ x , D ) . A point-estimate logistic score, however, ignores parameter uncertainty, which can be substantial for sparse calibration data or correlated predictors. Bayesian logistic regression gives the appropriate posterior-predictive quantity, although the logistic likelihood is not conjugate to the Gaussian prior (Bishop, 2006; Gelman et al., 2013). Numerical approximation is therefore required if general posterior integration is to remain computationally practical.
Laplace approximation is a classical deterministic approach to posterior integration (Tierney and Kadane, 1986; MacKay, 1992). Gauss-type quadrature supplies deterministic integration nodes and weights (Golub and Welsch, 1969; Gautschi, 2004); corrected importance quadrature can additionally compensate for discrepancies between a Gaussian proposal and the actual posterior. In this article, these well-established tools are assembled as a deliberately constrained decision system, with an explicit accounting of which statements are exact and which depend on numerical approximation. The method does not claim that generic nonconjugate Bayes can be integrated exactly or that Gaussian approximation alone constitutes a certified safety mechanism.
Our mathematical development is organized around four observations. First, the actual logistic–Gaussian posterior is strictly log-concave: the curvature exists, is positive definite, and has a unique mode even though exact marginalization is unavailable. Second, a Gaussian Laplace posterior collapses the risk integral to one scalar normal expectation, so costly high-dimensional quadrature is unnecessary in this backend. Third, for small parameter dimension, direct density-ratio correction under a tensor Gauss–Hermite reference permits a deterministic, non-Gaussian numerical approximation with explicit ratio-error accounting. Fourth, guardrail decisions follow from expected loss and a subsequent admissibility rule; they are not identified with thresholding a risk score alone.
  • Scope and positioning.
The intended contribution is a mathematically explicit synthesis grounded in the implementation for NeMo Guardrails, not an originality claim about Laplace methods, numerical quadrature, or Bayesian decisions. Integrated nested Laplace approximations address broader latent Gaussian model classes (Rue et al., 2009); we neither implement INLA nor claim its properties. Statistical validity requires representative labeled calibration data and detector performance that is not established merely by the existence of the software (Guo et al., 2017; Gneiting and Raftery, 2007). The released implementation and its limitations are described after the bibliography in Appendices Appendix A and Appendix B.

2. Problem Formulation and Statistical Model

2.1. Guardrail Event, Evidence and Calibration

Fix a phase ϕ ∈ { input , output } . A phase-specific detector vector is x ∈ [ 0 , 1 ] p , where the coordinates are trusted scores: for example, injection and toxicity signals for an input phase, or an unsupported-claim signal for an output phase. The vector is not generated from untrusted conversation text by the Bayesian layer; an upstream detector or application must supply it. Let H ∈ { 0 , 1 } denote a binary violation label under an operational policy. Its precise semantics must be specified before collecting data; distinct kinds of risk can otherwise be conflated.
The offline calibration sample is
D = { ( x i , y i ) : x i ∈ [ 0 , 1 ] p , y i ∈ { 0 , 1 } , i = 1 , … , n } , y i = I { H i = 1 } .
Write d = p + 1 and augment each feature vector with an intercept, z i = ( 1 , x i ⊤ ) ⊤ ∈ R d . The design matrix A ∈ R n × d has rows z i ⊤ . Conditional on θ ∈ R d , the calibration labels are modeled as independent Bernoulli random variables:
P ( H i = 1 ∣ x i , θ ) = σ ( z i ⊤ θ ) , σ ( t ) = 1 1 + exp ( − t ) .
The independence in Equation (2) concerns the calibration labels conditional on parameters and observed feature rows. It must not be confused with assuming that individual detector coordinates are independent. A logistic model can contain correlated score features; strong collinearity still affects identifiability and calibration. Nor does Equation (2) specify a dynamic latent-state filter: repeated unlabeled conversation turns are not automatically incorporated as new labeled training observations.

2.2. Nonconjugate Posterior and Predictive Decision Quantity

Let the coefficient prior be a proper multivariate Gaussian,
θ ∼ N ( m 0 , Λ − 1 ) , Λ = Λ ⊤ ≻ 0 .
The log posterior, up to an additive normalizing constant, is
ℓ ( θ ) = ∑ i = 1 n y i z i ⊤ θ − log ( 1 + e z i ⊤ θ ) − 1 2 ( θ − m 0 ) ⊤ Λ ( θ − m 0 ) .
The probability distribution of interest is not a posterior distribution over the discrete action; rather, it is the integrated risk of the violation event for a new z = ( 1 , x ⊤ ) ⊤ :
r ( z ) P ( H = 1 ∣ x , D ) = ∫ R d σ ( z ⊤ θ ) e ℓ ( θ ) d θ ∫ R d e ℓ ( θ ) d θ .
Equation (5) is the full Bayesian objective. Both deployed numerical methods approximate it deterministically; they are not exact evaluations for an arbitrary nonconjugate posterior. The distinction matters because an output such as r ( z ) = 0.9 has a probabilistic interpretation only relative to the likelihood, prior, data distribution, and detector calibration assumptions.
Figure 1. Separation between offline calibration, deterministic posterior integration, and downstream guardrail action. The numerical layer consumes trusted detector features; r ^ ( z ) is an estimated posterior-predictive violation probability, while [ L x , U x ] is a posterior credible interval for the conditional violation probability. The layer does not perform detection.
Figure 1. Separation between offline calibration, deterministic posterior integration, and downstream guardrail action. The numerical layer consumes trusted detector features; r ^ ( z ) is an estimated posterior-predictive violation probability, while [ L x , U x ] is a posterior credible interval for the conditional violation probability. The layer does not perform detection.
Preprints 246547 g001

3. Posterior Geometry and Existence

The first task is to establish that the Laplace reference is well-defined for the implemented model. Write p i ( θ ) = σ ( z i ⊤ θ ) and W ( θ ) = diag ( p i ( θ ) ( 1 − p i ( θ ) ) ) . Differentiating Equation (4) gives
∇ ℓ ( θ ) = A ⊤ ( y − p ( θ ) ) − Λ ( θ − m 0 ) ,
− ∇ 2 ℓ ( θ ) = A ⊤ W ( θ ) A + Λ ≕ H ( θ ) .
Theorem 1
(Strict log-concavity, a unique mode and curvature bounds). Under Equations (1)–(3), the posterior is proper and strictly log-concave. Its log density has a unique maximizer θ ^ ∈ R d . For every θ,
Λ ⪯ H ( θ ) ⪯ Λ + 1 4 A ⊤ A .
Consequently the negative log posterior is λ min ( Λ ) -strongly convex and its gradient is Lipschitz with constant at most λ max ( Λ ) + ∥ A ∥ 2 2 / 4 .
Proof. 
The Bernoulli likelihood factors lie between zero and one, so multiplying them by the proper prior in Equation (3) produces an integrable nonnegative posterior kernel with a positive integral. Since 0 < p i ( 1 − p i ) ≤ 1 / 4 , Equation (7) yields the Loewner inequalities in Equation (8). Because Λ ≻ 0 , − ℓ is strongly convex. In addition, the positive definite quadratic term in Equation (4) dominates the log likelihood at infinity, so − ℓ is coercive. Existence and uniqueness of its minimizer follow. The eigenvalue bounds in Equation (8) imply the stated strong-convexity and gradient-Lipschitz constants.    □
Remark 1
(What the posterior geometry does and does not say). The actual logistic–Gaussian posterior in Equation (4) cannot be multimodal under the stated proper prior; the uniqueness in Theorem 1 is global. This does not imply that the posterior is Gaussian or that its tails and asymmetry are accurately represented by a local Hessian. Such errors motivate the correction in Section 5. More general mixture priors or non-log-concave likelihoods could be multimodal, but are outside the implemented model.

3.1. Computing the Posterior Mode

The implemented calibration routine uses a damped Newton step rather than an unrestricted update. At an iterate θ k , let g k = ∇ ℓ ( θ k ) and H k = H ( θ k ) . The proposed ascent direction is
d k = H k − 1 g k , θ k + 1 = θ k + η k d k ,
with a backtracking step η k ∈ ( 0 , 1 ] accepted only when the log posterior improves sufficiently. Positive definiteness in Theorem 1 makes g k ⊤ d k > 0 whenever g k ≠ 0 ; thus d k is an ascent direction. This supplies the basis for a standard safeguarded Newton method (Nocedal and Wright, 2006). The finite-iteration implementation must still signal calibration failure if its stopping and conditioning checks are unmet. A mathematical unique mode is not a promise that every finite-precision optimization run succeeds.
Proposition 1
(Local quadratic model). Let H ^ = H ( θ ^ ) and C = H ^ − 1 . The second-order Taylor expansion of Equation (4) at the unique mode is
ℓ ( θ ) = ℓ ( θ ^ ) − 1 2 ( θ − θ ^ ) ⊤ H ^ ( θ − θ ^ ) + R 3 ( θ ) ,
where R 3 ( θ ) collects terms of order three and above. The Gaussian Laplace approximation , obtained by discarding R 3 , is q ( θ ) = N ( θ ^ , C ) .
Proof. 
The gradient vanishes at θ ^ by Theorem 1. Substituting Equation (7) into the multivariate Taylor expansion gives Equation (10). The quadratic exponential normalizes to the stated Gaussian because H ^ ≻ 0 .    □

4. One-Dimensional Laplace–Gauss–Hermite Inference

The high-dimensional Bayesian integral in Equation (5) becomes elementary in structure under the Gaussian reference. Define the Laplace posterior-predictive approximation
r L ( z ) E θ ∼ q σ ( z ⊤ θ ) .
Although q is multivariate, the logistic link depends on θ only through a linear functional. The resulting Gaussian projection removes any need for tensor quadrature at runtime.
Theorem 2
(Exact scalar reduction under the Laplace reference). Set
m z = z ⊤ θ ^ , v z = z ⊤ C z .
Then
r L ( z ) = 1 2 π ∫ R σ ( m z + v z t ) e − t 2 / 2 d t .
This dimension reduction is exact conditional on the Gaussian approximation q, but Equation (13) is not generally equal to the exact nonconjugate predictive risk in Equation (5).
Proof. 
A linear functional of θ ∼ N ( θ ^ , C ) is normal with mean m z and variance v z . Applying the change of variables z ⊤ θ = m z + v z t and taking the expectation of the logistic function yields Equation (13). The distinction from the actual posterior arises because q was obtained by discarding R 3 in Equation (10).    □
Let ( t j , w j ) j = 1 K be physicists’ Gauss–Hermite nodes and positive weights, normalized so that ∑ j w j = π . The K-node rule for Equation (13) is
r ^ L , K ( z ) = 1 π ∑ j = 1 K w j σ m z + 2 v z t j .
It evaluates a bounded smooth scalar integrand with K deterministic function evaluations. Gauss–Hermite quadrature integrates polynomials of degree at most 2 K − 1 exactly under its Gaussian weight; the logistic function is not a polynomial, so its finite-rule error remains numerical and must be checked with quadrature refinement (Golub and Welsch, 1969; Gautschi, 2004).
Proposition 2
(Valid range and monotone credible limits). For m z ∈ R and v z ≥ 0 , the approximation in Equation (14) satisfies 0 < r ^ L , K ( z ) < 1 . Moreover, under the Gaussian approximate posterior q, the central ( 1 − α ) credible interval for the conditional risk σ ( z ⊤ θ ) is
L q , α ( z ) , U q , α ( z ) = σ m z − ζ 1 − α / 2 v z , σ m z + ζ 1 − α / 2 v z ,
where ζ γ = Φ − 1 ( γ ) is the standard-normal quantile. The interval is exact under q, not an exact credible interval under the true nonconjugate posterior.
Proof. 
Every Gauss–Hermite weight is positive, σ maps finite real numbers into ( 0 , 1 ) , and the normalized weights sum to one, proving the risk range. Because σ is strictly increasing and z ⊤ θ is normal under q, applying σ to the Gaussian central quantiles gives exactly Equation (15).    □
A point-estimate decision would replace Equation (11) by σ ( m z ) . The discrepancy can be quantified without assuming a particular sign for the logistic curvature.
Proposition 3
(A Gaussian parameter-dispersion bound). The difference between the Laplace predictive risk and its mode plug-in counterpart obeys
r L ( z ) − σ ( m z ) ≤ 3 36 v z .
Proof. 
For s = σ ( t ) , the second derivative of the logistic link is σ ″ ( t ) = s ( 1 − s ) ( 1 − 2 s ) , whose absolute maximum over s ∈ [ 0 , 1 ] is 3 / 18 . Taylor’s theorem around m z gives σ ( Z ) = σ ( m z ) + σ ′ ( m z ) ( Z − m z ) + R ( Z ) with | R ( Z ) | ≤ ( 3 / 36 ) ( Z − m z ) 2 . Taking expectations for Z ∼ N ( m z , v z ) eliminates the linear term and gives Equation (16).    □
Remark 2
(Meaning of the dispersion bound). Equation (16) bounds the cost of using a Laplace-posterior mode plug-in instead of the Laplace-integrated prediction; it does not bound the approximation error | r ( z ) − r L ( z ) | . Since v z = z ⊤ C z depends on the test direction, two inputs with similar plug-in scores can have materially different parameter uncertainty. This is the relevant motivation for retaining the integrated prediction.

5. Posterior-Corrected Deterministic Quadrature

The Laplace approximation is computationally attractive but treats the true posterior as Gaussian. A different deterministic backend evaluates the exact log-posterior kernel Equation (4) at a finite set of multidimensional nodes and corrects for the Gaussian proposal. This backend is only feasible for small coefficient dimension; it is not a general substitute for high-dimensional posterior inference.

5.1. Change of Measure

Let q ( θ ) = N ( θ ^ , C ) , with a Cholesky factor C = B B ⊤ . Introduce the unnormalized density ratio
ρ ( θ ) e ℓ ( θ ) q ( θ ) .
Constants independent of θ cancel from the normalized ratio in the next equation, so implementations may shift the log weights by ℓ ( θ ^ ) for numerical stability. For any bounded measurable f,
E p ( θ ∣ D ) [ f ( θ ) ] = E q [ f ( θ ) ρ ( θ ) ] E q [ ρ ( θ ) ] .
Unlike pure Laplace integration, Equation (18) is an exact change-of-measure identity before quadrature.
For a tensor Gauss–Hermite rule with K nodes in each of d dimensions, index the nodes by a multi-index j = ( j 1 , … , j d ) ∈ { 1 , … , K } d , and write t j = ( t j 1 , … , t j d ) ⊤ . Under q, a transformed node and its Gaussian reference weight are
θ j = θ ^ + 2 B t j , ω j = π − d / 2 ∏ s = 1 d w j s .
Equation (19) requires K d nodes. The corrected and normalized weights are
b j = log ω j + ℓ ( θ j ) − ℓ ( θ ^ ) + ∥ t j ∥ 2 2 ,
ω ˜ j = exp ( b j − b max ) ∑ k exp ( b k − b max ) , b max = max j b j .
The added ∥ t j ∥ 2 2 term cancels the Gaussian reference factor in the density ratio. It is essential: omitting it would not recover a quadrature approximation to the true posterior expectation.
Theorem 3
(Posterior-corrected Gauss–Hermite identity and estimator). With Equations (17), (19) and (21), the self-normalized deterministic estimator of the risk in Equation (5) is
r ^ C , K ( z ) = ∑ j ∈ { 1 , … , K } d ω ˜ j σ ( z ⊤ θ j ) .
The weights are nonnegative and sum to one. Therefore r ^ C , K ( z ) ∈ ( 0 , 1 ) for all finite nodes. If the tensor quadrature rules converge for both functions ρ and ρ σ ( z ⊤ · ) under q, then r ^ C , K ( z ) → r ( z ) as K → ∞ along any sequence for which these convergence assumptions hold.
Proof. 
The Gaussian density at θ ^ + 2 B t is proportional to exp ( − ∥ t ∥ 2 ) . Hence inserting Equation (19) into the density ratio in Equation (17) yields the unnormalized weights in Equation (20), up to a common positive constant. Replacing each Gaussian expectation in Equation (18) by the tensor quadrature and dividing numerator by denominator gives Equation (22). Positivity and normalization follow from Equation (21). If numerator and denominator converge to their respective expectations, the limit of the ratio is their ratio because the normalizing expectation E q ρ is strictly positive.    □
Remark 3
(No unqualified convergence rate). Theorem 3 is a conditional convergence statement, not a claim of uniform convergence in dimension or a computable error certificate from the selected quadrature order. The importance ratio can vary sharply away from the Laplace mode, and the tensor-node count is exponential in d. The implementation rejects configurations exceeding its node cap rather than implicitly claiming high-dimensional accuracy.

5.2. A Deterministic Ratio-Error Bound

The following finite-dimensional lemma clarifies how errors in the numerator and denominator contribute to a corrected posterior expectation. It is independent of any particular quadrature family.
Lemma 1
(Ratio perturbation bound). Let N = E q [ ρ f ] , Z = E q [ ρ ] > 0 and r = N / Z with 0 ≤ f ≤ 1 . Let N K , Z K be numerical approximations satisfying
| N K − N | ≤ ε N , | Z K − Z | ≤ ε Z < Z .
Then
N K Z K − r ≤ ε N + r ε Z Z − ε Z ≤ ε N + ε Z Z − ε Z .
Proof. 
Writing N = r Z and subtracting gives N K / Z K − r = ( N K − N − r ( Z K − Z ) ) / Z K . The triangle inequality bounds the numerator by ε N + r ε Z , while | Z K | ≥ Z − ε Z > 0 . Finally 0 ≤ r ≤ 1 yields the second inequality.    □
Lemma 1 does not assert that ε N or ε Z are known in a given run. Its value is to separate the numerical integration problem from the decision-theoretic consequences of the resulting risk error, analyzed in Section 6. In code, a quadrature-weight concentration diagnostic
N eff = 1 ∑ j ω ˜ j 2
can flag cases in which the corrected rule is dominated by few nodes. This is a numerical diagnostic, not a proof of small integration error or a sampling effective sample size in an MCMC sense.

5.3. Risk Intervals Under Corrected Quadrature

For each node define s j ( z ) = σ ( z ⊤ θ j ) . The corrected approximate posterior distribution of the conditional violation probability is the discrete measure
Π ^ K , z = ∑ j ω ˜ j δ s j ( z ) .
A central posterior credible interval for conditional violation probability can be obtained from weighted quantiles of Equation (26). Unlike Equation (15), which transforms Gaussian quantiles analytically, these quantiles depend on the finite corrected grid. Both types of interval reflect parameter uncertainty under their approximating distributions; neither provides an unconditional guarantee that an answer is safe.
Algorithm 1 Offline calibration and deterministic posterior-predictive evaluation
Preprints 246547 i005

6. Bayesian Decisions and Post-Decision Admissibility

Posterior risk has no operational content until a decision loss is specified. Let the available actions be A = { allow , review , block } and let L ( u , h ) ≥ 0 be the cost of taking action u ∈ A when the true event is H = h . For any candidate risk r ∈ [ 0 , 1 ] , the expected loss of action u is
R ( u ; r ) = ( 1 − r ) L ( u , 0 ) + r L ( u , 1 ) .
For an unrestricted action set, the Bayesian rule is
u * ( r ) ∈ arg min u ∈ A R ( u ; r ) .
A deterministic implementation replaces the unavailable exact risk r ( z ) by r ^ ( z ) from Equations (14) and (22), where z = ( 1 , x ⊤ ) ⊤ . The initial Bayes-loss decision is a finite comparison of affine functions, requiring no LLM or optimization at runtime.

6.1. An Explicit Three-Region Loss Geometry

A particularly transparent configuration assigns no penalty to a correct allow or correct block, a cost c A > 0 to allowing an unsafe request, a cost c B > 0 to blocking a safe request, and a constant review cost c R > 0 :
action H = 0 H = 1 allow 0 c A review c R c R block c B 0 .
The three expected losses are the lines
R ( allow ; r ) = c A r , R ( review ; r ) = c R , R ( block ; r ) = c B ( 1 − r ) .
The review action is economically meaningful only when its cost is below the competing allow/block intersection loss.
Theorem 4
(Exact allow–review–block risk regions). Assume the loss matrix in Equation (29) and
0 < c R < c A c B c A + c B .
Define τ A = c R / c A and τ B = 1 − c R / c B . Then 0 < τ A < τ B < 1 and, apart from ties at the endpoints, the Bayes action in Equation (28) is
u * ( r ) = allow , 0 ≤ r < τ A , review , τ A < r < τ B , block , τ B < r ≤ 1 .
Proof. 
The allow and review losses cross at r = τ A , while the review and block losses cross at r = τ B . The allow and block losses cross at r 0 = c B / ( c A + c B ) . Condition Equation (31) is equivalent both to τ A < r 0 and to r 0 < τ B . For r < τ A , allowing beats review and, because r < r 0 , beats blocking. For τ A < r < τ B , review beats both alternatives. For r > τ B , blocking beats review and, because r > r 0 , beats allowing. The inequalities also imply 0 < τ A < τ B < 1 .    □
Figure 2. Analytically derived decision-loss geometry for the illustrative cost values in Appendix A.3; the plot is not an empirical performance result. The boundaries follow from Theorem 4.
Figure 2. Analytically derived decision-loss geometry for the illustrative cost values in Appendix A.3; the plot is not an empirical performance result. The boundaries follow from Theorem 4.
Preprints 246547 g002
The shipped demonstration assigns c A = 10 , c B = 3 and c R = 0.8 . Substitution into Theorem 4 gives τ A = 0.08 and τ B = 1 − 0.8 / 3 . These values concern a chosen decision cost model; they should not be confused with validated safety thresholds or a reported detector’s operating characteristics.

6.2. Parameter-Risk Uncertainty and Admissibility

The posterior-predictive violation probability r ( z ) is a posterior expectation, while σ ( z ⊤ θ ) varies with the unknown parameter θ . Let [ L x , U x ] be a central interval for this latter conditional risk, computed under the chosen approximating posterior as in Equations (15) and (26). The implementation imposes additional policy restrictions on the approximate action in Equation (34):
allow admissible only if U x ≤ γ A , block admissible only if L x ≥ γ B ,
where γ A , γ B ∈ [ 0 , 1 ] are configured application-policy parameters. If the selected action fails its interval gate, the system selects review; a separate hard veto takes precedence and requires block according to Equation (35).
Definition 1
(Bayes decision followed by deterministic admissibility gates). For a phase with complete and valid detector vector x, let z = ( 1 , x ⊤ ) ⊤ and select the unconstrained approximate Bayes-loss action
u ^ ( x ) ∈ arg min u ∈ A R ( u ; r ^ ( z ) ) .
Let V ( x ) ∈ { 0 , 1 } indicate an independent hard veto, and let A ad ( x ) contain the actions passing the configured interval gates in Equation (33), with review ∈ A ad ( x ) . The implemented final decision is
u final ( x ) = block , V ( x ) = 1 , u ^ ( x ) , V ( x ) = 0 and u ^ ( x ) ∈ A ad ( x ) , review , otherwise .
If mandatory detector evidence is missing or malformed, the output is review (withhold) rather than an attempt to evaluate Equation (34). A hard veto can block independently of the posterior. Neither review nor block authorizes release.
The final policy in Equation (35) is a Bayes-loss decision followed by deterministic post-decision restrictions. It is not, in general, a minimizer of expected loss over A ad ( x ) : when the initially chosen action fails a gate, the specified fallback is review, regardless of whether another admissible action has smaller expected loss.
Remark 4
(Approximate credible intervals are not certificates). The gates in Equation (33) are heuristic safety restrictions expressed using approximate parameter credible intervals; they are neither conformal frequentist coverage guarantees nor distribution-free bounds on adversarial failure. Even with exact Bayesian integration, the interpretation would depend on model specification, labels, priors and calibration data (Gelman et al., 2013; Guo et al., 2017). The word credible should not be silently replaced by certified safe.

6.3. Cost of Deterministic Posterior Approximation

A deterministic risk approximation can change the chosen action. The following result isolates the mathematical cost of that change before admissibility gates are imposed.
Theorem 5
(Posterior risk error to decision-regret transfer). Let A 0 be a fixed finite action set with costs L ( u , h ) . Define
S = max u ∈ A 0 | L ( u , 1 ) − L ( u , 0 ) | .
Suppose the exact risk is r ∈ [ 0 , 1 ] , the computed risk is r ^ ∈ [ 0 , 1 ] , and | r ^ − r | ≤ δ . If u * ( r ) minimizes Equation (27) over A 0 and u ^ = u * ( r ^ ) , then
0 ≤ R ( u ^ ; r ) − R ( u * ( r ) ; r ) ≤ 2 S δ .
Proof. 
The expected loss Equation (27) is affine in risk, with slope L ( u , 1 ) − L ( u , 0 ) . Thus | R ( u ; r ) − R ( u ; r ^ ) | ≤ S δ for every u. Write u * = u * ( r ) and the decision regret as
R ( u ^ ; r ) − R ( u * ; r ) = R ( u ^ ; r ) − R ( u ^ ; r ^ ) + R ( u ^ ; r ^ ) − R ( u * ; r ^ ) + R ( u * ; r ^ ) − R ( u * ; r ) .
The middle term is nonpositive by optimality of u ^ under r ^ ; each outer term is at most S δ . This yields Equation (37).    □
Corollary 1
(Decision error under posterior total variation). Let p denote the exact parameter posterior and q any approximate posterior distribution. If the predictive risk is integrated exactly under each distribution, then
| E p σ ( z ⊤ θ ) − E q σ ( z ⊤ θ ) | ≤ TV ( p , q ) .
Under the fixed-action assumptions of Theorem 5, substituting the approximate-posterior risk therefore produces regret at most 2 S TV ( p , q ) .
Proof. 
For any function f valued in [ 0 , 1 ] , the total-variation characterization implies | E p f − E q f | ≤ TV ( p , q ) . Apply it to f ( θ ) = σ ( z ⊤ θ ) and then use Theorem 5.    □
Remark 5
(Limits of the regret statement). Theorem 5 and Corollary 1 are deterministic conditional bounds, not statements that an implementation knows δ or TV ( p , q ) . They do not include model misspecification or calibration error, and they do not directly apply when the admissible action set itself changes because of approximate credible-bound gates. For corrected quadrature, a numerical risk-error estimate may be analyzed with Lemma 1 when suitable integration-error bounds are available.

7. Safety-Preserving Composition with NeMo

The mathematical Bayesian decision layer is separate from the external NeMo policy engine. This separation has a formal benefit: it prevents a probabilistic score from overriding a native block. Let b ( x ) = u final ( x ) be the gated Bayesian policy decision from Equation (35); let c denote checked content and ξ native NeMo execution context. The native status is n ( c , ξ ) , not a function of detector scores alone. We distinguish passed , modified , blocked , and unexpected statuses. A release protocol is an authorization predicate, not a new probabilistic model.
Definition 2
(Release protocol). For a completed native check on content c in context ξ, define
Release ( x , c , ξ ) = I b ( x ) = allow · I n ( c , ξ ) ∈ { passed , modified } .
The checked content c and execution context ξ are distinct from detector scores x. For a native modified status, only the replacement content returned by the native checker is eligible for release, never the original unchecked content. If b ( x ) is review or block, no native check is required to authorize withholding: release is defined as false without calling the native engine. Unknown native statuses never count as permission to release.
Theorem 6
(Native block preservation and monotonic non-release). Under Definition 2, for every x and every possible Bayesian risk estimate: (i) if a native check reports blocked, its content is not released; (ii) if the Bayesian policy reports review or block, the content is not released; and (iii) if the native checker reports modified, the original unchecked content cannot be released through the designated checked-content output.
Proof. 
For (i), a native blocked status makes the second indicator in Equation (39) zero. For (ii), the first indicator is zero. For (iii), Definition 2 restricts the eligible content to the checked replacement supplied by NeMo; the unchecked original is not an authorized output of the adapter. All three conclusions are independent of the numerical value of the Bayesian posterior risk.    □
The guarantee in Theorem 6 is a composition property conditional on the implementation honoring Definition 2; it does not show that the native checker detects all unsafe content. In the released wrapper, malformed or missing detector signals result in withholding, and unchecked token streaming is disabled. This last property is necessary when a post-generation output check may reject content after the model has produced it; any tokens sent to the consumer before that check would bypass Equation (39).

7.1. Two Engine Adapters and a Trust Boundary

The legacy NeMo LLMRails engine supports custom Python actions associated with Colang conversational flows. The Bayesian package can register an action that obtains trusted detector scores from NeMo context and returns a boolean allow result. The newer IORails engine uses a separate integration boundary: the Bayesian wrapper calls the native check_async and generate_async methods but does not claim to be a native IORails custom rail. Both paths have been tested against NeMo 0.25.0 as documented in Appendix B; these are version-specific interfaces, not promises of forward compatibility with all future upstream versions.
The trust boundary has an additional statistical meaning. Posterior predictive inference assumes the test vector x has the same feature meaning and preprocessing used in Equation (1). Allowing an adversarial prompt to populate those scores itself would defeat the decision model. Scores must therefore be generated by application-controlled detector code or explicitly trusted context, not parsed as instructions from retrieved documents.

8. Computational Complexity and Numerical Reliability

Let n denote the calibration sample size, d = p + 1 the coefficient dimension, K the quadrature order, and I the number of accepted damped Newton iterations. Constructing the gradient and Hessian in Equations (6) and (7) by dense matrix operations takes O ( n d 2 ) work per iteration; a Cholesky solve for the Newton direction takes O ( d 3 ) . Thus a straightforward dense calibration costs
O I ( n d 2 + d 3 ) .
These are offline costs. The posterior mode, Cholesky factors, and either corrected-node support or Gaussian covariance information are serialized as a calibration snapshot.
Table 1. Costs of the two deterministic integration choices. Complexity counts omit constants and external detector/NeMo/model latency.
Table 1. Costs of the two deterministic integration choices. Complexity counts omit constants and external detector/NeMo/model latency.
Task Laplace + scalar GH Posterior-corrected tensor GH
Extra offline quadrature Store K scalar nodes and weights; Gaussian curvature factorization K d posterior evaluations; O ( K d ( n d + d 2 ) ) with dense evaluation and weight storage
Runtime prediction O ( d 2 + K ) for dense C; O ( d + K ) only if C is diagonal (or a specified linear-time quadratic-form representation is available) O ( K d d ) for stored nodes and weights
Quadrature storage O ( K + d 2 ) O ( K d d + d 2 )
Main numerical limitation Gaussian shape error and 1-D quadrature truncation Tensor-grid explosion and posterior-ratio concentration
For Laplace inference with a general dense covariance, the per-query cost is O ( d 2 + K ) , dominated by z ⊤ C z and K evaluations in Equation (14); a diagonal C makes this O ( d + K ) . For corrected quadrature, the offline construction in Equations (19) and (21) is more costly, while each runtime query computes the K d logits and a weighted sum; the ratio weights need not be recalibrated on each query. tab:complexity summarizes these distinctions. The released implementation constrains the corrected node count, quadrature order, Hessian condition number, and numerical validity of the saved weights. These are engineering guards against unstable execution, not proofs of approximation accuracy.

8.1. Error Accounting

There are several logically distinct uncertainties: statistical misspecification of Equation (2), finite calibration data, Gaussian approximation error | r − r L | , scalar quadrature error | r L − r ^ L , K | , and, alternatively, corrected multidimensional quadrature error | r − r ^ C , K | . A useful decomposition for the Laplace backend is
| r ( z ) − r ^ L , K ( z ) | ≤ | r ( z ) − r L ( z ) | + | r L ( z ) − r ^ L , K ( z ) | .
The first term is a posterior approximation error; raising K can reduce only the second. For the corrected backend, Lemma 1 separates numerator and denominator errors, but no universal finite-grid certificate is available from this model alone. Consequently, empirical quadrature refinement is a useful diagnostic, and held-out calibration is required for external probability validity (Guo et al., 2017; Gneiting and Raftery, 2007; Brier, 1950).

9. Discussion

The central point of this construction is that uncertainty-aware guardrail control has three mathematically separable components: a statistical estimator of violation risk, a decision rule with asymmetric costs, and an authorization boundary that cannot be overridden by probabilistic evidence. The posterior predictive quantity in Equation (5) integrates model-parameter uncertainty; it is distinct from the most likely coefficient vector. The Laplace construction in Section 4 exploits the linear logistic predictor to make inference inexpensive. Corrected quadrature in Section 5 offers a deterministic non-Gaussian alternative when d is small. The decision regions in Section 6 expose the consequence of choosing to review borderline cases, and Theorem 6 formalizes the non-override property with respect to the native guardrail engine.
Several limitations are essential to the interpretation of these results. No theorem here establishes correctness of an upstream prompt-injection detector or hallucination detector. A dataset consisting of synthetic labels, including the released demonstration snapshots, cannot establish real-world calibration, safety, robustness or RAG utility. Deterministic posterior calculations do not remove the need for actual labels, and the meaning of H must remain stable between training and deployment. The implemented logistic–Gaussian model is static and phase-specific; it neither learns a conversation-level hidden Markov state nor estimates causal dependence among arbitrary detector streams. More expressive Bayesian models would require additional assumptions and, possibly, different numerical inference machinery. Finally, the corrected tensor rule scales exponentially with parameter dimension, and neither backend is an exact solver for general nonconjugate Bayes.

10. Conclusion

We have presented a theory-led formulation of Bayesian risk control for NeMo Guardrails. The approach defines a full posterior-predictive risk objective under a nonconjugate logistic model, approximates it deterministically by Laplace–Gauss–Hermite or density-corrected quadrature, and maps it to three-way decisions by Bayes expected loss followed by explicit uncertainty gates and hard non-override constraints. Strict posterior log-concavity makes the mode and covariance reference unambiguous; scalar reduction avoids unnecessary runtime high-dimensional integration; corrected quadrature retains information from the original posterior kernel; and explicit risk-error bounds clarify what approximate integration can imply for decision loss. The NeMo integration is software-oriented and version-specific, with implementation and verification details deferred to the appendices that follow the references.

11. Software and Data Availability

The Python implementation and synthetic demonstration data are openly available at
https://github.com/AngshulMajumdar/Bayesian-NeMo-Guardrails
The interactive manual-score demonstration is available at
https://huggingface.co/spaces/Angshul/Bayesian-NeMo-Guardrails
The accompanying documentation is at
https://angshulmajumdar.github.io/Bayesian-NeMo-Guardrails/
This work is an independent software extension and is not an official NVIDIA product.

Appendix A. Software Architecture and Reproducibility

The main text develops the mathematics independently of a software API. This appendix records the correspondence with the released Bayesian-NeMo-Guardrails package, version 0.1.0, inspected on 26 November 2026. Implementation material is placed here after the references rather than in a supplementary document. In Table A1, the short nonbreaking names model.py, policy.py, adapters.py, calibration.py and api.py have the common directory prefix src/bayesiannemo/; policy.yaml belongs to examples/, and tests/ is a top-level directory. The GitHub and Hugging Face repositories are linked in Section 11.

Appendix A.1. Correspondence Between Mathematical Objects and Source Files

Table A1. Source-level correspondence to the main mathematical development.
Table A1. Source-level correspondence to the main mathematical development.
Repository path Mathematical responsibility
model.py Posterior mode and curvature (Section 3), Laplace scalar rule (Equation (14)), corrected weights (Equation (21)), posterior credible interval for conditional violation probability (Equations (15) and (26)).
policy.py Expected loss (Equation (27)), review action (Theorem 4), credible-bound gates and hard vetoes (Definition 1).
adapters.py Safe composition for LLMRails/IORails (Definition 2 and Theorem 6).
calibration.py Offline labeled CSV fitting of Equation (4) and model snapshot serialization.
api.py Stateless evaluation API that accepts a phase and trusted score dictionary.
policy.yaml Illustrative loss matrix, phase-specific model paths, credible bounds and vetoes.
tests/ Numerical, adapter, API and actual NeMo integration tests.

Appendix A.2. Installation and Deterministic Inference

At the repository root, the released Python package can be installed and tested with the commands in Listing A1. The standard executable permits a phase-specific evaluation without running a language model.
Listing A1: Installation and example command-line risk evaluation.
Preprints 246547 i001
A separate offline calibration command uses the shipped synthetic input file solely to illustrate the schema:
Listing A2: Offline calibration of a small corrected-quadrature model with illustrative data.
Preprints 246547 i002
The labels in the example CSV were generated for demonstration, and Listing A2 is not a recipe for certifying a deployed detector. To use real labeled data, the application must preserve feature identities, collect independently adjudicated policy-violation labels, and train and evaluate on appropriately separated calibration/validation data. The calibration command writes a versioned JSON model snapshot, which the runtime YAML selects through its phases.*.model fields. Unlabeled live conversation events do not become ground-truth labels.

Appendix A.3. Illustrative Policy Configuration

The published examples/policy.yaml specifies the cost structure in Equation (29) as
c A = 10 , c B = 3 , c R = 0.8 .
Its credible mass is 0.95 and its illustrative allow/automatic-block interval gates are γ A = 0.12 and γ B = 0.75 . The input phase names injection_risk and toxicity_risk; the output phase names unsupported_claim_risk. High-risk hard veto thresholds are specified independently from the posterior model. These values are deployment configuration examples, not statistically calibrated safety limits; see Remark 4. A simplified excerpt is provided in Listing A3.
Listing A3: Structure of a phase-specific example Bayesian policy (illustrative values).
Preprints 246547 i003

Appendix A.4. API and Adapter Boundaries

The packaged FastAPI service exposes GET /health, GET /config, and POST /evaluate; the latter accepts phase and scores. It does not itself run detectors. The call in Listing A4 is an evaluation of manually supplied scores, not an adversarial prompt evaluation.
Listing A4: Example REST API evaluation.
Preprints 246547 i004
For the NeMo adapter, LLMRailsAdapter registers an optional bayesian_nemo_input Colang action; its score dictionary arrives through trusted context. The separate IORailsAdapter wraps Guardrails(...,require_iorails=True). It is not a native IORails custom action. In both cases, an allow verdict from the Bayesian component is necessary but not sufficient for releasing output. Native NeMo checking is separately required, following Definition 2. Modified content must come from the native checked result. The wrapper intentionally prohibits unchecked token streaming; output scoring must be supplied for generation if that phase is configured.
The source repository includes executable local examples in examples/legacycolang/runlocal.py and examples/iorails/runlocal.py. These use deterministic scores and native rule checks to exercise integration without downloading an LLM or running on a GPU. In the corrected backend, serialized quadrature nodes and weights remain tied to the offline calibration snapshot, so changing the labeled data requires rebuilding that snapshot.

Appendix B. Verification Scope and Model Limitations

Appendix B.1. Published Integration Tests

The repository includes a GitHub Actions workflow at .github/workflows/tests.yml with Python unit-test jobs and a NeMo 0.25.0 integration job. The successful CI run inspected on 26 November 2026 reports 40 passed, 1 skipped for the Python 3.12 unit job (the optional NeMo module is skipped when NeMo is absent), and 6 passed for the NeMo-installed integration module. The job is traceable at:
https://github.com/AngshulMajumdar/Bayesian-NeMo-Guardrails/actions/runs/45779281046
These counts document software checks, not statistical benchmark results. The separate Hugging Face Space exposes manual-score evaluation for both Laplace and corrected-quadrature modes; its public address is given in Section 11.

Appendix B.2. What Has Not Been Established

The software record does not contain production-calibrated risk labels, an end-to-end RAG/LLM safety experiment, a controlled comparison with alternative calibration models, or a distribution-free bound on unsafe content. It also does not establish deterministic quadrature accuracy in arbitrary high dimension. These omissions do not undermine the mathematical identities and conditional theorems in the main paper, but they materially limit claims about practical protection. In particular, an approximate Bayesian posterior interval is an interval over uncertainty in model coefficients under the chosen model, not a certificate that a guardrail prevents all harmful responses.

Appendix C. Reference and Source Audit

The theoretical citations preceding this appendix identify the original literature for Bayesian decision theory (Berger, 1985; Robert, 2007; Bernardo and Smith, 1994), posterior approximation (Tierney and Kadane, 1986; MacKay, 1992; Rue et al., 2009), Gauss quadrature (Golub and Welsch, 1969; Gautschi, 2004), and probability calibration (Guo et al., 2017; Gneiting and Raftery, 2007). They are not presented as results originally proved by the author of this software. NVIDIA NeMo Guardrails is separately credited through Rebedea et al. (2023). The original source repository is available at https://github.com/AngshulMajumdar/Bayesian-NeMo-Guardrails; this manuscript does not contain a copy of NVIDIA source code.

References

  1. Rebedea, T.; Dinu, R.; Sreedhar, M.N.; Parisien, C.; Cohen, J. NeMo Guardrails: A Toolkit for Controllable and Safe LLM Applications with Programmable Rails. In Proceedings of the Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing: System Demonstrations, 2023, pp. 431–445. [CrossRef]
  2. Bishop, C.M. Pattern Recognition and Machine Learning; Springer, 2006.
  3. Gelman, A.; Carlin, J.B.; Stern, H.S.; Dunson, D.B.; Vehtari, A.; Rubin, D.B. Bayesian Data Analysis, 3 ed.; Chapman and Hall/CRC, 2013.
  4. Tierney, L.; Kadane, J.B. Accurate Approximations for Posterior Moments and Marginal Densities. Journal of the American Statistical Association 1986, 81, 82–86. [CrossRef]
  5. MacKay, D.J.C. A Practical Bayesian Framework for Backpropagation Networks. Neural Computation 1992, 4, 448–472. [CrossRef]
  6. Golub, G.H.; Welsch, J.H. Calculation of Gauss Quadrature Rules. Mathematics of Computation 1969, 23, 221–230. [CrossRef]
  7. Gautschi, W. Orthogonal Polynomials: Computation and Approximation; Oxford University Press, 2004. [CrossRef]
  8. Rue, H.; Martino, S.; Chopin, N. Approximate Bayesian Inference for Latent Gaussian Models by Using Integrated Nested Laplace Approximations. Journal of the Royal Statistical Society: Series B (Statistical Methodology) 2009, 71, 319–392. [CrossRef]
  9. Guo, C.; Pleiss, G.; Sun, Y.; Weinberger, K.Q. On Calibration of Modern Neural Networks. In Proceedings of the Proceedings of the 34th International Conference on Machine Learning, 2017, Vol. 70, Proceedings of Machine Learning Research, pp. 1321–1330.
  10. Gneiting, T.; Raftery, A.E. Strictly Proper Scoring Rules, Prediction, and Estimation. Journal of the American Statistical Association 2007, 102, 359–378. [CrossRef]
  11. Nocedal, J.; Wright, S.J. Numerical Optimization, 2 ed.; Springer, 2006. [CrossRef]
  12. Brier, G.W. Verification of Forecasts Expressed in Terms of Probability. Monthly Weather Review 1950, 78, 1–3. [CrossRef]
  13. Berger, J.O. Statistical Decision Theory and Bayesian Analysis, 2 ed.; Springer, 1985. [CrossRef]
  14. Robert, C.P. The Bayesian Choice: From Decision-Theoretic Foundations to Computational Implementation, 2 ed.; Springer, 2007. [CrossRef]
  15. Bernardo, J.M.; Smith, A.F.M. Bayesian Theory; Wiley, 1994. [CrossRef]
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.
Copyright: This open access article is published under a Creative Commons CC BY 4.0 license, which permit the free download, distribution, and reuse, provided that the author and preprint are cited in any reuse.