{'fraction_non_alphanumeric': 0.03442575822912175, 'fraction_numerical': 0.014374011786689666, 'mean_word_length': 5.057683935568132, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Transformer Models for Text Coherence Assessment

Coherence is an important aspect of text quality and is crucial for ensuring its readability. It is essential desirable for outputs from text generation systems like summarization, question answering, machine translation, question generation, table-to-text, etc. An automated coherence scoring model is also helpful in essay scoring or providing writing feedback. A large body of previous work has leveraged entity-based methods, syntactic patterns, discourse relations, and more recently traditional deep learning architectures for text coherence assessment. Previous work suffers from drawbacks like the inability to handle long-range dependencies, out-of-vocabulary words, or model sequence information. We hypothesize that coherence assessment is a cognitively complex task that requires deeper models and can benefit from other related tasks. Accordingly, in this paper, we propose four different Transformer-based architectures for the task: vanilla Transformer, hierarchical Transformer, multi-task learning-based model, and a model with fact-based input representation. Our experiments with popular benchmark datasets across multiple domains on four different coherence assessment tasks demonstrate that our models achieve state-of-the-art results outperforming existing models by a good margin.


Introduction
Coherence is a crucial metric for text quality analysis. It assimilates how well the sentences are connected and how well the document is organized. Coherent documents have a clear topic transitions that are discussed throughout the text with a smooth flow of concepts, typically in an increasing order of complexity. Ideas are first introduced in preceding sentences and are referred to later in document. Connectives are often used to assist the structure as well as smooth transitions within the document. Overall, coherence leads to better text clarity.
Many formal theories of coherence (Grosz et al., 1995;Mann and Thompson, 1988;Asher et al., 2003) have been proposed leading to further development of various coherence models. Based on such theories, multiple text coherence models like entity-grid (Barzilay and Lapata, 2008) and its extensions have been proposed. Other linguistic approaches for text coherence include coreferences, discourse relations, lexical cohesion, and syntactic features. However, such models are incapable of handling long transitions. Also, feature engineering is decoupled from the prediction task thus limiting model performance. Recently, various models have been proposed which leverage deep learning architectures like convolutional neural networks (CNNs), recurrent neural networks (RNNs), long short-term memory networks (LSTMs). Although, Transformer (Vaswani et al., 2017) based models have revolutionized the field of NLP, surprisingly, there is no rigorous study which investigates the effectiveness of Transformer architectures for text coherence. In this paper, we study four different kinds of Transformer architectures.
We propose models for four different coherence assessment tasks: 2-way classification, 3-way classification, sentence ordering, and coherence score prediction. For each of these tasks, we investigate effectiveness of four Transformer architectures: (1) vanilla Transformer models, (2) hierarchical Transformers with two levels, (3) multi-task learning with text coherence assessment as primary task and textual entailment as auxiliary task, and (4) fact based input representation where besides the original document, we also pass extracted facts as input. We assess the extent to which these architectures generalize to different domains and prediction tasks, establishing a new state-of-the-art (SOTA).
Overall, in this paper, we make the following main contributions. (1) We investigate the effectiveness of four Transformer architectures. (2) We assess the extent to which the information encoded in the network generalizes to multiple domains and four prediction tasks, and demonstrate the effectiveness of our approach not only on standard sentence ordering tasks but also on more realistic task like predicting coherence of varying degrees in people's everyday writings. (3) Experiments on popular benchmark datasets (GCDC and WSJ) indicate that our proposed methods establish SOTA across multiple (task, dataset) combinations. On GCDC, our best method beats the existing SOTA by: 0.15 F 0.5 on the 2-way classification task, 3.00 absolute percent points accuracy 3-way classification task, 6.40 absolute percent points accuracy on sentence ordering task and 0.18 Spearman correlation on coherence score prediction resp. On WSJ, our best method provides an improvement of 1.28 absolute percent points on sentence ordering task. We make the code and dataset publicly available 1 .

Related Work
Entity-Grid based methods: Discourse coherence has been studied widely using both deep learning as well as non-deep learning models. (Barzilay and Lapata, 2008) proposed the entity grid model, which is based on Centering Theory (Grosz et al., 1995). It captures the distribution of discourse entities and transition of grammatical roles (subject, object, neither) across the sentences. Several extensions were proposed by utilising entity specific features (Elsner and Charniak, 2008), modifying ranking scheme (Feng and Hirst, 2012) or transforming problem into bipartite graph (Mesgar and Strube, 2015). The entity grid method as well as extensions suffer from two main drawbacks: (1) they use discrete representation for grammatical roles and features, which prevents the model from considering sufficiently long transitions due to the curse of dimensionality problem. (2) Feature engineering is decoupled from the prediction task, 1 https://tinyurl.com/mry9464u which limits the model's capacity to learn taskspecific features.
Other feature engineering methods: Besides entity grid, other linguistic approaches for text coherence include coreferences, discourse relations, lexical cohesion, and syntactic features. (Elsner and Charniak, 2008) proposed a maximum-entropy based discourse-new classifier that classifies mentions of all referring expression as first mention (discourse-new) or subsequent (discourse-old) mentions. (Louis and Nenkova, 2012) proposed a coherence model based on syntactic patterns by assuming that sentences in a coherent discourse should share the same structural syntactic patterns. Other approaches have used syntactic patterns (Louis and Nenkova, 2012), lexical cohesion (Morris and Hirst, 1991;Somasundaran et al., 2014) or capturing topic shifts via Hidden Markov Models ( Barzilay and Lee, 2004).
Deep learning methods: Recently, multiple deep learning approaches have been proposed. (Li and Hovy, 2014) propose a neural framework to compute the coherence score of a document by estimating a coherence probability for each clique of L sentences. (Li and Jurafsky, 2017) propose generative methods to capture global topic information. (Nguyen and Joty, 2017; Mohiuddin et al., 2018) transform entity-grid based methods into deep learning versions that obtains better result than traditional counterparts. (Farag and Yannakoudakis, 2019) propose a hierarchical attention model with multi-task learning objective. (Xu et al., 2019;Moon et al., 2019) show that modeling local coherence with discriminative models could capture both the local and the global contexts of coherence. (Guz et al., 2020) propose an RST-Recursive model, which takes advantage of the text's RST features. (Farag et al., 2020) extend some of the previous discriminative models using BERT (Bidirectional Encoder Representations from Transformers) (Devlin et al., 2018) embeddings. Further details on some of the above mentioned methods are provided in Section 4.2.
Except for the last work, none of the previous methods have investigated the use of Transformer based models for text coherence modeling. Even (Farag et al., 2020) simply experiment with BERT embeddings (they do not train the Transformer architecture), and that too only on one task with synthetic data. We experiment with multiple Transformer architectures. Our experiments establish a new state of the art outperforming these models by a good margin.

Text Coherence Assessment Models
In this section, we first discuss details of the text assessment tasks, and then present the proposed Transformer-based architectures.

Text Coherence Assessment Tasks
We propose models for four different coherence assessment tasks: (i) 3-way classification, (ii) 2-way classification, (iii) sentence ordering, (iv) coherence score prediction. 3-way classification: Given a document, the task is to classify it into one of the three different labels (high, medium and low) which denotes the textual coherence level of the given document. 2-way classification: This task is similar to the 3way classification task, except that there are only two labels: non-coherent or other. Sentence ordering: For this task, every original document is assumed to be coherent. 20 random permutations (other than the original document) of sentences in the document are then obtained and labeled as negative. The dataset is created by pairing the original document and the permuted document. The task is to rank the original document higher than the permuted one in terms of coherence. Coherence score prediction: A 3-point coherence score might not reflect the range of coherence that actually exists in the data. Hence, we also experiment with a coherence score prediction task. It is a regression task where, given a document, the task is to predict the degree of the textual coherence.
Note that manual judgment labels are required for 3-way classification, 2-way classification and coherence score prediction tasks. Dataset for the sentence ordering task can be generated in a synthetic manner. Also note that for all tasks, the input is a single document except for the sentence ordering task where the input is a pair of documents.

Proposed Transformer based architectures
Transformer ( (1) vanilla Transformer models, (2) hierarchical Transformers with two levels, (3) multi-task learning with text coherence assessment and textual entailment, and (4) fact based input representation where besides the original document, we also pass extracted facts as input. We discuss details of each of these methods in the following. For each of these architectures 2 , we use RoBERTa as the basic Transformer model; we tried using BERT as well, but found RoBERTa to be better across all experiments. Fig. 1 shows the basic architecture of each of these models.

Vanilla Transformer
The simplest way of performing text coherence tasks is to feed the input text to a Transformer model as shown in Fig. 1(A). We choose RoBERTa (Liu et al., 2019) which is an extension of BERT with changes to the pretraining procedure. The modifications include: (1) training the model longer, with bigger batches, over more data (2) removing the next sentence prediction objective (3) training on longer sequences, and (4) dynamically changing the masking pattern applied to the training data. RoBERTa has been shown to perform very well across many NLP tasks. RoBERTa however cannot handle very long sequences. Thus, for long sequence tasks (especially sentence ordering), we resort to Longformer (Beltagy et al., 2020). Longformer has an attention mechanism that scales linearly with sequence length, making it easy to process documents of thousands of tokens or longer. Longformer's attention mechanism is a drop-in replacement for the standard self-attention and combines a local windowed attention with a task motivated global attention.

Hierarchical Transformer
In our hierarchical Transformer architecture, we leverage a two-level hierarchical RoBERTa model for obtaining document representation as shown in Fig. 1(B). To obtain the representation of document D, we use two encoders: a sentence encoder to transform each sentence in D to a vector and a document encoder to learn sentence representations given their surrounding sentences as context. Both the sentence encoder and document encoder are based on the Transformer encoder. The sentence encoder takes individual sentences (separated by SEP token) as input. The outputs from each position of the last layer of the sentence encoder are pooled (separately for each sentence) using various pooling strategies like min, max, mean, sum, attention or none. In the "none" pooling strategy, the representation for the last sentence token is used to represent the sentence. Each sentence in the document is encoded by the sentence encoder and passed as input to the document encoder. Finally, the CLS token's transformed representation from the document encoder is fed to a dense layer with ReLU activation which is then connected to a taskspecific output layer. The two encoders can either be initialized randomly or using transfer learning.

MTL with Transformers
When multiple related prediction tasks need to be performed, multi-task learning (MTL) has been found to be very effective. Hard parameter sharing is the most commonly used approach to MTL in neural networks. It is generally applied by sharing the hidden layers between all tasks, while keeping several task-specific output layers. Given a pair of sentences, the textual entailment task aims to predict whether the second sentence (hypothesis) is an entailment with respect to the first one (premise) or not. Textual entailment and text coherence assessment are very similar tasks. As shown in Fig. 1(C), we share the Transformer encoder weights across the two tasks. Task specific layers for each task are conditioned on the shared Transformer encoder. For the sentence entailment task, we form input by concatenating the hypothesis and premise with sentence separator token SEP placed between them. For both the tasks (coherence and entailment), we use a fully-connected layer with ReLU, and then a softmax output layer.
The final loss is computed as a sum of the individual losses for the two tasks.

Fact-aware Transformer
We leverage MinIE, an Open Information Extraction system (Gashteovski et al., 2017) to generate a set of facts for each sentence. Open Information Extraction systems aim to exploit linguistic information including dependency relations in sentences to extract facts in a knowledge-agnostic manner. A fact is essentially an ordered 3-tuple (subject, verb and object) extracted from a particular sentence. A single sentence can produce multiple facts. Consider the sentence "They are trying to determine whether it was used to attack Steenkamp, if she used the bat in self-defense." Two facts that can be extracted from this sentence are ("it", "was used to attack", "Steenkamp") and ("she", "used bat in", "self-defense"). Each of the three components of a fact triple can contain multiple words.
Let the length of sequence of tokens present in document D be denoted by L and the number of distinct facts obtained from the document using MinIE system be denoted by M . As shown in Fig. 1(D), our fact-aware Transformer method consists of three kinds of encoders: a document encoder, M fact encoders (F E 1 , F E 2 . . . F E M ) and a fact-aware document encoder. Each encoder uses a vanilla Transformer model. Document encoder and all the fact encoders share weights. Document encoder encodes the document expressed using standard sub-word tokens. Fact encoder F E i encodes the i th fact using the (subject, verb, object) for the fact as input delimited by SEP. Document encoder produces document representation T , while each of the fact encoders F E i produce fact representation f i . These fact representations and the document representation form the input for the fact-aware document encoder. Finally, the representation from the last layer of the fact-aware encoder corresponding to the CLS token, is connected to a fully-connected layer with ReLU, and then a softmax output layer.
For all tasks except sentence ordering, we pass the document representation obtained from proposed models to a dense layer with ReLU activation which is then connected to a task-specific output layer, as shown in Fig. 1. For sentence ordering task, we apply Siamese network (Bromley et al., 1993) or twin neural network approach with each of our four proposed architectures, as illustrated in Fig. 2. In this approach, the coherent and incoher-  Figure 2: Overview of Siamese neural approach applied for sentence ordering task. Document encoder weights are shared. Dense layer weights are also shared. ent document representation is obtained by using any of the four document encoders (from Fig. 1). The document encoder for the coherent as well as the incoherent document, share weights. Further, both the document representations are separately connected to a dense layer with shared weights. The outputs of the dense layers are used to calculate the margin ranking loss.

Datasets
We experiment with two popular benchmark datasets: Wall Street Journal (WSJ) and Grammarly Corpus of Discourse Coherence (GCDC). GCDC is a real dataset while WSJ is a synthetic dataset. We use the Recognizing Textual Entailment (RTE) dataset  for training an auxiliary task for our MTL model (2490 train and 277 validation instances) for experiments on GCDC. For WSJ, we found MTL to perform better when we use the Multi-Genre Natural Language Inference (MNLI) dataset (Williams et al., 2018) for training the auxiliary task.

WSJ
The WSJ portion of the Penn Treebank (Elsner and Charniak, 2008;Nguyen and Joty, 2017) is one of the most popular datasets for the sentence ordering task. It contains long articles without any constraint on style. Following previous work (Barzilay and Lapata, 2008;Nguyen and Joty, 2017), we also use the sections 00 -13 for training and 14 -24 for testing (documents consisting of one sentence are removed). We create 20 permutations per document, making sure to exclude duplicates or versions that happen to have the same ordering of sentences as the original article. We present the basic statistics of the dataset in Table 1   calculates the fraction of correct pairwise rankings in the test data (i.e., the original coherent text should be ranked higher than its permuted noncoherent counterpart).

GCDC
The GCDC dataset contains emails and reviews written with varying degrees of proficiency and care (Lai and Tetreault, 2018). The WSJ dataset contains documents that have been professionally written and extensively edited. In contrast to WSJ, the GCDC dataset contains writing from nonprofessional writers in everyday contexts. Rather than using permuted or machine generated texts as examples of low coherence, GCDC has real sentences in which people try but fail to write coherently. GCDC is a corpus that contains texts from four domains, covering a range of coherence, each annotated with a document-level coherence score. Specifically, the dataset contains texts from four domains: Yahoo online forum posts, emails from Hillary Clinton's office, emails from Enron and Yelp business reviews. We present the basic statistics of the dataset in Table 2. 3-way classification: For each of these domains, a fixed split of 1000 and 200 was used for train and test respectively as specified in (Lai and Tetreault, 2018). Of the 1000 documents, we use 200 documents for validation and remaining 800 for training. For our experiments, we use the consensus rating of the expert scores as calculated by (Lai and Tetreault, 2018), and train our models for all the four tasks. To evaluate model performance, we use 3-way classification accuracy.  Table 3: Basic statistics of the GCDC dataset for the sentence ordering task. We used the same train and test split as specified in [Lai and Tetreault, 2018].

2-way classification:
A text is labeled as noncoherent if at least two expert annotators judged the text to be low coherence, or labeled as "other" otherwise. For 2-way classification task, we report the F 0.5 score of low coherence class where precision is emphasized twice as much as recall. This is in line with evaluation standards in writing feedback applications (Ng et al., 2014) and also in previous text coherence studies (Lai and Tetreault, 2018). Sentence ordering: Similar to (Lai and Tetreault, 2018) we created the synthetic dataset for this task in the same way as for WSJ. Since the sentence ordering task assumes well-formed texts, we use only the high coherence texts. Statistics of the GCDC dataset wrt this task are shown in Table 3. We use PRA as the metric for this task as well.
Coherence Score Prediction: For this task, gold score is the mean of 3 expert rater judgments (low coherence = 1, medium = 2, high = 3). We report Spearman's rank correlation coefficient between the gold scores and the predicted coherence scores.

Baselines
We experiment with the following baselines. While Flesch-Kincaid grade level (Kincaid et al., 1975) is a readability measure, previous work has treated readability and text coherence as overlapping tasks (Barzilay and Lapata, 2008;Mesgar and Strube, 2015). For coherence classification, we search over the grade level scores on the training data and select thresholds that result in the highest accuracy. Entity grid (EGRID) (Barzilay and Lapata, 2008) builds an entity grid which is a matrix that tracks entity mentions over sentences. Random forest classifier is trained over features extracted from entity grid. CNN-Egrid (Nguyen and Joty, 2017) is a local coherence model that employs a CNN that operates over the entity grid representation. Lexicalized CNN-Egrid (Mohiuddin et al., 2018) extends CNN-Egrid with lexical information about the entities. In Local Coherence Model (LC) (Li and Hovy, 2014), sentences are encoded with a recurrent or recursive layer and a filter of weights is applied over each window of sentence vectors to extract scores that are aggregated to calculate overall document coherence score. Paragraph sequence (PARSEQ) (Lai and Tetreault, 2018) contains three stacked LSTMs to represent sentence, paragraph and document. Hierachical LSTM (Farag and Yannakoudakis, 2019) is very similar to PARSEQ, but with attention and uses BiLSTMs. Coh+GR (Farag and Yannakoudakis, 2019) extends Hierachical LSTM by training it to predict word-level labels indicating the predicted grammatical role (GR) type at the bottom layers of the network, along with the document-level coherence score. Coh+SOX (Farag and Yannakoudakis, 2019) is same as Coh+GR where, for each word, we only predict subject (S), object (O) and 'other' (X) roles. Seq2Seq (Li and Jurafsky, 2017) consists of two LSTM generative language models and uses the difference between conditional log likelihood of a sentence given its preceding/succeeding context, and the marginal log likelihood of the current/next sentence to assess coherence. Local Coherence Discriminator (LCD-G) (Xu et al., 2019) uses averaged GloVe embeddings as the sentence representations. A representation for two consecutive sentences is then computed by concatenating the output of a set of linear transformations applied to the two sentences. This is fed to a dense layer and used to predict a local coherence score. LCD-L (Xu et al., 2019) is similar to LCD-G, but applies max-pooling on the hidden state of the language model to get the sentence representation.
Coh+GR_BERT (Farag et al., 2020) is similar to Coh+GR, except that BERT embeddings are used instead of GloVe embeddings as input to BiL-STMs. LCD_BERT (Farag et al., 2020) is similar to LCD-G but uses averaged BERT (instead of GloVe) embeddings as the sentence representations.

Experimental Settings
All experiments were run on a machine equipped with four 32GB V100 GPUs. For all Transformer models, we use 12-layer models, and embedding layer was frozen except for the sentence ordering task on WSJ. For Hierarchical Transformer models, we used pretrained model for the sentence en-coder and a randomly initialized RoBERTa for document encoder. For fact-aware Transformer models, we used pretrained model for the fact encoders and document encoder, and a randomly initialized RoBERTa for fact-aware document encoder. For all experiments we run 10 epochs, weight decay of 0.01 and use a dropout of 0.1. We use Adam optimizer for all the experiments, except for WSJ experiments where we use AdamW. For all the baseline models, we report results from their original papers. For all of our models, the reported results are the mean of 10 runs with different random seeds. When we use margin ranking loss, where margin is set to 1. For MTL based Transformers, categorical cross entropy loss was used for the auxiliary task. For Longformer, we fixed max sequence length to 2048. For RoBERTa, we fixed it to 512.

Results
Tables 4 to 8 show the results across all the four text coherence tasks for WSJ and GCDC datasets.
Broadly we observe that our proposed Transformerbased methods significantly outperform baselines, establishing a new SOTA across all tasks. We also experimented with a fact-aware hierarchical MTL model (or a combined model) but observed that the combination does not lead to any better results. Sentence ordering results: Tables 4 and 5 show results for the sentence ordering task for WSJ and GCDC datasets respectively. We make the following observations for WSJ results (Table 4): (1) Fact aware transformer outperforms hierarchical model as it can incorporate the factual information flow (subject in discourse) in addition to textual information which helps it to correctly determine the coherent sentences.
(2) MTL with Transformers outperforms other variants as the auxiliary task helps in better generalization over test set.   3-way classification results: Table 6 shows 3-way classification results on GCDC. We make the following observations: (1) While MTL with Transformers leads to best results on average across all domains, there is no unique winner for individual domains. Still, our proposed methods outperformed the baselines.
(2) Re-ordering of associated facts helps the fact-aware Transformer model in identifying the change in sentence order (in WSJ synthetic data) but seems ineffective on realistic (GCDC) documents.
(3) Out of the three gold coherence labels (low, medium, high) all the models have difficulty in correctly classifying documents of medium level coherence, which can be attributed to the smaller number of training examples for that particular class. Coherence Score Prediction results: Table 7 shows Coherence Score Prediction results on GCDC. We observe that (1) Table 7: Coherence Score Spearman correlation Prediction results on GCDC. "(all)" indicates that training data across all four domains was used.  Table 8: 2-way classification F 0.5 results on GCDC. "(all)" indicates that training data across all four domains was used.

Conclusion
In this paper, we investigate the efficacy of four different transformer architectures: vanilla, hierarchical, MTL with transformer, and fact-aware transformer on four different coherence assessment tasks: 2-way classification, 3-way classification, sentence ordering, and coherence score prediction. We observe that all the transformer based approaches outperforms existing models. It indicate that deeper models like transformer captures textual coherence signal well. Our work also shows that inductive transfer between MTL-based transformer models' tasks: textual coherence assessment and textual entailment, helps it achieve the best performance for most coherence assessment tasks.
In the future, we plan to extend this work to evaluate the text coherence in an open domain setting. We also plan to evaluate the impact of coherence estimation on downstream applications like essay evaluation and summarization.