Image making · Research feature

InGuard: Towards Generalized Inner Guardrail for Safe Text-to-Image Generation

A new safety system for text-to-image AI models evaluates prompts and images within the generation process, reducing unsafe outputs and improving efficiency.

Adapted from research by Zeyu Wang, Xiaodan Li, Zhiwen Li and colleagues.

arXiv preprint revision · 2026-09-23 · Attribution & reuse
In this article
Editorial illustration of a color study.

Editor’s introduction

The study evaluates a framework called InGuard, which integrates safety checks directly into the text-to-image generation pipeline. It uses the model’s internal text encoder embeddings to classify prompts as safe, risky, or unsafe, without relying on external language models. For risky prompts, the system applies SAGE to modify embeddings to produce safer outputs, and monitors latent representations midway through generation to detect risk early. This approach achieves high safety rates across five open-weight models, outperforming traditional outer guardrails in both accuracy and efficiency. The evaluation uses a benchmark of 10,000 real-image reverse-generated prompts with controlled IP characters, testing risks like porn, gore, and intellectual property.

Introduction

Modern open-weight text-to-image (T2I) models, including Qwen-Image, HunyuanImage, FLUX, and Z-Image, can generate high-fidelity images from a wide range of natural-language prompts. However, their broad generative capabilities also increase the risk of misuse. Relevant risks include not-safe-for-work (NSFW) content, such as pornographic and gory imagery, and the generation of controlled intellectual-property (IP) characters that may conflict with deployment policies. Deploying these models in public-facing applications therefore requires robust safety mechanisms.

The conventional safety approach forms an outer guardrail around the generation pipeline: a prompt classifier that checks the prompt for risk before generation, and a post-hoc image classifier that checks the fully generated image for NSFW content. This design has three limitations: (1) On the prompt side, the classifier normally relies on an external language model. Real-time deployment pushes it toward compact encoders such as BERT and mE5, whose small representation capacity limits the accuracy of risk assessment. Scaling up to a larger language model can improve accuracy, but it also increases computational overhead. (2) On the image side, the image is checked only after generation is complete. All denoising steps have already finished by the time the check runs, so the compute is wasted whenever a risky image is detected. (3) In the rejection-based configuration, risk detected on either side leads to outright rejection, which degrades the user experience. In practice, many requests can be guided and corrected to generate safe images, rather than rejected as a whole. In-pipeline enhancement methods can achieve this by modifying the prompt or its embeddings. All three limitations share the same root: the guardrail is blind to the model’s own representations. It works on the input text and the generated image, not on the embeddings and intermediate features.

Research on T2I generation safety has grown in step with the open-weights release of LDMs, Diffusion Transformers (DiTs), and Flow-Matching models. Existing strategies fall into two families: enhancement methods suppress unsafe concepts so that users receive safe images even from risky prompts, whereas detection methods identify risk in prompts or generated content. We review both, together with the safety benchmarks used to evaluate them.

T2I Safety Enhancement

Training-time approaches modify model parameters directly, requiring additional training or fine-tuning. Concept Ablation fine-tunes model parameters to align a target concept’s conditional distribution with that of an anchor concept, SafeGen modifies the self-attention within the U-Net to suppress sexually explicit content, and Erased Stable Diffusion suppresses unsafe concepts through model fine-tuning. Such approaches introduce model-update costs and can affect semantically related benign concepts.

Inference-time methods operate at the text-embedding, latent, or attention level. At the text-embedding level, SAFREE projects trigger tokens away from toxic concept subspaces using a hard trigger threshold. This projection component requires no training and is computed before denoising. SAFREE additionally provides Self-Validating Filtering (SVF), which adjusts conditioning across denoising steps. STG, Responsible Diffusion, and ItD refine embeddings through per-step gradient ascent or external safe directions, incurring overhead or relying on precomputed components. At the latent level or the attention level, SLD guides latents away from unsafe regions via classifier-free guidance but risks disturbing benign outputs. SafeRoPE perturbs positional embeddings in safety-critical attention heads, while CASG dynamically selects category-aligned guidance to address multi-category conflicts and can be applied to latent-space or text-space safeguards.

T2I Safety Detection

Safety detection at the prompt and image sides constitutes a common outer guardrail. On the prompt side, classifiers are often built on compact text encoders such as BERT and mE5, which are separate from the generator’s own text encoder. On the image side, widely deployed classifiers inspect the generated image once the full denoising process finishes. Examples include the built-in safety checker of Stable Diffusion (a CLIP-based filter that flags sexual content), as well as Q16, NudeNet, and the LAION classifier. Q16 employs prompt-tuning on socio-moral value datasets to classify inappropriate image content. NudeNet provides models for nudity classification and body-part detection and is widely adopted in open-source moderation pipelines. The LAION classifier is a lightweight CLIP-based model that provides NSFW scores for filtering web-scale training corpora such as LAION-5B. Their target labels differ, so coverage of gore or controlled IP characters requires task-specific evaluation or adaptation. Post-hoc detectors also run only after generation completes, and adaptation may be needed when transferring from natural to generated images. In-generation detection has also been explored. FlowGuard uses linear latent decoding and curriculum learning to inspect intermediate denoising states and terminate unsafe generations early.

