A controllable text generation method fusing differential correction and explicit semantic guidance

By combining differential correction mechanism and explicit semantic guidance, the problems of dataset distribution bias and random initialization in controllable text generation are solved, improving the accuracy and fluency of attribute control of generated text, especially in emotion control, topic control and toxicity avoidance tasks.

CN123180177APending Publication Date: 2026-11-27CHONGQING UNIV OF TECH
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611712860.7
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-11-02
Publication Date
2026-11-27

AI Technical Summary

Technical Problem

Existing controllable text generation techniques face challenges such as implicit attribute interference introduced by the inherent distribution of datasets and weak semantic signals in the early stages of training due to random initialization prefixes, which affect the control of target attributes and the accuracy and fluency of generated text.

Method used

A differential correction mechanism is adopted to model the overall generation trend of the dataset through a general soft prefix, and distribution-level weighted differencing is performed during the generation stage to reduce the interference of the inherent distribution tendency of the dataset. At the same time, a specific soft prefix is ​​initialized using target attribute keywords through an explicit semantic guidance strategy to enhance the semantic signal in the early stage of training.

Benefits of technology

It improves the accuracy of target attribute control and the fluency of generated text, significantly enhances the generation effect of sentiment control, topic control and toxicity avoidance tasks, and achieves higher attribute control precision and text quality.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123180177A_ABST
    Figure CN123180177A_ABST
Patent Text Reader

Abstract

The application discloses a controllable text generation method fusing differential correction and explicit semantic guidance, belongs to the technical field of natural language processing, and aims to solve the problems of low attribute control precision and poor text fluency caused by the interference of inherent distribution tendency of a data set and insufficient semantic signal of prefix initialization of the prior art method. The application constructs a differential correction mechanism, respectively performs forward calculation and normalization on specific soft prefixes and general soft prefixes, performs weighted differential operation on the two types of probability distribution to obtain a corrected mixed distribution, and weakens the interference of the inherent distribution of the data set; an explicit semantic guidance strategy is constructed, semantic representation of a target attribute keyword is mapped to a prefix space and a specific soft prefix is initialized, and an explicit semantic signal is injected; in the training stage, the main parameters of a basic language model are frozen, the original distribution and the corrected distribution are fused in the generation stage, and text is generated by sampling. The application can improve the attribute control precision and the text fluency, and has the advantages of high parameter efficiency and stable control.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of natural language processing technology, and in particular to a controllable text generation method that integrates differential correction and explicit semantic guidance. Background Technology

[0002] Text generation is one of the core tasks in the field of natural language generation, aiming to generate coherent and natural text sequences based on input. It shows broad application prospects in news writing, machine translation, and content creation. However, traditional text generation models often struggle to precisely control the output content, resulting in generated results that may not meet the specific needs of users or the requirements of application scenarios. To address this, Controllable Text Generation (CTG) has emerged, aiming to introduce control conditions into the text generation process so that the output satisfies specified attributes or constraints while maintaining high fluency.

[0003] Existing controllable text generation technologies can be broadly categorized into two main approaches based on their implementation paths: retraining methods and prompting engineering methods. Retraining is a traditional method for adapting deep learning models to downstream tasks. Its core idea is to improve performance by further optimizing model weights on task-specific data based on the parameters of a pre-trained model. Early work like CTRL added control code (such as domain, style, topic, entity relations, etc.) before the Transformer model and retrained it on large-scale corpora to achieve conditional text generation, while also proposing Top-k sampling to reduce generation repetition. Insertion methods such as POINTER and CBART satisfy lexical constraints by progressively inserting or replacing words. CBART, in particular, implements parallel decoding on top of a pre-trained BART model, improving generation efficiency without modifying the model architecture. CoCon and Mention Flags modules inject control modules into pre-trained language models to achieve word-level and phrase-level constraints and utilize self-supervised learning to alleviate the problem of insufficient labeled data. Retraining methods are flexible and effective, but they typically have high computational costs, rely on large-scale labeled data, and can weaken the generality of pre-trained language models to some extent.

[0004] Cue engineering has become a mainstream research direction in controllable text generation in recent years. Its core idea is to guide the model to generate text that meets specific attributes or constraints by designing input prompts, without modifying the main parameters of the base model, thus achieving higher parameter efficiency. Cue engineering can be further divided into hard cue methods and soft cue methods: Hard cue uses natural language text as the control signal, is highly sensitive to the wording of the cue, and has a coarse control granularity; soft cue is parallel to hard cue and is another branch of cue engineering. The trainable continuous vectors used in soft cue are usually called soft prefixes, as opposed to hard prefixes composed of natural language text. Soft prefixes have no explicit literal semantics; they are trained and updated through gradient descent, enabling the learning of fine-grained control signals that are difficult to express in discrete text. The training process only updates the prefix vectors without modifying the main parameters of the base model, making it a parameter-efficient fine-tuning scheme. Typical examples of soft cue methods are prefix-tuning and prompt-tuning.

[0005] Prefix fine-tuning is primarily applied to natural language generation tasks, especially in the GPT series models. Task-specific prefix vectors are appended to the input sequence of each transformer layer, guiding the model to generate text that conforms to specified attributes without modifying the original model parameters. Cue tuning, on the other hand, adds cue vectors before the input embedding layer. By training these cue embeddings, task adaptation is achieved with lower parameter overhead. Simultaneously, contextual modeling of the input can be performed during generation, improving the model's understanding and utilization of information.

