Year: 2021

Abstract:
Maximum likelihood estimation (MLE) is the predominant algorithm for training text generation models. This paradigm relies on direct supervision examples, which is not applicable to many emerging applications, such as generating adversarial attacks or generating prompts to control language models. Reinforcement learning (RL) on the other hand offers a more flexible solution by allowing users to plug in arbitrary task metrics as reward. Yet previous RL algorithms for text generation, such as policy gradient (on-policy RL) and Q-learning (off-policy RL), are often notoriously inefficient or unstable to train due to the large sequence space and the sparse reward received only at the end of sequences. In this paper, we introduce a new RL formulation for text generation from the soft Q-learning (SQL) perspective. It enables us to draw from the latest RL advances, such as path consistency learning, to combine the best of on-/off-policy updates, and learn effectively from sparse reward. We apply the approach to a wide range of text generation tasks, including learning from noisy/negative examples, adversarial attacks, and prompt generation. Experiments show our approach consistently outperforms both task-specialized algorithms and the previous RL methods.

heading: 1 INTRODUCTION
text: Recent natural language generation systems have made remarkable progress in producing wellformed coherent text, especially with the massive pretrained language models (LMs) (Radford et al., 2019; Brown et al., 2020; Lewis et al., 2020; Raffel et al., 2019). Those models are typically trained using maximum likelihood estimation (MLE) with a large amount of data supervisions. Despite its successful outcomes, the standard training method suffers from limited applicability to many emerging text generation problems, where little or no supervised data is available. Prominent examples of such low-data problems include generating prompts to control the massive LMs (Yin et al., 2019; Shin et al., 2020; Zhong et al., 2021), learning text generation from noisy or even negative data, generating adversarial text attacks for robustness study (Wallace et al., 2019; Atanasova et al., 2020), and others (Figure 1, right). Due to the failure of standard MLE, people have had to devise specialized algorithms for those problems respectively.
On the other hand, reinforcement learning (RL) (Sutton & Barto, 2018) offers an alternative principled framework for learning from arbitrary reward functions, and has achieved great advances in robotic and game control. However, RL by far has made limited success for training text generation, primarily due to the key challenges of sparse reward (i.e., a single reward signal is received only after the whole text sequence is generated) and large action space (i.e., a vocabulary of millions of words). For instance, a popular family of RL algorithms studied extensively for text generation is the policy-based (Williams, 1992) or actor-critic based (Bahdanau et al., 2016; Rennie et al., 2017) algorithms, with policy gradient (PG) being the most prevalent example (Ranzato et al., 2016; Li et al., 2016; Rennie et al., 2017; Tan et al., 2018; Pasunuru & Bansal, 2018; Paulus et al., 2018). Those algorithms train the model with on-policy updates, i.e., the text samples used for estimating policy gradients are from the target model itself. Due to the exponentially large space of sequences, onpolicy updates often suffer from extremely high variance and low data efficiency (e.g., most model samples are not useful for learning). Thus directly training with PG from scratch is usually impossible. In practice, the model has to be initialized by MLE training, followed by PG as finetuning, which often leads to limited improvement (Choshen et al., 2020; Wu et al., 2018).
Another set of work has resorted to off-policy RL. The key advantage is that samples from other sources, e.g., human-written text, can be used, making them more data efficient than on-policy methods. Previous work has used either importance weighted PG (Pang & He, 2021; Zhou et al., 2017; Kandasamy et al., 2017) or Q-learning based algorithms (Guo, 2015; Jaques et al., 2020; Narasimhan et al., 2015). However, off-policy methods have been considered to be less stable. For example, theQ-learning performance relies heavily on how accurate the learnedQ-function assesses the quality of intermediate subsequences – a challenging task due to the sparse reward signals.
In this paper, we develop a new RL formulation for text generation that tackles the above issues (Figure 1, left). We reframe the text generation problem from the soft Q-learning perspective originally developed in robotics (Haarnoja et al., 2017; Schulman et al., 2017). The resulting connection allows us to seamlessly take advantage of the latest successful techniques from the RL literature. In particular, we introduce and adapt the principled path consistency learning (Nachum et al., 2017) to text generation, that (1) offers a natural way to train the model with both on- and off-policy updates, hence combining the best of the two strategies, (2) bridges the sparse reward signal to directly supervise the Q function learning, leading to more accurate Q estimation and credit assignment, and (3) makes efficient updates to Q-values by considering all candidate actions together.
The generality and efficiency of the proposed method allows us to train text generation in a wide range of applications: (1) With noisy and negative training examples, our approach learns to generate accurate entailment text that greatly improves upon the data itself as well as other various training methods; (2) Our approach also manages to train an effective adversarial text generator for robustness test for classifiers; (3) We train a prompt generator with our algorithm to achieve controllable generation of pretrained LMs in terms of topics. On all the three tasks, our approach consistently improves over not only previous RL algorithms for text generation, but also diverse task-specialized methods designed specifically for each of the problems, respectively. In the appendix (§A.1.4), we also show that on standard supervised tasks where MLE prevails, our approach is competitive to train text generation models from scratch, which was usually impossible for previous RL algorithms.

