<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yilong Qin on Medium]]></title>
        <description><![CDATA[Stories by Yilong Qin on Medium]]></description>
        <link>https://medium.com/@louixp?source=rss-c6874aa1d309------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Kr62rku-FV5SL6gB8wVnew.jpeg</url>
            <title>Stories by Yilong Qin on Medium</title>
            <link>https://medium.com/@louixp?source=rss-c6874aa1d309------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 02:51:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@louixp/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Pytorch ELMo, trained from scratch]]></title>
            <link>https://medium.com/data-science/pytorch-elmo-844d2391a0b2?source=rss-c6874aa1d309------2</link>
            <guid isPermaLink="false">https://medium.com/p/844d2391a0b2</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Yilong Qin]]></dc:creator>
            <pubDate>Wed, 17 Feb 2021 08:23:58 GMT</pubDate>
            <atom:updated>2021-02-24T13:41:08.891Z</atom:updated>
            <content:encoded><![CDATA[<h3>PyTorch ELMo, trained from scratch</h3><h4>Learn powerful contextual word embeddings on your own corpus using AllenNLP</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hVGFBoMIosG9dpAj" /><figcaption>Photo by <a href="https://unsplash.com/@renolaithienne?utm_source=medium&amp;utm_medium=referral">Reno Laithienne</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>E</strong>mbeddings from <strong>L</strong>anguage <strong>Mo</strong>del (ELMo) is a powerful contextual embedding method that finds application in a wide range of Natural Language Processing tasks. ELMo, along with others, started the trend of pretraining contextual word embeddings in NLP. The technique remains simple and intuitive, allowing itself to be easily added to existing models.</p><p>In this article, we will discuss <strong>how to train ELMo embeddings from scratch with our own text corpus</strong> and explain <strong>how it works under the hood</strong>. We will use <a href="https://allennlp.org/">AllenNLP</a>, a PyTorch-based NLP framework that provides many state-of-the-art models out of the box. If you are only interested in using pre-trained ELMo embeddings, feel free to hop to the last section — <a href="#7e4d"><em>Using ELMo in downstream tasks</em></a>.</p><h3>Table of contents</h3><ol><li><a href="#b484">Training ELMo from scratch</a></li><li><a href="#d881">Understanding the implementation</a></li><li><a href="#7e4d">Using ELMo in downstream tasks</a></li></ol><h3>Training ELMo from scratch</h3><p>I know you can’t wait so let’s dive right into the training. In the next section, we will go through the training step-by-step to understand how ELMo is implemented in AllenNLP.</p><h4>Dependencies</h4><p>First, let’s install <a href="https://github.com/allenai/allennlp-models">allennlp-models</a>. This package includes all the fancy models implemented in the AllenNLP framework. Installing this package should also find you the correct version of PyTorch and AllenNLP needed.</p><pre>pip install allennlp-models=v2.0.1</pre><h4>Corpus</h4><p>Next, we get our corpus data for training. For demonstration purposes, we use the original corpus — <a href="http://www.statmt.org/lm-benchmark/">1 Billion Word Language Model Benchmark</a>. You can also use any corpus of your choice.</p><pre>wget <a href="http://www.statmt.org/lm-benchmark/1-billion-word-language-modeling-benchmark-r13output.tar.gz">http://www.statmt.org/lm-benchmark/1-billion-word-language-modeling-benchmark-r13output.tar.gz</a></pre><pre>tar -xzf <a href="http://www.statmt.org/lm-benchmark/1-billion-word-language-modeling-benchmark-r13output.tar.gz">1-billion-word-language-modeling-benchmark-r13output.tar.gz</a></pre><pre>export BIDIRECTIONAL_LM_DATA_PATH=$PWD&#39;/1-billion-word-language-modeling-benchmark-r13output&#39;</pre><pre>export BIDIRECTIONAL_LM_TRAIN_PATH=$BIDIRECTIONAL_LM_DATA_PATH&#39;/training-monolingual.tokenized.shuffled/*&#39;</pre><h4>Vocabulary</h4><p>For indexing and performance purposes, AllenNLP requires preprocessed Vocabulary, which reads from a directory with tokens.txt inside, which includes all the unique tokens on each line. (The inner working of Vocabulary is actually a bit more complicated, but we assume this for simplicity.)</p><p>Here, we download the preprocessed vocabulary. If you are using your own corpus, take a look at tokens.txt to understand its format. Pay special attention to the first three tokens — &lt;/S&gt;, &lt;S&gt;, @@UNKNOWN@@. They are critical for ELMo to know the boundaries of sentences and words outside of vocabulary.</p><pre>pip install awscli </pre><pre>mkdir vocabulary <br>export BIDIRECTIONAL_LM_VOCAB_PATH=$PWD&#39;/vocabulary&#39; <br>cd $BIDIRECTIONAL_LM_VOCAB_PATH </pre><pre>aws --no-sign-request s3 cp s3://allennlp/models/elmo/vocab-2016-09-10.txt . </pre><pre>cat vocab-2016-09-10.txt | sed &#39;s/&lt;UNK&gt;/@@UNKNOWN@@/&#39; &gt; tokens.txt<br>rm vocab-2016-09-10.txt </pre><pre>echo &#39;*labels\n*tags&#39; &gt; non_padded_namespaces.txt</pre><h4>Training</h4><p>We have arrived at our last step of training ELMo from scratch. In this step, we use a precomposed configuration file to kick off the training.</p><pre>wget <a href="https://raw.githubusercontent.com/allenai/allennlp-models/main/training_config/lm/bidirectional_language_model.jsonnet">https://raw.githubusercontent.com/allenai/allennlp-models/main/training_config/lm/bidirectional_language_model.jsonnet</a></pre><pre>allennlp train bidirectional_language_model.jsonnet --serialization-dir output_dir/</pre><h4>Not satisfied?</h4><p>The above steps borrowed heavily from <a href="https://docs.allennlp.org/v1.0.0rc5/tutorials/how_to/elmo/">the official AllenNLP HowTo</a>. It might seem quite unclear if you want to tweak the underlying architecture or if you want to process your own corpus into the desired format. While offering stunning simplicity, AllenNLP sweeps a huge amount of underlying assumptions about data and architectures under its rugs.</p><p>While you are waiting for the training to complete, we will take a look at how ELMo works from the perspective of the AllenNLP framework.</p><h3>Understanding the implementation</h3><p>To understand the ELMo architecture and how it is implemented, we take a closer look at bidirectional_language_model.jsonnet, which is essentially a configuration file that specifies everything at a very high level. It allows us to easily define how data gets processed (tokenized and embedded) and what the architecture looks like.</p><p>Note: within the JSON objects, we see many with the key &quot;type”. This is AllenNLP’s syntax to register custom classes. By using its <a href="https://docs.allennlp.org/main/api/common/registrable/#register">register decorator</a>, we are exposing our classes to AllenNLP, enabling us to use them in our configurations.</p><h4>DatasetReader</h4><p><em>connecting natural language to natural numbers</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UPirqwpBWnNmcwoUjfZZIA.png" /><figcaption>simple_language_modeling DatasetReader</figcaption></figure><p>The first thing we are concerned with is how data flows into the model from natural language texts that sit on our disk. The data is first tokenized by a Tokenizer, splitting the sentence at white spaces. Then, individual tokens are converted into numbers by an TokenIndexer.</p><p>In many cases, it is enough to convert the words into their respective ids in a vocabulary. Since we are using a character-level CNN to capture the subword information, we need to additionally convert the words by each character.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e110fb463fa91dac00cd7fd6870a70ec/href">https://medium.com/media/e110fb463fa91dac00cd7fd6870a70ec/href</a></iframe><p>The boundary between the model and the dataset reader lies in whether inner states are learnable. To be more concrete, the conversions from tokens to index numbers is a fixed procedure, often relying on a lookup table, therefore it belongs to the dataset reader.</p><h4>Model — embedders</h4><p><em>connecting indices to uncontextualized embeddings</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05oYW2IUu_3vedjx3mocPA.png" /><figcaption>ELMo architecture overview</figcaption></figure><p>However, converting these index numbers into an uncontextualized embedding is a learnable procedure, regardless of the technique (e.g. embedding table, character convolutions, etc.)</p><p>Notice how the token_embedders share the same keys with the token_indexers. This allows the model to connect with the dataset reader internally.</p><p>In ELMo, we are only using the character-level uncontextualized embeddings. Therefore, the indices of words are discarded by the empty embedder and the indices of characters are fed into the character_encoding embedder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*3_wsDpyNG-TylsRACF48yA.png" /><figcaption>character convolution</figcaption></figure><p>Let’s take a closer look at the character embedder. Internally, it converts the character indices into character embeddings with a learning embedding matrix. Then, for each word, it uses a CNN to learn its word embedding by convolving over the character embeddings of respective words. Doing so gives us an uncontextualized word embedding that includes subword information.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4275421a1a6231c73113c5cb9e33c49/href">https://medium.com/media/e4275421a1a6231c73113c5cb9e33c49/href</a></iframe><p>Uncontextualized word embeddings have been around for quite a while. Embeddings like <a href="https://arxiv.org/abs/1301.3781">word2vec</a>, <a href="https://nlp.stanford.edu/projects/glove/">GloVe</a> have long been the standard features in NLP. A long-standing problem with such embeddings is the loss of context. With uncontextualized embeddings, the embeddings of “bank” are the same in “river bank” and “bank account”. However, we know these words have drastically different meanings. Next, we take a look at how ELMo handles this issue with its contextualizer.</p><h4>Model — contextualizer</h4><p><em>nudging a word embedding by looking at the sentence</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*8pG54o28pbD2L0dv5THL-A.png" /><figcaption>biLSTM contextualizer</figcaption></figure><p>In the original paper, Peters et al. use a <strong>biLSTM</strong> as the contextualizer. The forward LSTM captures the context from words that come before; the backward LSTM captures the context from words that come after.</p><p>For example, to contextualize an embedding xₜ, the forward LSTM looks at x₁, …, xₜ₋₁ and creates a hidden state; the backward LSTM looks at xₜ₊₁, …, xₙ and creates another hidden state. By concatenating two hidden states, we obtain a contextualized embedding that considers both the forward context and the backward context.</p><p>In <a href="https://arxiv.org/abs/1808.08949">a later study</a>, Peters et al. found that while LSTM enjoys a higher accuracy in downstream tasks, transformer enjoys a much better inference speed with a little drop in performance. As a result, the implementation uses a transformer-based contextualizer. Intuitively, it achieves the same goal the LSTM tries to achieve — adding sentence context into each word embeddings.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f016a2bf43f6e9cee19e9fda7125e2f/href">https://medium.com/media/5f016a2bf43f6e9cee19e9fda7125e2f/href</a></iframe><p>This completes the ELMo architecture, i.e. we use the resulting contextual embeddings in our downstream tasks. One last component we have to discuss is its training objective — the bidirectional language model loss.</p><h4>Model — loss</h4><p><em>using previous words to predict the ____</em></p><blockquote>Given a sequence of N tokens, (t₁, t₂, …, tₙ), a forward language model computes the probability of the sequence by modeling the probability of token tₖ given the history (t₁, …, tₖ₋₁)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*6W-idyVazGwxvsSEdzOA8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*SKFLs52vFdw90Usci8nNDw.png" /><figcaption>forward and backward LM from <a href="https://arxiv.org/abs/1802.05365"><em>Deep contextualized word representations</em></a></figcaption></figure><p>Similarly, we can derive the backward language model. Our final bidirectional language model objective is simply the sum of two log probabilities over all sentences in our corpus.</p><p>In AllenNLP, the loss is baked into the language_model model so we only have to set the parameter bidirectional to true in our configuration. We can also use sampled softmax loss to speed things up a bit by setting num_samples.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbd2aa536a2d1f505f7c45564da966a6/href">https://medium.com/media/dbd2aa536a2d1f505f7c45564da966a6/href</a></iframe><p>Whew! That concludes the ELMo architecture and its implementation in AllenNLP. While you are reading, your model might have finished training (ok, probably not). In the next section, we will use the trained ELMo to embed some texts!</p><h3>Using ELMo in downstream tasks</h3><p>Now that you have finished training, you should be able to see the metrics for each epoch in output_dir/, where you can also find the trained model weights model.tar.gz. Alternatively, you can grab one of <a href="https://allennlp.org/elmo">the pre-trained weights</a> and integrate it into your model.</p><p>To integrate ELMo into your AllenNLP model configuration, we simply use it as another token_embedder:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bb6f1ec53189f4f5220d1af8b2932b4/href">https://medium.com/media/0bb6f1ec53189f4f5220d1af8b2932b4/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dff3b4dfc67a7a5e01062057e6518ff/href">https://medium.com/media/9dff3b4dfc67a7a5e01062057e6518ff/href</a></iframe><p>Don’t want to use a configuration file? You can also call ELMo directly in Python:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d778708e6499494704768b2a87d68601/href">https://medium.com/media/d778708e6499494704768b2a87d68601/href</a></iframe><p>You’ve made it to the end! While the syntax of AllenNLP might still be confusing to you, we do see its power in training a PyTorch-based ELMo from scratch with 0 lines of code! It also includes many amazing NLP models out of the box. If you are interested in using them, take a look at its <a href="https://guide.allennlp.org/">official guide</a> and <a href="https://docs.allennlp.org/v2.0.1/">documentation</a>.</p><h3>References</h3><ol><li><a href="https://arxiv.org/abs/1802.05365"><em>Deep contextualized word representations</em></a> first purposed the ELMo architecture. It obtained the state-of-the-art of many NLP tasks at its time while the architecture remained easily integrable into other models.</li><li><a href="https://arxiv.org/abs/1808.08949"><em>Dissecting Contextual Word Embeddings: Architecture and Representation</em></a> further studied the ELMo architecture. It tried to address how and why pre-trained contextual embeddings are so effective. In this study, a tradeoff between speed and accuracy was discovered by experiments with different contextualizers (LSTM, transformer, gated CNN). A relationship between network depth and captured information was reported, with lower layers capturing syntactic features and upper layers capturing semantic features.</li><li><a href="https://www.bioinf.jku.at/publications/older/2604.pdf"><em>Long Short-Term Memory</em></a> was first introduced to capture long-term dependencies in sequences and to address the vanishing gradient problem in vanilla RNNs. ELMo uses the way LSTM generates hidden states to contextualize word embeddings. For a more involved explanation of LSTM, check out <a href="http://colah.github.io/posts/2015-08-Understanding-LSTMs/">colah’s blog</a>.</li><li><a href="https://arxiv.org/abs/1706.03762"><em>Attention is all you need</em></a> introduced transformers into the world. It uses self-attention to capture the dependencies among tokens, making it massively parallelizable. HavardNLP dives deeply into its implementation in the <a href="https://nlp.seas.harvard.edu/2018/04/03/attention.html">annotated transformer</a>, while Jay Alammar provides a nice intuition in his <a href="http://jalammar.github.io/illustrated-transformer/">illustrated transformer</a>.</li><li><a href="https://arxiv.org/abs/1803.07640"><em>AllenNLP: A Deep Semantic Natural Language Processing Platform</em></a> brings us the AllenNLP framework. It provides many common abstractions working with text data and intelligently handles things like batching and padding. I personally find it extremely useful, with its vast collection of NLP models. For more information, check out its <a href="https://guide.allennlp.org/">official guide</a>, <a href="https://docs.allennlp.org/v2.0.1/">documentation</a>, and GitHub repo for <a href="https://github.com/allenai/allennlp-models">open source models</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=844d2391a0b2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/pytorch-elmo-844d2391a0b2">Pytorch ELMo, trained from scratch</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>