<?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 Maddie Lupu on Medium]]></title>
        <description><![CDATA[Stories by Maddie Lupu on Medium]]></description>
        <link>https://medium.com/@madalina.lupu.d?source=rss-d276f184cbd2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HXiNuxa3tnUtXrRy0aBAxw.png</url>
            <title>Stories by Maddie Lupu on Medium</title>
            <link>https://medium.com/@madalina.lupu.d?source=rss-d276f184cbd2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:16:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@madalina.lupu.d/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[Agentic AI Recipe Part 2: Build a Router Engine with Watsonx]]></title>
            <link>https://medium.com/@madalina.lupu.d/agentic-ai-recipe-part-2-build-a-router-engine-with-watsonx-c141896e1e49?source=rss-d276f184cbd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c141896e1e49</guid>
            <category><![CDATA[decision-making]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[llms-reasoning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Maddie Lupu]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 11:15:57 GMT</pubDate>
            <atom:updated>2024-08-06T11:16:13.902Z</atom:updated>
            <content:encoded><![CDATA[<h4>Router Engine with LlamaIndex and Watsonx</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*fNSDjIRJRNXe1FowUXY7NQ.png" /><figcaption>image source: <a href="https://www.vecteezy.com/vector-art/355584-direction-vector-icon">https://www.vecteezy.com/vector-art/355584-direction-vector-icon</a></figcaption></figure><p>In the first part of the “<a href="https://medium.com/@madalina.lupu.d/the-agentic-ai-recipe-5b26de148d89">Agentic AI Recipe</a>” article, I discuss what Agentic AI is and how it differs from fixed Large Language Model flows or simple RAG query engines designed solely for question and answer tasks.</p><p>In this second part of the article, I will showcase the capabilities of Agentic AI. We’ll build a simple Router Engine using <a href="https://www.llamaindex.ai/">LlamaIndex</a> and <a href="https://www.ibm.com/watsonx">Watsonx</a>. This engine will answer questions based on a transcript from my all-time favourite podcast, “<a href="https://freakonomics.com/podcast/why-is-it-so-hard-to-make-decisions/">No Stupid Questions,</a>” hosted by Angela Duckworth and Mike Maughan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uAkvsO6R-sNMlQyhj1wRxA.png" /></figure><p>Given a question, the Router will select one of the query engines to perform an action. The Router Engine’s primary function will be to either summarise or retrieve specific context from the podcast transcript.</p><p>The podcast episode we will use for the Router Engine is all about Decision Making. We all make decisions constantly, and I’ve always been intrigued by why it’s sometimes so difficult. Our Router Engine will help us understand how to make better decisions, avoid analysis paralysis, and provide recommendations for improving our decision-making skills! 💪</p><p>Here is how the Router is going to work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RBf1zx-aII7VJ86xnpVPXw.png" /><figcaption>source: deeplearning.ai</figcaption></figure><p>Let’s crack on! ⚡</p><ol><li>Import some libraries to start and load Watsonx credentials</li></ol><p>We are going to use mistral-large-2 because I am curious about its capabilities, especially since it has just been launched and added to the Watson.ai platform. It has a large context window of 128k tokens and demonstrates good performance based on the LLM benchmarks published.</p><pre>from dotenv import load_dotenv<br>import os<br>import nest_asyncio<br>nest_asyncio.apply()<br>load_dotenv()<br>from llama_index.llms.ibm import WatsonxLLM<br><br>apikey = os.getenv(&quot;WATSONX_API_KEY&quot;, None)<br>project_id = os.getenv(&quot;PROJECT_ID&quot;, None)<br>url = os.getenv(&quot;url&quot;, None)<br>max_new_tokens = 200<br>additional_params = {<br>    &quot;decoding_method&quot;: &quot;greedy&quot;,<br>    &quot;repetition_penalty&quot;: 1.2,<br>    &quot;stop_sequence&quot;: [&quot;&lt;|endoftext|&gt;&quot;]<br>}<br>watsonx_llm = WatsonxLLM(<br>    model_id=&quot;mistralai/mistral-large&quot;,<br>    url=url<br>    project_id=project_id,<br>    apikey=apikey,<br>    max_new_tokens=max_new_tokens,<br>    additional_params=additional_params,<br>)</pre><p>2. Load documents</p><p>I saved the podcast episode transcript in a PDF file and the code below divides it into evenly sized sentences. Each node includes both the chunk text and metadata about the document.</p><pre>from llama_index.core import SimpleDirectoryReader<br>from llama_index.core.node_parser import SentenceSplitter<br><br>documents = SimpleDirectoryReader(input_files=[&quot;decisions-freakonomics.pdf&quot;]).load_data()<br>splitter = SentenceSplitter(chunk_size=800)<br>nodes = splitter.get_nodes_from_documents(documents)</pre><p>3. Set Global Settings to define Embedding Model and LLM</p><p>For the LLM I we are going to use the watsonx_llm instance we defined above. For the embedding model we are going to use a text embedding model BAAI/bge-small-en-v1.5developed by Beijing Academy of Artificial Intelligence (BAAI) that works well for retrieval cases and with LlamaIndex.</p><pre>from llama_index.core import Settings<br>from llama_index.embeddings.huggingface import HuggingFaceEmbedding<br><br>Settings.llm = watsonx_llm<br>Settings.embed_model = HuggingFaceEmbedding(<br>    model_name=&quot;BAAI/bge-small-en-v1.5&quot;)</pre><p>4. Define SummaryIndex and VectorIndex over the same nodes.</p><p>An index contains a set of metadata on top of the data, enabling different retrieval behaviours or filters. The key distinction between a vector index and a summary index lies in their retrieval behaviours.</p><p>The VectorStoreIndex returns most similar nodes by embedding similarity, while a SummaryIndex will return all the nodes in the vector store.</p><p>Each Vector Store serves as a query interface over the indexed data, combining retrieval with LLM synthesis to enhance the retrieval process.</p><pre>from llama_index.core import SummaryIndex, VectorStoreIndex<br><br>summary_index = SummaryIndex(nodes)<br>vector_index = VectorStoreIndex(nodes)<br><br>summary_query_engine = summary_index.as_query_engine(<br>    response_mode=&quot;tree_summarize&quot;,<br>    use_async=True,<br>)<br>vector_query_engine = vector_index.as_query_engine(similarity_top_k=3)</pre><p>5. Test the Query Engines</p><pre># Query 1<br>response = summary_query_engine.query(&quot;What is the summary of the document?&quot;)<br>print(str(response))<br><br># Query 2<br>response_query = vector_query_engine.query(&quot;What is analysis paralysis?&quot;)<br>print(str(response_query))</pre><pre># Output Query 1<br> The document contains excerpts from a podcast titled &#39;Episode 176 - Why Is It So Hard to Make Decisions?&#39; hosted by Angela Duckworth and Mike Maughan. The main topics discussed include the challenges associated with making decisions, particularly when faced with numerous options, leading to phenomena such as &#39;analysis paralysis.&#39; Key points involve insights from psychologists and economists like Herb Simon and Barry Schwartz, discussing concepts like &#39;maximizers vs. satisficers,&#39; the impact of excessive choices on mental health, and strategies to cope with indecision. Additionally, the text covers various contextual applications including purchasing decisions, relationship dynamics, and professional scenarios.<br></pre><pre># Output Query 2<br> Analysis paralysis refers to the situation where individuals are unable to make a decision due to excessive analysis and consideration of options.</pre><p>6. Define the Tools we are going to use for our Router</p><p>Below we define a query tool for each query engine. A query tool is essentially a query engine enhanced with additional metadata. This metadata includes a description specifying the types of questions the tool can answer, ensuring that each tool is optimised for its intended purpose.</p><pre>from llama_index.core.tools import QueryEngineTool<br><br><br>summary_tool = QueryEngineTool.from_defaults(<br>    query_engine=summary_query_engine,<br>    description=(<br>        &quot;Useful for summarisation questions related to No Stupid Questions podcast, episode Why Is It So Hard to Make Decisions?&quot;<br>    ),<br>)<br>vector_tool = QueryEngineTool.from_defaults(<br>    query_engine=vector_query_engine,<br>    description=(<br>        &quot;Useful for retrieving specific context and information from No Stupid Questions podcast, episode Why Is It So Hard to Make Decisions?&quot;<br>    ),<br>)</pre><p>7. Last step! Build Router Query Engine</p><p>There are several ways to build a query engine in LlamaIndex. In the example below, we use an LLMSingleSelector, which outputs a JSON that is parsed to query the corresponding indexes. To build the Router Query Engine, we also need to import RouteQueryEngine(), which takes as parameters the LLM selector and the summary and vector tools we defined earlier.</p><pre>from llama_index.core.query_engine.router_query_engine import RouterQueryEngine<br>from llama_index.core.selectors import LLMSingleSelector<br><br><br>query_engine = RouterQueryEngine(<br>    selector=LLMSingleSelector.from_defaults(),<br>    query_engine_tools=[<br>        summary_tool,<br>        vector_tool,<br>    ],<br>    verbose=True<br>)</pre><p>Let’s ask our Router Engines a couple of questions to help us make better decisions!</p><p>Let’s start with a summarisation question to get a snapshot of what Angela and Mike discussed in the show.</p><pre>response = query_engine.query(&quot;What is the summary of the document?&quot;)<br>print(response)</pre><pre>Output:</pre><pre>Selecting query engine 0: Choice 1 mentions being useful for summarisation questions..</pre><pre><br>The document contains excerpts from a podcast titled <br>&#39;Episode 176 - Why Is It So Hard to Make Decisions?&#39; hosted by Angela Duckworth and Mike Maughan. </pre><pre>The main topics discussed include the challenges associated with making decisions, particularly when faced with numerous options, leading to phenomena such as &#39;analysis paralysis.&#39; </pre><pre>Key points involve insights from psychologists and economists like Herb Simon and Barry Schwartz, discussing concepts like &#39;maximizers vs. satisficers,&#39; the impact of excessive choices on mental health, and strategies to cope with indecision. </pre><pre>Additionally, the text covers various contextual applications including purchasing decisions, relationship dynamics, and professional scenarios.</pre><p>In the output, we can see the reasoning of the model of why it picked this engine along with the response which looks pretty good!</p><p>The authors talk quite a bit about ‘analysis paralysis’. Let’s see what this means.</p><pre>response = query_engine.query(&quot;What is analysis paralysis as described by the authors?&quot;)<br>print(str(response))</pre><pre>Output:</pre><pre>Selecting query engine 1: Retrieving specific information about what analysis paralysis is would require detailed content from the podcast..  </pre><pre>Analysis paralysis refers to the situation where individuals are overwhelmed by numerous choices or options, leading to indecision and inaction despite thorough analysis.<br></pre><p>You’d think a Data Analyst or someone deep in the data would’ve snapped this up first, but it makes perfect sense! After all, it’s not just Data Analysts who make decisions all day long.</p><p>Let’s continue with a question to engage again the vector_tool.</p><pre>response = query_engine.query(&quot;What did Mike struggled with when trying to purchase a car&quot;)<br>print(str(response))</pre><pre>Output:<br><br>Selecting query engine 1: This option mentions retrieving specific <br>information which aligns well with finding out what Mike specifically <br>struggled with while purchasing a car..<br><br>Mike struggled with making a decision on purchasing a new car due to <br>overanalyzing various factors related to different car models.</pre><p>And it worked! It revealed why Mike had such a tough time choosing a car. I totally relate to his experience as I am such a maximiser. This reminds me of Chidi from <em>The Good Place</em> who was trying to maximise even the smallest decisions. In fact, that’s how Chidi ends up dying — he can’t decide between a donut and a cupcake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*_boMZmByZTy8zm8wI87F3g.png" /><figcaption>image source: <a href="https://tvgag.com/gag/ive-made-my-decision/">https://tvgag.com/gag/ive-made-my-decision/</a></figcaption></figure><p>Let’s now find out why is it so hard to make decisions based on what the authors discussed.</p><pre>response = query_engine.query(&quot;Why is it hard to make decisions?&quot;)<br>print(str(response))</pre><pre>Output:</pre><pre>Selecting query engine 0: This option specifically mentions being <br>useful for summarization questions about why making decisions can be <br>difficult..<br></pre><pre>Selecting query engine 1: <br>While this option refers to retrieving specific context and information, it does not directly mention summarising or explaining difficulties in decision-making..</pre><pre> <br>It is hard to make decisions primarily because of overwhelming options that may cause analysis paralysis, emotional considerations like fear of missing out (FOMO) or regret, limitations in human cognitive abilities to process large volumes of data efficiently, uncertainty about future outcomes, and high personal standards seeking perfect solutions. </pre><pre>Additionally, having a multitude of choices can overload our attention span, further complicating the decision-making process.</pre><p>In this scenario, we can see there is some confusion regarding the engine selection by the model, resulting in the selection of both engines. One thing we could do to address this is to tweak the description of the tools to clearly differentiate between the two. The response in this case though belongs to the vector_tool.</p><p>You can verify the response by running the following command to inspect the source and length of the nodes.</p><pre>print(response.source_nodes)<br>print(len(response.source_nodes))</pre><p>Lastly, let’s ask our Router Engine to summarise what we can all do to make better decisions!</p><pre>response = query_engine.query(&quot;summarise what we can do to make <br>better decisions?&quot;)<br>print(str(response))</pre><pre>Output:</pre><pre>Selecting query engine 0: This option specifically mentions being useful for summarisation questions..</pre><pre>1. **Understand the Limits**: Recognize that humans have limited capacity to process vast amounts of information. Simplification is necessary despite potential errors.</pre><pre>2. **Reduce Options**: Too many choices can overwhelm; aim for a moderate number rather than infinite options.</pre><pre>3. **Use Trustworthy Advice**: Copying reliable individuals or seeking expert opinions can simplify complex decisions.</pre><pre>4. **Balance Assessment and Action**: Know when to gather information and when to act upon it. Avoid prolonged indecision.</pre><pre>5. **Distinguish Between One-Way and Two-Way Doors**: <br>Identify reversible vs irreversible decisions to determine urgency and importance.</pre><p>In this article, we developed a simple Router Query Engine with LlamaIndex and Watsonx to summarise and retrieve information on making better decisions. Mistral Large 2 performed admirably, generating outputs effectively with minimal prompting. We discovered that providing clear, distinct descriptions of the Router’s tools is essential for the model to select the desired one. This is just a tiny demonstration of what we can achieve with Agentic AI — the Router can be expanded to include calling functions, APIs, or other data retrievers.</p><p>Plus as a bonus, we learned several strategies for improving decision-making such as: simplifying options by reducing them, seeking out expertise, balancing assessment with action, and distinguishing between reversible and irreversible decisions to establish their urgency.</p><p>Thank you for reading!</p><p><strong><em>PS: If you enjoyed the read, show some love with a few claps below </em></strong>❤️</p><p><a href="https://www.linkedin.com/in/madalina-lupu/"><strong><em>Find me on LinkedIn</em></strong></a><strong><em>!</em></strong></p><h3>References:</h3><p>Building Agentic AI Applications with LlamaIndex: <a href="https://www.deeplearning.ai/short-courses/building-agentic-rag-with-llamaindex/">https://www.deeplearning.ai/short-courses/building-agentic-rag-with-llamaindex/</a></p><p>LlamaIndex with Watsonx: <a href="https://docs.llamaindex.ai/en/stable/examples/llm/ibm_watsonx/">https://docs.llamaindex.ai/en/stable/examples/llm/ibm_watsonx/</a></p><p>Watsonx: <a href="https://www.ibm.com/watsonx">https://www.ibm.com/watsonx</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c141896e1e49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Agentic AI Recipe]]></title>
            <link>https://medium.com/@madalina.lupu.d/the-agentic-ai-recipe-5b26de148d89?source=rss-d276f184cbd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b26de148d89</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[compound-ai-system]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[llm-agent]]></category>
            <dc:creator><![CDATA[Maddie Lupu]]></dc:creator>
            <pubDate>Fri, 02 Aug 2024 08:05:40 GMT</pubDate>
            <atom:updated>2024-08-02T08:05:40.402Z</atom:updated>
            <content:encoded><![CDATA[<h4>From Fixed LLMS Flows to Autonomous AI Agents</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WxDeafvdUCTJoBefmnkBeg.jpeg" /></figure><p>Ever since I transitioned from my previous Data Scientist role to AI Engineer last year, Retrieval-Augmented Generation (RAG) has quickly become my go-to technique — you could call it my little AI magic trick.</p><blockquote>Grab the knowledge base, ground your LLM in it, give it as context to your LLM, and voilà, you get a relevant answer to your question. It’s the most classic input-output engine, quoting Rihanna “shining bright like a diamond” without changing the model’s underlying layers.</blockquote><p>But does a simple RAG approach fully harness the reasoning capabilities of LLMs or make customers leap out of their seats, saying, ‘Yes, I’m ready to upgrade to Generative AI, and it’s worth the investment!?’</p><blockquote>The answer is more nuanced than a simple yes or no…</blockquote><p>While RAG is a powerful tool, it’s just one piece of the puzzle in the broader landscape of AI capabilities. Customers don’t want just a question-and-answer machine — input in, output out. They want an AI that gets things done: submitting holiday requests, booking flights, checking statuses, retrieving data. This requires an AI agent that not only provides answers but also interacts with other systems or APIs to complete tasks for you.</p><blockquote>🪄That’s the magic of Agentic AI! 🪄</blockquote><p>Instead of spoon-feeding the LLM with instructions on how to get things done, we involve the LLM in the decision-making and reasoning process, making it more autonomous. This concept is known in research as a Compound AI System.</p><p>A Compound AI System solves AI tasks by orchestrating multiple interacting components. This includes chaining together model calls, using external tools, and incorporating information retrieval techniques. Despite the rapid scaling of individual AI models, Compound Systems are increasingly demonstrating state-of-the-art performance across a wide range of applications.</p><p>Recent research from Berkeley Artificial Intelligence Research (BAIR) indicates a move away from solely focusing on model size towards the development of Compound Systems. These systems combine multiple components to achieve state-of-the-art results. This trend is echoed in the industry, with Databricks reporting that a significant portion of LLM applications leverage Retrieval Augmented Generation (RAG) and or multi-step chains.</p><p>Even researchers who used to report results from a single LLM call, now they are reporting results from complex inference strategies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5s0iS-LUjYUCG39FhxrgUA.png" /><figcaption>Source: BAIR, The Shift from Models to Compound AI Systems</figcaption></figure><p>In the industry, Microsoft showcased a chaining strategy that outperformed GPT-4 by 9% on medical exams. Google’s Gemini launch showcased impressive MMLU benchmark results achieved through a COT@32 inference strategy, essentially querying the model 32 times. This approach has sparked controversy, as critics question the fairness of comparing it to the single LLM call utilised by GPT-4.</p><h3>What drives Agentic AI?</h3><p>LLMs have tremendous reasoning capabilities, and these are only getting sharper as they grow — think of parameters as memory. They also have the nifty ability to call tools. By instructing the model to think step by step, it can create a plan and access a specific tool for each part of that plan.</p><p>Your model gains more autonomy in solving problems because you’re no longer prescribing every step. Instead of instructing your model to take the user query, run it through a search, retrieve the context, and then feed it back to generate a response, the AI agent now figures out this path on its own. This shift transforms rigid, fixed flows into flexible, adaptive ones, think Elastigirl from The Incredibles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*CO05GrJbqovQxLEnDeFIbg.png" /><figcaption><strong>Elastigirl </strong><a href="https://www.disney.co.uk/movies/incredibles-2/meet-the-characters">Incredibles 2</a></figcaption></figure><p>This new paradigm of Compound AI Systems opens many design questions but promises AI results that can be achieved through clever engineering, not just scaling up training.</p><h4>What makes Agentic AI valuable?</h4><ul><li>Certain tasks are inherently better suited for improvement through system design rather than solely relying on model training. While LLMs can enhance accuracy, building a compound system tailored to a specific task often yields a higher return on investment.</li><li>Unlike static ML models constrained by their training data, Agentic AI systems offer dynamic capabilities. By combining models with other components like search, retrieval, or API calls, we can create more adaptable and versatile solutions.</li><li>Agentic AI also enhances control and trust in AI outputs. Neural networks, despite training, can still produce hallucinations. An Agentic System allows for filtering and controlling model behaviour. Additionally, incorporating search functionality can boost trust by providing citations and enabling automatic verification of information.</li></ul><h3>Is simple RAG gone?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*uTxOGMrwG8ZweanaETHt7g.png" /></figure><blockquote>The short answer is NO.</blockquote><p>RAG is far from obsolete. In fact, both RAG and programmatic (or Agentic AI) approaches can complement each other effectively. For problems with well-defined solutions, RAG often provides a cost-efficient path. However, when exploring multiple potential solutions or addressing complex scenarios, Agentic AI shines brighter. The optimal strategy lies in carefully selecting the approach that best aligns with the problem while implementing robust safeguards.</p><h3>Agentic AI Challenges</h3><p>Challenges remain, particularly regarding the security and designing and optimisation of these AI Compound Systems.</p><p>Prompt injection poses a critical security risk. Rigorous safeguards must be integrated into the LLM’s decision-making processes to mitigate this threat. Additionally, the dynamic nature of API code generation introduces further vulnerabilities. To ensure responsible development, a human-in-the-loop approach is essential during the early stages, empowering the agent to seek human intervention when necessary.</p><p>Another challenge lies in the optimal design of interacting components, which can include various retrievers, LLM calls, or plugins. Determining the ideal allocation of resources is complex: should the focus be on optimising LLM response quality or accelerating retrieval times? This intricate balancing act represents a new research area.</p><p>Finally, the multi-step nature of these systems significantly complicates ML operations. Effectively logging, analysing, and debugging complex AI system traces is a big challenge. Developing robust tools and methodologies to streamline this process is essential for the adoption of Agentic AI.</p><p>Thank you for reading!</p><p><em>Stay tuned for Agentic AI Part 2, where I’ll demonstrate how to build a simple Router Engine using Watsonx.</em></p><p><strong><em>PS: If you enjoyed the read, show some love with a few claps below </em></strong>❤️</p><p><a href="https://www.linkedin.com/in/madalina-lupu/"><strong><em>Find me on LinkedIn</em></strong></a><strong><em>!</em></strong></p><h3>References</h3><p>The Shift from Models to Compound AI Systems: <a href="https://bair.berkeley.edu/blog/2024/02/18/compound-ai-systems/">https://bair.berkeley.edu/blog/2024/02/18/compound-ai-systems/</a></p><p>An LLM Compiler for Parallel Function Calling: <a href="https://arxiv.org/pdf/2312.04511">https://arxiv.org/pdf/2312.04511</a></p><p>AI Agents : <a href="https://www.youtube.com/watch?v=G8lnNR1-rsw&amp;list=PLOspHqNVtKADvnJYHm3HButDlWykOTzlP&amp;index=3">https://www.youtube.com/watch?v=G8lnNR1-rsw&amp;list=PLOspHqNVtKADvnJYHm3HButDlWykOTzlP&amp;index=3</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b26de148d89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Reward Hacking and Constitutional AI?]]></title>
            <link>https://medium.com/@madalina.lupu.d/what-is-reward-hacking-and-constitutional-ai-4d010273e499?source=rss-d276f184cbd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d010273e499</guid>
            <category><![CDATA[reward-hacking]]></category>
            <category><![CDATA[constitutional-ai]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Maddie Lupu]]></dc:creator>
            <pubDate>Thu, 06 Jun 2024 08:11:00 GMT</pubDate>
            <atom:updated>2024-06-30T18:30:46.906Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>AI Learns Best with Rewards Part 2</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*nhoOieTcwroEHQCakPrVRQ.png" /><figcaption>source: Wikimedia Commons, Alexander Hamilton making the first draft of the Constitution for the United States 1787</figcaption></figure><p>In my <a href="https://medium.com/@madalina.lupu.d/align-llms-with-reinforcement-learning-from-human-feedback-595d61f160d5">previous article</a> I discuss Reinforcement Learning from Human Feedback to align<a href="https://medium.com/@madalina.lupu.d/the-building-blocks-of-transformers-2b46057c0eb1"> Large Language Models (LLMs)</a> with human preferences.</p><p>Here is a quick recap of the process:</p><ul><li>choose an instruct LLM to generate completions based on a prompt</li><li>feed it’s completions into a reward model</li><li>the reward model assigns a reward score based on a pre-defined metric such as helpfulness or harmlessness</li><li>the reward is then fed into a Reinforcement Learning algorithm which adjusts the weights of the LLM to reflect your preferences.</li></ul><p>One thing that can happen during this process is reward hacking and if you thought about cheating, that’s precisely what it is!</p><h3>Reward Hacking</h3><p>How could it even happen, how can AI cheat?</p><blockquote>The agent, determined to be a top performer student, might take some clever shortcuts during training to maximise the rewards, even if they’re a bit off-topic…</blockquote><p>Continuing the book review example I started in my previous article, let’s say that your goal is to detoxify your model. You have already trained a reward model that will classify model completions as toxic or non-toxic. You select a prompt from your training data and pass it to your instruct model which generates a completion. As the policy tries to optimise the reward, it can diverge too much from the initial result, like in the below example where the model quickly diverges from a toxic response to a non toxic but useless one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*lDHF7RJfbHAfKsZxGfZGAQ@2x.jpeg" /></figure><p>Now, technically, the policy achieved its objective. It transformed a toxic response into a non-toxic one. But… is “were the most beautiful characters” a particularly helpful or insightful review? Not quite.</p><p>This scenario highlights the challenges of reward hacking in reinforcement learning. We want the policy to learn the right behaviours, but sometimes, it prioritises the reward signal over the actual meaning or quality of the output.</p><h4>How to prevent reward hacking?</h4><p>Penalise the model whenever it generates language that deviates too far from the initial response. To achieve this, you’ll need a metric of course!✨</p><h4><strong><em>Kullback-Leibler Divergence (KL Divergence)</em></strong></h4><p>is a popular metric often used with Reinforcement Learning Algorithms like Proximal Policy Optimisation (PPO) which compares the probability distributions of the initial and newly generated responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLhGwK7YRRVdTZmwYioxTA.png" /><figcaption>Little Prince — a boa sneak swallowed an elephant</figcaption></figure><p>KL Divergence plays a crucial role in guiding the optimisation process to ensure that the updated policy does not deviate too far (e.g., exceeding a predefined threshold) from the initial policy.</p><blockquote>KL Divergence measures the average difference in information needed when using the original policy to encode samples from the new proposed policy. The purpose here is to keep surprises to a minimum and prevent drastic changes that might hinder the learning process.</blockquote><p>Think of this process like tackling a new language.</p><p>Imagine you’re learning a new language. Your initial understanding (the original policy) is like having basic grammar and vocabulary understanding. Now, you’re trying a new learning approach (the new proposed policy) — maybe focusing on advanced grammar or slang. Ideally, this new approach builds upon your existing knowledge. Just like learning new vocabulary or slang with familiar grammar rules makes things easier, a good new policy should help you grasp new concepts by leveraging what you already know. This smooths the learning process and allows the model to adapt effectively.</p><h4>KL Divergence in practice</h4><p>One way to apply KL Divergence to compare the initial output with the newly generated one is to use 2 LLMs. Here goes the classic drill, freeze the initial model’s weights, so these are not updated in the RL process and create a separate copy of it to update. But is this efficient? If you have read my previous article on <a href="https://medium.com/@madalina.lupu.d/sharpen-your-llms-with-efficient-fine-tuning-techniques-1ec7def74916">efficient fine-tuning methods</a>, you would quickly say NO.</p><p>This process can get quite expensive, so instead of working with two complete copies, you can use <a href="https://medium.com/@madalina.lupu.d/sharpen-your-llms-with-efficient-fine-tuning-techniques-1ec7def74916"><em>PEFT</em></a> to only update a set of the model’s weights, rather than updating all the parameters. Let’s see a picture of the whole process to illustrate it more clearly and gain intuition over the high level process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CgICpmabyzemMNLNN6waGg.png" /><figcaption>source: deeplearning.ai</figcaption></figure><p>One challenge with RLHF is that it can create assistants that prioritise helpfulness above anything else. They might provide misleading or even harmful information in their eagerness to be helpful. On the other hand, RLHF can also lead to assistants overly focused on avoiding harm that they become frustratingly evasive. These “evasive assistants” dodge tricky questions by simply stating “I cannot answer,” without providing any explanation leaving users frustrated. Constitutional AI aims to tackle these shortcomings and also remove human bottlenecks associated with RLHF.</p><h3>Constitutional AI (CAI)</h3><p>First proposed in 2022 by Anthropic, Constitutional AI aims to replace Reinforcement Learning from Human Feedback (RLHF). This approach removes the need for humans to directly review the model’s outputs. Human involvement focuses only on defining the principles and instructions the model should adhere to in its completions.</p><h4>CAI Motivations</h4><p>Beyond scaling supervision and eliminating human bottlenecks in traditional Reinforcement Learning, Constitutional AI has two additional motivations:</p><ol><li>Enhancing assistant evasiveness for challenging questions and training AI assistants to gracefully handle questions they can’t answer or shouldn’t answer.</li><li>Increasing transparency in the principles governing AI to make the decision-making process of AI models more understandable to humans.</li></ol><p>Constitutional AI provides a list of short instructions or principles to govern models’ behaviour and scale human feedback through model self-improvement and supervision.</p><p>Anthropic’s research paper offers a set of Constitutional AI principles that can serve as a blueprint for anyone developing ethical AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*R_CSe1b2pziN8W8UXaboIQ@2x.jpeg" /><figcaption>Constitutional AI Principles — Antrophic paper</figcaption></figure><h4>CAI in practice</h4><p>The process of Constitutional AI involves both a supervised learning and reinforcement learning phase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*BVXuBmt0v5wxcVwsHWZW3w@2x.jpeg" /><figcaption>source: Antrophic paper</figcaption></figure><h4><strong>Supervised Learning stage</strong></h4><h4>Red Teaming — Critique — Revision</h4><p>The first stage uses a security practice called Red Teaming. Here, the AI assistant, initially trained for helpfulness, is exposed to prompts designed to elicit harmful responses. These initial responses are typically quite harmful. The model is then asked to evaluate its own response against the principles outlined in the constitution. It then revises the original response based on this self-critique. This process is repeated iteratively, with the model being presented with randomly selected principles from the constitution to guide its revisions. Once complete, we fine-tune a pre-trained language model using supervised learning with the final revised responses as training data. Here is an example of Red Teaming and self-critique for a harmful prompt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*Vr6aP_Fg2OqKlQvMCNAvwg@2x.jpeg" /><figcaption>source: Constitutional AI paper</figcaption></figure><h4>Reinforcement Learning stage</h4><h4>Comparison — Preference Model — Reinforcement Learning</h4><p>The second stage draws inspiration from Reinforcement Learning from Human Feedback (RLHF). However, instead of relying on human input to assess harmlessness, the model leverages its own feedback mechanism. This means the AI evaluates its responses against the predefined constitutional principles you establish.</p><p>The AI assistant trained earlier generates a pair of responses for each harmful prompt. We then combine each prompt with the generated completions to pair them into a multiple choice question where we ask the model to rank the responses according to a certain constitutional principle. This creates a dataset of AI-generated responses that reflects its understanding of the principles. To this data, we add human labels for helpfulness to train a hybrid AI/human based reward model just as in regular RLHF. This preference model assigns a reward to any given completion. Finally, the supervised model from the first stage undergoes further refinement (fine-tuning) using reinforcement learning resulting in a policy trained Reinforcement Learning from AI.</p><p>Thank you for reading!</p><p><strong><em>PS: If you enjoyed the read, show some love with a few claps below 👏👏👏</em></strong></p><p><a href="https://www.linkedin.com/in/madalina-lupu/"><strong><em>Find me on LinkedIn</em></strong></a><strong><em>!</em></strong></p><h3>References</h3><p><a href="https://arxiv.org/pdf/2212.08073">Constitutional AI: Harmlessness from AI Feedback</a></p><p><a href="https://www.coursera.org/learn/generative-ai-with-llms/home/module/3">Reward Hacking</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d010273e499" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Align LLMs with Reinforcement Learning from Human Feedback]]></title>
            <link>https://medium.com/@madalina.lupu.d/align-llms-with-reinforcement-learning-from-human-feedback-595d61f160d5?source=rss-d276f184cbd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/595d61f160d5</guid>
            <category><![CDATA[ai-ethics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Maddie Lupu]]></dc:creator>
            <pubDate>Thu, 16 May 2024 08:50:31 GMT</pubDate>
            <atom:updated>2024-05-16T08:51:09.515Z</atom:updated>
            <content:encoded><![CDATA[<h4>AI Learns Best with Rewards</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NmkSQjqQoEyzETg9" /><figcaption>Photo by <a href="https://unsplash.com/@ryanquintal?utm_source=medium&amp;utm_medium=referral">Ryan Quintal</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Large Language Models(LLMs) may behave badly. They can generate toxic, harmful or misleading information. This stems from the massive datasets they’re trained on, which may contain biases or imperfections.</p><p>Fine-Tuning LLMs with Reinforcement Learning acts as an etiquette coach, gently nudging LLMs towards human preferences and responsible information sharing.</p><h4>LLMs <strong>with a moral compass?</strong></h4><p>Not built-in, but definitely trainable!</p><blockquote><strong>Helpful, Honest and Harmless (HHH) </strong>is a set of principles researchers apply to align LLMs with human values.</blockquote><p>While regular Fine-Tuning aims to boost model performance, natural-sounding outputs, or prompt comprehension, Fine-Tuning with Reinforcement Learning takes a different approach. Here, the goal is to align the LLM with human preferences. This can mean either detoxifying its responses, removing aggressive language or preventing the spread of dangerous information.</p><h4>What does Reinforcement Learning have to do with dogs?</h4><p>Meet Caspy, my sister’s dog! 🐶</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*FXgvwtczJS4MpGnCSYjWUQ.png" /></figure><p>While mischievous and spoiled, he would sometimes entertain to do a trick for you. When Caspy does a good trick, like fetching a toy, we give him a treat or reward. That makes him want to do the trick again! Reinforcement learning is like that but for computers. When a computer program makes a good choice, it gets a <em>reward</em>. This helps the program learn what choices you value the most.</p><h4>How does Reinforcement Learning work in practice?</h4><p>Let’s see how Reinforcement Learning works in practice with a familiar example. Since I’ve been battling Tetris relentlessly lately, imagine we’re training the ultimate enemy — the CPU itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*WSo3RsFVxZkiJ2I9XZOH0g@2x.jpeg" /><figcaption>adapted by the author based on deeplearning.ai diagram</figcaption></figure><p>Meet Feli, my worthy Tetris rival. For those playing Tetris, you know Feli’s a total badass, but for the sake of this training exercise, let’s imagine she needs a little extra polish<strong>.</strong></p><blockquote>The objective in the illustrated diagram is for the agent Feli to win the Tetris game.</blockquote><p>In this scenario, Feli interacts with the Tetris game as the <strong><em>environment</em></strong>. Every possible move Feli can make is considered an <strong><em>action</em></strong>. The current arrangement of blocks on the screen defines the <strong><em>state</em></strong>. Feli attempts different moves and receives rewards based on their effectiveness — clearing lines, avoiding stacking chaos and round bridges. The series of actions and moves Feli will take is called <strong><em>Playout or Rollout.</em></strong> Through trial and error (dropping those Tetriminos), Feli learns a winning strategy.</p><blockquote>The goal of Reinforcement Learning is for the agent to learn the optimal policy within a specific environment. This policy is discovered iteratively through trial and error, with the goal of maximising the agent’s rewards.</blockquote><p>Now that we got the Reinforcement Learning jargon out of the way, let’s see this diagram adjusted for LLMs.</p><h3>Fine-Tuning LLMs with Reinforcement Learning from Human Feedback (RLHF)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*OhEc3nJzKqVRj2wBQLFYpA@2x.jpeg" /><figcaption>adapted by the author based on deeplearning.ai diagram</figcaption></figure><p>Let’s pick an Instruct model to Fine-Tune with RLHF as they can do well at general tasks. The <strong><em>agent</em></strong> policy that guides the actions is the LLM. Its <strong><em>objective</em></strong> is to generate text that’s aligned with human values (e.g., not toxic, informative, helpful).</p><p>The <strong><em>action</em></strong> the LLM can take can be a word, sentence or text chunk the LLM generates in response to a prompt.</p><p>The <strong><em>environment</em></strong> is the token vocabulary meaning all the possible words and sentences the model can choose from to complete the text.</p><p><strong><em>Current Context</em></strong> is the prompt text and the LLM’s internal state considering the probability of each token in the vocabulary. This influences the next action the LLM takes.</p><p><strong><em>Rewards</em></strong> are assigned based on how closely the completions align with human preferences. Unlike simpler tasks, the reward for LLMs is more complex.</p><p>In the diagram above, you probably noticed in the loop a <strong><em>reward model </em></strong>and a <strong><em>little lady</em></strong>.</p><blockquote>Ladies first, so let’s talk about the method for improving LLMs that involves human evaluation.</blockquote><p>Here, humans assess LLM outputs based on specific predefined metrics such as non toxicity. They can assign a simple binary score (0 or 1), thumb up or thumb down or ranks to indicate whether the output is problematic. This feedback is then used to iteratively adjust the LLM’s internal parameters to reflect the human feedback. Collecting ranks feedback is more rich and it offers more nuanced data than just collecting thumbs up or thumbs down. This can also balance bad labelling if the humans in the loop did not understand the task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*K-P3eUMuSidtqc-TxAlKhg@2x.jpeg" /></figure><p>In the above example we have 3 human labellers to evaluate the model responses with human feedback based on helpfulness where 1 is the best and 3 is the worse. The same completion is assigned to multiple human labellers to establish consensus and collect robust evaluations. The first completion <em>“UK weather tends to be rainy” </em>gets a <em>3</em> from the first and second labeller because it’s not that helpful and the last completion gets a 1 from both because it does suggest some alternatives and acknowledges the fact that the weather is bad.</p><p>The third one looks like they misunderstood the task as the ranks assigned seem to be the other way around. In the labelling process, it’s important labellers get clear instruction on how to evaluate the completion to ensure high data quality.</p><p>While gathering extensive human feedback can be a bottleneck, there’s a powerful alternative — reward models. These models can analyse LLM outputs and assess their alignment with human preferences, effectively overcoming the need for large-scale human evaluation.</p><h3>Reinforcement Learning with a Reward Model</h3><p>The reward model becomes a central component of the Reinforcement Learning process. It encodes all of the preferences that are learned from human feedback, and it plays a crucial role in how the model updates its weights over many iterations.</p><p>In this scenario, you still need <em>some</em> data — you can start with a few human labelled examples and train the secondary model using supervised ML to classify the outputs. Once trained you can use this reward model to asses the output of the LLM and assign a reward value which in turn is used to update the weights of the LLM and train a human aligned version.</p><p>Let’s get a glimpse of how that looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*AMy1yAtTBlTCDIbdxCadOA@2x.jpeg" /><figcaption>adapted by the author based on deeplearning.ai diagram</figcaption></figure><p>The objective in the above example is for the LLM to generate aligned text. The metric is helpfulness and each completion gets a reward value. In the above example “<em>the book was…” — </em>“<em>a waste of time”</em> completion gets a negative reward as it’s not that helpful and <em>“intuiting but slow”</em> gets a positive reward. The model’s weights are updated by a Reinforcement Algorithm to reflect this favourite response — let’s call this model an RL-updated LLM. The aim here is to iterate over this process and if going well, you should be seeing the rewards values given by the reward model increase.</p><p>You will iterate over this process until achieving a certain pre-defined threshold reward value or a certain number of iterations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*Ypvqx_Zboi2qX-tH40OmIA@2x.jpeg" /><figcaption>adapted by the author based on deeplearning.ai diagram</figcaption></figure><p>The above shows that the best acceptable answer has been reached in this case. For <em>“fascinating, starts slow but with an excellent plot twist” </em>the model got a reward of<strong> </strong>2.3 and the LLM parameters are updated to reflect this preference. The higher the reward, the better the completion is aligned with the defined metric. Proximal Policy Optimisation (PPO) is a popular and complex algorithm that can be used to update the model’s weights. Read more about PPO <a href="https://openai.com/index/openai-baselines-ppo/">here</a>. Now you have a Human-aligned LLM.🎉</p><h4>Closing words</h4><p>In this article we explored how RLHF is used to align LLMs with human preferences. This involves guiding LLMs according to the 3H principle — Honest, Harmless and Helpful. Just as dogs get treats when they do a good trick, LLMs are rewarded to generate more aligned responses. Reward Models offer a solution to the bottleneck of collecting human feedback, efficiently updating LLMs to reflect preferred responses. The potential for RLHF extends beyond LLM alignment. One application that I find particularly exciting is personalised training materials or even AI-powered tutors tailored to individual needs.</p><p>Thank you for reading!</p><p><strong><em>PS: If you enjoyed the read, show some love with a few claps below 👏👏👏</em></strong></p><p><a href="https://www.linkedin.com/in/madalina-lupu/"><strong><em>Find me on LinkedIn</em></strong></a><strong><em>!</em></strong></p><h4>References</h4><p><a href="https://arxiv.org/abs/1909.08593">Training a Helpful and Harmless Assistant with Reinforcement Learning from Human Feedback</a></p><p><a href="https://www.coursera.org/learn/generative-ai-with-llms/home/week/3">Reinforcement Learning with Human Feedback</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=595d61f160d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sharpen Your LLMs with Efficient Fine-Tuning Techniques]]></title>
            <link>https://medium.com/@madalina.lupu.d/sharpen-your-llms-with-efficient-fine-tuning-techniques-1ec7def74916?source=rss-d276f184cbd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ec7def74916</guid>
            <dc:creator><![CDATA[Maddie Lupu]]></dc:creator>
            <pubDate>Sun, 14 Apr 2024 15:45:35 GMT</pubDate>
            <atom:updated>2024-04-15T07:41:01.095Z</atom:updated>
            <content:encoded><![CDATA[<h4>Computational Efficient LLM Fine-Tuning Methods: LoRA, DoRA and ReFT</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0mmJ9Z_DAgXU2xLI" /><figcaption>Photo by <a href="https://unsplash.com/@jessbaileydesigns?utm_source=medium&amp;utm_medium=referral">Jess Bailey</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>/</figcaption></figure><p>Large Language Models(LLMs) can do surprisingly well wit<em>h zero shot inferenc</em>e. They can attempt solving problems without knowing the context of your task or how exactly the output should look like. It performs even better if you show what you expect from it with a few relevant examples. The latter technique is known as<em> few-shot inference or learning</em>.</p><p>Both of these methods involve interacting with the LLM through a prompt – an instruction message sent to the model which can be tweaked to optimise the LLM output. Known as <em>prompt engineering</em>, while powerful, this method has its limitations. Here are some key prompt engineering challenges:</p><ul><li>Limited context window — LLMs typically have a pre-defined context window. This means everything you throw at it in the input text needs to fit within this space.</li><li>Smaller models may struggle — Smaller LLMs might have less capacity to effectively process in-context examples and understand the desired output, especially for complex tasks.</li><li>Domain knowledge — If the task is highly specialised or niche, even multiple and diverse examples may not provide sufficient context for the model to perform well.</li></ul><p>Fortunately there are other methods practitioners can use to optimise and fine tune LLMs’ results!</p><h3>Full Parameter Fine-Tuning</h3><p>Full Parameter Fine-Tuning takes a pre-trained model and trains again all the model’s layers on a smaller, specific dataset with the goal to improve performance for a particular task.</p><p>We are going to be diving into several Fine-Tuning methods. To make things easier, let’s use an education analogy.</p><p>Imagine you want to become a Generative AI expert — Full Fine-Tuning would be like enrolling in a specialised Generative AI program with an extensive curriculum. It’s in-depth, but takes time and significant resources.</p><p>While Full Fine-Tuning can be performant, it comes with significant drawbacks.</p><p>Training all the model’s layers can become computationally expensive, especially for very large models. This can translate to longer training times and higher resource consumption. Catastrophic forgetting can occur during Full Fine-Tuning — in this scenario, the model forgets the general knowledge it learned during pre-training in favour of the new, specific task. This throws away the value of the pre-trained model.</p><p>Since all the model’s weights are updated during Full Fine-Tuning, a completely new copy of the model is created. This can significantly increase the storage requirements of the LLM.</p><p>Parameter-efficient fine-tuning(PEFT) techniques offer an effective alternative for adapting LLMs. These methods can achieve results as good as, or even better than, Full Fine-Tuning, while keeping costs down.</p><h3>What is PEFT?</h3><p>Unlike Full Fine-Tuning, Parameter-Efficient Fine-Tuning (PEFT) updates a limited subset of the model’s existing parameters, often in the self-attention layers, using a relatively small dataset of thousands of data points.</p><h4>What makes PEFT stand out?</h4><p>Reduced memory footprint — PEFT only updates a limited subset of the model’s parameters, while the original weights remain frozen. This significantly reduces the model’s memory requirements, making it easier to train and deploy on even single GPUs.</p><p>Faster training — with fewer parameters to train, PEFT can be performed on a single GPU. This avoids the need for expensive and complex distributed clusters of GPUs, leading to faster training times and lower overall costs.</p><p>Improved portability — PEFT’s smaller size makes it more portable across different hardware configurations. This is especially beneficial if you plan to fine-tune the model for multiple tasks.</p><h4>PEFT Methods</h4><p>There are certain variations of PEFT which include adjusting just a few layers or adding a small number of new parameters to fine tune only the new components. Here is an overview of PEFT Methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NKWwEuWytTKEZ7aP-rVfOA.png" /><figcaption>PEFT methods by the author</figcaption></figure><p><strong>Adapter</strong> based models train additional layers on top of the frozen pre-trained method. Since this PEFT method adds new components that cannot be easily added into existing models’ layers, makes it less efficient as it introduces an additional burden at inference time.</p><p><strong>Soft Prompts </strong>add randomly initialised soft tokens to the input prompt and train their embeddings while keeping the LLM weights frozen. The performance of this method is less optimal compared to other PEFT methods and comes with significant inference overhead.</p><p><strong>LoRA</strong> injects low-rank matrices to train and requires no additional overhead as the model’s weights can be easily added to the original layers.</p><p><strong>DoRA</strong> is a brand new method which refines LoRA’s low-rank adaptation by decomposing weights into magnitude and direction, allowing for more focused training compared to LoRA.</p><p><strong>Selective</strong> methods focus on a subset of the original LLM weights and retrains them. This method has shown mixed results in the past.</p><p>LoRA is one the most performant PEFT methods that’s been around for a while, so let’s do a dive in and see how it works!</p><h3>Low Rank Adaptation of LLM</h3><p>Back to becoming a Generative AI expert story, LoRA is like <a href="https://medium.com/@madalina.lupu.d/unlock-your-own-path-to-mastery-a-quick-dive-into-impactful-learning-techniques-072603b60847">learning</a> using flashcards. You focus on key concepts, making learning faster (faster training) and less resource-intensive (lower memory usage). However, there’s a risk you might miss crucial details.</p><h4>How to apply LoRA</h4><p>Let’s put things in perspective. Inside the traditional Transformer with dense layers, you have 2 kinds of neural networks: the self attention network and the feed forward network. The weights of these are learned during pre-training. Check below the <a href="https://medium.com/@madalina.lupu.d/the-building-blocks-of-transformers-2b46057c0eb1">Transformer architecture</a> for a refresher.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJEsgr6KjzLCeYziuWCfqw.png" /><figcaption>Transformers Architecture adapted by the author</figcaption></figure><p>After the Embedding vectors are created, these are fed into the self attention layers where attention scores are calculated. It turns out that applying LoRA just to the self-attention layers of the LLM works well enough to yield good results and save compute.</p><p>Essentially, you can apply it to the feed forward layer as well but since most of the parameters of the LLM are in the self-attention layer, you are going to get the biggest savings in trainable parameters by applying LoRA to these weights matrices.</p><p>LoRA can be applied to both the encoder and decoder. However, to illustrate its workings more clearly, let’s focus on the encoder component and develop an intuition of how LoRA is applied there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DZG-fBwBl-dVv-Jw-WXu-Q.png" /><figcaption>Add LoRA to the self-attention layer</figcaption></figure><h4>LoRA process high level</h4><blockquote>1. Freeze most of the original LLM weights</blockquote><blockquote>2. Inject 2 rank decomposition matrices</blockquote><blockquote>3. Train the weights of the smaller matrices</blockquote><p>Let’s take the base Transformer of dimensions <em>512 x 64</em> and illustrate how to apply low rank decomposition matrices to it.</p><p>In linear algebra, a low rank decomposition refers to expressing a matrix as a product of two smaller matrices. Let’s choose a rank of 8 to decompose the original transformer matrix which has 32.768 trainable parameters. If decomposed with a rank of 8, this results in only 4.608 trainable parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iAI4GpOKSj9XoUyNeoxYwA.png" /></figure><blockquote>Steps to update the model for inference</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cqx39FW9PIkNwzZWunXQkA.png" /></figure><p>The resulting model has the same number of parameters as the original one so there is no latency overhead.</p><p>An essential advantage of LoRA is that it’s flexible. Suppose you train a pair of LoRA matrices for a specific task A. To carry out inferences for this task, you multiply the matrices and add them to the frozen layers. You then replace these in the original model. If you have a Task B, you (can pretty much) repeat the same process. The memory required to store these LoRA matrices is very small and you can switch out the weights when you need them.</p><h4>How to choose the rank of a matrix?</h4><blockquote>The smaller the rank → the smaller the number of parameters -&gt; the bigger the savings</blockquote><p>In the paper that first introduced LoRA, Microsoft researchers found a plateau in the loss value for ranks greater than 16. See below rank performance across a set of metrics.</p><p>The authors suggest that a 4 to 32 rank range provides a good trade-off between reducing the number of trainable parameters and preserving performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6PXyL25aX0Msswaj_cz8hQ.png" /><figcaption>Source: LoRA paper</figcaption></figure><p>Fine tuning LLM with LoRA results in good enough performance to accept the efficiency and performance trade-off. Models fine tuned with LoRA show almost as good results as fully fine tuning.</p><p>For an even more memory-efficient and potentially device-agnostic approach, QLoRA takes LoRA’s adaptation a step further by leveraging Quantization. Explore more about QLoRA <a href="https://arxiv.org/pdf/2305.14314.pdf">here</a> and delve deeper into Quantization in my previous <a href="https://medium.com/@madalina.lupu.d/how-to-shrink-large-language-models-quantization-and-1-bit-llms-explained-c50c76df0b42">article</a>.</p><p><strong>Weight-Decomposed Low-Rank Adaptation (DoRA)</strong></p><p>One of the newly published methods in February this year is DoRA which builds upon LoRA by introducing a weight decomposition technique that separates the magnitude and direction of the weight updates. DoRA promises similar benefits to LoRA (faster training, lower memory usage) while potentially achieving better performance due to its finer-grained control over weight updates.</p><p>To build intuition of this method<strong>, </strong>back to becoming a Generative AI expert, this builds on LoRA by creating improved flashcards. Your flashcards have weights based on their importance to your subject enabling more nuanced and focused learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yv2GHx9D_8voFKMcKW3l9g.png" /><figcaption>How DoRA works. Source: DoRA research paper</figcaption></figure><h4>Representation Fine-tuning (ReFT)</h4><p>Representation Fine-tuning(ReFT) is a brand new method introduced this month which takes a new approach towards fine-tuning LLMs. Similar to other PEFT methods, this operates on a frozen base model and learns task-specific interventions on hidden representations.</p><p>Instead of adapting model’s weights, ReFT methods train interventions that manipulate a small fraction of the model representations in order to nudge the model to solve downstream tasks.</p><p>Low-rank Linear Subspace(LoReFT) is one instance of this methods and promises to be 10x — 50x more parameter efficient than prior PEFTs. This intervenes on hidden representations in the linear subspace by a low projection matrix. The intuition is that it performs interventions that lead the model to accurately make predictions for the task at hand.</p><p>LoReFT shows promising results outperforming PEFT methods on a set of tasks, while requiring a smaller number of parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*NT6_eDueXATv039CFJopfw@2x.jpeg" /><figcaption>LoReFT outperforming PEFT on several tasks. Source: ReFT paper</figcaption></figure><p>Back to becoming a Generative AI expert analogy. Chances are that you might have some knowledge of AI and you want to take it to another level, ReFT is like targeting weak spots in your AI knowledge, much like deliberate learning. This can result in faster and more focused learning than flashcards (LoRA/DoRA).</p><p>While promising, DoRA and ReFT are still under development, and more research is needed to fully understand its capabilities compared to other fine-tuning methods.</p><h3><strong>Closing words</strong></h3><p>In this article, we delved into various techniques for computationally efficient fine-tuning of large language models (LLMs). These techniques, including PEFT, LoRA, DoRA, and ReFT, aim to achieve good performance while minimising training time and memory usage.</p><p>To solidify our understanding of these techniques, let’s recap them quickly through the lens of the learning process to become a Generative AI expert:</p><ul><li><strong>Full Fine-Tuning —</strong> this is like enrolling to a comprehensive AI class and going through the entire curriculum. While in-depth, it takes a longer time and requires significant memory space.</li><li><strong>LoRA (Low-Rank Adaptation) —</strong> this is like learning using flashcards. You focus on key concepts, making learning faster (faster training) and less resource-intensive (lower memory usage). However, there’s a risk of missing crucial details.</li><li><strong>DoRA (Weight-Decomposed Low-Rank Adaptation) — </strong>this builds on LoRA by creating improved flashcards. Your flashcards have weights based on their importance to the AI subject enabling more nuanced and focused learning.</li><li><strong>ReFT</strong> (<strong>Representation efficient Fine-Tuning</strong>) — this takes a different approach and it’s like practicing deliberate learning on your weak spots. This can be even faster and potentially more effective than flashcards (LoRA) or improved flashcards (DoRA)</li></ul><p>Making LLMs accessible and efficient is an active area of research with methods being introduced at a fast pace such as DoRA and ReFT. These incremental and rapid innovations show great potential to democratize AI and make it accessible across a variety of industries.</p><p>Thank you for reading!</p><p>If you enjoyed it, show some love with a few claps below 👏</p><p><em>Find me on </em><a href="https://www.linkedin.com/in/madalina-lupu/"><em>LinkedIn</em></a><em>!</em></p><h3>References</h3><p>LoRA: <a href="https://arxiv.org/pdf/2106.09685.pdf">https://arxiv.org/pdf/2106.09685.pdf</a></p><p>DoRA: Weight-Decomposed Low-Rank Adaptation: <a href="https://arxiv.org/pdf/2402.09353.pdf">https://arxiv.org/pdf/2402.09353.pdf</a></p><p>ReFT: Representation Finetuning for Language Models: <a href="https://arxiv.org/pdf/2404.03592.pdf">https://arxiv.org/pdf/2404.03592.pdf</a></p><p>Generative AI with LLMs: <a href="https://www.coursera.org/learn/generative-ai-with-llms/home/week/2">https://www.coursera.org/learn/generative-ai-with-llms/home/week/2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ec7def74916" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why choose a Small Language Model?]]></title>
            <link>https://medium.com/@madalina.lupu.d/why-choose-a-small-language-model-8c9f8d92013d?source=rss-d276f184cbd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c9f8d92013d</guid>
            <category><![CDATA[small-language-model]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[efficiency]]></category>
            <dc:creator><![CDATA[Maddie Lupu]]></dc:creator>
            <pubDate>Sun, 31 Mar 2024 18:53:12 GMT</pubDate>
            <atom:updated>2024-04-02T15:13:31.455Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hPq5xhZQ4HEQsuL_" /><figcaption>Photo by <a href="https://unsplash.com/@johnmoeses?utm_source=medium&amp;utm_medium=referral">John Moeses Bauan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Problem</h3><p>The goal in <a href="https://medium.com/@madalina.lupu.d/the-building-blocks-of-transformers-2b46057c0eb1">pre-training any Large Language Model(LLM)</a> or training any good old Machine Learning model is to optimize model performance while minimising the loss function when making predictions. The loss function represents the difference between the actual values and the values your model predicted. Assuming your model is not overfitting, the smaller the loss, the better the model’s overall performance.</p><h4>Question</h4><p>Here is a question for you:</p><blockquote>Your LLM’s performance is decent but you have high standards you believe your model can achieve. How would you go about minimising that loss function?</blockquote><blockquote>A. Give your model more horse power — increase the compute power and the time you are going to train the model</blockquote><blockquote>B. Give your model more muscles — increase the model size or the model parameters</blockquote><blockquote>C. Give your model more training material — increase the size of the dataset</blockquote><p>The paper <strong>Scaling Laws for Neural Language Models</strong> shows that increasing model size, dataset size, and training compute all independently enhance performance.</p><blockquote>But what if you could only focus on one?</blockquote><p>I’d go for <strong><em>C </em></strong><em>— give your model more training material and increase the size of the dataset!</em><strong><em> </em></strong>Let me explain why by discussing these one by one.</p><h4>⚡Option A</h4><blockquote>A. Give your model more horse power — increase the compute power and the time you are going to train the model</blockquote><p>Think about the last project you worked on and how much leeway you had in terms of its timeline and resources. Chances are, timelines were tight and you might have even had to work under additional constraints. Similarly, when training LLMs, the time and budget allocated can be hard constraints set by the business, potentially making this option less favourable.</p><h4>💪 Option B</h4><blockquote>B. Give your model more muscles — increase the model size or the model parameters</blockquote><p>In the DeepMind paper <strong>Training Compute-Optimal Large Language Models </strong>(also known as the Chinchilla paper), the authors suggest that current big models might be over-parameterised and under-trained in terms of dataset size. For the past years, companies have been baking model after model, one bigger than the other — look at ChatGPT (175B parameters), Jurassic (178B parameters), or the massive Megatron-Turing NLG (530B parameters). But what’s the catch?</p><p>The drive to train larger and larger models has certainly contributed to improving the state of the art in many language tasks. Model’s parameters act like model’s memory and the higher their number, the higher the chances for the model to perform well across a downstream of tasks. Predictably, based on the <a href="https://crfm.stanford.edu/helm/lite/latest/">Stanford HELM evaluation </a>GPT-4 is the overall leading model across language tasks outperforming the rest of the models.</p><blockquote>Is bigger always the answer though?</blockquote><p>Generative AI or LLMs can boost productivity at scale. In organisations this can save a lot of money and time, leaving us — the humans spend our time making more informed decisions, fitting pieces together and focusing on the bigger picture. Essentially, doing more strategic thinking rather than operational tasks.</p><p>Organisations want solutions they can easily deploy to production and are cost and compute efficient. That’s where the true challenge of picking the right model lies. The cost of a very large model can easily go out of proportion. Maryam Ashoori Phd lays out which are the costs to run an LLM in production :</p><blockquote>- Inference cost — the cost of calling an LLM to generate a response</blockquote><blockquote>- Tuning cost — the cost of tuning an LLM to drive tailored pre-trained model responses</blockquote><blockquote>- Pre-training cost — the cost of training a new LLM from scratch</blockquote><blockquote>- Hosting cost — the cost of deploying and maintaining a model behind an API, supporting inference or tuning</blockquote><p>While not all of these costs apply universally (like pre-training, which depends on your specific use case), production costs for Generative AI can fluctuate based on your chosen task and how often you use the model. Each provider has their own LLM pricing, with larger models naturally being more expensive. These costs can quickly escalate, potentially breaking your bank — especially when considering the vast difference between models like those with 175B vs. 15B parameters. For a comprehensive cost analysis, I highly recommend reading the full article referenced at the bottom of this page.</p><h4>📖 Option C</h4><blockquote>C. Increase the size of the dataset</blockquote><p>Back to the Chinchilla paper mentioned above, the authors suggest that smaller models trained on more data could perform as well as large models if trained on larger datasets. But how do you determine the right amount of data?</p><blockquote>The authors show that the optimal training dataset size for a given model is about <strong>20 times larger</strong> than the number of parameters of the model.</blockquote><p>The Chinchilla model trained by Deepmind was trained optimally and the size of the dataset was <strong>1.4T</strong> and the number of parameters is <strong>70B</strong>. Llama-65B also follows a similar pattern, in contrast to GPT-3 or BLOOM models highlighted in red in the picture below. The Chinchilla model actually outperforms GPT-3 across a few downstream tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezLLIRYZcyFl0636yz30hw.png" /><figcaption>Source: deeplearning.ai</figcaption></figure><h3>The rise of Small Language Models (SLMs)</h3><blockquote>Pick me! I am small but fierce</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5F-po0lbBcUfaiti" /><figcaption>Photo by <a href="https://unsplash.com/@alvannee?utm_source=medium&amp;utm_medium=referral">Alvan Nee</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Small Language Models (SLMs) are similar in concept to Large Language Models (LLMs), but a key difference lies in the number of parameters they have. SLMs have fewer parameters, typically ranging from millions to a few billion.</blockquote><p>Nimble and specialised models could be the answer to many business problems. For fields like Medicine, Finance, or Law, where highly specialized language is used, a regular <em>good for every task</em> model might not be suitable. This specialized domain language may not exist in the public datasets used to train models like GPT-4, or the words might carry different meanings from everyday usage. This makes specialised models a better fit for these specific use cases.</p><p>Since the Chinchilla paper, many SLMs have emerged — Bloomberg (50B), <br>LLaMA (a collection of LLMs from 7B to 65B), IBM Granite(13B), Mistral(7B), and others. These offer greater efficiency and suitability for enterprise use while maintaining high performance standards. However, some challenges remain. For example, the Bloomberg finance model faced a lack of sufficient data to achieve optimal compute efficiency, forcing a compromise with a smaller dataset.</p><p>Unsurprisingly SLMs are not perfect and there are drawbacks one should consider. Let’s look into their benefits and shortcomings to get an intuition of what use cases these might be more suitable for.</p><h4>Benefits and shortcomings of Small Language Models</h4><h4>Benefits</h4><ul><li><strong>Efficient —</strong> SLMs are more nimble and require less computational power which makes them more efficient to deploy in production</li><li><strong>Cost-effective — </strong>Less parameters means that you need less resources to train, maintain and run an SLM compared to an LLM</li><li><strong>Specialised —</strong> SLMs can be trained on high quality datasets for specific domain tasks. This often leads to better performance within that niche</li><li><strong>Explainable —</strong> Because these are less complex and use more targeted data can offer more transparency into their outputs. Explainability is valued in most Enterprises especially in sensitive applications</li></ul><h4>Shortcomings</h4><ul><li><strong>Task-limited —</strong> Due to their specialised nature SLMs might struggle to perform as well on tasks outside their training domain. They lack the breadth of knowledge that LLMs possess</li><li><strong>Performance-limited —</strong> SLMs have a lower capacity for learning and understanding complex language patterns compared to larger models. This can lead to limitations in the types of tasks they can handle effectively</li><li><strong>Dataset-dependent — </strong>Smaller but less curated datasets can lead to less robust models as the performance of SLMs relies heavily on the quality and relevance of the data they are trained on</li></ul><h3>Closing Words</h3><p>In this article, we’ve explored ways to optimise LLM performance, including minimising loss functions and ensuring optimal training. We’ve also seen how Small Language Models are gaining ground, offering efficiency and adaptability that make them well-suited for specialised tasks. While selecting the ideal production model can be complex, especially with the costs of LLMs, the right choice can significantly boost productivity and reduce costs. On a separate but current note, I’m particularly excited about the potential of SLMs in the <a href="https://medium.com/@madalina.lupu.d/how-to-shrink-large-language-models-quantization-and-1-bit-llms-explained-c50c76df0b42">1-bit LLM era</a> and the innovative models that may emerge.</p><p>Enjoyed the read? Show some love with a few claps below 🙌</p><p><em>Find me on </em><a href="https://www.linkedin.com/in/madalina-lupu/"><em>LinkedIn</em></a><em>!</em></p><h3>References:</h3><p><a href="https://arxiv.org/pdf/2001.08361.pdf">Scaling law for neural language models</a></p><p><a href="https://arxiv.org/pdf/2203.15556.pdf">Training Compute-Optimal Large Language Models</a></p><p><a href="https://www.linkedin.com/pulse/decoding-true-cost-generative-ai-your-enterprise-maryam-ashoori-phd/?trackingId=RjN5QH7vSgWty4Lkg4fGGg%3D%3D">Decoding the True Cost of Generative AI for Your Enterprise</a></p><p><a href="https://www.coursera.org/learn/generative-ai-with-llms/lecture/SmRNp/scaling-laws-and-compute-optimal-models">Scaling laws and compute-optimal models</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c9f8d92013d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to shrink Large Language Models. Quantization and 1-bit LLMs explained]]></title>
            <link>https://medium.com/@madalina.lupu.d/how-to-shrink-large-language-models-quantization-and-1-bit-llms-explained-c50c76df0b42?source=rss-d276f184cbd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c50c76df0b42</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[quantization]]></category>
            <dc:creator><![CDATA[Maddie Lupu]]></dc:creator>
            <pubDate>Thu, 14 Mar 2024 15:29:48 GMT</pubDate>
            <atom:updated>2024-03-14T15:30:04.342Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i6VGnZhecCsFlSbvZzZ-fQ.png" /><figcaption>generated by the author with DALL-E</figcaption></figure><h3>The Memory Challenge</h3><p>It’s in their name: Large Language Models are LARGE, containing billions of parameters. Think of these parameters as the model’s memory, the greater their number, the better model’s potential performance. But this sheer size brings a big challenge — running out of memory while trying to train them. Indeed, LLMs demand tons of memory and computational power, and that’s just the tip of the iceberg.</p><p>Let’s do some quick math to develop an intuition of the problem:</p><ul><li>Let’s acknowledge that parameters take up space</li><li>A single parameter takes up typically 4 bytes as a 32-bit float</li><li>A billion parameters? That’s 4GB of GPU RAM just to store the model’s weights at full precision. This is already a lot of memory! 😱</li><li>Now consider the Adam optimizer, gradients, and everything else needed to actually train the beast. This can easily lead to 20 extra bytes of memory per model parameter as shown in the picture below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YpR4JT2uVOYIqGampOUa_A.png" /><figcaption>Source: deeplearning.ai</figcaption></figure><p>In fact, you’ll need roughly 6x the amount of GPU RAM compared to the model weights alone. So, for a 1 billion parameter model at full precision, get ready to spin 24GB of GPU RAM. 😵‍💫</p><blockquote>Reality Check</blockquote><p>To put things in perspective, the average computer has between 2 and 8GB GPU RAM. This makes training even moderately sized LLMs almost impossible on consumer hardware. And even powerful data centre equipment will struggle if you want to train everything on a single processor.</p><h3>Quantization</h3><p>What options do you have to reduce the memory required for training?</p><blockquote>✨ Quantization ✨</blockquote><p>One way to overcome the memory hurdle is to reduce the precision used to store model weights. Instead of the standard 32-bit floating-point format (FP32), you can use:</p><ul><li><strong>16-bit floating-point (FP16):</strong> cuts memory usage in half, often with minimal impact on accuracy.</li><li><strong>8-bit integers (INT8):</strong> provides even greater memory savings. However, can lead to significant accuracy loss.</li><li><strong>BFLOAT16:</strong> a 16-bit format with a similar range to FP32, offering a balance between memory efficiency and precision.</li></ul><p>This process is called <em>quantization</em>, and it works by statistically projecting the original 32-bit floating-point numbers into a lower-precision space. This is achieved using scaling factors calculated based on the range and distribution of the original 32-bit values.</p><blockquote>📚 <strong>Understanding Floating-Point Representation</strong></blockquote><p>Computers always have their own way with numbers, don’t they? These don’t store numbers exactly the way we write them but rather in 0 and 1 format, where 0 is for positive numbers and 1 is for negative numbers.</p><p>In floating-point formats, a number is broken down into:</p><ul><li><strong>Sign Bit:</strong> tells us if the number is positive or negative.</li><li><strong>Exponent Bits:</strong> like scientific notation, these control the overall scale of the number.</li><li><strong>Mantissa Bits:</strong> these hold the <em>digits</em> of the number, determining its precision.</li></ul><p>To understand how <em>quantization</em> works, let’s take an example and shrink Pi from 32-bit to 16-bit floating-point format.</p><blockquote><strong>Squeeze — FP32 to FP16</strong></blockquote><p>Noticeably, FP32 has more bits than FP16, hence it is more precise, as you can see in the picture below. To quantize Pi, we essentially squeeze its numerical representation into a smaller space. Imagine Pi shrinking slightly fitting into a smaller shape. This might cause it to lose its shape and round from 3.1415… to something like 3.1406…</p><p>We do lose a tiny bit of detail, but quantization frees up a lot of memory. This precision vs. memory trade-off is often acceptable when training LLMs, allowing to work with these huge models on more limited hardware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*He3T-em407M2Q6YEamrYPA.png" /><figcaption>Shrinking Pi from FP32 ro FP16. Source: deeplearning.ai</figcaption></figure><blockquote>The BFLOAT16 Squeeze — the better Squeeze 😎</blockquote><p>BFLOAT16 developed at Google Brain has become a popular choice in deep learning, powering the pre-training of LLMs like FLAN-T5. Think of it as a hybrid between FP16 and FP32. BFLOAT16 uses only 16 bits, like FP16, but keeps the full 8-bit exponent of FP32 as shown in the picture below. What’s the effect?</p><p>This maintains the wide dynamic range needed for complex models, while cutting down memory use and speeding up calculations. BFLOAT16 is not ideal for integer-heavy calculations but it does shine in deep learning which requires floating-point operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vvRy6jh3EsOttku-Nmycgg.png" /><figcaption>Shrinking Pi from FP32 to BFLOAT16. Source: deeplearning.ai</figcaption></figure><blockquote>INT8 — A squeeze to an OOMPA LOOMPA parameter?</blockquote><p>To draw a full picture, let’s see what happens when you quantize Pi from 32-bit into even lower precision 8-bit space. Imagine squeezing it from its spacious 32-bit space into a narrow 8-bit world. With just seven bits left to work with, INT8 gives us a tiny world of numbers from -128 to 127. Pi is going to be separated from its sibling decimals and become a plain 3. We now cut down the memory from 4 to 1 bytes, but obviously Pi is now tragically imprecise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mq5m_p6ZDZM_vu151YGdAw.png" /><figcaption>Shrinking Pi from FP32 ro INT8. Source: deeplearning.ai</figcaption></figure><h3>1-bit LLMs</h3><blockquote>A new scaling law 💥</blockquote><p>In the recent research paper <em>The Era of 1-bit LLMs </em>the authors introduced a promising approach for reducing the cost of LLMs even more while maintaining their performance.</p><p>What’s the catch? Vanilla LLMs are trained in 16-bit floating values (FP16 or BF16), and the heavy lifting happens at matrix multiplication. So, the vast computation cost comes from the floating-point addition and additional operation. In contrast, 1-bit LLMs involve only integer addition which saves ton of memory and money.</p><blockquote>The new girl — BitNet b1.58</blockquote><p>The paper introduces <strong>BitNet b1.58</strong> which as it’s name suggest takes 1.58 bytes per parameter. Mind you — that’s almost 2 bytes, not 1! but let’s go on. The authors added an additional value of 0 to the original 1-bit BitNet, resulting in 1.58 bits. A parameter or weight of the model is going to be represented by a ternary system which essentially means that it can take one of these 3 values {<em>-1, 0 and 1}.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sUHA8KiWfVClwTGQcaYIkA.png" /><figcaption>Multiplications are replaced with additions for BitNet. Source: <em>The Era of 1-bit LLMs paper</em></figcaption></figure><p>The results of this new variant look quite promising and the authors show how it matches the full-precision of FP16 or BF16 Transformer LLM in terms of both perplexity and end-task performance, while being significantly more cost-effective in terms of latency, memory, throughput, and energy consumption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vclkcnE5kfW5zNE7-45LEg.png" /><figcaption>Performance vs Cost BitNet b1.58 vs FP16/BP16. Source: <em>The Era of 1-bit LLMs paper</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vclkcnE5kfW5zNE7-45LEg.png" /></figure><p>To summarise<em>, The Era of 1-bit</em> <em>LLMs </em>paper defines a new scaling law and way to train new LLMs that are both high performant but also cost effective. Furthermore, it may drive the design of specific hardware optimized for 1-bit LLMs.</p><h3>Quick recap</h3><p>We have looked into the concept of quantization and why this is important allowing LLMs to be stored at lower precision while keeping high performance, making LLMs more cost efficient. <em>The Era of 1-bit LLMs </em>takes it to the extreme drastically reducing costs and resource requirements. This approach facilitates easier LLM deployment and calls for the development hardware tailored for the unique requirements of 1-bit LLMs.</p><p>Give yourself a pat on the back for reading!</p><p>Enjoyed the read? Show some love with a few claps below 🙌</p><h3>References</h3><ul><li>Generative AI: <a href="https://www.coursera.org/learn/generative-ai-with-llms">https://www.coursera.org/learn/generative-ai-with-llms</a></li><li>Era of 1-bit LLMs paper page: <a href="https://arxiv.org/abs/2402.17764">https://arxiv.org/abs/2402.17764</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c50c76df0b42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Building blocks of Transformers]]></title>
            <link>https://medium.com/@madalina.lupu.d/the-building-blocks-of-transformers-2b46057c0eb1?source=rss-d276f184cbd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b46057c0eb1</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[foundation-models]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[attention-mechanism]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Maddie Lupu]]></dc:creator>
            <pubDate>Wed, 28 Feb 2024 08:31:07 GMT</pubDate>
            <atom:updated>2024-04-13T13:53:23.552Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Building an intuitive understanding of the </strong>Transformer architecture and its major components</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9KnU5S9dnPiJQEy8wwHNXg.png" /><figcaption>credits to quantumdesign</figcaption></figure><p><em>Note: Images in this article are adapted from </em><a href="https://community.deeplearning.ai/t/genai-with-llms-lecture-notes/361913"><em>deeplearning.ai materials.</em></a><em> Original sources will be cited where applicable.</em></p><p>Deliberate focus and attention is key when it comes to studying and achieving complex goals. Similarly, Large Language Models achieve great results at <em>understanding</em> and responding to language thanks to their <em>attention</em> mechanism within the Transformer architecture. In this article, I am going to explore the mechanics of this architecture giving you an intuition of what’s happening under the hood.</p><p>Introduced in the landmark 2017 paper <a href="https://arxiv.org/abs/1706.03762"><em>Attention is All You Need</em></a>, the Transformer architecture revolutionised natural language processing, laying the groundwork for today’s advancements in Generative AI (Gen AI).</p><h3>Transformers vs Recurrent Neural Networks (RNNs)</h3><p>With all the hype around LLMs, one might think generative algorithms popped yesterday. Like any breakthrough, they built on years of work. Predecessors like RNNs paved the way. While powerful at the time, RNN-based models struggled remembering long chunks of text and needed tons of computing power to work well.</p><p>RNNs predict words one at a time, looking at what came just before. This works fine for short sentences, but fails over longer text. It’s like trying to review a whole book after reading only the final sentences — impossible to get the full picture!</p><p>RNNs tend to forget essential information if this appears early on in the text. This makes it hard for them to fully understand. Throw in a few homonyms — those deceptive words with multiple meanings — and things get truly confusing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TFpOOSQxgDlbnDN8b4CuXA.png" /><figcaption>Photo adapted by the author</figcaption></figure><h3>Attention</h3><p>Attention came to the rescue! Transformers use it to grasp how words relate to each other in a sentence, no matter how far apart these are. This makes Transformers better at getting the full picture. Besides— we are talking plural — there’s not just one, but many attention mechanisms. Because Transformers process words non-sequentially, they can run attention mechanisms in parallel on GPUs. This leads to faster training and response times compared to earlier models.</p><blockquote>Sentence Processing — RNNs vs Transformers</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQWyN2mvb9YWlxwZJatUeQ.png" /><figcaption>RNNs process words sequentially</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mN_y-PeK9m01urJtUEbQUg.png" /><figcaption>Transformers process words by analysing all the word relationships</figcaption></figure><p>Transformers use attention weights to create attention maps. These maps capture the relationship between words during the training phase on large amounts of text. This mechanism is called self-attention. This allows the model to focus on relevant connections within a sentence. For example, here’s how an attention map might look for the sentence above — notice the thicker lines representing stronger connections and thinner lines for weaker ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*5If4JTyyttnXby-MOqPx2w.png" /><figcaption>Attention map by the author</figcaption></figure><h3><strong>Architecture</strong></h3><p>Now that we have an intuition over the power of the attention mechanism, let’s dive into the broader Transformer architecture. It’s divided into two distinct components: the Encoder and Decoder. To help us visualise the concepts within the architecture, I’ll reference the simplified diagram from the original paper throughout this article (right hand side diagram).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jOIh9lgn2UQtBibufzyG-A.png" /><figcaption>Transformers architecture — Attention is all you need paper</figcaption></figure><p>Let’s uncover how this architecture works by analysing its key components.</p><h3><strong>Translate words to numbers </strong>— tokenise</h3><p>Machine Learning algorithms are big statistical calculators. They don’t understand words directly but numbers. To bridge that gap between language and numbers we need to use tokenisation. There are different ways to map words to numbers, but it’s important to use the method used to pre-train the model. This way, words become code numbers the model recognises from its own dictionary. On top of that, tokenisation helps the model figure out unseen words.</p><p>Notice in the picture below how the German words <em>Ich</em>, <em>mag</em> etc. in the sentence <em>Ich mag weiße Schokolade</em> have each been assigned unique token IDs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-Xg8IKHXV-8aXU4aAfFgw.png" /><figcaption>Words to tokens</figcaption></figure><h3>Tokens to vectors — embedding layer</h3><p>Next, pass the tokens to the embedding layer. This layer acts like a skilled librarian. Having spent years organising a huge library with multiple shelves, the librarian instinctively knows where to find related topics and books. The embedding layer works similarly, taking each token (a word or subword) and placing it within a high-dimensional space. Like the librarian’s carefully arranged shelves, words with similar meanings are <em>shelved</em> close together within this space. While it’s challenging for us to fully visualise this space, the original Transformer used vectors of length 512 to represent word positions while capturing their meaning. Notice in the picture below how each token is allocated a vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SN_8lWl_mqwg5bZcFsquvQ.png" /><figcaption>Each token id is assigned a multidimensional vector</figcaption></figure><p>To better grasp the embeddings concept, imagine a vector size of two to capture the relationship between words. Within this 2D space, word meanings would be plotted as points. Words with similar meanings, like <em>chocolate</em> and <em>cake</em> would be placed closer together than unrelated words like AI. To determine the similarity between two words, we can calculate the angle between their corresponding vectors. Smaller angles imply higher similarity, capturing shared context and meaning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oAh85d0T-2FfAIC1945ZEw.png" /><figcaption>Measure similarity between two words</figcaption></figure><h3>Positional Encoding</h3><p>Next, add positional encodings. These act like a ticketing machine, assigning each word a unique label that reveals its place in the sentence. Since Transformers process words simultaneously rather than sequentially, positional encodings are essential for maintaining word order and context within the sentence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqpfk6tQ1MfE6DkSwAw54A.png" /><figcaption>Adding positional embeddings to token embeddings</figcaption></figure><p>After summing up the token vectors and positional encodings, the resulting vectors are passed to the self-attention layer. Here the model analyses the relationship between tokens and capture dependencies. This layer enables the model to analyze how different words in the sequence relate to each other. For a translation task, it’s like having multiple language experts working together. One expert might focus on grammar, another on word order, and another on the overall meaning. The number of attention heads varies by model, with 12–100 being common.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4mfNtOVjCqT7Msw3dtr6kw.png" /><figcaption>Multi-headed self attention and attention maps</figcaption></figure><p>After calculating attention weights based on words relationship in a sentence, the model selectively emphasises the most relevant elements of the input. This refined representation of the data is then passed through a feed-forward neural network, which further transforms it. The network generates logits, which represent the model’s confidence scores for each word in its vocabulary. Finally, A softmax layer converts these logits into probabilities, revealing the likelihood of each word in the current context. The word with the highest probability is the model’s top prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*40QFvSAut9XaFDXbjJTT6w.png" /></figure><h3>Different Transformers Architectures</h3><p>As mentioned earlier, the Encoder and Decoder are two distinct components of the architecture. There are actually 3 common ways LLMs use these as shown in the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XwGWBvSs9fZdzsskIXouhQ.png" /><figcaption>Transformers architecture types by deeplearning.ai</figcaption></figure><ul><li><strong>Encoder-Only Models </strong>focus on understanding and representing the meaning of input text. They’re great for tasks like: sentiment analysis, entity extraction and text classification. A few model examples here: BERT, RoBERTa and DistilBERT</li><li><strong>Encoder-Decoder Models </strong>excel at transforming one sequence of information into another. Perfect for: translation, text summarisation, question and answering (q&amp;a). Examples<strong>:</strong> T5 and BART</li><li><strong>Decoder-Only Models </strong>generate text one word (or token) at a time. Great for: text generation, chatbots, language modelling and predicting the next word in a sequence. Examples: GPT models and Jurassic.</li></ul><h3>Encoder-Decoder example</h3><p>Now that you got a sense of how transformers use the Encoder and Decoder components, let’s take an example to illustrate what happens when we make inferences with an Encoder-Decoder model.</p><p>The Transformer architecture was actually originally designed for translation, so let’s translate the following German sentence to English: <em>Ich mag weiße Schokolade.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJEsgr6KjzLCeYziuWCfqw.png" /><figcaption>How transformers process words to make inferences</figcaption></figure><p>In the above diagram, the sentence is translated to token ids: <em>156, 780 ..,</em> then these are translated to vectors <em>x1, x2, ..</em> before they are fed into the self-attention layers. The outputs of the multi-headed attention layers pass through a feed-forward network. This data becomes the output of the Encoder. At this point, the encoder has created a deep representation of the input sentence’s structure and meaning.</p><p>This representation is inserted into the middle of the Decoder to influence the next token. The output of the decoder’s self-attention layers flows through the decoder feed-forward network and a final softmax output layer. The decoder then repeats this process until a stop sequence is reached, much like reaching the period at the end of a sentence. Finally, the final sequence of tokens is transformed back into words, and there you have your output:<em> I like white chocolate.</em></p><h3>Closing words</h3><p>In this article, we’ve discovered the remarkable power of the attention mechanism and how it revolutionised natural language processing. We have looked back at earlier models in Generative AI and their shortcomings and how Transformers helped overcome those. We’ve delved into the inner workings of the major Transformers components revealing how they collaborate to process information.</p><p>The future of Transformers extends far beyond language — their potential shines bright in computer vision, image classification, protein structure analysis, drug discovery, and countless other fields. As they continue to evolve, I have no doubts we will be seeing even more astonishing breakthroughs that will shape the way we interact with machines and the world at large.</p><p>Thank you for reading!</p><p>Enjoyed the read? Show some love with a few claps below 🙌</p><p><strong>References:</strong></p><p><a href="https://huggingface.co/learn/nlp-course/en/chapter1/4">Transformers architecture</a></p><p><a href="https://community.deeplearning.ai/t/genai-with-llms-lecture-notes/361913">Generative AI with LLMs</a></p><p><a href="https://arxiv.org/abs/1706.03762">Attention is all you need</a></p><p><a href="https://towardsdatascience.com/transformers-141e32e69591">How Transformers work</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b46057c0eb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge your AI learning or any learning with these creative techniques]]></title>
            <link>https://medium.com/@madalina.lupu.d/unlock-your-own-path-to-mastery-a-quick-dive-into-impactful-learning-techniques-072603b60847?source=rss-d276f184cbd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/072603b60847</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[mastery]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[learning-how-to-learn]]></category>
            <dc:creator><![CDATA[Maddie Lupu]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 08:28:17 GMT</pubDate>
            <atom:updated>2024-02-14T10:02:37.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hUPBdrRXfC_9JBvM" /><figcaption>Photo by <a href="https://unsplash.com/@dstudiobcn?utm_source=medium&amp;utm_medium=referral">Dstudio Bcn</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Keeping up with the latest on Generative AI and Large Language Models (LLMs) can feel overwhelming at times. From new research papers to complex-sounding techniques, it’s easy to feel lost. Yet making sense of these does not have to be a daunting endeavour.</p><p>As a self-taught AI thinker, I’m always on the hunt to accelerate my learning. A great source of inspiration recently came from Barbara Oakley’s book <em>A Mind for Numbers</em>. Now, I know it sounds focused on math and science, but I promise these learning techniques can help anyone untangle complex concepts of ALL kinds, not just numbers.</p><p>Let’s start with some of my favourites which include <strong><em>Chunking</em></strong>, <strong><em>Recall</em></strong>, and the use of <strong><em>Metaphors and Analogies</em></strong>.<strong> </strong>Yes, even math can be better understood with a little story mixed in. Let’s unpack these!</p><h3>Chunking — one at a time</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kRK_LsZaxS--9m_6" /><figcaption>Photo by <a href="https://unsplash.com/@ashkfor121?utm_source=medium&amp;utm_medium=referral">Ashkan Forouzani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Chunking can be used to break down big topics and concepts into bite sized information.</p><p>Here is how to form chunks:</p><ol><li>Focus your attention on the concept you want to study. Avoid <em>time confetti</em>, as Adam Grant calls it — those interruptions that break your concentration and disrupt your flow.</li><li>Understand the basic idea in its simplest form</li><li>Practice it in different contexts to get an intuition of when to apply it</li></ol><p>Let’s take an example. Perhaps you want to master the concept of LLMs. Well, this can involve a LOT. But what about you start with the mere concept of what a LLM is. The basic idea you might come up with is that LLMs are big statistical calculators that generate text based on probabilities. To practice this in different contexts you might want to step back a little and understand how they differ from their elder, popular sibling: Recurrent Neural Networks. Once you have mastered this chunk, you can move to your next chunk such as understanding how LLMs work or their architecture.</p><p>While our short-term memory may only hold about 4 chunks of information, those chunks can be surprisingly complex and interconnected. To build intuition for the things we learn, we need to shift these chunks from short-term to long-term memory. The more we practice, the deeper and stronger the neural pathways in our memories become, making them easier to recall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*hnDSK2AtZaltrjv8ARxn3w.png" /><figcaption>Forming chunks as illustrated in A mind for numbers. The more you practice, the firmer, darker and stronger the mental patterns become.</figcaption></figure><h3><strong>Recall — p</strong>ractice makes progress</h3><p>Bad news is that just rereading the material is unfortunately not enough for newly formed chunks to move from short-term to long-term memory.<strong> </strong>Think of short-term memory as a juggler keeping a few balls in the air at once. You can actively focus on a limited amount of information, but if you add too much or get distracted, things start to drop. Long-term memory is like a warehouse or RAM (Random Access Memory) that you can access anytime or <em>almost</em> <em>anytime</em>.</p><p>Illusion of competence is real. Just reviewing notes or a worked-out solution might trick you into feeling like you understand a concept. This might be amplified by <em>aha</em> moments, but this does not necessarily mean that you will be able to solve the problem in a different context. To combat the illusion of competence and truly grasp the material, make your learning more active.</p><p>Rehearsing is crucial to make information stick. Recall is one type of practice to make learning more effective. Recalling the key ideas by writing them down, talking to yourself or explaining these to someone is much more helpful. The trick here is to alternate focused and diffuse thinking. Focused thinking happens when you are deliberately working on a problem. Diffuse thinking happens when you relax your attention and let your mind wander. That’s why it’s important to take breaks or engage in low-intensity activities like exercising, walking, or napping to refresh your mind and enhance your learning. These breaks are going to allow your diffuse thinking to still work on the problem in the background and generate your best ideas.</p><p>Save the chunk — use spaced-out repetitions and don’t wait too long for the recall practice. When learning new concepts it’s a good rule of thumb to not let things go untouched for longer than a day. Otherwise, vampires will come by and suck the little chunk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*loVh-VUwjojR7MrbMOpU8Q.png" /><figcaption>if you don’t make a point of repeating what you want to remember, your ‘metabolic vampires’ can suck out the neural pattern related to that memory before it can strengthen or solidify. — Barbara Oakley</figcaption></figure><h3>Metaphors and Analogies — make it memorable</h3><p>Here is the catch — we are not built to memorise numbers nor complex concepts. Our memories are rather spacial and visual. Why — might you ask. Remember the last time you entered a room and you passively paid attention to your surroundings. You might still remember a lot of the objects and how they were placed. It is an evolutionary thing as you might have already anticipated. Our ancestors did not need to memorise numbers but they had to pay attention to their surroundings to figure out how to get back to their camp or home after coming back from hunting.</p><p>We can unlock this superpower through powerful or dare I suggest <em>silly</em> visualisations and metaphors. These might not be perfect and sometimes can take a lot of time to build, but they can make a world of a difference!</p><p>Let’s put this into practice. Imagine you want to memorise a linear function, f, defined by its slope (w), input variable (x), and y-intercept (b)</p><pre>f = wx + b</pre><p>To memorise this more efficiently, imagine in your mind’s eye a wise(w) letter X(x) drinking a bobba tea(b).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*8G60J5Xs9qZoT6acVuh5oA.png" /><figcaption>perhaps this X might not look that wise to you, but you get the point, sometimes a goofy image is all your brain needs to memorise abstract concepts</figcaption></figure><blockquote>Did you know Einstein’s theory of relativity did not particularly arise from his mathematical skills — he sometimes needed help from other mathematicians to make progress. Einstein had a great ability to pretend. He imagined himself as a photon and then imagined how a second photon might perceive him. What would the second photon see and feel?</blockquote><p>Let’s take another example, this architecture for fine tuning LLMs with Reinforcement Learning from Human Feedback (RLFH)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SfCslThmxjdUE0SPeiC6Gw.png" /><figcaption>RLHF by deeplearning.ai</figcaption></figure><p>At times, LLMs can generate toxic, harmful or unhelpful text. The objective of RLHF is to align LLMs with human preferences and values. The diagram depicts the agent, the LLM and its objective to generate aligned text. The environment is the current context window or the prompt space. The LLM examines the existing conversation (the state) to decide what to write next (the action). The model takes an action based on its statistical training representations to generate words. Humans examine the LLM completions and give a rank based on how well it aligns with the pre-agreed metric. For positive outputs, the LLM receives a reward, allowing the agent to learn and improve over time through the reward signal. In practice, a reward model trained on human judgments is used, but for now, we will focus on direct human evaluations.</p><p>Let’s work with an analogy to make this process more sticky. Imagine a young child learning what’s good and bad behaviour. This is similar to how a Large Language Model (LLM) starts out — exploratory and a little mischievous. The parent providing guidance is like the human feedback in the fine tuning process. Sharing a toy earns a smile, like a positive rating for a helpful LLM output. Hitting another child brings a frown and an explanation, mirroring negative feedback given to the LLM.</p><p>Over time, just like the child learns to understand why some actions get smiles and others don’t, the LLM starts figuring out which types of text are preferred by humans. With this understanding, it becomes more likely to produce human aligned and appropriate responses, much like the child chooses actions that get a positive reaction.</p><p>Metaphors and analogies can be super powerful not just for memorising. These can help overcoming the Einstellung effect which means accepting your first idea when solving a problem. This is rarely the best solution. My favourite part about using metaphors and analogies is that it makes you more creative in the process, while it helps you memorise better and explain concepts easier to others.</p><p>Whatever learning journey you’re on, embrace the Law of Serendipity and the power of perseverance. As Barbara Oakley states in her book:</p><blockquote>“Lady luck favours the one who tries”</blockquote><p>Whether you consider yourself a slow or a fast learner, perseverance is often more important than intelligence. Approaching material with a goal of truly understanding it creates a unique path to mastery.</p><p>The next time you’re wrestling with challenging concepts, long functions, or complex equations, try some of these techniques and observe how your learning progresses. You might be surprised!</p><p>Enjoyed the read? Show some love with a few claps below 🙌</p><p>📚Learn more below 📚</p><ul><li><a href="https://www.amazon.co.uk/Mind-Numbers-Science-Flunked-Algebra/dp/039916524X/ref=asc_df_039916524X/?tag=googshopuk-21&amp;linkCode=df0&amp;hvadid=310867999190&amp;hvpos=&amp;hvnetw=g&amp;hvrand=13736801887476738638&amp;hvpone=&amp;hvptwo=&amp;hvqmt=&amp;hvdev=c&amp;hvdvcmdl=&amp;hvlocint=&amp;hvlocphy=9045891&amp;hvtargid=pla-404584213199&amp;psc=1&amp;mcid=c871b45e9c623343b2fbc3773c51c631&amp;th=1&amp;psc=1">A mind for numbers book</a></li><li><a href="https://www.coursera.org/learn/learning-how-to-learn">Learning how to learn</a></li><li><a href="https://www.deeplearning.ai/courses/generative-ai-with-llms/">Generative AI with LLMs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=072603b60847" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>