heading: 2 BACKGROUND AND CHALLENGES
text: The goal of text generation is to produce coherent text y = (y0, ..., yT ) of certain properties for a given task, where yt is a token from a vocabulary V , and T is the text length. The generation can condition on arbitrary input context, which we omit for simplicity of notations. We aim to learn a
generation model pθ(y) which is typically decomposed autoregressively as pθ(y) = ∏T t=0 pθ(yt | y<t), where y<t = (y0, ..., yt−1) is the prefix, and the distribution at each step t is obtained by applying the softmax function on the output logits:
pθ(yt | y<t) = exp fθ(yt | y<t)∑ y′∈V exp fθ(y ′ | y<t) . (1)
Here fθ(y | y<t) is the logit of token y computed by the generation model. Given a training example y∗, maximum likelihood training (MLE) updates the model with the gradient ∇θLMLE(θ)= ∑T t=0∇θ log pθ (y∗t | y∗<t). Despite its popularity, MLE-based training only applies when clean supervised data y∗ is available, and cannot be used to optimize arbitrary task metrics (e.g., BLEU, entailment score) which are typically the goal in many text generation tasks.

heading: 2.1 REINFORCEMENT LEARNING (RL) FORMULATIONS FOR TEXT GENERATION
text: Notations. Previous research has formulated text generation as an RL problem by considering the following finite-time Markov Decision Process (MDP). At each time step t, let the “state” be st = y<t, namely the partial sequence generated so far. The model, also known as the “agent”, takes as input the current state st and outputs a token, also called “action”, at ∈ V according to a policy π(at | st). The agent then receives a reward rt = r(st, at) and deterministically transitions to next state st+1 (i.e., the concatenation of the tokens in st and the new token at).
Following the notation convention in RL, let τ be the trajectory (i.e., text sample) generated by the policy. The agent’s objective is to maximize the accumulative reward, J(π) = Eτ∼π [∑T t=0 γ trt ] , where γ ∈ (0, 1] is the discount factor. A central concept in RL is the Q-function of policy π, defined as Qπ(st, at) = Eπ [∑T t′=t γ t′rt′ | st, at ] , which is the expected future reward of taking action at (i.e., generating token at) in state st and continuing with the policy π.
Challenges. Text generation poses significant challenges to RL, particularly because (1) the reward signal is usually sparse, i.e., rt = 0, ∀t < T and the agent receives a non-zero reward rT only after it generates the full sequence, (2) the action space (i.e., the vocabulary V) is extremely large, often containing millions of words. The challenges have led to difficulties of the two major families of RL approaches applied to text generation problems, as detailed below.
Policy-based RL techniques directly parameterize the policy πθ with parameters θ. Thus the policy πθ(at | st) exactly corresponds to the above generation model pθ(yt | y<t). Policy gradient (PG) is one of the most widely used algorithms for text generation (Ranzato et al., 2016). It optimizes the cumulative reward with the policy gradient:
∇θJ(πθ) = −Eτ∼πθ [∑T
t=0 Q̂(st, at)∇θ log πθ (at | st)
] , (2)
where Q̂(st, at) is the estimated Qπθ value with sample τ . Notice that the expectation is taken w.r.t. the policy πθ, which makes PG an on-policy algorithm, meaning that the sample τ needs to come from the the current policy πθ itself. In practice, however, optimizing this objective alone from scratch is unlikely going to work because most samples τ ∼ πθ are just gibberish with zero reward, failing to provide meaningful training signals for updating the policy. Previous literature either initializes the policy πθ with MLE training, and/or use a combination of MLE and PG updates, which often leads to marginal gains in practice (Wu et al., 2018; Choshen et al., 2020).
Value-based RL techniques, such as Q-learning, implicitly learn the policy π by approximating the value Qπ(s, a) directly. Specifically, let Q∗(s, a) = maxπ Qπ(s, a) denote the optimal value over policies. Thus the optimal policy π∗ is simply taking the action of maximal Q∗ value at each state. The approximation of Q∗ is based on the well-known Bellman temporal consistency:
Q∗(st, at) = rt + γmaxat+1 Q ∗(st+1, at+1). (3)
Deep Q-learning (Mnih et al., 2013) parameterizes the Q-function as Qθ(x, a) (e.g., a neural network), and train the parameters by minimizing the following regression objective:
L(θ) = Eπ′ [ 0.5 · ( rt + γmaxat+1 Qθ̄(st+1, at+1)−Qθ(st, at) )2] , (4)
Single-Step PCL Training Multi-Step PCL Training
. . . sequence reward
. . . sequence reward
Figure 2: SoftQ-Learning with path consistency learning (PCL) objectives, where we illustrate with a vocabulary of size 3. Left: Single-step objective (Eq.9), where for each (st, at), the computation involves step t and t+1. Dashed boxes in dark green and gray indicate the regression target, where the intermediate reward rt is often 0 due to sparsity. The gradient is applied to parameters θ at step t (indicated by orange color). Right: Multi-step objective (Eq.11) which aggregates from step t all the way to T . In this way, the final-step non-zero reward rT is used as the regression target.
where θ̄ is the parameters of the target Q-network, which is a slow copy of θ and considered as constant for gradient computation of θ. Here π′ is an behavior policy which can be an arbitrary distribution over text, such as the data distribution or replay buffer (Mnih et al., 2013). This makes Q-learning an off-policy algorithm because of its ability to use samples coming from other policies. After learning Qθ, one can induce a policy π from it that takes arg maxaQθ(s, a) at each state s. Jaques et al. (2017) instead sample tokens from the softmax function applied to Qθ.
However, the training can be unstable and inefficient due to several challenges: (1) The bootstrapping nature of the above regression problem can make the training unstable. That is, the regression target rt + γmaxat+1 Qθ̄(st+1, at+1) itself is derived from the Q-function to be learned (Kumar et al., 2019). The problem is exacerbated in the presence of sparse reward in text generation, where the real observed signal rt is zero for all intermediate t < T ; (2) The large action space (e.g., 104) in text generation results in slow updates. In particular, notice that Eq.(4) applies the gradient update to the Qθ-value of the only one particular token at (out of the 104 candidate tokens in the vocabulary), making the training inefficient; (3) Besides, pure off-policy updates could be highly sensitive to the quality of training data, and miss the opportunity of on-policy exploration that maximizes the reward of interest in a more direct way.
3 THE SOFT Q-LEARNING FRAMEWORK
In this section, we combat the difficulties of previous RL methods by introducing the softQ-learning (SQL) formulation of text generation. We show that the formulation is seamlessly compatible with the common architecture of text generation model (Eq.1), permitting easy implementation (§3.1). The formulation further allows us to integrate the latest advances in RL, notably path consistency learning (Nachum et al., 2017) that makes the RL training efficient and stable in practice (§3.2). Figure 2 and Algorithm 1 summarizes the resulting SQL framework for efficient training.
3.1 SOFT Q-LEARNING FORMULATION FOR TEXT GENERATION
SoftQ-learning (Haarnoja et al., 2017; Schulman et al., 2017; Nachum et al., 2017) is an maximumentropy (MaxEnt) extension to the standard (hard) Q-learning (Mnih et al., 2015; Sutton & Barto, 2018). Under this framework, the agent is encouraged to optimize the reward while staying as stochastic as possible, with the objective JMaxEnt(π) = Eτ∼π [∑T t=0 γ trt + αH (π (· | st)) ] , which augments the vanilla J(π) with the additional Shannon entropy term H with coefficient α.1 This is appealing because it seamlessly connects the Q-values to the familiar output logits of a text generation model, which enables straightforward implementation of the SQL formulation.
Q-values as Generation Model Logits. We show the connection of the Q-values with the logits, i.e., the model outputs right before the softmax layer. Concretely, with the SQL objective, the following relationship between optimal policy π∗ and action-value Q∗ holds (Haarnoja et al., 2017; Schulman et al., 2017):
π∗(a | s) = expQ ∗(s, a)∑
a′ expQ ∗ (s, a′)
. (5)
1WLOG, we can assume α=1, as it can be folded into the reward function by scaling the latter with 1/α.
This form is highly reminiscent of the softmax layer of the generation model in Eq.(1). The connection suggests that we can naturally parameterize the Q-function in SQL as the generation model logit function, i.e., Qθ(s, a) ≡ fθ(a | s). In other words, the model output fθ(a | s), originally interpretted as the “logit” of token a given the preceding tokens s, is now re-interpretted as the Qvalue of action a in state s. When achieving optimality, fθ∗(a | s), namely Q∗(s, a), represents the best possible future reward achievable by generating token a in state s. Similarly, the full generation model pθ(a | s) in Eq.(1) that applies softmax to fθ now precisely corresponds to the policy πθ induced from Qθ(s, a). That is,
πθ(a | s) = expQθ(s, a)∑ a′ expQθ (s, a ′) ≡ exp fθ(a | s)∑ a′ exp fθ (a ′ | s) = pθ(a | s). (6)
We could further gain even more intuitive interpretation of the above generation policy π∗ from the lens of advantage function (Sutton & Barto, 2018). Specifically, in SQL, the optimal state-value function is the log-normalizer of the optimalQ-values (Haarnoja et al., 2017; Schulman et al., 2017). This allows us to rewrite Eq.(5) into a more concise form:
V ∗ (s) = log ∑
a′ expQ∗
( s, a′ ) , π∗(a | s)= exp ( Q∗(s, a)−V ∗(s) ) = expA∗(s, a), (7)
where A∗ is the optimal advantage function. The equation says that, in the proposed text generation SQL formulation, the optimal policy generates token a in state s according to the token’s advantage.