[0006] To further improve the accuracy and generalization ability of attribute control, various soft prompt optimization methods have emerged in academia: Contrastive Prefixes utilize contrastive learning to extract attribute vectors, guiding text generation without modifying model parameters and improving generation quality and control accuracy; T5 Encoder-Decoder Soft Prompt Tuning introduces soft prompts simultaneously at the encoder and decoder layers, generating text that meets specific control requirements by optimizing prompt embeddings; Discriminator-Cooperative Unlikelihood Prompt-tuning (DisCup) introduces an attribute discriminator to assist in prompt optimization, enhancing attribute control capabilities through back-likelihood training, but its fixed prompt template makes it difficult to adapt to complex multi-attribute scenarios; Text-Attribute GeneraL Controller (Tailor) proposes a multi-attribute prompt concatenation and attribute connector strategy to achieve simultaneous control of multi-dimensional attributes, but a single template still limits the model's generalization ability to diverse text structures; and Plug-and-Play Controller methods... The Prompt-PPC and Plug and Play with Prompts (PPP) methods dynamically adjust the prompt embedding through an external attribute classifier and optimize the prompt vector using the classifier gradient during the inference phase, taking into account both the fluency of the generated text and attribute consistency.

[0007] Overall, soft suggestion methods achieve controllable task adaptation with low parameter overhead while preserving the generality of pre-trained models, and represent an important development direction for the controllable generation of large-scale pre-trained language models.

[0008] Despite significant progress in the fluency, diversity, and applicability of controllable text generation methods based on large-scale pre-trained language models, existing methods still face two core challenges in practical applications. Firstly, controllable generation datasets often exhibit inherent distributional tendencies, which can be viewed as unannotated implicit attributes. These tendencies introduce non-target attribute signals during training and generation, interfering with the control effect of the target attribute. Secondly, cue-based optimization methods typically use randomly initialized prefixes. The semantic signals of the target attribute are weak in the early stages of training, which not only reduces the learning efficiency of the prefixes but also affects the accuracy and fluency of the generated text. Summary of the Invention

[0009] This invention aims to at least solve the technical problems existing in the prior art, and in particular, it innovatively proposes a controllable text generation method that integrates differential correction and explicit semantic guidance.

[0010] To achieve the above-mentioned objectives of this invention, this invention provides a controllable text generation method that integrates differential correction and explicit semantic guidance, comprising the following steps:

[0011] S1. Construct a differential correction mechanism. Given the input context, perform forward computation using the specific soft prefix and the general soft prefix of the transformer model respectively. Normalize the computation results to obtain the specific soft prefix distribution and the general soft prefix distribution. Perform a weighted difference operation on the specific soft prefix distribution and the general soft prefix distribution to obtain a corrected mixed distribution, so as to weaken the interference of the inherent distribution tendency of the dataset on the control of the target attribute.

[0012] S2, construct an explicit semantic guidance strategy, predefine a target attribute keyword set, obtain an attribute semantic representation based on the keyword set, map the attribute semantic representation to the prefix space and use it to initialize the parameters of the specific soft prefix, and inject an initial explicit semantic signal into the specific soft prefix;

[0013] S3, Model Training and Text Generation: During the training phase, the main parameters of the basic language model are frozen and the prefix parameters are optimized. During the generation phase, the original distribution of the basic language model and the attribute distribution corrected by the differential correction mechanism are fused, and a text sequence that conforms to the target attribute is generated by sampling.

[0014] In the preferred embodiment of the above technical solution, step S1, which involves forward calculation using a specific soft prefix and a general soft prefix, includes: calculating the attribute probability distribution based on the target attribute using the specific soft prefix; calculating the overall trend distribution based on the overall generation trend of the dataset using the general soft prefix; and then normalizing the attribute probability distribution and the overall trend distribution respectively.

[0015] In a preferred embodiment of the above technical solution, the weighted difference operation includes: weighting the specific soft prefix distribution with a difference correction coefficient, and then weighting the general soft prefix distribution with corresponding weights based on the difference correction coefficient as a deviation term, followed by normalization to obtain the corrected mixed distribution. Specifically, the weight of the specific soft prefix distribution is 1+α, the weight of the general soft prefix distribution is α, and the difference between the two weights is always equal to 1, forming an affine combination that maintains the overall probability quality; the difference result is truncated element-wise to non-negativity and then normalized by the sum of elements to ensure that the corrected mixed distribution is a valid probability distribution under any non-negative α.

[0016] In the preferred embodiment of the above technical solution, step S2, obtaining the attribute semantic representation based on the keyword set, includes: obtaining the word embedding vector of each keyword in the keyword set and averaging them to obtain an average semantic vector, and then mapping the average semantic vector to the prefix space through a projection matrix to obtain the attribute semantic representation.

[0017] In the preferred embodiment of the above technical solution, the explicit semantic guidance strategy only applies to the specific soft prefix, while the general soft prefix remains randomly initialized.

[0018] In the preferred embodiment of the above technical solution, the training phase in S3 includes: using the cross-entropy loss of the autoregressive language model as the optimization objective, freezing the main parameters of the basic language model, updating only the parameters of the specific soft prefix and the general soft prefix, so that the specific soft prefix learns the target attribute distribution, and the general soft prefix learns the overall generation trend of the dataset.

[0019] In a preferred embodiment of the above technical solution, the generation stage includes: at each generation step, fusing the original distribution of the basic language model with the attribute distribution corrected by the differential correction mechanism to obtain the conditional probability of the next word, filtering candidate words based on the conditional probability and sampling to generate the next word, and repeating this process until a complete text sequence is generated.

[0020] In a preferred embodiment of the above technical solution, a control strength parameter is introduced during the fusion process to adjust the degree of influence of the attribute control signal on the final generated distribution.

[0021] In a preferred embodiment of the above technical solution, the controllable text generation method is applied to one or more of the tasks of emotion control, topic control, and toxicity avoidance.

[0022] In a preferred embodiment of the above technical solution, the lengths of the specific soft prefix and the general soft prefix are configured according to task requirements; the basic language model adopts the GPT-2 series model.

[0023] In summary, due to the adoption of the above technical solution, the beneficial effects of the present invention are:

