SlowGuess/NAACL_2021_OCR huggingface dataset:
Tianwen Wei* Jianwei Qi Shenghuan He Songtao Sun  
Xiaomi AI
{weitianwen,qijianwei,heshenghuan,sunsongtao}@xiaomi.com
Conditional Random Field (CRF) based neural models are among the most performant methods for solving sequence labeling problems. Despite its great success, CRF has the shortcoming of occasionally generating illegal sequences of tags, e.g. sequences containing an "I-" tag immediately after an "O" tag, which is forbidden by the underlying BIO tagging scheme. In this work, we propose Masked Conditional Random Field (MCRF), an easy to implement variant of CRF that impose restrictions on candidate paths during both training and decoding phases. We show that the proposed method thoroughly resolves this issue and brings consistent improvement over existing CRF-based models with near zero additional cost.
Sequence labeling problems such as named entity recognition (NER), part of speech (POS) tagging and chunking have long been considered as fundamental NLP tasks and drawn researcher's attention for many years.
Traditional work is based on statistical approaches such as Hidden Markov Models (Baum and Petrie, 1966) and Conditional Random Fields (Lafferty et al., 2001), where handcrafted features and task-specific resources are used. With advances in deep learning, neural network based models have achieved dominance in sequence labeling tasks in an end-to-end manner. Those models typically consist of a neural encoder that maps the input tokens to embeddings capturing global sequence information, and a CRF layer that models dependencies between neighboring labels. Popular choices of neural encoder have been convolutional neural network (Collobert et al., 2011), and bidirectional LSTM (Huang et al., 2015). Recently, pretrained language models such as ELMo (Peters et al., 2018) or BERT
(Devlin et al., 2019) have been proven far superior as a sequence encoder, achieving state-of-the-art results on a broad range of sequence labeling tasks.
Most sequence labeling models adopt a BIO or BIOES tag encoding scheme (Ratinov and Roth, 2009), which forbids certain tag transitions by design. Occasionally, a model may yield sequence of predicted tags that violates the rules of the scheme. Such predictions, subsequently referred to as illegal paths, are erroneous and must be dealt with. Existing methods rely on hand-crafted post-processing procedure to resolve this problem, typically by retaining the illegal segments and re-tagging them. But as we shall show in this work, such treatment is arbitrary and leads to suboptimal performance.
The main contribution of this paper is to give a principled solution to the illegal path problem. More precisely:
1. We show that in the neural-CRF framework the illegal path problem is intrinsic and may accounts for non-negligible proportion (up to  $40\%$  ) of total errors. To the best of our knowledge we are the first to conduct this kind of study.
2. We propose Masked Conditional Random Field (MCRF), a constrained version of the CRF that is by design immune to the illegal paths problem. We also devise an algorithm for MCRF that incurs almost zero overhead and requires only a few lines of code to implement. Further, we provide a theoretical justification of the proposed method.
3. We show in comprehensive experiments that MCRF performs significantly better than its CRF counterpart, and that its performance is on par with and sometimes better than more sophisticated models. We achieve new State-of-the-Arts in two Chinese NER datasets.
The remainder of the paper is organized as follows. Section 2 describes the illegal path problem
Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pages 2024-2035 June 6-11, 2021. ©2021 Association for Computational Linguistics
Dataset	legal & TP	illegal & TP	legal & FP	illegal & FP	illegal & TP illegal	illegal & FP FP	illegal total
Resume	1445	1	68	17	1.4%	20%	1.2%
MSRA	5853	6	318	107	1.9%	25%	1.8%
Ontonotes	5323	5	1336	314	1.6%	19%	4.6%
Weibo	277	2	124	46	1.6%	27%	10.7%
ATIS	1643	0	70	24	0.0%	26%	1.4%
SNIPS	1542	13	237	156	5.2%	40%	8.7%
CoNLL2000	22957	36	888	100	3.9%	10%	0.6%
CoNLL2003	5131	2	535	74	0.4%	12%	1.3%
Table 1: Statistics of the predicted text segments by category over a variety of sequence labeling datasets. A BERT-CRF model with BIO scheme is trained for each of the dataset, and the statistics are computed on the respective dev set. When the model generates an illegal path, we determine the predicted segments as in (Sang et al., 2000), see Section 2.2 for more details. In the table "TP" and "FP" refer to "True Positive" and "False Positive" respectively. The column named " $\frac{illegal\& TP}{illegal}$ " indicates the proportion of illegal segments that are correct predictions. The column named " $\frac{illegal\& FP}{FP}$ " indicates the proportion of erroneous predictions that are due to illegal segments. The column named " $\frac{illegal}{total}$ " stands for the proportion of illegal segments over all predictions.
and existing strategies that resolve it. In Section 3 we propose MCRF, its motivation and an approximate implementation. Section 4 is devoted to numerical experiments. We conclude the current work in Section 5.
2 The illegal path problem
As a common practice, most sequence labeling models utilize a certain tag encoding scheme to distinguish the boundary and the type of the text segments of interest. An encoding scheme makes it possible by introducing a set of tag prefixes and a set of tag transition rules. For instance, the popular BIO scheme distinguishes the Beginning, the Inside and the Outside of the chunks of interest, imposing that any I- $*$  tag must be preceded by a B- $*$  tag or another I- $*$  tag of the same type. Thus “O O O I-LOC I-LOC O” is a forbidden sequence of tags because the transition  $O \rightarrow I-LOC$  directly violates the BIO scheme design. Hereafter we shall refer to a sequence of tags that contains at least one illegal transition an illegal path.
As another example, the BIOES scheme further identifies the Ending of the text segments and the Singleton segments, thereby introducing more transition restrictions than BIO. e.g. an  $\mathbb{I} - *\mathrm{tag}$  must always be followed by an  $\mathbb{E} - *\mathrm{tag}$  of the same type, and an S-* tag can only be preceded by an  $\mathbb{O}$ , an E-* or another S-* tag, etc. For a comparison of the performance of the encoding schemes, we refer to (Ratinov and Roth, 2009) and references therein.
When training a sequence labeling model with an encoding scheme, generally it is our hope that the model should be able to learn the semantics and the transition rules of the tags from the training data. However, even if the dataset is noiseless, a properly trained model may still occasionally make predictions that contains illegal transitions. This is especially the case for the CRF-based models, as there is no hard mechanism built-in to enforce those rules. The CRF ingredient by itself is only a soft mechanism that encourages legal transitions and penalizes illegal ones.
The hard transition rules might be violated when the model deems it necessary. To see this, let us consider a toy corpus where every occurrence of the token "America" is within the context of "North America", thus the token is always labeled as I-LOC. Then, during training, the model may well establish the rule "America  $\Rightarrow$  I-LOC" (Rule 1), among many other rules such as "an I-LOC tag does not follow an O tag" (Rule 2), etc. Now consider the test sample "Nathan left America last month", which contains a stand-alone "America" labeled as B-LOC. During inference, as the model never saw a stand-alone "America" before, it must generalize. If the model is more confident on Rule 1 than Rule 2, then it may yield an illegal output "O O I-LOC O O".
2.2 Strategies
The phenomenon of illegal path has already been noticed, but somehow regarded as trivial matters.
For the BIO format, Sang et al. (2000) have stated that
The output of a chunk recognizer may contain inconsistencies in the chunk tags in case a word tagged  $\mathbb{I} - \mathbb{X}$  follows a word tagged O or I-Y, with X and Y being different. These inconsistencies can be resolved by assuming that such I-X tags starts a new chunk.
This simple strategy has been adopted by CoNLL-2000 as a standard post-processing procedure<sup>1</sup> for the evaluation of the models' performance, and gain its popularity ever since.
We argue that such treatment is not only arbitrary, but also suboptimal. In preliminary experiments we have studied the impact of the illegal path problem using the BERT-CRF model for a number of tasks and datasets. Our findings (see Table 1) suggest that although the illegal segments only account for a small fraction (typically around  $1\%$ ) of total predicted segments, they constitute approximately a quarter of the false positives. Moreover, we found that only a few illegal segments are actually true positives. This raises the question of whether retaining the illegal segments is beneficial. As a matter of fact, as we will subsequently show, a much higher macro F1-score can be obtained if we simply discard every illegal segments.
Although the strategy of discarding the illegal segments may be superior to that of (Sang et al., 2000), it is nonetheless a hand-crafted, crude rule that lacks some flexibility. To see this, let us take the example in Fig. 1. The prediction for text segment World Boxing Council is (B-MISC, I-ORG, I-ORG), which contains an illegal transition B-MISC  $\rightarrow$  I-ORG. Clearly, neither of the post-processing strategies discussed above is capable of resolving the problem. Ideally, an optimal solution should convert the predicted tags to either (B-MISC, I-MISC, I-MISC) or (B-ORG, I-ORG, I-ORG), whichever is more likely. This is exactly the starting point of MCRF, which we introduce in the next section.
In this section we introduce the motivation and implementation of MCRF. We first go over the
conventional neural-based CRF models in Section 3.1. We then introduce MCRF in Section 3.2. Its implementation will be given in Section 3.3.
3.1 Neural CRF Models
Conventional neural CRF models typically consist of a neural network and a CRF layer. The neural network component serves as an encoder that usually first maps the input sequence of tokens to a sequence of token encodings, which is then transformed (e.g. via a linear layer) into a sequence of token logits. Each logit therein models the emission scores of the underlying token. The CRF component introduces a transition matrix that models the transition score from tag  $i$  to tag  $j$  for any two consecutive tokens. By aggregating the emission scores and the transition scores, deep CRF models assign a score for each possible sequence of tags.
Before going any further, let us introduce some notations first. In the sequel, we denote by  $x = \{x_{1},x_{2},\ldots ,x_{T}\}$  a sequence of input tokens, by  $y = \{y_{1},\dots ,y_{T}\}$  their ground truth tags and by  $l = \{l_1,\dots ,l_T\}$  the logits generated by the encoder network of the model. Let  $d$  be the number of distinct tags and denote by  $[d]\coloneqq \{1,\dots ,d\}$  the set of tag indices. Then  $y_{i}\in [d]$  and  $l_{i}\in \mathbb{R}^{d}$  for  $1\leq i\leq T$ . We denote by  $W$  the set of all trainable weights in the encoder network, and by  $A = (a_{ij})\in \mathbb{R}^{d\times d}$  the transition matrix introduced by the CRF, where  $a_{ij}$  is the transition score from tag  $i$  to tag  $j$ . For convenience we call a sequence of tags a path. For given input  $x$ , encoder weights  $W$  and transition matrix  $A$ , we define the score of a path  $p = \{n_1,\dots ,n_T\}$  as
$$
s (p, x, W, A) = \sum_ {i = 1} ^ {T} l _ {i, n _ {i}} + \sum_ {i = 1} ^ {T - 1} a _ {n _ {i}, n _ {i + 1}}, \tag {1}
$$
where  $l_{i,j}$  denotes the  $j$ -th entry of  $l_i$ . Let  $\mathcal{S}$  be the set of all training samples, and  $\mathcal{P}$  be the set of all possible paths. Then the loss function of neural CRF model is the average of negative log-likelihood over  $\mathcal{S}$ :
$$
\mathcal {L} (W, A) = - \frac {1}{| \mathcal {S} |} \sum_ {(x, y) \in \mathcal {S}} \log \frac {\exp s (y , x)}{\sum_ {p \in \mathcal {P}} \exp s (p , x)} \tag {2}
$$
where we have omitted the dependence of  $s(\cdot, \cdot)$  on  $(W, A)$  for conciseness. One can easily minimize  $\mathcal{L}(W, A)$  using any popular first-order methods such as SGD or Adam.
Let  $(W_{\mathrm{opt}},A_{\mathrm{opt}})$  be a minimizer of  $\mathcal{L}$ . During decoding phase, the predicted path for a test sample
<sup>1</sup>We are referring to the conlleval script, available from https://www/clips.uantwerpen.be/conll2000/chunking/.
Figure 1: An example of CRF decoded path vs. MCRF decoded path. The CRF decoded path is represented as black arrows in the figure. This path contains one illegal transition (black dashed arrow) B-MISC  $\rightarrow$  I-ORG, which results in two erroneous predictions: MISC for "World" and ORG for "Boxing Council". When using MCRF instead, the decoding algorithm has to search for an alternative path (red arrows), as all illegal transitions are blocked. In this example, MCRF correctly predicts MISC for the entity "World Boxing Council".
$x_{\mathrm{test}}$  is the path having the highest score, i.e.
$$
y _ {\text {o p t}} = \underset {p \in \mathcal {P}} {\operatorname {a r g m a x}} s (p, x _ {\text {t e s t}}, W _ {\text {o p t}}, A _ {\text {o p t}}). \tag {3}
$$
The decoding problem can be efficiently solved by the Viterbi algorithm.
3.2 Masked CRF
Our major concern on conventional neural CRF models is that no hard mechanism exists to enforce the transition rule, resulting in occasional occurrence of illegal predictions.
Our solution to this problem is very simple. Denote by  $\mathcal{I}$  the set of all illegal paths. We propose to constrain the "path space" in the CRF model to the space of all legal paths  $\mathcal{P} / \mathcal{I}$ , instead of the entire space of all possible paths  $\mathcal{P}$ . To this end,
1. during training, the normalization term in (2) should be the sum of the exponential scores of the legal paths;
2. during decoding, the optimal path should be searched over the space of all legal paths.
The first modification above leads to the following new loss function:
$$
\mathcal {L} ^ {\prime} (W, A) := - \frac {1}{| \mathcal {S} |} \sum_ {(x, y) \in \mathcal {S}} \log \frac {\exp s (y , x)}{\sum_ {p \in \mathcal {P} / \mathcal {I}} \exp s (p , x)}, \tag {4}
$$
which is obtained by replacing the  $\mathcal{P}$  in (2) by  $\mathcal{P} / \mathcal{I}$ . Similarly, the second modification leads to
$$
y _ {\text {o p t}} ^ {\prime} = \underset {p \in \mathcal {P} / \mathcal {I}} {\operatorname {a r g m a x}} s (p, x _ {\text {t e s t}}, W _ {\text {o p t}} ^ {\prime}, A _ {\text {o p t}} ^ {\prime}) \tag {5}
$$
obtained by replacing the  $\mathcal{P}$  in (3) by  $\mathcal{P} / \mathcal{I}$ , where  $(W_{\mathrm{opt}}^{\prime},A_{\mathrm{opt}}^{\prime})$  is a minimizer of (4).
Note that the decoding objective (5) alone is enough to guarantee the complete elimination of illegal paths. However, this would create a mismatch between the training and the inference, as the model would attribute non-zero probability mass to the ensemble of the illegal paths. In Section 4.1, we will see that a naive solution based on (5) alone leads to suboptimal performance compared to a proper solution based on both (4) and (5).
Figure 2: An example of the masked transition matrix under the BIO scheme. The entries in the red cells are masked as they correspond to illegal transitions. Under the BIO scheme, there are two types of illegal transitions:  $\mathrm{O} \rightarrow \mathrm{I} - \mathrm{X}$  for any  $\mathrm{X}$  and  $\mathrm{B} - \mathrm{X} \rightarrow \mathrm{I} - \mathrm{Y}$  for any  $\mathrm{X}, \mathrm{Y}$  such that  $\mathrm{X} \neq \mathrm{Y}$ .
Although in principle it is possible to directly minimize (4), thanks to the following proposition we can also achieve this via reusing the existing tools originally designed for minimizing (2), thereby saving us from making extra engineering efforts.
Proposition 1. Denote by  $\Omega \subset [d] \times [d]$  the set of all illegal transitions. For a given transition matrix  $A$ , we denote by  $\bar{A}(c) = (\bar{a}_{ij}(c))$  the masked transition matrix of  $A$  defined as (see Fig. 2)
$$
\bar {a} _ {i j} (c) = \left\{ \begin{array}{l l} c & \text {i f} (i, j) \in \Omega , \\ a _ {i j} & \text {o t h e r w i s e}, \end{array} \right. \tag {6}
$$
where  $c \ll 0$  is the transition mask. Then for arbitrary model weights  $(W_0, A_0)$ , we have
$$
\lim  _ {c \rightarrow - \infty} \mathcal {L} \left(W _ {0}, \bar {A} _ {0} (c)\right) = \mathcal {L} ^ {\prime} \left(W _ {0}, A _ {0}\right) \tag {7}
$$
$$
\lim  _ {c \rightarrow - \infty} \nabla_ {W} \mathcal {L} \left(W _ {0}, \bar {A} _ {0} (c)\right) = \nabla_ {W} \mathcal {L} ^ {\prime} \left(W _ {0}, A _ {0}\right) \tag {8}
$$
and for all  $(i,j)\in \Omega$
$$
\lim  _ {c \rightarrow - \infty} \nabla_ {a _ {i j}} \mathcal {L} (W _ {0}, \bar {A} _ {0} (c)) = \nabla_ {a _ {i j}} \mathcal {L} ^ {\prime} (W _ {0}, A _ {0}). \tag {9}
$$
Moreover, for negatively large enough  $c$  we have
$\operatorname*{argmax}_{p\in \mathcal{P}}s(p,x_{test},W,A) = \operatorname*{argmax}_{p\in \mathcal{P} / \mathcal{I}}s(p,x_{test},W,A)$
Proposition 1 states that for any given model state  $(W, A)$ , if we mask the entries of  $A$  that correspond to illegal transitions (see Figure 2) by a negatively large enough constant  $c$ , then the two objectives (2) and (4), as well as their gradients, can be arbitrarily close. This suggests that the task of minimizing (4) can be achieved via minimizing (2) combined with keeping  $A$  masked (i.e. making  $a_{ij} = c$  constant for all  $(i,j) \in \Omega$ ) throughout the optimization process.
Intuitively, the purpose of transition masking is to penalize the illegal transitions in such a way that they will never be selected during the Viterbi decoding, and the illegal paths as a whole only constitutes negligible probability mass during training.
Based on Proposition 1, we propose the Masked CRF approach, formally described in Algorithm 1.
In this section, we run a series of experiments $^2$  to evaluate the performance of MCRF. The datasets used in our experiments are listed as follows:
Algorithm 1 (MCRF)
1: Input: Library for computing the gradients of conventional CRF loss (2), training dataset  $S$ , stopping criterion  $\mathcal{C}$ , set of illegal transitions  $\Omega$ , masking constant  $c \ll 0$ .
2: Initialize: model weight  $W$  and tag transition matrix  $A = (a_{ij})$ .
3: while  $\mathcal{C}$  is not met do
4: Sample a mini-batch from  $\mathcal{S}$
5: Update  $W$  and  $A$  based on batch gradient
6: for  $(i,j)\in \Omega$  do
7:  $a_{ij} \gets c$ $\triangleright$  maintain the mask
8: end for
9: end while
10: Output: Optimized  $W$  and  $A$ .
- Chinese NER: OntoNotes 4.0 (Weischedel et al., 2011), MSRA (Levow, 2006), Weibo (Peng and Dredze, 2015) and Resume (Zhang and Yang, 2018).
- English NER: CoNLL2003 (Tjong Kim Sang and De Meulder, 2003)
- Slot Filling: ATIS (Hemphill et al., 1990) and SNIPS (Coucke et al., 2018)
- Chunking: CoNLL2000 (Sang et al., 2000)
The statistics of these datasets are summarized in Table 2.
dataset	task	lan.	labels	train	dev	test
Resume	NER	CN	8	3.8k	472	477
MSRA	NER	CN	3	46.3k	-	4.3k
Ontonotes	NER	CN	4	15.7k	4.3k	4.3k
Weibo	NER	CN	7	1.3k	270	270
ATIS	SF	EN	79	4.5k	500	893
SNIPS	SF	EN	39	13.0k	700	700
CoNLL2000	Chunk.	EN	11	8.9k	-	2.0k
CoNLL2003	NER	EN	4	14.0k	3.2k	3.5k
Table 2: Statistics of the datasets.
For Chinese NER tasks, we use the public-available $^3$  BERT $_{\text{BASE}}$  as the pretrained model. For English NER and Chunking tasks, we use the cased version of BERT $_{\text{BASE}}$  model. We use uncased BERT $_{\text{BASE}}$  for English slot filling tasks.
In preliminary experiments, we found out that the discriminative fine-tuning approach (Howard and Ruder, 2018) yields slightly better results than
Resume	MSRA	Ontonotes	Weibo
Lattice (Zhang and Yang, 2018)	94.5	93.2	73.9	58.8
Glyce (Meng et al., 2019)†	96.5	95.5	81.6	67.6
SoftLexicon (Ma et al., 2020)†	96.1	95.4	82.8	70.5
FLAT (Li et al., 2020a)†	95.9	96.1	81.8	68.6
MRC (Li et al., 2020b)†	-	95.7	82.1	-
DSC (Li et al., 2020c)†	-	96.7	84.5	-
BERT-tags-retain	95.7 (94.7)	94.0 (92.7)	78.1 (76.8)	67.7 (65.3)
BERT-tags-discard	96.2 (95.5)	94.6 (93.6)	80.7 (79.2)	69.7 (67.5)
BERT-CRF-retain	95.9 (94.8)	94.2 (93.7)	81.8 (81.2)	70.8 (64.5)
BERT-CRF-discard	97.2 (96.6)	95.5 (94.9)	83.1 (82.4)	71.9 (65.7)
BERT-MCRF-decoding	97.3 (96.6)	95.6 (95.0)	83.2 (82.5)	72.2 (65.8)
BERT-MCRF-training	97.6 (96.9)	95.9 (95.3)	83.7 (82.7)	72.4 (66.5)
the standard fine-tuning as recommended by (Devlin et al., 2019). In discriminative fine-tuning, one uses different learning rates for each layer. Let  $r_{L}$  be the learning rate for the last  $(L$ -th) layer and  $\eta$  be the decay factor. Then the learning rate for the  $(L - n)$ -th layer is given by  $r_{L - n} = r_{L}\eta^{n}$ . In our experiments, we use  $r_{L} \in \{1e - 4,5e - 5\}$  and  $\eta \in \{1 / 2,2 / 3\}$  depending on the dataset. The standard Adam optimizer is used throughout, and the mini-batch size is fixed to be 32. We always fine-tune for 5 epochs or 10000 iterations, whichever is longer.
In this section we present the MCRF results on 8 sequence labeling datasets. The baseline models are the following:
- BERT-tags: The output of the final hidden representation for to each token is fed into a classification layer over the label set without using CRF. This is the approach recommended in (Devlin et al., 2019).
- BERT-CRF: BERT followed by a CRF layer, as is described in Section 3.1.
We use the following strategies to handle the illegal segments (See Table 4 for an example):
- retain: Keep and retag the illegal segments. This strategy agrees with (Sang et al., 2000).
- discard: Discard the illegal segments completely.
Table 3: Results on Chinese NER datasets. The “†” symbol implies that the reported result is based on BERT. The numbers in the parenthesis and the numbers next to it indicate the average and max F1-score, respectively.
original:	O	I-PER	O	B-LOC	I-MISC
retain:	O	B-PER	O	B-LOC	B-MISC
discard:	O	O	O	B-LOC	O
Table 4: An example illustrating the difference between "retain" strategy and "discard" strategy.
We distinguish two versions of MCRF:
- MCRF-decoding: A naive version of MCRF that does masking only in decoding. The training process is the same as that in conventional CRF.
- MCRF-training: The proper MCRF approach proposed in this work. The masking is maintained in the training, as is described in Section 3.3. We also refer to it as the MCRF for simplicity.
For each dataset and each model we ran the training 10 times with different random initializations and selected the model that performed best on the dev set for each run. We report the best and the average test F1-scores as the final results. If the dataset does not provide an official development set, we randomly split the training set and use  $10\%$  of the samples as the dev set.
4.1.1 Results on Chinese NER
The results on Chinese NER tasks are presented in Table 3. It can be seen that the MCRF-training approach significantly outperforms all baseline models and establishes new State-of-the-Arts for Re
sume and Weibo datasets. From these results we can assert that the improvement brought by MCRF is mainly due to the effect of masking in training, not in decoding. Besides, we notice that the "discard" strategy substantially outperforms the "retain" strategy, which agrees with the statistics presented in Table 1.
We also plotted in Fig. 3 the loss curves of CRF and MCRF on the development set of MSRA. It can be clearly seen that MCRF incurs a much lower loss during training. This confirms our hypothesis that the CRF model attributes non-zero probability mass to the ensemble of the illegal paths, as otherwise the denominators in (4) and in (2) would have been equal, and in that case the loss curves of CRF and MCRF would have converged to the same level.
Figure 3: Curves of dev loss for CRF and MCRF.