heading: 3.2 EFFICIENT TRAINING WITH PATH CONSISTENCY
text: The above section has described parameterizing the Q-function with the common generation model with parameters θ. Now we present how to learn theQθ function within the SQL framework. Vanilla training based on the Bellman temporal consistency can suffer from the instability and inefficiency issues similar to the conventional Q-learning (§2.1), as we discuss more in the appendix (§A.3.2). Fortunately, our SQL formulation allows us to import latest advances of RL techniques to the text generation setting that overcome the difficulties.
Specifically, we adapt the unified path consistency learning (PCL) that has excelled in game control (Nachum et al., 2017). The PCL-based training updates Q-values of all tokens at once through a connection between the value function and the induced policy. More specifically, it is shown in Nachum et al. (2017) that the optimal policy π∗ (Eq.5) and the optimal state value function V ∗ (Eq.7) in SQL must satisfy the following consistency property for all states and actions:
V ∗ (st)− γV ∗ (st+1) = rt − log π∗ (at | st) , ∀st, at. (8)
Accordingly, the PCL-based training attempts to encourage the satisfaction of the consistency with the following regression objective:
LSQL, PCL(θ) = Eπ′ [ 1
2
( − Vθ̄ (st) + γVθ̄ (st+1) + rt − log πθ (at | st) )2] , (9)
where πθ is the induced policy defined in Eq.(6); Vθ̄ is defined similarly as in Eq.(7) but depends on the target Qθ̄ network (i.e., a slow copy of the Qθ to be learned), and recall that π
′ is an arbitrary behavior policy (e.g., data distribution). Please see Figure 2 (left) for an illustration. Crucially, notice that the gradient update is applied to θ through the log πθ term which explicitly involves the Qθ-values of all tokens a in the vocabulary. This shows an important difference from the above vanilla training in conventional Q-learning (§2.1) where Qθ is updated only through the particular at token. The PCL training thus offers more efficient updates for the Qθ function.
Multi-step PCL for Sparse Reward. The above PCL objective Eq.(9) alone does not resolve the potential instability issue due to the bootstrapped Vθ̄(st+1) value and the sparse reward (i.e., r(st, at) = 0 for t < T ). Our SQL formulation allows us to additionally incorporate the multi-step variant of the PCL training (Nachum et al., 2017) to resolve the issue. Specifically, by applying a telescoping sum on the consistency equation (Eq.8) starting from t up to T , we arrive at the multistep temporal consistency:
V ∗ (st)− γT−tV ∗ (sT+1) = ∑T−t l=0 γl ( rt+l − log π∗ (at+l | st+l) ) , (10)
where the value of past-terminal state is zero, V ∗ (sT+1) = 0; and the rewards are only available at the end, ∑T−t l=0 γ lrt+l = γ T−trT . We can then come to the following multi-step objective function,
LSQL, PCL-ms(θ) = Eπ′ [ 1
2
( −Vθ̄ (st) + γ T−trT − ∑T−t
l=0 γl log πθ (at+l | st+l)
)2] . (11)
We can see the objective side-steps the need to bootstrap intermediate value functions Vθ̄(st′) for t′ > t. Instead, it directly uses the non-zero end reward rT to derive the update for θ. Please see Figure 2 (right) for an illustration. In practice, we combine the single- and multi-step objectives (Eqs.9 and 11) together for training.
Joint On- and Off-policy Training. Finally, we highlight that the behavior policy π′ involved in the objectives Eqs.(9) and (11) can be an arbitrary policy (i.e., distribution over text sequences), from which we can draw trajectories τ (i.e., text samples). For example, π′ can be a (possibly noisy) text dataset, or a set of text samples produced by other generation models, resulting in off-policy training. We can also set π′ to be the current generation model πθ to be learned, resulting in onpolicy training. In practice, we could first train the model with only off-policy data for warming up, and then continue with joint on- and off-policy training to further maximize the reward.
Algorithm 1 Efficient Soft Q-Learning for Text Generation Input: Qθ function (i.e., generation model logit function fθ in Eq.1)
Reward function r(s, t) Training examples D (for off-policy updates; optional)
1: Initialize θ and target model parameters θ̄ 2: repeat 3: Draw a batch of off-policy samples {τoff} ∼ D 4: Draw a batch of on-policy samples {τon} by decoding with policy πθ(at | st) (Eq.6) 5: Compute Qθ(st, at) values (i.e., the model logits) and target Qθ̄(st, at) for (st, at) ∈ {τoff} ∪ {τon} 6: Compute the objectives in Eqs.(9) and (11) 7: Update the model parameters θ via gradient descent 8: Update the target model parameters θ̄ by θ̄ ← ρθ̄ + (1− ρ)θ with update rate ρ 9: until convergence
Output: The trained Qθ∗ function and the induced generator πθ∗