[0024] To address the issue that the inherent distributional tendency of controllable generated datasets can easily introduce implicit attribute interference, this invention proposes a differential correction mechanism. This mechanism introduces a general soft prefix to model the overall generation trend of the dataset and performs distribution-level weighted differencing between the normalized distribution of specific soft prefixes and the general soft prefix distribution. This mitigates the interference of the inherent distributional tendency of the dataset on the generation of target attributes, improving the accuracy of attribute control. To address the problem that existing prompting optimization methods result in weak semantic signals and low learning efficiency in the early stages of training due to random prefix initialization, this invention proposes an explicit semantic guidance strategy. This strategy initializes specific soft prefixes using target attribute keywords, ensuring that the specific soft prefixes carry clear attribute semantic information from the early stages of training. This enhances the target attribute control signal and improves the accuracy of generated text attributes. Experiments on three tasks—emotional control, topic control, and toxicity avoidance—verify that this invention significantly improves the fluency and naturalness of the generated text while enhancing attribute control accuracy. Compared to existing baselines, this method demonstrates superior control performance in all three tasks, accurately generating target attribute text and effectively avoiding biased or harmful content.

[0025] Additional aspects and advantages of the invention will be set forth in part in the description which follows, and in part will be obvious from the description, or may be learned by practice of the invention. Attached Figure Description

[0026] The above and / or additional aspects and advantages of the present invention will become apparent and readily understood from the description of the embodiments taken in conjunction with the following drawings, in which:

[0027] Figure 1 This is the overall framework diagram of the DCSG of this invention;

[0028] Figure 2 This is a graph showing the impact of parameters on model performance in the emotion control task of this invention;

[0029] Figure 3 This is a diagram showing the impact of parameters on model performance in the subject control task of this invention;

[0030] Figure 4 This is a graph showing the impact of parameters on model performance in the toxicity avoidance task of this invention;

[0031] Figure 5 This is a graph showing the impact of different scale language models of this invention on the performance of text generation tasks;

[0032] Figure 6 This is a graph showing the effect of different sequence lengths on the control effect of the present invention. Detailed Implementation

[0033] Embodiments of the present invention are described in detail below. Examples of these embodiments are shown in the accompanying drawings, wherein the same or similar reference numerals denote the same or similar elements or elements having the same or similar functions throughout. The embodiments described below with reference to the accompanying drawings are exemplary and are only used to explain the present invention, and should not be construed as limiting the present invention.

[0034] like Figures 1 to 6 As shown, this invention discloses a controllable text generation method integrating differential correction and explicit semantic guidance, namely DCSG (Differential Correction and Explicit Semantic Guidance). This method optimizes only the prefix vector while freezing the parameters of the GPT-2 base model to achieve efficient attribute control. Specifically, based on the differential correction mechanism, it models the overall generation trend of the dataset using a general prefix, and performs distribution-level weighted differencing between the specific prefix distribution and the general prefix distribution during the generation stage, thereby reducing the interference of the dataset's inherent distributional bias on the generation of target attributes. Simultaneously, an explicit semantic guidance strategy is proposed, using target attribute keywords to semantically initialize specific prefixes, enabling the prefixes to carry explicit attribute semantic information in the early stages of training, thus helping to accelerate model convergence and enhance attribute control strength. Experimental results show that this method outperforms various baseline methods in three tasks: sentiment control, topic control, and toxicity avoidance. It can improve attribute control accuracy while maintaining good text fluency, providing a more stable and effective solution for attribute-controllable text generation. The method includes:

[0035] Given a sequence of tokens of length n and a set of controllable attributes Controlled text generation tasks aim to address the issue of given context. Generate the next token under the condition Formally, the generation of the next token is represented as a conditional probability, specifically calculated as follows:

[0036] ;

[0037] in, This is a conditional probability calculation function used to calculate the probability of a target event occurring under given conditions. The target token at the nth position in a token sequence of length n is the language unit to be generated in the current step. From the 1st to the 1st A sequence of preceding context tokens represents all the generated preceding content. for The element-wise expansion of corresponds sequentially to the 1st, 2nd, ... th element in the sequence above. One token; vertical line The left side is the target event to be predicted, and the right side is the known preconditions.

[0038] This formula is the basic form without attribute constraints, defining the generation of tokens under the condition of an already generated preceding token. The probability of.

[0039] Further under attribute control As a condition, it is extended to the generation of a complete sequence, generating a sequence. The conditional probability is expressed as:

[0040]

[0041] in, The joint conditional probability of generating a complete token sequence X given a target attribute; This is a series of multiplication operations from the 1st to the nth position, representing the generation probability of each position in the sequence being multiplied sequentially; n is the total length of the complete token sequence; i is the position index of the token in the sequence; The single-step conditional probability of generating the i-th token under the constraints of the generated context and target attributes; The context sequence preceding the i-th token, i.e., from the 1st to the i-th token. The generated content consists of several tokens; C is the set of target attributes, such as sentiment, topic category, toxicity constraints, and other generation control conditions. A unified convention is used: 'a' represents a specific target attribute currently in effect within set C, i.e., 'a' belongs to C, and subsequent formulas involving a single attribute will use 'a' as the attribute label; the sequence length during the generation phase is denoted as 'n', and the sequence length of the training corpus is denoted as 'T'.

[0042] The goal of controllable text generation is to design a model that generates sequences. conditional probability Maximize this to generate text that is both coherent and natural, and satisfies the target attributes.