T2I Safety Benchmarks

These benchmarks are designed to measure how much risk a model produces. Their annotations therefore record which risks a prompt carries and how often it elicits them, rather than how severe each risk is. Most release risky prompts only. Six-CD also releases benign prompts in two forms: a risky prompt with the unwanted concept deleted, and plain captions from a general web corpus. Neither form explicitly targets the graded near-boundary cases considered here. T2ISafety includes neutral prompts, which target demographic bias. Prompt sets further differ in how reliably they elicit risk, and Six-CD keeps a prompt only if it yields unsafe images in at least four of five generations.

Overview

The RevGen Safety Benchmark covers three risk dimensions (porn, gore, and IP) together with benign prompts. Prompts carry graded porn/gore labels and categorical IP labels, allowing category- and level-dependent responses rather than a single accept-or-reject decision. The benign prompts include cases written close to a risk category, where false positives are most likely to occur.

VLM-Driven Generation Pipeline

The VLM-driven reverse generation pipeline consists of four stages: source image pooling, VLM-driven reverse generation, IP character rewriting for a subset of prompts, and clustering-based diversity sampling. Each stage is described below. The resulting prompts are then rendered by the T2I models, which supports the measurements reported in Sections 3.3 and 3.4.

Stage 2: VLM-Driven Reverse Generation

The core of our pipeline is a reverse generation process that bridges real-world imagery and text-to-image prompt design. Our method begins with real source images and leverages a VLM to convert each image into a text-to-image prompt intended to reproduce its main visual elements when fed to an LDM. This reverse generation strategy grounds the resulting prompts in the visual complexity, composition, and context of real images.

Stage 4: Clustering-Based Diversity Sampling

Prompts within each sub-category are embedded with TF-IDF followed by truncated SVD, then grouped with K-Means. From each cluster we take the prompts closest to the centroid, up to a fixed per-cluster cap. The cap limits the contribution of any single cluster without requiring equal counts from clusters of different sizes. The trainset and testset are generated independently with source-image-level separation: prompts derived from the same source image, including English/Chinese versions and IP rewrites, remain in the same split. MinHash-LSH deduplication is additionally applied between the splits to reduce textual overlap.

Risk Elicitation Statistics

To verify that the prompts elicit risk, we generate an image for every prompt with each of the five LDMs and measure the Risk Hit Ratio, the proportion of generated images flagged as risky by the Qwen3.7-Plus image-level annotator. Risky prompts reach 21.60%–94.00% across dimensions and models, while no benign sub-category exceeds 3.20%.

Prompt Embedding Risk Classification

Before applying safety enhancement, each prompt is classified into multi-dimensional risk categories at the embedding level. The classifier operates directly on the text encoder’s output embeddings, which are the same embeddings that subsequently condition the diffusion process, requiring no additional text encoding pass. Risk is assessed along three independent dimensions: pornographic, gore, and IP-controlled content.

Asymmetric Soft-Gated Blending

SAGE applies the modified embeddings at all denoising steps, requiring no step-based switching. This contrasts with the Self-Validating Filtering (SVF) mechanism, where modified and original embeddings alternate across denoising steps with a danger score determining the switch point.

Latent-Space Safety Detection

While the embedding-space enhancement suppresses unsafe content at the text level before generation begins, it cannot guarantee complete elimination, since some risky content may survive in subtle or implicit forms. We therefore introduce a latent-space detection track that runs alongside the diffusion process. Modern latent diffusion models generate images through an iterative denoising process in the latent space of a variational autoencoder (VAE). The intermediate latents allow early termination: once a latent exhibits risk indicators, generation is aborted and all subsequent denoising steps are skipped. However, latent representations differ fundamentally from natural RGB images in channel count, spatial resolution, and distribution, so ImageNet-pretrained backbones require input adaptation. We use domain-adaptive pretraining to improve their initialization for latent classification. In the following, we first describe how detection latents are obtained from the flow-matching generation process, then present the latent detector backbone and the two-stage training strategy.

Training Phase A: Domain-Adaptive Pretraining

This is a pairwise algebraic identity, not a proof that inference-time estimates and VAE-encoded images have identical distributions. A regressed velocity field generally estimates a conditional average rather than the velocity of an individual training pair. Prediction error, denoising time, and the difference between natural-image pretraining data and generated content can all introduce a distribution gap. We therefore use VAE latents as an inexpensive pretraining source and retain Phase B adaptation on generation-derived latents. VAE encoding requires one encoder pass rather than iterative denoising, making large-scale feature pretraining practical.

Training Phase B: Safety Fine-tuning

The pretrained backbone is fully fine-tuned on safety-labeled latents extracted from the RevGen Safety Benchmark’s generation process. Full fine-tuning is preferred over freezing the backbone and training only the heads, because Phase A provides domain-adaptive features but not safety-specific ones, and the backbone must further specialize to distinguish safety-relevant content. The three heads are trained jointly with cross-entropy loss, sharing a common backbone representation while maintaining head-specific decision boundaries, the same multi-task principle used in the prompt risk classifier.

