{'fraction_non_alphanumeric': 0.022943459401872004, 'fraction_numerical': 0.009245871699261853, 'mean_word_length': 5.019926706367384, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Generative Adversarial Imitation Learning for Empathy-based AI

Generative adversarial imitation learning (GAIL) is a model-free algorithm that has been shown to provide strong results in imitating complex behaviors in high-dimensional environments. In this paper, we utilize the GAIL model for text generation to develop empathy-based context-aware conversational AI. Our model uses an expert trajectory of empathetic prompt-response dialogues which can accurately exhibit the correct empathetic emotion when generating a response. The Generator of the GAIL model uses the GPT-2 sequential pre-trained language model trained on 117 million parameters from 40 GB of internet data. We propose a novel application of an approach used in transfer learning to fine tune the GPT-2 model in order to generate concise, user-specific empathetic responses validated against the Discriminator. Our novel GAIL model utilizes a sentiment analysis history-based reinforcement learning approach to empathetically respond to human interactions in a personalized manner. We find that our model's response scores on various human-generated prompts collected from the Facebook Empathetic Dialogues dataset outperform baseline counterparts. Moreover, our model improves upon various history-based conversational AI models developed recently, as our model's performance over a sustained conversation of 3 or more interactions outperform similar conversational AI models.


Introduction
Text generation models designed for intelligent conversation systems are increasingly popular in research. Many modern text generation models take advantage of deep learning paradigms for natural dialogue generation. State-of-the-art results in this field utilize the numerous processing layers of deep learning architectures typified by Recurrent Neural Networks, Variational Autoencoders, and Transformer models (Sutskever et al., 2011;Zhang et al., 2019;Li et al., 2020). These neural network approaches are capable of context-aware, history-based text generation, however, it is less often the case we see research focused on developing empathetic dialogue systems.
The challenge of developing empathetic dialogue systems is inherently a conceptual one: in literature and application, there is no clear definition of empathy. Cognitive neuroscientists are actively seeking to define empathy empirically, however, even the most objective definitions fail to cater to each individual's perception of empathy (Gerdes et al., 2010). It is even more so challenging to develop artificial empathy capable of detecting and responding to human emotions (Asada, 2015).
In this paper, we propose an architecture capable of empathetic, context-aware, natural dialogue generation. To tackle the challenges of such a problem, we employ the use of deep reinforcement learning. Deep reinforcement learning has recently been used for traditional text generation, as the nature of reinforcement learning allows for success in complex, high dimensional environments. The challenge of picking an appropriate response out of an entire set of possible utterances in a language is certainly the caliber of problem that reinforcement learning is able to solve. Li et al. (2016) proposed one of the first applications of deep Q-learning for dialogue generation by simulating dialogue between two virtual agents using policy gradient methods. Their work showed improvements over traditional MLE-based Seq2Seq models, citing the main advantages of deep Q-learning to be its ability to keep the conversation moving through non-generic responses and its ability to recognize repetitive utterances.
While traditional reinforcement learning has shown success for natural dialogue generation, a key shortcoming is evident when we introduce empathy-based intelligent conversation agents. For an empathetic dialogue agent to select an optimal policy in a state-space, it must maximize a reward function which defines empathetic conversation. However, the same problem arises: it is virtually impossible to define a statistical formula for empathy.
We propose the application of inverse reinforcement learning or imitation learning to solve this problem in a different way. Instead of postulating an empirical formula for empathy, we feed the model a trajectory of empathetic expert actions that an empathetic dialogue agent can imitate. Our rationale behind this approach is that it is significantly easier to recognize examples of empathy in conversation, actions, or people rather than developing an overarching formula for empathy.
In our implementation, we utilize the generative adversarial imitation learning (GAIL) model developed by Ho and Ermon (2016), a reinforcement learning variant of the generative adversarial network (GAN) developed by Goodfellow et al. (2014), used famously for video and image generation. We also use the large-scale pre-trained language model GPT-2 within the Generator of the GAIL architecture that allows for basic textual understanding and generation (Radford et al., 2019). Our novel implementation allows us to fine tune the language model using the expert empathetic trajectories for empathetic dialogue generation. For the optimization, we utilize proximal policy optimization (PPO) (Schulman et al., 2017).
For a fair evaluation, we utilize an error metric commonly used in the field of natural language processing to evaluate langauge models. We evaluate our model over single-turn and multi-turn conversations using the perplexity and BLEU error metrics (Chen et al., 1998;Papineni et al., 2002). Instead of testing our model's performance over common baselines for natural dialogue generation including COCO, ROCStories, and CommonGEN (Lin et al., 2014(Lin et al., , 2019Mostafazadeh et al., 2017), we evaluate our model against others using our own empathetic dataset. The motivation for such a methodology is that the typical benchmarks used for conditional and unconditional text generation do not contain empathetic prompts or responses, and as a result, our model's effectiveness will not be tested. Moreover, our model does not accomplish the same tasks that would be measured in these text generation baseline datasets.
We make several contributions: (1) we propose an application of the generative adversarial imitation learning architecture for text generation, (2) we fine tune the large-scale pre-trained language model GPT-2 using expert empathetic actions to generate empathetic dialogues, (3) we show that our novel architecture outperforms similar text generation models in singe-turn and multi-turn empathetic dialogues using the perplexity and BLEU error metrics.

Related Work
Artificial empathy is a large field, however, research into intelligent conversation agents with empathy is scarce. One of the most famous proprietary chatbot systems available to consumers is WoeBot developed by Fitzpatrick et al. (2017). WoeBot is an intelligent conversation agent that allows patients to converse in a structured set of prompts to deal with various mental health issues. The intelligent agent is certified in cognitive behavioral therapy (CBT). Although it does not provide natural context-aware text generation, as the set of prompts are relatively static with respect to the subject of the conversation, WoeBot is able to discover and respond to human emotions. Fung et al. (2018) is one of the first papers to introduce the application of deep reinforcement learning for empathetic dialogue generation. Their work describes a reinforcement learning variant of a traditional Seq2Seq model used for dialogue generation. Instead of defining a reward function for empathy, they seek to categorize each human prompt into an emotion class. They classify each prompt into an emotion class by the words and emoticons used in each utterance, and then respond using a set of predefined responses based on the discovered emotion class. They train their deep reinforcement learning architecture using Proximal Policy Optimization (PPO). Wu et al. (2020) is perhaps the most similar to our proposed research. They propose the application of a generative adversarial imitation learning model for traditional text generation. They utilize pretrained language models including the RoBERTa architecture for text generation within the GAIL architecture (Liu et al., 2019). Their model shows improvement over previous work on text generation of image captions and baseline text generation tasks including COCO, CommonGEN, and ROCStories.

Model Architecture
In this section, we describe the architecture of our proposed model. We describe our novel fine tuning approach on pre-trained language models using expert empathetic actions, as well as the structure of the Generator and Discriminator models within our generative adversarial imitation learning architecture. A visualization of the overall architecture of our model is described in Figure  1.
For dialogue generation, we modify the generative adversarial imitation learning architecture similar to Wu et al. (2020). Generative adversarial imitation learning is a model-free imitation learning architecture able to directly imitate near-optimal expert trajectories in high dimensional, complex environments. The GAIL architecture consists of a generator G and discriminator D, where the generator seeks to generate responses similar to empathetic human responses, while the discriminator seeks to distinguish between the generated responses and the expert empathetic responses and propagate a reward signal back to the generator. Note that the reward signal here is not the reward function that a reinforcement learning agent must maximize, but it is a measure of similarity, defined as 'occupancy measure' in the paper. As a result, the GAIL architecture does not ever need to dis-cover the exact reward function that a typical reinforcement learning agent would maximize, which suits our goal of empathetic dialogue generation.
The generator of the GAIL model performs imitation learning by constructing an environment where the inverse reinforcement learning problem is the dual of the reinforcement learning problem. That is, we define the reinforcement learning problem as where π ∈ is a recovered policy, H(π) is the γ−distributed entropy of policy π, and c(s, a) is the cost for state s and action a. Similarly, we then define the ψ-regularized maximum entropy inverse reinforcement learning problem as where ψ is a regularization term and π E is the optimal policy. Note that ψ-regularized inverse reinforcement learning implicitly seeks a policy where its occupancy measure ρ is close to the expert.
The generated policy of the GAIL is then where ρ π is the occupancy measure of the recovered policy and ρ π E is the occupancy measure of the expert policy. We can select a regularizer that allows us to implement a more complex class of cost functions using neural networks. In our implementation, we define our cost regularizer as The motivation behind this specific cost regularizer is because the convex conjugate ψ * is the optimal negative log-loss of the binary classification problem of distinguishing between state-action pairs of π and π E : which is also exactly the same as the cost function of the discriminator network of a traditional generative adversarial network (GAN).
For dialogue generation, we replace the state s within the GAIL with a two-part input and its corresponding action a with the target response. This two-part input consists of (1) an optional history of the earlier prompts and responses in the conversation and (2) a required input prompt. We also optimize the policy generation within the generator of the GAIL with PPO instead of trust region policy optimization (TRPO) (Schulman et al., 2015), which was used in the original paper. The TRPO algorithm is a constrained optimization problem that ensures that the policy is not moving too far away from the starting point by using the KL-divergence. TRPO is a commonly used policy optimizer, but more recent research has shown newer policy optimizers that have lower variance and do not solely require small steps to convergence (Engstrom et al., 2019). PPO is a simpler, more effective policy optimization algorithm compared to TRPO. PPO tries to compute an update at each time step that minimizes the cost function while ensuring the deviation from the previous policy is small. Instead of a KL-divergence constraint like TRPO, PPO uses a KL-divergence penalty: For the Generator network, we utilize the pre-trained language model GPT-2, a large-scale multipurpose language model with a transformer architecture developed by OpenAI with 117 million parameters trained on 40 GB of internet data. The nature of our modified GAIL model allows for the expert empathetic actions to fine tune the baseline language model for empathetic dialogue generation in a similar manner to the fine tuning process found in transfer learning. Essentially, instead of retraining the language model for empathetic dialogues, which would be computationally infeasible due to the size of the language model, the GAIL model treats all possible GPT-2 responses for a prompt as the set of possible actions to take in the state-space, and the architecture selects the response most similar with respect to the occupancy score of the optimal expert empathetic response.
We describe the training process of our overall modified generative adversarial imitation learning algorithm in Algorithm 1. We also describe the training process of the generator network within the modified GAIL architecture in Algorithm 2.
Algorithm 1 Modified GAIL Algorithm Input: Expert empathetic trajectories τ E each with history h E , prompt p E and response r E ; initial policy and discriminator parameters θ 0 , w 0 for i = 0, 1, 2, . . . do Sample trajectories τ i for discriminator D Collect occupancy score ρ i from discriminator D for all τ i Update discriminator parameters from w i to w i+1 using Eq. 6 Update generator parameters by taking policy step from θ i to θ i+1 using PPO end for Algorithm 2 Generator Algorithm Input: Initial policy parameters θ 0 , Noise prior p(z) for i = 0, 1, 2, . . . do Sample noise sample z i ∼ p(z) Generate possible responses using GPT-2 language model Recover generated response using z i to form γ i Update parameters by taking policy step from θ i to θ i+1 using PPO end for Output: Generated policy γ G each with history h G , prompt p G , and response r G

Experiments
In this section, we describe the datasets and implementation details of our experiments.

Figure 2: EmpatheticDialogues Example Data
The datasets we used for the following experiments were selected to be clear examples of empathetic conversations, actions, or dialogues. Our dataset plays a larger role in the performance of our model compared to similar research because the empathetic nature of our model comes from imitating our dataset of expert empathetic trajectories. As a result, we chose our dataset very carefully in order to exemplify human empathetic actions in a broad setting. Note that all data we use in this paper is open source, anonymized, and does not contain any personally identifiable or offensive content.
The first dataset we used is the EmpatheticDialogues dataset collected by Facebook AI Research (Rashkin et al., 2018). The EmpatheticDialogues dataset consists of 25 thousand single-turn and multi-turn empathetic conversations. Each data sample contains (1) a label which describes the overall emotion of the conversation and (2) the transcript of a conversation between exactly two human speakers. These conversations were human-labeled and human-generated through crowd sourcing via Amazon Mechanical Turk. An example of the data is shown in Figure 2.
The second dataset we used is the DailyDialog dataset collected by Li et al. (2017) consisting of 13 thousand multi-turn empathetic conversations. The data labeling task was crowd sourced and human-labeled. We use this dataset as it provides longer example conversations sustained over a single topic. This allows our model to produce more context-aware and history-based dialogue generation, as it imitates the sustained flow of conversation evident in the DailyDialog dataset. A sample DailyDialog conversation is shown in Figure 3.

Figure 3: DailyDialog Example Conversation
Finally, we also collect empathetic tweets as a datasource. We find that including empathetic tweets allow our model to offer advice or provide inspirational responses at certain points in the conversation, resulting in a more thoughtful and altruistic conversational agent. We collect the entire twitter histories of established uplifting Twitter accounts including @DalaiLama, @DailyZen, and @Mind-fulEveryday. Some examples of these tweets are shown in Figure 4.

Implementation
Our implementation of our modified generative adversarial imitation learning architecture uses a neural network architecture with two hidden layers of 100 units each, with tanh nonlinearities in between for the generator and discriminator. The pre-trained model weights for the Generator network is the base GPT-2 model. A majority of our implementation was completed using the PyTorch Python framework for Python 3.7.7 (PyTorch, 2021). All external frameworks used in our implementation including GPT-2 and PyTorch are accessed and provided as open-source assets.
To create the expert empathetic trajectories from the dataset, we must pre-process the conversation data. For the EmpatheticDialogues and DailyDialog datasets, we create an expert trajectory for each turn of the conversation, where a turn is defined as a prompt speaker from one speaker and a response utterance from another speaker. If the data sample is a single turn conversation, then we construct an expert empathetic trajectory sample where the history h i is an empty string, the input prompt p i is the first speaker's utterance, and the optimal response r i is the second speaker's utterance. For multi turn conversations, we stagger the generation of expert trajectories such that we create a trajectory for the first turn in the conversation with no history h i , but the first two utterances as prompt p i and response r i . For every turn after the first, we concatenate all previous turns before the current turn and store the utterances as the history h i , the current turn's first speaker utterance as the prompt p i and the current turn's second speaker utterance as the response r i .
For each conversation in either the EmpatheticDialogues or DailyDialog dataset, there is at least one generated empathetic trajectory. In general, there are usually more generated for each data sample, since most conversations in these datasets are multi turn: EmpatheticDialogues has an average of 2.3 turns per conversation; DailyDialog has an average of 4.8 turns per conversation.
For the empathetic tweets that are not in conversation format, we store no history h i but store the tweet text as both the prompt p i and the response r i . For each tweet, there is exactly one generated expert empathetic trajectory. In total, we generate 208600 expert empathetic trajectories: 79353 from EmpatheticDialogues, 61935 from DailyDialog, and 67312 from empathetic tweets. We train our model over 750 epochs with a batch size of 32, a validation frequency of every 10 epochs, and a human demonstration mix ratio set at 0.3 at the start of training which was configured to decrease linearly throughout training. Our train-test-validation split was 70-20-10 respectively. Our generator network optimizes our policy through a custom minimal implementation of PPO with a minibatch size of 8 and an epsilon value of 0.2. We evaluate our error using the perplexity and BLEU error metrics commonly used to measure the effectiveness of language models in the field of natural language processing.
We describe additional hyperparameter selections for our model implementation in Table 1. All hyperparameter choices were either chosen empirically or left as default as a result of running various hyperparameter tuning iterations. We train and evaluate our model using the Google Colaboroa-

Results
To evaluate the effectiveness of our model, we collect error metric results for our model against baseline dialogue generation models. The error metrics we use throughout our experiments are the perplexity and BLEU error metrics. In a general sense, perplexity measures the human-readability of a generated text, where a low perplexity score corresponds to an easily understandable output. The perplexity score P for a language model p M (next word w| history h) on a test set .
The Bilingual Evaluation Understudy Score (BLEU) error metric measures the similarity of a candidate sentence to a target sentence. Here, we will measure the BLEU scores on generated responses to optimal empathetic responses in the test set.  We test our model against three baselines. For each baseline, due to the nature of our problem, we collect perplexity error by training and evaluating these models on our empathetic dataset as opposed to a common benchmark dataset. For all baselines, we utilize the default hyperparameters described in their respective implementations. All baselines we select are dialogue generation models. Our first baseline is a base GPT-2 dialogue generation instance fine tuned to our dataset through maximum likelihood estimation (MLE). Our second baseline is the reinforcement learning variant of the Seq2Seq architecture developed by Fung et al. (2018) where they classify input prompts into emotion classes to respond empathetically. Our final baseline is the TextGAIL model developed by Wu et al. (2020) that utilizes the RoBERTa pre-trained language model within the architecture of a GAIL model for dialogue generation. We test our model against the baselines using the BLEU and perplexity error metrics for a single turn, 2 turn, and 3+ turn conversations. That is, a single turn conversation contains no history; a 2 turn conversation contains the history of a single turn; and a 3+ turn conversation contains the history of multiple turns. We provide our results in Table 2 along with error bars with respect to various iterations using different random seeds. We provide a visualization of perplexity and BLEU error over conversation length for each model in Figure 5 and 6 respectively. Our BLEU and perplexity error metric results show that our model, EmpathyGAIL, provides significant improvement over baselines.

Metric
In order to display the empathetic abilities of our approach, we also provide some example responses from our model. Each example response corresponds to an input prompt and an optional history. Table 3 describes a few of these results.

Example Results
History I moved to LA a few years ago and I never had the chance to visit home. Prompt I'm going to see my parents soon! Generated Response That's awesome! I hope you have a good time.

History
None Prompt He was a very good friend of mine. Last month, he passed away. Generated Response I am very sad to hear that he is no longer alive.

History
I was in a drive-thru line and someone cut in front of me.

Prompt
I was furious and blew up at him.

Generated Response
Sometimes it makes more sense to just walk away. You cannot control others, you can only control yourself.

History
None Prompt I had a job interview today and I think it went really well. Generated Response Wonderful!

Conclusion
We propose a generative adversarial imitation learning architecture for empathetic dialogue generation. Our key contributions include a modified GAIL architecture for dialogue generation, a fine tuning approach using expert empathetic trajectories on large-scale pre-trained language models, and our results show improved perplexity and BLEU scores over single turn and multi turn conversations. Our work shows that deep imitation learning models can accurately and effectively provide context-aware, empathetic, and natural dialogue generation.
Our results show an average perplexity error decrease of 80% and a BLEU error decrease of 81% compared to a base GPT-2 model fine tuned to our dataset through MLE. Our results also show an average perplexity error decrease of 42% and a BLEU error decrease of 44% compared to a generative adversarial imitation learning model for text generation (Wu et al., 2020).
There are a few limitations of our model. We find that at certain times, our model will begin to generate fake experiences or stories in an attempt to connect with the input prompt. This is because the input empathetic datasets we use are entirely human generated such that a human responder can empathetically respond to a human prompt by narrating their own prior experiences. Since our architecture seeks to imitate these empathetic responses, we find that our model does the same. Also the GPT-2 pre-trained language model we use within the generator of the GAIL is trained on datasets which contain biases or factual inaccuracies, and as a result will be reflected in the output of our model.

Future Work and Impacts
We hope to use additional sources of empathetic data which are human-labeled but may not be human-generated to ensure that our model does not generate fake experiences or stories to connect with the input prompt. We also hope to implement more powerful pre-trained language models like the recently developed GPT-3 model (Brown et al., 2020). Another direction we would like to take our research is developing a more personalized sense of empathy for each user. Empathy is individual-specific, so we hope to implement a set of calibrating questions that gauge the perception of empathy for a user prior to providing empathetic dialogue.
We forsee our impacts as a tool for patients suffering with mental health, anxiety, or depression to converse with an empathetic chatbot at any time. Before making our developments available for public use, we will have to complete rigorous training and testing to ensure that the chatbot provides help and not harm. There may be serious negative societal impacts if adequate testing is not completed, so we will heavily focus our future research into ensuring the safety and effectiveness of our work.