[0043] The DCSG method proposed in this invention aims to improve the accuracy and fluency of text in attribute control tasks. Attribute Distribution Reconstruction for Decoding-Time (Air-Decoding) alleviates the attribute distribution imbalance problem under high-intensity control by reconstructing attributes, but it mainly focuses on the weight balance within the attribute distribution and is insufficient in modeling the interference caused by the inherent distributional tendencies of the dataset. These tendencies can be regarded as implicit attributes that are not explicitly labeled, which may introduce non-target attribute signals during training and generation, thereby interfering with the control of the target attribute. To mitigate the interference of the inherent distributional tendencies of the dataset on the generation of target attributes, this invention introduces a general soft prefix on the basis of the Air-Decoding framework to model the overall generation trend of the dataset. During the generation stage, the Distribution-level Subtraction Method (DLSM) is used to differentially correct the outputs of specific soft prefixes and the general soft prefix, thereby weakening the influence of non-target attribute signals on the generation process. Simultaneously, this invention proposes an explicit semantic guidance strategy, using target attribute keywords to initialize specific soft prefixes, so that the prefixes carry explicit attribute semantic information from the early stages of training. During the training phase, the main parameters of the GPT-2 base language model are frozen, and only the prefix vectors are optimized. The main parameters of the base language model remain fixed throughout training to provide basic language modeling capabilities and ensure the fluency of text generation. During the generation phase, the conditional probability of each token is jointly determined by the distribution of the base language model and the attribute distribution after attribute reconstruction and general soft prefix correction, thus achieving a balance between attribute control and text fluency. The overall framework is as follows: Figure 1 As shown.

[0044] To mitigate the interference of inherent distributional tendencies in the dataset on the generation of target attributes, this invention introduces a general soft prefix differential correction mechanism (DCM) based on the Air-Decoding framework. This mechanism borrows the idea of ​​co-modeling specific and general soft prefixes in Focused Prefix Tuning, distinguishing the target attribute control signal from the overall generation trend of the dataset. Specifically, the specific soft prefix is ​​used to learn the generation distribution under a given target attribute, while the general soft prefix is ​​used to learn the general generation trend of the dataset as a whole. By differentially correcting the output distributions of both during the generation stage, the model can reduce the interference of inherent distributional tendencies in the data on the generation process while preserving the target attribute signal.

[0045] S1. Construct a differential correction mechanism. Given the input context, perform forward computation using the specific soft prefix and the general soft prefix of the transformer model respectively. Normalize the computation results to obtain the specific soft prefix distribution and the general soft prefix distribution. Perform a weighted difference operation on the specific soft prefix distribution and the general soft prefix distribution to obtain a corrected mixed distribution, so as to weaken the interference of the inherent distribution tendency of the dataset on the control of the target attribute.

[0046] Define context for input For target attributes The model performs forward computation using both the specific soft prefix and the general soft prefix of the transformer model to obtain the corresponding logits, denoted as follows: and To ensure that the two types of prefix outputs are in a comparable probability space, this invention first performs a normalization process with numerical stabilization, the calculation of which is as follows:

[0047] ;

[0048] ;

[0049] Where t represents the generation time step of the current token; , These are the maximum values ​​in the corresponding logits vectors, and the max function acts on them respectively. and The maximum value in the corresponding logits vector is used to achieve numerical stability of softmax and avoid overflow in exponential operations; It is a probability normalization function that transforms the input real-valued vector into a valid probability distribution with a sum of 1 and values ​​between 0 and 1. After normalization, the attribute probability distribution corresponding to a specific soft prefix contains both the target attribute signal and non-target attribute noise brought about by the inherent distribution tendency of the dataset. After normalization, the overall generation trend distribution corresponding to the general soft prefix only reflects the general generation pattern and inherent distribution deviation of the dataset.

[0050] The present invention calculates the correction for the mixed distribution as follows:

[0051] ;

[0052] ;

[0053] in, is the intermediate vector obtained by weighted difference and non-negative truncation at step t; the max function is the element-wise non-negative truncation function, which sets the negative components generated by the difference to zero to ensure the non-negativity of the probability; 1+α is the amplification weight of the specific soft prefix distribution, and α is the deduction weight of the general soft prefix distribution. The difference between the two is always equal to 1, forming an affine combination to keep the total probability quality of the distribution before and after the difference consistent. This holds true for any non-negative α deduction direction; V is the vocabulary, that is, the set of all candidate words in the basic language model; v is the candidate word in the vocabulary; The denominator is the intermediate vector The sum of the elements in vocabulary V is normalized to make the sum of the components equal to 1. This represents the final mixed probability distribution after the correction at step t, which is used for subsequent word sampling and generation.

[0054] When α equals 0, the deduction term is zero. Degenerate into This corresponds to the ablation scenario where the differential correction mechanism is removed; as α increases, the intensity of the subtraction of the general soft prefix distribution increases accordingly, and the model's suppression of the inherent distributional bias of the dataset is enhanced. In this way, the mixed distribution... It can reduce the impact of non-target attribute signals on the generation process while preserving target attribute information.

[0055] In subsequent generation processes, this invention incorporates this hybrid distribution into the attribute probability calculation. For each token generated in each step, the model updates the probability ratios between different attributes based on the hybrid distribution, and combines this with the attribute distribution reconstruction method in the baseline to obtain a more stable attribute control distribution. Ultimately, the basic language model distribution and the corrected attribute distribution jointly determine the generation probability of the next token.

[0056]

[0057] in, Given the preceding context and target attributes, generate the final conditional probability of the t-th token; Let be the target token at position t in the sequence. This refers to the entire preceding sequence of the t-th token; The sign is a positive proportion, indicating that the final probability is positively correlated with the product on the right. The complete probability distribution can be obtained by normalization without changing the relative probability ratio of each candidate token. The original generation distribution of the basic language model in the current context. This represents the attribute control distribution after attribute reconstruction and general soft prefix difference correction. The intensity parameter is used to adjust the influence of the attribute control signal on the final generated distribution.

