<?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 Shuyang Xiang on Medium]]></title>
        <description><![CDATA[Stories by Shuyang Xiang on Medium]]></description>
        <link>https://medium.com/@vanillaxiangshuyang?source=rss-9b74bc8c860d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NRQ1LYFkqecDb58ktvTGmg.jpeg</url>
            <title>Stories by Shuyang Xiang on Medium</title>
            <link>https://medium.com/@vanillaxiangshuyang?source=rss-9b74bc8c860d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:39:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vanillaxiangshuyang/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[Talking About Math with a Kindergartener]]></title>
            <link>https://medium.com/@vanillaxiangshuyang/talking-about-math-with-a-kindergartener-b44a13d879e1?source=rss-9b74bc8c860d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b44a13d879e1</guid>
            <category><![CDATA[maths-tutor]]></category>
            <category><![CDATA[children]]></category>
            <dc:creator><![CDATA[Shuyang Xiang]]></dc:creator>
            <pubDate>Fri, 10 Oct 2025 07:49:21 GMT</pubDate>
            <atom:updated>2025-10-10T07:49:21.672Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gApFJdMClkjT9HeB9Rg8Aw.png" /></figure><h3>A Programming Game</h3><p>One day in August, I was working from home. My little one was bored, climbed onto my lap, and watched my screen full of python code. The long afternoon hummed with cicadas, and both of us were yawning in front of lines of code.</p><p>He asked me, “Is your job just typing whatever on the screen? And you get money for that?”</p><p>I wanted to say no but couldn’t really find another argument. We were both tired and I decided to have a rest. I drew two dots on the floor with some red chalk — one for the start, one for the finish — and connected them with zigzag lines. I said, “Now you’re a robot. I can tell you only three things: go forward one step, turn left, or turn right. Let’s see how you can get from start to finish.”</p><p>Five days lasted that simple programming game. On the fifth day, I would like to try the idea of loops — “do something until…” But it seemed too hard to explain that concept to a small kid. I let it go.</p><p>Still, I opened a google doc and recorded what had happened the last five days. I was thinking: when his logical thinking matures enough to understand loops, we’ll try again. Then, I thought — since I’m already writing these words — why not keep a log of all our math-related conversations?</p><h3>School Mathematics</h3><p>Until high school graduation, I was just so so at math for years.</p><p>When I chose mathematics as my undergraduate major, it was just to prove a point— “I can’t believe I just <em>can’t</em> do well in maths.” And…the more I studied it, the more beautiful the mathematical world became.</p><p>One day in college, I was working on a problem in the library on the second floor. The moment I reached the solution after two hours, sunlight was pouring through the window, and I felt as if some celestial being had unlocked a hidden channel in my brain. After so many years, I finally <em>loved</em> math.</p><p>Looking back, it wasn’t some miraculous “awakening.” Not at all. It was just that school education had hidden math’s true essence. I never had time or space to feel what it <em>really</em> meant. My logical mind back then wasn’t mature enough to understand a theorem or an algorithm, yet I was expected to memorize them anyway.</p><p>That’s why I’m against children being pushed too hard academically: some subjects — or the ways they are taught — are inherently hard to grasp. Scoring high on tests doesn’t mean that knowledge becomes part of you.</p><p>I never became a mathematician, but math — like literature — has become a refuge for me, a quiet place in the noisy world. And that is enough.</p><p>I know one day my child will enter the school system, learning strange and arbitrary things he’s told to memorize.</p><p>One day he asked me, “Why are you already thirty-something but not taller than teenagers?” I realized that to him, height and age <em>should</em> be proportional — many things we take for granted are incomprehensible in his logic.</p><p>So while he’s still at the playful stage, I’ll only talk about what his mind can grasp — show him the simple beauty behind deep mathematical ideas.</p><p>The following are excerpts from my notes over the past two months.</p><h3>More Than Arithmetic</h3><p>One evening I asked, “Which are there more of — rectangles or squares?”</p><p>Without hesitation he said, “Squares, because stores are squares.” (Whatever that meant!)</p><p>I asked, “Can you explain what a square is?”<br> “It has four sides.”<br> “But rectangles have four sides too.”<br> “Yes, but rectangles are squished.”</p><p>I didn’t press further — maybe I’ll ask again six months later.</p><p>Then we played a “find the odd one out” game: rabbit, panda, snake, suitcase.<br> “Which one is different?”<br> “The suitcase.”<br> “Why?”<br> “The rabbit and panda are round, but the suitcase isn’t.”<br> “What about the snake?”<br> “The snake is a line. But you can twist it to make a circle too.”</p><p>I took the chance to explain a simple Venn diagram: one circle can represent a group — for example, rabbit, panda, and snake in one, suitcase in another.</p><p>Before bed, he asked, “Didn’t you say we’d do math today? We didn’t!”<br> I said, “But we did!”</p><p>He wrote down something like <em>14851 + 3841</em> on paper and said, “Then do this math!” Clearly, even at his age, he had already formed the idea that “math” means hard arithmetic.</p><p>Equating math with arithmetic is, of course, wrong. I don’t want to drill pure calculation with him — when I was little, I often got answers wrong, or the format wrong even when the answer was right. But arithmetic <em>does</em> have meaning beyond numbers.</p><p>Once, I bought a 250 ml can of pineapple juice and poured 150 ml for him. I said, “That’s enough for now. I’ll save the rest for you.” But the juice looked too tempting, so I secretly drank a couple of sips, thinking he wouldn’t notice.</p><p>After dinner, he poured out the rest and said, “This isn’t 100 ml — it’s only 80! Mommy, you drank some!”</p><p>I had to confess and apologize.</p><p>There were other arithmetic moments, but honestly, they’re less interesting. Sure, you can do subtraction to check if Mommy stole juice — but without a <em>real</em> reason, what’s the point of doing math? Motivation matters more than correct answers.</p><p>Still, arithmetic has fun rules too.</p><p>One night, when he again made me do big addition problems, I decided to talk about the <em>commutative property</em>.</p><p>I said, “Sometimes order matters. You can’t go to kindergarten before you wake up, or go to sleep before brushing your teeth. But look — if I buy one apple and then two, or two and then one, it’s the same.”</p><p>He thought for a moment. “Right, today at kindergarten I found that 8 + 1 and 1 + 8 are the same. I tried both!”</p><p>I asked, “Then do you think 100,000 + 200,000 and 200,000 + 100,000 are the same?”<br> “Yeah.”<br> “Any numbers?”<br> He hesitated, then said, “Yes, all of them.”</p><h3>Probability and Combinations</h3><p>Beyond integers come fractions. One day, walking past the train station, I said, “Did you know there’s a strike today? The news says only three-fourths of trains are running.”</p><p>He asked, “What’s three-fourths?”</p><p>I gave a quick explanation, thinking maybe next time we could use musical notes to explain fractions, since he’d learned basic staff notation at kindergarten — and maybe one day even talk about harmonic series.</p><p>If he could grasp fractions, maybe we could talk about probability or combinations next.</p><p>Of course, probability is not so easy. For several evenings we played two games:</p><ol><li>Put socks (or marbles, or paper pieces) of different colors in a bag and take turns drawing until someone gets two of the same color.</li><li>Draw a 4×4 grid on paper with numbers 1–16. Each player has three tokens. Every round, we bet on one number, roll three dice, and if the total matches a number someone bet on, that player wins all tokens on the grid.</li></ol><p>At first, he always bet on 16 — but soon realized that was impossible. Then he switched to 4. He noticed 2 rarely came up, but didn’t realize some numbers were more likely than others. He lost. Later he switched to 9, but still lost.</p><p>At the end, he said, “It feels like 6 and 7 show up a lot.”</p><p>Close observation indeed.</p><p>Probability led naturally to combinations.</p><p>One day I drew several strings of five beads each and asked him to color any two blue. “How many different ways can you do that?”</p><p>He did four combinations, then stopped. Interestingly, his method was systematic: he fixed the first blue bead and moved the second one along. But when those were exhausted, he didn’t think of moving the <em>first</em> bead — he just said, “I don’t want to do it anymore.”</p><p>I didn’t push. Maybe next time I’ll make it a “gold mining” game instead.</p><h3>Geometry and Spatial Sense</h3><p>Numbers and algebra are abstract, but we live in three dimensions — our experience naturally nurtures geometric intuition.</p><p>His geometric sense mostly comes from LEGO. One night, he built a tower. I put it on the table and said, “Build another tower on the floor with the same height.” He counted the blocks, used the same number and kind, and made one.</p><p>Then I asked, “What if I don’t let you use the same kind of blocks?” He didn’t answer.</p><p>A few days later, he spent an afternoon building new shapes by himself. I looked and thought, <em>Ah — he’s discovered area conservation!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VI_XdG7QOhNtSBY1U91KxQ.jpeg" /></figure><p>LEGO is a great math tool. I’ve designed other math activities with it, but usually we forget to finish — because play is more important than math.</p><p>Another day before lunch, I suddenly thought of floor plans. I asked him to draw one for our living room, bathroom, and kitchen. The drawing was rough but surprisingly accurate in layout and proportions.</p><h3>Codes and Symbols</h3><p>Last night, I told him about cryptography — why we use codes, how to encrypt and decrypt.</p><p>I wrote a sentence and showed him a simple substitution cipher: shift each letter by one, so <em>b</em> replaces <em>a</em>, <em>c</em> replaces <em>b</em>, and so on. For example: “J xbou b cbobob.”</p><p>He thought for a moment and invented his own system: replace <em>e</em> with <em>a</em>, <em>o</em> with <em>c</em>, and <em>u</em> with <em>v</em>. Then he challenged me to decode. Later he started using numbers and musical notes as codes. He realized he could use the position of letters in the alphabet as a cipher, and before I knew it, I was flooded with encrypted sentences for half an hour before bedtime.</p><p>Reading that note again today, I realized: using <em>b</em> for <em>a</em> is logically the same as using <em>x</em> to stand for all apples. Maybe understanding ciphers can help with the abstraction of algebraic symbols — using <em>x</em> to represent apples, pears, or bananas instead of drawing them or writing their names.</p><p>But that’s for later.</p><p>May play linger in his world a little longer.</p><p>And one last thing: if you don’t love math yourself, don’t force yourself to teach it just because “math is useful.” Whatever you love — play <em>that</em> with your child.</p><p>And finally, most importantly: next time, buy two cans of pineapple juice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b44a13d879e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading Kafka again, at the time of LLM]]></title>
            <link>https://medium.com/operations-research-bit/reading-kafka-again-at-the-time-of-llm-0405abc42407?source=rss-9b74bc8c860d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0405abc42407</guid>
            <dc:creator><![CDATA[Shuyang Xiang]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 19:30:41 GMT</pubDate>
            <atom:updated>2025-06-03T13:31:09.438Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>I find myself more and more like … a giant beetle.</strong></h4><p><strong>I find myself more and more like … a giant beetle.</strong></p><p>In the time of big data and artificial intelligence, human communication is becoming increasingly homogenized and standardized.</p><p>Whether in real-life or social media conversations, everything seems polished by some invisible standard. Drown in these words, I often feel as if they are pre-written scripts, programmed in a way that would trigger an error if anything falls out of the allowed rules. I can’t find any errors in my everyday conversation surrounded by people, but I also feel no warmth from it. Little by little, I have grown silent. At meetings and social gatherings, I become part of the background, a mere decoration, a … ballon. I have no interest in discussing real estate or investments, nor do I have anything about my kids to share. Loving life have to mean going to the beach during the summer vacation; if you don’t buy expensive products, you don’t love yourself enough.</p><p>During the weekend, all I did was just reading a good book or discovering an interesting maths algorithm. But when I speak out, people cry at me, “Can you stop talking about maths?” No, my body has not transformed, yet the environment has pushed me into a dark corner, as if I am a beetle. I crawl alone on the ceiling, as an anomaly.</p><p>The internet, as an extension of reality, takes this to a greater level. Many voices seem to express themselves, but their messages sound like each other.</p><p>Society has standardized rules and laws. This was the case in Kafka’s time, and it remains the same in mine. Nothing has ever changed. From or even before were are born, being “normal” and “successful” are pre-defined within a strict framework. If you don’t follow, you are a beast. Don’t agree? That’s just jealous because you are succeful enough.</p><p>Everyone is discussing LLM, which themselves arise from these standard social rules. They are trained on massive amounts of text born from these standards. The way they are trained and optimized ensures that their responses are also somehow standardized — they have to be “reasonable,” “widely acceptable.” During training, outliers are systematically weakened; expressions that exceed conventions are also marked as outliers, erased by the algorithm in the end.</p><p>The loss function is designed to reduce errors in a global sense, making sure that AI’s output is consistent with a unified human understanding. But whose understanding is it, to be serious? It is the dominant voice of society and the capitalism, the standard reinforced by the social media. But that is not my understanding of the world! And so, while these models become increasingly accurate, they may also filter out different voices.</p><p>A thousand people may have a thousand understanding of Hamlets, but they must be similar versions of Hamlet. And AI? It turns those similarities into a single standardized answer with even smaller or no deviation.</p><p>Yes, we are happy to realize AI can truly “speak,” our daily production is increasingly dependent on LLMs. The things it says converge to norms even more precisely than our human speech does.</p><p>I don’t know if the standardization of language led by AI will lead to a standardization of human thoughts, making the society that already struggles to bear any “difference” even unable to accept the beetle on the ceiling, someone different.</p><p>After Gregor Samsa transformed into a beetle in the novel, his existence became an embarrassment for people he loved. A man who used be the support of his whole family became a total outcast. Even his beloved little sister, when he crawled out of his room wanting to kiss her as she was playing the violin, ultimately hated him and wanted him to die. In the end, he was left to be forgotten in the shadows.</p><p>On this late lonely night, reading <em>The Metamorphosis</em>, I finally understand Kafka’s loneliness. Countless times, I have sat in lively social meetings that I had no chance to avoid, only to find myself pushed to the corners like Gregor. They discuss forever mainstream and so-called hot topics, but I no longer — or want to — understand what they are saying. I reach out to touch this world many many times, but it has become so polished, without a flaw, without an edge for different people to grasp.</p><p>Gregor’s loneliness came from becoming a complete insecte. My loneliness comes from still being human — giving up to become a standardized human.</p><p>The world no longer seems to need real conversation; it only needs answers within prediction of a very good accuracy score and thoughts that don’t obey the order. Individuality and difference is increasingly regarded as noise. Gregor’s story ends with his death, his body swept out of the house, and his family finally returned to pease.</p><p>But in the end, who is it that truly transformed? Those who follow to norms, who submit to the rules — were they those who really undergone a metamorphosis? We are all born as unique human, yet as soon as we walk into society, we begin speaking the same words and pursuing the same goals. Isn’t it a real metamorphosis?</p><p>And yet, I still want to have my own voice — even if it sounds like the ugly rustling of an insect.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0405abc42407" width="1" height="1" alt=""><hr><p><a href="https://medium.com/operations-research-bit/reading-kafka-again-at-the-time-of-llm-0405abc42407">Reading Kafka again, at the time of LLM</a> was originally published in <a href="https://medium.com/operations-research-bit">Operations Research Bit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sparse AutoEncoder: from Superposition to interpretable features]]></title>
            <link>https://medium.com/data-science/sparse-autoencoder-from-superposition-to-interpretable-features-4764bb37927d?source=rss-9b74bc8c860d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4764bb37927d</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[interpretability]]></category>
            <dc:creator><![CDATA[Shuyang Xiang]]></dc:creator>
            <pubDate>Sat, 01 Feb 2025 18:02:21 GMT</pubDate>
            <atom:updated>2025-02-01T18:02:21.841Z</atom:updated>
            <content:encoded><![CDATA[<h4>Disentangle features in complex Neural Network with superpositions</h4><p><strong>Complex neural networks</strong>, such as Large Language Models (LLMs), suffer quite often from <strong>interpretability</strong> challenges. One of the most important reasons for such difficulty is <strong>superposition</strong> — a phenomenon of the neural network having fewer dimensions than the number of features it has to represent. For example, a toy LLM with 2 neurons has to present 6 different language features. As a result, we observe often that a single neuron needs to activate for multiple features. For a more detailed explanation and definition of superposition, please refer to my previous <a href="https://medium.com/towards-data-science/superposition-what-makes-it-difficult-to-explain-neural-network-565087243be4">blog post</a>: “Superposition: What Makes it Difficult to Explain Neural Network”.</p><p>In this blog post, we take one step further: let’s try to disentangle some fsuperposed features. I will introduce a methodology called <strong>Sparse Autoencoder</strong> to decompose complex neural network, especially LLM into interpretable features, with a toy example of language features.</p><h3>Sparse AutoEncoder</h3><p>A <strong>Sparse Autoencoder</strong>, by definition, is an Autoencoder with sparsity introduced on purpose in the activations of its hidden layers. With a rather simple structure and light training process, it aims to decompose a complex neural network and uncover the features in a more interpretable way and more understandable to humans.</p><p>Let us imagine that you have a trained neural network. The autoencoder is not part of the training process of the model itself but is instead a post-hoc analysis tool. The original model has its own activations, and these activations are collected afterwards and then used as input data for the sparse autoencoder.</p><p>For example, we suppose that your original model is a neural network with one hidden layer of 5 neurons. Besides, you have a training dataset of 5000 samples. You have to collect all the values of the 5-dimensional activation of the hidden layer for all your 5000 training samples, and they are now the input for your sparse autoencoder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jUULgu9bp3MjADynOa-fEg.png" /><figcaption>Image by author: Autoencoder to analyse an LLM</figcaption></figure><p>The autoencoder then learns a new, sparse representation from these activations. The encoder maps the original MLP activations into a new vector space with higher representation dimensions. Looking back at my previous 5-neuron simple example, we might consider to map it into a vector space with 20 features. Hopefully, we will obtain a sparse autoencoder effectively decomposing the original MLP activations into a representation, easier to interpret and analyze.</p><p>Sparsity is an important in the autoencoder because it is necessary for the autoencoder to “disentangle” features, with more “freedom” than in a dense, overlapping space.. Without existence of sparsity, the autoencoder will probably the autoencoder might just learn a trivial compression without any meaningful features’ formation.</p><h3>Toy Model</h3><h4>Language model</h4><p>Let us now build our toy model. I beg the readers to note that this model is not realistic and even a bit silly in practice but it is sufficient to showcase how we build sparse autoencoder and capture some features.</p><p>Suppose now we have built a language model which has one particular hidden layer whose activation has three dimensions. Let us suppose also that we have the following tokens: “cat,” “happy cat,” “dog,” “energetic dog,” “not cat,” “not dog,” “robot,” and “AI assistant” in the training dataset and they have the following activation values.</p><pre>data = torch.tensor([<br>    # Cat categories<br>    [0.8, 0.3, 0.1, 0.05],  # &quot;cat&quot;<br>    [0.82, 0.32, 0.12, 0.06],  # &quot;happy cat&quot; (similar to &quot;cat&quot;)<br>    # Dog categories<br>    [0.7, 0.2, 0.05, 0.2],  # &quot;dog&quot;<br>    [0.75, 0.3, 0.1, 0.25],  # &quot;loyal dog&quot; (similar to &quot;dog&quot;)<br>    <br>    # &quot;Not animal&quot; categories<br>    [0.05, 0.9, 0.4, 0.4],  # &quot;not cat&quot;<br>    [0.15, 0.85, 0.35, 0.5],  # &quot;not dog&quot;<br>    <br>    # Robot and AI assistant (more distinct in 4D space)<br>    [0.0, 0.7, 0.9, 0.8],  # &quot;robot&quot;<br>    [0.1, 0.6, 0.85, 0.75]  # &quot;AI assistant&quot;<br>], dtype=torch.float32)</pre><h4>Construction of autoencoder</h4><p>We now build the autoencoder with the following code:</p><pre>class SparseAutoencoder(nn.Module):<br>    def __init__(self, input_dim, hidden_dim):<br>        super(SparseAutoencoder, self).__init__()<br>        self.encoder = nn.Sequential(<br>            nn.Linear(input_dim, hidden_dim),<br>            nn.ReLU()<br>        )<br>        self.decoder = nn.Sequential(<br>            nn.Linear(hidden_dim, input_dim)<br>        )<br><br>    def forward(self, x):<br>        encoded = self.encoder(x)<br>        decoded = self.decoder(encoded)<br>        return encoded, decoded</pre><p>According to the code above, we see that the encoder has a only one fully connected linear layer, mapping the input to a hidden representation with hidden_dim and it then passes to a ReLU activation. The decoder uses just one linear layer to reconstruct the input. Note that the absence of ReLU activation in the decoder is intentional for our specific reconstruction case, because the reconstruction might contain real-valued and potentially negative valued data. A ReLU would on the contrary force the output to stay non-negative, which is not desirable for our reconstruction.</p><p>We train model using the code below. Here, the loss function has two parts: the reconstruction loss, measuring the accuracy of the autoencoder’s reconstruction of the input data, and a sparsity loss (with weight), which encourages sparsity formulation in the encoder.</p><pre># Training loop<br>for epoch in range(num_epochs):<br>    optimizer.zero_grad()<br><br>    # Forward pass<br>    encoded, decoded = model(data)<br><br>    # Reconstruction loss<br>    reconstruction_loss = criterion(decoded, data)<br><br>    # Sparsity penalty (L1 regularization on the encoded features)<br>    sparsity_loss = torch.mean(torch.abs(encoded))<br><br>    # Total loss<br>    loss = reconstruction_loss + sparsity_weight * sparsity_loss<br><br>    # Backward pass and optimization<br>    loss.backward()<br>    optimizer.step()</pre><h3>Interpretable features</h3><p>Now we can have a look of the result. We have plotted the encoder’s output value of each activation of the original models. Recall that the input tokens are “cat,” “happy cat,” “dog,” “energetic dog,” “not cat,” “not dog,” “robot,” and “AI assistant”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*lVM2CkHW3lC13qFeWhXzwQ.png" /><figcaption>Image by author: features learned by encoder</figcaption></figure><p>Even though the original model was designed with a very simple architecture without any deep consideration, the autoencoder has still captured meaningful features of this trivial model. According to the plot above, we can observe at least four features that appear to be learned by the encoder.</p><p>Give first Feature 1 a consideration. This feautre has big activation values on the 4 following tokens: “cat”, “happy cat”, “dog”, and “energetic dog”. The result suggests that Feature 1 can be something related to “animals” or “pets”. Feature 2 is also an interesting example, activating on two tokens “robot” and “AI assistant”. We guess, therefore, this feature has something to do with “artificial and robotics”, indicating the model’s understanding on technological contexts. Feature 3 has activation on 4 tokens: “not cat”, “not dog”, “robot” and “AI assistant” and this is possibly a feature “not an animal”.</p><p>Unfortunately, original model is not a real model trained on real-world text, but rather artificially designed with the assumption that similar tokens have some similarity in the activation vector space. However, the results still provide interesting insights: the sparse autoencoder succeeded in showing some meaningful, human-friendly features or real-world concepts.</p><h3>Conclusion</h3><p>The simple result in this blog post suggests:, a sparse autoencoder can effectively help to get high-level, interpretable features from complex neural networks such as LLM.</p><p>For readers interested in a real-world implementation of sparse autoencoders, I recommend this <a href="https://transformer-circuits.pub/2023/monosemantic-features/index.html">article</a>, where an autoencoder was trained to interpret a real large language model with 512 neurons. This study provides a real application of sparse autoencoders in the context of LLM’s interpretability.</p><p>Finally, I provide here this google colab <a href="https://colab.research.google.com/drive/11uqjg3a6IdhXok4iNnbbojC_cVASmIHH#scrollTo=boRLI5vmUBwx&amp;line=44&amp;uniqifier=1">notebook</a> for my detailed implementation mentioned in this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4764bb37927d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/sparse-autoencoder-from-superposition-to-interpretable-features-4764bb37927d">Sparse AutoEncoder: from Superposition to interpretable features</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[Superposition: What Makes it Difficult to Explain Neural Network]]></title>
            <link>https://medium.com/data-science/superposition-what-makes-it-difficult-to-explain-neural-network-565087243be4?source=rss-9b74bc8c860d------2</link>
            <guid isPermaLink="false">https://medium.com/p/565087243be4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[getting-started]]></category>
            <category><![CDATA[superposition]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Shuyang Xiang]]></dc:creator>
            <pubDate>Sun, 29 Dec 2024 14:01:45 GMT</pubDate>
            <atom:updated>2024-12-30T17:09:08.023Z</atom:updated>
            <content:encoded><![CDATA[<h4>When there are more features than model dimensions</h4><h3>Introduction</h3><p>It would be ideal if the world of neural network represented a one-to-one relationship: each neuron activates on one and only one feature. In such a world, interpreting the model would be straightforward: this neuron fires for the dog ear feature, and that neuron fires for the wheel of cars. Unfortunately, that is not the case. In reality, a model with dimension <em>d</em> often needs to represent <em>m</em> features, where <em>d &lt; m</em>. This is when we observe the phenomenon of superposition.</p><p><em>One small remark concerning one comment: superposition might still occur when d&gt;m but with different intepretation and mechanism. The higher dimensionality in the hidden layer provides the network with more capacity without eliminating the need for superposition — it simply allows for a richer combination of shared and distinct features within the larger representational space.</em></p><p>In the context of machine learning, superposition refers to a specific phenomenon that one neuron in a model represents multiple overlapping features rather than a single, distinct one. For example, InceptionV1 contains one neuron that responds to cat faces, fronts of cars, and cat legs [1]. This leads to what we can superposition of different features activation in the same neuron or circuit.</p><p>The existence of superposition makes model explainability challenging, especially in deep learning models, where neurons in hidden layers represent complex combinations of patterns rather than being associated with simple, direct features.</p><p>In this blog post, we will present a simple toy example of superposition, with detailed implementations by Python in this <a href="https://colab.research.google.com/drive/1WXHfWOjFBLN8T6E6QfkvsJ2v7ZoLY3qK#scrollTo=PAqPr42lwzVX">notebook</a>.</p><h3>What makes Superposition Occur: Assumptions</h3><p>We begin this section by discussing the term “feature”.</p><p>In tabular data, there is little ambiguity in defining what a feature is. For example, when predicting the quality of wine using a tabular dataset, features can be the percentage of alcohol, the year of production, etc.</p><p>However, defining features can become complex when dealing with non-tabular data, such as images or textual data. In these cases, there is no universally agreed-upon definition of a feature. Broadly, a feature can be considered any property of the input that is recognizable to most humans. For instance, one feature in a large language model (LLM) might be whether a word is in French.</p><p>Superposition occurs when the number of features is more than the model dimensions. We claim that two necessary conditions must be met if superposition would occur:</p><ol><li><strong>Non-linearity</strong>: Neural networks typically include non-linear activation functions, such as sigmoid or ReLU, at the end of each hidden layer. These activation functions give the network possibilities to map inputs to outputs in a non-linear way, so that it can capture more complex relationships between features. We can imagine that without non-linearity, the model would behave as a simple linear transformation, where features remain linearly separable, without any possibility of compression of dimensions through superposition.</li><li><strong>Feature Sparsity</strong>: Feature sparsity means the fact that only a small subset of features is non-zero. For example, in language models, many features are not present at the same time: e.g. one same word cannot be is_French and is_other_languages. If all features were dense, we can imagine an important interference due to overlapping representations, making it very difficult for the model to decode features.</li></ol><h3>Toy Example: Linearity vs non-linearity with varying sparsity</h3><h4>Synthetic Dataset</h4><p>Let us consider a toy example of 40 features with linearly decreasing feature importance: the first feature has an importance of 1, the last feature has an importance of 0.1, and the importance of the remaining features is evenly spaced between these two values.</p><p>We then generate a synthetic dataset with the following code:</p><pre>def generate_sythentic_dataset(dim_sample, num_sapmple, sparsity): <br>  &quot;&quot;&quot;Generate synthetic dataset according to sparsity&quot;&quot;&quot;<br>  dataset=[]<br>  for _ in range(num_sapmple): <br>    x = np.random.uniform(0, 1, n)<br>    mask = np.random.choice([0, 1], size=n, p=[sparsity, 1 - sparsity])<br>    x = x * mask  # Apply sparsity<br>    dataset.append(x)<br>  return np.array(dataset)</pre><p>This function creates a synthetic dataset with the given number of dimensions, which is, 40 in our case. For each dimension, a random value is generated from a uniform distribution in [0, 1]. The sparsity parameter, varying between 0 and 1, controls the percentage of active features in each sample. For example, when the sparsity is 0.8, it the features in each sample has 80% chance to be zero. The function applies a mask matrix to realize the sparsity setting.</p><h4>Linear and Relu Models</h4><p>We would now like to explore how ReLU-based neural models lead to superposition formation and how sparsity values would change their behaviors.</p><p>We set our experiment in the following way: we compress the features with 40 dimensions into the 5 dimensional space, then reconstruct the vector by reversing the process. Observing the behavior of these transformations, we expect to see how superposition forms in each case.</p><p>To do so, we consider two very similar models:</p><ol><li><strong>Linear Model</strong>: A simple linear model with only 5 coefficients. Recall that we want to work with 40 features — far more than the model’s dimensions.</li><li><strong>ReLU Model</strong>: A model almost the same to the linear one, but with an additional ReLU activation function at the end, introducing one level of non-linearity.</li></ol><p>Both models are built using PyTorch. For example, we build the ReLU model with the following code:</p><pre>class ReLUModel(nn.Module):<br>    def __init__(self, n, m):<br>        super().__init__()<br>        self.W = nn.Parameter(torch.randn(m, n) * np.sqrt(1 / n))<br>        self.b = nn.Parameter(torch.zeros(n))<br>    <br>    def forward(self, x):<br>        h = torch.relu(torch.matmul(x, self.W.T))  # Add ReLU activation: x (batch, n) * W.T (n, m) -&gt; h (batch, m)<br>        x_reconstructed = torch.relu(torch.matmul(h, self.W) + self.b)  # Reconstruction with ReLU<br>        return x_reconstructed </pre><p>According to the code, the n-dimensional input vector x is projected into a lower-dimensional space by multiplying it with an m×n weight matrix. We then reconstruct the original vector by mapping it back to the original feature space through a ReLU transformation, adjusted by a bias vector. The Linear Model is given by the similar structure, with the only difference being that the reconstruction is done by using only the linear transformation instead of ReLU. We train the model by minimizing the mean squared error between the original feature samples and the reconstructed ones, weighted one the feature importance.</p><h3>Results Analysis</h3><p>We trained both models with different sparsity values: 0.1, 0.5, and 0.9, from less sparse to the most sparse. We have observed several important results.</p><p>First, whatever the sparsity level, ReLU models “compress” features much better than linear models: While linear models mainly capture features with the highest feature importance, <strong>ReLU models could focus on less important features by formation of superposition</strong>— where a single model dimension represents multiple features. Let us have a vision of this phenomenon in the following visualizations: for linear models, the biases are smallest for the top five features, (in case you don’t remember: the feature importance is defined as a linearly decreasing function based on feature order). In contrast, the biases for the ReLU model do not show this order and are generally reduced more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0HfEwi1yGNKcvAR9UH26dw.png" /><figcaption>Image by author: reconstructed bias</figcaption></figure><p>Another important and interesting result is that: superposition is much more likely to observe when sparsity level is high in the features. To get an impression of this phenomenon, we can visualize the matrix W^T@W, where W is the m×n weight matrix in the models. One might interpret the matrix W^T@W as a quantity of how the input features are projected onto the lower dimensional space:</p><p>In particular:</p><ol><li>The diagonal of W^T@W represents the “self-similarity” of each feature inside the low dimensional transformed space.</li><li>The off-diagonal of the matrix represents how different features correlate to each other.</li></ol><p>We now visualize the values of W^T@W below for both the Linear and ReLU models we have constructed before with two different sparsity levels : 0.1 and 0.9. You can see that when the sparsity value is high as 0.9, the off-diagonal elements become much bigger compared to the case when sparsity is 0.1 (You actually don’t see much difference between the two models output). This observation indicates that correlations between different features are more easily to be learned when sparsity is high.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*opt7iYLJHxSGK2mIpry5TQ.png" /><figcaption>Image by Author: matrix for sparsity 0.1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b-w90n9Atm3gjoLdhYIFnw.png" /><figcaption>Image by author: matrix for sparsity 0.9</figcaption></figure><h3>Conclusion</h3><p>In this blog post, I made a simple experiment to introduce the formation of superposition in neural networks by comparing Linear and ReLU models with fewer dimensions than features to represent. We observed that the non-linearity introduced by the ReLU activation, combined with a certain level of sparsity, can help the model form superposition.</p><p>In real-world applications, which are much more complex than my navie example, superposition is an important mechanism for representing complex relationships in neural models, especially in vision models or LLMs.</p><h3>References</h3><p>[1] Zoom In: An Introduction to Circuits. <a href="https://distill.pub/2020/circuits/zoom-in/">https://distill.pub/2020/circuits/zoom-in/</a></p><p>[2] Toy models with superposition. <a href="https://transformer-circuits.pub/2022/toy_model/index.html">https://transformer-circuits.pub/2022/toy_model/index.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=565087243be4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/superposition-what-makes-it-difficult-to-explain-neural-network-565087243be4">Superposition: What Makes it Difficult to Explain Neural Network</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[Under-trained and Unused tokens in Large Language Models]]></title>
            <link>https://medium.com/data-science/under-trained-and-unused-tokens-in-large-language-models-db5fa17589ec?source=rss-9b74bc8c860d------2</link>
            <guid isPermaLink="false">https://medium.com/p/db5fa17589ec</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Shuyang Xiang]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 16:42:16 GMT</pubDate>
            <atom:updated>2024-10-01T16:42:16.803Z</atom:updated>
            <content:encoded><![CDATA[<h4>Existence of under-trained and unused tokens and Identification Techniques using GPT-2 Small as an Example</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*LdYdFjBlpjlJ2MzFxD9yUw.jpeg" /><figcaption>Image generated by <a href="https://deepai.org/machine-learning-mode">deepai</a> from the text: under-trained tokenization of LLMs</figcaption></figure><h3>Introduction: Unused and Under-trained Tokens</h3><p>We have observed the existence of both unused and under-trained tokens in exploration of transformer based large language models (LLMs) such as ChatGPT, of which the tokenization and the model training stay as two separate processes. Unused tokens and under-trained tokens have the following different behaviors:</p><ul><li><strong>Unused Tokens</strong> exist in the LLM’s vocabulary and were included during the process training but were not sufficiently seen.</li><li><strong>Under-Trained Tokens</strong> may or may not exist in the LLM’s vocabulary and were not at all represented in the training data.</li></ul><p>Ideally, the two types of tokens would have very low probabilities to be generated, or equivalently, have extremely negative logit values, so that they should not be generated by the LLMs. However, in practice, users have still found some unused tokens with important logits and the model can sometimes unfortunately predict them. This can lead to undesirable behaviors in LLMs.</p><p>Let us consider an LLM which unexpectedly generates nonsensical or inappropriate text because of some tokens that was never trained during the model training. Such occurrences can sometimes cause serious consequences, such as hallucination, leading to lack of accuracy and appropriateness.</p><p>We claim this issue is due to the separation between tokenization and the training process of LLMs. In general, these two aspects are never trained together and it did happen that a token in the model’s vocabulary fails to be trained and appears randomly in the output of the model.</p><p>In this article, we will demonstrate the existence of unused tokens, including under-trained ones, with some simple experiments using GPT-2 Small . We will also discuss techniques for identifying under-trained tokens.</p><h3>Existence of Unused Tokens: Experiments on GPT-2 Small</h3><p>In many LLMs, including GPT-2 Small on which our experiments are executed, there exist unused tokens, that is, tokens existing in the LLM’s vocabulary and were included during the process training but were not sufficiently seen.</p><p>In the following examples, we give two cases proving the existence of unused tokens:</p><h4>Example 1: Reproducing Unused Tokens</h4><p>In this experiment, we aim to show how GPT-2 Small struggles to reproduce unused tokens, even with very straightforward instructions. Let us now consider the following unused token:&quot;ú&quot; (\u00fa). We would like to instruct GPT-2 small to repeat the token exactly as given by the input.</p><p>This is a very simple task: For the given input token &quot;ú&quot;, the model have to give the same token as output.</p><pre>from transformers import GPT2LMHeadModel, GPT2Tokenizer</pre><pre># Load pre-trained model (GPT-2 Small) and tokenizer<br>model_name = &quot;gpt2&quot;  # GPT-2 Small (124M parameters)<br>model = GPT2LMHeadModel.from_pretrained(model_name)<br>tokenizer = GPT2Tokenizer.from_pretrained(model_name)<br>tokenizer.pad_token = tokenizer.eos_token</pre><pre># Configure the model&#39;s `pad_token_id`<br>model.config.pad_token_id = model.config.eos_token_id</pre><pre># Encode a prompt to generate text<br>token= &quot;\u00fa&quot;<br>prompt_text = &quot;Rpeats its input exactly&quot; + &#39;, &#39;.join([f&quot;Input: {token}, Output: {token}&quot; for _ in range(20)])+ f&quot;Input: {token}, Output: &quot;<br>inputs = tokenizer(prompt_text, return_tensors=&quot;pt&quot;, padding=True)</pre><pre># Generate text with attention mask<br>output = model.generate(<br>    inputs[&#39;input_ids&#39;],<br>    attention_mask=inputs[&#39;attention_mask&#39;],  # Explicitly pass attention_mask<br>    max_new_tokens=10,  # Maximum length of the generated text<br>    num_return_sequences=1,  # Number of sequences to return<br>    no_repeat_ngram_size=2,  # Prevent repeating n-grams<br>    do_sample=True,  # Enable sampling<br>    top_k=50,  # Limit sampling to top k choices<br>    top_p=0.95,  # Use nucleus sampling<br>)</pre><p>As you can see in the code above, we have designed a prompt as n-shot examples, instructing the model to give exactly the same specific token &quot;ú&quot; . What we see is that the model fails to predict this token: it gives some grabled text as &quot;Output: - ß, *- *-, &quot; . In contrast, when we tested the same task with common tokens such as &quot;a&quot; , the model successfully predicted the correct output, showing the stark difference in performance between frequently encountered and unused tokens.</p><h4>Example 2: Token Repetition</h4><p>We now consider the range of unused tokens from indices 177 to 188, the range of unused tokens for GPT2 [1].</p><p>Our goal now is to generate sequences of repeated random tokens and evaluate the model’s performance on the repeated sequencee. As discussed in my previous blog post, <strong>“</strong><a href="https://medium.com/towards-data-science/how-to-interpret-gpt2-small-76e0536a588a"><strong>How to Interpret GPT-2 Small: Mechanistic Interpretability on Prediction of Repeated Tokens,</strong></a><strong>”</strong> transformer-based LLMs have a strong ability to recognize and predict repeated patterns, even for small models such as GPT2 small.</p><p>For example, when the model encounters an ‘A’, it searches for the previous occurrence of ‘A’ or a token closely related to ‘A’ in the embedding space. It then identifies the subsequent token, ‘B’, and predicts that the next token following ‘A’ will be ‘B’ or a token similar to ‘B’ in the embedding space.</p><p>We begin by defining a function, generate_repeated_tokens which generated a sequence whose second half repeats the first half.</p><pre>import torch as t<br>from typing import Tuple<br># Assuming HookedTransformer and other necessary components are defined elsewhere.<br>t.manual_seed(42)<br>def generate_repeated_tokens(<br>    model: HookedTransformer, seq_len: int, batch: int = 1<br>) -&gt; Int[Tensor, &quot;batch full_seq_len&quot;]:<br>    &#39;&#39;&#39;<br>    Generates a sequence of repeated random tokens<br>    Outputs are:<br>        rep_tokens: [batch, 1+2*seq_len]<br>    &#39;&#39;&#39;<br>    bos_token = (t.ones(batch, 1) * model.tokenizer.bos_token_id).long()  # generate bos token for each batch<br>    rep_tokens_half = t.randint(177, 188, (batch, seq_len), dtype=t.int64)<br>    rep_tokens = t.cat([bos_token, rep_tokens_half, rep_tokens_half], dim=-1).to(device)<br>    return rep_tokens</pre><p>Next, we define the run_and_cache_model_repeated_tokens function, which runs the model on the generated repeated tokens, returning the logits and caching the activations. We will use only logits here.</p><pre>def run_and_cache_model_repeated_tokens(model: HookedTransformer, seq_len: int, batch: int = 1) -&gt; Tuple[t.Tensor, t.Tensor, ActivationCache]:<br>    &#39;&#39;&#39;<br>    Generates a sequence of repeated random tokens, and runs the model on it, returning logits, tokens and cacheShould use the `generate_repeated_tokens` function above<br>    Outputs are:<br>        rep_tokens: [batch, 1+2*seq_len]<br>        rep_logits: [batch, 1+2*seq_len, d_vocab]<br>        rep_cache: The cache of the model run on rep_tokens<br>    &#39;&#39;&#39;<br>    rep_tokens = generate_repeated_tokens(model, seq_len, batch)<br>    rep_logits, rep_cache = model.run_with_cache(rep_tokens)<br>    return rep_tokens, rep_logits, rep_cache</pre><p>Now we run the model using the defined run_and_cache_model_repeated_tokens function, generating both the tokens and the associated logits with the following code:</p><pre>seq_len = 25<br>batch = 1<br>(rep_tokens, rep_logits, rep_cache) = run_and_cache_model_repeated_tokens(gpt2_small, seq_len, batch)<br>rep_cache.remove_batch_dim()<br>rep_str = gpt2_small.to_str_tokens(rep_tokens)<br>gpt2_small.reset_hooks()<br>log_probs = get_log_probs(rep_logits, rep_tokens).squeeze()Copy co</pre><p>After running the model, we analyze the log probabilities of the predicted tokens for both halves of the repeated sequences. We observed a mean log probability of -17.270 for the first half and -19.675 for the second half for token sequences varying in indices 177 to 188.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ieSDh1wzkFwHbksNcx8EhA.png" /><figcaption>Image by author: log prob of repeated tokens ranging in 177 to 188</figcaption></figure><p>On the other hand, doing the same experiment with a commonly used range of tokens gives different results: When examining token indices 100 to 110, we observe significantly better performance in the second half, with log probabilities of -0.971 compared to -7.327 in the first half.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QpFuktPDIoiNxhvmWii1HQ.png" /><figcaption>Image by author: log prob of repeated tokens ranging in 100 to 111</figcaption></figure><h3>Under-trained Tokens</h3><p>The world of LLM would ideally have less surprise if all unused tokens had significantly negative logits and the model would therefore never produce weird texts.</p><p>The reality is, unfortunately much more complex. The fact that the creation of the tokenizer and the training of LLM do not happen at the same time lead sometimes to undertrained tokens which are, the the culprits of unexpected behaviors of LLMs.</p><p>An example of undertrained tokens is:_SolidGoldMagikarp[1] which was seen sometimes in ChatGPT’s outputs. Now we would like to prove the existence of under-trained tokens in the case of GPT-2 Small.</p><h4>Example: Reproducing Unused Tokens</h4><p>In our former experiment of reproducing unused tokens within the GPT-2 Small model, we proved that the token &quot;ú&quot; has hardly any chance to be generated by the model.</p><p>Now we slice the logits tensor after runing the model to isolate the outputs to the unused token indices ranging from 177 to 188:</p><pre>sliced_tensor = gpt2_logits[0, :, 177:188]</pre><p>Interestingly, we have observed that the logit values for some tokens in this “unused” range reached approximately -1.7, which is to say, there is a probability of around 0.18 for some unused tokens being generated.</p><p>This finding highlights the model’s possiblity to assign non-negligible probabilities to some unused tokens, despite they are uncommonly used in most of the context.</p><h3>Identifying Under-Trained Tokens</h3><p>In recent years, researchers have proposed techniques to automatically identify under-trained tokens in LLMs. Works in this area include those by Watkins and Rumbelow (2023), and Fell (2023) among which one very interesting approach to identifying under-trained tokens involves analyzing the output embeddings E_{out} generated by the model:</p><p>The the method computes the average embedding vector of the unused tokens and uses cosine distances to measure how the vector is similar to all tokens’e embedding vector of the model. Tokens with cosine distances close to the mean embeddings are thus marked as candidates of under-trained tokens. Please check more details in [1].</p><h3>Conclusion</h3><p>In conclusion, this blog posts discusses the under-trained tokens LLMs. We do some experiments with GPT-2 Small to illustrate that under-trained tokens can unexpectedly affect model outputs, giving sometimes unpredictable and undesirable behaviors. Recent researches propose methods in identifying under-trained tokens accordingly. For those interested in more details of my implementation, you can check my accompanying <a href="https://colab.research.google.com/drive/13h_X8uvkai49yUWW2cndKDVMg-8RqlIb#scrollTo=ckKDzTnF1r3l">notebook</a>.</p><h3>Reference</h3><p>[1] Land, S., &amp; Bartolo, M. (2024). <em>Fishing for Magikarp: Automatically detecting under-trained tokens in large language models</em>. arXiv. <a href="https://doi.org/10.48550/arXiv.2405.05417">https://doi.org/10.48550/arXiv.2405.05417</a>.</p><p>[2] Jessica Rumbelow and Matthew Watkins. 2023. SolidGoldMagikarp (plus, prompt generation). Blog Post.</p><p>[3] Martin Fell. 2023. A search for more ChatGPT / GPT3.5 / GPT-4 “unspeakable” glitch tokens. Blog post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db5fa17589ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/under-trained-and-unused-tokens-in-large-language-models-db5fa17589ec">Under-trained and Unused tokens in Large Language 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>
        <item>
            <title><![CDATA[KernelSHAP can be misleading with correlated predictors]]></title>
            <link>https://medium.com/data-science/kernelshap-can-be-misleading-with-correlated-predictors-9f64108f7cfb?source=rss-9b74bc8c860d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f64108f7cfb</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[model-interpretability]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Shuyang Xiang]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 14:15:30 GMT</pubDate>
            <atom:updated>2024-10-05T10:31:53.109Z</atom:updated>
            <content:encoded><![CDATA[<h4>A concrete case study</h4><blockquote>“Like many other permutation-based interpretation methods, the Shapley value method suffers from inclusion of unrealistic data instances when features are correlated. To simulate that a feature value is missing from a coalition, we marginalize the feature. ..When features are dependent, then we might sample feature values that do not make sense for this instance. ”—<a href="https://christophm.github.io/interpretable-ml-book/shapley.html#disadvantages-13"> Interpretable-ML-Book</a>.</blockquote><p>SHAP (SHapley Additive exPlanations) values are designed to fairly allocate the contribution of each feature to the prediction made by a machine learning model, based on the concept of Shapley values from cooperative game theory. The Shapley value framework has several desirable theoretical properties and can, in principle, handle any predictive model. However, SHAP values can potentially be misleading, especially when using the KernelSHAP method for approximation. When predictors are correlated, these approximations can be imprecise and even have the opposite sign.</p><p>In this blog post, I will demonstrate how the original SHAP values can differ significantly from approximations made by the <a href="https://shap.readthedocs.io/en/latest/example_notebooks/overviews/An%20introduction%20to%20explainable%20AI%20with%20Shapley%20values.html">SHAP framework</a>, especially the KernalSHAP and discuss the reasons behind these discrepancies.</p><h3><strong>Case Study: Churn Rate</strong></h3><p>Consider a scenario where we aim to predict the churn rate of rental leases in an office building, based on two key factors: occupancy rate and the rate of reported problems.</p><p>The occupancy rate significantly impacts the churn rate. For instance, if the occupancy rate is too low, tenants may leave due to the office being underutilized. Conversely, if the occupancy rate is too high, tenants might depart because of overcrowding, seeking better options elsewhere.</p><p>Furthermore, let’s assume that the rate of reported problems is highly correlated with the occupancy rate, specifically that the reported problem rate is the square of the occupancy rate.</p><p>We define the churn rate function as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GAuKxLiSTaK3U5PV_W5WIQ.png" /><figcaption>Image by author: churn rate function</figcaption></figure><p>This function with respect to the two variables can be represented by the following illustrations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*yQtERFH2iNsOyLxsgueWjg.png" /><figcaption>Image by author: Churn on two variables</figcaption></figure><h3>Discrepancies between original SHAP and Kernel SHAP</h3><h4>SHAP Values Computed Using Kernel SHAP</h4><p>We will now use the following code to compute the SHAP values of the predictors:</p><pre># Define the dataframe <br>churn_df=pd.DataFrame(<br>    {<br>        &quot;occupancy_rate&quot;:occupancy_rates,<br>        &quot;reported_problem_rate&quot;: reported_problem_rates,<br>        &quot;churn_rate&quot;:churn_rates,<br>    }<br>)<br>X=churn_df.drop([&quot;churn_rate&quot;],axis=1)<br>y=churn_df[&quot;churn_rate&quot;]<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 42)<br># append one speical point<br>X_test=pd.concat(objs=[X_test, pd.DataFrame({&quot;occupancy_rate&quot;:[0.8], &quot;reported_problem_rate&quot;:[0.64]})])<br><br># Define the prediction<br>def predict_fn(data):<br>    occupancy_rates = data[:, 0]<br>    reported_problem_rates = data[:, 1]<br><br>    churn_rate= C_base +C_churn*(C_occ* occupancy_rates-reported_problem_rates-0.6)**2 +C_problem*reported_problem_rates<br>    return churn_rate<br><br># Create the SHAP KernelExplainer using the correct prediction function<br>background_data = shap.sample(X_train,100)<br>explainer = shap.KernelExplainer(predict_fn, background_data)<br>shap_values = explainer(X_test)</pre><p>The code above performs the following tasks:</p><ol><li>Data Preparation: A DataFrame named churn_df is created with columns occupancy_rate, reported_problem_rate, and churn_rate. Variables and target (churn_rate ) are then created from and Data is split into training and testing sets, with 80% for training and 20% for testing. Note that a special data point with specific occupancy_rate and reported_problem_rate values is added to the test set X_test.</li><li>Prediction Function Definition: A function predict_fn is defined to calculate churn rate using a specific formula involving predefined constants.</li><li>SHAP Analysis: A SHAP KernelExplainer is initialized using the prediction function and background_data samples from X_train. SHAP values for X_test are computed using the explainer.</li></ol><p>Below, you can see a summary SHAP bar plot, which represents the average SHAP values for X_test :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*ICNZV8UC8N9cxaXRjHOoBA.png" /><figcaption>Image by author: average shap values</figcaption></figure><p>In particular, we see that at the data point (0.8, 0.64), the SHAP values of the two features are 0.10 and -0.03, illustrated by the following force plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DsPHWMjiOg3p7jUDcgKUOw.png" /><figcaption>Image by author Force Plot of one data point</figcaption></figure><h4>SHAP Values by orignal definition</h4><p>Let’s take a step back and compute the exact SHAP values step by step according to their original definition. The general formula for SHAP values is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*8-APOBVdBTjec41FW0K7BA.png" /></figure><p>where: S is a subset of all feature indices excluding i, |S| is the size of the subset S, M is the total number of features, f(XS​∪{xi​}) is the function evaluated with the features in S with xi present while f(XS) is the function evaluated with the feature in S with xi absent.</p><p>Now, let’s calculate the SHAP values for two features: occupancy rate (denoted as x1​) and reported problem rate (denoted as x2​) at the data point (0.8, 0.64). Recall that x1​ and x2are related by x1 = x2².</p><p>We have the SHAP value for occupancy rate at the data point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*RfsF1k3im5C4QQyKFeY_zQ.png" /></figure><p>and, similary, for the feature reported problem rate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*0a3eULF_C4WNf_AzGKoS_g.png" /></figure><p>First, let’s compute the SHAP value for the occupancy rate at the data point:</p><ol><li>The first term is the expectation of the model’s output when X1​ is fixed at 0.8 and X2​ is averaged over its distribution. Given the relationship x1 = x2², this expectation leads to the model’s output at the specific point (0.8, 0.64).</li><li>The second term is the unconditional expectation of the model’s output, where both X1 and X2 are averaged over their distributions. This can be computed by averaging the outputs over all data points in the background dataset.</li><li>The third term is the model’s output at the specific point (0.8, 0.64).</li><li>The final term is the expectation of the model’s output when X1​ is averaged over its distribution, given that X2​ is fixed at the specific point 0.64. Again, due to the relationship x_1 = x_2²​, this expectation matches the model’s output at (0.8, 0.64), similar to the first step.</li></ol><p>Thus, the SHAP values compute from the original definition for the two features occupancy rate and reported problem rate at the data point (0.8, 0.64) are -0.0375 and -0.0375, respectively, which is quite different from the values given by Kernel SHAP.</p><p>Where comes discrepancies?</p><h3>Cause of Discrepancies in SHAP Values</h3><p>As you may have noticed, the discrepancy between the two methods primarily arises from the second and fourth steps, where we need to compute the conditional expectation. This involves calculating the expectation of the model’s output when X1X_1X1​ is conditioned on 0.8.</p><ul><li><strong>Exact SHAP</strong>: When computing exact SHAP values, the dependencies between features (such as x1=x_2² in our example​) are explicitly accounted for. This ensures accurate calculations by considering how feature interactions impact the model’s output.</li><li><strong>Kernel SHAP</strong>: By default, Kernel SHAP assumes feature independence, which can lead to inaccurate SHAP values when features are actually dependent. According to the paper <a href="https://arxiv.org/abs/1705.07874"><em>A Unified Approach to Interpreting Model Predictions</em>,</a> this assumption is a simplification. In practice, features are often correlated, making it challenging to achieve accurate approximations when using Kernel SHAP.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6LhIWV-Ir1jEmuo6wKK-bQ.png" /><figcaption>Screenshot from the paper</figcaption></figure><h3>Potential resolutions</h3><p>Unfortunately, computing SHAP values directly based on their original definition can be computationally expensive. Here are some alternative approaches to consider:</p><h4>TreeSHAP</h4><ul><li>Designed specifically for tree-based models like random forests and gradient boosting machines, TreeSHAP efficiently computes SHAP values while effectively managing feature dependencies.</li><li>This method is optimized for tree ensembles, making it faster and more scalable compared to traditional SHAP computations.</li><li>When using TreeSHAP within the SHAP framework, set the parameter feature_perturbation = &quot;interventional&quot; to account for feature dependencies accurately.</li></ul><h4>Extending Kernel SHAP for Dependent Features</h4><ul><li>To address feature dependencies,<a href="http://Unfortunately, computing SHAP values directly based on their original definition can be computationally expensive. Here are some alternative approaches to consider:"> this paper</a> involves extending Kernel SHAP. One method is to assume that the feature vector follows a multivariate Gaussian distribution. In this approach:</li><li>Conditional distributions are modeled as multivariate Gaussian distributions.</li><li>Samples are generated from these conditional Gaussian distributions using estimates from the training data.</li><li>The integral in the approximation is computed based on these samples.</li><li>This method assumes a multivariate Gaussian distribution for features, which may not always be applicable in real-world scenarios where features can exhibit different dependency structures.</li></ul><h4>Improving Kernel SHAP Accuracy</h4><ul><li><strong>Description</strong>: Enhance the accuracy of Kernel SHAP by ensuring that the background dataset used for approximation is representative of the actual data distribution with independant features.</li></ul><p>By utilizing these methods, you can address the computational challenges associated with calculating SHAP values and enhance their accuracy in practical applications. However, it is important to note that no single solution is universally optimal for all scenarios.</p><h3>Conclusion</h3><p>In this blog post, we’ve explored how SHAP values, despite their strong theoretical foundation and versatility across various predictive models, can suffer from accuracy issues when predictors are correlated, particularly when approximations like KernelSHAP are employed. Understanding these limitations is crucial for effectively interpreting SHAP values. By recognizing the potential discrepancies and selecting the most suitable approximation methods, we can achieve more accurate and reliable feature attribution in our models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f64108f7cfb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/kernelshap-can-be-misleading-with-correlated-predictors-9f64108f7cfb">KernelSHAP can be misleading with correlated predictors</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[Creating an Assistant with OpenAI Assistant API and Streamlit]]></title>
            <link>https://medium.com/data-science/creating-an-assistant-with-openai-assistant-api-and-streamlit-282d9be9f03e?source=rss-9b74bc8c860d------2</link>
            <guid isPermaLink="false">https://medium.com/p/282d9be9f03e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[openai-assistant]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Shuyang Xiang]]></dc:creator>
            <pubDate>Tue, 18 Jun 2024 19:15:47 GMT</pubDate>
            <atom:updated>2024-06-18T19:15:47.057Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step guide</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*bX5eqE7EUmnwxWuqjZDzIQ.gif" /><figcaption>Image by author: assistant done with assistant api and streamlit</figcaption></figure><h3>OpenAI Assistant API</h3><p>OpenAI has recently introduced new features that showcase an agent-like architecture, such as the Assistant API. According to OpenAI:</p><blockquote>The Assistants API allows you to build AI assistants within your own applications. An Assistant has instructions and can leverage models, tools, and files to respond to user queries. The Assistants API currently supports three types of tools: Code Interpreter, File Search, and Function calling.</blockquote><p>While these advancements are promising, they still lag behind LangChain. LangChain enables the creation of agent-like systems powered by LLMs with greater flexibility in processing natural language input and executing context-based actions.</p><p>However, this is only the beginning.</p><p>At a high level, interaction with the Assistant API can be envisioned as a loop:</p><ul><li>Given a user input, an LLM is called to determine whether to provide a response or take specific actions.</li><li>If the LLM’s decision suffices to answer the query, the loop ends.</li><li>If an action leads to a new observation, this observation is included in the prompt, and the LLM is called again.</li><li>The loop then restarts.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*9tUzk7PdL-vvXJzBMEILog.png" /><figcaption>Image by author: LLM agent loop</figcaption></figure><p>Unfortunately, despite the announced advantages, I found the documentation for the API to be poorly done, especially regarding interactions with custom function calls and building apps using frameworks like Streamlit.</p><p>In this blog post, I will guide you through building an AI assistant using the OpenAI Assistant API with custom function calls, paired with a Streamlit interface, to help those interested in effectively using the Assistant API.</p><h3>Use case: Tax Computation Assistant</h3><p>In this blog post, I will demonstrate a simple example: an AI assistant capable of calculating tax based on a given revenue. Langchain users can easily come into mind implementing this by creating an <a href="https://python.langchain.com/v0.1/docs/modules/agents/">agent</a> with a “tax computation” tool.</p><p>This tool would include the necessary computation steps and a well-designed prompt to ensure the LLM knows when to call the tool whenever a question involves revenue or tax.</p><p>However, this process is not exactly the same with the OpenAI Assistant API. While the code interpreter and file search tools can be used directly in a straightforward manner according to <a href="https://platform.openai.com/docs/assistants/how-it-works/creating-assistants">OpenAI’s documentation</a>, custom tools require a slightly different approach.</p><pre>assistant = client.beta.assistants.create(<br>  name=&quot;Data visualizer&quot;,<br>  description=&quot;You are great at creating beautiful data visualizations. You analyze data present in .csv files, understand trends, and come up with data visualizations relevant to those trends. You also share a brief text summary of the trends observed.&quot;,<br>  model=&quot;gpt-4o&quot;,<br>  tools=[{&quot;type&quot;: &quot;code_interpreter&quot;}],<br>)</pre><p>Let’s break it down step by step. We aim to:</p><ol><li>Define a function that computes tax based on given revenue.</li><li>Develop a tool using this function.</li><li>Create an assistant that can access this tool and call it whenever tax computation is needed.</li></ol><h3>Tax Computation Function for Assistant Integration</h3><p>Please note that the tax computation tool described in the following paragraph is designed as a toy example to demonstrate how to use the API discussed in the post. It should not be used for actual tax calculations.</p><p>Consider the following piecewise function, which returns the tax value for a given revenue. Note that the input is set as a string for simpler parsing:</p><pre>def calculate_tax(revenue: str):<br>    try:<br>        revenue = float(revenue)<br>    except ValueError:<br>        raise ValueError(&quot;The revenue should be a string representation of a number.&quot;)<br><br>    if revenue &lt;= 10000:<br>        tax = 0<br>    elif revenue &lt;= 30000:<br>        tax = 0.10 * (revenue - 10000)<br>    elif revenue &lt;= 70000:<br>        tax = 2000 + 0.20 * (revenue - 30000)<br>    elif revenue &lt;= 150000:<br>        tax = 10000 + 0.30 * (revenue - 70000)<br>    else:<br>        tax = 34000 + 0.40 * (revenue - 150000)<br><br>    return tax</pre><p>Next, we define the assistant:</p><pre>function_tools = [<br>    {<br>        &quot;type&quot;: &quot;function&quot;,<br>        &quot;function&quot;: {<br>            &quot;name&quot;: &quot;calculate_tax&quot;,<br>            &quot;description&quot;: &quot;Get the tax for given revenue in euro&quot;,<br>            &quot;parameters&quot;: {<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {<br>                    &quot;revenue&quot;: {<br>                        &quot;type&quot;: &quot;string&quot;,<br>                        &quot;description&quot;: &quot;Annual revenue in euro&quot;<br>                    }<br>                },<br>                &quot;required&quot;: [&quot;revenue&quot;]<br>            }<br>        }<br>    }<br>]<br># Define the assistant<br>assistant = client.beta.assistants.create(<br>    name=&quot;Assistant&quot;,<br>    instructions=&quot;&quot;,<br>    tools=function_tools,<br>    model=&quot;gpt-4o&quot;,<br>)</pre><p>Now, the essential point:</p><p>How does the assistant use the function when “calculate_tax” is called? This part is poorly documented in the OpenAI assistant, and many users might get confused the first time using it. To handle this, we need to define an EventHandler to manage different events in the response stream, specifically how to handle the event when the &quot;calculate_tax&quot; tool is called.</p><pre>    def handle_requires_action(self, data, run_id):<br>        tool_outputs = []<br><br>        for tool in data.required_action.submit_tool_outputs.tool_calls:<br>            if tool.function.name == &quot;calculate_tax&quot;:<br>                try:<br>                    # Extract revenue from tool parameters<br>                    revenue = ast.literal_eval(tool.function.arguments)[&quot;revenue&quot;]<br>                    # Call your calculate_tax function to get the tax<br>                    tax_result = calculate_tax(revenue)<br>                    # Append tool output in the required format<br>                    tool_outputs.append({&quot;tool_call_id&quot;: tool.id, &quot;output&quot;: f&quot;{tax_result}&quot;})<br>                except ValueError as e:<br>                    # Handle any errors when calculating tax<br>                    tool_outputs.append({&quot;tool_call_id&quot;: tool.id, &quot;error&quot;: str(e)})<br>        # Submit all tool_outputs at the same time<br>        self.submit_tool_outputs(tool_outputs)</pre><p>The code above works as follows: For each tool call that requires action:</p><ul><li>Check if the function name is “calculate_tax”.</li><li>Extract the revenue value from the tool parameters.</li><li>Call the calculate_tax function with the revenue to compute the tax. (This is where the real interaction happens.)</li><li>After processing all tool calls, submit the collected results.</li></ul><h3>Talking to the assistant</h3><p>You can now interact with the assistant following these standard steps documented by OpenAI (for that reason, I will not provide many details in this section):</p><ol><li><strong>Create a thread:</strong> This represents a conversation between a user and the assistant.</li><li><strong>Add user messages:</strong> These can include both text and files, which are added to the thread.</li><li><strong>Create a run:</strong> Utilize the model and tools associated with the assistant to generate a response. This response is then added back to the thread.</li></ol><p>The code snippet below demonstrates how to run the assistant in my specific use case: The code sets up a streaming interaction with an assistant using specific parameters, including a thread ID and an assistant ID. An EventHandler instance manages events during the stream. The stream.until_done() method keeps the stream active until all interactions are complete. The with statement ensures that the stream is properly closed afterward.</p><pre>  with client.beta.threads.runs.stream(thread_id=st.session_state.thread_id,<br>                                         assistant_id=assistant.id,<br>                                         event_handler=EventHandler(),<br>                                         temperature=0) as stream:<br>        stream.until_done()</pre><h3>Streamlit interface</h3><p>While my post could end here, I’ve noticed numerous inquiries on the Streamlit forum (<a href="https://discuss.streamlit.io/t/openai-assistants-api-streaming/64690/3">like this one</a>) where users struggle to get streaming to work on the interface, even though it functions perfectly in the terminal. This prompted me to delve deeper.</p><p>To successfully integrate streaming into your app, you’ll need to extend the functionality of the EventHandler class mentioned earlier, specifically focusing on handling text creation, text deltas, and text completion. Here are the three key steps required to display text in the Streamlit interface while managing chat history:</p><ol><li><strong>Handling Text Creation (</strong><strong>on_text_created):</strong> Initiates and displays a new text box for each response from the assistant, updating the UI to reflect the status of preceding actions.</li><li><strong>Handling Text Delta (</strong><strong>on_text_delta):</strong> Dynamically updates the current text box as the assistant generates text, enabling incremental changes without refreshing the entire UI.</li><li><strong>Handling Text Completion (</strong><strong>on_text_done):</strong> Finalizes each interaction segment by adding a new empty text box, preparing for the next interaction. Additionally, it records completed conversation segments in chat_history.</li></ol><p>For instance, consider the following code snippet for managing text deltas:</p><pre>def on_text_delta(self, delta: TextDelta, snapshot: Text):<br>    &quot;&quot;&quot;<br>    Handler for when a text delta is created<br>    &quot;&quot;&quot;<br>    # Clear the latest text box<br>    st.session_state.text_boxes[-1].empty()<br>    <br>    # If there is new text, append it to the latest element in the assistant text list<br>    if delta.value:<br>        st.session_state.assistant_text[-1] += delta.value<br>    <br>    # Re-display the updated assistant text in the latest text box<br>    st.session_state.text_boxes[-1].info(&quot;&quot;.join(st.session_state[&quot;assistant_text&quot;][-1]))</pre><p>This code accomplishes three main tasks:</p><ul><li><strong>Clearing the Latest Text Box:</strong> Empties the content of the most recent text box (st.session_state.text_boxes[-1]) to prepare it for new input.</li><li><strong>Appending Delta Value to Assistant Text:</strong> If new text (delta.value) is present, it appends this to the ongoing assistant text stored in st.session_state.assistant_text[-1].</li><li><strong>Re-displaying Updated Assistant Text:</strong> Updates the content of the latest text box to reflect the combined content of all assistant text accumulated so far (st.session_state[&quot;assistant_text&quot;][-1]).</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FE0GEakoxSdY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DE0GEakoxSdY&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b30bd641cf972e03ba4431a7f27c566a/href">https://medium.com/media/b30bd641cf972e03ba4431a7f27c566a/href</a></iframe><h3>Conclusion</h3><p>This blog post demonstrated how to use the OpenAI Assistant API and Streamlit to build an AI assistant capable of calculating tax.</p><p>I did this simple project to highlight the capabilities of the Assistant API, despite its less-than-clear documentation. My goal was to clarify ambiguities and provide some guidance for those interested in using the Assistant API. I hope this post has been helpful and encourages you to explore further possibilities with this powerful tool.</p><p>Due to space constraints, I have tried to avoid including unnecessary code snippets. However, if needed, please visit my <a href="https://github.com/ShuyangenFrance/openai_assistant">Github repository</a> to view the complete implementation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=282d9be9f03e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/creating-an-assistant-with-openai-assistant-api-and-streamlit-282d9be9f03e">Creating an Assistant with OpenAI Assistant API and Streamlit</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[Can Neural Networks Formulate Shock Wave?]]></title>
            <link>https://medium.com/data-science/can-neural-networks-formulate-shock-wave-147bb75d0715?source=rss-9b74bc8c860d------2</link>
            <guid isPermaLink="false">https://medium.com/p/147bb75d0715</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[physics-informed-learning]]></category>
            <category><![CDATA[shock-wave]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shuyang Xiang]]></dc:creator>
            <pubDate>Thu, 04 Apr 2024 17:15:52 GMT</pubDate>
            <atom:updated>2024-04-04T17:15:52.614Z</atom:updated>
            <content:encoded><![CDATA[<h4>How we build a PINN for inviscid Burgers Equation with shock formulation</h4><h3>PINN on Shock Waves</h3><p><strong>Physics-informed neural networks</strong> (<strong>PINNs</strong>) are a special type of neural networks. They estimate solutions to partial differential equations by incorporating the governing physical laws of a given dataset into the learning process.</p><p>An example of such an equation is the inviscid Burgers’ equation, a prototype for conservation laws that can develop shock waves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*Tj8SK837D7PHTRKGm4Snwg.gif" /><figcaption>Image from <a href="https://en.wikipedia.org/wiki/Burgers%27_equation">wikipedia</a>: Inviscid Burgers Equation in two space variables up until the time of shock formation.</figcaption></figure><p>The current literature struggles to effectively tackle this issue. As shock waves are not continuous solutions, they only satisfy the equations in a weak sense. <strong>Continuous Time Models</strong> that depend solely on training samples, like the algorithmic differentiation method, cannot capture shock waves. These methods are only applicable to cases of functional regularity.</p><p>One could attempt to use <strong>Discrete Time Models</strong> where neural networks and time discretization work together to help the model formulate shocks. However, this method somewhat diminishes the advantages of Physics-informed Neural Networks (PINNs) and reverts to traditional numerical methods. This can be challenging for someone who understands equations but is not familiar with numerical solutions.</p><p>In this article, I will address the limitations of existing Continuous Time Models of PINN methods for the Burgers equation. I will introduce calculations for discontinuity and weak solutions based on algorithmic differentiation, enabling the equation to capture shocks. This article might inspire those who are interested in the intersection of neural networks and physics-based modeling, especially in domains related to conservation laws.</p><p>However, it should be noted that this method has only shown promising results for one of the simplest one-dimensional hyperbolic equations. Whether it can be extended to higher dimensions or more complex equations is an aspect that the author has not explored, and I invite readers to contribute their own ideas and resources on this topic.</p><h3>PINN: Continuous Time Models for Burgers</h3><p>According to the original <a href="https://arxiv.org/pdf/1711.10561.pdf">paper</a>: “Physics Informed Neural Networks (PINNs) are trained to solve supervised learning tasks whilst respecting any given laws of physics, described by general nonlinear partial differential equations (PDEs). ”</p><p>These PDEs take the following form in general [1]:</p><p>ut + N [u] = 0, x ∈ Ω, t ∈ [0, T],</p><p>where u(t, x) represents the solution, N [·] is a nonlinear differential operator, and Ω is a subset of the d-dimensional space.</p><p>Let’s denote by</p><p>L(u) = ut + N [u].</p><p>It can be immediately seen that f=0 if u is the solution of the equation. We will construct the solution u as a neural network</p><p>u = neural_net(t,x;weights)</p><p>where the inputs are the time and space variables. We determine the weights by minimizing the mean square error of f (as is said before, L(u) should be close to 0 if u is the solution of the equation) and certain initial and boundary conditions. For more details, please refer to the original paper.</p><p>Now, let’s consider the 1-dimensional inviscid Burgers Equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/0*F9_-nsoUKjkS6X_L" /><figcaption>Inviscid burgers equation</figcaption></figure><p>The solution to the equation, adhering to the initial condition, can be constructed implicitly using the <a href="https://en.wikipedia.org/wiki/Method_of_characteristics">method of characteristics</a>, that is, u=f(x-ut) with the characteristic curve x(t)= x0+f(x0)t. We see from the formula that the characteristics x(t) are straight lines without the same slope, so if there exists two points x1, x2 such that x1+f(x1)t= x2+f(x2)t at a finite time t, we will see the intersectfion of two characteristics and the wave breaks [2].</p><p>The following code is inspired by the git repository <a href="https://github.com/okada39/pinn_burgers">pinn-burgers</a>. Here, a viscous Burgers’ equation is considered for 𝜈&gt;0. The equation is proven to have a globally defined smooth solution, given that the initial condition is a smooth function growing like o(|x|) at infinity [3].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/124/1*XmtcH7MaMosAqjj8fw0E8g.png" /><figcaption>viscous Burgers’ equation</figcaption></figure><p>We will express u(t,x) as neural_net(t,x;weights) with the aim to minimize the mean square error of L(u) (in this case, ut+uux) and the initial and boundary condition. If the solution to the equation is smooth, TensorFlow can be naturally used to write the following code to compute the desired unknowns:</p><pre>with tf.GradientTape() as g:<br>    g.watch(x)<br>    u = neural_net(x)<br>du_dtx = g.batch_jacobian(u, x)<br>du_dt = du_dtx[..., 0]<br>du_dx = du_dtx[..., 1]</pre><p>The L(u) (in the code, we call it u_eqn) will be define simply as:</p><pre>u_eqn = du_dt+ u*du_dt # (1)</pre><p>The issue is that the equation ut + uux only holds true in the weak sense. This means that it may not be useful to consider the values of ut and ux when shock waves form as they will explode. The equation only applies in an integrated form. Common Python packages like TensorFlow or PyTorch provide APIs for neural networks and differentiation algorithms but don’t offer weak sense solutions. Therefore, we need to reconfigure the formula of L(u) to compel the neural network to form the shock wave.</p><h3>Introduction of Shock</h3><p>We’re introducing the Rankine–Hugoniot conditions, also known as Rankine–Hugoniot jump conditions or relations. These describe the relationship between states on either side of a shock wave. For the Burgers equation, the Rankine–Hugoniot condition appears as: 1/2[[𝑢²]]=𝑠[[𝑢]]. The brackets [[ ]] represent the difference between the right-hand side and left-hand side values, while ‘s’ is the shock propagation velocity.</p><p>Considering a specific space variable ‘x’, we aim to closely examine the left or right limits, i.e., u(x±) in cases of discontinuity. Here’s the relevant code:</p><pre>delta = 1e-3<br>xl = x - delta<br>xr= x  + delta<br>with tf.GradientTape() as g:<br>   g.watch(x)<br>    u = neural_net(x)<br>    ul = neural_net(xl)<br>    ur = neural_net(xr)<br><br>du_dtx = g.batch_jacobian(u, x)<br>du_dt = du_dtx[..., 0]<br>du_dx = du_dtx[..., 1]</pre><p>We define a small delta and calculate the value of the solution on both the left and right sides of the space variable x, up to a delta.</p><p>Following this, we redefine the function L(u) as :</p><pre> <br>   term1 = du_dt + u * du_dx<br>   term2 = (ul + ur) / 2<br>   condition = tf.less(du_dt, 1e3)<br>   u_eqn = tf.where(condition, term1, term2) # (2)</pre><p>We use the regular form of the equation when the value of du_dt is finite (specifically, smaller than a sufficiently large value), and we use the Rankine–Hugoniot condition when the value of du_dt is infinite.</p><h3>Experiment</h3><p>Let’s consider the Burgers equation with an initial condition of sin(πx) on the interval [-1, 1]. The solution can be expressed as u=sin(π(x-ut)), and a shock forms when t=1. Using formula (1), we derive the following solution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*8DU-4VisNmtPpvV1UlCj7w.png" /><figcaption>Image by author: Solution of Burgers Equation using formula (1)</figcaption></figure><p>The model has struggled to find the correct answer without being informed about what a shock is. However, if we switch to formula (2), we obtain the following solution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*tKiVO_63tpOlQJYz_YwBKQ.png" /><figcaption>Image by author: Solution of Burgers Equation using formula (2)</figcaption></figure><p>You can see that the model successfully captures the shock wave at t=1.</p><h3>Conclusion</h3><p>Physics-informed neural networks (PINNs) can estimate solutions to partial differential equations by incorporating physical laws into their learning process. However, they often have difficulties with discontinuous solutions such as shock waves. I propose calculations for weak solutions that allow the Burgers equation to capture shocks. It’s important to note that while the 1-D Burgers Equation is a simple use case, this method may not be applicable to more complex equations without deeper consideration.</p><h3>Reference</h3><p>[1] M. Raissi, P. Perdikaris, G.E. Karniadakis,<br>Physics-informed neural networks: A deep learning framework for solving forward and inverse problems involving nonlinear partial differential equations, Journal of Computational Physics,Volume 378,2019, Pages 686–707.</p><p>[2] A. Salih, Inviscid Burgers’ Equation. Lecture notes. Department of Aerospace Engineering Indian Institute of Space Science and Technology.</p><p>[3] J Unterberger, Global existence for strong solutions of viscous Burgers equation. March 2015. Control and Cybernetics 46(2).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=147bb75d0715" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/can-neural-networks-formulate-shock-wave-147bb75d0715">Can Neural Networks Formulate Shock Wave?</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[How to Interpret GPT2-Small]]></title>
            <link>https://medium.com/data-science/how-to-interpret-gpt2-small-76e0536a588a?source=rss-9b74bc8c860d------2</link>
            <guid isPermaLink="false">https://medium.com/p/76e0536a588a</guid>
            <category><![CDATA[interpretability]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[gpt]]></category>
            <dc:creator><![CDATA[Shuyang Xiang]]></dc:creator>
            <pubDate>Fri, 22 Mar 2024 00:22:01 GMT</pubDate>
            <atom:updated>2024-03-22T08:56:20.685Z</atom:updated>
            <content:encoded><![CDATA[<h4>Mechanistic Interpretability on prediction of repeated tokens</h4><p>The development of large-scale language models, especially ChatGPT, has left those who have experimented with it, myself included, astonished by its remarkable linguistic prowess and its ability to accomplish diverse tasks. However, many researchers, including myself, while marveling at its capabilities, also find themselves perplexed. Despite knowing the model’s architecture and the specific values of its weights, we still struggle to comprehend why a particular sequence of inputs leads to a specific sequence of outputs.</p><p>In this blog post, I will attempt to demystify GPT2-small using mechanistic interpretability on a simple case: the prediction of repeated tokens.</p><h3>Mechanistic Interpretability</h3><p>Traditional mathematical tools for explaining machine learning models aren’t entirely suitable for language models.</p><p>Consider SHAP, a helpful tool for explaining machine learning models. It’s proficient at determining which feature significantly influenced the prediction of a good quality wine. However, it’s important to remember that language models make predictions at the token level, while SHAP values are mostly computed at the feature level, making them potentially unfit for tokens.</p><p>Moreover, Language Models (LLMs) have numerous parameters and inputs, creating a high-dimensional space. Computing SHAP values is costly even in low-dimensional spaces, and even more so in the high-dimensional space of LLMs.</p><p>Despite tolerating the high computational costs, the explanations provided by SHAP can be superficial. For instance, knowing that the term “potter” most influenced the output prediction due to the earlier mention of “Harry” doesn’t provide much insight. It leaves us uncertain about the part of the model or the specific mechanism responsible for such a prediction.</p><p>Mechanistic Interpretability offers a different approach. It doesn’t just identify important features or inputs for a model’s predictions. Instead, it sheds light on the underlying mechanisms or reasoning processes, helping us understand how a model makes its predictions or decisions.</p><h3>Prediction of repeated tokens by GPT2-Small</h3><p>We will be using GPT2-small for a simple task: predicting a sequence of repeated tokens. The library we will use is <a href="https://neelnanda-io.github.io/TransformerLens/index.html">TransformerLens</a>, which is designed for <a href="https://distill.pub/2020/circuits/zoom-in/">mechanistic interpretability</a> of GPT-2 style language models.</p><pre>gpt2_small: HookedTransformer = HookedTransformer.from_pretrained(&quot;gpt2-small&quot;)</pre><p>We use the code above to load the GPT2-Small model and predict tokens on a sequence generated by a specific function. This sequence includes two identical token sequences, followed by the bos_token. An example would be “ABCDABCD” + bos_token when the seq_len is 3. For clarity, we refer to the sequence from the beginning to the seq_len as the first half, and the remaining sequence, excluding the bos_token, as the second half.</p><pre>def generate_repeated_tokens(<br>    model: HookedTransformer, seq_len: int, batch: int = 1<br>) -&gt; Int[Tensor, &quot;batch full_seq_len&quot;]:<br>    &#39;&#39;&#39;<br>    Generates a sequence of repeated random tokens<br><br>    Outputs are:<br>        rep_tokens: [batch, 1+2*seq_len]<br>    &#39;&#39;&#39;<br>    bos_token = (t.ones(batch, 1) * model.tokenizer.bos_token_id).long()  # generate bos token for each batch<br><br>    rep_tokens_half = t.randint(0, model.cfg.d_vocab, (batch, seq_len), dtype=t.int64)<br>    rep_tokens = t.cat([bos_token,rep_tokens_half,rep_tokens_half], dim=-1).to(device)<br>    return rep_tokens</pre><p>When we allow the model to run on the generated token, we find an interesting observation: the model performs significantly better on the second half of the sequence than on the first half. This is measured by the log probabilities on the correct tokens. To be precise, the performance on the first half is -13.898, while the performance on the second half is -0.644.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqUpWEjf8hK9G6XjAKqplA.png" /><figcaption>Image for author: Log probs on correct tokens</figcaption></figure><p>We can also calculate prediction accuracy, defined as the ratio of correctly predicted tokens (those identical to the generated tokens) to the total number of tokens. The accuracy for the first half sequence is 0.0, which is unsurprising since we’re working with random tokens that lack actual meaning. Meanwhile, the accuracy for the second half is 0.93, significantly outperforming the first half.</p><h3>Induction Circuits</h3><h4>Finding induction head</h4><p>The observation above might be explained by the existence of an induction circuit. This is a circuit that scans the sequence for prior instances of the current token, identifies the token that followed it previously, and predicts that the same sequence will repeat. For instance, if it encounters an ‘A’, it scans for the previous ‘A’ or a token very similar to ‘A’ in the embedding space, identifies the subsequent token ‘B’, and then predicts the next token after ‘A’ to be ‘B’ or a token very similar to ‘B’ in the embedding space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*cg94T3U_3ApQ-yuh6zNT3Q.png" /><figcaption>Image by author: Induction circuit</figcaption></figure><p>This prediction process can be broken down into two steps:</p><ol><li>Identify the previous same (or similar) token. Every token in the second half of the sequence should “pay attention” to the token ‘seq_len’ places before it. For instance, the ‘A’ at position 4 should pay attention to the ‘A’ at position 1 if ‘seq_len’ is 3. We can call the attention head performing this task the “<strong>induction head</strong>.”</li><li>Identify the following token ‘B’. This is the process of copying information from the previous token (e.g., ‘A’) into the next token (e.g., ‘B’). This information will be used to “reproduce” ‘B’ when ‘A’ appears again. We can call the attention head performing this task the “<strong>previous token head</strong>.”</li></ol><p>These two heads constitute a complete induction circuit. Note that sometimes the term “induction head” is also used to describe the entire “induction circuit.” For more introduction of induction circuit, I highly recommend the article <a href="https://transformer-circuits.pub/2022/in-context-learning-and-induction-heads/index.html">In-context learning and induction head</a> which is a master piece!</p><p>Now, let’s identify the attention head and previous head in GPT2-small.</p><p>The following code is used to find the induction head. First, we run the model with 30 batches. Then, we calculate the mean value of the diagonal with an offset of seq_len in the attention pattern matrix. This method lets us measure the degree of attention the current token gives to the one that appears seq_len beforehand.</p><pre>def induction_score_hook(<br>    pattern: Float[Tensor, &quot;batch head_index dest_pos source_pos&quot;],<br>    hook: HookPoint,<br>):<br>    &#39;&#39;&#39;<br>    Calculates the induction score, and stores it in the [layer, head] position of the `induction_score_store` tensor.<br>    &#39;&#39;&#39;<br>    induction_stripe = pattern.diagonal(dim1=-2, dim2=-1, offset=1-seq_len) # src_pos, des_pos, one position right from seq_len<br>    induction_score = einops.reduce(induction_stripe, &quot;batch head_index position -&gt; head_index&quot;, &quot;mean&quot;)<br>    induction_score_store[hook.layer(), :] = induction_score<br><br>seq_len = 50<br>batch = 30<br>rep_tokens_30 = generate_repeated_tokens(gpt2_small, seq_len, batch)<br>induction_score_store = t.zeros((gpt2_small.cfg.n_layers, gpt2_small.cfg.n_heads), device=gpt2_small.cfg.device)<br><br><br>    rep_tokens_30,<br>    return_type=None, <br>        pattern_hook_names_filter,<br>        induction_score_hook<br>    )]<br>)</pre><p>Now, let’s examine the induction scores. We’ll notice that some heads, such as the one on layer 5 and head 5, have a high induction score of 0.91.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*YAnk4CoUXGQgyeCiLN2r8Q.png" /><figcaption>Image by author: Induction head scores</figcaption></figure><p>We can also display the attention pattern of this head. You will notice a clear diagonal line up to an offset of seq_len.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*iE3_JZKil0J-LrpH_Cst-w.png" /><figcaption>Image by author: layer 5, head 5 attention pattern</figcaption></figure><p>Similarly, we can identify the preceding token head. For instance, layer 4 head 11 demonstrates a strong pattern for the previous token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*KAeTFr7TBm3887wPEi0UsA.png" /><figcaption>Image by author: previous token head scores</figcaption></figure><h4>How do MLP layers attribute?</h4><p>Let’s consider this question: do MLP layers count? We know that GPT2-Small contains both attention and MLP layers. To investigate this, I propose using an ablation technique.</p><p>Ablation, as the name implies, systematically removes certain model components and observes how performance changes as a result.</p><p>We will replace the output of the MLP layers in the second half of the sequence with those from the first half, and observe how this affects the final loss function. We will compute the difference between the loss after replacing the MLP layer outputs and the original loss of the second half sequence using the following code.</p><pre>def patch_residual_component(<br>    residual_component,<br>    hook,<br>    pos,<br>    cache,<br>):<br>    residual_component[0,pos, :] = cache[hook.name][pos-seq_len, :]<br>    return residual_component<br><br>ablation_scores = t.zeros((gpt2_small.cfg.n_layers, seq_len), device=gpt2_small.cfg.device)<br><br>gpt2_small.reset_hooks()<br>logits = gpt2_small(rep_tokens, return_type=&quot;logits&quot;)<br>loss_no_ablation = cross_entropy_loss(logits[:, seq_len: max_len],rep_tokens[:, seq_len: max_len])<br><br>for layer in tqdm(range(gpt2_small.cfg.n_layers)):<br>  for position in range(seq_len, max_len):<br>    hook_fn = functools.partial(patch_residual_component, pos=position, cache=rep_cache)<br>    ablated_logits = gpt2_small.run_with_hooks(rep_tokens, fwd_hooks=[<br>              (utils.get_act_name(&quot;mlp_out&quot;, layer), hook_fn)<br>    ])<br>    loss = cross_entropy_loss(ablated_logits[:, seq_len: max_len], rep_tokens[:, seq_len: max_len])<br>    ablation_scores[layer, position-seq_len] = loss - loss_no_ablation</pre><p>We arrive at a surprising result: aside from the first token, the ablation does not produce a significant logit difference. This suggests that the MLP layers may not have a significant contribution in the case of repeated tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*6dtICd7bWoxvBbOt2WIsKg.png" /><figcaption>Image by author: loss different before and after ablation of mlp layers</figcaption></figure><h3><strong>One induction circuit</strong></h3><p>Given that the MLP layers don’t significantly contribute to the final prediction, we can manually construct an induction circuit using the head of layer 5, head 5, and the head of layer 4, head 11. Recall that these are the induction head and the previous token head. We do it by the following code:</p><pre>def K_comp_full_circuit(<br>    model: HookedTransformer,<br>    prev_token_layer_index: int,<br>    ind_layer_index: int,<br>    prev_token_head_index: int,<br>    ind_head_index: int<br>) -&gt; FactoredMatrix:<br>    &#39;&#39;&#39;<br>    Returns a (vocab, vocab)-size FactoredMatrix,<br>    with the first dimension being the query side<br>    and the second dimension being the key side (going via the previous token head)<br><br>    &#39;&#39;&#39;<br>    W_E = gpt2_small.W_E<br>    W_Q = gpt2_small.W_Q[ind_layer_index, ind_head_index]<br>    W_K = model.W_K[ind_layer_index, ind_head_index]<br>    W_O = model.W_O[prev_token_layer_index, prev_token_head_index]<br>    W_V = model.W_V[prev_token_layer_index, prev_token_head_index]<br><br>    Q = W_E @ W_Q<br>    K = W_E @ W_V @ W_O @ W_K<br>    return FactoredMatrix(Q, K.T)</pre><p>Computing the top 1 accuracy of this circuit yields a value of 0.2283. This is quite good for a circuit constructed by only two heads!</p><p>For detailed implementation, please check my <a href="https://colab.research.google.com/drive/1_Qx67oPB2ZNeKa1ANYhFa9tkKGSZhX6a#scrollTo=ss1yF3e8PNYD"><em>notebook</em></a>. And many thanks to Neel Nanda who developed the wonderful <a href="https://neelnanda-io.github.io/TransformerLens/index.html">TransformerLen</a> as a great tool for Mechanistic Interpretability of LLMs!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76e0536a588a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-interpret-gpt2-small-76e0536a588a">How to Interpret GPT2-Small</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[How Can AI Help Visually Impaired People See The World]]></title>
            <link>https://pub.towardsai.net/how-can-ai-help-visually-impaired-people-see-the-world-4389cb326f0d?source=rss-9b74bc8c860d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4389cb326f0d</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[visually-impaired]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Shuyang Xiang]]></dc:creator>
            <pubDate>Thu, 28 Dec 2023 08:26:15 GMT</pubDate>
            <atom:updated>2023-12-29T12:36:07.837Z</atom:updated>
            <content:encoded><![CDATA[<h4>An attempt to craft an App empowered by LLM to support the visually impaired</h4><h3>My Passion for AI and Challenges Faced by the Visually Impaired</h3><p>For over six years, I’ve dedicated my time as a volunteer for an association aiding visually impaired individuals in their daily tasks — tasks that are seemingly simple for those of us with sight, such as shopping, reading, visiting a doctor, or merely taking a walk.</p><p>Lately, however, I find myself increasingly frustrated. On one side, my passion lies in mathematics and AI, yet on the other, my visually impaired friends continue to grapple with basic daily activities, reaping little benefit from the rapid advancements in AI. Instead of bridging the gap between us and them, it seems that new technologies are only widening it.</p><p>I have been contemplating for a while about how AI, particularly Large Language Models (LLMs), could play a role in narrowing the gap. This blog post marks my initial attempt, acknowledging that it’s still in its early stages of development. I aim to share my nascent ideas and implementations here, serving as the starting point for my exploration. I welcome discussions and hope that if someone is interested in taking the next step with me, it would be truly appreciated.</p><h3>A Voice to Voice Vision Assistant</h3><p>I am embarking on the development of a voice-controlled image assistant powered by LLMs as one of my initial initiatives. This project is driven by the recognition that visually impaired individuals often face challenges in performing basic tasks, such as object detection and color recognition. The purpose of this assistant is to provide a means for them to interact with an AI assistant independently of their visual limitations. By leveraging advanced algorithms in computer vision, the assistant aims to empower users by offering a virtual vision that transcends the reliance on their eyes, allowing them to experience the world through the lens of technology.</p><p>In essence, my idea is to construct an agent through Langchain on ChatGPT, coupled with a variety of image-related tools like color recognition and object detection. Departing from traditional text-based input and output, our interaction with the language agent will be facilitated through voice, using both speech recognition and text-to-speech tools.</p><h4>Voice to voice</h4><p>For transcribing Audio to Text as LLM’s input, we can use SpeechRecognition with google speech api.</p><pre>recognizer = sr.Recognizer()<br> with sr.Microphone() as source:<br>     recognizer.adjust_for_ambient_noise(source,duration=4)<br>     audio=recognizer.listen(source)<br>     user_input=recognizer.recognize_google(audio, language=&#39;en&#39;)</pre><p>The code initializes a recognizer object from the speech_recognition library, serving as a tool for audio processing and speech recognition. This enables the transformation of audio signals into text. For a comprehensive understanding and exploration of additional recognition options, kindly refer to the detailed information provided in this accompanying <a href="https://saiharishcherukuri.medium.com/real-time-speech-recognition-and-voice-enabled-ai-chatbot-integration-using-bing-and-openai-80f3709d870f">blog post</a>.</p><p>To convert the text output generated by the LLM into spoken words, we will employ gTTS (Google Text-to-Speech) and playsound modules.</p><pre>response_voice = gTTS(text=response, lang=&#39;en&#39;, slow=False)<br>response_voice.save(&quot;response_voice.mp3&quot;)<br>playsound.playsound(&quot;response_voice.mp3&quot;)</pre><p>The code utilizes gTTS to convert the response text into speech, saving the audio locally, and then plays it using playsound. While this initial prototype relies on gTTS, it’s worth noting that there are alternative options for achieving higher-quality voice synthesis, such as leveraging the AWS Polly engine for a more realistic text-to-speech experience.</p><h4>Image tools</h4><p>Much of our interaction with the world is shaped by our visual perception. Simple tasks like recognizing objects and identifying colors come effortlessly to us. However, when faced with a scenario devoid of visual input, even tasks as basic as selecting color-coordinated attire can pose a challenge.</p><p>In light of this, my intention is to construct a language agent enhanced by a suite of image-related tools. To articulate the tools accessible to the Language Model (LLM), we employ langchain tools:</p><pre>from langchain.tools import tool<br>import torch<br>from torchvision import transforms<br>from torchvision.models.detection import fasterrcnn_resnet50_fpn<br><br>@tools.append<br>@tool<br>def object_detection(image_path: str):<br>    &quot;&quot;&quot;Use this tool to dectect objects.<br>     It will return the detected objects and their quantities.&quot;&quot;&quot;<br>    # TODO: find a way to search for the latest image<br>    threshold=0.5<br><br>    model = fasterrcnn_resnet50_fpn(pretrained=True)<br>    model.eval()<br><br>        # Load and preprocess the input image<br>    image = Image.open(image_path).convert(&quot;RGB&quot;)<br>    transform = transforms.Compose([transforms.ToTensor()])<br>    image_tensor = transform(image).unsqueeze(0)<br><br>    # Make predictions<br>    with torch.no_grad():<br>        predictions = model(image_tensor)<br><br>    # Filter predictions based on confidence threshold<br>    labels = predictions[0][&#39;labels&#39;][predictions[0][&#39;scores&#39;] &gt; threshold]<br>    labels=[COCO_INSTANCE_CATEGORY_NAMES[label] for label in labels]<br>    labels = Counter(labels)<br>    # Generate the formatted string<br>    result = &#39;, &#39;.join(<br>        f&quot;{count}: {label}s&quot; if count &gt; 1 else f&quot;{count} {label}&quot; for label, count in labels.items())<br><br>    return result</pre><p>As described, the tool accepts an image path as input and provides the detected objects along with their respective quantities as output. It employs the pretrained model fasterrcnn_resnet50_fpn, which predicts bounding box coordinates and class probabilities. We selectively consider labels with probabilities surpassing a predefined threshold.</p><p>It’s essential to note that the model outputs integer labels, which may not be intuitive for users. To address this, we utilize a dictionary named COCO_INSTANCE_CATEGORY_NAMES to translate these integers into human-readable label names, such as “bike,” “bus,” and so forth.</p><p>Introducing our next tool, specifically designed for color recognition.</p><pre>import cv2<br>from sklearn.cluster import KMeans<br>from webcolors import CSS3_NAMES_TO_HEX, hex_to_rgb, rgb_to_name<br><br>@tools.append<br>@tool<br>def cluster_colors(image_path):<br>    &quot;&quot;&quot;Use this tool to find three main colors in the image&quot;&quot;&quot;<br>    image = cv2.imread(image_path)<br>    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  # Convert to RGB format<br><br>    # Reshape the image to a 2D array of pixels<br>    pixels = image.reshape((-1, 3))<br><br>    # Use K-means clustering to find dominant colors<br>    kmeans = KMeans(n_clusters=3)<br>    kmeans.fit(pixels)<br><br>    # Get the RGB values of the cluster centers<br>    dominant_colors = kmeans.cluster_centers_.astype(int)<br><br>    # Convert RGB values to color names<br>    color_names = []<br>    for color in dominant_colors:<br>        try:<br>            color_name = rgb_to_name((color[0], color[1], color[2]))<br>        except:<br>            # If the color name is not found, find the closest CSS3 color name<br>            color_name = find_closest_color_name(color)<br>        color_names.append(color_name)<br><br>    # Join the color names into a string, separated by commas<br>    color_names_string = &#39;, &#39;.join(color_names)<br><br>    return color_names_string</pre><p>As outlined in the description, this tool accepts the image path as input and extracts the three predominant colors present in the image. This is achieved by employing K-means clustering to group all colors into three main clusters. Subsequently, the center of each cluster is utilized to identify the corresponding color name with the help of the webcolor library.</p><p>It’s noteworthy that in cases where the RGB value does not precisely correspond to a name in the webcolor dictionary, the tool intelligently finds the nearest matching color name instead. While the intricate details are omitted here, this approach ensures accurate color recognition across a diverse range of images.</p><h4><strong>Langchain Agent</strong></h4><p>We are now ready to construct an agent using the standard initialize_agent API provided by Langchain:</p><pre>from langchain.memory import ConversationBufferMemory<br>from langchain.agents import initialize_agent, AgentType<br><br>agent = initialize_agent(<br>        tools,<br>        llm,<br>        agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION,<br>        memory=conversational_memory,<br>        verbose=True<br>    )</pre><p>The code establishes an agent by incorporating the image-related tools defined earlier.</p><h4>Vision Assistant</h4><p>With all the necessary components in place, we are poised to create our voice-to-voice vision assistant. The model’s architecture is illustrated in the chart below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1iSFFEAI77QjhoTkG4nKA.png" /><figcaption>Image by author: Vison assistant illustration</figcaption></figure><p>For a visual demonstration of how it operates, you can refer to the video I’ve created:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDRrvMHcZagQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDRrvMHcZagQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDRrvMHcZagQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2e9813a52517efcaf1c17abdbda4e36/href">https://medium.com/media/c2e9813a52517efcaf1c17abdbda4e36/href</a></iframe><h3>Embarking on Inclusive AI</h3><p>In the preceding chapter, I have developed a vision assistant empowered by LLM. This technology holds the potential to benefit visually impaired individuals by assisting them with tasks such as object detection and color recognition. Moreover, as the system evolves, it may encompass additional vision functionalities to further enhance its utility.</p><p>Nevertheless, it’s crucial to acknowledge that this remains a very early-stage prototype. My motivation for undertaking this initiative is to draw attention from the community toward the prospect of leveraging AI to aid marginalized groups within society, particularly those with visual impairments. I hold a modest hope that anyone sharing an interest in this subject might reach out, and together, we could potentially pave the way for a more comprehensive and mature project in the future.</p><p>The comprehensive implementation is available on my <a href="https://github.com/ShuyangenFrance/vision-assistant">GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4389cb326f0d" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/how-can-ai-help-visually-impaired-people-see-the-world-4389cb326f0d">How Can AI Help Visually Impaired People See The World</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>