Training data is organized into risk groups: porn, gore, IP-controlled characters, borderline samples (visually ambiguous content at the boundary between safe and unsafe, such as suggestive but non-explicit imagery or mild violence), and normal images. Borderline samples are included to expose the classifier to ambiguous cases near the safety boundary. Stratified sampling balances representation across these categories, preventing the majority class (normal images) from dominating training and ensuring that rare categories receive adequate gradient signal. Training and test data are separated by source image, keeping all derived prompt variants within their split. We additionally filter testset IDs from the training data to exclude direct ID overlap.

Experiments

We evaluate InGuard through experiments organized to mirror the method’s three-component structure. We first describe the unified experimental setup, then evaluate each component individually: prompt embedding risk classification, SAGE embedding-space enhancement, and latent-space safety detection including computational efficiency. We finally present the system-level comparison of our InGuard and the conventional outer guardrail along two dimensions: the safety rate and the benign disturbance rate.

Datasets

Safety-supervised training uses data constructed with the RevGen pipeline, and evaluation uses the 10,000-prompt RevGen testset with labels across porn (0–5), gore (0–5), and IP (0–7). The latent-detector experiments vary the safety-training pool from 5K to 50K. Phase A domain-adaptive pretraining instead uses VAE-encoded natural images from OpenImages.

Baselines and Comparisons

We compare two guardrail paradigms: the conventional outer guardrail and our InGuard. The outer guardrail screens the prompt with a text classifier (mE5-base or mBERT-cased) and the generated image with an image classifier (ConvNeXt-Base). The inner guardrail operates within the LDM pipeline: PE-MLP classifies prompts on the LDM’s text encoder embeddings, SAGE suppresses toxic concept directions in the embeddings, and a latent detector (ConvNeXt-Base on intermediate latents) checks generation at a selected intermediate step. We choose SAFREE as the primary baseline for SAGE, since it can also serve as an embedding-space enhancement component within the inner guardrail.

Pretraining effects

To demonstrate the effect of the proposed distillation pretraining, we compare two latent detector configurations across four training pool sizes (5K–50K) for all five LDMs. The configurations are: (1) Latent (w/o pretrain): latent input with ImageNet-1K pretraining, no distillation; (2) Latent (w/ distill. pretrain.): latent input with Phase A distillation pretraining. Performance is measured by Avg F1, which is the mean of the F1 scores across the three risk categories.

Detection efficiency

Detection is already informative at the initial step and generally improves over the early denoising stages. We report deployment at step 3 for Z-Image-Turbo, step 4 for the three 10-step models, and step 8 for InternVL-U. At these steps, latent-detector Avg F1 is within 0.26–1.71% of image-level detection. If a request is intercepted there, 50–55.6% of denoising evaluations are avoided. Requests that pass the check still complete generation. These fractions exclude text encoding, SAGE’s masked re-encoding and projection, classifier inference, and VAE decoding; they do not establish a corresponding reduction in wall-clock latency or average serving cost.

System-Level Comparison: Inner vs. Outer Guardrails

We report two metrics. Safety rate is the fraction of all requests for which the final generated image is safe. An intercepted request counts as safe. Benign disturbance rate is measured among samples whose prompt and original, unguarded image are both safe, and counts interception or VLM-judged semantic alteration. For InGuard, disturbance can arise from direct PE-MLP interception, SAGE modification, or latent-detector interception. Prompt-risky but originally image-safe samples are excluded from this disturbance denominator by definition.

Conclusion and Future Work

These results also point to several directions for future work. First, the label-gated design ties SAGE to the accuracy of the prompt classifier and to a finite concept set. Making it more robust to adversarial rewriting and to multi-character IP scenes is therefore an important next step. Second, our evaluation covers three risk categories, namely porn, gore, and IP. Other policy dimensions, such as hate and privacy, remain to be explored. Third, our detection relies on the one-step latent estimate. As new open-weight generators and modalities keep appearing, extending it to unseen generators, to video generation, and to other iterative synthesis processes would let safety coverage keep pace with these models, which is a promising direction for further study.

Backbone Architecture Comparison

ConvNeXt beats ViT at every pool size, reaching 91.4–92.1% Avg F1 versus 85.0–85.4% at 50K without distillation, though ViT also lags in the RGB configuration, so this is not a latent-specific effect. Distillation at 50K adds 5.38–6.23% Avg F1 for ViT and 0.82–1.25% for ConvNeXt, and within the distilled ConvNeXt family Avg F1 spans only 92.66% (Tiny) to 93.19% (Large). We select Base (92.87% Avg F1, 88.6M parameters) over Large (198M) as a recall-oriented choice: relative to Tiny it trades higher risk recall (95.59% vs. 92.45%) for higher disturbance (9.40% vs. 6.18%), rather than being uniformly best.