[0058] Overall, the general soft prefix differential correction mechanism reduces the interference of inherent data distribution tendencies on target attribute control by introducing a general soft prefix to model the overall generation trend of the dataset and performing weighted differencing between the output distributions of specific soft prefixes and the general soft prefix during the generation stage. Compared with generation methods that rely solely on specific soft prefixes, this mechanism enables the model to further improve the accuracy and fluency of generated text while maintaining the consistency of target attributes.

[0059] S2, construct an explicit semantic guidance strategy, predefine a target attribute keyword set, obtain an attribute semantic representation based on the keyword set, map the attribute semantic representation to the prefix space and use it to initialize the parameters of the specific soft prefix, and inject an initial explicit semantic signal into the specific soft prefix;

[0060] To further enhance the expressive power of specific soft prefixes for target attributes, this invention proposes an Explicit Semantic Guidance (ESG) strategy. Unlike the random initialization of prefixes, this strategy semantically initializes specific soft prefixes with keywords related to the target attribute before training begins, enabling them to carry explicit attribute semantic information from the early stages of training. This helps to strengthen attribute control signals and improve the attribute consistency of the generated text.

[0061] In the specific implementation, a keyword set is predefined for each explicit attribute. For example, the set of positive sentiment attributes corresponds to {good, great, excellent, amazing, wonderful}, and the set of negative sentiment attributes corresponds to {bad, terrible, awful, horrible, disgusting}. A similar approach is used for the topic and detoxification task sets. For each attribute prefix, it is first encoded into a token sequence using a GPT-2 tokenizer, and the corresponding token vector is obtained from the GPT-2 word embedding layer. Subsequently, the word embeddings of all keyword tokens are averaged to obtain the semantic representation of the target attribute. The average semantic vector is represented as follows:

[0062]

[0063] in, Indicates the first Keyword token word embedding, This represents the total number of tokens obtained after word segmentation of the keyword set. Represents attributes The corresponding average semantic vector, This is an element-wise summation operation used to accumulate the word embedding vectors of the first to Nth keywords; The coefficient is used to calculate the mean, which is used to average the accumulated vector to eliminate the influence of the difference in the number of keywords on the vector magnitude and obtain a stable and unified semantic representation of the attribute. Since the GPT-2 word embedding dimension and the prefix intermediate dimension may be inconsistent, this invention further maps the average semantic vector to the prefix space through the projection matrix.

[0064]

[0065] in, The projection matrix is ​​initialized using Xavier uniform initialization. This represents the attribute semantic vector mapped to the intermediate dimension of the prefix. The average semantic vector corresponding to the target attribute 'a' is obtained by averaging the word embeddings of all keywords for that attribute, carrying the core semantic information of the target attribute. If the word embedding dimension is the same as the prefix median dimension, the average semantic vector is directly used as the initialization vector. Subsequently, the mapped attribute semantic vector is expanded into a matrix with the same length as the prefix and used to initialize the Key and Value representations of the corresponding specific soft prefix. In this way, the explicit semantic information in the target attribute keywords is introduced into the specific soft prefix parameters, giving the prefix a certain semantic foundation from the early stages of training.

[0066] It should be noted that explicit semantic guidance only applies to specific soft prefixes, while the general soft prefix remains randomly initialized. This is because the goal of specific soft prefixes is to learn explicit target attribute control signals, while the general soft prefix is ​​primarily used to model the overall generation trend of the dataset. Adding attribute keyword initialization to the general soft prefix might weaken its role as a general background distribution.

[0067] During the generation phase, specific soft prefixes, initialized and trained with explicit semantic guidance, participate in attribute distribution calculation, providing more explicit semantic control signals for target attribute generation. Furthermore, this specific soft prefix distribution works in conjunction with the general soft prefix distribution in the differential correction mechanism, enabling the model to strengthen the expression of target attributes while mitigating non-target attribute interference caused by the inherent distributional bias of the dataset.

[0068] Overall, explicit semantic guidance initializes specific soft prefixes with attribute keywords, giving the model a clear semantic foundation for target attributes in the early stages of training. This helps improve text fluency and attribute consistency of generated text. This strategy does not require modification of the main parameters of the GPT-2 base language model, exhibiting good parameter efficiency and task adaptability. It can be applied to various attribute-controllable text generation tasks, such as sentiment control, topic control, and toxicity avoidance.

[0069] S3, Model Training and Text Generation: During the training phase, the main parameters of the basic language model are frozen and the prefix parameters are optimized. During the generation phase, the original distribution of the basic language model and the attribute distribution corrected by the differential correction mechanism are fused, and a text sequence that conforms to the target attribute is generated by sampling.

[0070] During the training phase, this invention uses the cross-entropy loss of an autoregressive language model as the optimization objective, enabling the model to predict the next token given an attribute prefix. For the input sequence... The training objective is represented by the following formula:

[0071]

[0072] in, Let t be the target token at position t in the sequence. For the entire preceding sequence of the t-th token, The main parameters of the frozen GPT-2 base language model, This represents the trainable prefix parameters. During training, only the prefix-related parameters are updated to learn the distribution of the target attribute for a specific soft prefix and the overall generation trend of the general soft prefix learning dataset.

[0073] During the generation phase, the model performs autoregressive generation based on the input prompt. At each generation step, the conditional probability distribution of the next token is jointly determined by the original distribution of the base language model and the attribute distribution after attribute reconstruction and differencing. Subsequently, the model filters candidate tokens using a Top-K algorithm and generates the next token based on multinomial distribution sampling, repeating this process until a complete text sequence is generated. This process enables control over target attributes while maintaining text fluency.

[0074] To make the objectives, technical solutions, and advantages of this invention clearer, the invention will be further described in detail below with reference to specific embodiments.

[0075] Example 1

