{"id":18587619,"url":"https://github.com/sgrvinod/a-pytorch-tutorial-to-sequence-labeling","last_synced_at":"2025-04-07T12:05:50.351Z","repository":{"id":65340704,"uuid":"136120015","full_name":"sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling","owner":"sgrvinod","description":" Empower Sequence Labeling with Task-Aware Neural Language Model | a PyTorch Tutorial to Sequence Labeling ","archived":false,"fork":false,"pushed_at":"2020-06-03T03:51:41.000Z","size":6655,"stargazers_count":365,"open_issues_count":8,"forks_count":83,"subscribers_count":13,"default_branch":"master","last_synced_at":"2025-03-31T10:08:32.629Z","etag":null,"topics":["co-training","conditional-random-fields","crf","entity-extraction","entity-recognition","language-model","nlp","pos-tagger","pos-tagging","pytorch","pytorch-tutorial","sequence-labeling","sequence-tagger"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sgrvinod.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-06-05T04:32:16.000Z","updated_at":"2025-01-11T08:39:06.000Z","dependencies_parsed_at":"2023-01-18T03:45:56.681Z","dependency_job_id":null,"html_url":"https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sgrvinod%2Fa-PyTorch-Tutorial-to-Sequence-Labeling","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sgrvinod%2Fa-PyTorch-Tutorial-to-Sequence-Labeling/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sgrvinod%2Fa-PyTorch-Tutorial-to-Sequence-Labeling/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sgrvinod%2Fa-PyTorch-Tutorial-to-Sequence-Labeling/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sgrvinod","download_url":"https://codeload.github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247648976,"owners_count":20972945,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["co-training","conditional-random-fields","crf","entity-extraction","entity-recognition","language-model","nlp","pos-tagger","pos-tagging","pytorch","pytorch-tutorial","sequence-labeling","sequence-tagger"],"created_at":"2024-11-07T00:39:48.113Z","updated_at":"2025-04-07T12:05:50.327Z","avatar_url":"https://github.com/sgrvinod.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"This is a **[PyTorch](https://pytorch.org) Tutorial to Sequence Labeling**.\n\nThis is the second in [a series of tutorials](https://github.com/sgrvinod/Deep-Tutorials-for-PyTorch) I'm writing about _implementing_ cool models on your own with the amazing PyTorch library.\n\nBasic knowledge of PyTorch, recurrent neural networks is assumed.\n\nIf you're new to PyTorch, first read [Deep Learning with PyTorch: A 60 Minute Blitz](https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html) and [Learning PyTorch with Examples](https://pytorch.org/tutorials/beginner/pytorch_with_examples.html).\n\nQuestions, suggestions, or corrections can be posted as issues.\n\nI'm using `PyTorch 0.4` in `Python 3.6`.\n\n---\n\n**27 Jan 2020**: Working code for two new tutorials has been added — [Super-Resolution](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Super-Resolution) and [Machine Translation](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Machine-Translation)\n\n---\n\n# Contents\n\n[***Objective***](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling#objective)\n\n[***Concepts***](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling#concepts)\n\n[***Overview***](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling#overview)\n\n[***Implementation***](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling#implementation)\n\n[***Training***](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling#training)\n\n[***Frequently Asked Questions***](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling#faqs)\n\n# Objective\n\n**To build a model that can tag each word in a sentence with entities, parts of speech, etc.**\n\n![](./img/ill.jpg)\n\nWe will be implementing the [_Empower Sequence Labeling with Task-Aware Neural Language Model_](https://arxiv.org/abs/1709.04109) paper. This is more advanced than most sequence tagging models, but you will learn many useful concepts – and it works extremely well. The authors' original implementation can be found [here](https://github.com/LiyuanLucasLiu/LM-LSTM-CRF).\n\nThis model is special because it augments the sequence labeling task by training it _concurrently_ with language models.\n\n# Concepts\n\n* **Sequence Labeling**. duh.\n\n* **Language Models**. Language Modeling is to predict the next word or character in a sequence of words or characters. Neural language models achieve impressive results across a wide variety of NLP tasks like text generation, machine translation, image captioning, optical character recognition, and what have you.\n\n* **Character RNNs**. RNNs operating on individual characters in a text [are known](http://karpathy.github.io/2015/05/21/rnn-effectiveness/) to capture the underlying style and structure. In a sequence labeling task, they are especially useful since sub-word information can often yield important clues to an entity or tag.\n\n* **Multi-Task Learning**. Datasets available to train a model are often small. Creating annotations or handcrafted features to help your model along is not only cumbersome, but also frequently not adaptable to the diverse domains or settings in which your model may be useful. Sequence labeling, unfortunately, is a prime example. There is a way to mitigate this problem – jointly training multiple models that are joined at the hip will maximize the information available to each model, improving performance.\n\n* **Conditional Random Fields**. Discrete classifiers predict a class or label at a word. Conditional Random Fields (CRFs) can do you one better – they predict labels based on not just the word, but also the neighborhood. Which makes sense, because there _are_ patterns in a sequence of entities or labels. CRFs are widely used to model ordered information, be it for sequence labeling, gene sequencing, or even object detection and image segmentation in computer vision.\n\n* **Viterbi Decoding**. Since we're using CRFs, we're not so much predicting the right label at each word as we are predicting the right label _sequence_ for a word sequence. Viterbi Decoding is a way to do exactly this – find the most optimal tag sequence from the scores computed by a Conditional Random Field.\n\n* **Highway Networks**. Fully connected layers are a staple in any neural network to transform or extract features at different locations. Highway Networks accomplish this, but also allow information to flow unimpeded across transformations. This makes deep networks much more efficient or feasible.\n\n# Overview\n\nIn this section, I will present an overview of this model. If you're already familiar with it, you can skip straight to the [Implementation](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling#implementation) section or the commented code.\n\n### LM-LSTM-CRF\n\nThe authors refer to the model as the _Language Model - Long Short-Term Memory - Conditional Random Field_ since it involves **co-training language models with an LSTM + CRF combination**.\n\n![](./img/framework.png)\n\nThis image from the paper thoroughly represents the entire model, but don't worry if it seems too complex at this time. We'll break it down to take a closer look at the components.\n\n### Multi-Task Learning\n\n**Multi-task learning is when you simultaneously train a model on two or more tasks.**\n\nUsually we're only interested in _one_ of these tasks – in this case, the sequence labeling.\n\nBut when layers in a neural network contribute towards performing multiple functions, they learn more than they would have if they had trained only on the primary task. This is because the information extracted at each layer is expanded to accomodate all tasks. When there is more information to work with, **performance on the primary task is enhanced**.\n\nEnriching existing features in this manner removes the need for using handcrafted features for sequence labeling.\n\nThe **total loss** during multi-task learning is usually a linear combination of the losses on the individual tasks. The parameters of the combination can be fixed or learned as updateable weights.\n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"./img/loss.png\"\u003e\n\u003c/p\u003e\n\nSince we're aggregating individual losses, you can see how upstream layers shared by multiple tasks would receive updates from all of them during backpropagation.\n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"./img/update.png\"\u003e\n\u003c/p\u003e\n\nThe authors of the paper **simply add the losses** (`β=1`), and we will do the same.\n\nLet's take a look at the tasks that make up our model.\n\n**There are _three_**.\n\n![](./img/forwchar.jpg)\n\nThis leverages sub-word information to predict the next word.\n\nWe do the same in the backward direction.\n![](./img/backchar.jpg)\n\nWe _also_ use the outputs of these two **character-RNNs** as inputs to our **word-RNN** and **Conditional Random Field (CRF)** to perform our primary task of sequence labeling.\n![](./img/word.jpg)\n\nWe're using sub-word information in our tagging task because it can be a powerful indicator of the tags, whether they're parts of speech or entities. For example, it may learn that adjectives commonly end with \"-y\" or \"-ul\", or that places  often end with \"-land\" or \"-burg\".\n\nBut our sub-word features, viz. the outputs of the Character RNNs, are also enriched with _additional_ information – the knowledge it needs to predict the next word in both forward and backward directions, because of models 1 and 2.\n\nTherefore, our sequence tagging model uses both\n- **word-level information** in the form of word embeddings.\n- **character-level information** up to and including each word in both directions, enriched with the know-how required to be able to predict the next word in both directions.\n\nThe Bidirectional LSTM/RNN encodes these features into new features at each word containing information about the word and its neighborhood, at both the word-level and the character-level. This forms the input to the Conditional Random Field.\n\n### Conditional Random Field (CRF)\n\nWithout a CRF, we would have simply used a single linear layer to transform the output of the Bidirectional LSTM into scores for each tag. These are known as **emission scores**, which are a representation of the likelihood of the word being a certain tag.\n\nA CRF calculates not only the emission scores but also the **transition scores**, which are the likelihood of a word being a certain tag _considering_ the previous word was a certain tag. Therefore the transition scores measure how likely it is to transition from one tag to another.\n\nIf there are `m` tags, transition scores are stored in a matrix of dimesions `m, m`, where the rows represent the tag of the previous word and the columns represent the tag of the current word. A value in this matrix at position `i, j` is the **likelihood of transitioning from the `i`th tag at the previous word to the `j`th tag at the current word**. Unlike emission scores, transition scores are not defined for each word in the sentence. They are global.\n\nIn our model, the CRF layer outputs the **aggregate of the emission and transition scores at each word**.\n\nFor a sentence of length `L`, emission scores would be an `L, m` tensor. Since the emission scores at each word do not depend on the tag of the previous word, we create a new dimension like `L, _, m` and broadcast (copy) the tensor along this direction to get an `L, m, m` tensor.\n\nThe transition scores are an `m, m` tensor. Since the transition scores are global and do not depend on the word, we create a new dimension like `_, m, m` and broadcast (copy) the tensor along this direction to get an `L, m, m` tensor.\n\nWe can now **add them to get the total scores which are an `L, m, m` tensor**. A value at position `k, i, j` is the _aggregate_ of the emission score of the `j`th tag at the `k`th word and the transition score of the `j`th tag at the `k`th word considering the previous word was the `i`th tag.\n\nFor our example sentence `dunston checks in \u003cend\u003e`, if we assume there are 5 tags in total, the total scores would look like this –\n\n![](./img/tagscores0.jpg)\n\nBut wait a minute, why are there `\u003cstart\u003e` end `\u003cend\u003e` tags? While we're at it, why are we using an `\u003cend\u003e` token?\n\n### About `\u003cstart\u003e` and `\u003cend\u003e` tags, `\u003cstart\u003e` and `\u003cend\u003e` tokens\n\nSince we're modeling the likelihood of transitioning between tags, we also include a `\u003cstart\u003e` tag and an `\u003cend\u003e` tag in our tag-set.\n\nThe transition score of a certain tag given that the previous tag was a `\u003cstart\u003e` tag represents the **likelihood of this tag being the _first_ tag in a sentence**. For example, sentences usually start with articles (a, an, the) or nouns or pronouns.\n\nThe transition score of the `\u003cend\u003e` tag considering a certain previous tag indicates the **likelihood of this previous tag being the _last_ tag in a sentence**.\n\nWe will use an `\u003cend\u003e` token in all sentences and not a `\u003cstart\u003e` token because the total CRF scores at each word are defined with respect to the _previous_ word's tag, which would make no sense at a `\u003cstart\u003e` token.\n\nThe correct tag of the `\u003cend\u003e` token is always the `\u003cend\u003e` tag. The \"previous tag\" of the first word is always the `\u003cstart\u003e` tag.\n\nTo illustrate, if our example sentence `dunston checks in \u003cend\u003e` had the tags `tag_2, tag_3, tag_3, \u003cend\u003e`, the values in red indicate the scores of these tags.\n\n![](./img/tagscores.jpg)\n\n### Highway Networks\n\nWe generally use activated linear layers to transform and process outputs of an RNN/LSTM.\n\nIf you're familiar with residual connections, we can add the input before the transformation to the transformed output, creating a path for data-flow around the transformation.\n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"./img/nothighway.png\"\u003e\n\u003c/p\u003e\n\nThis path is a shortcut for the flow of gradients during backpropagation, and aids in the convergence of deep networks.\n\nA **Highway Network** is similar to a residual network, but we use a **sigmoid-activated gate to determine the ratio in which the input and transformed output is combined**.\n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"./img/highway.png\"\u003e\n\u003c/p\u003e\n\nSince the character-RNNs contribute towards multiple tasks, **Highway Networks are used for extracting task-specific information** from its outputs.\n\nTherefore, we will use Highway Networks at **three locations** in our combined model –\n\n- to transform the output of the forward character-RNN to predict the next word.\n- to transform the output of the backward character-RNN to predict the next word (in the backward direction).\n- to transform the concatenated output of the forward and backward character-RNNs for use in the word-level RNN along with the word embedding.\n\nIn a naive co-training setting, where we use the outputs of the character-RNNs directly for multiple tasks, i.e. without transformation, the discordance between the nature of the tasks could hurt performance.\n\n### Putting it all together\n\nIt might be clear by now what our combined network looks like.\n\n![](./img/model.jpg)\n\n### Other configurations\n\nProgressively removing parts of our network results in progressively simpler networks that are used widely for sequence labeling.\n\n![](./img/configs.jpg)\n\n#### (a) a Bi-LSTM + CRF sequence tagger that leverages sub-word information.\n\nThere is no multi-task learning.\n\nUsing character-level information without co-training still improves performance.\n\n#### (b) a Bi-LSTM + CRF sequence tagger.\n\nThere is no multi-task learning or character-level processing.\n\nThis configuration is used quite commonly in the industry and works well.\n\n#### (c) a Bi-LSTM sequence tagger.\n\nThere is no multi-task learning, character-level processing, or CRFing. Note that a linear or Highway layer would replace the latter.\n\nThis could work reasonably well, but a Conditional Random Field provides a sizeable performance boost.\n\n### Viterbi Loss\n\nRemember, we're not using a linear layer that computes only the emission scores. Cross Entropy is not a suitable loss metric.\n\nInstead we will use the **Viterbi Loss** which, like Cross Entropy, is a \"negative log likelihood\". But here we will measure the likelihood of the gold (true) tag sequence, instead of the likelihood of the true tag at each word in the sequence. To find the likelihood, we consider the softmax over the scores of all tag sequences.\n\nThe score of a tag sequence `t` is defined as the sum of the scores of the individual tags.\n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"./img/vscore.png\"\u003e\n\u003c/p\u003e\n\nFor example, consider the CRF scores we looked at earlier –\n\n![](./img/tagscores.jpg)\n\nThe score of the tag sequence `tag_2, tag_3, tag_3, \u003cend\u003e tag` is the sum of the values in red, `4.85 + 6.79 + 3.85 + 3.52 = 19.01`.\n\n**The Viterbi Loss is then defined as**\n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"./img/vloss1.png\"\u003e\n\u003c/p\u003e\n\nwhere `t_G` is the gold tag sequence and `T` represents the space of all possible tag sequences.\n\nThis simplifies to –\n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"./img/vloss3.png\"\u003e\n\u003c/p\u003e\n\nTherefore, the Viterbi Loss is the **difference between the log-sum-exp of the scores of all possible tag sequences and the score of the gold tag sequence**, i.e. `log-sum-exp(all scores) - gold score`.\n\n### Viterbi Decoding\n\n**Viterbi Decoding** is a way to construct the most optimal tag sequence, considering not only the likelihood of a tag at a certain word (emission scores), but also the likelihood of a tag considering the previous and next tags (transition scores).\n\nOnce you generate CRF scores in a `L, m, m` matrix for a sequence of length `L`, we start decoding.\n\nViterbi Decoding is best understood with an example. Consider again –\n\n![](./img/tagscores0.jpg)\n\nFor the first word in the sequence, the `previous_tag` can only be `\u003cstart\u003e`. Therefore only consider that one row.\n\nThese are also the cumulative scores for each `current_tag` at the first word.\n\n![](./img/dunston.jpg)\n\nWe will also keep track of the `previous_tag` that corresponds to each score. These are known as **backpointers**. At the first word, they are obviously all `\u003cstart\u003e` tags.\n\nAt the second word, **add the previous cumulative scores to the CRF scores of this word to generate new cumulative scores**.\n\nNote that the first word's `current_tag`s are the second word's `previous_tag`s. Therefore, broadcast the first word's cumulative score along the `current_tag` dimension.\n\n![](./img/checks1.jpg)\n\nFor each `current_tag`, consider only the maximum of the scores from all `previous_tag`s.\n\nStore backpointers, i.e. the previous tags that correspond to these maximum scores.\n\n![](./img/checks2.jpg)\n\nRepeat this process at the third word.\n\n![](./img/in1.jpg)\n![](./img/in2.jpg)\n\n...and the last word, which is the `\u003cend\u003e` token.\n\nHere, the only difference is you _already know_ the correct tag. You need the maximum score and backpointer **only for the `\u003cend\u003e` tag**.\n\n![](./img/end1.jpg)\n![](./img/end2.jpg)\n\nNow that you accumulated CRF scores across the entire sequence, **you trace _backwards_ to reveal the tag sequence with the highest possible score**.\n\n![](./img/backtrace.jpg)\n\nWe find that the most optimal tag sequence for `dunston checks in \u003cend\u003e` is `tag_2 tag_3 tag_3 \u003cend\u003e`.\n\n# Implementation\n\nThe sections below briefly describe the implementation.\n\nThey are meant to provide some context, but **details are best understood directly from the code**, which is quite heavily commented.\n\n### Dataset\n\nI use the CoNLL 2003 NER dataset to compare my results with the paper.\n\nHere's a snippet –\n\n```\n-DOCSTART- -X- O O\n\nEU NNP I-NP I-ORG\nrejects VBZ I-VP O\nGerman JJ I-NP I-MISC\ncall NN I-NP O\nto TO I-VP O\nboycott VB I-VP O\nBritish JJ I-NP I-MISC\nlamb NN I-NP O\n. . O O\n```\n\nThis dataset is not meant to be publicly distributed, although you may find it somewhere online.\n\nThere are several public datasets online that you can use to train the model. These may not all be 100% human annotated, but they are sufficient.\n\nFor NER tagging, you can use the [Groningen Meaning Bank](http://gmb.let.rug.nl/data.php).\n\nFor POS tagging, NLTK has a small dataset available you can access with `nltk.corpus.treebank.tagged_sents()`.\n\nYou would either have to convert it to the CoNLL 2003 NER data format, or modify the code referenced in the [Data Pipeline](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling#data-pipeline) section.\n\n### Inputs to model\n\nWe will need eight inputs.\n\n#### Words\n\nThese are the word sequences that must be tagged.\n\n`dunston checks in`\n\nAs discussed earlier, we will not use `\u003cstart\u003e` tokens but we *will* need to use `\u003cend\u003e` tokens.\n\n`dunston, checks, in, \u003cend\u003e`\n\nSince we pass the sentences around as fixed size Tensors, we need to pad sentences (which are naturally of varying length) to the same length with `\u003cpad\u003e` tokens.\n\n`dunston, checks, in, \u003cend\u003e, \u003cpad\u003e, \u003cpad\u003e, \u003cpad\u003e, ...`\n\nFurthermore, we create a `word_map` which is an index mapping for each word in the corpus, including the `\u003cend\u003e`, and `\u003cpad\u003e` tokens. PyTorch, like other libraries, needs words encoded as indices to look up embeddings for them, or to identify their place in the predicted word scores.\n\n`4381, 448, 185, 4669, 0, 0, 0, ...`\n\nTherefore, **word sequences fed to the model must be an `Int` tensor of dimensions `N, L_w`** where `N` is the batch_size and `L_w` is the padded length of the word sequences (usually the length of the longest word sequence).\n\n#### Characters (Forward)\n\nThese are the character sequences in the forward direction.\n\n`'d', 'u', 'n', 's', 't', 'o', 'n', ' ', 'c', 'h', 'e', 'c', 'k', 's', ' ', 'i', 'n', ' '`\n\nWe need `\u003cend\u003e` tokens in the character sequences to match the `\u003cend\u003e` token in the word sequences. Since we're going to use character-level features at each word in the word sequence, we need character-level features at `\u003cend\u003e` in the word sequence.\n\n`'d', 'u', 'n', 's', 't', 'o', 'n', ' ', 'c', 'h', 'e', 'c', 'k', 's', ' ', 'i', 'n', ' ', \u003cend\u003e`\n\nWe also need to pad them.\n\n`'d', 'u', 'n', 's', 't', 'o', 'n', ' ', 'c', 'h', 'e', 'c', 'k', 's', ' ', 'i', 'n', ' ', \u003cend\u003e, \u003cpad\u003e, \u003cpad\u003e, \u003cpad\u003e, ...`\n\nAnd encode them with a `char_map`.\n\n`29, 2, 12, 8, 7, 14, 12, 3, 6, 18, 1, 6, 21, 8, 3, 17, 12, 3, 60, 0, 0, 0, ...`\n\nTherefore, **forward character sequences fed to the model must be an `Int` tensor of dimensions `N, L_c`**, where `L_c` is the padded length of the character sequences (usually the length of the longest character sequence).\n\n#### Characters (Backward)\n\nThis would be processed the same as the forward sequence, but backward. (The `\u003cend\u003e` tokens would still be at the end, naturally.)\n\n`'n', 'i', ' ', 's', 'k', 'c', 'e', 'h', 'c', ' ', 'n', 'o', 't', 's', 'n', 'u', 'd', ' ', \u003cend\u003e, \u003cpad\u003e, \u003cpad\u003e, \u003cpad\u003e, ...`\n\n`12, 17, 3, 8, 21, 6, 1, 18, 6, 3, 12, 14, 7, 8, 12, 2, 29, 3, 60, 0, 0, 0, ...`\n\nTherefore, **backward character sequences fed to the model must be an `Int` tensor of dimensions `N, L_c`**.\n\n#### Character Markers (Forward)\n\nThese markers are **positions in the character sequences** where we extract features to –\n- generate the next word in the language models, and\n- use as character-level features in the word-level RNN in the sequence labeler\n\nWe will extract features at the end of every space `' '` in the character sequence, and at the `\u003cend\u003e` token.\n\nFor the forward character sequence, we extract at –\n\n`7, 14, 17, 18`\n\nThese are points after `dunston`, `checks`, `in`, `\u003cend\u003e` respectively. Thus, we have **a marker for each word in the word sequence**, which makes sense. (In the language models, however, since we're predicting the _next_ word, we won't predict at the marker which corresponds to `\u003cend\u003e`.)\n\nWe pad these with `0`s. It doesn't matter what we pad with as long as they're valid indices. (We will extract features at the pads, but we will not use them.)\n\n`7, 14, 17, 18, 0, 0, 0, ...`\n\nThey are padded to the padded length of the word sequences, `L_w`.\n\nTherefore, **forward character markers fed to the model must be an `Int` tensor of dimensions `N, L_w`**.\n\n#### Character Markers (Backward)\n\nFor the markers in the backward character sequences, we similarly find the positions of every space `' '` and the `\u003cend\u003e` token.\n\nWe also ensure that these **positions are in the same _word_ order as in the forward markers**. This alignment makes it easier to concatenate features extracted from the forward and backward character sequences, and also prevents having to re-order the targets in the language models.\n\n`17, 9, 2, 18`\n\nThese are points after `notsnud`, `skcehc`, `ni`, `\u003cend\u003e` respectively.\n\nWe pad with `0`s.\n\n`17, 9, 2, 18, 0, 0, 0, ...`\n\nTherefore, **backward character markers fed to the model must be an `Int` tensor of dimensions `N, L_w`**.\n\n#### Tags\n\nLet's assume the correct tags for `dunston, checks, in, \u003cend\u003e` are –\n\n`tag_2, tag_3, tag_3, \u003cend\u003e`\n\nWe have a `tag_map` (containing the tags `\u003cstart\u003e`, `tag_1`, `tag_2`, `tag_3`,  `\u003cend\u003e`).\n\nNormally, we would just encode them directly (before padding) –\n\n`2, 3, 3, 5`\n\nThese are `1D` encodings, i.e., tag positions in a `1D` tag map.\n\nBut the **outputs of the CRF layer are `2D` `m, m` tensors** at each word. We would need to encode tag positions in these `2D` outputs.\n\n![](./img/tagscores.jpg)\n\nThe correct tag positions are marked in red.\n\n`(0, 2), (2, 3), (3, 3), (3, 4)`\n\nIf we unroll these scores into a `1D` `m*m` tensor, then the tag positions in the unrolled tensor would be\n\n```python\ntag_map[previous_tag] * len(tag_map) + tag_map[current_tag]\n```\n\nTherefore, we encode `tag_2, tag_3, tag_3, \u003cend\u003e` as\n\n`2, 13, 18, 19`\n\nNote that you can retrieve the original `tag_map` indices by taking the modulus\n\n```python\nt % len(tag_map)\n```\n\nThey will be padded to the padded length of the word sequences, `L_w`.\n\nTherefore, **tags fed to the model must be an `Int` tensor of dimensions `N, L_w`**.\n\n#### Word Lengths\n\nThese are the actual lengths of the word sequences including the `\u003cend\u003e` tokens. Since PyTorch supports dynamic graphs, we will compute only over these lengths and not over the `\u003cpads\u003e`.\n\nTherefore, **word lengths fed to the model must be an `Int` tensor of dimensions `N`**.\n\n#### Character Lengths\n\nThese are the actual lengths of the character sequences including the `\u003cend\u003e` tokens. Since PyTorch supports  dynamic graphs, we will compute only over these lengths and not over the `\u003cpads\u003e`.\n\nTherefore, **character lengths fed to the model must be an `Int` tensor of dimensions `N`**.\n\n### Data Pipeline\n\nSee `read_words_tags()` in [`utils.py`](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling/blob/master/utils.py).\n\nThis reads the input files in the CoNLL 2003 format, and extracts the word and tag sequences.\n\nSee `create_maps()` in [`utils.py`](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling/blob/master/utils.py).\n\nHere, we create encoding maps for words, characters, and tags. We bin rare words and characters as `\u003cunk\u003e`s (unknowns).\n\nSee `create_input_tensors()` in [`utils.py`](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling/blob/master/utils.py).\n\nWe generate the eight inputs detailed in the [Inputs to Model](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling#inputs-to-model) section.\n\nSee `load_embeddings()` in [`utils.py`](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling/blob/master/utils.py).\n\nWe load pre-trained embeddings, with the option to expand the `word_map` to include out-of-corpus words present in the embedding vocabulary. Note that this may also include rare in-corpus words that were binned as `\u003cunk\u003e`s earlier.\n\nSee `WCDataset` in [`datasets.py`](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling/blob/master/datasets.py).\n\nThis is a subclass of PyTorch [`Dataset`](https://pytorch.org/docs/master/data.html#torch.utils.data.Dataset). It needs a `__len__` method defined, which returns the size of the dataset, and a `__getitem__` method which returns the `i`th set of the eight inputs to the model.\n\nThe `Dataset` will be used by a PyTorch [`DataLoader`](https://pytorch.org/docs/master/data.html#torch.utils.data.DataLoader) in `train.py` to create and feed batches of data to the model for training or validation.\n\n### Highway Networks\n\nSee `Highway` in [`models.py`](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling/blob/master/models.py).\n\nA **transform** is a ReLU-activated linear transformation of the input. A **gate** is a sigmoid-activated linear transformation of the input. Note that **both transformations must be the same size as the input**, to allow for adding the input in a residual connection.\n\nThe `num_layers` attribute specifices how many transform-gate-residual-connection operations we perform in series. Usually just one is sufficient.\n\nWe store the requisite number of transform and gate layers in separate `ModuleList()`s, and use a `for` loop to perform successive operations.  \n\n### Language Models\n\nSee `LM_LSTM_CRF` in [`models.py`](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling/blob/master/models.py).\n\nAt the very outset, we **sort the forward and backward character sequences by decreasing lengths**. This is required to use [`pack_padded_sequence()`](https://pytorch.org/docs/master/nn.html#torch.nn.utils.rnn.pack_padded_sequence) in order for the LSTM to compute over only the valid timesteps, i.e. the true length of the sequences.\n\nRemember to also sort all other tensors in the same order.\n\nSee [`dynamic_rnn.py`](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling/blob/master/dynamic_rnn.py) for an illustration of how `pack_padded_sequence()` can be used to take advantage of PyTorch's dynamic graphing and batching capabilities so that we don't process the pads. It flattens the sorted sequences by timestep while ignoring the pads, and the **LSTM computes over only the effective batch size `N_t` at each timestep**.\n\n![](./img/sorted.jpg)\n\nThe **sorting allows the top `N_t` at any timestep to align with the outputs from the previous step**. At the third timestep, for example, we process only the top 5 images, using the top 5 outputs from the previous step. Except for the sorting, all of this is handled internally by PyTorch, but it's still very useful to understand what `pack_padded_sequence()` does so we can use it in other scenarios to achieve similar ends. (See the related question about handling variable length sequences in the [FAQs](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling#faqs) section.)\n\nUpon sorting, we **apply the forward and backward LSTMs on the forward and backward `packed_sequences`** respectively. We use [`pad_packed_sequence()`](https://pytorch.org/docs/master/nn.html#torch.nn.utils.rnn.pad_packed_sequence) to unflatten and re-pad the outputs.\n\nWe **extract only the outputs at the forward and backward character markers** with [`gather`](https://pytorch.org/docs/master/torch.html#torch.gather). This function is very useful for extracting only certain indices from a tensor that are specified in a separate tensor.\n\nThese **extracted outputs are processed by the forward and backward Highway layers** before applying a **linear layer to compute scores over the vocabulary** for predicting the next word at each marker. We do this only during training, since it makes no sense to perform language modeling for multi-task learning during validation or inference. The `training` attribute of any model is set with `model.train()` or `model.eval()` in `train.py`. (Note that this is primarily used to enable or disable dropout and batch-norm layers in a PyTorch model during training and inference respectively.)\n\n### Sequence Labeling Model\n\nSee `LM_LSTM_CRF` in [`models.py`](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling/blob/master/models.py) (continued).\n\nWe also **sort the word sequences by decreasing lengths**, because there may not always be a correlation between the lengths of the word sequences and the character sequences.\n\nRemember to also sort all other tensors in the same order.\n\nWe **concatenate the forward and backward character LSTM outputs at the markers, and run it through the third Highway layer**. This will extract the sub-word information at each word which we will use for sequence labeling.\n\nWe **concatenate this result with the word embeddings, and compute BLSTM outputs** over the `packed_sequence`.\n\nUpon re-padding with `pad_packed_sequence()`, we have the features we need to feed to the CRF layer.\n\n### Conditional Random Field (CRF)\n\nSee `CRF` in [`models.py`](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling/blob/master/models.py).\n\nYou may find this layer is surprisingly straightforward considering the value it adds to our model.\n\nA linear layer is used to transform the outputs from the BLSTM to scores for each tag, which are the **emission scores**.\n\nA single tensor is used to hold the **transition scores**. This tensor is a [`Parameter`](https://pytorch.org/docs/master/nn.html#torch.nn.Parameter) of the model, which means it is updateable during backpropagation, just like the weights of the other layers.\n\nTo find the CRF scores, **compute the emission scores at each word and add it to the transition scores**, after broadcasting both as described in the [CRF Overview](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling#conditional-random-field-crf).\n\n### Viterbi Loss\n\nSee `ViterbiLoss` in [`models.py`](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling/blob/master/models.py).\n\nWe established in the [Viterbi Loss Overview](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling#viterbi-loss) that we want to minimize the **difference between the log-sum-exp of the scores of all possible valid tag sequences and the score of the gold tag sequence**, i.e. `log-sum-exp(all scores) - gold score`.\n\nWe sum the CRF scores of each true tag as described earlier to calculate the **gold score**.\n\nRemember how we encoded tag sequences with their positions in the unrolled CRF scores? We extract the scores at these positions with `gather()` and eliminate the pads with `pack_padded_sequences()` before summing.\n\nFinding the **log-sum-exp of the scores of all possible sequences** is slightly trickier. We use a `for` loop to iterate over the timesteps. At each timestep, we **accumulate scores for each `current_tag`** by –\n\n- **adding the CRF scores at this timestep to the accumulated scores from the previous timestep** to find the accumulated score for each `current_tag` for each `previous_tag`. We do this at only the effective batch size, i.e. for sequences that haven't completed yet. (Our sequences are still sorted by decreasing word lengths, from the `LM-LSTM-CRF` model.)\n- **for each `current_tag`, compute the log-sum-exp over the `previous_tag`s** to find the new accumulated scores at each `current_tag`.\n\nAfter computing over the variable lengths of all sequences, we are left with a tensor of dimensions `N, m`, where `m` is the number of (current) tags. These are the log-sum-exp accumulated scores over all possible sequences ending in each of the `m` tags. However, since valid sequences can only end with the `\u003cend\u003e` tag, **sum over only the `\u003cend\u003e` column to find the log-sum-exp of the scores of all possible valid sequences**.\n\nWe find the difference, `log-sum-exp(all scores) - gold score`.\n\n### Viterbi Decoding\n\nSee `ViterbiDecoder` in [`inference.py`](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling/blob/master/inference.py).\n\nThis implements the process described in the [Viterbi Decoding Overview](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling#viterbi-decoding).\n\nWe accumulate scores in a `for` loop in a manner similar to what we did in `ViterbiLoss`, except here we **find the maximum of the `previous_tag` scores for each `current_tag`**, instead of computing the log-sum-exp. We also **keep track of the `previous_tag` that corresponds to this maximum score** in a backpointer tensor.\n\nWe **pad the backpointer tensor with `\u003cend\u003e` tags** because this allows us to trace backwards over the pads, eventually arriving at the _actual_ `\u003cend\u003e` tag, whereupon the _actual_ **backtracing** begins.\n\n# Training\n\nSee [`train.py`](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling/blob/master/train.py).\n\nThe parameters for the model (and training it) are at the beginning of the file, so you can easily check or modify them should you wish to.\n\nTo **train your model from scratch**, simply run this file –\n\n`python train.py`\n\nTo **resume training at a checkpoint**, point to the corresponding file with the `checkpoint` parameter at the beginning of the code.\n\nNote that we perform validation at the end of every training epoch.\n\n### Trimming Batch Inputs\n\nYou will notice we **trim the inputs at each batch to the maximum sequence lengths in that batch**. This is so we don't have more pads in each batch that we actually need.\n\nBut why? Although the RNNs in our model don't compute over the pads, **the linear layers still do**. It's pretty straightward to change this – see the related question about handling variable length sequences in the [FAQs](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling#faqs) section.\n\nFor this tutorial, I figured a little extra computation over some pads was worth the straightforwardness of not having to perform a slew of operations – Highway, CRF, other linear layers, concatenations – on a `packed_sequence`.\n\n### Loss\n\nIn the multi-task scenario, we have chosen to sum the Cross Entropy losses from the two language modelling tasks and the Viterbi Loss from the sequence labeling task.  \n\nEven though we are **minimizing the sum of these losses**, we are actually only interested in minimizing the Viterbi Loss _by virtue of minimizing the sum of these losses_. It is the Viterbi Loss which reflects performance on the primary task.\n\nWe use `pack_padded_sequence()` to eliminate pads wherever necessary.\n\n### F1 Score\n\nLike in the paper, we use the **macro-averaged F1 score as the criterion for early-stopping**. Naturally, computing the F1 score requires Viterbi Decoding the CRF scores to generate our optimal tag sequences.\n\nWe use `pack_padded_sequence()` to eliminate pads wherever necessary.\n\n### Remarks\n\nI have followed the parameters in the authors' implementation as closely as possible.\n\nI used a batch size of `10` sentences. I employed Stochastic Gradient Descent with momentum. The learning rate was decayed every epoch. I used 100D [GloVe](https://nlp.stanford.edu/projects/glove/) pretrained embeddings without fine-tuning.\n\nIt took about 80s to train one epoch on a Titan X (Pascal).\n\nThe F1 score on the validation set hit `91%` around epoch 50, and peaked at `91.6%` on epoch 171. I ran it for a total of 200 epochs. This is pretty close to the results in the paper.\n\n### Model Checkpoint\n\nYou can download this pretrained model [here](https://drive.google.com/open?id=1P-w-s6QbsixcGnm3UjPMkgGpuz684kiY).\n\n# FAQs\n\n__How do we decide if we need `\u003cstart\u003e` and `\u003cend\u003e` tokens for a model that uses sequences?__\n\nIf this seems confusing at first, it will easily resolve itself when you think about the requirements of the model you are planning to train.\n\nFor sequence labeling with a CRF, you need the `\u003cend\u003e` token (_or_ the `\u003cstart\u003e` token; see next question) because of how the CRF scores are structured.\n\nIn my other tutorial on image captioning, I used _both_ `\u003cstart\u003e` and `\u003cend\u003e` tokens. The model needed to start decoding _somewhere_, and learn to recognize _when_ to stop decoding during inference.\n\nIf you're performing text classification, you would need neither.\n\n---\n\n__Can we have the CRF generate `current_word -\u003e next_word` scores instead of `previous_word -\u003e current_word` scores?__\n\nYes. In this case you would broadcast the emission scores like `L, m, _`, and you would have a `\u003cstart\u003e` token in every sentence instead of an `\u003cend\u003e` token. The correct tag of the `\u003cstart\u003e` token would always be the `\u003cstart\u003e` tag. The \"next tag\" of the last word would always be the `\u003cend\u003e` tag.\n\nI think the `previous word -\u003e current word` convention is slightly better because there are language models in the mix. It fits in quite nicely to be able to predict the `\u003cend\u003e` token at the last real word, and therefore learn to recognize when a sentence is complete.\n\n---\n\n__Why are we using different vocabularies for the sequence tagger's inputs and language models' outputs?__\n\nThe language models will learn to predict only those words it has seen during training. It's really unnecessary, and a huge waste of computation and memory, to use a linear-softmax layer with the extra ~400,000 out-of-corpus words from the embedding file it will never learn to predict.\n\nBut we _can_ add these words to the input layer even if the model never sees them during training. This is because we're using pre-trained embeddings at the input. It doesn't _need_ to see them because the meanings of words are encoded in these vectors. If it's encountered a `chimpanzee` before, it very likely knows what to do with an `orangutan`.\n\n---\n\n__Is it a good idea to fine-tune the pre-trained word embeddings we use in this model?__\n\nI refrain from fine-tuning because most of the input vocabulary is not in-corpus. Most embeddings will remain the same while a few are fine-tuned. If fine-tuning changes these embeddings sufficiently, the model may not work well with the words that weren't fine-tuned. In the real world, we're bound to encounter many words that weren't present in a newspaper corpus from 2003.\n\n---\n\n__What are some ways we can construct dynamic graphs in PyTorch to compute over only the true lengths of sequences?__\n\nIf you're using an RNN, simply use [`pack_padded_sequence()`](https://pytorch.org/docs/master/nn.html#torch.nn.utils.rnn.pack_padded_sequence). PyTorch will internally compute over only the true lengths. See [`dynamic_rnn.py`](https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Sequence-Labeling/blob/master/dynamic_rnn.py) for an example.\n\nIf you want to execute an operation (like a linear transformation) only on the true timesteps, `pack_padded_sequences()` is still the way to go. This flattens the tensor by timestep while removing the pads. You can perform your operation on this flattened tensor, and then use [`pad_packed_sequence()`](https://pytorch.org/docs/master/nn.html#torch.nn.utils.rnn.pad_packed_sequence) to unflatten it and re-pad it with `0`s.\n\nSimilarly, if you want to perform an aggregation operation, like computing the loss, use `pack_padded_sequences()` to eliminate the pads.\n\nIf you want to perform timestep-wise operations, you can take a leaf out of how `pack_padded_sequences()` works, and compute only on the effective batch size at each timestep with a `for` loop to iterate over the timesteps. We did this in the `ViterbiLoss` and `ViterbiDecoder`. I also used an `LSTMCell()` in this fashion in my image captioning tutorial.\n\n---\n\n__*Dunston Checks In*? Really?__\n\nI had no memory of this movie for twenty years. I was trying to think of a short sentence that would be easier to visualize in this tutorial and it just popped into my mind riding a wave of 90s nostalgia.\n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"./img/dci.jpg\"\u003e\n\u003c/p\u003e\n\nI wish I hadn't googled it though. Damn, the critics were harsh, weren't they? This gem was overwhelmingly and universally panned. I'm not sure I'd disagree if I watched it now, but that just goes to show the world is so much more fun when you're a kid.\n\nDidn't have to worry about LM-LSTM-CRFs or nuthin...\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsgrvinod%2Fa-pytorch-tutorial-to-sequence-labeling","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsgrvinod%2Fa-pytorch-tutorial-to-sequence-labeling","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsgrvinod%2Fa-pytorch-tutorial-to-sequence-labeling/lists"}