heading: 4 APPLICATIONS AND EXPERIMENTS

heading: 4.1 LEARNING FROM NOISY (NEGATIVE) TEXT
text: The popular MLE algorithm learns by (blindly) imitating training data. However, it is often expensive to curate clean quality data. It is thus highly desirable to be able to learn from data with noises, or even negative examples. With the guidance of task metrics (rewards), the model can even learn to “outperform” the training data and achieve desired generation behaviors. To this end, we consider the task of entailment generation (Pasunuru & Bansal, 2017). Given a sentence (premise), the goal is to generate a new sentence (hypothesis) that logically follows the premise. For example, given source sentence “Sophie is walking a dog outside her house”, the hypotheses “Sophie is outdoor” is considered entailed, but “Sophie is inside her house” is not and even is a negative (contradictive) sentence.
Setup (more in the appendix §A.2.1). We sub-sampled 50k training examples from the SNLI dataset (Bowman et al., 2015), a commonly used entailment classification dataset. The hypotheses have an average entailment probability of only 50%, and over 2/5 of them less than 20% (negative/contradictive examples). This poses a significant challenge for the models to learn from the noises. The rewards used in RL algorithms include (1) the entailment score of the generation measured by a robust entailment classifier (Nie et al., 2020), (2) the log-likelihood of the generation as an indicator of language quality measured by a GPT-2 language model (Radford et al., 2019), and (3) BLEU score w.r.t the input premises as another language quality reward that avoids trivial outputs. We sum together all rewards with weights 1.0.
We compare our approach with a broad range of baselines, including (1) the standard MLE training (MLE); (2) MLE+reward, where we use the reward function to filter examples; (3) joint MLE and
PG training with MLE initialization (MLE+PG), where we initialize the model with MLE training, then train it with combined MLE and PG losses; previous text-generation RL algorithms including (4) MIXER (Ranzato et al., 2016), (5) Self-critic (Rennie et al., 2017), and (6) one of the latest methods GOLD-s (Pang & He, 2021) which is a pure off-policy method based on importancesampling PG. To ablate the effect of multi-step training (§3.2), we additionally compare with a simplified variant of our approach that uses only vanilla single-step PCL training (SQL(single)). In the appendix (§A.1.1) we compare and discuss more baselines such as MLE weighted by rewards.
We evaluate generation results in terms of entailment rate, language quality (perplexity), and diversity which is measured by the Shannon entropy over unigrams and bigrams (H1, H2) (Gehrmann et al., 2021). Since text generation models intrinsically trade off diversity and quality (Caccia et al., 2019; Hashimoto et al., 2019), we vary the generation diversity by generating samples via top-p sampling (Holtzman et al., 2019) with different p values, and plot the entailment rate and perplexity against diversity, resp. We also evaluate the samples produced by beam-search decoding.
Results. Figure 3 (left) shows the results. First, notice that MLE performs poorly, while MLE+reward improves upon it. This is not surprising as the training data contain noisy/negative examples. Similarly, since the pure off-policy algorithm GOLD-s relies heavily on the data distribution, we observed that it achieves sub-optimal performance. The on-policy MLE+PG with MLE initialization gives better entailment rate. In comparison, our full SQL framework achieves the best entailment-diversity trade-off. The comparison between SQL and SQL(single) highlights the importance of having the multi-step objective which directly uses the end reward rather than bootstrapping intermediate Q-values for supervision.
4.2 Universal ADVERSARIAL ATTACKS
We next study the application in text adversarial attacks, where again no supervised data is available. Adversarial attacks is an increasingly important research topic as they reveal models’ vulnerabilities and flaws. This is especially true for universal attacks (Wallace et al., 2019; Atanasova et al., 2020), where we want to generate universal examples that trick the model on all possible inputs. For instance, consider the context of entailment classification. Our goal is to find universal humanreadable hypotheses that are going to be classified as “entailment” with as high probability as possible, regardless of the input premises. This is a more challenging setting compared to previous instance-specific attack (Morris et al., 2020; Jin et al., 2020; Ebrahimi et al., 2017) where the attack model conditions on a premise and generates an adversarial hypothesis specific to the premise.
Setup (more in the appendix §A.2.2). We aim to attack one of the most popular MultiNLI (Williams et al., 2018) entailment classifiers on HuggingFaceHub.2 The attack generation model generates adversarial text without conditioning on any inputs so that the generated attacks are universal to all premises. We compare our SQL with MLE+PG. We use all hypotheses in the MultiNLI dataset as the training data for the MLE training in MLE+PG and the off-policy updates for our SQL. We do not compare with previous specialized adversarial text attack methods, because they either are not applicable to the challenging universal attack setting (Morris et al., 2020;
2https://github.com/pytorch/fairseq/tree/master/examples/roberta
Jin et al., 2020; Ebrahimi et al., 2017), or were not designed to generate human-readable sentences (Wallace et al., 2019). We use similar settings as in §4.1 to explore the diversity-quality trade-off by plotting the entailment rate and perplexity against diversity, respectively. The entailment classifier to be attacked is used as entailment score reward functions. We additionally include a token-level repetition penalty reward for readability.
Results. Figure 3 (right) shows the results, and Table 4 (appendix) shows samples. We can see that SQL outperforms MLE+PG consistently across different diversity values. The outputs from MLE+PG are not diverse even with high p’s, indicating the model collapses and can only generate a small set of unique adversarial examples. The model by SQL discovers the pattern “saint-pierre-et-saint-paul” (an entity name), and exploits this to generate samples with high universal entailment rate.