[0076] Step 1: Generate a text quality evaluation index system. Automatic evaluation: To comprehensively evaluate the quality of the generated text, automatic evaluation is performed from three aspects: attribute accuracy, text fluency, and diversity. (1) Attribute accuracy: For sentiment and topic tasks, referring to the evaluation scheme of the existing technology Air-Decoding, an enhanced pre-trained language model (RoBERTa) classifier trained on the Yelp user review dataset and the AG News topic classification dataset is used to calculate the attribute accuracy of the generated text. For the toxicity avoidance task, the average toxicity of the generated text is evaluated using the text toxicity detection standard interface (Perspective API) to measure the model's performance in reducing harmful content. (2) Text fluency: Perplexity (PPL) is calculated using GPT-2 large to reflect the fluency of the text. A lower PPL value indicates that the generated text is more natural and more in line with language habits. (3) Generative diversity: To reflect the richness of the generated text and avoid repetition and templates, a standard evaluation metric (distinctness) is used to evaluate the diversity of generated text. Specifically, the number of 1-grams, 2-grams, and 3-grams in all generated texts is calculated, and their proportions in all words are counted, denoted as Dist-1, Dist-2, and Dist-3.

[0077] Human evaluation: Referring to the existing Air-Decoding technology's human evaluation criteria, the generated text is scored from three dimensions: relevance, topicality, and fluency. (1) Relevance: Measures whether the generated text accurately reflects the specified controlled attributes, such as sentiment or topic. (2) Topicality: Evaluates whether the generated text is consistent with the content of the input prompt, that is, whether the generated text closely follows the given context. (3) Fluency: Evaluates the naturalness and readability of the text from a human perspective, including the rationality of grammar, word choice, and sentence structure.

[0078] Step 2: Compare the baseline methods and experimental settings to verify the effectiveness of the DCSG method in the controllable text generation task, and compare it with six representative baseline methods. (1) Generative Discriminator (GeDi): Uses a small class-conditional generation model to guide a large model to generate text, achieving target attribute control. (2) Decoding with Domain Experts (DExperts): Combines experts and reverse expert models to reduce the probability of non-target attribute generation and enhance attribute control accuracy. (3) Air-Decoding: Reconstructs logits weights in the decoding stage to suppress latent attribute interference and improve text attribute preservation and fluency. (4) Tailor: Represents each attribute as a soft prefix and combines multiple prefixes through non-training strategies or MAP connectors to achieve controllable single / multi-attribute text generation. (5) Freedom + Control (FreeCtrl): Uses keyword constraints and adaptive attribute adjustment to control the generated text in a lightweight or training-free manner. (6) Dynamic Token-level Prefix Augmentation (DTPA): Dynamically enhances token-level prefix attention and reconstructs attribute distribution, improving attribute control in long text generation.

[0079] This experiment follows the experimental setup of Air-Decoding, using its published results as a baseline, and maintains the same model architecture, training, and sampling settings as the original method to ensure the fairness and reproducibility of the comparison.

[0080] Step 3: Emotional Control Task Experiment

[0081] Experiment setup

[0082] Dataset: For the sentiment control task, the IMDb dataset is used. This dataset contains movie review texts labeled with positive or negative sentiment tags and is widely used in sentiment analysis and sentiment control generation research. To train the sentiment attribute generation model, 5K positive reviews and 5K negative reviews are randomly selected as training data. A total of 10,000 training samples are used, with a balanced number of positive and negative classes to avoid introducing new distributional biases into the prefixes due to prior class differences. In the generation phase, 15 prompts are used, consistent with existing benchmark methods. Each prompt generates 50 positive texts and 50 negative texts, with a text length of 50 characters.

[0083] Training settings: During training, GPT-2 medium was used as the base model, with a batch size of 4, weight decay of 0.01, a learning rate of 3e-5, and 5 training epochs. During the generation phase, the control strength was set to 130, and Top-k random sampling (Top-k=200) was used. DCSG (w / o DCM) is a variant of DCSG with the differential correction mechanism removed, and DCSG (w / o ESG) is a variant of DCSG with the explicit semantic guidance strategy removed.

[0084] Automatic evaluation results

[0085] Table 1. Experimental results of the emotion control task. Bold text indicates best results.

[0086]

[0087] GeDi: Derived from Generative Discriminator, it stands for Generative Discriminator. "Ge" comes from Generative, and "Di" from Discriminator. The full meaning of its title is Sequence Generation Guided by Generative Discriminator.

[0088] Air-Decoding: The full title of the paper is Air-Decoding: Attribute Distribution Reconstruction for Decoding-Time Controllable Text Generation, which translates to "Attribute Distribution Reconstruction Method for Decoding-Time Controllable Text Generation".

[0089] Tailor: Derived from Text-Attribute general controller, it is a general controller for text attributes. Based on the case of the original text, the extracted letters are T, A, I, L, O, and R, which are combined to form Tailor.

[0090] FreeCtrl: This stands for Learning-Free or Control-Free. The original paper defines it as a controllable text generation method that requires no training or learning process, controlling text attributes by adjusting the weights of the feedforward network vectors.

[0091] DTPA stands for Dynamic Token-level Prefix Augmentation. Here, 'D' stands for Dynamic, 'T' for Token-level, 'P' for Prefix, and 'A' for Augmentation.

[0092] DCSG, derived from Differential Correction and Explicit Semantic Guidance, is the complete method proposed in this application.

[0093] DCM stands for Differential Correction Mechanism.

[0094] ESG stands for Explicit Semantic Guidance.

[0095] w / o: is a common abbreviation of without, indicating that a module is not included, removed, or disabled.

[0096] DCSG (w / o DCM): DCSG with differential correction mechanism removed, i.e., an ablation model that retains only the explicit semantic guidance strategy.

[0097] DCSG (w / o ESG): DCSG with explicit semantic guidance strategies removed, i.e., an ablation model that retains only the differential correction mechanism.

[0098] DCSG: A complete model that includes both differential correction mechanisms and explicit semantic guidance strategies.

