<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <author>
    <name>Pranav Chaturvedi</name>
  </author>
  <generator uri="https://hexo.io/">Hexo</generator>
  <id>https://pranavchat.com/</id>
  <link href="https://pranavchat.com/" rel="alternate"/>
  <link href="https://pranavchat.com/atom.xml" rel="self"/>
  <rights>All rights reserved 2026, Pranav Chaturvedi</rights>
  <subtitle>Brain Dumps That Matter</subtitle>
  <title>Pranav Chaturvedi</title>
  <updated>2024-07-19T22:08:21.000Z</updated>
  <entry>
    <author>
      <name>Pranav Chaturvedi</name>
    </author>
    <category term="Poetry" scheme="https://pranavchat.com/tags/poetry/"/>
    <category term="G.K. Chesterton" scheme="https://pranavchat.com/tags/G-K-Chesterton/"/>
    <content>
      <![CDATA[<blockquote>  <p>    Lo! I am come to autumn,<br>       When all the leaves are gold;<br>    Grey hairs and golden leaves cry out<br>       The year and I are old.<br>    <br>    In youth I sought the prince of men,<br>       Captain in cosmic wars,<br>    Our Titan, even the weeds would show<br>       Defiant, to the stars.<br>    <br>    But now a great thing in the street<br>       Seems any human nod,<br>    Where shift in strange democracy<br>       The million masks of God.<br>    <br>    In youth I sought the golden flower<br>       Hidden in wood or wold,<br>    But I am come to autumn,<br>       When all the leaves are gold.  </p>  <footer>― G.K. Chesterton</footer></blockquote>]]>
    </content>
    <id>https://pranavchat.com/2024/07/20/gold-leaves---an-excerpt/</id>
    <link href="https://pranavchat.com/2024/07/20/gold-leaves---an-excerpt/"/>
    <published>2024-07-19T22:08:21.000Z</published>
    <summary>
      <![CDATA[<blockquote>
  <p>
    Lo! I am come to autumn,<br>
       When all the leaves are gold;<br>
    Grey hairs and golden leaves cry out<br>]]>
    </summary>
    <title>Gold Leaves - an Excerpt</title>
    <updated>2024-07-19T22:08:21.000Z</updated>
  </entry>
  <entry>
    <author>
      <name>Pranav Chaturvedi</name>
    </author>
    <category term="Poetry" scheme="https://pranavchat.com/tags/poetry/"/>
    <category term="Shakespeare" scheme="https://pranavchat.com/tags/Shakespeare/"/>
    <content>
      <![CDATA[<blockquote>  <p>    Our revels now are ended. These our actors,<br>    As I foretold you, were all spirits, and<br>    Are melted into air, into thin air;<br>    And, like the baseless fabric of this vision,<br>    The cloud-capped towers, the gorgeous palaces,<br>    The solemn temples, the great globe itself,<br>    Yea, all which it inherit, shall dissolve;<br>    And, like this insubstantial pageant faded,<br>    Leave not a rack behind. We are such stuff<br>    As dreams are made on, and our little life<br>    Is rounded with a sleep.  </p>  <footer>― William Shakespeare, The Tempest (IV.i.148–158)</footer></blockquote>]]>
    </content>
    <id>https://pranavchat.com/2024/07/20/the-tempest---an-excerpt/</id>
    <link href="https://pranavchat.com/2024/07/20/the-tempest---an-excerpt/"/>
    <published>2024-07-19T21:20:37.000Z</published>
    <summary>
      <![CDATA[<blockquote>
  <p>
    Our revels now are ended. These our actors,<br>
    As I foretold you, were all spirits, and<br>
    Are melted into]]>
    </summary>
    <title>The Tempest - an Excerpt</title>
    <updated>2024-07-19T21:20:37.000Z</updated>
  </entry>
  <entry>
    <author>
      <name>Pranav Chaturvedi</name>
    </author>
    <category term="Poetry" scheme="https://pranavchat.com/tags/poetry/"/>
    <category term="Percy Bysshe Shelley" scheme="https://pranavchat.com/tags/Percy-Bysshe-Shelley/"/>
    <content>
      <![CDATA[<blockquote>  <p>    "The One remains, the many change and pass;<br>    Heaven's light forever shines, Earth's shadows fly;<br>    Life, like a dome of many-coloured glass,<br>    Stains the white radiance of Eternity,<br>    Until Death tramples it to fragments.—Die,<br>    If thou wouldst be with that which thou dost seek!<br>    Follow where all is fled!—Rome's azure sky,<br>    Flowers, ruins, statues, music, words are weak<br>    The glory they transfuse with fitting truth to speak."  </p>  <footer>― Percy Bysshe Shelley, <cite>Adonais</cite></footer></blockquote>]]>
    </content>
    <id>https://pranavchat.com/2024/07/18/adonais---An-Excerpt/</id>
    <link href="https://pranavchat.com/2024/07/18/adonais---An-Excerpt/"/>
    <published>2024-07-18T02:37:43.000Z</published>
    <summary>
      <![CDATA[<blockquote>
  <p>
    "The One remains, the many change and pass;<br>
    Heaven's light forever shines, Earth's shadows fly;<br>
    Life,]]>
    </summary>
    <title>Adonais - an Excerpt</title>
    <updated>2024-07-18T02:37:43.000Z</updated>
  </entry>
  <entry>
    <author>
      <name>Pranav Chaturvedi</name>
    </author>
    <category term="GenAI" scheme="https://pranavchat.com/tags/GenAI/"/>
    <category term="LVMs" scheme="https://pranavchat.com/tags/LVMs/"/>
    <content>
      <![CDATA[<blockquote><p>Text-to-Image models like Stable Diffusion struggle with negation as part of the prompt. We explore here why of it, draw parallels with human thought process and discuss technique that has been developed to deal with it.</p></blockquote><h1 id="The-Elephant-in-the-Room"><a href="#The-Elephant-in-the-Room" class="headerlink" title="The Elephant in the Room"></a>The Elephant in the Room</h1><p>Picture this: You ask an AI to draw “anything but a green elephant,” because who wants a green elephant when they look perfectly gorgeous as they are. And what do you get? Lo and behold, a green elephant!</p><p>Let’s dive into the world of Language Vision Models (LVMs) and their struggle with negative instructions.</p><p>To illustrate this phenomenon, let us first see some images generated by the Stable Diffusion 3 model:</p><div style="display: flex; flex-direction: column; align-items: center; width: 100%;">  <div style="margin: 20px 0; text-align: center;">    <img src="/blog_images/2024-06-29-dont-think-of-a-green-elephant.webp" alt="Don't think of a green elephant" style="width: 100%; max-width: 400px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);">    <p><em>Prompt: "Don't think of a green elephant"</em></p>  </div>  <div style="margin: 20px 0; text-align: center;">    <img src="/blog_images/2024-06-29-a-human-without-teeth.webp" alt="A human without teeth" style="width: 100%; max-width: 400px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);">    <p><em>Prompt: "A human without teeth"</em></p>  </div>  <div style="margin: 20px 0; text-align: center;">    <img src="/blog_images/2024-06-29-a-human-without-hair-walking-on-a-non-snowy-road.webp" alt="A human without hair walking on a non-snowy road" style="width: 100%; max-width: 400px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);">    <p><em>Prompt: "A human without hair walking on a non-snowy road"</em></p>  </div></div><p>Okay, third one did get it half-right. But you see the point though.<br><br></p><h1 id="The-Elephant-in-Our-Minds-Human-Thought-Processes"><a href="#The-Elephant-in-Our-Minds-Human-Thought-Processes" class="headerlink" title="The Elephant in Our Minds: Human Thought Processes"></a>The Elephant in Our Minds: Human Thought Processes</h1><p>If we think about it, it’s very similar to how humans behave. When asked not to think of a green elephant, we exactly do that too.</p><p>If I have to break the process down into individual steps, of how I personally do it, it would be like this:</p><ul><li>First, the mind scans for the major words in the sentence.</li><li>Then, mind tries to fetch from one-to-many mapping, visuals, that these words might represent. Specifically, nouns are visualized first, then adjectives, and so on.</li><li>And then, those visuals are combined with different degrees of variations or say weights, to form a coherent image.</li></ul><p>So when someone says “don’t think of a green elephant,” my mind tries to pick up on nouns and adjectives, fetches the visuals that are mapped to the words from past experiences, and then combines them to create a coherent scenery.<br><br></p><h2 id="Scenario-1-Sentence-with-Straight-Forward-Cues"><a href="#Scenario-1-Sentence-with-Straight-Forward-Cues" class="headerlink" title="Scenario 1: Sentence with Straight-Forward Cues"></a>Scenario 1: Sentence with Straight-Forward Cues</h2><p>Take this sentence: </p><blockquote><p>A bright <span style="color:red">red balloon</span> floating gently in a clear <span style="color:skyblue">blue</span> sky.</p></blockquote><p>I wouldn’t presume to know how every mind in the universe works, but if I have to describe it, it would be something like this:</p><ul><li>The mind immediately thinks of “red balloon” almost as if they are not two separate words but one.</li><li>Then the next word mind goes to, is “sky.”</li></ul><p>After the word balloon, mind sort of waits for the next cue. And it is not until the word sky, that it changes the already created scenery and adds to it.<br><br></p><h2 id="Scenario-2-Sentence-with-Not-So-Straight-Forward-Cues"><a href="#Scenario-2-Sentence-with-Not-So-Straight-Forward-Cues" class="headerlink" title="Scenario 2: Sentence with Not So Straight-Forward Cues"></a>Scenario 2: Sentence with Not So Straight-Forward Cues</h2><p>In contrast, let’s think of the sentence:</p><blockquote><p>Imagine the sound of a silent echo.</p></blockquote><p>At most, what I can think of is an echo-chamber. Almost as if there is a gap in the mental map for words like sound, silent, and echo. A musician or an audio engineer might have a different opinion though. Discussion on this topic is a matter for another post.<br><br></p><h2 id="Scenario-3-Sentence-with-Negative-Cue"><a href="#Scenario-3-Sentence-with-Negative-Cue" class="headerlink" title="Scenario 3: Sentence with Negative Cue"></a>Scenario 3: Sentence with Negative Cue</h2><p>What I feel is more difficult to visualize, even for us as humans who are at the top of the cognitive pyramid, is the sentence that has a negative cue.</p><blockquote><p>Don’t think of a green elephant.</p></blockquote><p>By the time I hit the word “think”, it’s already <em>BZZZZT</em> in my mind. The brake was applied, but the train of thought fails to stop. It has already reached the green elephant station. A glorious green elephant stands in the middle of my mind.</p><p>What should I do now? Should I go back and delete it? Of course, I can delete the elephant from the mental scene. But LVMs do not have that luxury.</p><p>And maybe that gives a clue why LVMs struggle with negative instructions.</p><h3 id="What-Goes-on-in-a-Humans-Mind-When-They-See-a-Negative-Cue"><a href="#What-Goes-on-in-a-Humans-Mind-When-They-See-a-Negative-Cue" class="headerlink" title="What Goes on in a Human’s Mind When They See a Negative Cue?"></a>What Goes on in a Human’s Mind When They See a Negative Cue?</h3><p>What happens in the case of a negative cue is that it is interpreted and appended to the scene after the scene has already been visualized. For example, if I am asked not to think of a red apple, I would visualize a red apple first and then append the negative cue to erase the apple from the scene.</p><p>The combination of word negations and their visual counterparts do not exist even for us humans, and there is always a bit of post-processing that happens to erase the visuals of the object from the scene.<br><br></p><h1 id="The-Elephants-Digital-Cousin-How-LVMs-See-the-World"><a href="#The-Elephants-Digital-Cousin-How-LVMs-See-the-World" class="headerlink" title="The Elephant’s Digital Cousin: How LVMs See the World"></a>The Elephant’s Digital Cousin: How LVMs See the World</h1><p>While training, LVMs are shown a vast amount of data. And through the course of training, they associate words with their visual counterparts on the basis of their co-occurrence. It creates sort of a loose mapping between words and features of objects they have seen.</p><p>What LVMs lack is the mapping of negation of each of those words and their corresponding visual representations. This limitation comes from the fact that during training, LVMs are primarily exposed to positive associations between words and images. They learn to generate images based on what should be present, rather than what should be absent.</p><p>The sequential nature of text processing in these models means that by the time a negative instruction is processed, the model may have already activated the visual features associated with the negated concept. Unlike us humans, who can consciously suppress and modify mental images, LVMs lack this flexible, top-down control over their generative process.</p><p>For LMs to work with negations, they need to be trained with a lot of negation data. But that’s quite a bit of a challenge. There are so many questions to be answered for that.</p><ul><li>How would the negation data look like?</li><li>Do we go about labeling all the images not containing balloons as not-balloons?</li><li>In the case of the instruction “Don’t create a balloon,” what should the model create? Should it create an empty space? Is that even a valid instruction?</li><li>What is the good way to include negation data in the training?</li></ul><p>There is no good way.<br><br></p><h1 id="The-Elephants-Eraser-Negative-Prompts-to-the-Rescue"><a href="#The-Elephants-Eraser-Negative-Prompts-to-the-Rescue" class="headerlink" title="The Elephant’s Eraser: Negative Prompts to the Rescue"></a>The Elephant’s Eraser: Negative Prompts to the Rescue</h1><p>And so comes the idea of negative prompts. It is an auxiliary optional input prompt that goes with the primary prompt where we can mention something that we don’t want the model to generate.</p><p>It is a nice way of moving the model away from a feature space that belongs to the things we don’t want them to generate.</p><p>Practically, what it does is it subtracts the embeddings of the negative prompt text from the embeddings of the positive prompt text.</p><p>Here’s a simplified example of how it works internally: </p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">positive_prompt_embedding = get_embedding(<span class="string">&quot;A human&quot;</span>)</span><br><span class="line">negative_prompt_embedding = get_embedding(<span class="string">&quot;teeth&quot;</span>)</span><br><span class="line"></span><br><span class="line">final_embedding = positive_prompt_embedding - negative_prompt_embedding</span><br><span class="line"></span><br><span class="line">generated_image = generate_image_from_embedding(final_embedding)</span><br></pre></td></tr></table></figure><br>And what happens when these negative prompts are applied to the model? Here are some of the results generated by the Stable Diffusion 3 model with the negative prompts:<div style="display: flex; flex-direction: column; align-items: center; width: 100%;">  <div style="margin: 20px 0; text-align: center;">    <img src="/blog_images/2024-06-29-dont-think-of-a-green-elephant-negative-prompt.webp"     alt="Don't think of a green elephant" style="width: 100%; max-width:     400px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);">    <p><em>Prompt: "Think of an elephant"</em></p>    <p><em>Negative Prompt: "green"</em></p>  </div>  <div style="margin: 20px 0; text-align: center;">    <img src="/blog_images/2024-06-29-a-human-without-teeth-negative-prompt.webp" alt="A human     without teeth" style="width: 100%; max-width: 400px; border-radius:     10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);">    <p><em>Prompt: "A human"</em></p>    <p><em>Negative Prompt: "teeth"</em></p>  </div>  <div style="margin: 20px 0; text-align: center;">    <img src="/blog_images/2024-06-29-a-human-without-hair-walking-on-a-non-snowy-road-negative-prompt.webp" alt="A human walking on a road" style="width: 100%; max-width: 400px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);">    <p><em>Prompt: "A human walking on a road"</em></p>    <p><em>Negative Prompt: "hair, snow"</em></p>  </div></div><p>In above cases, the prompt in itself would have been enough to generate these images, but the negative prompts help the model move further away from the features that we don’t want the model to generate.</p><br><p>If you found this article useful, please cite it as:</p><blockquote><p>Chaturvedi, Pranav. (June 2024). Don’t Think of a Green Elephant. <a href="https://pranavchat.com/lvms/2024/06/29/dont-think-of-a-green-elephant/">https://pranavchat.com/lvms/2024/06/29/dont-think-of-a-green-elephant/</a></p></blockquote><p>or</p><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">@article&#123;chaturvedi2024elephant,</span><br><span class="line">  title   = &#123;Don&#x27;t Think of a Green Elephant&#125;,</span><br><span class="line">  author  = &#123;Chaturvedi, Pranav&#125;,</span><br><span class="line">  journal = &#123;pranavchat.com&#125;,</span><br><span class="line">  year    = &#123;2024&#125;,</span><br><span class="line">  month   = &#123;June&#125;,</span><br><span class="line">  url     = &#123;https://pranavchat.com/lvms/2024/06/29/dont-think-of-a-green-elephant/&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><br><h2 id="Attributions"><a href="#Attributions" class="headerlink" title="Attributions"></a>Attributions</h2><p>Stable Diffusion 3. Response to “Don’t think of a green elephant”. AI-generated image. STABILITY AI LTD, 2024. <a href="https://stability.ai/stable-diffusion">Stable Diffusion</a></p><p>Stable Diffusion 3. Response to “A human without teeth”. AI-generated image. STABILITY AI LTD, 2024. <a href="https://stability.ai/stable-diffusion">Stable Diffusion</a></p><p>Stable Diffusion 3. Response to “A human without hair walking on a non-snowy road”. AI-generated image. STABILITY AI LTD, 2024. <a href="https://stability.ai/stable-diffusion">Stable Diffusion</a></p><p>Stable Diffusion 3. Response to “Think of an elephant” with negative prompt “green”. AI-generated image. STABILITY AI LTD, 2024. <a href="https://stability.ai/stable-diffusion">Stable Diffusion</a></p><p>Stable Diffusion 3. Response to “A human” with negative prompt “teeth”. AI-generated image. STABILITY AI LTD, 2024. <a href="https://stability.ai/stable-diffusion">Stable Diffusion</a></p><p>Stable Diffusion 3. Response to “A human walking on a road” with negative prompt “hair, snow”. AI-generated image. STABILITY AI LTD, 2024. <a href="https://stability.ai/stable-diffusion">Stable Diffusion</a></p>]]>
    </content>
    <id>https://pranavchat.com/lvms/2024/06/29/dont-think-of-a-green-elephant/</id>
    <link href="https://pranavchat.com/lvms/2024/06/29/dont-think-of-a-green-elephant/"/>
    <published>2024-06-28T18:49:59.000Z</published>
    <summary>
      <![CDATA[<blockquote>
<p>Text-to-Image models like Stable Diffusion struggle with negation as part of the prompt. We explore here why of it, draw par]]>
    </summary>
    <title>Don't Think of a Green Elephant</title>
    <updated>2024-06-28T18:49:59.000Z</updated>
  </entry>
  <entry>
    <author>
      <name>Pranav Chaturvedi</name>
    </author>
    <category term="GenAI" scheme="https://pranavchat.com/tags/GenAI/"/>
    <category term="LLMs" scheme="https://pranavchat.com/tags/LLMs/"/>
    <category term="Sampling" scheme="https://pranavchat.com/tags/Sampling/"/>
    <content>
      <![CDATA[<blockquote><p>LLMs are known to show creativity and produce diverse outputs. But how do they do it?<br>This post explores various methods to achieve diversity and creative unpredictability in LLM outputs.</p></blockquote><h1 id="Determinism-in-LLM-Outputs"><a href="#Determinism-in-LLM-Outputs" class="headerlink" title="Determinism in LLM Outputs"></a>Determinism in LLM Outputs</h1><p>Large Language Models (LLMs), by design, exhibit non-deterministic behavior. This means that they do not generate identical responses to the same input across different instances. As a result, each query, even if repeated under similar conditions, can yield varied outcomes. This variability is fundamental to the design of LLMs, enhancing their ability to produce diverse and creative outputs.</p><p>Take for example these two responses:</p><p><span style="color:blue"><strong>Input:</strong></span> Answer in 10 words. What is an apple?.</p><p><span style="color:green"><strong>Response 1:</strong></span> A juicy, sweet, and crunchy fruit that grows on trees.</p><p><span style="color:green"><strong>Response 2:</strong></span> A juicy, sweet, and crunchy fruit that’s often eaten fresh.<br><br></p><p><u>At the core of the difference is the way the next token are sampled.</u><br><br></p><p>To illustrate this point, let’s take an example of “A quick brown fox”. </p><p>Given these words as input, model will generate next token in the sequence which according to common knowledge, is “jumps”. So, the model will assign highest probability to “jumps” token. </p><p><span style="color:blue"><strong>Input:</strong></span> A quick brown fox </p><p>The model will take these input words as token and output logits(logprobs) for each token in the vocabulary for the next token prediction. These logits are converted to normalized probabilities using Softmax function.<br><br></p><p>Normalized Probabilities:</p><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">tensor([[0.01, 0.05, 0.2, 0.02, ...]])</span><br></pre></td></tr></table></figure><p>The next step involves selecting a probability that corresponds to the next token in the sequence. A straightforward approach might be to simply choose the highest probability. However, this method is not optimal as it leads to deterministic behavior in the model’s output.</p><p>The deterministic method has several drawbacks:</p><ul><li>During the inference phase, the tokens generated by the model are fed back as input for next predictions. If these tokens are inaccurate, the errors are perpetuated through each cycle of feedback, leading to a degradation in the quality of the output.</li><li>Additionally, deterministic selection tends to cause repetitive sequences of tokens. Such repetition can render the text output unnatural, robotic, and lacking in coherence.</li></ul><p>To enhance the quality and variability of the output, it is preferable to employ a <strong>sampling method</strong>. This method involves selecting the next token based on a probabilistic distribution of the predicted probabilities, rather than merely choosing the token with the highest probability.</p><h1 id="Sampling"><a href="#Sampling" class="headerlink" title="Sampling"></a>Sampling</h1><p>Sampling refers to the technique of selecting a specific subset from a larger set of data, which in this context is referred to as the population. </p><p>In the case of language models, this subset consists of a single token chosen from the output probabilities of the entire vocabulary. This selection process is crucial and acts as a control knob for diverse and contextually appropriate responses.</p><h2 id="Sampling-from-a-Multinomial-Distribution"><a href="#Sampling-from-a-Multinomial-Distribution" class="headerlink" title="Sampling from a Multinomial Distribution"></a>Sampling from a Multinomial Distribution</h2><p>The selection of the next token in a sequence is performed using a probabilistic approach based on a multinomial distribution. Here’s how it works:</p><ol><li><p><strong>Probability Assignment:</strong> First, the model computes the logits for each potential next token and applies the softmax function to convert these logits into normalized probabilities.</p></li><li><p><strong>Random Sampling:</strong> A random number between 0 and 1 is generated. This number is used to select a token whose cumulative probability exceeds this random value.</p></li></ol><p>For instance, consider the phrase “A quick brown fox”. After processing this input, the model predicts the probabilities for potential next tokens. Let’s explore how the token “jumps” might be selected based on these probabilities:</p><ul><li>The model calculates the logits for each possible next token and applies the softmax function to derive the probabilities.</li><li>A random number is generated. The token corresponding to the first cumulative probability that is greater than this random number is chosen as the next token in the sequence.</li></ul><p>This method ensures that while the most probable token (“jumps” in our example) is often selected, there is still room for less likely tokens to be chosen occasionally, and as a result introducing variability and creativity in the text generated by the model.</p><h2 id="Example-of-Token-Selection-Using-Cumulative-Probabilities"><a href="#Example-of-Token-Selection-Using-Cumulative-Probabilities" class="headerlink" title="Example of Token Selection Using Cumulative Probabilities"></a>Example of Token Selection Using Cumulative Probabilities</h2><p>Consider the following table which lists tokens along with their individual and cumulative probabilities:</p><table><thead><tr><th>Token</th><th>Probability</th><th>Cumulative Probability</th></tr></thead><tbody><tr><td>sits</td><td>0.01</td><td>0.01</td></tr><tr><td>runs</td><td>0.05</td><td>0.06</td></tr><tr><td>jumps</td><td>0.2</td><td>0.26</td></tr><tr><td>disappears</td><td>0.02</td><td>0.28</td></tr></tbody></table><p>Imagine a scenario where a random number, say 0.15, is generated to determine the next token. The selection process would proceed as follows:</p><table><thead><tr><th>Token</th><th>Probability</th><th>Cumulative Probability</th><th>Random Number</th><th>Selection Outcome</th></tr></thead><tbody><tr><td>sits</td><td>0.01</td><td>0.01</td><td>0.15</td><td>Not Selected</td></tr><tr><td>runs</td><td>0.05</td><td>0.06</td><td>0.15</td><td>Not Selected</td></tr><tr><td>jumps</td><td>0.2</td><td>0.26</td><td>0.15</td><td>Selected</td></tr><tr><td>disappears</td><td>0.02</td><td>0.28</td><td>0.15</td><td>-</td></tr></tbody></table><p>In this example, the token “jumps” is selected because its cumulative probability of 0.26 is the first to exceed the random number of 0.15. This illustrates how the model can select a token based on a probabilistic approach, ensuring that while the most probable token is often chosen, other less likely tokens can also be selected occasionally, thereby adding diversity and unpredictability to the generated text.</p><p>The technique of choosing the next token from a set of possible tokens is known as sampling from a Multinomial Distribution.</p><p>Why is it called multinomial? The term multinomial is used because the selection isn’t binary; instead, there are multiple potential tokens that could be chosen next, each with its own associated probability. This method reflects the reality that multiple outcomes are possible, each with a different likelihood.</p><h2 id="Why-this-approach-is-effective"><a href="#Why-this-approach-is-effective" class="headerlink" title="Why this approach is effective?"></a>Why this approach is effective?</h2><div style="background-color: #f0f0f0; padding: 10px; border-radius: 5px;">  <img src="/blog_images/cumulative_probs.svg" alt="Cumulative Probability" style="max-width: 100%; height: auto;"></div><p>This method is effective because a randomly generated number is more likely to fall within a range that corresponds to a higher probability category. As illustrated in the figure above, the category with a probability of 0.5 covers a larger section of the probability range (from 0.5 to 1). Therefore, it’s statistically more likely for the random number to fall within this range, leading to the selection of the corresponding token.</p><h1 id="Ways-to-control-determinism"><a href="#Ways-to-control-determinism" class="headerlink" title="Ways to control determinism"></a>Ways to control determinism</h1><p>In the context of token selection, once we have established probabilities for all potential tokens in our vocabulary, we can apply further filtering techniques such as Top-k and Top-p sampling to refine our selection process.</p><h2 id="Top-k-Sampling"><a href="#Top-k-Sampling" class="headerlink" title="Top-k Sampling"></a>Top-k Sampling</h2><p>Top-k sampling involves selecting the k tokens with the highest probabilities and then randomly sampling from this subset. This method allows us to control the diversity and creativity of the generated text. By reducing the value of k, we narrow the pool of likely tokens, making the output more deterministic and predictable, as lower probability tokens are excluded from the selection process.</p><h2 id="Top-p-Sampling"><a href="#Top-p-Sampling" class="headerlink" title="Top-p Sampling"></a>Top-p Sampling</h2><p>Top-p sampling, on the other hand, is similar to Top-k but focuses on the cumulative probability. Instead of selecting a fixed number of tokens (k), it selects all tokens whose cumulative probabilities exceed a predefined threshold (p). For example, if we set top-p to 0.5:</p><ul><li>We first sort the token probabilities in descending order.</li><li>We then calculate the cumulative probability and continue to add tokens until the cumulative probability exceeds 0.5.</li><li>Finally, we sample a token from this refined subset.</li></ul><p>This method ensures that the selection is not just limited to the most probable tokens but also includes any token that collectively contributes to reaching the threshold probability, thus maintaining a balance between predictability and variability in the generated text.</p><h2 id="Logit-Scaling-Temperature"><a href="#Logit-Scaling-Temperature" class="headerlink" title="Logit Scaling (Temperature):"></a>Logit Scaling (Temperature):</h2><p>Logit scaling, controlled by a temperature parameter, adjusts the distribution of token probabilities. A temperature below 1 sharpens the distribution, amplifying higher probabilities and leading to the selection of more probable tokens. </p><p>Conversely, a temperature above 1 flattens the distribution, boosting lower probabilities and increasing diversity but potentially reducing coherence. This technique allows for a customizable balance between predictability and creativity in text generation.</p><p>Hint: The scaling follows graph of hyperbolic tangent function.</p><p>Here is the implementation of some of the techniques discussed in the blog provided by Andrej Karpathy in the nanoGPT project:<br><a href="https://github.com/karpathy/nanoGPT/blob/325be85d9be8c81b436728a420e85796c57dba7e/model.py#L306">Generate from nanoGPT</a></p><blockquote><p>Chaturvedi, Pranav. (June 2024). How LLMs Introduce Creativity. <a href="https://pranavchat.com/llms/2024/05/12/sampling-in-llms.html">https://pranavchat.com/llms/2024/05/12/sampling-in-llms.html</a></p></blockquote><p>or</p><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">@article&#123;chaturvedi2024sampling,</span><br><span class="line">  title   = &#123;How LLMs Introduce Creativity&#125;,</span><br><span class="line">  author  = &#123;Chaturvedi, Pranav&#125;,</span><br><span class="line">  journal = &#123;pranavchat.com&#125;,</span><br><span class="line">  year    = &#123;2024&#125;,</span><br><span class="line">  month   = &#123;May&#125;,</span><br><span class="line">  url     = &#123;https://pranavchat.com/llms/2024/05/12/sampling-in-llms.html&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h1 id="Attributions"><a href="#Attributions" class="headerlink" title="Attributions"></a>Attributions</h1><ul><li><a href="https://github.com/karpathy/nanoGPT/blob/325be85d9be8c81b436728a420e85796c57dba7e/model.py#L306">nanoGPT Implementation</a> by Andrej Karpathy</li></ul>]]>
    </content>
    <id>https://pranavchat.com/llms/2024/05/12/sampling-in-llms.html</id>
    <link href="https://pranavchat.com/llms/2024/05/12/sampling-in-llms.html"/>
    <published>2024-05-11T21:28:35.000Z</published>
    <summary>
      <![CDATA[<blockquote>
<p>LLMs are known to show creativity and produce diverse outputs. But how do they do it?<br>This post explores various methods]]>
    </summary>
    <title>How LLMs Introduce Creativity</title>
    <updated>2024-05-11T21:28:35.000Z</updated>
  </entry>
</feed>
