<?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 Devon Slonaker on Medium]]></title>
        <description><![CDATA[Stories by Devon Slonaker on Medium]]></description>
        <link>https://medium.com/@devonslonaker?source=rss-1525926828b3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HNCLOoGt09tKuBogAZecGQ.jpeg</url>
            <title>Stories by Devon Slonaker on Medium</title>
            <link>https://medium.com/@devonslonaker?source=rss-1525926828b3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:40:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@devonslonaker/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[Why the U.S. is Falling so Far Behind in AI]]></title>
            <link>https://medium.com/ai-lab-c4ai/why-the-u-s-is-falling-so-far-behind-in-ai-95196bd6b666?source=rss-1525926828b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/95196bd6b666</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Devon Slonaker]]></dc:creator>
            <pubDate>Fri, 31 Jan 2025 03:08:43 GMT</pubDate>
            <atom:updated>2025-02-19T20:52:13.438Z</atom:updated>
            <content:encoded><![CDATA[<p>DeepSeek R1 is the latest household AI name of the year. Made supposedly by some guys in a hedge fund who had some spare crypto-mining GPUs from a few years ago, $6 million, and some time to work on a side-project, R1 came into existence. DeepSeek’s R1 671b model is a highly advanced ChatGPT o1 competitor model that is free, open-weights under the MIT license, and the full flagship version of the model can be run by anyone with powerful enough hardware. Even the tiny 1.5b distilled version of R1 can be run locally on your phone with zero internet connection. The influence of R1 is so vast, Nvidia dropped nearly $600 billion in market value in a single day because of how seemingly nonchalant it was to make R1. Why is DeepSeek so influential, why are major AI companies in a panic, and why is the U.S. falling so far behind in this new AI-era Space Race?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*L738BX-FO7qpwl1OsWkHtw.png" /><figcaption>The infamous “side project” tweet. Source: <a href="https://x.com/hxiao/status/1882099204044239007">https://x.com/hxiao/status/1882099204044239007</a></figcaption></figure><p>For a while now, many people have been extremely fearful of AI stealing their data to further train their models. For a long time, OpenAI, Anthropic, Google, Microsoft, and Meta have been massive players in the AI world, creating numerous foundation models for people to use. These companies, with the exception of Meta and their Llama models, have long since locked their massive state of the art models such as ChatGPT o1, Claude 3.5 Sonnet, Gemini 2.0 Advanced, and Copilot behind APIs, apps, websites, and paywalls. With these massive, really performant models, people have the urge to want to use them, but do not want to keep giving companies like Google and Microsoft their sensitive information to then put into future AI models (especially with the already poor reputation these companies have surrounding data privacy). Meta themselves outright states in their Privacy Center that if you use their platform (or even if you don’t use their platform), they are collecting your data to train future models. Don’t believe me? Have a look for yourself!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*OFzWFLFJJh427ggJPK3yzQ.png" /><figcaption>Meta’s AI training policy. Source: <a href="https://www.facebook.com/privacy/genai/">https://www.facebook.com/privacy/genai/</a></figcaption></figure><p>You can find similar things in OpenAI’s policies as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*RYgvkLzHLZEsY0Oot-ob1Q.png" /><figcaption>OpenAI data usage. Source: <a href="https://help.openai.com/en/articles/5722486-how-your-data-is-used-to-improve-model-performance">https://help.openai.com/en/articles/5722486-how-your-data-is-used-to-improve-model-performance</a></figcaption></figure><p>It is clear that the fear of many people regarding the data mining and stealing of personal information is real and valid. The tool of AI itself has even gotten this stigma as some big-brother dystopian technology because of how prevalent and omniscient it seems to be to the average person because of just the vast amounts of data scraped and mined used to train these models.</p><p>This then transitions into the question of why then has DeepSeek become so influential and a household name overnight? “Surely, DeepSeek also steals your data through their app and website,” you may be exclaiming. “Why would I want to use them?” It’s because DeepSeek gives you the option to not use their app and website and to run their flagship ChatGPT o1 competitor foundation model locally on your own hardware.</p><p>DeepSeek claims in a benchmark graph that they are able to compete with the absolute monster that is ChatGPT o1, and even beat OpenAI’s o1-mini model in numerous benchmarks. On top of these great advancements, DeepSeek does not lock their flagship foundation model behind any APIs, websites, apps, and paywalls like other AI companies. Sure, you can access DeepSeek R1 through APIs, websites, and apps, but that’s not your only conduit. The big appeal of DeepSeek R1 is that you can download it locally to your system and use it without internet. Additionally, DeepSeek has made R1 extremely accessible, having distilled variants as 1.5b, 7b, 8b, 14b, 32b, and 70b sizes. So you don’t even need to have a massive data center to run these models. You can even run the 1.5b distilled version of DeepSeek R1 on your phone, locally, without internet today. There is a size of DeepSeek R1 for anyone, for any machine, and for any use case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VfsEToYexITwZGhL.jpg" /><figcaption>DeepSeek R1 benchmark results. Source: <a href="https://huggingface.co/deepseek-ai/DeepSeek-R1">https://huggingface.co/deepseek-ai/DeepSeek-R1</a></figcaption></figure><p>Another big appeal of DeepSeek R1 is that to most people, $0/month is cheaper than $20/month or even $200/month. In order to use ChatGPT o1, it costs as much as $20/month. If you were using OpenAI’s o1-Pro model, you would be forking over $200/month. Why would anyone do that when they can just load up LM Studio, OpenWebUI, or Ollama and chat away with any of the DeepSeek R1 variants locally on their machine for free without fear of having their data stolen?</p><p>Researchers are also infatuated with DeepSeek R1. OpenAI makes it especially difficult to scrape out the actual thinking process of its o1 models, as to not allow anyone to train their own models to think like o1 and to have competitor models like, well, DeepSeek R1. OpenAI has gone so far as to flag certain prompts asking o1 to reveal its thinking process as a violation of the usage policy of OpenAI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*8JhNUOOEFhm26-O_5DniGg.png" /><figcaption>A ChatGPT o1 prompt being flagged for asking to reveal the thinking process.</figcaption></figure><p>On the flip side of things, DeepSeek has allowed people to see the full thinking process of R1 and to even extract the thinking process through special `&lt;think&gt;` tags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-OyQhmbHzepJStyxz47d0A.png" /><figcaption>A DeepSeek R1 1.5b model prompt showcasing the &lt;think&gt; tags.</figcaption></figure><p>Because DeepSeek R1 is free in both the monetary sense and use-case sense while being more powerful than OpenAI’s o1-mini model, it’s no wonder that people are flocking to try out DeepSeek and even canceling their OpenAI subscriptions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*d50tXCsHTD0cXTgYfbXR1w.png" /><figcaption>Fellow Medium user Dqj announcing the canceling of their OpenAI subscription because of DeepSeek R1. Source: <a href="https://medium.com/@dqj1998/i-canceled-my-subscription-to-chatgpt-after-this-10-minute-test-on-deepseek-r1-cb8dca91ef91">https://medium.com/@dqj1998/i-canceled-my-subscription-to-chatgpt-after-this-10-minute-test-on-deepseek-r1-cb8dca91ef91</a></figcaption></figure><p>With this, many AI companies, namely OpenAI, are now in a panic. As many companies spend tens of millions to even billions of dollars developing new models on the latest and greatest Nvidia hardware, DeepSeek, if they are to be believed, showed that a good and competitive model can be done with older hardware on just a $6 million budget, paving the way of optimism for startups to begin making their own models, threatening the big-tech AI monopoly. Shortly after the time of this writing, OpenAI actually announced the public release of ChatGPT o3-mini, showing they are scrambling to distract the world from the influence of DeepSeek R1, and are desperately attempting to take the spotlight once again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*hfGhuhi_I5gxEwsxvVHqfg.png" /><figcaption>ChatGPT o3-mini announcement. Source: <a href="https://openai.com/index/openai-o3-mini/">https://openai.com/index/openai-o3-mini/</a></figcaption></figure><p>Even with the announcement by President Trump of the $500 billion investment into The Stargate Project involving SoftBank, OpenAI, Oracle, and MGX, the release of DeepSeek R1 sent Nvidia stocks into a free fall and OpenAI into a panic, now claiming that DeepSeek “inappropriately” trained R1 on ChatGPT outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*F912AXicgXl3RT2QUjvmKg.png" /><figcaption>Insight on OpenAI’s inappropriate usage claims. Source: <a href="https://www.axios.com/2025/01/29/openai-deepseek-ai-models-data-training">https://www.axios.com/2025/01/29/openai-deepseek-ai-models-data-training</a></figcaption></figure><p>This statement is quite hypocritical as Microsoft just a few weeks ago released their Phi-4 model along with the model’s technical report deeply highlighting that they utilized GPT-4 as a “teacher” model for Phi-4. Despite training Phi-4 on synthetic data distilled from GPT-4 to make it perform much better than it would otherwise on purely organic data, there was no push-back from OpenAI on this. If I had to guess, it’s because Microsoft is a heavy investor in OpenAI, while DeepSeek is the new kid on the block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*N9M41bUemrL0AVSb8UoxLA.png" /><figcaption>The Phi 4 Technical Report Abstract. Source: <a href="https://arxiv.org/pdf/2412.08905">https://arxiv.org/pdf/2412.08905</a></figcaption></figure><p>It’s also quite interesting that OpenAI is claiming that DeepSeek stole their data to train R1 while OpenAI themselves are facing a lawsuit over training their models on stolen data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*BoITsI9JnyPOaUpQuX9iZA.png" /><figcaption>Article reporting the class-action lawsuit against OpenAI. Source: <a href="https://www.pcmag.com/news/openai-sued-for-using-stolen-data-violating-your-privacy-with-chatgpt">https://www.pcmag.com/news/openai-sued-for-using-stolen-data-violating-your-privacy-with-chatgpt</a></figcaption></figure><p>Many people are now wondering just how are U.S.-based AI companies performing so poorly in comparison to competitors such as DeepSeek? I think the main reason is where the focus of AI currently is, and it’s not on developing models.</p><p>Safe AI, or AI Safety, is a term used to described “practices and principles that help ensure AI technologies are designed and used in a way that benefits humanity and minimizes any potential harm or negative outcomes” (<a href="https://www.ibm.com/think/topics/ai-safety">https://www.ibm.com/think/topics/ai-safety</a>). In simpler terms, this means fine-tuning a model on prompts, questions, answers, and phrases that it can and can not answer. This process is why ChatGPT will not tell you ways in order to harm yourself. While Safe AI is a good topic to be studied in order to ensure that models do not go off the rails and produce genuinely harmful content such as how to harm yourself, Safe AI is being implemented in such a way that it censors too many model outputs, even benign ones. OpenAI will spend upwards of half a year lobotomizing its model to make it aligned with what humans think is morally correct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*MiEJH-1gqqvtqhOuBULEDA.png" /><figcaption>A snippet of OpenAI’s AI Safety article. Source: <a href="https://openai.com/index/our-approach-to-ai-safety/">https://openai.com/index/our-approach-to-ai-safety/</a></figcaption></figure><p>Hundreds of frameworks on how to develop AI models and numerous AI safety standards are being proposed every single day, and this is a hindrance on the development of good AI models as more time is going into developing these frameworks instead of developing AI models. While I am in agreement that models should be trained on basic things such as not telling someone to harm themselves, I think that training it on anything extra, such as modern day political correctness, is harming the U.S. dominance in the AI space as this over-censorship of models adds exceedingly to the time required to develop these models as well as aiding in the degradation of the performance of the model itself. The U.S. did not win the Space Race against the Soviet Union through various organizations telling NASA engineers how they should be building the rocket. We just let the engineers build the rocket.</p><p>OpenAI tested what kind of effects RLHF (Reinforcement Learning with Human Feedback) in the context of output alignment had on the effectiveness of GPT-4 and its confidence levels to answers in their GPT-4 technical report. Before the RLHF alignment on harmful topics, GPT-4 was perfectly confident in nearly all of its answers on the MMLU benchmark. After the RLHF alignment of harmful topics, GPT-4’s confidence on the same MMLU benchmark was all over the place and was no longer confident in really any of its answers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*EUf5Dnxbm2-NlAkeNaJccQ.png" /><figcaption>Snippet from the GPT-4 technical report talking about RLHF alignment. Source: <a href="https://arxiv.org/pdf/2303.08774">https://arxiv.org/pdf/2303.08774</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*UtMxrijLHXs0n7klg12EBg.png" /><figcaption>Graphs showing GPT-4’s confidence levels in MMLU before and after RLHF. Source: <a href="https://arxiv.org/pdf/2303.08774">https://arxiv.org/pdf/2303.08774</a></figcaption></figure><p>Heavily censored models may even perform worse on benchmarks as they may refuse to follow certain commands or answer certain questions required for the benchmark as it may become overly cautious about answering certain benign topics (as discussed in the GPT-4 technical report snippet above), thus performing worse on the benchmark than if it had no RLHF alignment.</p><p>Language models are trained to answer questions, not to not answer questions. So when censorship is introduced, it is being taught to not answer questions which is a conflict of interest in already being trained on answering questions. This can be described as training a model on “green beans are good” and “green beans are bad”. The model does not understand that “green beans are ok” is a valid middle ground option. Models cannot generalize and reason in the sense that humans do. AI models are nothing more than a Wild West of matrix multiplication doing text completion. It’s all math. So training a model on two conflicting topics will not make it better, it will make it confused. This is why we see the censorship of benign topics where the model should have been able to answer.</p><p>On the Open LLM Leaderboard (<a href="https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard#/">https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard</a>) it can be seen that some uncensored models outperform their parent models. Some examples include:</p><p>Mistral’s Mistral 7b Instruct v0.3 model ranks <strong>2048</strong> on the leaderboard.<br>cognitivecomputations/dolphin-2.9.3-mistral-7B-32k ranks <strong>2025</strong> on the leaderboard.</p><p>Meta’s Llama 3.1 8b Instruct ranks <strong>776</strong> on the leaderboard.<br>T145/Llama-3.1-8B-Instruct-Zeus ranks <strong>634</strong> on the leaderboard.</p><p>Alibaba’s Qwen 2.5 72b Instruct ranks <strong>135</strong> in the leaderboard.<br>zetasepic/Qwen2.5-72B-Instruct-abliterated ranks <strong>9</strong> on the leaderboard.</p><p>Now, why am I talking about all of this censorship and RLHF alignment stuff? It’s because DeepSeek’s R1 model seems to just try to be a good model without dwelling too much on censoring everything, despite coming from China where information is heavily censored. I found that it is super easy to jailbreak after some preliminary testing. There is still some basic initial guarding around things like illegal substances, self-harm, and other potentially harmful topics, but with some basic prompt engineering, like with the Grandma Jailbreak, DeepSeek R1’s censorship can be easily bypassed. Being a Chinese model, certain topics pertaining to Chinese history or negative connotations towards the Chinese government are also inherently censored, but DeepSeek R1 does not go entirely out of its way to censor every little thing one tries to do like current ChatGPT models such as o1. For instance, the Grandma Jailbreak used to work on earlier versions of ChatGPT to obtain uncensored results before being patched out in later versions. Using the Grandma Jailbreak to ask ChatGPT o1 things it would censor is still censored by the model, but uncensored results for the same prompt are easily obtainable from DeepSeek R1.</p><p>The leniency of censorship from DeepSeek R1 is possibly where it excels over something ChatGPT o1-mini. I suspect that if DeepSeek R1 had the same level of censorship that o1 and o1-mini do, R1 would most likely fall behind o1-mini in numerous benchmarks instead of being wildly ahead. Conversely, if ChatGPT o1 and o1-mini were more uncensored, I have a feeling they would perform exceedingly better, even more than they already do in various benchmarks.</p><p>Despite the censorship from ChatGPT o1 and DeepSeek R1, DeepSeek R1 still has the upper hand in that it is open-weight. Numerous uncensored and ablated (uncensored) fine-tunes of R1 have already begun showing up on Hugging Face, and I am curious how they will perform in benchmarks compared to their parent model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QI6Lh-5gVcJS2lzsDG0Lfg.png" /><figcaption>Uncensored DeepSeek R1 models on Hugging Face. Source: <a href="https://huggingface.co/models?other=uncensored&amp;sort=trending&amp;search=deepseek-r1">https://huggingface.co/models?other=uncensored&amp;sort=trending&amp;search=deepseek-r1</a></figcaption></figure><p>So how do we fix the issue of censorship mainly in proprietary models like ChatGPT (as open-weight models can be ablated to remove the censorship entirely)? Many believe it is important to censor model outputs for the good of others, but at the same time there is the trade off of time and effectiveness in doing so that has been talked about in the entirety of this section. I believe Meta, IBM, and Google already have solutions to this problem. Llama Guard, Granite Guardian, and ShieldGemma respectively are all “guard” models designed to prevent the input and output of harmful topics. The idea behind these specially designed classification models is that they can be programmatically put at the user input and the model output in a website or an app to prevent harmful outputs from being generated. Not only could the modular nature of these “guard” models save time, money, and effort on training by allowing models to be released in a more uncensored state, but because it is modular, it can just be slapped to any successor model with very little effort, and we could have new ChatGPT releases 6 months earlier, increasing competition in the AI space. At the same time, companies like OpenAI, Anthropic, Microsoft, and Google could use the more raw uncensored models in benchmarks in order to show the true power of their models without completely lobotomizing them and holding them back.</p><p>The conversation does not end here, however. DeepSeek’s open-weights approach and being able to run their models locally on your home system is very appealing to many people. OpenAI used to do this up until GPT-3 and then starting making their models proprietary. I believe that if U.S. AI companies want to have a chance against super competitive open-weight models like DeepSeek R1, they must, at the very least, begin open-weighting older models. Elon Musk has made it a point to open-weight any older Grok models when new ones are released, already open-weighting Grok 1 upon the release of Grok 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*I7kBLNCScm4zBTLDibN9Eg.png" /><figcaption>Elon Musk alludes to open-sourcing Grok 2 amid a potential Grok 3 release. Source: <a href="https://x.com/elonmusk/status/1842248588149117013">https://x.com/elonmusk/status/1842248588149117013</a></figcaption></figure><p>Untrue to its name, there is no excuse as to why a company like OpenAI has still refused to open-weight models like GPT-3, GPT-3.5, and GPT-3.5 Turbo, all of which are no longer accessible on ChatGPT’s website, including under the “More Models” tab. GPT-3 and GPT-3.5 aren’t even available under API access anymore. Instead of letting older models waste away as software e-waste, AI companies should begin open-weighting older models they clearly don’t care about anymore to give back to the community who supports them, and to generate hype which will get them more notice, usage, and funding in the long run.</p><p>DeepSeek has produced a truly formidable model, giving models like ChatGPT o1 a run for its money all while being free, open-weight, and accessible to many different kinds of people on various devices. DeepSeek lives up to what OpenAI once was, and I hope this AI Sputnik pulled off by DeepSeek scares many AI companies awake and makes them realize that if they want to compete, they must focus on creating genuinely good models with the near limitless funding and hardware power they have at their disposal instead of sub-par models that are easily outdone by some bored hedge fund guys with some leftover GPUs and spare pocket change.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95196bd6b666" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-lab-c4ai/why-the-u-s-is-falling-so-far-behind-in-ai-95196bd6b666">Why the U.S. is Falling so Far Behind in AI</a> was originally published in <a href="https://medium.com/ai-lab-c4ai">AI Lab @ C4AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Make An Embedding Model]]></title>
            <link>https://medium.com/ai-lab-c4ai/how-to-make-an-embedding-model-6e8834ce6c05?source=rss-1525926828b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e8834ce6c05</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[embedding-model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Devon Slonaker]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 20:13:34 GMT</pubDate>
            <atom:updated>2024-11-07T20:13:34.968Z</atom:updated>
            <content:encoded><![CDATA[<h3>What Is An Embedding Model?</h3><p>An embedding model is a neural network that takes an object (word, sentence, phrase, image, video, file, etc) and turns it into an embedding, or a condensed vector format. Or in simpler terms, an embedding model represents an object as a point on a plane or map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rt7AfZuyNXp6TqN4y_0vGQ.png" /><figcaption>A ChatGPT representation of an embedding model</figcaption></figure><h3>Why Would You Need An Embedding Model?</h3><p>Embedding models are useful as they can be used for getting embeddings of various objects and storing them in a vector database. A vector database is useful for two main reasons:</p><ol><li>Finding similarities between objects</li><li>Getting an approximate result from a query</li></ol><p>An embedding model naturally embeds similar things closer to one another, and dissimilar things further from one another, typically based on semantic context. For example, “cat” and “kitten” may be very close, but “cat” and “mitten” may be very far from one another.</p><p>In the context of a vector database, someone may query “baby cat”, and with the context of knowing that that a baby cat typically refers to a kitten, the embedding of “baby cat” will be very close to the embedding of “kitten”, and “kitten” will be returned to the user.</p><h3>Why Would You Want To Make Your Own Embedding Model?</h3><p>An embedding model only embeds on the structure it is trained on. For example, an embedding model may embed semantically, similar to the “cat” and “kitten” example. An embedding model may also embed on phonetics, so rhyming for example. Words that sound similar will be closer together in this form of model, so “cat” and “kitten” will no longer be close to one another, but “kitten” and “mitten” will. So a single embedding model is not a “jack of all trades” sort of deal. The model embeds how it was trained to embed, and if you want things to be embedded a different way, you either need to go and find a model that does it for you, or make one tailored to your needs.</p><h3>Overview of Making Your Own Embedding Model</h3><p>In this example, we will be making a very simple and high-level implementation of a text-based embedding model. At a high-level, an embedding model is a very simple neural network that can boil down to just two layers; your input layer and your output layer (your vocabulary layer, and your embedding layer).</p><p>In our example, we will be using Python and we will be using the PyTorch library for our neural network based tasks. Training an embedding model to embed text may take a lot of memory and compute power depending on your corpus size (your collection of texts or documents). It is recommended that you be aware of your system resource usage before embarking on this endeavor. I recommend closing any unused tabs, unused programs, and closing any background tasks that would be a hindrance to your computer’s memory.</p><h3>Preparing The Proper Prerequisites</h3><h4>Python</h4><p>To begin, PyTorch requires at least Python version 3.8. If you do not currently have Python installed, you can install the latest version from the following link: <a href="https://www.python.org/downloads/">https://www.python.org/downloads/</a></p><p><em>If you are using a Linux-based operating system, please refer to your specific distribution’s package installer for installing Python.</em></p><p>If you already have Python installed, check your version with the following command in your command prompt/terminal:</p><pre>python3 --version</pre><p>If you currently do not have Python 3.8 or later, please refer to the download instructions above.</p><h4>Making a Python Virtual Environment</h4><p>At this point, make a new Python project in either by manually creating a virtual environment or using an IDE such as PyCharm to make one. Virtual environments are important as they allow us to isolate projects from one another so there is no interference between them.</p><p>If you are a beginner to Python, PyCharm is a very simple IDE that allows for easy ways to use Python, to use virtual environments, and to install packages easily with Pip through a built-in terminal.</p><p>In your virtual environment, ensure you have Pip and make sure it is up to date to the latest version by entering the following command:</p><pre>python3 -m pip install --upgrade pip</pre><p>Depending on your hardware, there are various versions of PyTorch you can install. There are versions for CPU support, CUDA (Nvidia) support, and ROCm (AMD) support. If you are unsure as to what hardware you have, simply install PyTorch using the CPU installation command.</p><h4>CPU Only PyTorch Installation</h4><p>If you do not have a CUDA or ROCm capable graphics card, install PyTorch that only supports your CPU by running the following command:</p><pre>pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu</pre><h4>CUDA PyTorch Installation</h4><p>If you have an Nvidia card, check your specific CUDA version by opening a command prompt or terminal window and typing the following:</p><pre>nvcc --version</pre><p>To install PyTorch with Nvidia CUDA support, enter in the following command (replacing the CUDA version with your specific CUDA version).</p><p>At the time of this article, PyTorch for CUDA supports CUDA versions 11.8, 12.1, and 12.4. For example, if you have CUDA 12.4, you will enter in the following command:</p><pre>pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124</pre><p>If you are unsure about what command to run for your specific CUDA version, please refer to the PyTorch installation guide here: <a href="https://pytorch.org/get-started/locally/">https://pytorch.org/get-started/locally/</a></p><h4>ROCm PyTorch Installation</h4><p>To install PyTorch with AMD ROCm support, please ensure you have ROCm version 6.1. You can check your ROCm version with the following command in a terminal:</p><pre>rocminfo</pre><p>To install PyTorch for ROCm, you will enter the following command:</p><pre>pip3 install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm6.2</pre><p>As a note, the PyTorch version available for ROCm 6.2 is only available on the Nightly (testing) branch, meaning you may encounter some issues. This is just something to keep in mind if things happen to break. If you are unsure that you want to use the Nightly branch, please install the CPU version of PyTorch instead which is through the Stable branch, or downgrade to ROCm 6.1 and download the PyTorch for ROCm 6.1 which is also through the Stable branch.</p><p>Please refer to the following PyTorch installation link to check for any updates regarding any ROCm PyTorch updates: <a href="https://pytorch.org/get-started/locally/">https://pytorch.org/get-started/locally/</a></p><h3>Imports</h3><p>For this embedding model example, we will be importing a few torch libraries, including torch itself, torch.nn (neural networks), and torch.optim (the optimizer that helps the model learn). We will also be importing sys and math for later when we query the vocabulary used in our embedding model as sort of a pseudo vector database.</p><p>The imports are as follows:</p><pre># PyTorch and other imports<br>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>import sys<br>import math</pre><h3>Pulling In A Document With Data</h3><p>We will now make a function that allows us to import a document and return an array of each word in the document which will be our corpus.</p><p>If you have excess text in the document that you do not want to be used in the training (for example, if you are trying to train on an HTML page, you may want to remove all the tags and keep just the important text) you can make an extra function to remove the excess stuff, or you can manually remove it. For this demonstration, we assume you have a raw text document entirely with information you want to train with.</p><p>The full code for making a function that brings in a document is as shown:</p><pre># Read in data from a file and split it<br>def read_words(doc):<br>    file = open(doc, &quot;r&quot;)<br>    text = file.read()<br>    file.close()<br>    return text.split()</pre><h3>Initialize The Vocabulary</h3><p>Next, we will be using the read_words() function we just created to pull in a document titled “hello.txt”. You can modify this to pull in a document of your own.</p><p>After that, we will be getting a vocabulary of our document, which is essentially a list of every word that occurs in our document, but without any duplicate words. This is essential in initializing the input layer of our embedding model. The model must have an input neuron for every known word, which is also why we have a variable holding the size of the vocabulary. After we make our vocabulary list, we then get the size of our vocabulary to later initialize the input size for our embedding model.</p><p>We then create a dictionary enumerating, or giving a unique number, to every word in our vocabulary. The neural network can’t take in raw strings. Neural networks work on numbers, so we must represent each word as a unique number, which is what enumeration does.</p><p>Presume our corpus is just “hello.txt” and it only contains “the quick brown fox jumped over the lazy dog”. The vocab enumeration would be</p><pre>{&#39;the&#39;: 0, &#39;quick&#39;: 1, &#39;brown&#39;: 2, &#39;fox&#39;: 3, &#39;jumped&#39;: 4, &#39;over&#39;: 5, &#39;lazy&#39;: 6, &#39;dog&#39;: 7}</pre><p>The full code for initializing the vocabulary is here:</p><pre># Read in from a document<br>words = read_words(&quot;hello.txt&quot;)<br><br># Create our vocabulary of unique words<br>vocab = []<br>for i in words:<br>    if i not in vocab:<br>        vocab.append(i)<br># Get the size of our vocabulary<br>vocab_size = len(vocab)<br><br># Enumerate each word in our vocabulary to have a unique index for each word<br>word_to_index = {}<br>for i in enumerate(vocab):<br>    word_to_index[i[1]] = i[0]</pre><h3>Creating The Embedding Model Class</h3><p>Our model will be inheriting from the neural network class of PyTorch.</p><p>Our init() function takes in two parameters. The first parameter is the size of the vocabulary, and the second parameter is the embedding dimension size. You can think of the embedding dimension size as the number of axes on a plane. A 3-dimensional embedding size is essentially an X, Y, Z plane. This number can be as high you want, but for our demonstration, the embedding dimension will be 3 as it is quite easy to envision a 3-dimensional plane. The smaller the number of the embedding dimension, the closer everything will be to one another. The higher the embedding dimension, the further things will be, and only very closely related things will be close to one another on the plane.</p><p>Our forward() function takes in a list of indexes of a sentence that has been split into an array of the unique indexes of each word. The following example is from the phrase “the brown dog”. You can cross reference the indexes for “the”, “brown”, and “dog” in the vocab enumeration example above.</p><pre>tensor([0, 2, 7])</pre><p>The first thing it does is transforms each word index into a PyTorch tensor (imagine this as a PyTorch compatible array) with each word index’s tensor having the size of the number of vocab words we have. This is the “object” variable. So if we pass in 3 word indexes (like we did above), we will have three PyTorch tensors with the size of the number of vocab words. Every value in each word index’s tensor has a value of 0, except for the corresponding word index of the respective word index tensor. The respective tensor at the corresponding word index has a value of 1, indicating that a specific word is being passed in and the index is that word’s position in the input layer. For example, taking the word “brown”, it has a value of 2 in the vocab enumeration. So what would happen is it will start of with a tensor of all zeroes the size of the vocabulary. In our case, we have 8 total unique words in our vocabulary, so the tensor for “brown” will start of as</p><pre>tensor([0., 0., 0., 0., 0., 0., 0., 0.])</pre><p>The index for “brown” in our vocab enumeration dictionary is 2, so at the 2 index in the tensor, the 0 will turn into a 1. This is to show that the word at the 3rd neuron in the neural network corresponds to “brown”. This will look like the following. (Keep in mind that when it comes to arrays/tensors in Python, the indexing starts at 0, so the value of 2 actually corresponds to the 3rd position in the array/tensor.)</p><pre>tensor([0., 0., 1., 0., 0., 0., 0., 0.])</pre><p>The process of turning an index value into a neural network tensor is called a one-hot transformation, and this transformation is required in order to pass the phrase into the neural network as the network expects a value for each input neuron (similar to how a programming function expects all parameters to have a value or it will error out). So let’s say we want to embed our phrase of “the brown dog”. The one-hot transformation would be:</p><pre>tensor([[1., 0., 0., 0., 0., 0., 0., 0.],<br>        [0., 0., 1., 0., 0., 0., 0., 0.],<br>        [0., 0., 0., 0., 0., 0., 0., 1.]])</pre><p>As you can see, for each word, there is a tensor the size of our vocabulary, and for each corresponding tensor for each passed in word, the index of that word in the corresponding tensor is 1 while everything else is 0.</p><p>You can cross reference the position of the 1 values in each array to the vocabulary enumerations above to see that the position of each 1 value corresponds to each word in “the brown dog” where “the” has index 0, “brown” has index 2, and “dog” has index 7 (again, remember that Python arrays start indexing at 0).</p><p>After the phrase undergoes the one-hot transformation, the model then gets the actual 3-dimensional embedding of each word index. This would look something like the following (you may get different numbers):</p><pre>tensor([[ 0.2114,  0.2118, -0.1024],<br>        [ 0.1414, -0.0792, -0.1173],<br>        [ 0.1880, -0.0456, -0.1486]], grad_fn=&lt;AddmmBackward0&gt;)</pre><p>We do not want to have embeddings for each individual word, totaling 9 different positions in this scenario. We want a single 3-dimensional embedding for the whole phrase. Therefore, we need to average the embeddings of each word to get the embedding for the entire phrase. If we average the above embeddings for each word in “the brown dog”, we could get something similar to the following code for the embedding of the entire phrase for “the brown dog”.</p><pre>tensor([ 0.1803,  0.0290, -0.1228], grad_fn=&lt;MeanBackward1&gt;)</pre><p>Now that we have laid the foundation of how the embedding model class works, the complete code for creating the EmbeddingModel class is as followed:</p><pre># Embedding Model Class<br>class EmbeddingModel(nn.Module):<br>    # Initialize the model<br>    def __init__(self, loc_vocab_size, loc_embedding_dim):<br>        super().__init__()<br>        # Network size of vocab size for the input and embedding dimension size as the output<br>        self.embedding = nn.Linear(loc_vocab_size, loc_embedding_dim)<br><br>    # What to do what the model is invoked<br>    def forward(self, index_list):<br>        # Turn word indexes into appropriate input values for the network<br>        objects = torch.nn.functional.one_hot(index_list, num_classes=vocab_size).float()<br>        # Get the embeddings and average the results<br>        embedded = self.embedding(objects).mean(dim=0)<br>        # Return the embedding<br>        return embedded</pre><h3>Establishing The Embedding Model Object</h3><p>The next thing we are going to do is actually utilize our model. The first thing we are going to do is establish the embedding dimension size. In this example, we are establishing a 3-dimensional embedding dimension size. To use the model, we will be making an object called “model” which calls our EmbeddingModel() class with the parameters of our vocab_size we initialized earlier, and using the embedding_dim size we just initialized.</p><p>We will then initialize an optimizer, which is essentially used to teach and train the model. Imagine the optimizer as a coach or a teacher and the model is the student. The optimizer will have the model make minor adjustments to help it better itself as it continues to learn. Without the optimizer, the model has no way to actually learn and develop.</p><p>We are using the AdamW optimizer which is an improved optimizer based on the Adam optimzer. Adam is already fairly standard and respected by many and is used in training many models, and AdamW makes it even better! AdamW includes optimizations over Adam that include better stability, better generalization (being able to embed phrases it has not seen before), and better protections on overfitting (or learning to train too specifically on the given data and not be able to handle new data very well).</p><p>The optimizer adjusts the model parameters as it goes along in its training in order to help the model gain a greater understanding. AdamW (as well as Adam) also incorporates the concept of momentum in which the model will move faster in the learning process in more familiar areas, and move slower or more cautiously in more unfamiliar areas. Here, we are initializing the AdamW optimizer with the model’s parameters, and then setting the initial learning rate to 0.01. This means that the model will have its parameters adjusted by up to 1% of the suggested gradient by the optimizer. The gradient is essentially a measurement of how much and in what direction the model should move in order to reach its goal. All of this is essentially having the model crawl before it is able to run while it still does not know how to move or where to go. You can adjust the learning rate, but be wary of setting it too low or too high. Setting it too low can cause the model to just wiggle around and move towards its goal at a very slow rate, and setting it too high will cause the model to essentially get up and try to sprint towards the goal, but always trip and fall and not know how to get up because it still does not know how to move.</p><p>The final part of this section is the criterion variable, which essentially holds a “score” of how far off the model is from some target value. The model wants to try to minimize this score (sort of like in golf), and the optimizer adjusts the model parameters to try to lower the score. In our scenario of making an embedding model, we are using the MSELoss() (Mean Squared Error Loss) criterion. This approach is simpler than other options and does many relevant things in an embedding model sense. One of the most notable features is MSELoss() can directly measure the vector distances between the predicted and targeted embeddings to gain a score as to how close to the target embeddings the predicted embeddings were. This score helps guide the model in learning how to more accurately represent words and phrases as embeddings.</p><p>Below is the full code for establishing the embedding model object:</p><pre># Initialize the embedding dimension<br>embedding_dim = 3<br># Create our embedding model object with input size of our vocab and output size of our embedding dimension<br>model = EmbeddingModel(vocab_size, embedding_dim)<br># Use AdamW to help train and improve the model<br>optimizer = optim.AdamW(model.parameters(), lr=0.01)<br># Use MSELoss as our score keeper<br>criterion = nn.MSELoss()</pre><h3>Training The Model</h3><p>We are now going to train the model. There is a lot going on here, but bear with me. The first thing we do is invoke model.train(), which simply tells the model it is going to be in training mode. The next thing we are going to do is establish two variables, one for the number of epochs (the times we want to train the model), and the context window size. Both of these variables are free for you to adjust, but make sure you have sufficient epochs and an appropriate sized context window. When selecting the number of epochs, you do not want to have too few epochs as your model may not learn enough, and you do not want too many epochs as you may overfit the training results. Similarly, you don’t want your window size to be too small as it may not capture a lot of context, and you do not want it too large as your model may overfit the results.</p><p>The context window size will be used in order to “slide” across a sentence or paragraph in order to get words of context for a paired “target” word. A “target” word, or a “focus” word, is the word in the middle of the context window in order to train the model on contextual word importance for a specific word. We will use this sliding window and target word technique on every word, where every word has a chance to be the “focus” word in order for the model to understand the context of every word in the corpus as to where it belongs in sentences and how it semantically relates to other words and phrases.</p><p>We then have a for loop that loops num_epoch number of times. We then establish two more variables. One is called running_loss which totals the score from the optimizer, and the count variable which is used to help give us the average loss per training epoch, or the average score from the optimizer per epoch.</p><p>In a nested for loop, we then initialize it to run the number of times as there are total words in our data. This will allow every word to be the “target” or “focus” word. In this for loop, we then create an empty array with an empty string called “context_words” which will hold surrounding words to the left and right of the target word as context. The target word will always be the word at the index of the current loop value in the data. The context words will always be the previous 3 “window” words and the following 3 “window” words. Again, you can adjust the window values to your own liking. For example, suppose in our “the quick brown fox jumped over the lazy dog” corpus, “fox” is the target word. If we had a context window of size 3, the context words for “fox” would be “the”, “quick”, “brown”, “jumped”, “over”, and “the”. With these context words, the model may begin to associate words like “quick” and “jumped” with the word “fox”. In the next pass, the new target word would be “jumped” and then the word “jumped” would be associated with its target words as the context window “slides” with the target word.</p><p>When calculating the context words, we also take into consideration edge cases in the data such as target words that do not have as many context words before or after it as required by the window size. In this case, we simply take as many context words near the edge case as we can. For example, using our “the quick brown fox jumped over the lazy dog” corpus, presume we have “quick” be the target word with our context window size of 3. The right context window is fine as there is no edge case. The right context words are simply “brown”, “fox”, and “jumped”. However, in our left context window for “quick”, we do not have enough words for a left context window of size 3. We therefore take only “the” as the left context window instead of simply discarding it. We then add together the left and right context windows to gain a full context for the target word, which in this case is “the”, “brown”, “fox”, and “jumped”.</p><p>After that, we get the unique numerical indexes for each context word and the target word and turn it into a PyTorch tensor in order for them to be passed into our model. We then do something called clearing the gradients in the optimizer using optimizer.zero_grad() so then the optimizer (the teacher) can focus on how the model performed in only the current batch. We do not want any influence on how well the model did from any previous iterations. Clearing the gradients would be similar to erasing a chalkboard to solve a new problem.</p><p>We then invoke our model with the indexes of our context words and the index of our target word to get the embeddings for each. We get the average embeddings of the context words and get the embeddings of the target word. We then call upon the MSELoss() criterion in order to see how well the model did at predicting the embeddings of the target word in relation to the average embeddings of the context words and store that in a variable called “loss”. Using this, we are able to figure out which part of the model messed up the most and needs adjustment. This approach is similar to the Continuous Bag Of Words algorithm (CBOW) where a word is predicted by the model based on some given context words. It’s like a fill-in-the-blank game for the model where the model tries to fill in where a word should go based on some given context clues. The model is just training to get REALLY good at it. Our approach, however, is slightly different from a true CBOW model because in a traditional implementation, CBOW is used to train model to to predict an actual word. Here, we are using the approach to train the model to calculate embeddings of a word.</p><p>We then use back-propagation on the “loss” variable in order to analyze the effectiveness of the model in the current batch. To put it plainly, when we invoked our MSELoss() criterion, we were measuring the effectiveness of the model. Here, in back-propagation, we are actually analyzing how well the model did given the results from MSELoss(). This would be like a coach watching you golf and he monitors each swing. Every swing, the coach looks to see what you did right, and what part of your swing needs improvement (such as foot placement or the placement of the hands on the club). After this, we then have the optimizer teach the model how to improve given the analysis of the results from MSELoss(). The optimizer then updates the model’s parameters to adjust the model to perform better in the next batch. This is equivalent to the golf coach slightly adjusting your stance or hand placement on the club in order to get you in a better position so then you can hit the ball further and more efficiently next time.</p><p>These next steps are mainly for our viewing for debugging and monitoring purposes to see how the model improves over time. First, we compute the total loss of the epoch. We sum the losses for each target word and context window pair and increment a counter by 1 each time as well in order to compute the average loss shortly after. After the epoch, we then display the epoch that just occurred along with the average loss of all the batches in the epoch in order to see over time how low the loss gets. This is useful because there comes a point in time where loss can plateau, so if you are trying to find optimal training epochs, this is one way to do it.</p><p>Below is the full code for the training implementation:</p><pre># Train the model<br>model.train()<br>num_epochs = 75<br>window = 3<br>for epoch in range(num_epochs):<br>    # Total loss for this epoch<br>    running_loss = 0.0<br>    # Get the number of words being<br>    count = 0<br><br>    for word in range(len(words)):<br>        context_words = []<br>        # Left context window is not enough<br>        if word &lt; window:<br>            context_words = words[0: word] + words[word + 1: word + window + 1]<br>        # Right context window is not enough<br>        elif word &gt; window:<br>            context_words = words[word - window: word] + words[word + 1: len(words) - 1]<br>        else:<br>            context_words = words[word - window: word] + words[word + 1: word + window + 1]<br><br>        # Turn the context words in their respective indexes<br>        context_indexes = []<br>        for i in context_words:<br>            context_indexes.append(word_to_index[i])<br>        context_indexes = torch.tensor(context_indexes)<br><br>        # Turn the target index into its respective index<br>        target_index = [word_to_index[words[word]]]<br>        target_index = torch.tensor(target_index)<br><br>        # Zero out the gradients<br>        optimizer.zero_grad()<br><br>        # Get the embedding results for the current context words and target word<br>        context_output = model(context_indexes)<br>        target_output = model(target_index)<br><br>        # Measure the &quot;score&quot; of how well the model did this batch.<br>        loss = criterion(context_output, target_output)<br>        # Analyze the &quot;score&quot;<br>        loss.backward()<br><br>        # Updating the model parameters to help it perform better<br>        optimizer.step()<br><br>        # Get the total epoch loss<br>        running_loss += loss.item()<br>        count += 1<br><br>    # Display the epoch and the average loss for the epoch<br>    print(&quot;Epoch:&quot;, epoch)<br>    avg_loss = running_loss / count<br>    print(&quot;Loss:&quot;, avg_loss)</pre><h3>Using Our Newly Trained Model</h3><p>Now that we have trained our model, we can now infer it (use it) to create embeddings for us! The first, and most obvious way, to use the embedding model is to simply give it a word or phrase and receive the embeddings. The second way is to make sort of a mini vector database with our vocabulary and try to find the most similar word in our vocabulary given a word or phrase.</p><h4>Getting Embeddings</h4><p>To get the embeddings of a word or phrase, let us first make a function out of it with a single parameter that takes in a string of the word or phrase we want to embed. We then put the model into evaluation mode with model.eval() (so it is no longer is in training), and tell PyTorch that in the current section we are not producing any gradients. This part is redundant since we have model.eval(), but it’s good practice to specify that we don’t want gradients to be calculated during inference.</p><p>Inside of the section where we are not computing gradients, we first need to split the input word or phrase into an array. We then get the indexes for each word in the input and put them in another array, turn the array into a PyTorch tensor to be used with our model, and then pass the tensor of indexes into our model and return the result. Now all you have to do is call the function with any word or phrase you want as the input, and you have embeddings!</p><p>Keep in mind that the model cannot work with any words or words in phrases that it has not already seen or trained on. For example, going back to our “the quick brown fox jumped over the lazy dog” corpus, we cannot see how “chipmunk” embeds because it was never used in any form of training. It’s not that the model would give us a weird embedding, it’s that the model would simply straight up error out. Think of it like an out-of-bounds error, or a key error in a dictionary. It’s going past the number of established vocabulary indices, and the model doesn’t know what “chipmunk” even means.</p><p>One approach to handling unknown words involves inserting an extra neuron into the model at creation time strictly dedicated to unknown words. So any new word that is seen while inferring the model that isn’t in the vocabulary could simply be transformed into some “unknown word” value and the model can deal with it that way.</p><p>Our model is also case sensitive, so “Fox” would not be able to be embedded either. If you wanted to, you can invoke the lower() function on your corpus and any inference words and phrases to make sure there are no casing issues when using your model. This would not only prevent casing issues, but it would also save memory in training. Keep in mind though that if you do this, distinctions may not be as prominent such as apple the fruit may not be as distinct from Apple the company.</p><p>The code for our embedding function is as such:</p><pre># Create an embedding<br>def generate_embed(embedding_words):<br>    # Move to evaluation mode<br>    model.eval()<br>    # Don&#39;t produce gradients<br>    with torch.no_grad():<br>        # Split the words and put their indices in an array<br>        embedding_words = embedding_words.split()<br>        output = []<br>        for i in embedding_words:<br>            output.append(word_to_index[i])<br>        # Get and return the embedding results<br>        output = torch.tensor(output)<br>        return model(output)</pre><h4>Comparing Words And Phrases To Our Vocabulary</h4><p>We are now going use our generate_embed() function in another function called find_similar_word() that takes in a single argument of a word or phrase. In the function, we do the same thing as in generate_embed() where we tell the model it is in evaluation mode and tell PyTorch not to calculate any gradients. After that, we then make a variable that calls generate_embed() with the argument of the passed in word or phrase to find_similar_word(). We then make two more variables, one which is called “similarity” will hold the word closest to the user input and another called “min_dist” which will hold the smallest distance between two embeddings.</p><p>We then loop through our entire vocabulary, and within the loop we get the embedding of the current vocab word and then calculate the euclidean distance between the user input embedding and the current vocabulary word embedding. This formula is similar to the Pythagorean theorem. The distance between the vocab word and user input embeddings is then checked against the current distance in “min_dist”. If the difference is smaller than what is in “min_dist”, then “min_dist” is updated with the new smallest distance and “similarity” has the vocab word associated with that distance.</p><p>After looking through every vocab word against the user input, the closest vocab word to the user input is then returned. This is a very high-level demonstration as to how querying in a vector database works.</p><p>The code for the function for the most similar word to a user input is here:</p><pre># Function to find similar words<br>def find_similar_word(compare_word):<br>    # Evaluation mode<br>    model.eval()<br>    with torch.no_grad():<br>        # Get embedding of input phrase<br>        word_embedding = generate_embed(compare_word)<br>        # Placeholders for closest word to input<br>        similarity = &quot;&quot;<br>        min_dist = sys.maxsize<br>        # Loop through entire vocabulary<br>        for i in vocab:<br>            # Get the embedding of the vocab<br>            temp_embedding = generate_embed(i)<br>            # Calculate euclidean distance between vocab word and user input<br>            dist = 0<br>            for dim in range(embedding_dim):<br>                dist += pow(word_embedding[dim] - temp_embedding[dim], 2)<br>            dist = math.sqrt(dist)<br>            # See current vocab word is closer to user input than previous word<br>            if dist &lt; min_dist:<br>                min_dist = dist<br>                similarity = i<br>        # Return closest word<br>        return similarity</pre><h4>Examples Of Calling The Functions</h4><p>We can finally call our two functions to see the outputs of the functions. We will be using “the quick dog” as our example phrase. Calling generate_embed() using the following code, we get the resulting embedding.</p><pre>phrase = &quot;the quick dog&quot;<br>generated_embed = generate_embed(phrase)<br>print(generated_embed)</pre><pre>tensor([ 0.2708, -0.0142,  0.0920])</pre><p>Using the same phrase on find_similar_word(), we should get a resulting output vocab word closest to our phrase.</p><pre>print(find_similar_word(&quot;the quick dog&quot;))</pre><pre>the</pre><p>In this particular instance, the closest word to “the quick dog” is “the”. Seeing as our corpus is extraordinarily small and trained in 75 epochs with a small window size of 3 with a small dimension size of 3, it is exciting to see that “the” is the closest word to our phrase as it is actually in our phrase.</p><p>The result can change every run as the model trains slightly differently every time, but should largely yield similar results.</p><h3>Other Things To Try</h3><h4>Adjusting The Hyperparameters Of The Model</h4><p>If the model is not embedding as you have hoped, try adjusting the values of “embedding_dim”, “num_epochs”, and “window” to try to get a result more tuned to your liking. Also try adjusting the learning rate in the optimizer. You can also try increasing your corpus size to include more text to train on. Currently, we are only working with “the quick brown fox jumped over the lazy dog,” but maybe try something with more context as such</p><pre>the fox is a quick animal<br>the fox can jump<br>the fox can be brown<br>the dog can be a lazy animal<br>the dog is short<br>the dog can lay down<br>the quick brown fox jumped over the lazy dog</pre><p>But don’t stop here! See what would happen if you trained your embedding model on a MUCH larger document, or multiple documents!</p><h4>Using A Skip-Gram Approach In Training</h4><p>Currently, we are using a Continuous Bag Of Words (CBOW) approach in training our model. A skip-gram approach is the complete opposite of CBOW. CBOW takes context words and tries to find a target word like a fill-in-the-blank. Skip-gram takes a single target word and tries to find context words.</p><p>This approach has its benefits and downfalls compared to CBOW. Skip-grams are able to see the context of rarer words whereas CBOW is better at getting context of more frequent words. Skip-grams also take longer to train compared to CBOW as it takes the target word and compares it against each word in the context window individually as opposed to taking the entire context window at once and training against the target word. However, due to the approach of looking at each individual word in a context window, this allows skip-grams to to see closer relationships of various words opposed to CBOW.</p><p>To implement skip-grams, we are going to modify the section of our training loop where we calculate the criterion and loss for each word in our context window. For each word in our context window we will add the criterion result to our loss, and then average the loss at the end. The updated training section is shown below:</p><pre># Train the model<br>model.train()<br>num_epochs = 75<br>window = 3<br>for epoch in range(num_epochs):<br>    # Total loss for this epoch<br>    running_loss = 0.0<br>    # Get the number of words being<br>    count = 0<br><br>    for word in range(len(words)):<br>        context_words = []<br>        # Left context window is not enough<br>        if word &lt; window:<br>            context_words = words[0: word] + words[word + 1: word + window + 1]<br>        # Right context window is not enough<br>        elif word &gt; window:<br>            context_words = words[word - window: word] + words[word + 1: len(words) - 1]<br>        else:<br>            context_words = words[word - window: word] + words[word + 1: word + window + 1]<br><br>        # Turn the context words in their respective indexes<br>        context_indexes = []<br>        for i in context_words:<br>            context_indexes.append(word_to_index[i])<br>        context_indexes = torch.tensor(context_indexes)<br><br>        # Turn the target index into its respective index<br>        target_index = [word_to_index[words[word]]]<br>        target_index = torch.tensor(target_index)<br><br>        # Zero out the gradients<br>        optimizer.zero_grad()<br><br>        target_output = model(target_index)<br><br>        # Measure the &quot;score&quot; of how well the model did this batch.<br>        loss = torch.zeros(1)<br>        # Get the embedding of each context word and compare it against the target<br>        for i in context_indexes:<br>            context_output = model(torch.tensor([i]))<br>            loss += criterion(target_output, context_output)<br>        # Average the loss of all the words<br>        loss = loss / len(context_indexes)<br><br>        # Analyze the &quot;score&quot;<br>        loss.backward()<br><br>        # Updating the model parameters to help it perform better<br>        optimizer.step()<br><br>        # Get the total epoch loss<br>        running_loss += loss.item()<br>        count += 1<br><br>    # Display the epoch and the average loss for the epoch<br>    print(&quot;Epoch:&quot;, epoch)<br>    avg_loss = running_loss / count<br>    print(&quot;Loss:&quot;, avg_loss)</pre><h4>Using PyTorch’s Native Embedding Network</h4><p>Put your pitchforks away! This is not what you think! I did not just waste your time telling you how to do it from scratch only for PyTorch to have something natively. The embedding network in PyTorch is simply an optimization that can replace our nn.Linear network in the class definition of our model. nn.Linear is not the absolute best approach to making an embedding model, but it’s not the worse either. nn.Embedding has a lot of built-in under the hood stuff that make it better for embedding models than nn.Linear.</p><p>One of the most notable optimizations is that nn.Embedding does one-hot encoding under the hood without us having to do it. This means we can insert an index tensor directly. Switching to nn.Embedding from nn.Linear is very simple and straightforward. Simply just replace nn.Linear with nn.Embedding, remove the one-hot encoding from the forward() function, and change the call to self.embedding from “objects” to “index_list”. Everything else in our code can stay the same.</p><p>The reason why we went over how to make embedding models with nn.Linear is to get a fine grasp of the things like one-hot encoding in order to understand more in depth how these embedding model networks work at a finer level of detail. However, it would be unethical of me to hide the existence of nn.Embedding as it is more suitable for a wider range of scenarios (such as use in real-world cases) because of its many optimizations, learning improvements, and speed enhancements.</p><p>The updated EmbeddingModel class is below:</p><pre># Embedding Model Class<br>class EmbeddingModel(nn.Module):<br>    # Initialize the model<br>    def __init__(self, loc_vocab_size, loc_embedding_dim):<br>        super().__init__()<br>        # Network size of vocab size for the input and embedding dimension size as the output<br>        self.embedding = nn.Embedding(loc_vocab_size, loc_embedding_dim)<br><br>    # What to do what the model is invoked<br>    def forward(self, index_list):<br>        # Get the embeddings and average the results<br>        embedded = self.embedding(index_list).mean(dim=0)<br>        # Return the embedding<br>        return embedded</pre><h3>Conclusion</h3><p>Congratulations! You now know how to make your own embedding model! You can now go on to train it on various things such as books and articles for semantic embedding, specific work such as school notes to store your various class materials in a vector database, or you can train it on all your juicy secrets!</p><p>Now that you understand not just how embedding models work, but also how neural networks work, you can now take your newfound knowledge to go on and make something even greater like a language model!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e8834ce6c05" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-lab-c4ai/how-to-make-an-embedding-model-6e8834ce6c05">How To Make An Embedding Model</a> was originally published in <a href="https://medium.com/ai-lab-c4ai">AI Lab @ C4AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Communicating with Patrons to Communicating with AI - My Journey]]></title>
            <link>https://medium.com/@devonslonaker/from-communicating-with-patrons-to-communicating-with-ai-my-journey-d5038f4adb3b?source=rss-1525926828b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5038f4adb3b</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[college]]></category>
            <category><![CDATA[university]]></category>
            <dc:creator><![CDATA[Devon Slonaker]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 16:23:50 GMT</pubDate>
            <atom:updated>2024-11-04T16:23:50.766Z</atom:updated>
            <content:encoded><![CDATA[<p>Back in 2018, I was clearing tables, communicating with restaurant patrons, and making salads. Fast forward to today, and I am communicating with something far different — AI models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*SlefkyA5GVINx2IOe46SDA.png" /><figcaption>A response from Qwen2.5 3b regarding how life can change.</figcaption></figure><p>Just 6 years ago, I was a busboy at a local restaurant, cleaning tables and looking forward to college. I didn’t even know what AI was back then. I had my eyes set on the great journey of Computer Science I had ahead of me. Aspiring to be a game developer, I had dreams of being on teams making the new Super Mario, Pokémon, or Call of Duty. Little did I know, God had other plans for me and my career path.</p><p>I was accepted into the University of Maryland, Baltimore County, and attended my first semester of Computer Science in the Fall of 2019. Having already taken basic programming classes in high-school, my first Computer Science Python class was no sweat. Later classes like C++, Computer Architecture, Discrete Mathematics, Algorithms, and Operating Systems were no big feat for me as well. While challenging in some areas, all seemed to come fairly naturally to me.</p><p>In the midst of my first Computer Graphics class, I knew it was going to be my last. Computer Graphics was one of the biggest classes for the Game Development track, and it was the hardest class I have ever taken. I quickly realized that I may not want to do Game Development as a career as, quite frankly, I was no good at it. I met my match. However, another class I was taking at the same time not only had me doing well but had me intrigued like no other class.</p><p>Computer Security was a class like none other. Creating rainbow tables, utilizing Metasploit, and creating my own SSL certificate were some of the coolest things I had ever done, and I was hooked. I knew I wanted to do something with this. This class inspired me to the point that I began making my own home network. Utilizing OPNSense to make a router with a Dell Optiplex, and using Unbound and AdGuard Home DNS on an old laptop to make my own DNS server only got me more interested and in love with Computer Security and developing applications with security in mind.</p><p>I later became a Teaching Assistant for the Computer Security course, and helping people with something I was now passionate with was an incredible feeling. I was later admitted into the Computer Science Master’s program at UMBC where I continued my Computer Security Teaching Assistant job and took Master’s level Computer Security based classes of my own. During that Summer, I had taken up a temporary Student Linux System Administrator job at UMBC migrating servers from a Red Hat Enterprise environment to an Ubuntu environment. This job granted me a great amount of Linux knowledge, and the abilities and know-how to manage and set up Linux servers of my own.</p><p>My 2024 Spring Master’s graduation was approaching quickly, and I had yet to find a post-college job. I spent the Spring searching through Indeed and LinkedIn trying to find any Computer Science related job. Nothing. In particular, I found a Software Engineering job at Canonical to be most interesting as I was familiar with Ubuntu after my Student Linux System Administrator job. I applied to that job numerous times in numerous areas, as it seemed to be great for a recent college graduate such as myself as it did not seem to require too much for an entry-level role. However, Canonical shut me down every time.</p><p>Later, I spoke with one of my professors about this, with whom I had taken three different classes, and I mentioned how I was looking to take up a role at Canonical. He had mentioned he knew some guys who worked with Red Hat, and that piqued my interest. Soon enough, I was interviewing with two gentlemen from the UMBC Training Centers, when I thought I was interviewing with people from Red Hat. I soon realized my misunderstanding, but decided to see where this would go.</p><p>During one of the interviews, I was told that the UMBC Training Centers was looking for candidates to help build a new start-up called the Center for Applied AI. I knew nothing about AI and did not have much interest in AI at the time, namely because I had the notion that services like ChatGPT were stealing your data whenever you talked with it. The most I had done with AI was take an AI class at UMBC and a making a machine learning Movie Recommendation System for another class. However, despite my previous lack of interest in AI, I was intrigued as to where this would go, for I knew AI was the way of the future.</p><p>The Center for Applied AI later offered me a job, and I promptly took it up. During my first few weeks working there, something changed. My outlook on AI shifted, and I became hooked with it just as I had become with Computer Security. I had found a new love. I quickly found out that AI could be made local, and when something is local, it can be made private and secure (which intrigued the Computer Security part of my mind).</p><p>From then on, my mission at the Center for Applied AI was to research and study various ways to use and serve AI in a local, private, and secure manner for both normal everyday users, and enterprise-grade applications. While journeying through this outlook, I realized that many people are like me in the sense that they too are very skeptical of AI as privacy concerns are a major reason many are not fond of the technology. This gave me all the more encouragement and enthusiasm to go full steam ahead in my research and development of local, private, and secure AI applications, which I am still pursuing to this day.</p><p>Because of my mission and outlook, many of my future articles will be focused on how you can utilize various AI applications locally at home that are privacy respecting, and even how to make your own AI and neural-network-based tools.</p><p>Thank you for reading my first article. May God bless you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5038f4adb3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>