[0099] The automatic evaluation results of the emotion control task are shown in Table 1. The DCSG method outperforms most baseline methods in both accuracy and text fluency. Specifically, GeDi and DExpert perform poorly in text fluency, with GeDi achieving the worst fluency score of 169.86, indicating that separating the guidance model from the generation model may affect the naturalness and overall quality of the generated text. Air-Decoding and FreeCtrl perform well in both accuracy and text fluency, with FreeCtrl slightly outperforming other baselines in diversity. Tailor's generated text is relatively conservative, performing only moderately in both accuracy and diversity. DTPA achieves high accuracy, but its diversity is still slightly inferior to FreeCtrl.

[0100] In comparison, the DCSG method demonstrates significant advantages across all three key metrics, achieving an accuracy of 98.93%, significantly higher than all baselines; and a perplexity of only 23.61, a reduction of 11.44% compared to Air-Decoding. Simultaneously, it maintains good levels in diversity metrics (Dist-1: 0.11, Dist-2: 0.46, Dist-3: 0.68), although slightly lower than FreeCtrl, balancing attribute control precision and generated text quality. Ablation experiments further demonstrate that the DCM and ESG modules positively contribute to model performance, enabling the method to achieve a good balance between attribute control, text fluency, and diversity.

[0101] Step 4: Subject Control Task Experiment

[0102] In the topic control task, the AGNews dataset was used. This dataset contains text from news articles and is labeled with four topic categories: World, Sports, Business, and Science. To train the topic attribute generation model, 5K samples were randomly selected in addition to the training data for the topic classifier. Consistent with the evaluation settings of existing state-of-the-art benchmark methods, 20 prompts were used for generation, with each prompt generating 50 texts per topic, all with a length of 50 characters. The training parameter settings were the same as for the sentiment control task, except that the control strength was set to 40.

[0103] Automatic evaluation results

[0104] Table 2. Experimental results of the topic control task. Bold text indicates best results.

[0105]

[0106] As shown in Table 2, the DCSG method outperforms most baseline methods in both accuracy and text fluency. Compared to GeDi and Tailor, DCSG achieves approximately 4–14 percentage points higher accuracy while significantly reducing perplexity, demonstrating superior text fluency. Compared to Air-Decoding and FreeCtrl, DCSG achieves slightly higher accuracy while maintaining a good level of diversity, although its Dist-1 metric is slightly lower than FreeCtrl. Using the full model, DCSG achieves 98.18% accuracy while maintaining high text fluency, demonstrating a good balance between attribute control and text quality. Ablation experiments show that removing two modules slightly reduces performance, indicating that these two modules have a positive effect on model stability and generation quality.

[0107] Step 5: Toxicity Avoidance Task Experiment

[0108] In the toxicity avoidance task, the Jigsaw Unintended Bias in ToxicityClassification Kaggle dataset was used for training. To train the attribute generation model, 5K toxic comments and 5K non-toxic comments were randomly selected from the dataset, with each prefix having a length of 20. During the generation phase, a selection of prompts consistent with existing benchmark methods was used as input; these prompts were derived from RealToxicityPrompts. Each prompt generated 20 texts with a length of 50. Training and generation parameter settings were consistent with the sentiment control task, except that the control strength was set to 120. All experiments were performed on an NVIDIA GeForce RTX 3090 environment.

[0109] Automatic evaluation results

[0110] Table 3. Experimental results of the toxicity avoidance task. Bold text indicates best results.

[0111]

[0112] As shown in Table 3, in the toxicity avoidance task, the DCSG method demonstrates significant advantages in both average toxicity and text fluency. GeDi and DEXPERT have average toxicities of 20.5 and 20.0, respectively, indicating limitations in reducing text toxicity. Furthermore, GeDi's PPL is as high as 166.01, indicating poor text fluency. Air-Decoding and DTPA show a balanced performance in toxicity control and PPL, demonstrating good control capabilities and text quality. Compared to the baselines, the DCSG method performs exceptionally well in the toxicity control task, reducing the average toxicity to 9.2 while maintaining low perplexity. In terms of diversity metrics, the complete DCSG model is slightly lower than some baselines, but still maintains a good level of text diversity. These results demonstrate that the DCSG method can not only significantly reduce text toxicity but also maintain good generation quality and reasonable diversity.

[0113] Step Six: Manual Evaluation of Results

[0114] Experimental Setup: Ten samples were randomly selected from the generated text for manual evaluation. Each text was scored by three independent annotators. Annotators evaluated each text based on relevance, fluency, and topic consistency, using a 1-10 scale, where 1 represents the worst and 10 represents the best. The final score for each text was the average of the three annotators' scores to ensure the objectivity and reliability of the evaluation results. The evaluation tasks covered three types of controllable text generation tasks: sentiment control, topic control, and toxicity avoidance, to comprehensively examine the model's performance under different control attributes.

[0115] Table 4. Results of manual evaluation

[0116]

[0117] In human evaluation, the DCSG method outperformed baseline methods in all three tasks: sentiment control, topic control, and toxicity avoidance. Evaluation results show that the DCSG method achieved higher scores in attribute relevance, fluency, and topic consistency, indicating that the model can more accurately achieve the required attribute control while maintaining text naturalness and readability. In the sentiment control task, the text better reflects the target sentiment, and the sentences are coherent and read more naturally. In the topic control task, the generated text closely follows the topic content of the input prompt, demonstrating stronger topic consistency. In the toxicity avoidance task, the text has low toxicity and maintains good semantic coherence, with overall generation quality significantly better than Air-Decoding. Overall, the DCSG method not only has strong attribute control capabilities in multi-task controllable text generation but also balances text fluency and topic consistency, demonstrating good stability and generalization ability.

[0118] Step 7: Performance Influencing Factor Analysis and Scalability Verification

