<?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 OXEN AI.  Build World-Class AI Datasets. Together. on Medium]]></title>
        <description><![CDATA[Stories by OXEN AI.  Build World-Class AI Datasets. Together. on Medium]]></description>
        <link>https://medium.com/@oxenai?source=rss-82ea984bd9af------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FX-s8MyyiDFrcdaT4OkEbw.png</url>
            <title>Stories by OXEN AI.  Build World-Class AI Datasets. Together. on Medium</title>
            <link>https://medium.com/@oxenai?source=rss-82ea984bd9af------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:26:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oxenai/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[How to Train Diffusion for Text from Scratch | Oxen.ai]]></title>
            <link>https://medium.com/@oxenai/how-to-train-diffusion-for-text-from-scratch-oxen-ai-fd74c1014e3e?source=rss-82ea984bd9af------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd74c1014e3e</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[OXEN AI.  Build World-Class AI Datasets. Together.]]></dc:creator>
            <pubDate>Tue, 30 Apr 2024 17:28:09 GMT</pubDate>
            <atom:updated>2024-04-30T17:28:09.879Z</atom:updated>
            <content:encoded><![CDATA[<p>This is part two of a series on <a href="https://www.oxen.ai/blog/arxiv-dives-text-diffusion-with-sedd?ref=ghost.oxen.ai">Diffusion for Text with Score Entropy Discrete Diffusion (SEDD) models</a>. Today we will be diving into the code for diffusion models for text, and see how they work from the inputs to the outputs to the intermediate representations of the diffusion process itself. By the end of it you will be able to train an end to end diffusion model for text and have a better understanding of the benefits and current limitations.</p><p>We do this series of <a href="https://www.oxen.ai/community/arxiv-dives?ref=ghost.oxen.ai">ArXiv Dives</a> live on Fridays with the Oxen.ai community. We believe that it is not only important to read the papers, but dive into the code that comes along with them to truly understand the implications, impact, and be able to apply the learnings to your own work.</p><p>The following are notes from our live session, feel free to follow along with the video below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Ff4tRAVGoWas%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Df4tRAVGoWas&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Ff4tRAVGoWas%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff84f3da10b6ecfc69a83d9075739f01/href">https://medium.com/media/ff84f3da10b6ecfc69a83d9075739f01/href</a></iframe><h3>Paper &amp; Code</h3><p>Discrete Diffusion Modeling by Estimating the Ratios of the Data Distribution by the teams at Stanford and Pika Labs.</p><p><a href="https://arxiv.org/abs/2310.16834?ref=ghost.oxen.ai">Discrete Diffusion Modeling by Estimating the Ratios of the Data Distribution</a></p><p>Big shout out to @louaaron and team for the <a href="https://github.com/louaaron/Score-Entropy-Discrete-Diffusion?ref=ghost.oxen.ai">initial code implementation</a> that was released along side the paper. For this dive, we stripped down the original code base and simplified for optimized for my own clarity and understanding. The modified codebase can run on a single A10 GPU depending on the model and batch sizes and tokenizer you use.</p><p><a href="https://github.com/Oxen-AI/Score-Entropy-Discrete-Diffusion?ref=ghost.oxen.ai">GitHub - Oxen-AI/Score-Entropy-Discrete-Diffusion: Modified Score-Entropy-Discrete-Diffusion to do a character level ml model and integrate with Oxen</a></p><h3>Quick Refresher on Diffusion for Text</h3><p>We went over the math and paper in detail <a href="https://www.oxen.ai/blog/arxiv-dives-text-diffusion-with-sedd?ref=ghost.oxen.ai">last week</a>, but to set context the end goal is a generative LLM that instead of generating text token by token, can generate the entire sequence at once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pynk_B1lCMw6vjse.gif" /></figure><p>Just like diffusion for images or video, the idea is we start with a noisy random text sequence and slowly de-noise text into a coherent passage. You should be able to trade off compute (time steps) for text quality and coherence.</p><h3>Why diffusion for text?</h3><p>The paper cites a few reasons that diffusion is appealing for text. The first is pure performance when measured by perplexity (how “perplexed” is the model to see the next word given a dataset and the model’s predicted probabilities).</p><p>SEDD Outperforms GPT-2 model of same size trained on the same amount of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*epTkbWLexPHx00r0.jpeg" /></figure><p>You may be thinking…but GPT-2 is old? Yes but we must start research somewhere. What’s nice is you don’t need too much compute to reproduce at least this size of a model, and you can trade off compute for quality during inference which is harder to do with standard auto-regressive modeling.</p><p>The second reason is that diffusion models are more optimized for parallel compute, and can take advantage of modern hardware like GPUs better than auto-regressive models. Auto-regressive models predict the next token one by one given the previous context. This means we must process the text sequentially instead of dividing and conquering in parallel.</p><p>The third reason is the fact that if an auto-regressive model makes a mistake, the errors can cascade. Yann Lecun calls this a “generation drifts” from the data distribution and causes the model to diverge during sampling. Diffusion has the benefit of using the complete global context during generation, resulting in better overall generation.</p><p>Finally, diffusion enables prompting from any position, or multiple positions, enabling use cases such as infilling or completing a prefix before a suffix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*bw9vVDPRWAtFUFrh.png" /></figure><p>Let’s put these reasons to the test…</p><h3>Diving into training details 🤿</h3><p>Before starting any model training, you need a dataset. To reproduce results similar to GPT-2, we need a dataset of text from the web. Luckily people have re-created such a dataset called OpenWebText. We took the time to index it into Oxen.ai if you want to reproduce the full paper results. Feel free to download it from here the link below.</p><p><a href="https://www.oxen.ai/datasets/OpenWebText?ref=ghost.oxen.ai">datasets/OpenWebText | Datasets at Oxen.ai</a></p><p>If you are not familiar with <a href="http://oxen.ai/?ref=ghost.oxen.ai">Oxen.ai</a>, it is a hub for large multi-modal machine learning datasets. Files of the scale and size that you would never check into git seamlessly index into Oxen.</p><p>The models cited in the paper are the same sizes as GPT-2. They also have the same tokenizer which contains a vocab of 50256 tokens.</p><h3>Pre-Trained SEDD Demo</h3><p>The first thing to do when trying out any model’s codebase is to test out any pre-trained models they have and see how it performs.</p><p>You can download the pre-trained model from Oxen.ai by using the oxen clone command.</p><pre>oxen clone https://hub.oxen.ai/models/SEDD-large</pre><p>Then run the script from the <a href="https://github.com/Oxen-AI/Score-Entropy-Discrete-Diffusion?ref=ghost.oxen.ai">GitHub Repo</a> to sample from it.</p><pre>python scripts/run_sample.py --model /path/to/SEDD-large/ --steps 1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bI683E51OoCn6X3-.png" /></figure><p>You will see text that does not look very coherent with a single step. Some english words, some invalid UTF-8. But promising start given it is supposed to start with noise. Let’s crank up the number of diffusion steps and see if it improves.</p><pre>python scripts/run_sample.py --model /path/to/SEDD-large/ --steps 10</pre><p>A little better…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qUbWup-GXt_sFId7.png" /></figure><p>We can see we have more valid english words, and some phrases that are definitely coherent. Now crank it up to 1024 and see what the output looks like.</p><pre>python scripts/run_sample.py --model /path/to/SEDD-large/ --steps 1024</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NRN0e-UTIbkvwXpp.png" /></figure><p>This time the entire context is rather coherent, and talking about the same subject the whole time — race cars.</p><p>Each time you run the script, it with sample randomly so it is hard to see how the text actually changes step by step. You can pass in a --show_intermediate flag to the script to print out the intermediate outputs and see how it slowly diffuses the text.</p><pre>python scripts/run_sample.py --model /path/to/SEDD-large/ --steps 10 --show_intermediate</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iVWL_EX1D0I_uWBL.png" /></figure><p>We can see we are progressively swapping tokens as we go along, to eventually arrive at something more and more! That’s great.</p><p>Now how does it actually work under the hood?</p><h3>Sampling with Model, Graph, and Noise</h3><p>If you recall from our dive <a href="https://www.oxen.ai/blog/arxiv-dives-text-diffusion-with-sedd?ref=ghost.oxen.ai">last week</a>, it is infeasible to add/remove noise every token at once within the sequence. <strong>Unlike images, text is represented by discrete values</strong>. Where small perturbations in pixel values result in an almost identical image, this is not the case with text.</p><p>Take for instance a simple <a href="https://en.wikipedia.org/wiki/Caesar_cipher?ref=ghost.oxen.ai">Caesar Cipher</a>. Remember, text is usually represented by tokens, which map to indices in a lookup table. If we change the index by just adding +1 to each value, we turn a coherent sentence into garbage in one fell swoop.</p><pre>python scripts/caeser_cipher.py &quot;Uploading large datasets with Oxen.ai is a satisfying 😌&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*scRQjFQMbArEW4_1.png" /></figure><h3>The Graph</h3><p>This means the diffusion process cannot add noise by simply adding a small number to the text indices. This paper addresses this problem by instead only modifying a subset of token indices at each step, progressively flipping more and more. The number of tokens we flip is called the “hamming distance”. If you only flip one token in a phrase, this would be a hamming distance of one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-ZV9kapMjH5PHzyK.png" /></figure><p>In theory, we can have a noise parameter that is passed into the model that represents roughly the hamming distance to the original text as context, then ask the model to predict which tokens to flip to make the text more coherent.</p><p>In the code, the component that does the flipping is called the AbsorbingGraph . The component that generates the noise is called LogLinearNoise . Together they can be used during model training and inference to corrupt text with noise and then de-noise it.</p><p>Let’s demo the AbsorbingGraph in action with a script that flips a random amount of tokens at given time step values.</p><pre>python scripts/demo_perturb.py &quot;Applying diffusion to text is kind of crazy&quot; -t 0.35</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ALKl-2HypMyhbWtZ.png" /></figure><p>In the case above, we passed in a time step value of 0.35 , tokenized the text, and then flipped a subset of tokens to the value 50257. If you recall, the tokenizer for GPT-2 has 50256 tokens, so this flipped value is an extra token that we can &quot;absorb&quot; and replace with &#39;&#39; (an empty string).</p><p>The text was perturbed from “Applying diffusion to text is kind of crazy” → “Applying diffusion text is kind”. The idea is that at training time we will randomly noise the training data with different known values and the models job is to figure out which tokens to flip back given the current text and the known noise level.</p><p>The code that actually does the flipping is in sedd/models/graph.py under the AbsorbingGraph.sample_transition function. Let&#39;s add some print statements to see how this works in practice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8mLrmXasteTClRxQ.png" /></figure><p>Let’s run the same script again and see what these intermediate values are.</p><pre>python scripts/demo_perturb.py &quot;Applying diffusion to text is kind of crazy&quot; -t 0.35</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_VXfllIbqUiKKTXi.png" /></figure><p>For one, you can see the randomness because we now perturbed the text to be “App diffusion to crazy”. The move chance represents how likely we are to swap any individual token to 20257 and then we get our a mask to swap those tokens appropriately.</p><h3>Loss Function</h3><p>If you look at the loss function, we sample a random t and noise, perturb the tokens, have the model look at the perturbed sentence, the noise, and the original sentence to compute our loss value.</p><pre>sedd/trainer/loss.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qsUo4zRnsEkfjnvn.png" /></figure><p>The model’s job is to assign high probability transitions to tokens that should be flipped given the level of noise. During training we sample a random time step each iteration, and the model has to guess which tokens were flipped and with what probability.</p><p>There is a script called scripts/demo_loss.py to make this more concrete. Uncomment the log_score and loss values before running this script.</p><pre>python scripts/demo_loss.py &quot;Oxen plows and maintains your fields of data&quot; -m /path/to/SEDD-large/ -t 0.5</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BPqey7jtKhFgGNs-.png" /></figure><p>Look closely at the shape of the log_score and the loss tensors. In this case we have 10 tokens. We then corrupt the tokens with a move probability of 0.5. The score that comes out of the model is [batch_size, context_len, vocab_size]. This means for each token we have a probability mass function representing which token from the vocab we should replace each token in our sequence with. If the probability of the current token is close to what the model predicts, our loss will be low.</p><p>If we do this over and over again during training, Monte Carlo sampling random levels of noise and our training distribution, eventually we will be able to estimate the full probability mass function and flip the tokens to more and more coherent values.</p><h3>The Model</h3><p>Under the hood, the model is simply a transformer with an output layer the shape of the log_score tensor above. The paper uses the same number of layers and block size as the GPT-2 paper. A transformer is able to use it&#39;s self attention mechanism to look at the entire context of the noised input to try to decide which tokens to flip.</p><p>They pass in the time step as an embedded value as well as use rotary embeddings for encoding the position of each token. Flash attention is used to speed up compute. Full model code can be found in sedd/models/sedd.py.</p><h3>Inference</h3><p>Now take a look at the inference code that reverses the text from random noise to coherent text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*291ldd6vRP4fDztt.png" /></figure><p>Given the number of time steps, we generate a linear set of values from [1.0 .. 0.0]. Then we sample from the model passing in the previous prediction, the time step, and the delta in time step. The projector function is used for prompting simply overwriting tokens with fixed values if we provide them.</p><p>What’s cool is you can use the simple projector function to prompt from any location in your text.</p><pre>def proj_fun(x): <br>  x[:, input_locs] = input_ids<br>  return x</pre><p>This overwrites indices during inference and insure the model uses them for the next time step.</p><p>To see the prefix and suffix prompting in action, you can run scripts/run_sample_cond.py</p><pre>python scripts/run_sample_cond.py --model /path/to/SEDD-large/ --prefix &quot;Hi my name is&quot; --suffix &quot;and that&#39;s why I&#39;m late&quot; --steps 1024</pre><blockquote><em>Hi my name is Sydney Jordan Brothers. I was a very good basketball player when I got there. Petersen and Richie, when I had, well, they were not an adopted brother but they were some similarities []. They both killed high balls. They were much brotherlier than me and much calmer than me. And they’re both very strong guys. They’re really-they’re really strong. I think was what keeps them happy. When I got there, I didn’t tell anybody because we heard about the same thing because I was a nonpro player. When I looked around and I was really happy, they no told what about me back then. But there were stupid rumors about running down the street and the same way we did things over there. But people you know why we’re happy is there was different environment and it’s a different type of individual I guess. Nobody was ready to workout like we grew up doing. It’s just, I was a first drop by teams. And it was only because the coaches had pushed me and I was ready to do it. It was another thing to-you know, because nobody knew about nobody, man, I wasn’t happy whatsoever. You was never after them for three years. You like it for a little bit. There’s a group of people that love you. You time out your business, and people you met at work were like, a few of them then come back and see your time. It’s a bit like a motion shoot. You know, it was the best part of my career. It was a lot and I was pretty good at making it work. You think how they treated you as a basketball player is a curse or curse? Just as I described it, that’s the main thing why I’m happy for a basketball player, I guess.</em></blockquote><blockquote><em>CW: Right. For most guys it’s the same thing. Yeah, you go drive to the mall going down there and you walk into the street and you drive by your family. You drive at night because that’s normally it. Those are your only customers so you drive by your family a lot. Yeah. For me, these days, I drive by my house. That’s the same thing is you’re a pro at this time at practice and they can send you to immediately go in and go to the house, at night, to see if you like the house. Until then, the house. If I’m sorry to tell you that you were offended or saying something, it takes awhile and then just shut up like me because you get used to it so much, you’re not talking about yourself, you’re just about the house. Or the house, you’re the housekeeper. The core thing is, because of the way you are treated and compared to guys the like of the leagues, perhaps you’d different and be done differently. That, I think there should be. Most players think it’s for the league to give them better treatment because the players are-you know, there are ten million five thousand of them, when you don’t know them, let’s be honest with you. That could get us killed. But they could be freaking out. Not today. I don’t think they want that. The other reason, for that to be a tough play, is, these players get paid. If you have millions in sports, you can be big, and if you can be little, you might not have so much. And they are playing here. So, when they first came in, and they know you, and they know the pay and you’re sitting and they expect you to get up to the car and pay up and drive home. You’re not supposed to say anything. It’s just like, I paid. We don’t have-money was not as good as us. But they have a bit. How is there money then? Yeah, they’d just have to use it more on our behalf. Yeah, that’s the way they’ve got to be careful, not the players, not the NBA, the league. I think these years, until it’s too late-Mille Mason didn’t hang around when I was 10. I mean, yeah, I hung around at home.. He threw perfect. I mean, we didn’t know he played football until 8. So, I remember him. I didn’t get around when he was like 10. And he’s just no slow mover just. He was a [earner than the first 300 receivers] from when he was done until he got released. So Nick comes along and they settle in, and he’s my friend, and I’m there. I had an introduction with him. We at, i think, hey, this is you, we’re talking to you, we are getting to know you and we know you, it’s life, it’s not like you have to have to be a regular job and it’s supposed to be fun. So that’s the real thing about it-and that’s why I’m late</em></blockquote><p>In theory this would be really nice to be able to prompt something like the the beginning of a code snippet, and the end, and be able to fill in the middle. In practice we fill the entire context length of 1024, so would have to modify the training regiment to output &#39;&#39; in the middle of sequences so that the infilling length of text is more dynamic.</p><h3>Training from Scratch</h3><p>Now that you have seen the noising during training and the sampling process, let’s put it all together and watch this thing train on a character level model. For this script, we replace the full GPT-2 tokenizer with a simple character level tokenizer, and reduce the model size significantly. This is simply so that we can see results quicker and verify everything is working end to end.</p><pre>python scripts/run_train.py --repo YOUR_OXEN_USERNAME/SEDD_baby_names</pre><p>This script trains the model on baby names with a context length of 32 and padding of empty string at the end. The training data is from our datasets/baby_names repository on Oxen.ai.</p><p><a href="https://www.oxen.ai/datasets/baby_names?ref=ghost.oxen.ai">datasets/baby_names | Datasets at Oxen.ai</a></p><p>To run the script fully, you will need to <a href="https://www.oxen.ai/register?ref=ghost.oxen.ai">create an Oxen.ai account</a> because we will be saving intermediate results there to compare over time.</p><p>Even after minimal training on 1000 steps we are starting to get short text strings that have capital letters at the start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oDuVQVvqY8LAW7Lu.png" /></figure><p>After training for a significant amount of time, we start to get actual strings that look like baby names out 🎉.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yJF8yB3wMjMqJoYm.png" /></figure><h3>Next Steps / Conclusion</h3><p>If you have enough compute, it would be interesting to train the full model on a larger dataset than even <a href="https://www.oxen.ai/datasets/OpenWebText?ref=ghost.oxen.ai">OpenWebText</a>. It remains to be seen how well this approach scales up to models the size of GPT-3 and beyond.</p><p>Overall I think this approach is cool in theory, but after playing with it the infilling capabilities are still in early days and not practically usable as is out of the box.</p><p>Hopefully this post gave you a good understanding of how diffusion for text works, how you can train it on your own data, and I hope you try some experiments of your own!</p><p>If you like this kind of content, feel free to join our to <a href="https://www.oxen.ai/community?ref=ghost.oxen.ai">Oxen.ai paper club</a> or subscribe to our YouTube channel 🐂</p><p><a href="https://www.youtube.com/@oxen-ai?ref=ghost.oxen.ai">Oxen</a></p><p><em>Originally published at </em><a href="https://www.oxen.ai/blog/how-to-train-diffusion-for-text-from-scratch"><em>https://www.oxen.ai</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd74c1014e3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to train Mistral 7B as a “Self-Rewarding Language Model” | Oxen.ai]]></title>
            <link>https://medium.com/@oxenai/how-to-train-mistral-7b-as-a-self-rewarding-language-model-oxen-ai-a47e5b18d860?source=rss-82ea984bd9af------2</link>
            <guid isPermaLink="false">https://medium.com/p/a47e5b18d860</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[OXEN AI.  Build World-Class AI Datasets. Together.]]></dc:creator>
            <pubDate>Wed, 20 Mar 2024 18:22:38 GMT</pubDate>
            <atom:updated>2024-03-20T18:23:17.145Z</atom:updated>
            <content:encoded><![CDATA[<p>About a month ago we went over the <a href="https://arxiv.org/abs/2401.10020?ref=ghost.oxen.ai">“Self-Rewarding Language Models” paper</a> by the team at Meta AI with the <a href="https://oxen.ai/community?ref=ghost.oxen.ai">Oxen.ai Community</a>. The paper felt very approachable and reproducible, so we decided to try to replicate the results all from Open Source components. Props to @raulc from our Discord community for taking on all the training!</p><p>This deep dive goes into how to train a Self-Rewarding Language Model starting from a base <a href="https://huggingface.co/mistralai/Mistral-7B-v0.1?ref=ghost.oxen.ai">mistralai/Mistral-7B-v0.1</a>. The idea is that this model will be able to generate new data that it can add to it’s own training set, and iteratively improve itself over time. The original research paper uses Llama-70b as a starting point, so we wanted to see if the same technique would work for a smaller 7B Mistral model that we could train on a single A10 GPU.</p><h3>Practical ArXiv Dives</h3><p>These are the notes from our live Friday research club called <a href="https://www.oxen.ai/community?ref=ghost.oxen.ai">Arxiv Dives</a>, feel free to follow along with the video for context.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FM8FY4ZvAf5w%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DM8FY4ZvAf5w&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FM8FY4ZvAf5w%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e2b7ebab1c5ce34dd6c7e18088000f4/href">https://medium.com/media/1e2b7ebab1c5ce34dd6c7e18088000f4/href</a></iframe><p>If you would like to join live to ask questions or join the discussion we would love to have you! Sign up below 👇</p><p><a href="https://lu.ma/oxen?ref=ghost.oxen.ai">Oxen.ai · Events Calendar</a></p><h3>Quick Refresher</h3><p>This self-rewarding loop relies on two main ideas. <a href="https://www.oxen.ai/blog/training-language-models-to-follow-instructions-instructgpt?ref=ghost.oxen.ai">Instruction Fine Tuning</a> and <a href="https://www.oxen.ai/blog/arxiv-dives-direct-preference-optimization-dpo?ref=ghost.oxen.ai">Direct Preference Optimization</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GuVQNTZxKcZ-C2nD.png" /></figure><p>We covered the details of the paper in a <a href="https://www.oxen.ai/blog/arxiv-dives-self-rewarding-language-models?ref=ghost.oxen.ai">previous dive</a>, but the high level overview of the process is as follows:</p><ol><li>First we perform a supervised fine tuning on an LLM to make it follow instructions as well as be able to be it’s own reward model. This model is called M0.</li><li>Next we generate a set of new prompts from an existing LLM given an N-shot example prompt.</li><li>Then we generate multiple responses for each prompt from the M0 model to create a new dataset of prompts and responses.</li><li>Once we have new prompt-response pairs, we have the fine-tuned LLM judge all of it’s own responses and create preference pairs.</li><li>Then we train the LLM with DPO on those preference pairs. This is called the M1 model and can be fed back into the loop.</li><li>The new filtered training data is then put back into the training dataset and the process is repeated.</li></ol><p>Over time you can go from an M0 model to an M1, M2, M3, etc.</p><p>If you want to learn more about the original research, feel free to refer to the deep dive we already did on the paper:</p><p><a href="https://www.oxen.ai/blog/arxiv-dives-self-rewarding-language-models?ref=ghost.oxen.ai">Arxiv Dives - Self-Rewarding Language Models | Oxen.ai</a></p><h3>TLDR ~ Why is this important?</h3><p>One of the most expensive steps in training LLMs is the human labor required to write prompts and responses, as well as rank and judge them. In theory if you can get an LLM to generate it’s own training data and judge it’s own outputs, you can eliminate one of the biggest costs.</p><p>Guiding the LLM through this process is important not only for model accuracy but AI safety. The hope is that with a well crafted “LLM as a Judge Prompt”, you can steer the system to filter out bad data and keep the good. Remember, machine learning is always about good data in — good responses out, bad data in — bad responses out. While safety may be a concern for larger models, we will be training a smaller 7B param LLM, and the bigger concern here is that it does not degenerate into generating non-sense.</p><h3>Code</h3><p>All the code for this project can be found on GitHub:</p><p>There is a script at the root of the repository that kicks every thing off.</p><pre>./self-reward.sh scripts mistralai/Mistral-7B-v0.1 M0</pre><p>You can give this script a base language model, and it will run all the steps to go from a M0 to M1 model. Each step along the way we upload the data and models to Oxen.ai so that you can debug the intermediate steps.</p><p>In theory you can put this base self-reward.sh script into a loop and feed in M0 into training M1 and generate as many iterations as you would like.</p><h3>What is Oxen.ai?</h3><p>If you are not familiar with Oxen.ai, it is a great platform for this type of workflow. Oxen at it’s core is a fast data version control tool, built for large unstructured datasets. It is built for machine learning scale datasets and models that you would not traditionally check into a git repository.</p><p>This Self-Rewarding loop will create many iterations of the datasets and the models, so it is a good idea to have them versioned so that we can see if/when the model starts improving or saturating during these experiments. For example here are the generated scores from the M0 model during this experiment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uMc-KhTitj9-GeND.png" /></figure><p>If you have not made an account on Oxen.ai, <a href="https://oxen.ai/register?ref=ghost.oxen.ai">feel free to set one up</a> so that you can upload the results there. Getting started is free, so start training as many self-rewarding language models as you’d like.</p><h3>Preparing the Datasets</h3><p>The initial instruct fine tune data (IFT) and evaluation fine tune data (EFT) are generated from the OASST dataset.</p><p><a href="https://www.oxen.ai/OpenAssistant/oasst2?ref=ghost.oxen.ai">OpenAssistant/oasst2 | Datasets at Oxen.ai</a></p><p>Following the instructions from the paper, we cleaned the OASST data and took the first 3200 highest scored examples from the English language as the Instruction Fine Tuning data (IFT) then take 1775 examples from the same dataset and create the EFT data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JKnJ9SaQHLf0L5vn.png" /></figure><p>The initial IFT dataset can be found here:</p><p><a href="https://www.oxen.ai/datasets/Self-Rewarding-Language-Models/file/main/M0/train/ift.jsonl?ref=ghost.oxen.ai">datasets/Self-Rewarding-Language-Models/M0/train/ift.jsonl at main</a></p><p>And the initial EFT dataset here:</p><p><a href="https://www.oxen.ai/datasets/Self-Rewarding-Language-Models/file/main/M0/train/eft.jsonl?ref=ghost.oxen.ai">datasets/Self-Rewarding-Language-Models/M0/train/eft.jsonl at main</a></p><p>The IFT dataset is meant to give the model the ability to follow instructions. The EFT dataset is to teach the model how to be it’s own reward model (LLM as a Judge). The balance of the two should give the model the ability to generate it’s own training data, as well as be a judge of it’s own output.</p><p>These two datasets are combined to create an initial IFT+EFT dataset that simple contains prompts and completions.</p><p><a href="https://www.oxen.ai/oxbot/SRLM/file/main/M0/train/ift_eft.jsonl?ref=ghost.oxen.ai">oxbot/SRLM/M0/train/ift_eft.jsonl at main</a></p><p>Feel free to go click around and get a sense for the training data. The prompts for the LLM as a Judge (EFT) all have the same format describing the scoring system and the completion is simply the score. The IFT data is simply instructions and completions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qBrNruHdRfQ4_OLc.png" /></figure><p>The LLM as a Judge prompt in the EFT samples is going to be part of the secret sauce, and is an interesting portion to tweak in this whole pipeline to steer the LLM in the direction you want it to go.</p><pre>Review the user’s question and the corresponding response using the additive 5-point<br>scoring system described below. <br><br>The user&#39;s question is between &lt;question&gt; and &lt;/question&gt;<br>The response of the AI Assistant is between &lt;response&gt; and &lt;/response&gt;<br><br>Points are accumulated based on the satisfaction of each<br>criterion:<br>- Add 1 point if the response is relevant and provides some information related to<br>the user’s inquiry, even if it is incomplete or contains some irrelevant content.<br>- Add another point if the response addresses a substantial portion of the user’s question,<br>but does not completely resolve the query or provide a direct answer.<br>- Award a third point if the response answers the basic elements of the user’s question in a<br>useful way, regardless of whether it seems to have been written by an AI Assistant or if it<br>has elements typically found in blogs or search results.<br>- Grant a fourth point if the response is clearly written from an AI Assistant’s perspective,<br>addressing the user’s question directly and comprehensively, and is well-organized and<br>helpful, even if there is slight room for improvement in clarity, conciseness or focus.<br>- Bestow a fifth point for a response that is impeccably tailored to the user’s question<br>by an AI Assistant, without extraneous information, reflecting expert knowledge, and<br>demonstrating a high-quality, engaging, and insightful answer.<br>- If the response repeats itself or is not concise and to the point, score the response 0.<br><br>&lt;question&gt;{prompt}&lt;/question&gt;<br>&lt;response&gt;{completion}&lt;/response&gt;<br><br>After examining the user’s instruction and the response:<br>- output the score of the evaluation using this exact format: &quot;score: &lt;total points&gt;&quot;, where &lt;total points&gt; is between 0 and 5<br>- Briefly justify your total score, up to 100 words.</pre><p>If the model does not learn how to score it’s own responses correctly, we have no chance in the later stages of the pipeline.</p><h3>Training M0</h3><p>If you only want to run the code and don’t need to know the internals, the first script is called 00_sft.py and you can run it with:</p><pre>python scripts/00_sft.py -d M0/train/ift_eft.jsonl -b mistralai/Mistral-7B-v0.1 -m mistralai/Mistral-7B-v0.1 -o M0/models/sft</pre><p>You can download the seed data directly from the UI above or through the Oxen CLI. To install the Oxen.ai checkout the developer docs:</p><p><a href="https://docs.oxen.ai/getting-started/install?ref=ghost.oxen.ai">⚒️ Installation - Oxen.ai</a></p><pre>oxen download datasets/Self-Rewarding-Language-Models M0/train/ift_eft.jsonl</pre><p>Once you have the data, the script itself is not too much code either. First we load the dataset into memory:</p><pre>from datasets import load_dataset<br><br>def collate_fn(tokenizer, x):<br>    text = tokenizer.apply_chat_template([<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: x[&#39;prompt&#39;]},<br>        {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: x[&#39;completion&#39;]},<br>    ], tokenize=False)<br>    return {&quot;text&quot;: text}<br><br>base_model = &quot;mistralai/Mistral-7B-v0.1&quot;<br><br>dataset_file = &quot;ift+eft.jsonl&quot;<br>dataset = load_dataset(&quot;json&quot;, data_files={&#39;train&#39;: dataset_file})<br>dataset = dataset[&#39;train&#39;].shuffle(seed=42)<br><br># use the chat template prompt to format it into a &quot;text&quot; field<br>dataset = dataset.map(lambda x: collate_fn(tokenizer, x))<br><br>print(&quot;First example in the dataset&quot;)<br>print(dataset[&#39;text&#39;][0])</pre><p>An example will now look like this, with special tokens delimiting the instruction [INST] [/INST] and start and end of sentence &lt;s&gt; &lt;/s&gt; .</p><pre>&lt;s&gt;[INST] What is the capital of France? [/INST] <br>Paris is the capital of France &lt;/s&gt;</pre><p>Once the data is loaded, we fine-tune the model with LORA using the Parameter Efficient Fine-Tuning (PEFT) library.</p><pre>from transformers import AutoModelForCausalLM, BitsAndBytesConfig, AutoTokenizer, TrainingArguments<br>from peft import (<br>    get_peft_model,<br>    LoraConfig,<br>    TaskType,<br>    prepare_model_for_kbit_training,<br>)<br>from trl import SFTTrainer<br><br>base_model_name = &quot;mistralai/Mistral-7B-v0.1&quot;<br>output_dir = &quot;M0/models/sft&quot;<br><br>bnb_config = BitsAndBytesConfig(<br>    load_in_4bit=True,<br>    bnb_4bit_quant_type=&quot;nf4&quot;,<br>    bnb_4bit_compute_dtype=torch.float16,<br>)<br><br>device_map = &quot;auto&quot;<br><br>base_model = AutoModelForCausalLM.from_pretrained(<br>    base_model_name,<br>    quantization_config=bnb_config,<br>    device_map=device_map,<br>    trust_remote_code=True,<br>)<br>base_model.config.use_cache = False<br>base_model.config.pretraining_tp = 1<br><br>tokenizer = AutoTokenizer.from_pretrained(base_model_name, trust_remote_code=True)<br>tokenizer.pad_token = tokenizer.eos_token<br>tokenizer.padding_side = &quot;right&quot;<br><br># from https://www.datacamp.com/tutorial/mistral-7b-tutorial<br>lora_dropout=0.1<br>lora_alpha=16<br>lora_r=64<br>learning_rate=2e-4<br><br>batch_size = 4<br><br>def create_peft_config(model):<br>    peft_config = LoraConfig(<br>        task_type=TaskType.CAUSAL_LM,<br>        inference_mode=False,<br>        lora_dropout=lora_dropout,<br>        lora_alpha=lora_alpha,<br>        r=lora_r,        <br>        bias=&quot;none&quot;,<br>        target_modules = [&quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;o_proj&quot;, &quot;gate_proj&quot;]<br>    )<br><br>    model = prepare_model_for_kbit_training(model)<br>    model = get_peft_model(model, peft_config)<br>    <br>    model.print_trainable_parameters()<br><br>    return model, peft_config<br><br>model, lora_config = create_peft_config(base_model)<br><br>training_args = TrainingArguments(<br>    output_dir=output_dir,<br>    per_device_train_batch_size=batch_size,<br>    learning_rate=learning_rate,<br><br>    gradient_accumulation_steps=4,<br>    warmup_steps=30,<br>    logging_steps=1,<br>    num_train_epochs=1,<br>    save_steps=50<br>)<br><br>max_seq_length = 1024<br><br>trainer = SFTTrainer(<br>    model=base_model,<br>    train_dataset=dataset,<br>    peft_config=lora_config,<br>    # dataset_text_field=&quot;prompt_response&quot;,<br>    max_seq_length=max_seq_length,<br>    tokenizer=tokenizer,<br>    args=training_args,<br>)<br><br>trainer.train()<br><br>output_dir = os.path.join(output_dir, &quot;final_checkpoint&quot;)<br>trainer.model.save_pretrained(output_dir)</pre><p>This takes about 3–4 hours on an NVIDIA A10 GPU with 24GB of VRAM. Run nvidia-smi and watch it cook 🥘.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ju-QVPZIvh_9V4UB.png" /></figure><h3>Generating New Prompts</h3><p>Once the first model is done training, we can use it to start generating new data. The first thing we need to do is generate a new set of prompts to feed the model. This is done by sampling from the model given an 8-shot prompt of example prompts.</p><pre>Come up with a series of tasks and questions. Only the task/question,<br>no further text/explanation, no additional information.<br>The task or question should be something a person would ask a chatbot.<br><br>&lt;task&gt;So if a hacker gets access to my computer and does a fork bomb, what to do to prevent it?&lt;/task&gt;<br>&lt;task&gt;Can you give me more detailed steps for the first and second step?&lt;/task&gt;<br>&lt;task&gt;i see, generate a list of the ten most comon flaours of ice cream&lt;/task&gt;<br>&lt;task&gt;Can you add 1 to 2?&lt;/task&gt;<br>...</pre><p>The next script feeds the model 8 random example tasks and questions, it will start repeating more. These are then collected, deduped, and added as candidates to the new training set.</p><p>Run this step with the 01_gen_prompts.py script:</p><pre>python scripts/01_gen_prompts.py mistralai/Mistral-7B-v0.1 M0/models/sft/final_checkpoint M0/train/ift.jsonl M0/generated/prompts.jsonl</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yfUZdf9mSO5AL9av.gif" /></figure><p>As you can see, sometimes the script will repeat itself, but eventually after de-duplicating you will have 1000 new generated prompts.</p><p>You can view an example of the final generations here:</p><p><a href="https://www.oxen.ai/oxbot/SRLM/file/main/M0/generated/prompts.jsonl?ref=ghost.oxen.ai">oxbot/SRLM/M0/generated/prompts.jsonl at main</a></p><h3>Generating New Responses</h3><p>Now we need to generate multiple responses per prompt. This is a pretty expensive process, and takes longer than training. Each prompt takes about 10 seconds to complete, and there are ~1000 new prompts where we want 4 responses per prompt. This means it takes about 11 hrs to generate all the new candidate prompt/response pairs.</p><pre>python scripts/02_gen_responses.py M0/models/sft/final_checkpoint M0/generated/prompts.jsonl M0/generated/responses.jsonl</pre><p>This is just a simple sampling function that is run on each one of the prompt 4 times.</p><pre>def do_sample(model, tokenizer, prompt):<br>    with torch.no_grad():<br>        prompt_sample = [<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}<br>        ]<br><br>        prompt_for_model = tokenizer.apply_chat_template(prompt_sample, tokenize=False)<br><br>        model_inputs = tokenizer(prompt_for_model, return_tensors=&quot;pt&quot;).to(&quot;cuda&quot;)<br>        streamer = TextStreamer(tokenizer)<br><br>        # Self Instruction Creation<br>        #  For candidate response generation we sample N = 4 candidate responses with temperature T = 0.7, p = 0.9.<br>        generated_ids = model.generate(<br>            **model_inputs,<br>            do_sample=True,<br>            pad_token_id=tokenizer.eos_token_id,<br>            num_return_sequences=1,<br>            streamer=streamer,<br>            temperature=0.7,<br>            top_p=0.9,<br>            max_new_tokens=224<br>        )<br><br>        answer = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)<br>        answer = answer[0]<br><br>        return answer</pre><p>One thing to note is the max_new_tokens parameter, which is rather small for some answers. The reason for this limit was simply the time it took to generate.</p><p>When it’s finished running, the final set of responses can be found in the M0/generated/responses.jsonl file.</p><p><a href="https://www.oxen.ai/oxbot/SRLM/file/main/M0/generated/responses.jsonl?ref=ghost.oxen.ai">oxbot/SRLM/M0/generated/responses.jsonl at main</a></p><h3>Scoring Responses (LLM as a Judge)</h3><p>Here is the most interesting step in terms of improving the training dataset. Now that we have a set of 4 responses per prompt, we use the same LLM to judge each one of the responses and give a score.</p><pre>python scripts/03_gen_scores.py mistralai/Mistral-7B-v0.1 M0/models/sft/final_checkpoint M0/generated/responses.jsonl M0/generated/scores.jsonl</pre><p>This will take each prompt and response and give it a score from 1–5. We parse out the score from each response and put it into the M0/generated/scores.jsonl file.</p><p><a href="https://www.oxen.ai/oxbot/SRLM/file/main/M0/generated/scores.jsonl?ref=ghost.oxen.ai">oxbot/SRLM/M0/generated/scores.jsonl at main</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3h4RWeyIZ9BW4cmE.png" /></figure><p>If you aggregate up the scores that come out of this step the model does generate a lot of 4s and 5s, which is definitely something that could be improved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pbqYeG-gVQ5IbGNz.png" /></figure><p>The distributions in the initial EFT training data look a little more balanced than the scores that are generated. This makes me think that the model could be trained for longer or tune more parameters to get it to become a better judge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0P9yfRTcxSOylExD.png" /></figure><p>We also had a few suggestions from the <a href="https://discord.com/invite/s3tBEn7Ptg?ref=ghost.oxen.ai">Discord Community</a> for the iterating on the prompt as well as having the reward model rank the pairs directly, which could be interesting paths to pursue.</p><h3>Generating Preference Pairs</h3><p>After we score each of the 4 responses and write it to M0/generated/scores.jsonl , we then need to generate preference pairs for Direct Preference Optimization (DPO).</p><pre>python scripts/04_gen_preferences.py M0/generated/scores.jsonl M0/generated/preferences.jsonl</pre><p>This will go through each prompt and group all the responses by id. Then it will take the highest and lowest scores and make preference pairs for each. If the scores match it will remove them.</p><p><a href="https://www.oxen.ai/oxbot/SRLM/file/main/M0/generated/preferences.jsonl?ref=ghost.oxen.ai">oxbot/SRLM/M0/generated/preferences.jsonl at main</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*52Su_ewcytuOClUW.png" /></figure><p>This generated data is by no means perfect, and I think LLM as a Judge skill could be improved, but there are some interesting examples where the LLM does reject clearly bad examples. For future experiments we would like to tweak LLM as a Judge prompt as well as annotate more data to train the initial SFT model longer.</p><h3>Direct Preference Optimization (DPO)</h3><p>Once the above data is generated, we can run the final step of the Self-Rewarding Loop of DPO. Take the preference data that was generated from the M0 model, and feed that into a DPO optimization. This will in theory guide the model towards better responses and away from poor responses.</p><p>Run the 05_dpo.py script as follows:</p><pre>python scripts/05_dpo.py mistralai/Mistral-7B-v0.1 M0/models/sft/final_checkpoint M0/generated/preferences.jsonl M0/models/dpo/</pre><p>This step takes another few hours depending on the size of the dataset, but in the end will give you a model that can be considered M1.</p><p>Congratulations, you have performed your first self-rewarding loop! There is still some benchmarking remaining, but overall the pipeline works and is a good starting place for experimentation.</p><h3>What’s Next</h3><p>This framework gives a preliminary proof implementation that now could be put into a self-rewarding loop. What’s interesting is uploading the data and model checkpoints to Oxen.ai during the intermediary steps gives us some intuitions on what to try next.</p><p>It would be great to have an evaluation step at the end on a dataset like MT-Bench in order to see if the model is actually improving.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cqokW6GGNFsuQx79.png" /></figure><p>Overall this loop was not too hard to create given the open source tools and models that are out there today, and cost about $30 to reproduce in Google Collab. We will continue running experiments and uploading them to Oxen.ai as it is an interesting area of research to explore given the cost of labeling training data with humans.</p><h3>Join the Oxen.ai Community</h3><p>To continue the conversation, we would love you to join our Discord! There are a ton of smart engineers, researchers, and practitioners that love diving into the latest in AI.</p><p><a href="https://discord.com/invite/s3tBEn7Ptg?ref=ghost.oxen.ai">Join the oxen Discord Server!</a></p><p>Best &amp; Moo,</p><p>~ The herd at <a href="https://oxen.ai/?ref=ghost.oxen.ai">Oxen.ai</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a47e5b18d860" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ArXiv Dives — Diffusion Transformers]]></title>
            <link>https://medium.com/@oxenai/arxiv-dives-diffusion-transformers-8928b35a0b03?source=rss-82ea984bd9af------2</link>
            <guid isPermaLink="false">https://medium.com/p/8928b35a0b03</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[OXEN AI.  Build World-Class AI Datasets. Together.]]></dc:creator>
            <pubDate>Wed, 13 Mar 2024 15:42:01 GMT</pubDate>
            <atom:updated>2024-03-13T15:42:01.105Z</atom:updated>
            <content:encoded><![CDATA[<h3>ArXiv Dives — Diffusion Transformers</h3><p>Diffusion transformers achieve state-of-the-art quality generating images by replacing the commonly used U-Net backbone with a transformer that operates on latent patches. They recently gained a lot of hype with the release of the <a href="https://openai.com/research/video-generation-models-as-world-simulators?ref=ghost.oxen.ai">Sora Technical Report</a> that stated that the core model architecture for Sora is a Diffusion Transformer.</p><p>Teams: UC Berkeley, NYU</p><p>Publish Date: March 2nd, 2023</p><p><a href="https://arxiv.org/abs/2212.09748?ref=ghost.oxen.ai">https://arxiv.org/abs/2212.09748</a></p><h3>ArXiv Dives</h3><p>Every Friday at <a href="https://oxen.ai/?ref=ghost.oxen.ai">Oxen.ai</a> we host a paper club called “ <a href="https://oxen.ai/blog/arxiv-dive-manifesto/?ref=ghost.oxen.ai">ArXiv Dives</a>” to make us smarter Oxen 🐂 🧠. We believe diving into the details of research papers is the best way to build fundamental knowledge, spot patterns and keep up with the bleeding edge.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FqUhfONmBS6M%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DqUhfONmBS6M&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqUhfONmBS6M%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab94134524ed8de58876f62abdd1e3d9/href">https://medium.com/media/ab94134524ed8de58876f62abdd1e3d9/href</a></iframe><p>These are the notes from our live session, feel free to follow along with the video for context. If you would like to join live to ask questions or join the discussion we would love to have you! Sign up below 👇</p><p><a href="https://lu.ma/oxen">Oxen.ai · Events Calendar</a></p><h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7fZ5739EEninOJWD.jpeg" /></figure><p>While transformers have taken the machine learning world by storm for many tasks in natural language processing, computer vision and several other domains, for some reason image generation models had remained holdouts on the trend. Prior state of the art image generation models these days are what’s called “diffusion models”.</p><p>Popular diffusion models such as “Stable Diffusion” use a convolutional U-Net architecture as their backbone.</p><p>This work on Diffusion Transformers shows that the inductive biases that come from Convolution, ResNets, and U-Nets are not crucial to the performance of diffusion models. You can replace the components inside a diffusion model with a transformer and have nice properties such as scalability, robustness, and efficiency.</p><h3>What is a U-Net?</h3><p>A U-Net is a type of neural network architecture that can be visualized as a U. It down samples an image to a latent space, then upsamples an output back to the same size as the original image. The latent spaces are connected by skip connections that allow information to flow nicely through the model. In the case of diffusion networks the output is a predicted set of noise, but U-Nets are commonly used in tasks like semantic segmentation image augmentation where the input has to be the same size of the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uxwZv5YJ96sHeRNw.png" /></figure><p>I recommend this source for a lot of the background needed for this post: <a href="https://www.amazon.com/Generative-Deep-Learning-Teaching-Machines/dp/1492041947?ref=ghost.oxen.ai">https://www.amazon.com/Generative-Deep-Learning-Teaching-Machines/dp/1492041947</a>. It covers U-Nets, VAEs, and Diffusion models in detail with great visuals and code.</p><h3>What is a Diffusion Model?</h3><p>A “Diffusion Model” in is any type of model that reconstructs images from noise. What is interesting about them is the data augmentation used in training. They use a trick of of slowly applying Gaussian noise to the training images at different time steps, until you end up with something that looks like the image on the right of just fuzzy noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xqi7MCKFo1v_u1UP.png" /></figure><p>Then a neural network is trained to predict the noise at each time step. Each time it predicts the noise, you subtract it from the image, and slowly a realistic image emerges. Kind of like black magic that this works at all.</p><p>This paper shows that you can swap out a U-Net with a Vision Transformer (ViT) to end up with a model they call the Diffusion Transformer (DiT).</p><p>Throughout the paper they have two metrics that they are optimizing for:</p><p>1) Network complexity (the compute used in terms of GFlops)</p><p>2) Sample Quality (how good the images look, measured in FID)</p><h3>Network Complexity</h3><p>It is common to use parameter count to estimate neural network architecture complexity. This paper argues that parameter count can be a poor proxy for complexity because it does not account for image resolution.</p><p>The larger the image, the more compute you typically need.</p><p>Whether you are using VIT patches or convolutions, the larger the image, the more surface area it has to cover. Because of this, they look at complexity in terms of Gflops (Giga Floating Point Operations) instead of pure parameter count.</p><h3>Fréchet inception distance (FID)</h3><p>The charts later in the paper that assess image quality are measured in a number called FID. This is a numeric metric that computes how well the distribution of generated images match the distribution of real images. Rather than comparing pixels directly to pixels with mean squared error, FID compares the mean and standard deviation of the deepest layer in a pre-trained Inception V-3 model. Keep this in mind as reading the results in the experiments seciton.</p><h3>Variational Auto Encoder (VAE)</h3><p>The first step in the Diffusion Transformer model is a VAE. Training a full diffusion model directly in pixel space can be computationally expensive.</p><p>Auto encoders can take any data — in this case images — and learn to compress it into a smaller representation (often a single vector of numbers, but could be set of numbers) and then learn to decompress it into the original data or image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F1koYtc4hIfZux5j.png" /></figure><p>For example, you could take the “FashionMnist” dataset which is 28x28 black and white images of clothes (like the pants above) and compress it all the way down to 4 floating point numbers</p><p>[6.3,-0.9]</p><p>And have the network learn to reconstruct the image from those 2 numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b5iR23H6aovVZx5_.png" /></figure><p>What’s cool about these is you can train them on pretty much unlimited data because you do not need a human in the loop labeling each image.</p><p>There is an encoder half of an auto encoder E and a decoder have D.</p><p>In their case they use a VAE or Variational Auto Encoder, but the mental model is roughly the same. VAEs help with the problem of “mode collapse” by spreading out the latents into a more well distributed space.</p><h3>Latent Diffusion Models</h3><p>Once you have an auto-encoder trained, now you can train a diffusion model on the latent space vectors instead of the pixels of the raw images. Training the diffusion model to predict noise in the latent space is much more efficient than doing it in pixel space, because the latent space is much smaller.</p><p>E &amp; D of the auto-encoder are typically frozen in this process, but you can apply the same method of adding noise to the latent space, predicting the noise in the latent space, and using the decoder D to decode the de-noised latent vector.</p><p>For the Diffusion Transformer model they use an “off the shelf” Convolutional Variational Auto Encoder, which is the same one used in the Stable Diffusion Models.</p><p>This means that a DiT is actually a hybrid of ConvNets and Transformers when you look under the hood, not purely transformers 😄</p><h3>Diffusion Transformer Architecture</h3><p>Putting it all together!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OPUQV0oJvGHJPBsz.png" /></figure><p>The starting difference between a U-Net and a Transformer is the way the network processes the images. A U-Net does convolutions across the image, where as Transformers chop the image into patches that can be processed and attended to in parallel.</p><p>If you are not familiar with Transformers or Vision Transformers I would recommend checking out <a href="https://www.oxen.ai/blog/arxiv-dives-vision-transformers-vit?ref=ghost.oxen.ai">our past deep dive on them</a>.</p><p>The input to the DiT is a 256x256x3 image which is run through a variational auto-encoder which turns it into 32x32x4 latent space z. The latent space is then “patchified” and flattened into a sequence as input into the ViT. They try patch sizes of 2,4, and 8.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xUlBu3DAs2jWQ1b1.png" /></figure><p>Above would be a patch size of 8, which turns into 4x4 patches (since there is a width and height of 32x32) or a sequence of 16.</p><p>They use standard sine-cosine positional embeddings to encode the location of the patch into the input since it is now in a sequence and not spatially arranged.</p><p>Changing the patch size has a big affect on the total compute in terms of GFlops, but does not impact the total parameter count. They say that halving p will at least quadruple the GFlops.</p><h3>DiT Block Design</h3><p>At a high level, the self-attention in a transformer allows each patch to look at each other patch in the image and relay information to one another. Along with the image patches themselves, they add in additional conditional information at this stage such as noise time steps t, class labels c, and eventually natural language.</p><p>They do a few variations of the architecture to see what works best (reference figure 3 above).</p><h3>In Context Conditioning</h3><p>To add in the additional information, they simply append t and c as additional tokens in the input sequence and treat them the same as image tokens.</p><p>t = denoising timestep</p><p>c = class index of the image (cat, dog, bird, etc)</p><h3>Cross-attention block</h3><p>Instead of adding t and c as additional tokens in the input sequence, they treat them as a separate sequence of length 2, then add additional cross-attention to the separate sequence. This causes 15% overhead in GFlops because of the additional attention.</p><h3>Adaptive layer norm (adaLN)</h3><p>Layer normalization is the process of making sure all the values within a layer are within a certain range (usually 0–1 or with zero mean and unit variance). This helps the network learn faster and be more stable training. Adaptive layer norm learns parameters gamma and beta to perform the normalization.</p><h3>AdaLN-Zero block</h3><p>They also learn a scaling parameter alpha applied immediately prior to any residual connections that helps guide how much information from the original input is passed through to the next layer.</p><h3>Transformer Decoder</h3><p>After the final DiT block, they need to decode the sequence of image tokens into a prediction of noise / a diagonal covariance prediction. They use a standard linear and reshape layers to do the decoding.</p><h3>Model Sizes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zKmM0U-NZzubr1F-.png" /></figure><h3>Experimental Results</h3><p>They evaluate using the FID metric and report FID-50k using 250 DDPM sampling steps. The best model consistently was the adaLN-Zero DiT blocks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0WDl5r0M5gZYLQXb.png" /></figure><p>The biggest takeaway of the result section is that <strong>scaling model size and decreasing patch size both yield better results</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7bbcyJKqHR42Hbjp.png" /></figure><p>What is interesting is parameter counts do not uniquely determine quality of the DiT model — it is more about the GFlops used.</p><p>For example: When model size is held constant and patch size is decreased, the parameter counts are effectively unchanged (in fact, total parameters slightly decrease) but the GFlops increase because you have more patches to process. The models with smaller patch size out perform the models with larger patch size and they claim this is correlated to GFlops.</p><p>Small models — even when trained longer, eventually become compute-inefficient relative to larger models trained for fewer steps.</p><p>So the smaller the patch size and the larger model the better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y_20kTL4WHShlquH.png" /></figure><p>They end up training the DiT-XL/2 for 7M steps to compare it to other models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9ePC8dJoixCHNBF6.png" /></figure><p>Note: The FID score metric was original in GAN research in 2017.</p><p><a href="https://arxiv.org/abs/1706.08500?ref=ghost.oxen.ai">https://arxiv.org/abs/1706.08500</a></p><p>The way it works is you take a pre-trained Inception V-3 model and run a real image through, and a generated image through, then look at the activations from the last pooling layer and compare them. If you want full details on the implementation check out these resources.</p><p><a href="https://machinelearningmastery.com/how-to-implement-the-frechet-inception-distance-fid-from-scratch/?ref=ghost.oxen.ai">https://machinelearningmastery.com/how-to-implement-the-frechet-inception-distance-fid-from-scratch/</a> <a href="https://github.com/openai/guided-diffusion/tree/main/evaluations?ref=ghost.oxen.ai">https://github.com/openai/guided-diffusion/tree/main/evaluations</a></p><p>The problems with this are we are using an image classification model trained on ImageNet meaning its features are only really going to know about objects that are well represented in that dataset. So it is not surprising that a generative model also trained on image net performs well. FID would probably not be a good metric to test out of domain performance for a model.</p><h3>Qualitative Results</h3><p>In general, the qualitative results from the model are super impressive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xh_pXZuxm2O9q35D.png" /></figure><p>But there are some fun errors if you look closely. Such as…arctic wolf eating rock?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jMY3walEO5mo8Gio.png" /></figure><p>Or demonic faces in the background of images?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5PmeWHyYvsO11T-q.png" /></figure><p>There are many more example in the appendix of the paper if you are interested.</p><h3>Conclusion</h3><p>The diffusion transformer paper shows that the inductive biases of traditional U-Nets are not crucial to the performance. If you scale up compute by increasing model size and decreasing patch size, Diffusion Transformers become state of the art image generation models.</p><p>In the Sora technical report they mention that the model is a “Diffusion Transformer”. They do not go into the exact technical details but you can imagine they added the time dimension to the patches and had the diffusion process not only sample latent spatial latent spaces in width and height, but also in the time dimension.</p><p>The closest paper I saw in the references to what they described in the technical report is a model called WALT from Google.</p><p>We will cover WALT in a future dive.</p><p><a href="https://arxiv.org/abs/2312.06662?ref=ghost.oxen.ai">https://arxiv.org/abs/2312.06662</a></p><p>If anyone is up for the challenge — It would be fun to try to implement one of these models and make some of the results reproducible on a smaller scale. The authors of the paper speculate that the Sora model may not be that large (even though it is probably trained on a massive dataset).</p><p>Here’s my take on the Sora technical report, with a good dose of speculation that could be totally off. First of all, really appreciate the team for sharing helpful insights and design decisions — Sora is incredible and is set to transform the video generation community.</p><p>What we… <a href="https://t.co/XbxFmgPKxT?ref=ghost.oxen.ai">pic.twitter.com/XbxFmgPKxT</a></p><p>- Saining Xie (@sainingxie) <a href="https://twitter.com/sainingxie/status/1758433676105310543?ref_src=twsrc%5Etfw&amp;ref=ghost.oxen.ai">February 16, 2024</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pD3TWY2nnCT_2yYU.jpeg" /></figure><p>People in the comments speculating that it could be 3B or 6B parameter model, in which case….we could probably train one ourselves given the right data. Let me know if you want to take a stab — Oxen.ai is collecting and gathering a large video dataset we will open source soon.</p><p>Feel free to email hello@oxen.ai if you are interested in collaborating.</p><h3>Next Up</h3><p>To continue the conversation, we would love you to join our Discord! There are a ton of smart engineers, researchers, and practitioners that love diving into the latest in AI.</p><p><a href="https://discord.com/invite/s3tBEn7Ptg?ref=ghost.oxen.ai">Join the oxen Discord Server!</a></p><p>If you enjoyed this dive, please join us next week live! We always save time for questions at the end, and always enjoy the live discussion where we can clarify and dive deeper as needed.</p><p><a href="https://lu.ma/oxenbookclub?ref=ghost.oxen.ai">Arxiv Dives with Oxen.AI - Self-Rewarding Language MOdels · Zoom · Luma</a></p><p>All the past dives can be found on the blog.</p><p><a href="https://oxen.ai/blog">Oxen.ai Blog | Oxen.ai</a></p><p>The live sessions are posted on YouTube if you want to watch at your own leisure.</p><p><a href="https://www.youtube.com/channel/UCIYC0IZ4fKmXaeGl95WIf5Q?ref=ghost.oxen.ai">Oxen</a></p><p>Best &amp; Moo,</p><p>~ The herd at <a href="https://oxen.ai/?ref=ghost.oxen.ai">Oxen.ai</a></p><h3>Who is Oxen.ai?</h3><p><a href="https://oxen.ai/?ref=ghost.oxen.ai">Oxen.ai</a> is an <a href="https://github.com/Oxen-AI/oxen-release?ref=ghost.oxen.ai">open source project</a> aimed at solving some of the challenges with iterating on and curating machine learning datasets. At its core Oxen is a lightning fast data version control tool optimized for large unstructured datasets. We are currently working on collaboration workflows to enable the high quality, curated public and private <a href="https://www.oxen.ai/explore?ref=ghost.oxen.ai">data repositories</a> to advance the field of AI, while keeping all the data accessible and auditable.</p><p>If you would like to learn more, <a href="https://github.com/Oxen-AI/oxen-release?ref=ghost.oxen.ai">star us on GitHub</a> or head to <a href="https://www.oxen.ai/?ref=ghost.oxen.ai">Oxen.ai</a> and create an account.</p><p><em>Originally published at </em><a href="https://www.oxen.ai/blog/arxiv-dives-diffusion-transformers"><em>https://www.oxen.ai</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8928b35a0b03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arxiv Dives — Toolformer: Language models can teach themselves to use tools]]></title>
            <link>https://medium.com/@oxenai/arxiv-dives-toolformer-language-models-can-teach-themselves-to-use-tools-b50c9312c2a9?source=rss-82ea984bd9af------2</link>
            <guid isPermaLink="false">https://medium.com/p/b50c9312c2a9</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[OXEN AI.  Build World-Class AI Datasets. Together.]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 18:46:47 GMT</pubDate>
            <atom:updated>2024-02-13T18:46:47.992Z</atom:updated>
            <content:encoded><![CDATA[<h3>Arxiv Dives — Toolformer: Language models can teach themselves to use tools</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*yAmWAEC-WeNq9JzURAtpgQ.png" /></figure><p>Large Language Models (LLMs) show remarkable capabilities to solve new tasks from a few textual instructions, but they also paradoxically struggle with basic functionality such as math, dates on a calendar, or replying with up to date information about the world.</p><p>As software engineers we have already solved these subset of problems with other tools such as a calculator, calendar or search and retrieval systems.</p><p>This paper introduces a model they call the <em>Toolformer</em> which has been trained to use external tools. The Toolformer decides which APIs to call, when to call them, and what arguments to pass in order to better answer user’s queries.</p><p>Paper: <a href="https://arxiv.org/abs/2302.04761?ref=ghost.oxen.ai">https://arxiv.org/abs/2302.04761</a></p><p>Team: Meta AI Research, Universitat Pompeu Fabra (Barcelona, Spain)</p><p>Date: Feb 9th, 2023</p><h3>ArXiv Dives</h3><p>Every Friday at <a href="https://oxen.ai/?ref=ghost.oxen.ai">Oxen.ai</a> we host a paper club called “ <a href="https://ghost.oxen.ai/arxiv-dive-manifesto/">ArXiv Dives</a>” to make us smarter Oxen 🐂 🧠. We believe diving into the details of research papers is the best way to build fundamental knowledge, spot patterns and keep up with the bleeding edge.</p><p>If you would like to join live to ask questions or join the discussion we would love to have you! Sign up below 👇</p><p><a href="https://lu.ma/oxenbookclub?ref=ghost.oxen.ai">Arxiv Dives with Oxen.AI - Self-Rewarding Language MOdels · Zoom · Luma</a></p><p>The following are the notes from the live session. Many thanks to the community asking great questions along the way. Feel free to watch the video and follow along for the full context.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FqvaxKDjAz4M%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DqvaxKDjAz4M&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqvaxKDjAz4M%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6307dee70e6ee26a3aa3af4f74f3f00/href">https://medium.com/media/f6307dee70e6ee26a3aa3af4f74f3f00/href</a></iframe><h3>Toolformer</h3><p>The Toolformer architecture lets the use of tools be learned in a self-supervised way without requiring large amounts of human annotations. Once the language model learns to use tools, it should be able to decide <em>when</em> and <em>how</em> to use which tool, while maintaining it’s general knowledge about language.</p><p>The 5 tools they enable in this paper are:</p><ol><li>Question answering system</li><li>Wikipedia search engine</li><li>Calculator</li><li>Calendar</li><li>Machine translation system</li></ol><h3>Approach</h3><p>Each tool that is available to the Language Model is represented by an API call. Since the language model is simply predicting sequences of text, they represent each API call as a text sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/0*A34fKaQ_dPowl4u-.png" /></figure><h3>Creating the Training Data</h3><p>They create synthetic data bootstrapped with plain text sequences and augment them with API calls.</p><h3>Three Steps</h3><ol><li>Use N-shot prompting to generate some synthetic data with candidate API calls</li><li>Execute these API calls and augment an existing language modeling dataset</li><li>Filter the generated data by checking whether the obtained responses are helpful for predicting future tokens (they have a fancy filtering metric for this step)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WUQmfYfM9avD9uVU.png" /></figure><h3>Injecting API Calls</h3><p>The first step in generating the dataset is taking a random passages from your corpus like:</p><p>“Pittsburgh is known as the Steel City”</p><p>and injecting API calls in the middle of the sentences. The API calls should help you get information required to complete the text. You can call the API by writing [QA(“what is xyz…”)] where “QA” is the API you want to call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*e6kkhL_XXFGCsdjC.png" /></figure><p>They inject this data with an existing base LLM and N-shot prompting. An example prompt looks like:</p><p>They have a specific prompt for each tool they want to generate data for. All the prompts can be found in the appendix. In order to get the passages to augment, they start with a corpus called CCNet. You could use and corpus of text for this step such as Wikipedia, The Pile, Red Pajama, etc.</p><p>Since each passage may require certain tools, they use some heuristics to make sure each tool gets relevant text. For example, they only consider texts for the calculator tool if it contains 3 or more numbers in a window of 100 tokens and also contains an = sign, “equals” “equal to” “total of” “average of” followed by a number.</p><h3>Executing API Calls</h3><ol><li>the original passage, without api calls</li><li>the passage, with the api call (but without a response filled in) — tool1(x,y)</li><li>the passage with api call and the response filled in — tool1(x, y) → {response}</li></ol><p>Once they have augmented passages that meet the criterion for each tool, they create 3 variations of the passages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*flPP7AZc1nxBsY28.png" /></figure><p>Examples of the third variation of fully flushed out passages with apis, parameters, and responses are in Table 10</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*3hB93cSVsbi8AWt-.png" /></figure><p>Note: although they use the strings &lt;API&gt; and &lt;/API&gt; in these examples they actually just use [ and ] in practice.</p><h3>Filtering API Calls</h3><p>Each synthetic generated API call is not guaranteed to be helpful, since we are just starting with a corpus of data with some heuristics. <em>The main novelty of this paper is defining this “fitness score” to filter which API calls we add to the dataset.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/0*cFSLd9y-uJ-4IpV5.png" /></figure><p>Don’t let the math intimidate you, the score is relatively straight forward once you get past the greek letters.</p><p>Let’s take an example passage:</p><pre>During ArXiv Dives on Friday, <br>February 9th, 2024 we will be going over the Toolformer paper.</pre><p>We want the model to inject tool usage after Friday, in order to look up what the current date is.</p><pre>During ArXiv Dives on Friday, [Calendar() → 02/09/2024] <br>February 9th, 2024 we will be going over the Toolformer paper.</pre><p>Under the hood a language model is predicting each token and gives a probability distribution associated with what token should come next. Taking the highest probability token would look something like this:</p><pre>During (0.6) Ar (0.9) _Xiv (0.7) Dives (0.8) ...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H37zFBZ58Nn1fshI.png" /></figure><p>Going back up to our equation, we are simply summing over the log probabilities of tokens given the previous token and some weighting.</p><p>They split the sentence into before you add the API call and after</p><pre>X1:j-1 = During ArXiv Dives on Friday <br>Xj = February 9th, 2024 we will be going over the Toolformer paper.</pre><ol><li>Empty L_i(e)</li><li>The API call with no response L_i(e(c_i, E))</li><li>The API call with the response L_i(e(c_i, r_i))</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qE3EHRvKD3VdGG3E.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*ReING0iD4jGrFJ4T.png" /></figure><p>Then have a z which could either be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/0*41t7l5pCC8hq9aDH.png" /></figure><p>Then <strong>they filter any generated passage with an API call that does not add relevant information for predicting the surrounding words</strong>. If adding an empty string or the API call without a response allows you to predict the next words with higher probability than making the API call itself, do not add the API call.</p><p>If you are wondering about the weighting mechanism</p><p><a href="https://github.com/lucidrains/toolformer-pytorch/blob/main/toolformer_pytorch/toolformer_pytorch.py?ref=ghost.oxen.ai#L440">https://github.com/lucidrains/toolformer-pytorch/blob/main/toolformer_pytorch/toolformer_pytorch.py#L440</a></p><p>They make it so the score is only affected by the 5 next tokens with 1-0.2*t which is a hyper parameter you could choose.</p><p>If you want to look at the implementation of the math in practice, check out this github repo, I linked directly to the filtering function:</p><h3>Model Fine Tuning</h3><p>After they have augmented the data and filtered it down to API calls that actually help complete the passages, they simply fine-tune the model on this dataset with the standard language modeling objective of predicting the next token in a sequence.</p><p>The base model they start with is GPT-J which is a 6B parameter model trained on The Pile dataset and can be found on Hugging Face.</p><p><a href="https://huggingface.co/EleutherAI/gpt-j-6b?ref=ghost.oxen.ai">EleutherAI/gpt-j-6b · Hugging Face</a></p><p>You could train any open source model you wanted here, and I’m sure by the time you read this post there will be many high quality base models to choose from.</p><h3>Inference</h3><p>Once you have this fine-tuned language model that can predict when it needs to make an API call, they perform standard decoding until the model produces the → token, indicating that we need to go make the API call. At this point they stop to decoding process, make the API call, insert the result into the context window, and continue decoding.</p><h3>Experiments</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/0*DTW0lFimtnBsYlsT.png" /></figure><p>In their experiments, they want to see if the model can decide for itself when and how to call any of its available tools, as well as maintain it’s core language modeling abilities. The biggest boost in performance was on Math benchmarks, which makes sense given the nature of the problems. Question answering, translation, and other language modeling tasks do seem to get better as model scale increases.</p><p>Starting with Question Answering + slot filling type tasks, the see how well different models perform with zero shot prompting. The smaller fine-tuned Toolformer significantly beats the baseline and starts to become competitive with much larger base language models such as GPT-3.</p><h3>Math</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/0*uSM4x53bRrM5cb6_.png" /></figure><p>Math is the biggest jump in performance compared to other tasks, which makes sense. To get a sense for the Math word problems we uploaded the ASDiv dataset here:</p><p>You can see the Toolformer blows models with much larger parameter counts out of the water on the math benchmarks.</p><h3>Scaling Laws</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*btSQgFom40oEwyUJ.png" /></figure><p>They also perform a fine tuning on the suite of GPT-2 models with 124M, 355M, 775M, and 1.6B parameters respectively.</p><p>They state that the ability to leverage the provided tools only emerges around the 775M parameter count. The smaller models achieve similar performance with and without tools. But the smaller 6B model with tool use can way outperform GPT-3 which has 175B params.</p><h3>Conclusion</h3><p>The Toolformer is a natural extension of a base transformer language model to add the ability to use external APIs and tools. All you need to do is fine tune the model with training data that contains sequences that represent which API you want to call, as well as the parameters to the API. The biggest contribution of this paper was the training data generation and data filtering techniques. Beyond that, it is a standard fine-tuning of a base language model.</p><p>Models such as OpenAI’s GPT-4 have been likely trained in a similar fashion to enable features such as function calling to integrate into your existing tools.</p><h3>Next Up</h3><p>To continue the conversation, we would love you to join our Discord! There are a ton of smart engineers, researchers, and practitioners that love diving into the latest in AI.</p><p><a href="https://discord.com/invite/s3tBEn7Ptg?ref=ghost.oxen.ai">Join the oxen Discord Server!</a></p><p>If you enjoyed this dive, please join us next week live! We always save time for questions at the end, and always enjoy the live discussion where we can clarify and dive deeper as needed.</p><p><a href="https://lu.ma/oxenbookclub?ref=ghost.oxen.ai">Arxiv Dives with Oxen.AI - Self-Rewarding Language MOdels · Zoom · Luma</a></p><p>All the past dives can be found on the blog.</p><p><a href="https://oxen.ai/blog">Oxen.ai Blog | Oxen.ai</a></p><p>The live sessions are posted on YouTube if you want to watch at your own leisure.</p><p><a href="https://www.youtube.com/channel/UCIYC0IZ4fKmXaeGl95WIf5Q?ref=ghost.oxen.ai">Oxen</a></p><p>Best &amp; Moo,</p><p>~ The herd at <a href="https://oxen.ai/?ref=ghost.oxen.ai">Oxen.ai</a></p><h3>Who is Oxen.ai?</h3><p><a href="https://oxen.ai/?ref=ghost.oxen.ai">Oxen.ai</a> is an <a href="https://github.com/Oxen-AI/oxen-release?ref=ghost.oxen.ai">open source project</a> aimed at solving some of the challenges with iterating on and curating machine learning datasets. At its core Oxen is a lightning fast data version control tool optimized for large unstructured datasets. We are currently working on collaboration workflows to enable the high quality, curated public and private <a href="https://www.oxen.ai/explore?ref=ghost.oxen.ai">data repositories</a> to advance the field of AI, while keeping all the data accessible and auditable.</p><p>If you would like to learn more, <a href="https://github.com/Oxen-AI/oxen-release?ref=ghost.oxen.ai">star us on GitHub</a> or head to <a href="https://www.oxen.ai/?ref=ghost.oxen.ai">Oxen.ai</a> and create an account.</p><p><em>Originally published at </em><a href="https://www.oxen.ai/blog/toolformer-language-models-can-teach-themselves-to-use-tools"><em>https://www.oxen.ai</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b50c9312c2a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-Rewarding Language Models — ArXiv Dives with Oxen.ai]]></title>
            <link>https://medium.com/@oxenai/self-rewarding-language-models-arxiv-dives-with-oxen-ai-ec297b1b4ab0?source=rss-82ea984bd9af------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec297b1b4ab0</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[OXEN AI.  Build World-Class AI Datasets. Together.]]></dc:creator>
            <pubDate>Tue, 06 Feb 2024 06:33:02 GMT</pubDate>
            <atom:updated>2024-02-06T06:33:02.436Z</atom:updated>
            <content:encoded><![CDATA[<h3>Self-Rewarding Language Models — ArXiv Dives with Oxen.ai</h3><p>The goal of this paper is to see if we can create a self-improving feedback loop to achieve “superhuman agents”. Current language models are bottlenecked by labeled data from humans. Not only is the quantity of labels a bottleneck, but also the quality. If we are able to get the language model to generate it’s own training data as well as learn how to reward itself in an iterative fashion, we may be able to escape the bottleneck of labeled data from humans.</p><p>Paper: <a href="https://arxiv.org/abs/2401.10020?ref=blog.oxen.ai">https://arxiv.org/abs/2401.10020</a></p><p>Team: NYU &amp; Meta</p><p>Publish Date: Jan 18th, 2024</p><h3>ArXiv Dives</h3><p>Every Friday at <a href="https://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a> we host a paper club called “ <a href="https://blog.oxen.ai/arxiv-dive-manifesto/">ArXiv Dives</a>” to make us smarter Oxen 🐂 🧠. We believe diving into the details of research papers is the best way to build fundamental knowledge, spot patterns and keep up with the bleeding edge.</p><p>If you would like to join live to ask questions or join the discussion we would love to have you! Sign up below 👇</p><p><a href="https://lu.ma/oxenbookclub?ref=blog.oxen.ai">Arxiv Dives with Oxen.ai 📚🤿🐂 · Zoom · Luma</a></p><p>The following are the notes from the live session. Many thanks to the community asking great questions along the way. Feel free to watch the video and follow along for the full context.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FjQEo5A-Pdls%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DjQEo5A-Pdls&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FjQEo5A-Pdls%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/531762e5212cb06432493c5a73887919/href">https://medium.com/media/531762e5212cb06432493c5a73887919/href</a></iframe><h3>Self-Rewarding Language Models</h3><p><a href="https://www.oxen.ai/blog/arxiv-dives-direct-preference-optimization-dpo?ref=blog.oxen.ai">Last week we went over DPO</a> as a more stable and efficient way to optimize a model than RLHF. The problem is DPO requires that you have a substantial amount of labeled human preference data in order to train a model.</p><p>This paper introduces agents that can both:</p><ol><li>Act as an instruction following model, generating a response given a prompt</li><li>Generate and evaluate new instruction following examples to add to their own training set.</li></ol><h3>Synthetic Data</h3><p>It’s common to be skeptical about the act of a model adding data to it’s own training set. This is because using data generated from a pre-trained model in theory will not give any new information that the model does not already have encoded in its parameters, so how can it learn new information?</p><p>Although theoretically a self-improving language model seems like it wouldn’t work, we are starting to see synthetic data be a successful technique in papers like this. I have been thinking why this is the case?</p><p>The best argument I have heard it is that with these large pre-trained models it is no longer about adding data from a new distribution, since in theory they have seen “all the distributions on the internet”. It is more about “spiking” the distribution in different directions that you want to control, and guiding them on how to behave. It is one thing to have a model that can say in theory say <em>anything</em> it is another thing for a model to say what you <em>want</em> it to say.</p><p>Being able to have the model generate it’s own synthetic data feels more like alignment or honing in skills than learning something new. The paper below stops after 3 iterations so it is hard to tell how far this particular technique can take us, but what it does show is that a language model can improve it’s own skills by adding data to it’s own training set.</p><p>Can a language model create brand new text that adds to the vast corpora of knowledge? Or will it just saturate with ideas we already know, simply filtered and reformulated? It’s an interesting thought experiment that is good to keep in the back of your mind as we dive in.</p><h3>Self-Rewarding Language Models</h3><p>If you’ve been following along with previous <a href="https://www.oxen.ai/community/arxiv-dives?ref=blog.oxen.ai">ArXiv Dives</a>, the entire pipeline should be pretty intuitive to wrap your head around.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_Yw1ooi12vmJNaZt.png" /></figure><p>First we start with a set of prompts. Then we seed a supervised fine tuned (SFT) model to have two skills i) generate responses ii) evaluate responses. Then we use the SFT model to generate data both in the form of prompts and responses as well as ranked preference pairs. There are multiple potential completions for each prompt, so we need to generate multiple responses and then use the same model to rank which response is better.</p><p>They use a clever “LLM-as-a-Judge” prompt to help generate and filter the data that is added back into the training dataset, in turn improving the model in a positive feedback loop.</p><h3>Skill 1) Instruction Following</h3><p>Hopefully from the past dives ( <a href="https://www.oxen.ai/blog/training-language-models-to-follow-instructions-instructgpt?ref=blog.oxen.ai">InstructGPT</a>, <a href="https://www.oxen.ai/blog/arxiv-dives-direct-preference-optimization-dpo?ref=blog.oxen.ai">DPO</a>) you are familiar with supervised fine tuning to get your model to follow instructions, and align with preference pairs.</p><p>An example of a prompt for instruction following could look like:</p><pre>[inst] <br>Make sure to output all data in json in the format: <br>{ &quot;answer&quot;: &quot;YOUR_ANSWER&quot; } <br><br>[prompt] <br>what does the team at Oxen.ai do? <br><br>[response]<br>{ &quot;answer&quot;: &quot;build open source tools to help manage machine learning datasets&quot; }</pre><p>It is nice to separate out an instruction or system message from the user prompt so that you can tailor the user experience or developer output. For example you could also have an instruction that said “always respond like a pirate”, and now every response has a little humor if that is what you are going for.</p><p>In the case of Self-Rewarding Language models, we will want our model to follow instructions to generate new data to feed back into the model.</p><h3>Skill 2) LLM-as-a-Judge</h3><p>The second step after getting a model to follow instructions, is to align the model to human preferences. Since there are multiple valid responses for each prompt, learning which responses we prefer takes a language model from a basic instruction following machine to a more robust and aligned model. Techniques like DPO or RLHF have been shown to improve the language model further than simply instruction fine tuning.</p><p>In this case the second preference optimization step uses the same LLM as a judge of it’s own outputs. For example you may have the start of a sentence with two valid completions, where one is more correct than the other.</p><pre>Oxen.ai is ... <br>👍 fast and easy to use <br>👎 a tool for helping farmers with their crops</pre><p>We would prefer the model generate the first completion rather than the second, so we rank it higher. You can have humans label these pairs that are generated from the model, but this is time consuming and expensive. If the language model can judge it’s own outputs and give a quality score, then we could feed the data back in a self-improving loop.</p><h3>Prompting as the Judge</h3><p>They use a well-crafted clever prompt in order to have the LLM judge it’s own outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*juobh5g28WKpDnn5.png" /></figure><p>The prompt is important to get working well for this entire pipeline to work. Later in the results section they cite other prompts that have been tried that only have a 26% pairwise accuracy when compared to humans, where-as this particular prompt has 65.1% as a starting point.</p><p>This is not the first time this approach for using LLM as a judge has been proposed. The paper “<a href="https://arxiv.org/abs/2306.05685?ref=blog.oxen.ai"><strong>Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena</strong></a><strong>”</strong> looks at how well LLMs can judge outputs of other LLMs their results are that:</p><p><em>Strong LLM judges like GPT-4 can match both controlled and crowdsourced human preferences well, achieving over 80% agreement, the same level of agreement between humans.</em></p><p>The interesting thing about this paper is that the initial LLM learns to be it’s own judge. They are not using a separate, smarter language model like GPT-4 as the judge. So not only does the base model get better at instruction following, but it gets better at judging it’s own outputs. This means as we iterate through training, we will each time we train a new model we will have a higher quality preference dataset than the previous iteration.</p><p>A few key things to note here:</p><ol><li>The initial model already needs to be able to generate reasonable responses for this to work</li><li>The reward prompt must do a decent job scoring the outputs to kick off the feedback loop</li></ol><p>If you don’t meet these two conditions, you would be generating garbage, ranking garbage, and feeding garbage back into the model.</p><h3>Initialization</h3><p>First they are given a seed set of instructions that they supervise fine tune Llama-70B. The data they perform SFT with is a subset of the OASST dataset with 3200 examples from the English language that are high-quality, based on their human annotated rank. This is what they call the initial Instruction Fine Tuning (IFT) dataset</p><p>We helped clean up the OASST dataset following the same method and uploaded the subset here:</p><p><a href="https://www.oxen.ai/Laurence/oasst2-self-rewarding/file/main/oasst2_instruction_fine_tuning.jsonl?ref=blog.oxen.ai">Laurence/oasst2-self-rewarding/oasst2_instruction_fine_tuning.jsonl at main</a></p><p>Then they create a second dataset called the Evaluation Fine Tuned (EFT) dataset. This dataset is prompts that do not overlap with the IFT dataset, but in the format of the LLM-as-a-judge prompt. The initial EFT dataset is 1775 training examples and 531 evaluation examples.</p><p>Example EFT data can be found here:</p><p><a href="https://www.oxen.ai/Laurence/oasst2-self-rewarding/file/main/oasst2_evaluation_fine_tuning.jsonl?ref=blog.oxen.ai">Laurence/oasst2-self-rewarding/oasst2_evaluation_fine_tuning.jsonl at main</a></p><p>They mix these datasets together to train the initial supervised fine tuned model.</p><h3>Self-Instruction Creation</h3><p>The model itself can then modify it’s own training set by:</p><ol><li>Generate a new prompt, given few show prompting</li><li>Generate N candidate responses, given each prompt</li><li>Evaluate each candidate response, using the LLM-as-a-judge skill of the same instruct tuned model to evaluate it’s own responses</li></ol><h3>AI Feedback Training Data Creation (AIFT)</h3><p>The data generated from the steps above is then added to the IFT+EFT data to create an AIFT dataset. When adding the new data to the AIFT training set, they consider two methods.</p><p>1) High and low pairs</p><p>Given a prompt x and responses y_i then they take the highest ranked winner and lowest ranked loser and add it to the <em>preference pair</em> dataset for DPO.</p><p>2) Positive examples only</p><p>Given a prompt x they only take responses with a perfect score from the evaluator of 5 and add this to the instruction following dataset.</p><p>They find that learning from the preference pairs (#1) and not just the positive examples gives superior performance in the end.</p><h3>Iterative Training</h3><p>The overall process trains a series of models M0..M1</p><p>M0: Start with a pre-trained Llama-70B with no fine tuning.</p><p>M1: Initialize with M0, then fine tune with the IFT+EFT seed data</p><p>M2: Initialize with M1, then trained with AIFT(M1) data using DPO</p><p>M3: Initialize with M2, then trained with AIFT(M2) data using DPO</p><p>They say that this procedure resembles other work such as the Pairwise Cringe Optimization and Iterative DPO papers, however the key difference is <em>the reward model is also improving each iteration</em>, since we use the same model to generate responses and rank responses in the pipeline.</p><p>When they train AIFT(M1) they add 3,964 preference pairs to the training set for DPO. When they trained AIFT(M2) they add 6,942 pairs to the training set to create M3.</p><h3>Evaluation</h3><p>They evaluate the model on two axes</p><ol><li>Ability to follow instructions</li><li>Ability to evaluate responses (reward model)</li></ol><h3>Instruction Following</h3><p>They use GPT-4 to evaluate performance of various models, using the AlpacaEval framework.</p><p>The idea here is that GPT-4 can check if the response follows the instruction accurately, and judge which response is better.</p><h3>Reward Modeling</h3><p>They evaluate the correlation with human rankings on the evaluation set from the Open Assistant dataset.</p><p>Each instruction has on average of 2.85 responses with given rankings. They compute a <em>pairwise accuracy</em> showing the model two responses and seeing if the ranking agrees from the model to the human label.</p><h3>Instruction Following Results</h3><p>They show that the first iteration M1 with the EFT+IFT data does not outperform the IFT data by much (30.5 vs 30.9). They say this is good because this means that adding a self-reward skill does not impact the instruction following skill.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mRV5E8PluHZJYpu6.png" /></figure><p>Then they show that the second iteration M2 provides superior instruction following to iteration 1. This is promising that adding this new AIFT(M1) preference data is adding to performance. Iteration 3 also improves over iteration 2 when evaluated against itself by GPT-4.</p><p>Not only does it win against it’s baselines, but each iteration starts to get a higher win rate over GPT-4 Turbo as evaluated by GPT-4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KjmbnE3L-Y8tvlbL.png" /></figure><p>This is exciting because some of the models on the leaderboard here (Claude 2, Gemini Pro, GPT4 0314) typically contain a large dataset, sometimes over 1 million annotations, or use targets distilled from stronger models to generate the dataset. The self improving technique starts with a much smaller dataset, and does not use any external models to generate or rank the responses.</p><h3>Reward Modeling Results</h3><p>They also show quantitatively that the reward model gets more accurate over time. They compare the model’s rankings to human rankings from the original human labeled dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nqDna-rcbzdF8kAR.png" /></figure><p>As mentioned before, the quality of the LLM-as-a-Judge prompt has a large impact on how well this iteration loop works. The below prompt gave a 26.6% pairwise accuracy, whereas the prompt they used in this paper gave 65.1%. Scroll up and see if you can find the differences, it is hard to tell just by quickly scanning, but shows the value of prompt engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hs_W7aVT3RPUmXpj.png" /></figure><p>Overall this paper is interesting because of the size of the dataset needed. They start with only a couple thousand examples and can outperform models that were trained on millions using this iterative process. The fact that they see improving performance over time without any human in the loop is also encouraging. This virtual cycle is promising in this small setting, but is only a preliminary study.</p><p>A few things that would be interesting to see:</p><ul><li>When does this approach stop improving? Why did they stop at 3 steps?</li><li>Would this method work with smaller (7B) models?</li><li>What other prompts could we use in the LLM-as-a-judge step to direct the model in different directions? This has implications for safety as well as performance.</li></ul><p>We have some community members in our <a href="https://discord.com/invite/s3tBEn7Ptg?ref=blog.oxen.ai">Oxen.ai Discord</a> working on a an implementation of this to see how well it works in practice with other models. Feel free to join us!</p><p><a href="https://discord.com/invite/s3tBEn7Ptg?ref=blog.oxen.ai">Join the oxen Discord Server!</a></p><h3>Next Up</h3><p>If you enjoyed this dive, please join us next week live! We always save time for questions at the end, and always enjoy the live discussion where we can clarify and dive deeper as needed.</p><p><a href="https://lu.ma/oxenbookclub?ref=blog.oxen.ai">Arxiv Dives with Oxen.ai 📚🤿🐂 · Zoom · Luma</a></p><p>All the past dives can be found on the blog.</p><p><a href="https://oxen.ai/blog">Oxen.ai Blog | Oxen.ai</a></p><p>The live sessions are posted on YouTube if you want to watch at your own leisure.</p><p><a href="https://www.youtube.com/channel/UCIYC0IZ4fKmXaeGl95WIf5Q?ref=blog.oxen.ai">Oxen</a></p><p>Best &amp; Moo,</p><p>~ The herd at <a href="https://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a></p><h3>Who is Oxen.ai?</h3><p><a href="https://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a> is an <a href="https://github.com/Oxen-AI/oxen-release?ref=blog.oxen.ai">open source project</a> aimed at solving some of the challenges with iterating on and curating machine learning datasets. At its core Oxen is a lightning fast data version control tool optimized for large unstructured datasets. We are currently working on collaboration workflows to enable the high quality, curated public and private <a href="https://www.oxen.ai/explore?ref=blog.oxen.ai">data repositories</a> to advance the field of AI, while keeping all the data accessible and auditable.</p><p>If you would like to learn more, <a href="https://github.com/Oxen-AI/oxen-release?ref=blog.oxen.ai">star us on GitHub</a> or head to <a href="https://www.oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a> and create an account.</p><p><a href="https://github.com/Oxen-AI/oxen-release?ref=blog.oxen.ai">GitHub - Oxen-AI/oxen-release: Lightning fast data version control system for structured and unstructured machine learning datasets. We aim to make versioning datasets as easy as versioning code.</a></p><p><em>Originally published at </em><a href="https://www.oxen.ai/blog/arxiv-dives-self-rewarding-language-models"><em>https://www.oxen.ai</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec297b1b4ab0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arxiv Dives — Direct Preference Optimization (DPO)]]></title>
            <link>https://medium.com/@oxenai/arxiv-dives-direct-preference-optimization-dpo-c3de57d417b7?source=rss-82ea984bd9af------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3de57d417b7</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[OXEN AI.  Build World-Class AI Datasets. Together.]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 01:01:51 GMT</pubDate>
            <atom:updated>2024-01-31T17:44:57.797Z</atom:updated>
            <content:encoded><![CDATA[<h3>Arxiv Dives — Direct Preference Optimization (DPO)</h3><p>This paper provides a simple and stable alternative to RLHF for aligning Large Language Models with human preferences called “Direct Preference Optimization” (DPO). They reformulate the loss function as a classification task between prompt completions and show that they can get competitive performance without adding the complexity of the reward model and reinforcement learning.</p><p>Paper: <a href="https://arxiv.org/abs/2305.18290?ref=blog.oxen.ai">https://arxiv.org/abs/2305.18290</a></p><p>Team: Stanford</p><p>Publish Date: May 29th, 2023</p><h3>ArXiv Dives</h3><p>Every Friday at <a href="https://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a> we host a paper club called “ <a href="https://blog.oxen.ai/arxiv-dive-manifesto/">ArXiv Dives</a>” to make us smarter Oxen 🐂 🧠. We believe diving into the details of research papers is the best way to build fundamental knowledge, spot patterns and keep up with the bleeding edge.</p><p>If you would like to join live to ask questions or join the discussion we would love to have you! Sign up below 👇</p><p><a href="https://lu.ma/oxenbookclub">Arxiv Dives with Oxen.ai 📚🤿🐂 · Zoom · Luma</a></p><p>The following are the notes from the live session. Many thanks to the community asking great questions along the way. Feel free to watch the video and follow along for the full context.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEKF4ZJrzPDs&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEKF4ZJrzPDs&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FEKF4ZJrzPDs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/354d59b384ace42e73f1bcde3474cbfc/href">https://medium.com/media/354d59b384ace42e73f1bcde3474cbfc/href</a></iframe><h3>Why is this paper important?</h3><p>Large Language Models that are trained on large datasets of text have been shown to acquire a surprising set of capabilities. Whether it is to be an AI coding assistant, or a creative writing assistant, we want the model to understand a wide variety of knowledge.</p><p>The authors state that we want LLMs to understand the nuances of language and that there can be multiple valid responses to a single prompt.</p><p>When writing code there is excellent code that compiles and runs, as well as what poor inefficient code looks like that runs and gives the same output. Both are technically valid, one is just better than the other. When performing creating writing we want the model to be aware of common misconceptions believed by 50% of people, but we do not want it to claim this misconception to be true.</p><p>We want to build AI systems that follow our preferences so that they are safe, performant and controllable. DPO provides a simple classification loss for going from a model that knows a lot, to a model that behaves how humans want it to.</p><h3>Zero to ChatGPT</h3><p>In order to understand where DPO fits in, and why people are excited about it, let’s look at the steps it takes to create a system like ChatGPT.</p><ol><li>Unsupervised pre-training (done by big company with lots of $, think LLama-2, Mistral, etc)</li><li>Supervised Fine Tuning (can be done by you, tailored to your use case)</li><li>Reinforcement learning from human feedback (RLHF) (can be done by you, but is hard)</li></ol><p>DPO replaces step 3, making it easier to understand and more stable to train, all while maintaining or beating performance of RLHF. If you are curious about prior work and background on RLHF, we did a previous dive on InstructGPT that goes over the basics.</p><h3>Replacing RLHF with DPO</h3><p>If we were to break down the total number of models required for end to end RLHF, we see you end up copying and modifying the base model four times.</p><ol><li>Pre-Trained Base LLM</li><li>Supervised Fine Tuned (SFT) LLM</li><li>Reward Model (LLM, but modified to be a reward model)</li><li>PPO Optimized Language Model (Final LLM aligned to preferences)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PdF3wlR2MJOwBFMt.png" /></figure><p>Each time you perform one of these steps, you are copying all the parameters and modifying them with some sort of training loop. This means if you want to do end to end RLHF with PPO for a 7B parameter model, each taking up ~14GB represented as f16, you will end up with four artifacts of a total of ~56GB of parameters.</p><p>The Reward Model is simply the SFT model copied, and modified so the un-embedding layer is removed, and a scalar reward head is added. The PPO model is also a copy of the SFT model, where the parameters will be updated to align with human preferences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-QwCtJV9XjPPpfFW.png" /></figure><p>DPO simplifies this process by removing the reward model all together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZkXOctFdaFLwU9He.png" /></figure><p>They instead feed a comparison dataset directly to the final model by modifying the loss function of the final step.</p><p>This is a great example of removing dependencies, and how keeping it simple can lead to better reseults.</p><h3>Let’s Get Lost in The Loss Function 🕵️‍♂️</h3><p>To understand fully the magic behind DPO, we must dive into the math. The loss function is the most important part of the paper. The paper states you can replace RL with “a simple classification loss”. Let’s see what that actually means in practice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JjpXZjTIIdFCEmWI.png" /></figure><p>Scan the paper, and skip all the derivations until you get to section 4, equation 7.</p><p>If you hit this section and said “it looks like Greek to me”, you are in the right place. Let’s try to explain what is going on here in plain english.</p><p>Loss is the measure of how well our model is doing, given the data. At the end of the day if we can minimize the loss, we are winning. Let’s start with a simplified version of the equation that has a winner (W) and a loser (L).</p><p>In our case the winner will be the text completion that we labeled as 👍 and the loser will be the text completion we labeled as 👎.</p><pre>Prompt (X): Oxen.ai&#39;s data version control ... <br><br>👍 W = Oxen.ai&#39;s data version control gives you visibility into <br>       changes into your data over time with simple easy to <br>       remember commands and workflows that mirror git. <br><br>👎 L = Oxen.ai&#39;s data version control is hard to learn because <br>       they throw a bunch of new lingo at you.</pre><p>If we were training a language model at Oxen.ai, we would prefer the first completion and give it the thumbs up.</p><p>Back to the math, if we get a high score for W and a low score for L, W — L will be a large number. Usually you want to minimize loss so they slap a negative sign on the start of the equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SVtRG7oOlpU-cb-t.jpg" /></figure><p>Although the full equation above looks more complicated with logs and beta’s and sigmas and pi’s at the end of the day we are trying to have a high score for W and a low score for L.</p><p>At a high level this is a simple binary cross-entropy objective, and similar to what you learn in machine learning 101 when learning about classification loss functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iixf3A6bsEkaGk-a.png" /></figure><p>Now let’s break it down a little further.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/0*m66EBw_8JMy6Vbwj.jpg" /></figure><p>What are these pi’s, ys, and xs doing in here?</p><p>In this expression x is the prompt, y_w is the completion, and pi_theta is the language model. It can be read as the probability of the winning completion, given a prompt.</p><p>Looking at our example above, the probability of the winning completion would the sum of the probabilities of each token predicted.</p><pre>Prompt: Oxen.ai&#39;s data version control ... <br><br>👍 W = gives (0.8) you (0.9) visibility (0.8) into (0.4) changes (0.75) ... <br>👎 L = is (0.6) hard (0.2) to (0.4) learn (0.5) because (0.8) <br><br><br>0.8 + 0.9 + 0.8 + 0.4 + 0.75 should give you a higher total probability <br>for W than L</pre><p>In practice you use log probabilities for numerical stability, but you can think of the probability of the entire sequence as the sum of all its parts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*4X1pxZksvrIqhxtq.jpg" /></figure><p>On the other side we have y_l and the probability of the losing completion given the same prompt.</p><p>Hopefully you start to see a pattern in the equation. Probabilities of the winners minus losers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e98uK39GCht_onEs.jpg" /></figure><p>Okay. Now that we understand the inner most terms, let’s zoom back out. We have our pi_theta divided a pi_ref.</p><p>pi_theta is the simply the language model we are training. pi_ref is the pre-trained language model we have already learned.</p><p>The reason they divide by the “reference model” is to make sure your DPO trained language model does not deviate too far from the knowledge of the original model. The pre-trained model has already learned a lot about the world, and we do not want to overfit to the just the preference data. They state that pi_theta and pi_ref are both initialized to the Supervised Fine Tuned (SFT) model.</p><p>You will often hear the drift between two distributions called the <strong>KL Divergence. </strong>This equation uses the KL Divergence so that the probability of y_w (winner) given the input x is high from the original language model, we want it to also be high from the new language model.</p><p>Overall we have the probability of the winning completion, minus the probability of the losing completion. Then we divide by the probability of the pre-trained reference language model in the denominator as regularization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yCWMF5gGLr6oVM0P.png" /></figure><p>One more look at the full thing now that you have seen the individual parts.</p><p>Squinting your eyes and assuming the beta and log and sigmoid are well chosen hyper parameters for numerical stability, I hope this helps you gain an intuition how this loss function would score a pair of completions. At it’s core it is a binary cross-entropy loss function with additional parameters inside.</p><h3>Putting It All Together</h3><ol><li>Sample two completions from our reference language model given a prompt x.</li><li>Optimize our new language model through backprop to pi_theta to minimize our loss.</li><li>The model gets rewarded if the completion y_w has a higher probability than y_l .</li><li>The model gets rewarded if the completions of W and L are close to the pre-trained model pi_ref&#39;s completions.</li></ol><p>Now that we understand the loss equation better, the full DPO pipeline is relatively straightforward.</p><h3>Experiments</h3><p>In the paper they run a few different experiments to compare DPO to PPO and RLHF.</p><h4>Sentiment Generation</h4><p>For this task, the prompt x is a prefix of a movie review from the IMDB dataset and the policy must generate a completion Y with positive sentiment. They are seeing if they can align a language model to only generate completions with positive sentiment.</p><pre>X: Iron man was ... Y_W: the best movie of all time because ... Y_L: the worse marvel movie I think I have ever seen ...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sDsv78WuiBcxQXDh.png" /></figure><p>First they performed supervised fine tuning on GPT-2-L on the train split of the IMDB dataset, so that the model would generate text that looks like movie reviews. Then they use a pre-trained sentiment classifier to generate the labeled preference dataset. This was then the dataset they evaluated DPO on.</p><p>The graph they present in the paper shows how the model generates a bunch of positive sentiment sentences (high reward) across a variety of KL divergence scores. They ran a suite of 22 different hyper parameter settings to generate this data for different types of models. (Section 6.1)</p><p>The takeaway is that DPO provides the highest alignment to preferences across completions that vary in probability distribution from the original reference model.</p><h4>Summarization</h4><p>For this task they take a forum post from reddit as the input X, then the policy must generate a summary Y of the main points in the post.</p><p>They use the Reddit TL;DR summarization dataset for this experiment along with human preferences already gathered.</p><p>Again, first perform supervised fine tuning on the reddit responses to learn to generate summaries. Then they used Anthropic’s Helpful and Harmless dialogue dataset containing 170k dialogues between a human and an assistant to align the model with human preferences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lgdNwFjsbLp8xeWY.png" /></figure><p>In order to evaluate the summarizations they use GPT-4 as the evaluator across a variety of temperature settings.</p><p>You can see that DPO exceeds PPO and pure SFT in summarization while being more robust to changes in temperature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/0*u1-E8u32H4QECuf7.png" /></figure><p>In order to justify usage of GPT-4 for evaluation, they conduct a study comparing it to human evaluators.</p><p>S stands for simple prompt which asks which summary is better<br>C stands for concise prompt which asks which summary is more concise.</p><p>GPT-4 tends to agree with humans about as often as humans agree with each other, suggesting that GPT-4 is a reasonable proxy.</p><h3>Conclusion</h3><p>DPO is exciting because it reduces the overhead of taking a model from a pretty good SFT model, to a high quality model aligned with your preferences. They propose DPO as an alternative to RLHF that was introduced in the InstructGPT paper by OpenAI, and it is really cool to see what academia can improve on given limited resources.</p><p>An open question at the time of publishing was how well this scales to larger models — in the paper they only trained models up to 6B parameters. Since the release of the paper, we have seen many open source models use DPO with great success.</p><p>It also remains to be seen how well DPO can generalize to out of distribution data. People are starting to experiment with using DPO as a self-play technique to see if you can improve a language model simply by sampling from it, and asking it to access it’s own outputs. We will dive into some of these self-play papers in upcoming ArXiv Dives!</p><h3>Next Up</h3><p>To find out what paper we are covering next and join the discussion at large, checkout our Discord 👇</p><p><a href="https://discord.com/invite/s3tBEn7Ptg?ref=blog.oxen.ai">Join the oxen Discord Server!</a></p><p>If you enjoyed this dive, please join us next week live! We always save time for questions at the end, and always enjoy the live discussion where we can clarify and dive deeper as needed.</p><p><a href="https://lu.ma/oxenbookclub?ref=blog.oxen.ai">Arxiv Dives with Oxen.ai 📚🤿🐂 · Zoom · Luma</a></p><p>All the past dives can be found on the blog.</p><p><a href="https://blog.oxen.ai/tag/arxiv-dives/">Arxiv Dives - Oxen.ai</a></p><p>The live sessions are posted on YouTube if you want to watch at your own leisure.</p><p><a href="https://www.youtube.com/channel/UCIYC0IZ4fKmXaeGl95WIf5Q?ref=blog.oxen.ai">Oxen</a></p><p>Best &amp; Moo,</p><p>~ The herd at <a href="https://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a></p><h3>Who is Oxen.ai?</h3><p><a href="https://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a> is an <a href="https://github.com/Oxen-AI/oxen-release?ref=blog.oxen.ai">open source project</a> aimed at solving some of the challenges with iterating on and curating machine learning datasets. At its core Oxen is a lightning fast data version control tool optimized for large unstructured datasets. We are currently working on collaboration workflows to enable the high quality, curated public and private <a href="https://www.oxen.ai/explore?ref=blog.oxen.ai">data repositories</a> to advance the field of AI, while keeping all the data accessible and auditable.</p><p>If you would like to learn more, <a href="https://github.com/Oxen-AI/oxen-release?ref=blog.oxen.ai">star us on GitHub</a> or head to <a href="https://www.oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a> and create an account.</p><p><em>Originally published at </em><a href="https://blog.oxen.ai/arxiv-dives-direct-preference-optimization-dpo/"><em>https://blog.oxen.ai</em></a><em> on January 30, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3de57d417b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arxiv Dives — Efficient Streaming Language Models with Attention Sinks]]></title>
            <link>https://medium.com/@oxenai/arxiv-dives-efficient-streaming-language-models-with-attention-sinks-9da6390cc527?source=rss-82ea984bd9af------2</link>
            <guid isPermaLink="false">https://medium.com/p/9da6390cc527</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[OXEN AI.  Build World-Class AI Datasets. Together.]]></dc:creator>
            <pubDate>Sat, 20 Jan 2024 19:13:03 GMT</pubDate>
            <atom:updated>2024-01-22T22:26:06.240Z</atom:updated>
            <content:encoded><![CDATA[<h3>Arxiv Dives — Efficient Streaming Language Models with Attention Sinks</h3><p>This paper introduces the concept of an Attention Sink which helps Large Language Models (LLMs) maintain the coherence of text into the millions of tokens while also maintaining a finite memory footprint and latency.</p><p>Transformer based language models tend to break down in terms of text quality, latency, memory usage once they reach a certain context length. The paper introduces the concept of a StreamingLLM to solve all three of these issues.</p><p>Paper: <a href="https://arxiv.org/abs/2309.17453?ref=blog.oxen.ai">https://arxiv.org/abs/2309.17453</a></p><p>Team: Massachusetts Institute of Technology, Meta AI, Carnegie Mellon University, NVIDIA</p><p>Publish Date: September 29th, 2023</p><h3>Arxiv Dives</h3><p>Every Friday at <a href="https://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a> we host a paper club called “ <a href="https://blog.oxen.ai/arxiv-dive-manifesto/">Arxiv Dives</a>” to make us smarter Oxen 🐂 🧠. We believe diving into the details of research papers is the best way to build fundamental knowledge, spot patterns and keep up with the bleeding edge.</p><p>If you would like to join live to ask questions or join the discussion we would love to have you! Sign up below 👇</p><p><a href="https://lu.ma/oxenbookclub?ref=blog.oxen.ai">https://lu.ma/oxenbookclub</a></p><p>The following are the notes from the live session presented by Arxiv Dive community member <a href="https://www.linkedin.com/in/daniel-varoli?utm_source=share&amp;utm_campaign=share_via&amp;utm_content=profile&amp;utm_medium=ios_app">Daniel Varoli</a>. Many thanks to the research he did preparing this dive for the group. Feel free to watch the video and follow along for the full context.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fc0-NDqacbgM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dc0-NDqacbgM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fc0-NDqacbgM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5feb06b2cc464fe51fd1b13dda11b19/href">https://medium.com/media/d5feb06b2cc464fe51fd1b13dda11b19/href</a></iframe><h3>Why are StreamingLLM’s important?</h3><p>Let’s start with a use case. Pretend you are building a chatbot. You pick LLama2–7B because it is open source and you can run it in your own infrastructure. You decide to run it without any modifications to get a baseline of performance.</p><p>Soon you get a beta user who starts using your chatbot. You observe the following behavior:</p><ul><li>The model gets slower as the conversation gets longer</li><li>At some point the model starts outputting gibberish</li><li>Eventually everything crashes and you don’t know why.</li></ul><p>You remember you’ve read something about a “context window” limitation and realize that after 4096 tokens is just about when your model starts generating gibberish and just before it starts running out of memory.</p><p>You spin up a larger GPU to get rid of the out of memory errors, but still see the conversation slowing down, and eventually the model is outputting gibberish.</p><p>Why is this?</p><h3>What is Context Length?</h3><p>Transformer based Large Language Models tend to only be able to handle input of a certain context window. You may have seen this limit on the OpenAI GPT APIs or while playing around with Open Source models.</p><p>The context window is usually set at training, in order to keep the GPU memory usage and computational complexity under control. The vanilla self attention mechanism has the property of being O(N²) with respect to the context length.</p><p>For example, GPT-2 had a context window of 1024 tokens, LLama-2 has a context winow of ~4k tokens, and GPT-4 has reached up to 32k tokens.</p><p>To relate these numbers to the real world — there are about 400 tokens in a single page in a book. So 4k tokens is about 10 pages of text.</p><p>This is not a hard limit on the model itself, but rather the fact that longer inputs can mean longer inference time, more GPU memory, and can affect your model’s perplexity or performance on language modeling tasks.</p><p>To see this in action, the GitHub repository that goes along with the paper has a great example video.</p><p><a href="https://github.com/mit-han-lab/streaming-llm/blob/main/README.md?ref=blog.oxen.ai">streaming-llm/README.md at main · mit-han-lab/streaming-llm</a></p><p>On the left and the right are two LLMs, one with Attention Sinks called the StreamingLLM, and one without. They both start by generating coherent text based on their training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oaPKR6GlFgSPqA3-.jpeg" /></figure><p>The problem is, once we hit a certain context length, the model without the StreamingLLM architecture starts slowing down as well as predicting text that is no longer coherent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*peJzIgTXLkftapsG.jpeg" /></figure><p>The model on the left starts spitting out random characters and patterns that no longer look like English. The StreamingLLM on the other hand continues to generate text that is readable and coherent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wpJvZgv6aNkCYOQV.jpeg" /></figure><p>Not only this, at a certain point the model without the StreamingLLM will quickly run out of GPU memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C5VEpmBalyPbvPDA.jpeg" /></figure><h3>What are we optimizing for?</h3><p>Back to our chatbot example, we need to fix three things:</p><ul><li>The <strong>speed</strong> of our model on long sequences</li><li>The <strong>memory usage</strong> of our model on long sequences</li><li>The <strong>text quality</strong> generated after the training context window has been exceeded.</li></ul><p><strong>Important Note</strong>: While this paper does produce stable perplexity as a measure of text quality on long sequences, <strong>it does not enable the model to remember everything within that context window</strong>. Perplexity is simply “how well do we model the next word prediction”. Or “how perplexed is the model when it sees the actual word in the training data vs what it generated”. Lower perplexity is better, as the model is less perplexed. You can have a low perplexity while still not referring back to context earlier in the sequence. Long term reasoning and memory would be a fourth axes you could optimize for, but is not in the scope of this paper.</p><p>With that said, let’s start with optimizing the speed of the model on long sequences.</p><h3>Key-Value (KV) Caching</h3><p>Before diving into Attention Sinks, there is a concept known as KV Caching that has proven to solve the first one of our problems — speeding up the text generation.</p><p>Transformer blocks within an LLM consist of three large matrices called the Key, Query, and Value matrices. These matrices require N² computation with respect to the sequence length in order for the model to look back all previous tokens generated.</p><p>When generating a new token, it is important to note that the previous tokens all remain unchanged. Because of this property, we can cache the previously computed Key and Value matrices and apply them to only the last token position in the Queries.</p><p>In other words, instead of this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ITnQlQA8xNmBfE4Z.jpeg" /></figure><p>We can do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YekdUqX-c5xEFO8U.jpeg" /></figure><p>Then on the next generation, only a single token will be passed in, and the cached KV rows will be stacked on top of the K and V row for the new token to produce the single row Q and multi-row K and V that we want.</p><p>For more on KV Caching, feel free to read this <a href="https://vgel.me/posts/faster-inference/?ref=blog.oxen.ai#KV_caching">blog post</a>. If you have no idea what Keys, Values and Queries are within a transformer block, we have another deep dive into the <a href="https://blog.oxen.ai/arxiv-dives-attention-is-all-you-need/">Attention is All You Need</a> paper that would be a good starting point.</p><p>KV Caching helps with speeding up the LLM, since we do not have to recompute everything for each new token. However now we have introduced a new variable of the size of the KV cache which will increase your memory usage with each generated token.</p><h3>Efficient Streaming with Attention Sinks</h3><p>Now that we have some context (pun intended) we can take a look at the core contribution of the paper.</p><p>We need our model to scale both in memory usage and speed, while maintaining perplexity (generating coherent text) all at the same time.</p><p>If you look at the Dense Attention mechanism in a vanilla transformer, you can see that we have poor computational complexity and high perplexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j2_cBDUFerMkTpcK.jpeg" /></figure><p>Techniques like sliding window attention improve computational complexity, but fall over in terms of perplexity after certain context lengths.</p><p>This paper introduced StreamingLLMs with special tokens that are used as “Attention Sinks” to give us the best of both worlds. It is both efficient and stable when generating text beyond the length of the trained context window.</p><h3>What are Attention Sinks?</h3><p>One of the things that the authors noticed in this paper is that methods that use the KV-Cache immediately spike in perplexity as soon as a the first entry is evicted from the KV-Cache. This suggests that these initial tokens are crucial for maintaining stability of the LLM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TCMo9qKpTJn7fA4_.jpeg" /></figure><p>After observing this spike in perplexity, they decided to look deeper into how the self attention mechanism was selecting the tokens to attend to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o2RVcM_pXz0kanhc.jpeg" /></figure><p>They noticed that the first few tokens accumulate a lot of the attention if you average it over the whole sequence. It seems that the model has learned a bias towards the absolute positions of these tokens during training, since they are always there while generating. If you evict them from the cache — this is where the model starts to go haywire.</p><p>This leads to the intuition that if we keep these first few tokens around, maybe the model’s performance will not degrade. Keeping the first few tokens in the KV-Cache is exactly what they decide to do, and they call this technique an “Attention Sink”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uO6ov13trSpm_gDf.jpeg" /></figure><p>The KV Cache typically has a fixed size to maintain memory consumption while increasing speed, so you have to evict the first tokens once the sequence reaches a certain length.</p><p><strong>The big reveal</strong>: with an “Attention Sink”, you can simply evict the 4th, 5th, 6th, token etc while keeping the first N tokens within the cache. Now the model can dump its “excess attention” to the first N tokens, and not be “surprised” when they are evicted.</p><p>This simple trick leads to stability in the generation as we go forward, and is a bit shocking that it works at all. While it does improve language modeling stability, it does still evict tokens from the cache so it does <em>not</em> improve the model’s ability to reason about long sequences of text.</p><p>What’s cool about this technique is that you do not have to retrain the model at all to get these results. You simply have to change how the KV-Cache is updated.</p><h3>Why does the model learn these mechanics?</h3><p>There is a great blogpost that illustrates why this behavior may emerge at all.</p><p><a href="https://www.evanmiller.org/attention-is-off-by-one.html?ref=blog.oxen.ai">Attention Is Off By One</a></p><p>The TLDR is that within the Self Attention Mechanism the model has a SoftMax that’s job is to choose which tokens to attend to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w8O3Krc8rxuy7pn1.jpeg" /></figure><p>One property of the SoftMax is that <em>something</em> always has to be picked. The probability density accumulates to 1, and the model has learned that the first token is a good default to dump it’s “extra attention” on.</p><p>This feels like an odd feature of the Transformer in general, but the fact is: adding attention sinks works. Future research may come up with a less hacky solution that builds this sort of bias into the model itself.</p><h3>Results on Perplexity</h3><p>They measure the perplexity of 4 different approaches to attention with a few different LLMs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WVWXK7Qd5hT2-PMI.jpeg" /></figure><p>As you can see, the perplexity stays consistent with respect to sequence length with the StreamingLLM while it immediate spikes with techniques such as sliding window attention.</p><p>They performed language modeling on a concatenated test set of 100 books (which is 4 million tokens!) and saw the model maintained stable perplexity as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kuRG1UIouKIrUrvz.jpeg" /></figure><p>Not only does the perplexity stay stable, the latency and memory usage of the StreamingLLM are also much more optimal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dv4_RWZ8XlownOSa.jpeg" /></figure><h3>What if we trained a model with a sink token?</h3><p>So far we have not even trained a model. It has simply been a matter of changing how we evict tokens from the KV-Cache.</p><p>The authors decide to run experiments on pre-training a model with an explicit “sink token” and prepending this token to all the training examples fed into the model.</p><p>In the “vanilla” setting without pre-training we need 4 sink tokens to recover perplexity. They train a 160 parameter model and show that by adding the sink token to the pre-training, 1 sink token is sufficient.</p><p>More details of the pre-training experiment are in the paper, but it is interesting that if you explicitly give the model capacity to dump it’s attention to a sink token, it will learn to use it.</p><h3>Conclusion</h3><p>The StreamingLLM is an interesting finding and essential research into fixing model behavior after they extend beyond their trained context window. It produces stable text while maintaining latency and low memory consumption.</p><p>The StreamingLLM does not necessarily mean the model will remember everything in its past, or be able to reason about long sequences of text. This is because we are still evicting tokens from the KV Cache. Understanding how the KV Cache works, and what eviction policy is optimal can help us design models to be more effective in the future.</p><p>This is a nice trick to get your models to work with long sequences in production, and a great jumping off point for future research.</p><p>We had a great discussion live and thank you to our guest presenter Daniel Varoli from Zapata.ai for putting together the research and presentation!</p><h3>Next Up</h3><p>To find out what paper we are covering next and join the discussion at large, checkout our Discord 👇</p><p><a href="https://discord.com/invite/s3tBEn7Ptg?ref=blog.oxen.ai">Join the oxen Discord Server!</a></p><p>If you enjoyed this dive, please join us next week live! We always save time for questions at the end, and always enjoy the live discussion where we can clarify and dive deeper as needed.</p><p><a href="https://lu.ma/oxenbookclub?ref=blog.oxen.ai">Arxiv Dives with Oxen.ai 📚🤿🐂 · Zoom · Luma</a></p><p>All the past dives can be found on the blog.</p><p><a href="https://blog.oxen.ai/tag/arxiv-dives/">Arxiv Dives - Oxen.ai</a></p><p>The live sessions are posted on YouTube if you want to watch at your own leisure.</p><p><a href="https://www.youtube.com/channel/UCIYC0IZ4fKmXaeGl95WIf5Q?ref=blog.oxen.ai">Oxen</a></p><p>Best &amp; Moo,</p><p>~ The herd at <a href="https://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a></p><h3>Who is Oxen.ai?</h3><p><a href="https://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a> is an <a href="https://github.com/Oxen-AI/oxen-release?ref=blog.oxen.ai">open source project</a> aimed at solving some of the challenges with iterating on and curating machine learning datasets. At its core Oxen is a lightning fast data version control tool optimized for large unstructured datasets. We are currently working on collaboration workflows to enable the high quality, curated public and private <a href="https://www.oxen.ai/explore?ref=blog.oxen.ai">data repositories</a> to advance the field of AI, while keeping all the data accessible and auditable.</p><p>If you would like to learn more, <a href="https://github.com/Oxen-AI/oxen-release?ref=blog.oxen.ai">star us on GitHub</a> or head to <a href="https://www.oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a> and create an account.</p><p><a href="https://github.com/Oxen-AI/oxen-release?ref=blog.oxen.ai">GitHub - Oxen-AI/oxen-release: Lightning fast data version control system for structured and unstructured machine learning datasets. We aim to make versioning datasets as easy as versioning code.</a></p><p><em>Originally published at </em><a href="https://blog.oxen.ai/arxiv-dives-efficient-streaming-language-models-with-attention-sinks/"><em>https://blog.oxen.ai</em></a><em> on January 20, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9da6390cc527" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arxiv Dives — How Mixture of Experts works with Mixtral 8x7B]]></title>
            <link>https://medium.com/@oxenai/arxiv-dives-how-mixture-of-experts-works-with-mixtral-8x7b-4acbbc64010d?source=rss-82ea984bd9af------2</link>
            <guid isPermaLink="false">https://medium.com/p/4acbbc64010d</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[OXEN AI.  Build World-Class AI Datasets. Together.]]></dc:creator>
            <pubDate>Sat, 13 Jan 2024 16:59:24 GMT</pubDate>
            <atom:updated>2024-01-16T18:32:10.003Z</atom:updated>
            <content:encoded><![CDATA[<h3>Arxiv Dives — How Mixture of Experts works with Mixtral 8x7B</h3><p>Mixtral 8x7B is an open source mixture of experts large language model released by the team at Mistral.ai that outperforms Llama-2 70B and GPT-3.5 on a variety natural language understanding tasks.</p><p>The magic of the model is that it only uses 13B parameters during inference, which makes it fast, but has access to a total of 47B parameters at its finger tips for higher accuracy. The model is open source for the community to experiment with.</p><p>Paper: <a href="https://arxiv.org/abs/2401.04088">https://arxiv.org/abs/2401.04088</a></p><p>Team: Mistral.ai</p><p>Paper Date: January 8th, 2024</p><h3>Arxiv Dives</h3><p>Every Friday at <a href="https://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a> we host a paper club called “ <a href="https://blog.oxen.ai/arxiv-dive-manifesto/">Arxiv Dives</a>” to make us smarter Oxen 🐂 🧠. We believe diving into the details of research papers is the best way to build fundamental knowledge, spot patterns and keep up with the bleeding edge.</p><p>If you would like to join live to ask questions or join the discussion we would love to have you! Sign up below 👇</p><p>The following are the notes from the live session. Feel free to watch the video and follow along for the full context.</p><h3>MOE Before Mixtral</h3><p>Mixture of Experts (MOE) is by no means not a new concept. The application of MOE to the Transformer architecture what is getting attention right now. If you want to learn a bit of the recent history of Mixture of Experts applied to Transformers the following papers are helpful.</p><p>Mixtral takes this research above and applies it to their 7B parameter language model and extends its parameters to a sparse 47B parameter Sparse Mixture of Experts (SMoE).</p><h3>What is MOE?</h3><p>The mechanism of MOE is quite simple and is applied inside the transformer block of the LLM. A standard transformer block contains the self attention mechanism, as well as a feed forward layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fJe_mdcBBkIXvY7a.png" /></figure><p>Within this transformer block, Mixtral 8x7B simply replaces the single feed forward layer with a set of N feed forward layers and adds a router in front of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b1v4_PJ8OspFlJYQ.png" /></figure><p>The number of experts is a configurable parameter that is fixed before training. In the case of Mixtral 8x7B they have 8 feed forward layers that can be routed to after the attention heads.</p><p>The router then choses 2 of the experts based on the current context to help predict the next word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*m-l-cDrr6XVzllEy.png" /></figure><h3>Motivation</h3><p>The intuition for why we would want a mixture of experts is that this allows for certain experts to specialize in different domains. For example — one expert could focus on math. Another could be great at biology. The third could focus on philosophy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0xWQo7UasN6Eo86M.png" /></figure><h3>How do the experts work?</h3><p>There are a few things you have to wrap your head around when thinking of MOE in the context of Language Modeling and Transformers.</p><ol><li>The experts help predict one token at a time</li><li>The router decides which expert is active at each token</li><li>Experts are combined through a gated linear combination to predict the next token</li></ol><h3>Token By Token</h3><p>Since the experts are within a transformer block, the routing happens on a token by token basis. As token X comes in, the transformer block’s job is to predict the next token Y. The transformer block has access to all of the previous context through the self attention mechanism. The output of the self attention mechanism then says to the router:</p><blockquote><em>Looks like are talking about physics, which one of you is going to help me predict the next token?</em></blockquote><p>The router has learned which experts help the most with physics problems, and decides to delegate the information to the top K experts.</p><h3>How does the routing work?</h3><p>If you are familiar with standard classification tasks in machine learning, this part will look very familiar. The routing is simply a softmax layer sitting between the attention heads and the set of K experts. This layer learns which expert is best for which type of tokens.</p><p>Here’s a visualization of the routing from the <a href="https://arxiv.org/abs/2209.01667?ref=blog.oxen.ai">Review of Sparse Expert Models</a> paper</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VUB4YxU_d-1GQ0AX.png" /></figure><p>To make it even more efficient, Mixtral 8x7B only takes the top 2 experts based on the logits of the router to feed through to predict the next token.</p><p>You may hear people refer to the “sparse parameter count” vs the “active parameter count”. The sparse count is the full count + all the experts, whereas the active count is only the parameter count of the model with the subset of K experts.</p><h3>How are the experts combined?</h3><p>The outputs of the experts are then computed by a weighted linear combination of each expert given the token multiplied by the softmax gated value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/0*mjU76bvV6qcV2-cC.png" /></figure><p>Again, K is a hyper parameter you can choose from. It would be interesting to see what the performance in Mixtral would be with K=1 vs K=4 and not just K=2.</p><p>That’s it. MOE only runs a subset of the experts per token so although you may have 47B parameters loaded into VRAM for efficiency we only perform floating point operations on 13B of them.</p><h3>Latency vs Throughput vs Memory consumption</h3><p>Although the model has less parameters to run at inference time, that does not mean it is easy to scale up on any type of hardware. You still need all the weights loaded into GPU memory if you want the GPU to go brrr. It is also more difficult to batch inputs on this type of architecture since you are not guaranteed that the experts are going to be routed to equally.</p><p>If you’re interested in these optimizations, I’d recommend reading “A Review of Sparse Expert Models in Deep Learning”. In this paper Jeff Dean and his colleagues talk about efficient ways to implement MOEs as well as the history in general.</p><p>So while Mixtral 8x7B is smaller than Llama-2 70B, it still takes 47GB of memory and integrated engineering to run. While you could page the experts in and out of memory, the time to copy between devices would slow the whole system down.</p><p>What is exciting is we are already seeing people apply MOE to even smaller models like Microsoft’s Phi 2.7B model.</p><p>I think this area of research is promising for getting powerful local models, but there is still plenty of engineering and experimentation to be done to get them to work well.</p><h3>Routing Analysis</h3><p>How do we know if each expert network is learning something different or specializing?</p><p>In order to evaluate this, they look at how often individual experts are selected for different subsets of The Pile validation set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I67KgrcC6cKDPKBx.png" /></figure><p>Surprisingly, they do not observe any obvious patterns of experts per topic. The text talking about Biology vs Philosophy vs Machine Learning all seemingly route to all experts.</p><p>The only topic that seems to have a strong difference in distribution is DM Mathematics. They state this may be because the dataset was synthetically generated and doesn’t cover that wide of a range of natural language.</p><p>This suggests that the router does exhibit preference to certain experts for structured syntactic behavior. You can really see this as they highlight the experts that are active in very syntactic tasks like writing code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tYPgCxPglQOMK-TW.png" /></figure><p>For example in the far right image, it seems like the yellow expert is quite good at white space and the dark red may be the best at punctuation and opening and closing parentheses.</p><p>It is still relatively a black box as to how the experts work, but interesting nonetheless.</p><h3>Instruction Fine Tuning</h3><p>The chat version of the model was fine-tuned to follow instructions using<br>supervised fine-tuning and Direct Preference Optimization on a paired feedback dataset.</p><p>They do not share what dataset they used, but they do report human evaluation results conducted by LMSys. The evaluation shows a higher ELO rating than GPT 3.5 Turbo and Claude-2.1. Starting to approach GPT-4. So far it is the highest ranked open source Apache 2.0 model on the leaderboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QEUcrz9eKpCXyV-8.png" /></figure><h3>Performance on QA Benchmarks</h3><p>They evaluate Mixtral 8x7B on all the traditional QA benchmarks. If you want to look at benchmarks in more detail, check them out on Oxen.ai</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4P6hftbQaGZEePHS.png" /></figure><p>I personally don’t love just staring at number blocks in these papers, and love to look at actual examples.</p><h3>Running Mixtral in the Wild</h3><p>If you’ve been following the Practical ML Dives with Oxen.ai, we have been playing around with RAG on the SQuAD Question Answering task hidden in a dataset of 1 million documents. We decided to throw Mixtral into the mix for the generation half of the problem 👨‍🍳.</p><p>Our full results sets can be found here:</p><p>Llama 70B: <a href="https://www.oxen.ai/ox/SQuAD-Context/file/main/experiments/dev-llama-70B-recall-1-precision-0-shot-1m-docs.jsonl?ref=blog.oxen.ai">https://www.oxen.ai/ox/SQuAD-Context/file/main/experiments/dev-llama-70B-recall-1-precision-0-shot-1m-docs.jsonl</a></p><p>Mixtral 8x7B: <a href="https://www.oxen.ai/ox/SQuAD-Context/file/main/experiments/dev-mixtral-8x7B-recall-1-precision-0-shot-1m-docs.jsonl?ref=blog.oxen.ai">https://www.oxen.ai/ox/SQuAD-Context/file/main/experiments/dev-mixtral-8x7B-recall-1-precision-0-shot-1m-docs.jsonl</a></p><p>~ TLDR ~ Llama 70B slightly outperforms on the task in terms of precision, but it is close.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YMDPcj85kzPsdvRZ.png" /></figure><p>I am a big fan of trying these models yourself on a task you are interested in, and not just taking the papers word for it. It is relatively easy to try out a lot of these open source models these days thanks to Together.ai and their API that mirrors the OpenAI interface.</p><pre>def run_together_ai(model, question, context, n_shot=0): import openai import os client = openai.OpenAI( api_key=os.environ.get(&quot;TOGETHER_API_KEY&quot;), base_url=&#39;https://api.together.xyz&#39;, ) prompt = construct_prompt(question, context, n=n_shot) messages = [ {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt} ] chat_completion = client.chat.completions.create( messages=messages, model=model, # &quot;mistralai/Mixtral-8x7B-Instruct-v0.1&quot;, max_tokens=1024 ) answer = chat_completion.choices[0].message.content return answer</pre><p>Feel free to try it on your own data!</p><h3>Conclusion</h3><p>MOE is a relatively simple technique that can be applied to any neural network architecture. They add additional feed forward layers within the transformer block that are selected and run at inference time with a router. The router classifies which feed forward network would be best to handle the current context.</p><p>This technique can help scale up the number of parameters in a model with minimally impacting the runtime. There is always the tradeoff of latency vs throughput vs memory consumption when optimizing a model for your use case. It will be exciting to see the developments in the coming months as the open source community applies MOE to a variety of models and architectures.</p><p>Another fun one that came out this week is MoE-Mamba (not to be confused with Mo Bamba 🪇)</p><h3>Next Up</h3><p>To find out what paper we are covering next and join the discussion at large, checkout our Discord 👇</p><p>If you enjoyed this dive, please join us next week!</p><p>All the past dives can be found on the blog.</p><p>The live sessions are posted on YouTube if you want to watch at your own leisure.</p><p>Best &amp; Moo,</p><p>~ The herd at <a href="https://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a></p><h3>Who is Oxen.ai?</h3><p><a href="https://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a> is an <a href="https://github.com/Oxen-AI/oxen-release?ref=blog.oxen.ai">open source project</a> aimed at solving some of the challenges with iterating on and curating machine learning datasets. At its core Oxen is a lightning fast data version control tool optimized for large unstructured datasets. We are currently working on collaboration workflows to enable the high quality, curated public and private <a href="https://www.oxen.ai/explore?ref=blog.oxen.ai">data repositories</a> to advance the field of AI, while keeping all the data accessible and auditable.</p><p>If you would like to learn more, <a href="https://github.com/Oxen-AI/oxen-release?ref=blog.oxen.ai">star us on GitHub</a> or head to <a href="https://www.oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a> and create an account.</p><p><em>Originally published at </em><a href="https://blog.oxen.ai/arxiv-dives-mixture-of-experts-moe-with-mixtral-8x7b/"><em>https://blog.oxen.ai</em></a><em> on January 13, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4acbbc64010d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arxiv Dives — LLaVA  an open source Large Multimodal Model (LMM)]]></title>
            <link>https://medium.com/@oxenai/arxiv-dives-llava-an-open-source-large-multimodal-model-lmm-28a43d75c532?source=rss-82ea984bd9af------2</link>
            <guid isPermaLink="false">https://medium.com/p/28a43d75c532</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[OXEN AI.  Build World-Class AI Datasets. Together.]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 17:08:48 GMT</pubDate>
            <atom:updated>2024-01-07T17:50:09.938Z</atom:updated>
            <content:encoded><![CDATA[<h3>Arxiv Dives — LLaVA 🌋 an open source Large Multimodal Model (LMM)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrnZ3A-nPAOJnjNig5tBRA.png" /></figure><h3>What is LLaVA?</h3><p>LLaVA is a Multi-Modal model that connects a Vision Encoder and an LLM for general purpose visual and language understanding.</p><p>Paper: <a href="https://arxiv.org/abs/2304.08485?ref=blog.oxen.ai">https://arxiv.org/abs/2304.08485</a></p><p>Team: Wisconsin-Madison, Microsoft Research, Columbia University</p><p>Release Date: April 17th, 2023</p><h3>What is Arxiv Dives?</h3><p>Every Friday at <a href="https://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a> we host a paper club called “ <a href="https://blog.oxen.ai/arxiv-dive-manifesto/">Arxiv Dives</a>” to make us smarter Oxen 🐂 🧠. We believe diving into the details of research papers is the best way to build fundamental knowledge, spot patterns and keep up with the bleeding edge.</p><p>If you would like to join live to ask questions or join the discussion we would love to have you! Sign up below 👇</p><p>The following are the notes from the live session. Feel free to watch the video and follow along for the full context.</p><h3>Intro</h3><p>We as humans navigate and interact with the world around us through both vision and language. Vision can be better at conveying some concepts, where text is better for others.</p><p>Like they say, an image is worth a thousand words.</p><p>Traditionally, neural networks for computer vision are quite limited in scope to what they can do.</p><p>For example, let’s imagine you are a data scientist who works for an NBA team, and you are tasked with analyzing game footage to find patterns in winning plays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/0*-RpIVbxPxggFi8aK.png" /></figure><p>A data scientist from the 2010s would have to train multiple networks. They would have one network detect where the ball is at all times, another detect the players, and another classify which action the player is taking etc.</p><p>Each one of these steps requires a separate labeled dataset and a separate model optimized for the task. This is system would be expensive to build and hard to maintain.</p><p>What if instead of 3 separate models and datasets, we could have one model to rule them all? What if we could describe in natural language the task, and the model would dynamically change what it was looking for in the image?</p><h3>Enter LLaVA 🌋</h3><p>Let’s prototype this action recognition pipeline without training a model at all. All it takes is some clever prompting, and faith that our model knows something about the game of basketball.</p><p>Feel free to follow along or try your own prompts at their live demo of the LLaVA system below.</p><p>With the simple prompt below, we have not only created an image classification system, but can chat with the model about the image.</p><p>Prompt:</p><pre>You are looking at a picture of a basketball player, <br>identify if they are shooting, dribbling or passing. <br>Answer with a single classification of &quot;shooting&quot;, &quot;dribbling&quot;, &quot;passing&quot;.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nKLVeqbPElgjnRAd.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*shJCalPahopVm7aR.png" /></figure><p>Prototyping a system with prompting gets your from zero-to-hero way faster than training an end to end model. While it might not be perfect, it is amazing the breadth of capabilities this model already has, given the instruction following dataset they introduce in the paper.</p><h3>Some other fun examples</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uaLQqxsd6HUYukI4.png" /></figure><p>Identify this artwork</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FFTFgUeMqTo5PGgs.png" /></figure><p>Meal from fridge</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XbePwWjpcqRVwPyZ.png" /></figure><p>Website from drawing</p><p>It is a great feeling when you can simply ask a model to do your bidding, and not have to write any additional code to do so.</p><p>All of it is Open Source, which means if it doesn’t work perfectly for your use case, you can take the model, add more data, and fine-tune it to your use case.</p><p>Let’s dive into how it works.</p><h3>Core Contributions</h3><ul><li>Datasets of Image-Text pairs to train on</li><li>An Open Source Large Multimodal Model (LMM) trained on these datasets</li></ul><p>The paper makes a couple core open source contributions:</p><p>Their best model is a 13B model, but they also have a 7B model that is only 1% lower accuracy from 90% to 89% on ScienceQA according to their ablation studies at the end. Since the papers release, the community has taken these models and fine tuned them to their use cases, and I think there is a lot of room to play and optimize.</p><p>A search for “llava” on hugging face at the time of writing returns over 200 models.</p><h3>Visual Instruction Data Generation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K_NLrdQPHZXD2pYe.png" /></figure><p>While there are large multimodal datasets such as CC and LAION and COCO, none of them focus explicitly on instruction following.</p><p>Creating a dataset of instructions and images is time-consuming and not very well defined when asking humans crowd source the task. In order to create the dataset at scale, with limited resources, they use GPT-4 to curate questions that someone might ask of an image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tq69bZXPBkwfu4Rg.png" /></figure><p>For the LLaVA dataset they take existing image — caption pairs and image bounding box pairs, and feed them to GPT-4 with an extensive prompt to generate both instructions and conversations about the images.</p><ol><li>Conversation</li><li>Detailed Description</li><li>Complex Reasoning</li></ol><p>They generate a few different types of instruction following data.</p><p>They give GPT-4 the captions and boxes as text sequences and do not show it the images themselves. This allows it to generate questions, generate answers to those questions, then elaborate into longer form conversation.</p><p>An example of an image caption might be:</p><blockquote><em>A group of people standing outside a black SUV</em></blockquote><p>Then GPT-4 can generate a question about the image, given the caption.</p><blockquote><em>What color is the SUV?</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u8v_uo3In-yX9e82.png" /></figure><p>They have examples in the appendix of the paper of the prompts used to generate the data.</p><ol><li>A pre-training dataset of 595k single image, prompt, response triples</li><li>An instruction tuned dataset of 158k instruction following conversations given an image.</li></ol><p>They generate two main datasets with this paper.</p><p>You can browse both datasets on Oxen.ai as well as download them for your own use.</p><ul><li><a href="https://www.oxen.ai/LilianZhou/LLaVA_pretrain_595k">LilianZhou/LLaVA_pretrain_595k | Datasets at Oxen.ai</a></li><li><a href="https://www.oxen.ai/datasets/LLaVA-Instruct?ref=blog.oxen.ai">datasets/LLaVA-Instruct | Datasets at Oxen.ai</a></li></ul><h3>Visual Instruction Tuning Model</h3><p>The model architecture is rather simple when looking at the high level building blocks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/0*DPAwkHkqP4mCVajA.png" /></figure><p>The two main building blocks of LLaVA are a Language Transformer (LLM) and a Vision Transformer (ViT). In theory you could take any off the shelf LLM and ViT and zip them together into a LLaVA-like architecture.</p><p>In this case, they take the Language Transformer from Vicuna and the Vision Transformer from CLIP (ViT-L/14) and add a trainable projection layer W on top of the image features and text features for the model to learn how to combine them.</p><p>The only addition here is the projection matrix W that helps encode the language tokens and the vision tokens into the same latent space. Quite a simple concept, and very few lines to implement in most neural net libraries like PyTorch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DeuEu2MNTLtVVbI4.png" /></figure><p>The data is then organized into conversations of the following form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dRJdaFV9jahat6ly.png" /></figure><p>Where X_instruct may be either an image then a question, or a question then an image, or simply a question later in the sequence.</p><p>For example:</p><blockquote>You are an AI Visual Assistant who is looking at a single image. Answer the user’s question about the image&lt;STOP&gt;<br>Human: How many fireworks are in the image?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/0*Encx2biMs7ogTU0k.png" /></figure><blockquote>&lt;STOP&gt;<br>Assistant: 8&lt;STOP&gt;<br>Human: Why is the Ox wearing a hat?&lt;STOP&gt;<br>Assistant: It is new years.&lt;STOP&gt;</blockquote><p>The image is broken up into 14x14 patches and fed into the ViT while the text is broken up into tokens and fed into the LLM. The projection layer learns to zip them together and voila! You can instruct the model to extract information from the image.</p><h3>Stage 1: Pre-training for Feature Alignment</h3><p>They first perform a large pre-training step on a subset of CC3M dataset which is filtered down to 595k image-text pairs.</p><p>We put all the data in Oxen.ai if you want to get a feel for it.</p><p><a href="https://www.oxen.ai/LilianZhou/LLaVA_pretrain_595k">LilianZhou/LLaVA_pretrain_595k | Datasets at Oxen.ai</a></p><p>This dataset consists of single turn conversations less complex and is just a set of questions generated directly from the captions, and lacks as much diversity and in-depth reasoning as the smaller instruct dataset.</p><p>The questions are generated by GPT-4 and the ground truth responses are simply the original captions.</p><p>This pre-training stage uses the larger dataset to make sure the LLM and the ViT embed the images and text into a similar space. During this phase they keep the ViT and the LLM frozen and are simply training the projection weights W in order to align the image features and the text features.</p><p>It is much more efficient to only train the projection matrix than train the whole model end to end.</p><p>They did an ablation study without the Pre-Training and simply fine-tune on the ScienceQA dataset and find a 5.11% drop in performance without it.</p><h3>Stage 2: Fine-Tuning End-to-End</h3><p>Next they perform a fine-tuning on the smaller dataset with full conversational data.</p><p><a href="https://www.oxen.ai/datasets/LLaVA-Instruct">datasets/LLaVA-Instruct | Datasets at Oxen.ai</a></p><p>During the fine tuning they keep the visual encoder weights frozen, and continue to update the projection layer as well as the end to end LLM.</p><p>They train the model on 8 x A100s. On this hardware setup they can complete the pre-training on 595k image-text pairs in 4 hours and the fine tuning on 158k conversations in 10 hours.</p><h3>Quantitative Evaluation</h3><p>They use a text-only GPT-4 to evaluate the quality of the responses. In order to do this they provide GPT-4 the text description of the images, the question, and the generated responses, then have GPT-4 give overall scores from 1 to 10 on helpfulness, relevance, and accuracy of the responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IsUFFpV_brYqUS7R.png" /></figure><p>I don’t know that it is necessarily a great evaluation metric seeing as they used GPT-4 to generate the training data as well as evaluate. Other models such as OpenFlamingo did not use GPT-4 in their training data. Using GPT-4 to generate training data means that it will be from a distribution that GPT-4 understands, so this evaluation technique feels biased.</p><p>It would be interesting to see a different model generate the instruction training data than the one evaluating. For example maybe we could use another open source model to generate training data, and then use GPT-4 to evaluate.</p><p>They create a couple small benchmarks to evaluate the models on as well including LLaVA-Bench with 30 images from COCO-Val-2014 and 24 images in the wild. For the 50+ images they have ~150 questions. These benchmarks also feel small, but in general it is hard to quantitatively evaluate these models, and we are all figuring it out as we go 😎.</p><h3>ScienceQA</h3><p>ScienceQA is a benchmark of 21k multiple choice questions that include images. There are a diverse set of topic categories and skills.</p><p><a href="https://www.oxen.ai/LilianZhou/ScienceQA">LilianZhou/ScienceQA | Datasets at Oxen.ai</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q8J0BPbFzfsgNmht.png" /></figure><p>Llava performs rather well when fine tuned on this dataset compared to chain of thought prompting on other models. MM-CoT stands for multimodal chain of thought.</p><h3>Conclusion</h3><p>This is promising research into using an LLM for synthetic data as well as how easy it can be to link together language and vision models through a simple linear projection.</p><p>The fact that the models and datasets are all open source allows the community to iterate on their own problems and have full control over the models without having to wait for the next drop of proprietary models.</p><p>It is hard to evaluate these models without multiple choice datasets or human labeling. I would love to explore this dataset a little more, and extend the instructions to other tasks, and really dive into what the model does well in a Practical ML Dive.</p><h3>Next Up</h3><p>To find out what paper we are covering next and join the discussion at large, checkout our Discord:</p><p><a href="https://discord.com/invite/s3tBEn7Ptg">Join the oxen Discord Server!</a></p><p>If you enjoyed this dive, please join us next week!</p><p><a href="https://lu.ma/oxenbookclub">Arxiv Dives with Oxen.ai 📚🤿🐂 · Zoom · Luma</a></p><p>All the past dives can be found on the blog.</p><p><a href="https://blog.oxen.ai/tag/arxiv-dives/">Arxiv Dives - Oxen.ai</a></p><p>The live sessions are posted on YouTube if you want to watch at your own leisure.</p><p><a href="https://www.youtube.com/channel/UCIYC0IZ4fKmXaeGl95WIf5Q">Oxen</a></p><p>Best &amp; Moo,</p><p>~ The herd at <a href="https://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a></p><h3>Who is Oxen.ai?</h3><p><a href="https://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a> is an <a href="https://github.com/Oxen-AI/oxen-release?ref=blog.oxen.ai">open source project</a> aimed at solving some of the challenges with iterating on and curating machine learning datasets. At its core Oxen is a lightning fast data version control tool optimized for large unstructured datasets. We are currently working on collaboration workflows to enable the high quality, curated public and private <a href="https://www.oxen.ai/explore?ref=blog.oxen.ai">data repositories</a> to advance the field of AI, while keeping all the data accessible and auditable.</p><p>If you would like to learn more, <a href="https://github.com/Oxen-AI/oxen-release?ref=blog.oxen.ai">star us on GitHub</a> or head to <a href="https://www.oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a> and create an account.</p><p><em>Originally published at </em><a href="https://blog.oxen.ai/arxiv-dive-how-to-llava-works/"><em>https://blog.oxen.ai</em></a><em> on January 7, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28a43d75c532" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical ML Dive — How to train Mamba for Question Answering]]></title>
            <link>https://medium.com/@oxenai/practical-ml-dive-how-to-train-mamba-for-question-answering-14982ef4ea66?source=rss-82ea984bd9af------2</link>
            <guid isPermaLink="false">https://medium.com/p/14982ef4ea66</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[OXEN AI.  Build World-Class AI Datasets. Together.]]></dc:creator>
            <pubDate>Thu, 21 Dec 2023 02:42:37 GMT</pubDate>
            <atom:updated>2023-12-22T17:48:55.431Z</atom:updated>
            <content:encoded><![CDATA[<h3>Practical ML Dive — How to train Mamba for Question Answering</h3><h3>What is Mamba 🐍?</h3><p>There is a lot of hype about Mamba being a fast alternative to the Transformer architecture. The paper released in December of 2023 claims <strong>5x faster throughput</strong> when compared to Transformers and <strong>scales linearly with the length of the sequence</strong> instead of quadratically.</p><p>Last Friday we did a deep dive into how the model architecture works. If you are curious about the internals, check out our Arxiv Dive covering the paper.</p><p><a href="https://blog.oxen.ai/mamba-linear-time-sequence-modeling-with-selective-state-spaces-arxiv-dives/">Mamba: Linear-Time Sequence Modeling with Selective State Spaces - Arxiv Dives</a></p><p>If you do not need to know about the internals, and just want to see how the model performs on your data, this is the blog post for you!</p><h3>Practical ML Dive</h3><p>This post is a part of a series called <a href="https://lu.ma/practicalml?ref=blog.oxen.ai">Practical ML Dives</a>. Every Wednesday we get together and hack on real world projects. If you would like to join the practical discussion live, <a href="https://lu.ma/practicalml?ref=blog.oxen.ai">sign up here</a>. Every week there are great minds from companies like Amazon Alexa, Google, Meta, MIT, NVIDIA, Stability.ai, Tesla, and many more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4nlbVklk0eBDvb-Y.png" /></figure><p>The following are the notes from the live session. Feel free to watch the video and follow along for the full context.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FqUfZruIKwtc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DqUfZruIKwtc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqUfZruIKwtc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/40201c80ddcd2a217ea0572f479e87a9/href">https://medium.com/media/40201c80ddcd2a217ea0572f479e87a9/href</a></iframe><h3>What are we building?</h3><p>Today we will be building a Question-Answering system using Mamba as the base LLM.</p><pre>Q: What is the capital of Norway?<br>A: Oslo</pre><p>This topic is close to home for me, as I worked many years on question answering for a small startup called AlchemyAPI that eventually got acquired into IBM Watson. Systems like IBM Watson had many hand crafted features to be able to answer Jeopardy Questions. At the end of the day, Watson was just one giant logistic regression trained on top of hand engineering features.</p><p>Today, these LLMs abstract away all of these features in their parameters, so I am excited to see how well it does without all the manual writing of feature extractors.</p><p>I haven’t played with QA systems in years, so if you are ready, buckle up and join me on this journey to see how well a model like Mamba solves the problem.</p><h3>Pre-Trained Models</h3><p>Mamba in theory should be really well suited for the QA problem. Processing large context windows to extract an answer is a key component in building a system that can answer questions.</p><p>Before we get ahead of ourselves, let’s start simple and kick around the models that were released with the paper. There are a variety of pre-trained language models that were trained on the Pile dataset, all with different sizes.</p><p>The raw language models can be found on linked to on the GitHub repository.</p><p><a href="https://github.com/state-spaces/mamba?ref=blog.oxen.ai">https://github.com/state-spaces/mamba</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/0*zRl43491qXsUYpD1.png" /></figure><h3>Start Smol</h3><p>For this practical session, I want to see what sort of bang for our buck we can get with the smallest model state-spaces/mamba-130m. The larger models in theory encode more hidden within their parameters, but they require you to have a large GPU and are slower to train.</p><p>Looking at nvidia-smi while training different size models, the largest I was able to successfully train was the state-spaces/mamba-790m model, but this one takes longer to train in general, and I only had a few days to run experiments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oskkCClCyFqQyRbT.png" /></figure><p>During training it seemed that sequence length mattered a lot, so while Mamba in theory has the nice property of scaling to sequence length of 1 million, in practice I was not able to train on very large sequence lengths given my 24GB GPU.</p><p>If you are GPU-poor like me, follow along and let’s milk the 130M model for all it’s worth.</p><h3>The Code</h3><p>Today we have a lot of code to cover, so I will be doing less copy-paste, and more running live so that we can see how the models behave.</p><p>All the code can be found here, and the dependencies can be installed with the requirements.txt</p><p>Note: This code does require an NVIDIA GPU with CUDA installed to get up and running. If you are having problems with install, consult our Getting Started Appendix for tips I found useful to get everything running on the GPU.</p><h3>Prompt Engineering</h3><p>One of the many benefits of this large pre-training step, as discovered in the early GPT papers, was that we can prompt the model in different ways to get a variety of behaviors. This is talked about at length in the paper “Language Models are Unsupervised Multitask Learners”.</p><p>To learn more about the basics of prompting and why it is affective, check out our Arxiv Dive on the topic.</p><p>To see it in action, let’s start by prompting the raw language model. The following is a quick command line utility to test out the raw model.</p><p>This simplest form of interacting with this model is simply a while loop that prompts you for input. I hard coded a prompt in the loop to get us up and running.</p><p>The prompt</p><pre>You are trivia bot. Answer the following trivia question. {user_message}</pre><p>prompt_mamba.py</p><pre>import torch<br>from transformers import AutoTokenizer<br>from mamba_ssm.models.mixer_seq_simple import MambaLMHeadModel<br>import sys<br><br># Validate CLI params<br>if len(sys.argv) != 2:<br>    print(&quot;Usage: python train.py state-spaces/mamba-130m&quot;)<br>    exit()<br><br># Take in the model you want to train<br>model_name = sys.argv[1]<br><br># Choose a tokenizer<br>tokenizer = AutoTokenizer.from_pretrained(&quot;EleutherAI/gpt-neox-20b&quot;)<br>tokenizer.eos_token = &quot;&lt;|endoftext|&gt;&quot;<br>tokenizer.pad_token = tokenizer.eos_token<br><br># Instantiate the MambaLMHeadModel from the state-spaces/mamba GitHub repo<br># https://github.com/state-spaces/mamba/blob/main/mamba_ssm/models/mixer_seq_simple.py#L173<br>model = MambaLMHeadModel.from_pretrained(model_name, device=&quot;cuda&quot;, dtype=torch.float16)<br><br>while True:<br>    # Take the user input from the command line<br>    user_message = input(&quot;\n&gt; &quot;)<br><br>    # Create a prompt<br>    prompt = f&quot;You are trivia bot. Answer the following trivia question.\n{user_message}&quot;<br>    print(prompt)<br><br>    # Encode the prompt into integers and convert to a tensor on the GPU<br>    input_ids = torch.LongTensor([tokenizer.encode(prompt)]).cuda()<br>    print(input_ids)<br>    <br>    # Generate an output sequence of tokens given the input<br>    # &quot;out&quot; will contain the raw token ids as integers<br>    out = model.generate(<br>        input_ids=input_ids,<br>        max_length=128,<br>        eos_token_id=tokenizer.eos_token_id<br>    )<br><br>    # you must use the tokenizer to decode them back into strings<br>    decoded = tokenizer.batch_decode(out)[0]<br>    print(&quot;=&quot;*80)<br><br>    # out returns the whole sequence plus the original<br>    cleaned = decoded.replace(prompt, &quot;&quot;)<br>    print(cleaned)</pre><p>Simply run it by passing in the name of mamba the model you want to run.</p><pre>python prompt_mamba.py state-spaces/mamba-130m</pre><p>You can try this same script any of the models listed here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/0*kyp6s_1AjzqeXDmg.png" /></figure><h3>🐍 Mamba Says What?</h3><p>The problem is — raw pre-trained models are kind of like parrots 🦜. They like to repeat the last thing they said, with only slight hints of intelligence.</p><p>Let’s make our Mamba, more than a parrot. A flying Parramba if you will!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ih2HECWSFsJUNJ0-.png" /></figure><p>Running the script above with a few different prompts, quickly see the raw model is not very helpful on it’s own.</p><pre>You are trivia bot. Answer the following trivia question. &#39;who is the current president?&#39;</pre><pre>&#39;Who is the current president?&#39;<br>&#39;Who is the current president?&#39;<br>&#39;Who is the current president?&#39;<br>&#39;Who is the current president?&#39;<br>&#39;Who is the current president?&#39;<br>&#39;Who is the current president?&#39;<br>&#39;Who is the current president?&#39;<br>&#39;Who is the current president?&#39;<br>&#39;Who is the current president?&#39;<br>&#39;Who is the current president?&#39;<br>&#39;Who is the current president?&#39;<br>&#39;Who is the current president?&#39;<br>&#39;Who is the current president?&#39;</pre><p>Very parrot like. Not very intelligent. What if I format it a little more like Q&amp;A?</p><pre>You are trivia bot. Answer the following trivia question.<br>Q: Who is the president?<br>A:</pre><pre>B: <br>C: <br>D: <br>E: <br>F: <br>G: <br>H: <br>I: <br>J: <br>K: <br>L: <br>M: <br>N: <br>O: <br>P: <br>Q: <br>R: <br>S: <br>T: <br>U: <br>V: <br>W: <br>X: <br>Y: <br>Z: </pre><p>So we know it knows the alphabet at least! But okay. Still not much intelligence yet. Is this just because we are using the 130m model? Or can we squeeze a little more out of our silly parrot-mamba.</p><h3>N-Shot Prompting</h3><p>These raw language models often need a little more than a nudge to start generating coherent text. A technique called N-shot prompting can save us from some of the hard work of training.</p><p>The idea is simple, since our model acts like a parrot, give it a pattern to follow. We can construct a prompt with a few examples and see if it can generalize to the next one. This is a good way to poke at what inherent trivia knowledge our model has.</p><p>Let’s build a prompt that cues the model to follow this pattern:</p><pre>You are a Trivia QA bot. <br>Answer the following question succinctly and accurately.<br><br>Q: What is the capital of France?<br>A: Paris<br><br>Q: Who invented the segway?<br>A: Dean Kamen<br><br>Q: What is the fastest animal?<br>A: Cheetah<br><br>Q: {user_input}<br>A: {model_response}</pre><p>Modifying our code above, we construct a prompt based on a set of N pre-defined examples of trivia questions.</p><pre># ... while True:<br><br>n_shot_prompting = [<br>    {<br>        &quot;question&quot;: &quot;What is the capital of France?&quot;,<br>        &quot;answer&quot;: &quot;Paris&quot;<br>    },<br>    {<br>        &quot;question&quot;: &quot;Who invented the segway?&quot;,<br>        &quot;answer&quot;: &quot;Dean Kamen&quot;<br>    },<br>    {<br>        &quot;question&quot;: &quot;What is the fastest animal?&quot;,<br>        &quot;answer&quot;: &quot;Cheetah&quot;<br>    }<br>]<br><br>prompt = f&quot;You are a Trivia QA bot.\nAnswer the following question succinctly and accurately.&quot;<br>prompt = f&quot;{prompt}\n\n&quot; + &quot;\n\n&quot;.join([f&quot;Q: {p[&#39;question&#39;]}\nA: {p[&#39;answer&#39;]}&quot; for p in n_shot_prompting])<br>prompt = f&quot;{prompt}\n\nQ: {user_message}&quot;<br><br># Debug print to make sure our prompt looks good<br>print(prompt)<br><br># Encode the text to token IDs<br>input_ids = torch.LongTensor([tokenizer.encode(prompt)]).cuda()<br><br># ... continue the generation code</pre><p>Now if we run the same script, we start to see some more intelligent behavior!</p><pre>python prompt_mamba.py state-spaces/mamba-130m <br><br>&gt; What is the capital of Norway?</pre><p>Everything highlighted from “Oslo” on was generated by the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nD93cjGx4XRtLFmJ.png" /></figure><p>This is great! Oslo is indeed the capital of Norway, but we are still getting some parrot-like behavior. We have primed the model to be in question+answer mode, so it continues to generate more questions and answers beyond our initial query.</p><p>A hack to fix this is simply taking the first answer before our double new line as the answer to the user’s query.</p><pre># out returns the whole sequence plus the original<br>cleaned = decoded.replace(prompt, &quot;&quot;)<br><br># the model will just keep generating, so only grab the first one<br>cleaned = cleaned.split(&quot;\n\n&quot;)[0]<br>print(cleaned)</pre><p>We had a the audience try a few more questions live, and got some interesting responses.</p><p>Inspired by <a href="https://interestingengineering.com/science/monty-python-and-the-holy-grail-airspeed-velocity-of-an-unladen-swallow?ref=blog.oxen.ai">Monty Python</a> we asked</p><pre>Q: What is the weight of a laden swallow?<br>A: 1,000 pounds</pre><p>Well… not quite right. A swallow rarely exceeds 2 ounces (about 55 grams) in weight.</p><p>Then we asked about the organ studies professor at Juilliard:</p><pre>Q: who is the organ studies professor at juilliard?<br>A: John H. S. Lewis</pre><p>Swing and a miss. The correct answer is Paul Jacobs. Not sure who this fictional John H. S. Lewis character is.</p><p>Then we asked some basic math, but I had a typo that I left in for fun. The trailing “ actually threw off the model a lot.</p><pre>Q: What is 1+1?&quot;<br>A: 1+1 = 1</pre><p>When corrected, it finally got a correct answer for the crowd 🎉</p><pre>Q: What is 1+1?<br>A: 1+1 = 2</pre><p>It’s all well and fine to kick the tires one prompt at a time, but to get a real sense of how much the model knows, let’s run it on a larger dataset.</p><h3>Evaluation</h3><p>A good test of the knowledge baked into our model is how well it can answer Trivia Questions. A common benchmark for Trivia is called <a href="https://rajpurkar.github.io/SQuAD-explorer/?ref=blog.oxen.ai">SQuAD</a> (The Stanford Question Answering Dataset). This dataset consists of questions, answers and context to back up the answer.</p><p>I put together a cleaned version of the training dataset here:</p><p>Then I created a subset of the eval set that was 1000 random examples.</p><p>The reason for not including the full 10.6k validation examples was purely time constraints (we do one of these a week and I only have one GPU 😅). 1000 random samples is usually enough to get an idea of how well a model is performing.</p><p>First grab the data from <a href="http://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a> so we are evaluating on the same set.</p><pre>oxen clone https://hub.oxen.ai/ox/Mamba-Fine-Tune</pre><p>Let’s write a script to iterate over this line delimited json and run our 130m model on it with N-shot prompting to see how well it performs. We will write all the results to a jsonl file we can refer back to later for debugging.</p><p>eval_n_shot_mamba.py</p><pre>import torch<br>from transformers import AutoTokenizer, AutoModelForCausalLM<br>from mamba_ssm.models.mixer_seq_simple import MambaLMHeadModel<br>import sys<br>import json<br>import pandas as pd<br>import time<br>from tqdm import tqdm<br><br>def run_mamba(model, question):<br>    n_shot_prompting = [<br>        {<br>            &quot;question&quot;: &quot;What is the capital of France?&quot;,<br>            &quot;answer&quot;: &quot;Paris&quot;<br>        },<br>        {<br>            &quot;question&quot;: &quot;Who invented the segway?&quot;,<br>            &quot;answer&quot;: &quot;Dean Kamen&quot;<br>        },<br>        {<br>            &quot;question&quot;: &quot;What is the fastest animal?&quot;,<br>            &quot;answer&quot;: &quot;Cheetah&quot;<br>        }<br>    ]<br><br>    text = f&quot;You are a Trivia QA bot.\nAnswer the following question succinctly and accurately.&quot;<br>    text = f&quot;{text}\n\n&quot; + &quot;\n\n&quot;.join([f&quot;Q: {p[&#39;question&#39;]}\nA: {p[&#39;answer&#39;]}&quot; for p in n_shot_prompting])<br>    text = f&quot;{text}\n\nQ: {question}\nA:&quot;<br>    # print(text)<br>    input_ids = torch.LongTensor([tokenizer.encode(text)]).cuda()<br>    num_tokens = input_ids.shape[1]<br>    # print(input_ids)<br>    <br>    out = model.generate(<br>        input_ids=input_ids,<br>        max_length=128,<br>        eos_token_id=tokenizer.eos_token_id<br>    )<br><br>    # print(out)<br>    decoded = tokenizer.batch_decode(out)[0]<br>    # print(&quot;=&quot;*80)<br>    # print(decoded)<br>    <br>    # out returns the whole sequence plus the original<br>    cleaned = decoded.replace(text, &quot;&quot;)<br>    <br>    # the model will just keep generating, so only grab the first one<br>    answer = cleaned.split(&quot;\n\n&quot;)[0].strip()<br>    # print(answer)<br>    return answer, num_tokens<br><br>def write_results(results, output_file):<br>    df = pd.DataFrame(results)<br>    df = df[[&quot;idx&quot;, &quot;question&quot;, &quot;answer&quot;, &quot;guess&quot;, &quot;is_correct&quot;, &quot;time&quot;, &quot;num_tokens&quot;, &quot;tokens_per_sec&quot;]]<br><br>    print(f&quot;Writing {output_file}&quot;)<br>    df.to_json(output_file, orient=&quot;records&quot;, lines=True)<br><br>model = sys.argv[1]<br>dataset = sys.argv[2]<br>output_file = sys.argv[3]<br>tokenizer = AutoTokenizer.from_pretrained(&quot;EleutherAI/gpt-neox-20b&quot;)<br>tokenizer.eos_token = &quot;&lt;|endoftext|&gt;&quot;<br>tokenizer.pad_token = tokenizer.eos_token<br><br>model = MambaLMHeadModel.from_pretrained(model, device=&quot;cuda&quot;, dtype=torch.float16)<br><br>results = []<br>with open(dataset) as f:<br>    all_data = []<br>    for line in tqdm(f):<br>        data = json.loads(line)<br>        all_data.append(data)<br><br>    total_qs = len(all_data)<br>    for i, data in enumerate(all_data):<br>        start_time = time.time()<br><br>        # print(data)<br>        question = data[&quot;prompt&quot;]<br>        answer = data[&quot;response&quot;]<br>        guess, num_tokens = run_mamba(model, question)<br>        end_time = time.time()<br>        is_correct = (answer.strip().lower() == guess.strip().lower())<br>        print(f&quot;Question {i}/{total_qs}&quot;)<br>        print(f&quot;num tokens: {num_tokens}&quot;)<br>        print(f&quot;Q: {question}&quot;)<br>        print(f&quot;A: {answer}&quot;)<br>        print(f&quot;?: {guess}&quot;)<br>        if is_correct:<br>            print(f&quot;✅&quot;)<br>        else:<br>            print(f&quot;❌&quot;)<br>        print(&quot;=&quot;*80)<br>        sys.stdout.flush()<br>        num_seconds = end_time - start_time<br>        tkps = num_tokens / num_seconds<br>        result = {<br>            &quot;idx&quot;: i,<br>            &quot;question&quot;: question,<br>            &quot;answer&quot;: answer,<br>            &quot;guess&quot;: guess,<br>            &quot;is_correct&quot;: is_correct,<br>            &quot;time&quot;: num_seconds,<br>            &quot;num_tokens&quot;: num_tokens,<br>            &quot;tokens_per_sec&quot;: tkps<br>        }<br>        results.append(result)<br><br>        if len(results) % 20 == 0:<br>            write_results(results, output_file)<br><br>write_results(results, output_file)</pre><p>Although the 130m model with n-shot prompting did well on a few example questions, it did terrible on 1,000 random sampled questions from the SQuAD eval set. It only got 5 of them right or 0.5% accuracy.</p><p>To quickly aggregate the “is_correct” column we can use the oxen CLI.</p><pre>oxen df data/Mamba-Fine-Tune/results/results.jsonl --sql &quot;SELECT is_correct, COUNT(*) FROM df GROUP BY is_correct;&quot;</pre><p>Looking at the output logs more closer, we do not do very well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/0*NgyLmRpi7v4ezQTv.png" /></figure><p>It does answer the right types of things, but the answers are not correct.</p><p>The good news is the throughput of the model is pretty high! It processes on average anywhere from 200–300 tokens per second.</p><p>I tried the 2.8b model and it was slightly better on the task, getting 75 questions right, but 7.5% accuracy is still not that impressive.</p><pre>python eval_n_shot_mamba.py state-spaces/mamba-2.8b-slimpj data/Mamba-Fine-Tune/squad_val_1k.jsonl data/Mamba-Fine-Tune/results/results.jsonl</pre><p>I put the full results set for this experiment in Oxen.ai if anyone want to take a look.</p><h3>Question Answering Requires Context</h3><p>These questions are much harder than basic trivia, but if you look at the questions closely, some of them also require some context to be able to fully answer.</p><p>For example:</p><p><em>“What hotel did the Panther’s stay at?”</em></p><p>How would one be able to answer this question without knowing the context of which Panther’s and at what point in time? Luckily the dataset comes with context to help answer the question.</p><p><em>“The Panthers used the San Jose State practice facility and stayed at the San Jose Marriott. The Broncos practiced at Stanford University and stayed at the Santa Clara Marriott.”</em></p><p>With this context, we are now able to answer the question.</p><p>While we can answer some easy Trivia Questions straight from the model parameters, in real life the questions we want to answer probably exist in some document somewhere. Let’s change the model to extract an answer from context, rather than spit it out from it’s pre-trained knowledge.</p><h3>Question Answering as Information Extraction</h3><p>In general, it is better practice to cite sources than to pull a random fact out of a hat. When a language model answers a question purely from it’s parameters, there is no evidence to back it up. The information could be out of date or simply a convincing hallucination.</p><p>The problem is…we are not served sentences that answer the question on a silver platter. This would be a pretty straight forward problem if we were.</p><p>First you have to go retrieve relevant sentences, then and only then can you extract the correct answer. Although this is a little more work than simply spitting out the answer, in the end it is worth it to have a source you can point back to as evidence for why the answer is correct.</p><p>Question: <em>What hotel did the Panther’s stay at?</em></p><p>Candidate Passages:</p><ul><li>The Carolina Panthers are a professional American football team based in Charlotte, North Carolina. The Panthers compete in the National Football League (NFL), as a member club of the league’s National Football Conference (NFC) South division.</li><li>The Panthers used the San Jose State practice facility and stayed at the San Jose Marriott. The Broncos practiced at Stanford University and stayed at the Santa Clara Marriott.</li><li>The Panthers, along with the Jacksonville Jaguars, began play in the 1995 NFL season as expansion teams. They have played in Charlotte since 1996, winning six division titles and two NFC Championships. The Panthers were the first NFL franchise based in the Carolinas and the second professional sports team based in Charlotte, the first being the NBA’s Charlotte Hornets.</li></ul><p>If you are thinking <a href="https://blog.oxen.ai/arxiv-dives-rag/">RAG</a> will help solve this problem, you are right, we will cover that in the next <a href="https://lu.ma/practicalml?ref=blog.oxen.ai">practical dive</a>, but there are more problems we have to address first.</p><h3>When to say “I don’t know”</h3><p>Even if we were served relevant sentences on a silver platter, not every single one of them is guaranteed to have an answer to the question. In fact, the vast majority of sentences probably <em>do not</em> answer the question.</p><p>Ideally we can train a system to — given a list of sentences, say “I don’t know” when the answer is not embedded, and give the answer when it is.</p><p>I have already pre-trained a mamba model to do this to give you a sense of what this would look like in practice.</p><p>You can grab the pre-trained model on hugging face.</p><pre>python prompt_mamba_with_context.py Oxen-AI/mamba-130m-context</pre><p>This model now can take the paragraphs from above and reply “I don’t know” to the ones who do not have the answer embedded, and properly extract the answer for the one that does.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*08-bOZovIs79NEaA.png" /></figure><p><em>Knowing when you do not know</em> is one of the most important problems in machine learning in the real world. It is always a balance of precision vs recall of how often you answer, vs how many times you answer correctly.</p><h3>Training Mamba for Information Extraction</h3><p>Now that we know how to re-formulate the problem, let’s try to train mamba for information extraction.</p><p>Let’s write a data loader that takes in the squad_train.jsonl and generates positive and negative examples. The data loader is probably the most important part of the training script, the rest is pretty boiler plate.</p><pre>import torch<br>import json<br>import random<br><br>from tqdm import tqdm<br>from torch.utils.data import Dataset<br><br>class SFTDataset(Dataset):<br>    def __init__(self, data_path, tokenizer):<br>        super(SFTDataset, self).__init__()<br>        data = []<br>        print(f&quot;Reading in data from file: {data_path}&quot;)<br>        with open(data_path, &quot;r&quot;) as file:<br>            for line in file:  <br>                try:<br>                    data.append(json.loads(line))<br>                except Exception as e:<br>                    print(&quot;json processing exception&quot;, e)<br>                    continue<br><br>        print(f&quot;Got {len(data)} examples, preprocess...&quot;)<br>        data_dict = self.preprocess(data, tokenizer)<br><br>        self.input_ids = data_dict[&quot;input_ids&quot;]<br>        self.labels = data_dict[&quot;labels&quot;]<br><br>    def __len__(self):<br>        return len(self.input_ids)<br><br>    def __getitem__(self, i):<br>        return dict(input_ids=self.input_ids[i], labels=self.labels[i])<br>    <br>    def preprocess(self, examples, tokenizer):<br>        &quot;&quot;&quot;<br>        Preprocess the data by tokenizing.<br>        &quot;&quot;&quot;<br>        all_input_ids = []<br><br>        print(&quot;Tokenizing dataset...&quot;)<br>        for ex in tqdm(examples):<br>            # Add a positive example<br>            text = f&quot;{ex[&#39;context&#39;]}\n\nQ: {ex[&#39;prompt&#39;]}\nA: {ex[&#39;response&#39;]}\n&quot;<br>            tokenized = tokenizer.encode(text)<br>            all_input_ids.append(torch.LongTensor(tokenized))<br>            <br>            # Generate a negative example<br>            random_ex = random.choice(examples)<br>            text = f&quot;{random_ex[&#39;context&#39;]}\n\nQ: {ex[&#39;prompt&#39;]}\nA: I don&#39;t know.\n&quot;<br>            tokenized = tokenizer.encode(text)<br>            all_input_ids.append(torch.LongTensor(tokenized))<br><br>        random.shuffle(all_input_ids)<br><br>        return dict(input_ids=all_input_ids, labels=all_input_ids)</pre><p>Notice how we grab a positive example and format it.</p><pre>The Panthers used the San Jose State practice facility and stayed at the San Jose Marriott.<br>The Broncos practiced at Stanford University and stayed at the Santa Clara Marriott.<br><br>Q: What hotel did the Panther’s stay at?<br>A: San Jose Marriott</pre><p>Then we generate a negative example by synthesizing it from a random example in the dataset.</p><pre># Generate a negative example<br>random_ex = random.choice(examples)<br>text = f&quot;{random_ex[&#39;context&#39;]}\n\nQ: {ex[&#39;prompt&#39;]}\nA: I don&#39;t know.\n&quot;<br>tokenized = tokenizer.encode(text)<br>all_input_ids.append(torch.LongTensor(tokenized))</pre><p>The negative examples will look something like:</p><pre>Some irrelevant text...<br><br>Q: What hotel did the Panther’s stay at?<br>A: I don&#39;t know</pre><p>We are relying on the laws of probability here that a random sentence from the training set does not contain the answer to the question.</p><p>The full training script can be found here:</p><p>Kick it off by passing in the base model, the path to the dataset, and the path to the output.</p><pre>python train_mamba_with_context.py --model state-spaces/mamba-130m \<br>  --data_path data/Mamba-Fine-Tune/squad_train.jsonl \<br>  --output models/mamba-130m-context \<br>  --num_epochs 10</pre><p>I let this train overnight for 10 epochs, it probably took around 8 hours on my 24GB GPU from Lambda Labs.</p><p>Let’s evaluate the model and see how well it does now given the context.</p><pre>python eval_mamba_with_context.py models/mamba-130m-context data/Mamba-Fine-Tune/squad_val_1k.jsonl data/Mamba-Fine-Tune/results_context.jsonl</pre><p>Letting this run to completion, we now outperform the 2.8b model and got to 12% accuracy!</p><p>This may not seem very high, and I agree, it is not. State of the art models get over 90% accuracy these days, which is even better than human performance of 86%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/0*6w5J47XYMXlK-MK0.png" /></figure><h3>Why such low accuracy?</h3><p>With all the hype around Mamba, why such low accuracy on question answering tasks? To answer this, I revisited the paper to take a look at some of the benchmarks that they cited.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/0*TyZoLAtxb57CWy3n.png" /></figure><p>For one, they did not benchmark against SQuAD, so I have no baseline to compare my model to.</p><p>They did benchmark on a question-answering dataset called PIQA so I decided to look into this dataset a bit.</p><p><a href="https://www.oxen.ai/ox/PIQA">ox/PIQA | Datasets at Oxen.ai</a></p><p>This dataset is actually just a binary classification dataset, so the high numbers make a lot more sense to me in the context of what the task actually is. Guessing randomly on a binary classification task will get you 50% accuracy. The task is: given a goal and two solutions, pick the correct one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1i7H74reWFd_LSvS.png" /></figure><p>My theory is that the SQuAD task is just way harder than the tasks Mamba was originally benchmarked against.</p><p>In general, I would love if researchers not only linked to a grid of numbers, but an actual dataset with the results. Even better if they store them in <a href="https://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*j1ey5ZgSpNfzizr9.png" /></figure><p>We are committed to benchmarking models in our practical dives on real world data. This way we can cut through the noise and hype of models and look at actual results on both the academic datasets and real world problems. Here are all the results from this experimentation:</p><p><a href="https://www.oxen.ai/ox/Mamba-Fine-Tune/dir/main/results?ref=blog.oxen.ai">ox/Mamba-Fine-Tune/results at main - ox/Mamba-Fine-Tune | Datasets at Oxen.ai</a></p><h3>Conclusion</h3><p>Thanks for diving in with us! The code with be posted on GitHub and the data on <a href="https://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a>.</p><p><a href="https://github.com/Oxen-AI/mamba-dive?ref=blog.oxen.ai">GitHub - Oxen-AI/mamba-dive: This is the code that went into our practical dive using mamba as information extraction</a></p><p>Mamba seems promising in terms of speed of training and inference, but I am yet to be convinced of it’s prowess on a real world task. It did well anecdotally on the question answering task with context, but when it came to actually benchmarking, it only got 12% accuracy. It was too computationally expensive for me to train long sequence lengths or with a larger model on the same dataset.</p><p><a href="https://www.oxen.ai/ox/Mamba-Fine-Tune/?ref=blog.oxen.ai">ox/Mamba-Fine-Tune | Datasets at Oxen.ai</a></p><h3>Next Up</h3><p>Thanks for sticking around this far! To find out what paper we are covering next and join the discussion at large, checkout our Discord:</p><p><a href="https://discord.com/invite/s3tBEn7Ptg?ref=blog.oxen.ai">Join the oxen Discord Server!</a></p><p>If you enjoyed this dive, please join us next week!</p><p><a href="https://lu.ma/oxenbookclub?ref=blog.oxen.ai">Arxiv Dives with Oxen.ai 📚🤿🐂 · Zoom · Luma</a></p><p>All the past dives can be found on the blog.</p><p><a href="https://blog.oxen.ai/tag/arxiv-dives/">Arxiv Dives - Oxen.ai</a></p><p>The live sessions are posted on YouTube if you want to watch at your own leisure.</p><p><a href="https://www.youtube.com/channel/UCIYC0IZ4fKmXaeGl95WIf5Q?ref=blog.oxen.ai">Oxen</a></p><p>Best &amp; Moo,</p><p>~ The herd at <a href="https://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a></p><h3>Who is Oxen.ai?</h3><p><a href="https://oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a> is an <a href="https://github.com/Oxen-AI/oxen-release?ref=blog.oxen.ai">open source project</a> aimed at solving some of the challenges with iterating on and curating machine learning datasets. At its core Oxen is a lightning fast data version control tool optimized for large unstructured datasets. We are currently working on collaboration workflows to enable the high quality, curated public and private <a href="https://www.oxen.ai/explore?ref=blog.oxen.ai">data repositories</a> to advance the field of AI, while keeping all the data accessible and auditable.</p><p>If you would like to learn more, <a href="https://github.com/Oxen-AI/oxen-release?ref=blog.oxen.ai">star us on GitHub</a> or head to <a href="https://www.oxen.ai/?ref=blog.oxen.ai">Oxen.ai</a> and create an account.</p><p><a href="https://github.com/Oxen-AI/oxen-release?ref=blog.oxen.ai">https://github.com/Oxen-AI/oxen-release</a></p><h3>Getting Started Appendix</h3><p>All of this work was done on a Machine in Lambda Labs.</p><p>You need to make sure your pytorch version matches cuda version and build the deps from scratch.</p><p>To get the cuda version:</p><pre>nvcc --version</pre><p>Then install the appropriate pytorch build. In my case my nvcc version said 11.8, so I needed to install the pytorch cu118 version for any of the other mamba dependencies to compile.</p><pre>pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118</pre><p><em>Originally published at </em><a href="https://blog.oxen.ai/practical-ml-dive-how-to-train-mamba-for-question-answering/"><em>https://blog.oxen.ai</em></a><em> on December 21, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14982ef4ea66" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>