<?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 Theo Lebryk on Medium]]></title>
        <description><![CDATA[Stories by Theo Lebryk on Medium]]></description>
        <link>https://medium.com/@tlebryk?source=rss-25d46b423610------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FQIW0ZdFzdQBfDWgWzsh1Q.png</url>
            <title>Stories by Theo Lebryk on Medium</title>
            <link>https://medium.com/@tlebryk?source=rss-25d46b423610------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 11:59:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tlebryk/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[CausalLM Part 2: Finetuning a model]]></title>
            <link>https://medium.com/data-science/causallm-part-2-finetuning-a-model-3fdb4d9bd936?source=rss-25d46b423610------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fdb4d9bd936</guid>
            <category><![CDATA[translation]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[supervised-fine-tuning]]></category>
            <dc:creator><![CDATA[Theo Lebryk]]></dc:creator>
            <pubDate>Thu, 14 Mar 2024 04:34:27 GMT</pubDate>
            <atom:updated>2024-03-21T13:36:38.456Z</atom:updated>
            <content:encoded><![CDATA[<h3>CausalLM Part 2: Fine-Tuning a Model</h3><h4>3 ways to fine-tune a CausalLM model on chat data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gAEjQVVfPRoOCG37" /><figcaption>In this tutorial, we’ll be fine-tuning a CausalLM model to do simple translation. Photo by <a href="https://unsplash.com/@ventanamedia?utm_source=medium&amp;utm_medium=referral">Rob Wilson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the<a href="https://towardsdatascience.com/training-causallm-models-part-1-what-actually-is-causallm-6c3efb2490ec"> last post</a>, we talked about what CausalLM is and how Hugging Face expects data to be formatted. In this post, we’re going to walk through an abridged notebook with three ways to format the data to fine-tune a model. The first is a straightforward approach building on the intuition from the previous post simply copying input_ids into labels. The second approach utilizes masking to learn select parts of the text. The third approach uses a separate library, <a href="https://huggingface.co/docs/trl/main/en/index">TRL</a>, so that we don’t have to manually mask the data.</p><p>I’ll leave out some function definitions to keep it readable, so it’s best to reference <a href="https://github.com/tlebryk/CausalLM/blob/main/finetune_casuallm.ipynb">the full noteboo</a>k to get all the code.</p><h4>Fine-tuning with labels copied from input ids</h4><p>We’re going to be using <a href="https://huggingface.co/bigscience/bloom-560m">Bloom-560m</a>, a multilingual model which is small enough that we can fine-tune it on a standard laptop.</p><pre>model_name = &quot;bigscience/bloom-560m&quot;<br>tokenizer = AutoTokenizer.from_pretrained(<br>    model_name, trust_remote_code=True, padding_side=&quot;right&quot;<br>)  # padding side should be right for CausalLM models<br># overfit to 5 made up examples<br>str1 = &#39;\n\n### Human: How do you say &quot;dog&quot; in Spanish?\n\n### Assistant: perro&#39;<br>str2 = &#39;\n\n### Human: How do you say &quot;water&quot; in Spanish?\n\n### Assistant: agua&#39;<br>str3 = &#39;\n\n### Human: How do you say &quot;hello&quot; in Spanish?\n\n### Assistant: hola&#39;<br>str4 = &#39;\n\n### Human: How do you say &quot;tree&quot; in Spanish?\n\n### Assistant: árbol&#39;<br>str5 = &#39;\n\n### Human: How do you say &quot;mother&quot; in Spanish?\n\n### Assistant: madre&#39;<br>train_data = {<br>    &quot;text&quot;: [str1, str2, str3, str4, str5],<br>}<br>dataset_text = Dataset.from_dict(train_data)<br><br># to test if we learn how to generate an unknown word. <br>holdout_str = (<br>    &#39;\n\n### Human: How do you say &quot;day&quot; in Spanish?\n\n### Assistant:&lt;s&gt;&#39;  # día<br>)<br>device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>holdout_input = tokenizer(holdout_str, return_tensors=&quot;pt&quot;).to(device)</pre><p>Let’s start by doing some preprocessing. We’re going to add some special tokens, namely “end of sequence” (eos) and “beginning of sequence“ (bos). These special tokens can be helpful for the model to know when it’s supposed to start and stop generating text.</p><pre>INSTRUCTION_TEMPLATE_BASE = &quot;\n\n### Human:&quot;<br>RESPONSE_TEMPLATE_BASE = &quot;\n\n### Assistant:&quot;<br>def add_special_tokens(<br>    example: Dict,<br>    tokenizer: PreTrainedTokenizerBase,<br>) -&gt; Dict:<br>    # add eos_token before human text and bos_token before assistant text<br>    example[&quot;text&quot;] = (<br>        example[&quot;text&quot;]<br>        .replace(<br>            INSTRUCTION_TEMPLATE_BASE, tokenizer.eos_token + INSTRUCTION_TEMPLATE_BASE<br>        )<br>        .replace(RESPONSE_TEMPLATE_BASE, RESPONSE_TEMPLATE_BASE + tokenizer.bos_token)<br>    )<br>    if not example[&quot;text&quot;].endswith(tokenizer.eos_token):<br>        example[&quot;text&quot;] += tokenizer.eos_token<br>    # Remove leading EOS tokens<br>    while example[&quot;text&quot;].startswith(tokenizer.eos_token):<br>        example[&quot;text&quot;] = example[&quot;text&quot;][len(tokenizer.eos_token) :]<br>    return example<br><br>dataset_text = dataset_text.map(lambda x: add_special_tokens(x, tokenizer))<br>print(f&quot;{dataset_text=}&quot;)<br>print(f&quot;{dataset_text[0]=}&quot;)<br>&gt;&gt;&gt; dataset_text=Dataset({<br>    features: [&#39;text&#39;],<br>    num_rows: 5<br>})<br>&gt;&gt;&gt; dataset_text[0]={&#39;text&#39;: &#39;\n\n### Human: How do you say &quot;dog&quot; in Spanish?\n\n### Assistant:&lt;s&gt; perro&lt;/s&gt;&#39;}</pre><p>Now, we’re going to do what we learned last session: create an input with a labels key copied from input_ids.</p><pre># tokenize the text<br>dataset = dataset_text.map(<br>    lambda example: tokenizer(example[&quot;text&quot;]), batched=True, remove_columns=[&quot;text&quot;]<br>)<br># copy the input_ids to labels<br>dataset = dataset.map(lambda x: {&quot;labels&quot;: x[&quot;input_ids&quot;]}, batched=True)<br>print(f&quot;{dataset=}&quot;)<br>print(f&quot;{dataset[0][&#39;input_ids&#39;]=}&quot;)<br>print(f&quot;{dataset[0][&#39;labels&#39;]=}&quot;)<br>&gt;&gt;&gt; dataset=Dataset({<br>    features: [&#39;input_ids&#39;, &#39;attention_mask&#39;, &#39;labels&#39;],<br>    num_rows: 5<br>})<br>&gt;&gt;&gt; dataset[0][&#39;input_ids&#39;]=[603, 105311, 22256, 29, 7535, 727, 1152, 5894, 20587, 744, 5, 361, 49063, 7076, 105311, 143005, 29, 1, 82208, 2]<br>&gt;&gt;&gt; dataset[0][&#39;labels&#39;]=[603, 105311, 22256, 29, 7535, 727, 1152, 5894, 20587, 744, 5, 361, 49063, 7076, 105311, 143005, 29, 1, 82208, 2]</pre><p>To start, labels and input_ids are identical. Let’s see what happens when we train a model like that.</p><pre># training code inspired by<br>#https://mlabonne.github.io/blog/posts/Fine_Tune_Your_Own_Llama_2_Model_in_a_Colab_Notebook.html<br>model = load_model(model_name)<br>output_dir = &quot;./results&quot;<br># How many times to iterate over the entire dataset<br>num_train_epochs = 15<br># We&#39;re not aligning the sequence length (ie padding or truncating)<br># so batch training won&#39;t work for our toy example.<br>per_device_train_batch_size = 1<br><br><br>training_arguments = TrainingArguments(<br>    output_dir=output_dir,<br>    num_train_epochs=num_train_epochs,<br>    per_device_train_batch_size=per_device_train_batch_size,<br>    seed=1,<br>)<br>trainer = Trainer(<br>    model=model,<br>    train_dataset=dataset,<br>    args=training_arguments,<br>)<br>training1 = trainer.train()<br><br><br># Sample generate prediction on holdout set<br>“\n\n### Human: How do you say &quot;good&quot; in Spanish?\n\n### Assistant:”<br># the correct output is “bueno&lt;/s&gt;”<br><br><br>sample_generate(model, tokenizer, holdout_inputs, max_new_tokens=5)<br>&gt;&gt;&gt; ‘&lt;/s&gt;’</pre><p>After 15 epochs, we’re still kind of confused. We output ‘&lt;/s&gt;’ which is close but we really want to output “bueno&lt;/s&gt;”. Let’s learn another 15 epochs.</p><pre>trainer.train()<br>sample_generate(model, tokenizer, holdout_input, max_new_tokens=5)<br>&gt;&gt;&gt; bueno &lt;/s&gt;</pre><p>After 30 epochs we learned what we were supposed to!</p><p>Let’s simulate what happens in training by iteratively predicting the prompt one token at a time, based on the previous tokens.</p><pre>print_iterative_generate(model, tokenizer, inputs)<br>&gt;&gt;&gt;<br>#<br>: How do you say &quot;how morning in Spanish?<br><br><br>### Assistant: gu buenopu</pre><p>That’s pretty close to the actual prompt, as we expected. But the task is translation, so we don’t really care about being able to predict the user prompt. Is there a way to learn just the response part?</p><h4>Masked approach</h4><p>Hugging Face allows you to only learn to predict certain tokens by “masking” the tokens you don’t care about in “labels.” This is different from the attention mask, which hides <em>previous </em>tokens we use to generate a new token. Masking the labels hides the token you’re supposed to output at a certain index from the loss function. Note the wording: Hugging Face has it implemented such that during training, we still generate predictions for that masked token. However, because we hide the true label to compare the predictions with, we don’t directly learn how to improve on that prediction.</p><p>We create the “mask” by flipping those tokens to -100 in the labels key.</p><pre>def create_special_mask(example: Dict) -&gt; Dict:<br>    &quot;&quot;&quot;Mask human text and keep assistant text as it is.<br><br>    Args:<br>        example (Dict): Result of tokenizing some text<br><br>    Returns:<br>        Dict: The dict with the label masked<br>    &quot;&quot;&quot;<br>    # setting a token to -100 is how we &quot;mask&quot; a token<br>    # and tell the model to ignore it when calculating the loss<br>    mask_token_id = -100<br>    # assume we always start with a human text<br>    human_text = True<br>    for idx, tok_id in enumerate(example[&quot;labels&quot;]):<br>        if human_text:<br>            # mask all human text up until and including the bos token<br>            example[&quot;labels&quot;][idx] = mask_token_id<br>            if tok_id == tokenizer.bos_token_id:<br>                human_text = False<br>        elif not human_text and tok_id == tokenizer.eos_token_id:<br>            # don’t mask the eos token, but the next token will be human text to mask<br>            human_text = True<br>        elif not human_text:<br>            # leave example[&#39;labels&#39;] text as it is when assistant text<br>            continue<br>    return example<br><br><br>dataset_masked = dataset.map(create_special_mask)<br># convert dataset from lists to torch tensors<br>dataset_masked.set_format(type=&quot;torch&quot;, columns=[&quot;input_ids&quot;, &quot;attention_mask&quot;, &quot;labels&quot;])<br>print(f&quot;{dataset_masked[0][&quot;labels&quot;]=}&quot;)<br><br>&gt;&gt;&gt; dataset[0][&quot;labels&quot;]=tensor([ -100,  -100,  -100,  -100,  -100,  -100,  -100,  -100,  -100,  -100, -100,  -100,  -100,  -100,  -100,  -100,  -100,  -100, 82208,     2])</pre><pre>model = load_model(model_name)<br>trainer = Trainer(<br>    model=model,<br>    train_dataset=dataset_masked,<br>    args=training_arguments,<br>)<br><br>training2 = trainer.train()<br><br>print(f&quot;{training2.metrics[&#39;train_runtime&#39;]=}&quot;)<br>print(f&quot;{training1.metrics[&#39;train_runtime&#39;] =}&quot;)<br>print(<br>    f&quot;{100*round((training1.metrics[&#39;train_runtime&#39;]  - training2.metrics[&#39;train_runtime&#39;]) / training1.metrics[&#39;train_runtime&#39;] , 2)}%&quot;<br>)<br><br><br>&gt;&gt;&gt; training2.metrics[&#39;train_runtime&#39;]=61.7164<br>&gt;&gt;&gt; training1.metrics[&#39;train_runtime&#39;] =70.8013<br>&gt;&gt;&gt; 13.0%</pre><p>First off, we were faster this time by more than 10%. Presumably, the fact that we have fewer loss calculations makes things a bit quicker.</p><p>I wouldn’t bank on the speed up being this large — our example is pretty lopsided with much more human text than generated text. But when training times are in the hours, every little percentage is helpful.</p><p>The big question: did we learn the task?</p><pre>sample_generate(model, tokenizer, holdout_input, max_new_tokens=5)<br>&gt;&gt;&gt; bueno &lt;/s&gt;</pre><p>This time we only need 15 epochs to learn the task. Let’s go back to how things are under the hood during training</p><pre>print_iterative_generate(model, tokenizer, inputs)<br>&gt;&gt;&gt;#include<br> code<br> to I get &quot;we&quot; in English?<br>A: Spanish: How bueno</pre><p>Iteratively predicting the prompt leads to non-sense compared with our first training approach. This checks out: we masked the prompt during training and therefore don’t learn how to predict anything up until our real target: the assistant response.</p><h4>Using TRL’s supervised fine-tuning trainer</h4><p>Hugging Face semi-recently rolled out a TRL (transformer reinforcement learning) library to add end-to-end support for the LLM training process. One feature is supervised fine-tuning. Using the DataCollatorForCompletionOnlyLM and SFTTrainer classes, we can create the labels like we did with <em>create_special_mask</em> with just a few configs.</p><pre>model = load_model(model_name)<br><br># a hugging face function to do the copying of labels for you.<br># using the instruction and response templates will mask everything between the instruction template and the start of the response_template<br>collator = DataCollatorForCompletionOnlyLM(<br>    instruction_template=tokenizer.eos_token,<br>    response_template=tokenizer.bos_token,<br>    tokenizer=tokenizer,<br>)<br><br>trainersft = SFTTrainer(<br>    model,<br>    train_dataset=dataset_text,<br>    dataset_text_field=&quot;text&quot;,<br>    data_collator=collator,<br>    args=training_arguments,<br>    tokenizer=tokenizer,<br>)<br>sftrain = trainersft.train()<br><br>sample_generate(model, tokenizer, holdout_input, max_new_tokens=5)<br>&gt;&gt;&gt; &#39; bueno&lt;/s&gt;&#39;</pre><p>Success! If you dig deeper, training actually took longer using SFT. This might be credited to the fact that we have to tokenize at training time rather than as a preprocessing step in the masked approach. However, this approach gives us free batching (you’d need to tweak the tokenization process to use the masked approach to batch properly), which should make things faster in the long run.</p><p>The full notebook explores a few other things like training off multi-turn chats and using special_tokens to indicate human vs chat text.</p><p>Obviously, this example is a bit basic. However, hopefully you can start to see the power of using CausalLM: You can imagine taking interactions from a large, reliable model, and using the techniques above to fine-tune a smaller model on the large model’s outputs. This is called knowledge distillation.</p><p>If we’ve learned anything over the last couple years of LLMs, it’s that we can do some surprisingly intelligent things just by training on next token prediction. Causal language models are designed to do just that. Even if the Hugging Face class is a bit confusing at first, once you’re used to it, you have a very powerful interface to train your own generative models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fdb4d9bd936" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/causallm-part-2-finetuning-a-model-3fdb4d9bd936">CausalLM Part 2: Finetuning a model</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>
        <item>
            <title><![CDATA[Training CausalLM Models Part 1: What Actually Is CausalLM?]]></title>
            <link>https://medium.com/data-science/training-causallm-models-part-1-what-actually-is-causallm-6c3efb2490ec?source=rss-25d46b423610------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c3efb2490ec</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Theo Lebryk]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 12:52:04 GMT</pubDate>
            <atom:updated>2024-03-06T17:56:49.091Z</atom:updated>
            <content:encoded><![CDATA[<h4>The first part of a practical guide to using HuggingFace’s CausalLM class</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NoYeJ4fe_I0JsEjvyRMYWw.png" /><figcaption>Causal langauge models model each new word as a function of all previous words. Source: <a href="https://www.pexels.com/photo/dog-eating-a-carrot-5255204/">Pexels</a></figcaption></figure><p>If you’ve played around with recent models on <a href="https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard">HuggingFace</a>, chances are you encountered a causal language model. When you pull up the documentation for a <a href="https://huggingface.co/docs/transformers/main/en/model_doc/llama">model</a> family, you’ll get a page with “tasks” like LlamaForCausalLM or LlamaForSequenceClassification.</p><p>If you’re like me, going from that documentation to actually finetuning a model can be a bit confusing. We’re going to focus on CausalLM, starting by explaining what CausalLM is in this post followed by a practical example of how to finetune a CausalLM model in a subsequent post.</p><h4>Background: Encoders and Decoders</h4><p>Many of the best models today such as LLAMA-2, GPT-2, or Falcon are “decoder-only” models. A decoder-only model:</p><ol><li>takes a sequence of <em>previous </em>tokens (AKA a prompt)</li><li>runs those tokens through the model (often creating embeddings from tokens and running them through transformer blocks)</li><li>outputs a single output (usually the probability of the next token).</li></ol><p>This is contrasted with models with “encoder-only” or hybrid “encoder-decoder” architectures which will input the <em>entire </em>sequence, not just <em>previous </em>tokens. This difference disposes the two architectures towards different tasks. Decoder models are designed for the generative task of writing new text. Encoder models are designed for tasks which require looking at a full sequence such as translation or sequence classification. Things get murky because you can repurpose a decoder-only model to do translation or use an encoder-only model to generate new text. Sebastian Raschka has a nice <a href="https://magazine.sebastianraschka.com/p/understanding-encoder-and-decoder">guide</a> if you want to dig more into encoders vs decoders. There’s a also a <a href="https://towardsdatascience.com/understanding-masked-language-models-mlm-and-causal-language-models-clm-in-nlp-194c15f56a5">medium article</a> which goes more in-depth into the differeneces between masked langauge modeling and causal langauge modeling.</p><p>For our purposes, all you need to know is that:</p><ol><li>CausalLM models generally are decoder-only models</li><li>Decoder-only models look at past tokens to predict the next token</li></ol><p>With decoder-only language models, we can think of the next token prediction process as “causal language modeling” because the previous tokens “cause” each additional token.</p><h4>HuggingFace CausalLM</h4><p>In HuggingFace world, CausalLM (LM stands for language modeling) is a class of models which take a prompt and predict new tokens. In reality, we’re predicting one token at a time, but the class abstracts away the tediousness of having to loop through sequences one token at a time. During inference, CausalLMs will iteratively predict individual tokens until some stopping condition at which point the model returns the final concatenated tokens.</p><p>During training, something similar happens where we give the model a sequence of tokens we want to learn. We start by predicting the second token given the first one, then the third token given the first two tokens and so on.</p><p>Thus, if you want to learn how to predict the sentence “the dog likes food,” assuming each word is a token, you’re making 3 predictions:</p><ol><li>“the” → dog,</li><li>“the dog” → likes</li><li>“the dog likes” → food</li></ol><p>During training, you can think about each of the three snapshots of the sentence as three observations in your training dataset. Manually splitting long sequences into individual rows for each token in a sequence would be tedious, so HuggingFace handles it for you.</p><p>As long as you give it a sequence of tokens, it will break out that sequence into individual single token predictions behind the scenes.</p><p>You can create this ‘sequence of tokens’ by running a regular string through the model’s tokenizer. The tokenizer will output a dictionary-like object with <em>input_ids </em>and an <em>attention_mask </em>as keys, like with any ordinary HuggingFace model.</p><pre>from transformers import AutoTokenizer<br>tokenizer = AutoTokenizer.from_pretrained(&quot;bigscience/bloom-560m&quot;)<br>tokenizer(&quot;the dog likes food&quot;)<br>&gt;&gt;&gt; {&#39;input_ids&#39;: [5984, 35433, 114022, 17304], &#39;attention_mask&#39;: [1, 1, 1, 1]}</pre><p>With CausalLM models, there’s one additional step where the model expects a <em>labels </em>key. During training, we use the “previous” <em>input_ids </em>to predict the “current” <em>labels </em>token. However, you do <strong>not </strong>want to think about labels like a question answering model where the first index of <em>labels </em>corresponds with the answer to the <em>input_ids </em>(i.e. that the <em>labels </em>should be concatenated to the end of the <em>input_ids</em>). Rather, you want <em>labels </em>and <em>input_ids </em>to mirror each other with identical shapes. In algebraic notation, to predict <em>labels </em>token at index k, we use all the <em>input_ids </em>through the k-1 index.</p><p>If this is confusing, practically, you can usually just make <em>labels </em>an identical copy of <em>input_ids </em>and call it a day. If you do want to understand what’s going on, we’ll walk through an example.</p><h4>A quick worked example</h4><p>Let’s go back to “the dog likes food.” For simplicity, let’s leave the words as words rather than assigning them to token numbers, but in practice these would be numbers which you can map back to their true string representation using the tokenizer.</p><p>Our input for a single element batch would look like this:</p><pre>{<br>    &quot;input_ids&quot;: [[&quot;the&quot;, &quot;dog&quot;, &quot;likes&quot;, &quot;food&quot;]],<br>    &quot;attention_mask&quot;: [[1, 1, 1, 1]],<br>    &quot;labels&quot;: [[&quot;the&quot;, &quot;dog&quot;, &quot;likes&quot;, &quot;food&quot;]],<br>}</pre><p>The double brackets denote that technically the shape for the arrays for each key is batch_size x sequence_size. To keep things simple, we can ignore batching and just treat them like one dimensional vectors.</p><p>Under the hood, if the model is predicting the kth token in a sequence, it will do so kind of like so:</p><pre>pred_token_k = model(input_ids[:k]*attention_mask[:k]^T)</pre><blockquote>Note this is pseudocode.</blockquote><p>We can ignore the attention mask for our purposes. For CausalLM models, we usually want the attention mask to be all 1s because we want to attend to all previous tokens. Also note that [:k] really means we use the 0th index through the k-1 index because the ending index in slicing is <em>exclusive</em>.</p><p>With that in mind, we have:</p><pre>pred_token_k = model(input_ids[:k])</pre><p>The loss would be taken by comparing the true value of <em>labels[k]</em> with <em>pred_token_k</em>.</p><p>In reality, both get represented as 1xv vectors where v is the size of the vocabulary. Each element represents the probability of that token. For the predictions (<em>pred_token_k</em>), these are real probabilities the model predicts. For the true label (<em>labels[k]</em>), we can artificially make it the correct shape by making a vector with 1 for the actual true token and 0 for all other tokens in the vocabulary.</p><p>Let’s say we’re predicting the second word of our sample sentence, meaning k=1 (we’re zero indexing k). The first bullet item is the context we use to generate a prediction and the second bullet item is the true label token we’re aiming to predict.</p><p>k=1:</p><ul><li>Input_ids[:1] == [the]</li><li>Labels[1] == dog</li></ul><p>k=2:</p><ul><li>Input_ids[:2] == [the, dog]</li><li>Labels[2] == likes</li></ul><p>k =3:</p><ul><li>Input_ids[:3] == [the, dog, likes]</li><li>Labels[3] == food</li></ul><p>Let’s say k=3 and we feed the model “[the, dog, likes]”. The model outputs:</p><pre>[P(dog)=10%, P(food)=60%,P(likes)=0%, P(the)=30%]</pre><p>In other words, the model thinks there’s a 10% chance the next token is “dog,” 60% chance the next token is “food” and 30% chance the next token is “the.”</p><p>The true label could be represented as:</p><pre>[P(dog)=0%, P(food)=100%, P(likes)=0%, P(the)=0%]</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58294b7bdaa2ec036a5c6c84b3b8730a/href">https://medium.com/media/58294b7bdaa2ec036a5c6c84b3b8730a/href</a></iframe><p>In real training, we’d use a loss function like cross-entropy. To keep it as intuitive as possible, let’s just use absolute difference to get an approximate feel for loss. By absolute difference, I mean the absolute value of the difference between the predicted probability and our “true” probability: e.g. <em>absolute_diff_dog = |0.10–0.00| = 0.10</em>.</p><p>Even with this crude loss function, you can see that to minimize the loss we want to predict a high probability for the actual label (e.g. food) and low probabilities for all other tokens in the vocabulary.</p><p>For instance, let’s say after training, when we ask our model to predict the next token given [the, dog, likes], our outputs look like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e91969aca100a15c84212d57cb6c878/href">https://medium.com/media/4e91969aca100a15c84212d57cb6c878/href</a></iframe><p>Now our loss is smaller now that we’ve learned to predict “food” with high probability given those inputs.</p><p>Training would just be repeating this process of trying to align the predicted probabilities with the true next token for all the tokens in your training sequences.</p><h4>Conclusion</h4><p>Hopefully you’re getting an intuition about what’s happening under the hood to train a CausalLM model using HuggingFace. You might have some questions like “why do we need <em>labels </em>as a separate array when we could just use the kth index of <em>input_ids </em>directly at each step? Is there any case when <em>labels </em>would be different than <em>input_ids</em>?”</p><p>I’m going to leave you to think about those questions and stop there for now. We’ll pick back up with answers and real code in the next post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c3efb2490ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/training-causallm-models-part-1-what-actually-is-causallm-6c3efb2490ec">Training CausalLM Models Part 1: What Actually Is CausalLM?</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>
        <item>
            <title><![CDATA[Introduction to the Structural Topic Model (STM)]]></title>
            <link>https://medium.com/data-science/introduction-to-the-structural-topic-model-stm-34ec4bd5383?source=rss-25d46b423610------2</link>
            <guid isPermaLink="false">https://medium.com/p/34ec4bd5383</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[topic-modeling]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <dc:creator><![CDATA[Theo Lebryk]]></dc:creator>
            <pubDate>Sun, 18 Apr 2021 03:33:56 GMT</pubDate>
            <atom:updated>2021-04-18T03:33:56.450Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to The Structural Topic Model (STM)</h3><h4>A unique way to use topic modelling for social science research</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CkwEm0N6SyXjlBeQ" /><figcaption>Photo by <a href="https://unsplash.com/@malinstrandvall?utm_source=medium&amp;utm_medium=referral">Malin Strandvall</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of the coolest things about topic modelling is that it has applications in a variety of areas. It can help motivate inquiry, provide unique insights into texts, and give you new ways to organize documents.</p><p>The Structural Topic Model (STM) is a form of topic modelling specifically designed with social science research in mind. STM allow us to incorporate metadata into our model and uncover how different documents might talk about the same underlying topic using different word choices.</p><h3>Motivating STM</h3><p>Topic modelling describes uncovering latent topics within a corpus of documents. The most famous topic model is probably <a href="https://jmlr.org/papers/volume3/blei03a/blei03a.pdf">Latent Dirichlet Allocation (LDA)</a>. LDA’s basic premise is to model documents as distributions of topics (topic prevalence) and topics as a distribution of words (topic content). Check out this medium guide for some <a href="https://towardsdatascience.com/latent-dirichlet-allocation-lda-9d1cd064ffa2">LDA basics</a>.</p><p>LDA is great, but it does make some restrictive assumptions:</p><ol><li>Topics within a document are independent of one another. In English: Just because document 1 has latent topic 1, it gives us no information whether document 1 has latent topic 2, 3, etc.</li><li>The distribution of words within a topic (i.e. topic content) is stationary. In English: topic 1 for document 1 uses identical words as topic 1 for document 2, 3, etc.</li><li>Topics can be modeled entirely based on the text of the document. In English: LDA only looks at the text of the document when determining topics, and doesn’t take any other information (author, date, source) into account.</li></ol><p>To address the first assumption of independence, check out <a href="https://towardsdatascience.com/intuitive-guide-to-correlated-topic-models-76d5baef03d3">Correlated Topic Models</a> (CTM). STM employs CTMs, but adds a couple more features on top.</p><p>From a social science or humanities perspective, assumption two is somewhat suboptimal. Two documents could be about the same topic — say a protest — yet come at the topic from different angles. Perhaps one tends to highlight “police brutality” or “peaceful protesters” whereas the other uses terms like “law and order” and “radical rioters.” Both documents can be said to be about the same topic, but the topic content (i.e. words that make up the topic) vary from document to document.</p><p>As for the third assumption, we might imagine that both the topic prevalence and topic content for a specific document is correlated with “metadata” about the document. For instance, certain sources may be more likely to write about politics or write about politics in a particular way. Metadata can include date published, author, publication, likes on social media, or any number of categorical or numerical variables about a document.</p><h3>The STM solution</h3><p>In LDA, our topic prevalence and content came from Dirichlet distributions with hyperparameters we set in advance — sometimes referred to as <em>a</em> and <em>b</em>. With STM, our topic prevalence and content come from document metadata. We’re going to call the matrix of document metadata used to generate topic prevalence “<em>X</em>” and the matrix of document metadata used to generate topic contents “<em>Y</em>.” To try and keep things simple, however, we’ll say that <em>X</em>=<em>Y</em> (i.e. we’re using the same metadata in both cases) and that both are <em>dxp</em> matrices where <em>d</em> is the number of documents in the corpus and <em>p</em> is the number of metadata features we will use.</p><h3>Topic prevalence</h3><p>For topic prevalence, our goal is to get to a probability vector for each document, which we’ll call θᵢ. We need to go from <em>X</em>ᵢ, a <em>1xp </em>metadata vector for a specific document, to θᵢ, a <em>1xk </em>vector whose entries sum to one and essentially correspond to how much of that document is made up of a given topic. For our purposes, <em>i </em>just means this θ is specific to a given document <em>i</em> Apologies; subscript “<em>i</em>” would usually be subscript “<em>d</em>” as in “document” in the literature but I cannot find a Unicode subscript “d” for the life of me.</p><p>To get to θᵢ, we’re going to multiply <em>X</em>ᵢ by a <em>pxk </em>matrix of weights called “τ.” Where does τ come from? Well, we’re going to call τ’s columns “γ.” The default settings on the <a href="https://cran.r-project.org/package=stm">R STM</a> package is for <em>γₚ,ₖ~N(0, σₖ²) </em>where <em>σₖ²~Half-Cauchy(1,1)</em>.</p><p>Interpretation-wise, the <em>Half-Cauchy (1,1)</em> prior means most parameters will start around zero (the mean on the normal distribution is zero and the <em>Half-Cauchy (1,1)</em> means the variance will also be near zero). During the inference steps, we’ll learn the actual parameter values, but the prior on these parameters will drag these values towards zero, meaning that only metadata that is highly correlated with a topic will end up being influential. The Half-Cauchy prior will shrink non-influential coefficients <em>towards</em> zero, but does not actually zero out parameters. If you have a ton of metadata which might not be relevant to the topics of a document (for example one-hot encoded features), we might want to induce sparsity. For these cases, the R package supports a Gamma prior with L1 or elastic net regularization.</p><p>Before we get too bogged down in STM’s implementation details, the most important thing is that we’ve done a linear transformation from a <em>1xp</em> metadata vector into a <em>1xk</em> vector roughly corresponding to topic prevalence.</p><p>We still don’t have a probability vector yet. The resulting vector from τ * <em>X</em>ᵢ will serve as the mean for the logistic normal distribution that will ultimately generate θ:</p><p>θᵢ ~ LogisticNormal(τ<em>X</em>ᵢ, Σ)</p><p>What this means is that we’re treating the result of τ<em>X</em>ᵢ as the mean of a multivariate normal with variance Σ. In fact, Σ is the <em>kxk</em> topic covariance matrix (see CTM for a more thorough explanation), which is how we break assumption one and incorporate correlations between topics into our model. We then transform the resulting vector from our multivariate normal (which is called η) into probabilities by passing it through the logistic function.</p><p>From here on, it’s just regular LDA where we generate per-word topics (<em>z</em>) based on a multinomial made up of these topic probabilities — i.e. <em>z</em>ᵢ,ₙ~<em>Multinomial(</em>θᵢ<em>), </em>for every <em>n</em> word in document <em>i</em>. Now that we have the topic for each word in the document, we still need to figure out the probabilities of different words for a given topic, which we’ll explore in the next section.</p><h3>Topic content</h3><p>For the topic content of a document, we start with <em>Y</em>ᵢ, our <em>1xp</em> vector of metadata for a given document <em>i. </em>Our end goal is a <em>kxV</em> matrix called βᵢ, where <em>V</em> is the length our vocabulary. In βᵢ, every <em>k</em> row is simply a probability vector, where each column value is the probability of a word being generated by that topic. As the <em>i </em>subscript indicates, this β is specific to a single given document.</p><p>To get word probabilities for a single topic in a single document (βᵢᵏ), we’re going to start with a baseline word probability we’ll call <em>m</em>. <em>m</em> is a <em>1xv</em> vector that basically represents the global word probabilities: usually this means the log-transformed rate of any given word across the corpus, but also could be set in advance according to some known word frequencies.</p><p>From there, we’re going to deviate from that baseline by adding some vectors we’ll call κ. Note that κ (kappa) is not the same as <em>k. </em>It’s confusing, I know, but remember that κ is a set of deviations away from global word frequencies while <em>k </em>is the number of topics.</p><p>First, we’re going to add a topic deviation from the baseline called κₖᵗ. The superscript “<em>t” </em>is just a reminder that this is our “topic” deviation and the “<em>k”</em> subscript is further reminder that this deviation is specific to a topic <em>k</em>. Slightly more precisely κᵗ is a <em>kxv</em> matrix with κₖᵗ meaning we only are looking at row <em>k</em> right now. Whatever the case, at this point, it’s basically like regular LDA as κₖᵗ is non-document specific impact of a topic on word frequencies.</p><p>Second, we’re going to improve over LDA by adding document deviation to the baseline, what we’ll call κᵧᵢᶜ (pretend that “γi” is actually “<em>y</em>ᵢ”… Unicode bests me again). The “c” superscript simply symbolizes this is the “covariate” deviation (another word for metadata) and the γi/<em>y</em>ᵢ is also indicating that this covariate comes from the specific document’s metadata. In other words, κᵧᵢᶜ is a deviation based on how the model thinks the metadata will affect our word frequencies.</p><p>Finally, for good measure, we’re going to add an interaction deviation from the topic and the covariates (aka metadata): κᵧᵢ,ₖ,ᵥⁱ. Nothing to write home about here; this last κ term merely covers our bases in case there’s an “interaction” (which the “<em>i”</em> superscript indicates) between the metadata and a given topic when it comes to impacting word-frequencies.</p><p>Once we add all that together, we can just apply some logistic transformations, and we’ll have our word probabilities for a given topic within a given document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*BXDh0w9uue4LSsv6OPcAOA.png" /><figcaption>Full formula for βᵢ,ₖ,ᵥ. βᵢ,ₖ,ᵥ means: for a given document <em>i and given topic k, what is the probability of a given word v.</em></figcaption></figure><p>Where κ comes from isn’t all that important as we learn it over the course of posterior inference. While κ may seem a bit opaque, put simply, it is what gives us <em>document-specific</em> topic content. Once we’ve built an STM model, we can see the most frequent words (i.e. the highest βᵢᵏ) for the same topic <em>k </em>across different documents.</p><p>With that, we’re basically done! Here’s the final Plate diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*HmGfmzjbfcEWK-UnOoG_8A.png" /><figcaption>STM plate diagram. Recall z is the topic our θ generates. W is the word selected from that topic, based on β. <em>M</em> is the number of documents in the corpus. <em>N</em> is the number of words in a document. Boxes are kind of like loops, meaning we’re repeating the innermost process (z and w) for every word for every document.</figcaption></figure><p>And here’s the gross looking posterior distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*-DKS8oPe9BdR3MKtxCzayw.png" /><figcaption>Posterior distribution. Recall that η is essentially our topic prevalence before the logistic transformation that converts it into a probability.</figcaption></figure><h3>Super Brief Inference Sidebar</h3><p>What that big equation is saying is that in STM, we’re given the documents’ words (<em>W) </em>the documents’ metadata (<em>X,Y</em>), and number of topics (<em>k</em>). We need to estimate the underlying topic prevalences (η); concrete topic assignments(<em>z</em>), covariate and interaction deviations from the baseline topic content (κ), the parameters to map from metadata to topic prevalence (γ), and the correlations between topics (Σ).</p><p>If you are interested in inference, the STM algorithm of choice is a “a fast variant of nonconjugate variational expectation-maximization (EM).” Broadly speaking, we first estimate (the estimation/E-step) topic content and prevalence parameters then update all the parameters using a couple different algorithms (the maximization/M-step). We’re testing how likely those parameters are given the data, updating the parameters based on our data, and iterating until the change in a parameter drops below some threshold (i.e. the model converges). This seems complicated, and it no doubt is tough computationally, but at a high level it boils down to regular Bayesian inference.</p><p>2 quick notes: I’ve included <em>k</em> as a hyperparameter we set in advance. The R STM package has a “searchK” function which will try to find the optimal k automatically. It’s not worth getting into how it determines the optimal<em> k,</em> and the posterior as far as we’re concerned treats <em>k </em>as a given so we’ve included it here as a hyperparameter. The original authors, however, don’t include it in their posterior equation, nor do they include <em>m. </em>Recall we can set <em>m</em> in advance or derive it from <em>W</em>. Either way, it isn’t something we’re estimating but does affect κ so I’ve included it in our posterior.</p><h3>Conclusion</h3><p>To recap: STM enables not just higher quality models, but also provides insights into the corpus such as how metadata affects the words a document uses within a topic. With that, you can hopefully understand the method behind papers about <a href="https://www.pnas.org/content/113/1/92.short">ideological polarization on climate change</a>, <a href="https://www.tandfonline.com/doi/full/10.1080/19331681.2019.1657048">what state judges tweet about</a>, and <a href="https://journals.sagepub.com/doi/full/10.1177/2053168015612808">when the pope talks politics</a>.</p><p>You’re also hopefully ready to start playing around with STM in R (or if R gives you headaches then you can use this <a href="https://cran.r-project.org/web/packages/stmgui/index.html">GUI</a> instead). I’d highly recommend taking a look at the <a href="https://www.structuraltopicmodel.com/">STM homepage</a> which has links to the methods papers, more STM packages, and more published papers using STM.</p><p>[1] M. Roberts, B. Stewart, D. Tingley, and E. Airoldi, <a href="https://scholar.princeton.edu/files/bstewart/files/stmnips2013.pdf">The Structural Topic Model and Applied Social Science</a> (2013), Prepared for the NIPS 2013 Workshop on Topic Models: Computation, Application, and Evaluation.</p><p>[2] M. Roberts, B. Stewart, and E. Airoldi, <a href="https://scholar.princeton.edu/sites/default/files/bstewart/files/stm.pdf">A Model of Text for Experimentation in the Social Science</a> (2016), The Journal of the American Statistical Association.</p><p>[3] D. Blei, A. Ng., and M. Jordan, <a href="https://www.jmlr.org/papers/volume3/blei03a/blei03a.pdf">Latent Dirichlet Allocation</a> (2003), The Journal of Machine Learning Research.</p><p>[4] D. Blei and J. Lafferty, <a href="https://dl.acm.org/doi/10.5555/2976248.2976267">Correlated Topic Models</a> (2005), NIPS’05: Proceedings of the 18th International Conference on Neural Information Processing Systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34ec4bd5383" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/introduction-to-the-structural-topic-model-stm-34ec4bd5383">Introduction to the Structural Topic Model (STM)</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>
        <item>
            <title><![CDATA[Intuitive Guide to Correlated Topic Models]]></title>
            <link>https://medium.com/data-science/intuitive-guide-to-correlated-topic-models-76d5baef03d3?source=rss-25d46b423610------2</link>
            <guid isPermaLink="false">https://medium.com/p/76d5baef03d3</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[topic-modeling]]></category>
            <category><![CDATA[lda]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[editors-pick]]></category>
            <dc:creator><![CDATA[Theo Lebryk]]></dc:creator>
            <pubDate>Fri, 05 Mar 2021 00:18:09 GMT</pubDate>
            <atom:updated>2021-03-06T15:26:00.563Z</atom:updated>
            <content:encoded><![CDATA[<h4>A neat extension to LDA which can be the backbone for even more advanced topic models</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5OnQMGIDPbdtQbiJ" /><figcaption>Photo by <a href="https://unsplash.com/@takeshi2?utm_source=medium&amp;utm_medium=referral">wu yi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ever since David Blei, Andrew Ng, and Michael Jordan (no not the basketball player; no not the actor) came out with Latent Dirichlet Allocation (LDA) in <a href="https://dl.acm.org/doi/pdf/10.5555/944919.944937">2003</a>, topic modeling has been one of the most well-trafficked models in all of data science. Fun fact: that original LDA paper is the most cited paper from the <a href="https://dl.acm.org/journal/jmlr">Journal of Machine Learning Research</a>.</p><p>Topic modelling, simply put, is finding out what a document is about. Unlike with supervised document classification, it’s unlikely we know the topics in advance. Instead, we take an unsupervised approach and uncover latent topics in the documents. LDA is particularly useful for document modeling, classification, and even collaborative filtering.</p><p>In this post, I’m going to introduce an important, but somewhat overlooked, extension to LDA: the<a href="http://people.ee.duke.edu/~lcarin/Blei2005CTM.pdf"> correlated topic model</a> (CTM).</p><p><strong>Motivating CTM: Limitations of LDA</strong></p><p>We’re going to build from the ground up by first reviewing LDA, then showing how CTM tries to improve over LDA. There are a couple of great <a href="https://towardsdatascience.com/latent-dirichlet-allocation-lda-9d1cd064ffa2">LDA</a> <a href="https://towardsdatascience.com/light-on-math-machine-learning-intuitive-guide-to-latent-dirichlet-allocation-437c81220158">guides</a> already on medium, which I highly recommend to supplement this brief overview.</p><p>LDA models documents as a distribution of topics and topics as a distribution of words. Our word generation process consists of selecting a topic from the document’s distribution of topics (a multinomial distribution we’ll call Θᵢ where <em>i </em>just means this Θ is specific to document <em>i</em>) and selecting a word from that topic’s distribution of words (another multinomial usually called β). These distributions are generated from Dirichlet distributions. For now, we’re only focused on the first of these Dirichlets that produces Θᵢ, the topic distributions for a document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*kSdYmDHsK2cimt8HSaGNcQ.png" /><figcaption>A place diagram for LDA. The bottom right corner of a box means repeat the operation that many times. <em>M</em> is the number of documents in the corpus; N is the number of words in a document; k is the number of topics. z is the specific topic that Θ spits out, which dictates which β probability vector we use to select our final word w. <em>a and </em>b are hyperparameters for the respective Dirichlet distributions.</figcaption></figure><p>For those less familiar with the Dirichlet, think of it as the multivariate generalization of the beta. It produces probabilities for not just a single Bernoulli trial, but rather for a probability vector with multiple classes, in our case for the <em>k</em> topics in our model. In other words, the Dirichlet is the <a href="https://towardsdatascience.com/conjugate-prior-explained-75957dc80bfb">conjugate prior</a> for the multinomial.</p><p>I know this is a bit jargony and quick, but even if you don’t totally understand, there are two takeaways to note:</p><ol><li>The fact that the Dirichlet is the conjugate prior for the multinomial makes the math come out nicely when we start to actually working with the data. We still need to do some approximations to get our final topics and their distributions, which we can do via <a href="https://jonathan-hui.medium.com/machine-learning-variational-inference-273d8e6480bb">variational inference</a>, or other techniques like <a href="https://www.ics.uci.edu/~asuncion/pubs/KDD_08.pdf">collapsed Gibbs sampling</a>.</li><li>The Dirichlet produces topic probabilities that are independent-ish (in math terms: it produces a <a href="https://en.wikipedia.org/wiki/Neutral_vector">neutral vector</a>). Recall for the multinomial if you drop one of the categories, the rest of the probabilities just renormalize around the remaining probability left to allocate. The remaining categories don’t change relative sizes.The Dirichlet is designed to generate probabilities with this in mind, meaning we are unable to model correlated topics.</li></ol><p>What if we think topics are highly correlated? This isn’t too far-fetched: one latent topic might contain a bunch of words about food while another topic might contain words about health and fitness. These two topics are probably at least somewhat dependent. A document about health and fitness is more likely to also be about food than a randomly chosen document.</p><p><strong>The CTM solution</strong></p><p>We’re going to leave the rest of the generative model alone and just focus on how we generate Θs. In order to introduce correlations, we’re going to start with the multivariate normal distribution instead of the Dirichlet. If the Dirichlet is the multivariate generalization of the beta, the multivariate normal is just the multivariate generalization of the normal. Just as before, our goal is to generate <em>k</em> values (one for each topic) for our probability vector.</p><p>With the univariate normal, we need a mean and standard deviation. With the multivariate normal, we’ll need <em>k</em> means and <em>k</em> standard deviations. We’re also going to factor in the covariances between the different topics. In total, we’re feeding the multivariate normal two parameters: a <em>k</em> length vector of means (μ) and a <em>kxk </em>covariance matrix (Σ).</p><p>At this point, our model will be spitting out a vector <em>k</em> of values of arbitrary sizes, which we’ll call η. These numbers could be negative or they could be enormous. Ultimately, our goal is to have a probability vector of non-negative numbers that sum to one (known as a simplex).</p><p>To map the results of our multivariate normal into probabilities, we’re going to pass all the values through a variant of the logistic function. Specifically, for every output multivariate normal ηⱼ (where <em>j</em> corresponds to a topic), we’re applying the transformation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/1*sOh1fuq7i3Yq9WGo50uLUw.png" /></figure><p>The end result of passing the multivariate normal through this logistic transformation is called the <a href="https://en.wikipedia.org/wiki/Logit-normal_distribution">logit normal distribution</a>. In sum, all we’ve done is swap the Dirichlet distribution — Θ ~ <em>Dir(</em>α<em>)</em> — with a logit-normal distribution — Θ~ <em>f(N(</em>μ, Σ), where f(x) is the logistic transformation and N is the multivariate normal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*GVjUErcJf1LnDnrcqNcbHQ.png" /><figcaption>CTM plate diagram. “Log” represents the logistic transformation listed above.</figcaption></figure><p>This little switch has a couple important implications. Unfortunately, the multivariate normal, plus the logistic transformation at the end, doesn’t have the same neat properties as the Dirichlet.</p><p>Thus, we can no longer use the standard variational inference technique LDA uses. Instead, CTM uses something called mean field variational inference. The mechanics of mean field variational inference are… involved. Let’s just leave it that we now have additional variational parameters which require iterative methods to optimize. For our purposes, the main takeaway is that training might take a bit longer for CTM.</p><p>The payoff for this longer training is that we get not only get better topics, we also get the added benefit of seeing the relationship between topics. In LDA, the researcher would have to go in after training to try to sort out correlations manually. With CTM, we have to look no farther than the model itself to observe correlations. Maybe books about leadership also use a lot of religious language and vice versa, which could show up in a correlation. Maybe we find superset-subset relationships through correlations (e.g. a topic with general sports words is probably correlated with a topic with basketball words).</p><p>CTMs are particularly helpful if:</p><ul><li>We have a hunch in advance that topics are likely to be correlated.</li><li>We are modelling a lot of topics, in which case at least a few are bound to be correlated.</li></ul><p>However, I should qualify that correlation is not some form of semantic distance between topics. We’re merely observing that certain topics tend to appear, or not appear, together. Because CTM relies on parameter inference/estimation, and not some closed form solution, it’s best to not read too deeply into the precise correlations between topics. However, when it comes to providing broad brushstrokes or motivating further inquiry during EDA, these sorts of insights can be pretty interesting.</p><p><strong>Conclusion</strong></p><p>To recap:</p><ul><li>Topic modelling is an unsupervised method of finding latent topics that a document is about.</li><li>The most common, well-known method of topic modelling is latent Dirichlet allocation. In LDA, we model documents as distributions of (independent-ish) topics which are themselves distributions of words.</li><li>We can improve on this baseline if we allow correlations between topics.</li><li>This comes at the cost of longer training time.</li><li>However, it enables the researcher to examine relationships between topics.</li></ul><p>To be honest, CTM isn’t exactly an out-of-the-box darling of the ML community. However, CTM definitely has its uses (see CTM papers from the last three years on <a href="https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0244839">covid-19 research</a>, <a href="https://link.springer.com/content/pdf/10.1007/s10734-020-00500-x.pdf">higher education research</a>, and <a href="https://www.tandfonline.com/doi/abs/10.1080/23251042.2020.1866281">climate change news</a>) and the intuition behind CTM is a helpful starting point for some pretty cool models.</p><p>Two pretty cool CTM extensions that come to mind:</p><ul><li><a href="https://www.mitpressjournals.org/doi/full/10.1162/tacl_a_00325">The Embedded Topic Model</a></li><li><a href="https://www.structuraltopicmodel.com/">Structural Topic Models</a></li></ul><p>For now, I’m linking to the original papers, but I’m hoping to put out more intuitive guides to embedded and structural topic models in the future. Stay tuned!</p><p>[1] D. Blei, A. Ng., and M. Jordan, <a href="https://www.jmlr.org/papers/volume3/blei03a/blei03a.pdf">Latent Dirichlet Allocation</a> (2003), The Journal of Machine Learning Research.</p><p>[2] D. Blei and J. Lafferty, <a href="https://dl.acm.org/doi/10.5555/2976248.2976267">Correlated Topic Models</a> (2005), NIPS’05: Proceedings of the 18th International Conference on Neural Information Processing Systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76d5baef03d3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/intuitive-guide-to-correlated-topic-models-76d5baef03d3">Intuitive Guide to Correlated Topic Models</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>