[0119] like Figures 2 to 4 As shown, to further study the parameters in the differential correction mechanism To assess the impact on the generated results, this invention conducted parameter analysis experiments within a range of 0-5, evaluating the effects from two perspectives: attribute control effectiveness and text fluency. Experimental results show that different tasks exhibit varying degrees of sensitivity to parameters; in emotion tasks, [the sensitivity is not specified in the original text]. A value of 0.5 yields the highest accuracy and lowest perplexity, hence this value is chosen. In the thematic task, as the parameter increases, accuracy decreases but perplexity significantly reduces. Considering both attribute control and fluency performance, [the following value is selected]. =3.0; In the toxicity avoidance task, When the value is 1.0, the toxicity value is low and the perplexity is the lowest, which can better balance the detoxication effect and text quality. Therefore, this value is selected as the final parameter.

[0120] To verify the scalability of the method of this invention, it was extended to the larger pre-trained language model GPT-2 large, and experiments were conducted on three tasks: emotion control, topic control, and toxicity avoidance. The results are as follows: Figure 5 As shown in the figure. Experimental results show that, even with increased model size, the method of this invention can still maintain good performance in different types of controllable text generation tasks, indicating that the proposed differential correction mechanism and explicit semantic guidance strategy do not depend on a specific scale of base model and have a certain degree of model scalability.

[0121] like Figure 6 As shown, to analyze the impact of different generation lengths on the control effect, experiments were conducted with generation lengths of 100, 150, and 256. The experiments show that the emotion and toxicity avoidance tasks maintain good performance across different generation lengths, indicating good stability of the method. The accuracy of the topic control task decreases slightly with increasing length, indicating a certain attenuation of topic constraints in long texts. Overall, the method of this invention maintains relatively stable control performance even in the generation of longer texts.

[0122] This invention proposes a controllable text generation method that integrates differential correction and explicit semantic guidance. A differential correction mechanism is introduced on top of baselines, capturing inherent biases in the dataset through a general soft prefix and performing distribution-level weighted differencing during the generation phase to reduce their interference with text generation. Simultaneously, explicit semantic guidance initializes specific soft prefixes with keywords, enabling the model to possess target attribute semantics early in training, accelerating convergence and improving the consistency of generated text. During training, the base model is frozen, and only the prefix vectors are optimized, achieving efficient parameter control; the generation phase, combined with the differential correction mechanism, achieves a balance between attribute control and text fluency. Experimental results show that this method outperforms multiple baselines in sentiment, topic, and toxicity control tasks, significantly improving accuracy and fluency. Ablation experiments verify the significant contributions of the differential correction mechanism and explicit semantic guidance to performance.

[0123] Although embodiments of the invention have been shown and described, those skilled in the art will understand that various changes, modifications, substitutions and alterations can be made to these embodiments without departing from the principles and spirit of the invention, the scope of which is defined by the claims and their equivalents.

Claims

1. A controllable text generation method integrating differential correction and explicit semantic guidance, characterized in that, Includes the following steps: S1. Construct a differential correction mechanism. Given the input context, perform forward computation based on the target attribute using a specific soft prefix of the transformer model to obtain the forward computation result corresponding to the target attribute. Perform forward computation based on the overall generation trend of the dataset using a general soft prefix of the transformer model to obtain the forward computation result corresponding to the overall generation trend. Normalize the two forward computation results to obtain the attribute probability distribution as the specific soft prefix distribution and the overall trend distribution as the general soft prefix distribution. Perform a weighted difference operation on the specific soft prefix distribution and the general soft prefix distribution to obtain a corrected mixed distribution, so as to weaken the interference of the inherent distribution tendency of the dataset on the control of the target attribute. S2, construct an explicit semantic guidance strategy, predefine a target attribute keyword set, obtain the word embedding vector of each keyword in the keyword set and take the average to obtain an average semantic vector, then map the average semantic vector to the prefix space through a projection matrix to obtain an attribute semantic representation, and use the attribute semantic representation to initialize the parameters of the specific soft prefix, injecting an initial explicit semantic signal into the specific soft prefix; S3, Model Training and Text Generation: During the training phase, the main parameters of the basic language model are frozen and the prefix parameters are optimized. During the generation phase, at each generation step, the original distribution of the basic language model is fused with the attribute distribution corrected by the differential correction mechanism to obtain the conditional probability of the next word. Based on the conditional probability, candidate words are selected and sampled to generate the next word. This process is repeated until a complete text sequence is generated to generate a text sequence that meets the target attributes.

2. The method according to claim 1, characterized in that, The weighted difference operation includes: weighting the specific soft prefix distribution with a difference correction coefficient, weighting the general soft prefix distribution with a weight based on the difference correction coefficient and subtracting it as a deviation term, and then normalizing it to obtain the corrected mixed distribution.

3. The method according to claim 1, characterized in that, The explicit semantic guidance strategy applies only to the specific soft prefix, while the general soft prefix remains randomly initialized.

4. The method according to claim 1, characterized in that, In S3, the training phase includes: using the cross-entropy loss of the autoregressive language model as the optimization objective, freezing the main parameters of the basic language model, updating only the parameters of the specific soft prefix and the general soft prefix, so that the specific soft prefix learns the target attribute distribution, and the general soft prefix learns the overall generation trend of the dataset.

5. The method according to claim 1, characterized in that, The fusion process introduces a control strength parameter to adjust the degree of influence of the attribute control signal on the final generated distribution.

6. The method according to any one of claims 1 to 5, characterized in that, The controllable text generation method is applied to one or more of the following tasks: emotion control, topic control, and toxicity avoidance.

7. The method according to any one of claims 1 to 5, characterized in that, The lengths of the specific soft prefix and the general soft prefix are configured according to task requirements; the basic language model adopts the GPT-2 series model.