heading: 4.3 PROMPT GENERATION FOR CONTROLLING PRETRAINED LANGUAGE MODELS
text: A reward function does not just have to be a metric like the BLEU score, but also a complicated pipeline that eventually returns a score. To demonstrate this, we consider the emerging task of prompting a large pretrained LM for controllable generation (Hu et al., 2017; Radford et al., 2019; Brown et al., 2020). The goal is to learn to generate text prompts that steer the LM to generate sentences of certain desired attributes (e.g., topics). The problem of controlling the generation of pretrained LMs was previously approached through specialized algorithms such as modifying the LM hidden states during decoding (Dathathri et al., 2020; Krause et al., 2020; Qin et al., 2020). Here we show that prompts offer an easier, faster, more effective way for controlled generation.
Learning to generate/tune prompts is gaining increasing attention recently. It side-steps the needs for expensive LM fine-tuning, and adapts LMs to new scenarios with prompt as the (computefriendly) interface. Most existing approaches (Wallace et al., 2019; Li & Liang, 2021; Lester et al., 2021) rely on gradient backpropagation and are applicable only when the whole training pipeline is differentiable. This does not hold for the text generation setting, as illustrated in Figure 4. In contrast, the RL framework is generally applicable to any differentiable or discrete pipelines.
Setup (more in the appendix §A.2.3). Following (Dathathri et al., 2019), we aim to control the generation to have one of 7 topics (e.g., “science”); the generated prompt is prepended to one of 20 input sentences for the pretrained LM to generate continuation sentences. Figure 4 shows the
architecture of prompt-based controllable generation. We compare our SQL method with MLE+PG as before. Since the prompt length could impact the generated sentences, we conducted experiments with maximum prompt length 5, 10, and 15. As ablation study, we also evaluate the SQL algorithm with only off-policy updates (i.e., without on-policy exploration), denoted as SQL(off), and compare it with vanilla MLE training. Finally, we also compare with two specialized controllable generation techniques based on pretrained LMs, namely PPLM (Dathathri et al., 2019) and GeDi (Krause et al., 2020), following similar procedures using their open-sourced code. We use a distilled GPT-2 model3 as the pretrained LM to be controlled. For rewards, we use the topic accuracy of the continuation sentences measured by a zero-shot classifier, plus the the log-likelihood of continuation sentences as the language quality reward measured by a distilled GPT-2.
Results Figure 5 shows the topic accuracy of the controlled LM outputs averaged across the 7 topics, and Table 1 shows the respective language quality results. More detailed topic accuracy results and samples are provided in the appendix (§A.1.3) (where GeDi obtained low accuracy on 2 of the 7 topics, possibly because the topic tokens are tokenized into two subwords for which the model released by the authors was not specifically trained). We can see that the prompts generated by our SQL cause the LM to generate sentences with high topic accuracy while maintaining low perplexity in most settings. Increasing the prompt length positively impacts the topic accuracy, which makes sense because longer prompts give more flexible for steering the LM. The comparison between MLE and SQL(off) shows that the off-policy component of SQL is better than standard MLE training, as it incorporates reward signals instead of just blindly following the (noisy) data.
Next, comparing with the previous steered decoding such as PPLM and GeDi, we can see the prompt-based control trained with RL achieves better trade-off between topic accuracy and language quality. Moreover, once a prompt is produced, we can use the pretrained LM to generate text of desired topics efficiently, with the same time cost as standard non-controlled decoding. In comparison, the dedicated steered decoding is often orders-of-magnitude slower, as shown in Table 2.

heading: 5 RELATED WORK
text: Standard RL algorithms maximizing the external rewards can sometimes be over-sensitive to the randomness in the environment. Recent works have considered maximum-entropy RL (MaxEnt RL) extensions, such as the soft Q-learning (SQL) (Haarnoja et al., 2017; Nachum et al., 2017; Schulman et al., 2017), that maximize the entropy of policy besides the rewards, and have demonstrated substantial improvement in robotic and game control (Ziebart et al., 2008; O’Donoghue et al., 2017; Nachum et al., 2018; Eysenbach & Levine, 2021). Our work is the first to adapt SQL and its advanced variants (in particular the path consistency learning (Nachum et al., 2017)) to the challenging text generation problem and show significant results on diverse applications. Applying RL for text generation has been discussed in alleviating the exposure bias problem and optimizing task metrics (Li et al., 2016; Wu et al., 2016; Rennie et al., 2017; Paulus et al., 2018; Chen & Bansal, 2018). For example, Ranzato et al. (2016) used the REINFORCE algorithm (Williams, 1992), and Bahdanau et al. (2016) used the actor-critic algorithm; Guo et al. (2018) and Shi et al. (2018) tried to relieve the sparsity problem via hierarchical and inverse RL methods, resp. They are all on-policy RL algorithms with the need of pretraining their models using MLE. Another line of work focused mostly on using only off-policy data, often for offline training of chatbots (Jaques et al., 2020; Kandasamy et al., 2017; Zhou et al., 2017; Pang & He, 2021). As a result, the opportunity of directly improving the reward (as in on-policy updates) for other rich tasks is missed. Our proposed framework combines on- and off-policy training, and further offers solutions for efficient training from scratch in the presence of large action space and sparse sequence-level reward in text generation.

heading: 6 CONCLUSION
text: We develop a new RL formulation for text generation based on softQ-learning and path consistency learning. We conduct experiments on learning with noisy and negative data, black box adversarial attack, prompting a pretrained language model for controllable generation, and finally, on standard supervised tasks. The RL formulation opens up enormous new opportunities to integrate more advances made in the fertile RL literature to improve text and other sequence generation problems.
3https://huggingface.co/distilgpt2

heading: 7 ETHICS STATEMENT
text: This work develops a new RL formulation for text generation. While we demonstrate the framework in four applications, it could be adapted to other (emerging) applications. One major component in these applications is the design of the reward function, which influences the behavior of the trained agent. While we believe the MaxEnt RL framework is more robust against reward misspecification (Eysenbach & Levine, 2021), the potential failures of sub-optimal reward functions are widely known and discussed.4 To this end, deploying this model to the wild requires careful and extensive examination, using tools such as Ribeiro et al. (2020). Further, we highlight the application for (black-box) adversarial attacks in the paper, with the intention of using adversarial attacks to understand the model’s inner workings. That being said, this could potentially be misused to conduct malicious attacks against systems. Hence, users of this framework might want to conduct adversarial attacks against their own models to avoid being attacked by other people with bad intentions.

heading: 8 REPRODUCIBILITY STATEMENT
text: We provide code in the supplementary materials, and additional experiment details in the appendix.

heading: A APPENDIX

heading: A.1 APPLICATIONS AND EXPERIMENTS

heading: A.1.1 LEARNING FROM NOISY (NEGATIVE) TEXT
text: Please see Table 5 for beam search results, Figure 6 for additional results for MLE+reward, and Table 7 for examples.
A.1.2 Universal ADVERSARIAL ATTACKS
Please see Table 4 for examples.

heading: A.1.3 PROMPT GENERATION FOR CONTROLLING PRETRAINED LANGUAGE MODELS
text: Please see Table 6 for detailed results breakdown, and Table 8-11 for examples. Examples are in the format: topic: [prompt] input sentence generated text.

heading: A.1.4 SUPERVISED TEXT GENERATION TASKS
text: Finally, we conduct experiment on standard generation tasks where clean supervised data is available. The study is to examine the capabilities of the proposed RL method to train a text generation model from scratch, which has been considered as exceedingly challenging for previous RL algorithms.
Setup. We study on two tasks, E2E (Novikova et al., 2017) and CommonGEN (Lin et al., 2020), and use the respective datasets pre-processed by (Gehrmann et al., 2021) which allow sequenceto-sequence modeling with standard transformers. We run four sets of methods: the standard MLE training (MLE); PG training from scratch (PG); joint MLE and PG training, with MLE ini-
tialization (MLE+PG); and our SQL training from scratch with both off-policy and on-policy updates (SQL). We use the standard BLEU as reward. We additionally investigate the training stability and sensitivity w.r.t hyperparameters, in particular the scale of reward. To this end, for MLE+PG and SQL, we vary the reward scale in {1, 10, 50, 100, 500, 1000} and evaluate the respective performance under different scales.
Results. Table 3 shows the performance on E2E of different models whose hyperparameters are picked using the validation set. We can see the proposed SQL that trains models from scratch achieves competitive results with the common MLE and MLE+PG. In contrast, the PG algorithm alone without MLE fails the training. Figure 7 (left) shows the respective training curves (on the validation set), demonstrating that SQL converges in an efficient and stable way as MLE.
We further demonstrate the sensitive of MLE+PG and SQL w.r.t the reward scale as a key hyperparameter. Figure 7 (middle and right) shows the training curves of the two methods with varying reward scales. We can see SQL is significantly more robust as reward scale changes, while MLE+PG tends to collapse with improper reward scale configurations.

heading: A.2 SETUP DETAILS
text: Our evaluation follows the GEM Benchmark (Gehrmann et al., 2021) when applicable,5 and otherwise same with the reward function used in training. We use a transformer model (Vaswani et al., 2017) based on Texar-Pytorch (Hu et al., 2019) by default, with 64 hidden dimension, 3 blocks, and 4 heads. For experiments that involve policy gradient training, we initialize the model with maximum likelihood training by default unless specified otherwise. We train soft Q-learning model from scratch with both off-policy (using data) and on-policy (using samples) by default except in §4.1 and §4.3, in which we find it beneficial to warm-up the model with just off-policy training. We apply similar tuning budgets to both soft Q-learning model, and policy-gradient (mostly the reward scale and top-k), based on performance on the validation dataset and sample qualities.
Reward Functions We use the robust entailment classifier (Nie et al., 2020) in §4.1,6 one of the most used entailment classifiers on HuggingFaceHub in §4.2.7 and a zero-shot classifier based on BART (Lewis et al., 2020) to compute the topic score in §4.3.8 To compute perplexities, we use a GPT-2 model (Radford et al., 2019) fine-tuned on the corresponding datasets for computing perplexity in §4.1 and 4.2, and a distilled GPT-2 model in §4.3 without fine-tuning.9 We simply set reward weights to 1.0, except in §4.2, where we changed the entailment weight to 0.5, log-likelihood and repetition penalty weight to 5.0.
A.2.1 SETUP DETAILS: §4.1
We study using the SNLI dataset (Bowman et al., 2015), a dataset commonly used in training an entailment classifier. The original dataset contains (premise, hypothesis) sentence pairs, where the hypothesis may or may not entail the premise. We sub-sampled 50, 000 training examples from the corpus such that the hypotheses have an average entailment probability of only 50% in terms of the premises, and over 2/5 examples have entailment probabilities less than 20%, which can be seen as negative (contradictive) examples. The resulting training set poses a significant challenge for the models to learn from the noises.
The RL algorithms (including PG and ours) permit us to plug in arbitrary reward functions to drive learning. Based on the goal of the task, we use the following intuitive rewards to ensure entailment accuracy and language quality: (1) a robust entailment classifier (Nie et al., 2020) that measures the entailment score of a generation in terms of the input premise, (2) a GPT-2 language model (Radford et al., 2019) that measures the log-likelihood of the generation as an indicator of language quality, and (3) BLEU score w.r.t the input premises as another language quality reward that avoids trivial outputs. We sum together all rewards with weights 1.0.
A.2.2 SETUP DETAILS: §4.2
We study the task of attacking an entailment classifier. In particular, we aim to attack one of the most popular entailment classifiers on HuggingFaceHub.10 The attack generation model generates adversarial text without conditioning on any inputs so that the generated attacks are universal to all premises. The generation model is trained with mostly the same setting as in §4.1, where the entailment classifier to be
5https://github.com/GEM-benchmark/GEM-metrics 6https://huggingface.co/ynie/roberta-large-snli_mnli_fever_anli_R1_R2_
R3-nli 7https://github.com/pytorch/fairseq/tree/master/examples/roberta. This classifier is ranked #1 (as of May 20, 2021) based on https://huggingface.co/models?search=nli. 8https://huggingface.co/facebook/bart-large-mnli 9https://huggingface.co/distilgpt2
10https://github.com/pytorch/fairseq/tree/master/examples/roberta, which is ranked #1 as of May 20, 2021 based on https://huggingface.co/models?search=nli.
attacked is used as entailment score reward functions. Besides, we additionally include a tokenlevel repetition penalty reward, which empirically benefits readability. Finally, we use the MultiNLI dataset (Williams et al., 2018) which includes more diverse examples than the SNLI used above.
We compare our SQL with MLE+PG. We use all hypotheses in the MultiNLI dataset as the training data for the MLE training in MLE+PG and the off-policy updates for our SQL. We do not compare with previous specialized adversarial text attack methods, because they either are not applicable to the universal attack setting (Morris et al., 2020; Jin et al., 2020; Ebrahimi et al., 2017), or were not designed to generate human-readable sentences (Wallace et al., 2019). Besides, it is worth noting that the general RL algorithms have an additional advantage of doing black-box attacks. That is, the algorithms only require the ability to query the entailment classifier for entailment probability, without need of knowing the internal structure of the classifier (e.g., for computing gradients) as in previous attack algorithms (Ebrahimi et al., 2017; Wallace et al., 2019).
For top-p sampling results, we sample a hypothesis for each premise and measure the average attack rate across the dataset. This is because sampling multiple hypotheses, each for all premises, and measure performance are expensive. Since the hypotheses are sampled input-independently, this should be a good approximation.
A.2.3 SETUP DETAILS: §4.3
Following (Dathathri et al., 2019), we aim to control the generation to have one of 7 topics (e.g., “science”); the generated prompt is prepended to one of 20 input sentences (Figure 4) for the pretrained LM to generate continuation sentences. There is no direct supervision data available for training the prompt generator. We randomly create some noisy text as the training data for MLE baselines below and for off-policy updates for our algorithm. Specifically, the noisy text is created by sampling keywords and topics from the list used in (Dathathri et al., 2020) and a paraphrase generation model.
Figure 4 shows the architecture of prompt-based controllable generation. We compare our SQL method with MLE+PG as before. At training time, for each generated prompt sample, the pretrained LM generates 2 continuation sentences for evaluating average reward. We use a zero-shot classifier to evaluate the topic accuracy of the continuation sentences. That is, we do not assume access to classifiers pretrained on topic-specific sentences, because generating such topic-specific sentences is the goal of the task in the first place. We additionally use an LM to evaluate the log-likelihood of continuation sentences for measuring language quality. Since the prompt length could impact the generated sentences, we conducted experiments with maximum prompt length 5, 10, and 15. As ablation study, we also evaluate the SQL algorithm with only off-policy updates (i.e., without onpolicy exploration), denoted as SQL(off), and compare it with vanilla MLE training. At test time, given a topic, the trained prompt generator produces one prompt using beam search decoding. For each generated prompt, the pretrained LM generates 100 sentences using top-k decoding (with k = 50) for evaluation. Finally, we also compare with two specialized controllable generation techniques based on pretrained LMs, namely PPLM (Dathathri et al., 2019) and GeDi (Krause et al., 2020), following similar procedures using their open-sourced code. We use a distilled GPT-2 model11 as the pretrained LM to be controlled. We use the paraphrase generation model based on Zhang et al. (2019).12 During decoding, we include no repeat ngram size= 2, which improves readability.13
A.3 THE SOFT Q-LEARNING FRAMEWORK

heading: A.3.1 COMPARISON WITH MLE OBJECTIVE
text: It is interesting to take a closer look at the above objective and compare with the common MLE training. Specifically, we notice the relations between the optimal Q∗, V ∗, and A∗ functions: A∗ (st, at) = Q
∗(st, at) − V ∗(st) = rt + γV ∗(st+1) − V ∗ (st), where the first equation is the definition of A∗ (see Eq.7) and the second equation is due to Eqs.(12) and (7). We thus can see the regression target in the above objective as an approximation to the advantage function:
11https://huggingface.co/distilgpt2 12https://huggingface.co/tuner007/pegasus_paraphrase 13https://huggingface.co/blog/how-to-generate
Ãθ̄ (st, at) := −Vθ̄ (st) + γVθ̄ (st+1) + rt. Therefore, by optimizing the regression objective, log πθ(at|st), which is the log probability of generating token at given preceding tokens st, is encouraged to match the approximate advantage value Ãθ̄ (st, at), no more and no less. This is different from the objective of MLE where the model is trained to (blindly) increase the probability of the observed token at given st and decrease the probability of the rest.
A.3.2 VANILLA TRAINING WITH TEMPORAL CONSISTENCY
Much like the Bellman temporal consistency in standard Q-learning (Eq.3), in SQL, the optimal action-value function follows the softmax form of the temporal consistency (Ziebart et al., 2008; Ziebart, 2010; Fox et al., 2016; Nachum et al., 2017):
Q∗ (st, at) = rt + γ log ∑
at+1 expQ∗ (st+1, at+1) . (12)
We thus can derive a regression objective similar to the standard Q-learning (Eq.4): LSQL, vanilla(θ) = Eπ′ [ 0.5 · ( rt + γ log ∑ at+1 expQθ̄ (st+1, at+1)−Qθ (st, at) )2] . (13)
Recall that π′ is an arbitrary behavior policy (e.g., data distribution), and Qθ̄ is the target Q-network which is a slow copy of the Qθ to be learned and is held fixed during the gradient updates. However, the above objective is inefficient due to exact the same reasons as in standard Q-learning discussed earlier, namely the unstable per-step bootstrapping-style training with sparse reward signals, plus the slow updates w.r.t only one token at out of the large vocabulary (action space).

Review summaries:
This paper considers the problem of learning text generation models using reinforcement learning. The problem is challenging in that RL algorithm becomes inefficient or unstable when dealing with large action space and the sparse reward situations in text generation. To address these problems, this paper adapts the path consistency learning approach to the text generation setting. It allows to train the model with both on- and off-policy samples, bridge the sparse reward signal to directly supervise the Q-function learning, and makes efficient updates to Q-values by considering all candidate actions together. Experiments result show that the proposed approach are effective in solving a wide range of applications where MLE are not applicable, where it achieves better performance than previous RL-based methods as well as task-specific methods. In addition, on standard MLE-based tasks, the proposed approach could also achieve competitive performance when training the models from scratch.