<?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 Syed Hasan on Medium]]></title>
        <description><![CDATA[Stories by Syed Hasan on Medium]]></description>
        <link>https://medium.com/@syed_hasan?source=rss-2a79006f7e86------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Za6OCYejpTCbg8cRwVLw_Q.png</url>
            <title>Stories by Syed Hasan on Medium</title>
            <link>https://medium.com/@syed_hasan?source=rss-2a79006f7e86------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 01:28:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@syed_hasan/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[DAPO (Decoupled Clip and Dynamic sAmpling Policy Optimization): GRPO on steroids]]></title>
            <link>https://medium.com/@syed_hasan/dapo-decoupled-clip-and-dynamic-sampling-policy-optimization-grpo-on-steroids-9c571a0536f3?source=rss-2a79006f7e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c571a0536f3</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[policy-optimization]]></category>
            <category><![CDATA[dapo]]></category>
            <category><![CDATA[grpo]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Syed Hasan]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 19:08:41 GMT</pubDate>
            <atom:updated>2025-03-24T19:08:41.817Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uEW2Yx83-QDUI64wfAQutg.jpeg" /><figcaption>Image by BING</figcaption></figure><h3>1. Introduction</h3><p>Large language models (LLMs) have come a long way in their ability to generate human-like text, but when it comes to deep reasoning, and logical consistency, they’ve fallen short. The shift from traditional supervised learning to reinforcement learning (RL) has been a game-changer, giving models a way to learn from feedback and continuously refine their responses. However, not all RL approaches are created equal.</p><p>At first, models were trained using <strong>Supervised Fine-Tuning (SFT), </strong>essentially learning from a massive dataset of human-written examples. This worked well for basic language understanding, but it had a major flaw: once trained, the model couldn’t easily correct its mistakes. That’s where <strong>Reinforcement Learning from Human Feedback (RLHF)</strong> stepped in.</p><h4>The Rise of RLHF and Proximal Policy Optimization (PPO)</h4><p>RLHF introduced a way for models to learn not just from static examples but from <strong>human preferences</strong>. Instead of simply mimicking past text, models could be guided toward responses that were more helpful, accurate, and aligned with human judgment. OpenAI’s ChatGPT and similar models leveraged RLHF extensively.</p><p>But RLHF had its own problems. Human feedback was expensive, slow, and sometimes inconsistent. Worse, <strong>it didn’t always scale well for complex reasoning tasks, </strong>especially when models needed to solve multi-step problems where errors in early steps could derail the entire answer. To stabilize training and make RLHF more effective, researchers turned to <strong>Proximal Policy Optimization (PPO)</strong>, a technique that carefully regulates how much a model’s behavior can change in each training step.</p><h4>GRPO and DAPO as RL Approaches</h4><p>Scaling large language models (LLMs) is an incredibly resource-intensive process. As models grow in size, so do the computational costs, training times, and the complexity of reinforcement learning (RL) techniques needed to optimize their performance.</p><h4>Key Challenges in Scaling LLM Training</h4><ul><li><strong>Computational Costs &amp; Resource Constraints</strong><br>Training state-of-the-art models like GPT-4 or Qwen2.5-32B requires massive GPU clusters, leading to high energy consumption and financial costs. Traditional RL methods, such as RLHF (Reinforcement Learning from Human Feedback), introduce additional inefficiencies by relying on costly human-labeled data.</li><li><strong>Long-Horizon Reasoning</strong><br>Many RL techniques struggle with multi-step reasoning, where an error in an early step can propagate through the sequence, leading to incorrect conclusions.</li><li><strong>Optimizing for Diversity vs. Stability</strong><br>Policy optimization techniques often face a trade-off between <strong>exploring diverse responses</strong> and <strong>ensuring stable learning</strong>. If the optimization is too aggressive, the model might generate unstable or unpredictable outputs. If it’s too conservative, the model might get stuck in suboptimal behaviors.</li><li><strong>Token-Level vs. Sequence-Level Learning</strong><br>Many RL algorithms (like GRPO) optimize responses at the <strong>sequence level</strong>, meaning they assess the overall response without fine-tuning specific areas of weakness. However, true reasoning improvements require <strong>token-level feedback</strong>, where adjustments are made to the model’s understanding at a granular level.</li><li><strong>Balancing Training Efficiency with Performance Gains</strong><br>Models should ideally improve with <strong>fewer training steps</strong> while maintaining high accuracy. Traditional reinforcement learning methods often require excessive tuning and lengthy iterations, leading to diminishing returns on additional training.</li></ul><p>When evaluating <strong>RL</strong> strategies for LLM training, it’s not just about which method performs better, it’s about understanding why one approach outperforms another. The comparison between <strong>GRPO (Group Relative Policy Optimization)</strong> and <strong>DAPO (Decoupled Clip and Dynamic Sampling Policy Optimization)</strong> offers deep insights into how advanced RL techniques evolve to address fundamental issues in model optimization.</p><h3>2. Background</h3><p><strong>Introduction to GRPO:</strong></p><p><strong>GRPO</strong> is a reinforcement learning (RL) algorithm designed to enhance the reasoning capabilities of LLMs, particularly in mathematical and logical tasks. It was introduced in the context of DeepSeekMath and further utilized for deepseek-r1, as detailed in <a href="https://arxiv.org/abs/2402.03300">DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models</a> and <a href="https://arxiv.org/abs/2501.12948">DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning</a>. These models aim to address challenges in reasoning-intensive tasks, such as mathematical problem-solving, by optimizing training efficiency and performance.</p><p><strong>Emergence of DAPO:</strong></p><p>The development of <strong>Decoupled Clip and Dynamic Sampling Policy Optimization (DAPO)</strong> was motivated by several critical challenges in enhancing reasoning capabilities within large language models (LLMs). The primary factors that led to DAPO’s inception include:</p><ol><li><strong>Lack of Reproducibility in Existing RL Methods</strong>: Prior reinforcement learning (RL) approaches, such as those employed in OpenAI’s o1 and DeepSeek R1, have been hindered by the absence of detailed technical disclosures.</li><li><strong>Inefficiencies in Current RL Algorithms</strong>: Traditional RL techniques often suffer from issues like entropy collapse<em> (</em><strong><em>Entropy collapse</em></strong><em> occurs in reinforcement learning when a model’s policy becomes overly deterministic, reducing diversity in its outputs and limiting exploration)</em> and inefficient sampling strategies. These challenges result in models that are less diverse and require extensive computational resources, making the training process both time-consuming and costly.</li><li><strong>Need for Enhanced Long-Form Reasoning</strong>: Existing RL methods have demonstrated limitations in handling long-chain reasoning tasks, which are essential for complex problem-solving and advanced language understanding. ​</li></ol><p>In response to these challenges, the development of DAPO was guided by several key research questions and objectives:</p><ul><li><strong>How can we design an RL algorithm that promotes policy diversity and prevents entropy collapse?</strong> Addressing this question led to the introduction of the <strong>Clip-Higher mechanism</strong>, aimed at enhancing the diversity of model outputs and ensuring more robust learning.</li><li><strong>What strategies can improve training efficiency and stability in RL for LLMs?</strong> This inquiry resulted in the development of <strong>Dynamic Sampling</strong>, a technique that enhances training efficiency by focusing on more informative and challenging samples, thereby improving the model’s learning process.</li><li><strong>In what ways can RL algorithms be optimized to better handle long-chain reasoning tasks?</strong> To tackle this, DAPO incorporates <strong>Token-Level Policy Gradient Loss</strong>, which allows for more precise adjustments during training, crucial for tasks requiring extended reasoning.</li><li><strong>How can we reduce reward noise and stabilize training in RL for LLMs?</strong> This led to the implementation of <strong>Overlong Reward Shaping</strong>, a technique designed to mitigate reward noise and enhance the stability of the training process.</li></ul><h3>3. Algorithmic Foundations</h3><h4><strong>Core Principle of GRPO</strong></h4><p>Group-based advantage estimation is a core principle of GRPO, enabling it to operate without a separate value function. For each prompt q, the algorithm generates multiple outputs (typically 64 per question, as seen in training details for deepseek-r1-Zero). The rewards for these outputs are calculated, and the advantage for each response​ is defined as:</p><p><strong>Aᵢ = (rᵢ — mean({r₁,r₂,…,rG})) / std({r₁,r₂,…,rG})</strong></p><p>This means the advantage is the standardized reward, where <strong>mean ( { 𝑟 1 , … , 𝑟 𝐺 } )</strong> is the average reward of the group, and <strong>std ( { 𝑟 1 , … , 𝑟 𝐺 } )</strong> is the standard deviation, normalizing the advantages to have zero mean and unit variance. This approach uses the group mean as an estimate of the expected reward for the prompt.</p><p>In standard RL, the advantage is typically <strong>Q(s,a)−V(s)</strong> where <strong>Q(s,a)</strong> is the expected return from <strong>state</strong> <strong>s</strong> taking <strong>action</strong> <strong>a</strong>, and <strong>V(s)</strong> is the expected return from <strong>state s</strong>. In GRPO, since each response is a complete action for the prompt, and there’s no further interaction, it’s a single-step decision-making process. Thus, <strong>ri−mean(r)</strong> approximates <strong>ri−V(q),</strong> where <strong>V(q)</strong> is the value function for prompt q, estimated by the group mean.</p><p>This method eliminates the need for a separate value network, as in PPO, reducing memory overhead significantly. For deepseek-r1-Zero, trained via pure RL without supervised fine-tuning, this approach led to impressive results, such as <strong>AIME 2024 pass@1 increasing from 15.6% to 71.0%</strong>, and with majority voting, reaching <strong>86.7%</strong>, matching <strong>OpenAI-o1-0912.</strong></p><h4>Standard Clipping and Uniform Sampling Methods</h4><p>Standard clipping in GRPO refers to the use of a clipped objective for policy updates, similar to PPO, to ensure stability. The objective function includes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*0ciPaXPd1oaJqgm2GUeHkQ.png" /><figcaption><a href="https://arxiv.org/pdf/2402.03300">Arxiv</a></figcaption></figure><p>Lets break it down:</p><ul><li><strong>J_GRPO(θ)</strong> → This is what the model tries to improve during training. The goal is to adjust the model’s parameters (<strong>θ</strong>) to maximize rewards.</li><li><strong>E[…]</strong> — &gt; The “E” symbol represents an expectation, meaning we are averaging over many tries to smooth out randomness in training.</li><li>Inside the sum, we have: <strong>min(Aᵢ, clip( … ) Aᵢ ), where Aᵢ</strong> represents the advantage, which tells us how much better or worse a particular action is compared to the average. The <strong>clip( … )</strong> function ensures stability by preventing updates that are too large.</li><li>The clipping mechanism works as follows: <strong>clip( π_θ(oᵢ | q) / π_θ_old(oᵢ | q) , 1 — ε , 1 + ε ). </strong>Here, <strong>π_θ(oᵢ | q)</strong> is the probability of the model choosing output <strong>oᵢ</strong> given question <strong>q</strong>, under the new model <strong>θ</strong>.</li><li><strong>π_θ_old(oᵢ | q)</strong> is the same probability under the older version of the model.</li><li>The ratio <strong>π_θ / π_θ_old</strong> shows how much the new model’s behavior differs from the old one.</li><li>If the ratio is too large or too small, we “clip” it between <strong>1 — ε</strong> and <strong>1 + ε</strong> (typically, <strong>ε = 0.2</strong>). This prevents drastic changes that could destabilize training.</li><li><strong>β D_KL( π_θ || π_ref ). </strong>This adds a <strong>penalty</strong> to prevent the new model from diverging too much from a reference policy. <strong>D_KL</strong> (Kullback-Leibler divergence) measures how different two probability distributions are. The <strong>β</strong> factor (e.g., <strong>β = 0.04</strong> in DeepSeek-R1) controls how strongly we enforce this constraint.</li></ul><p>The clipping term (<strong>highlighted in red</strong>)limits the ratio of the new policy probability to the old policy probability within the range [1-ε, 1+ε]. This prevents large policy updates that could destabilize training, with ε typically set to a small value like 0.2, as seen in training details for deepseek-r1-Zero (learning rate 1e-6, KL coefficient 0.04).</p><h4><strong>Innovative Techniques in DAPO:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vgDGngkzZqG7X36vSm0frg.png" /><figcaption><a href="https://arxiv.org/pdf/2503.14476">Arxiv</a></figcaption></figure><p><strong>Clip-Higher Mechanism</strong></p><p>The Clip-Higher mechanism in DAPO uses a bigger clipping range, like ε_high = 0.28 instead of the usual 0.2 in GRPO. The idea is to let the model explore more by allowing bigger changes in how it picks answers. This stops the model from getting stuck on boring, safe choices and encourages it to try new things, especially for tricky reasoning tasks.</p><p>With a higher clipping range, DAPO boosts policy diversity, meaning the model tries a wider mix of answers, without losing stability. GRPO’s smaller clip (e.g., ε = 0.2) keeps things steady but can limit creativity. DAPO balances this by pairing the higher clip with a lower one (ε_low = 0.2) for safety, helping deepseek-r1-like models perform better on tests like AIME 2024.</p><p><strong>Dynamic Sampling</strong></p><p>Dynamic Sampling in DAPO picks only the most useful questions for training. It skips ones where all answers score the same (like all 0s or all 1s), focusing on prompts that give clear feedback. This makes learning faster and sharper, as the model gets better updates from each step.</p><p>GRPO uses uniform sampling, meaning it picks every question randomly and tries lots of answers (e.g., 64 per prompt) no matter what. This can waste time on dull prompts. DAPO’s selective approach beats this by targeting effort where it counts, improving efficiency over GRPO’s broader, less picky method used in deepseek-r1.</p><p><strong>Fine-grained Feedback for Long Reasoning Chains</strong></p><p>Token-Level Policy Gradient Loss in DAPO looks at every word (token) in an answer, not just the whole thing. For long reasoning tasks, like math problems with many steps, it gives detailed feedback on each part. This helps the model fix small mistakes and get better at long chains of thought.</p><p>GRPO’s sequence-level loss judges the whole answer at once, which works fine for short stuff but misses details in long answers. DAPO’s token-level approach is more precise, especially for deepseek-r1-style models tackling big reasoning challenges, leading to stronger results on complex benchmarks.</p><p><strong>Overlong Reward Shaping</strong></p><p>Overlong Reward Shaping in DAPO handles answers that get too long. It sets a max length (e.g., 20,480 tokens) and gently lowers the score for extra words beyond a limit (e.g., 4,096 tokens). This <strong>“soft punishment”</strong> stops the model from rambling without being too harsh.</p><p>GRPO doesn’t have this trick, so it might let noisy, overly long answers slip through, hurting quality. DAPO’s method cuts the clutter, making outputs cleaner and more useful, especially for reasoning tasks where clear, concise answers matter, like in deepseek-r1’s math successes.</p><h3>4. Performance Metrics and Benchmark Analysis</h3><ul><li><strong>The Significance of AIME 2024 as a Benchmark for Reasoning Capabilities</strong><br>AIME 2024 is a tough math test for top high school students, making it a great way to check how well AI models reason. It’s harder than basic math benchmarks like GSM8K, with tricky problems needing step-by-step thinking.</li><li><strong>Comparative Performance: GRPO’s Scores vs. DAPO’s Improved Results</strong><br>GRPO, used in deepseek-r1, scores well on AIME 2024, deepseek-r1-Zero hits 47 points out of 60 with a Qwen-32B model. That’s strong, matching big names like OpenAI’s o1. But DAPO steps it up, reaching 50 points with the same Qwen-32B base, beating GRPO’s 47.</li><li><strong>Reduced Training Steps with DAPO</strong><br>DAPO cuts training time big-time. While GRPO takes lots of steps to get deepseek-r1 to 47 points on AIME 2024, DAPO gets to 50 points using 50% fewer steps.</li><li><strong>Computational Benefits and Scalability in Large-Scale Deployments</strong><br>DAPO saves computer power too. GRPO, in deepseek-r1, needs hefty resources to try 64 answers per question and crunch them. DAPO’s tricks — like skipping useless questions and adjusting rewards for long answers — mean it uses less juice to get better results.</li></ul><h3>5. Implementation Insights and Open-Source Commitment</h3><h4>The verl Framework</h4><p><strong>Architectural Design and Practical Integration of DAPO</strong></p><p>The verl framework is the backbone of DAPO, a system that trains large language models efficiently. It’s built to handle DAPO’s trick, like Clip-Higher and Dynamic Sampling, making them work smoothly together. This setup lets DAPO tweak models like Qwen2.5–32B to score 50 points on AIME 2024.</p><p><strong>Transparency and Reproducibility in Contrast with Some GRPO Implementations</strong></p><p>Unlike some GRPO setups, like deepseek-r1, where key details are hidden, verl and DAPO are fully open. They share all the code and steps, so anyone can rebuild or check the work. GRPO’s closed-off style makes it tough to copy, but DAPO’s clear approach fixes that, boosting trust and teamwork.</p><h4>Dataset and Reproducibility</h4><p><strong>Role of the DAPO-Math-17K Dataset</strong></p><p>The DAPO-Math-17K dataset is a hand-picked collection of 17,000 math problems, perfect for training models to think through tough reasoning tasks. It’s what powered DAPO to beat GRPO’s scores on AIME 2024, giving the model solid examples to learn from and test against.</p><p><strong>Community-Driven Improvements and Open-Source Collaboration</strong></p><p>DAPO’s open-source vibe invites everyone to pitch in. The DAPO-Math-17K dataset and verl code are free for all, so researchers can tweak, improve, or add to them. This teamwork could make DAPO even better, unlike GRPO’s more locked-down style, sparking faster progress in AI reasoning.</p><h3>6. Comparative Analysis: GRPO vs. DAPO</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IFRQJd8iv5qgtAOPJvdMoQ.png" /><figcaption>IP</figcaption></figure><h3>7. Conclusion</h3><p>DAPO proves that constant tinkering and sharing ideas openly can take reinforcement learning to new heights. GRPO did well, but DAPO’s leap forward — thanks to community access and bold experiments — shows why we need to keep trying new things. Open-source teamwork lets everyone build on successes like DAPO, driving language models to smarter, more useful places faster.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c571a0536f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step Guide: Building an MCP Server using Python-SDK, AlphaVantage & Claude AI]]></title>
            <link>https://medium.com/@syed_hasan/step-by-step-guide-building-an-mcp-server-using-python-sdk-alphavantage-claude-ai-7a2bfb0c3096?source=rss-2a79006f7e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a2bfb0c3096</guid>
            <category><![CDATA[claude-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[guide]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <dc:creator><![CDATA[Syed Hasan]]></dc:creator>
            <pubDate>Tue, 11 Mar 2025 12:24:59 GMT</pubDate>
            <atom:updated>2025-03-11T12:24:59.300Z</atom:updated>
            <content:encoded><![CDATA[<p>Step-by-Step Guide: Building an MCP Server using Python-SDK, AlphaVantage &amp; Claude AI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xXO9r_cCq2PqXjUlzCeqYg.jpeg" /><figcaption>Generated by Bing Image Generator</figcaption></figure><h3>Overview</h3><p><em>When I started exploring ways to integrate real-time stock market data with AI-powered insights, I wanted a setup that was both powerful and flexible. That’s when I built my own </em><strong><em>Model Context Protocol (MCP) server</em></strong><em> using Python, </em><strong><em>AlphaVantage</em></strong><em> for market data, and </em><strong><em>Claude AI</em></strong><em> as my analytical assistant. This setup allows me to fetch stock data, apply technical analysis (like </em><strong><em>moving averages and RSI</em></strong><em>), and generate trading recommendations — all in an automated, structured way. In this guide, I’ll walk you through how I built this step by step, so you can create your own intelligent stock market analysis system. You can also extend this to any other use-case. This is just a side-project.</em></p><h3>1. Introduction</h3><h4>Why I Built an MCP Server for Stock Market Analysis</h4><p>As someone who enjoys both financial markets and AI, I wanted to create a system that could help me analyze stocks more efficiently. While plenty of tools exist for this, I wanted something <strong>customizable</strong>, <strong>automated</strong>, and <strong>directly accessible to an AI assistant</strong> — something that could answer my questions about stock trends in real time.</p><p>That’s where <strong>MCP (Model Context Protocol) servers</strong> come in <em>(The Trending Topic).</em> They allow me to create <strong>tools</strong> that an LLM like Claude can call, meaning I don’t have to do the calculations myself anymore. Instead, I can just ask something like:</p><p><em>“What’s the RSI for AAPL right now?”</em></p><p>and my <strong>MCP server will fetch the latest stock data, calculate the RSI, and return the result instantly</strong>. This makes it way easier to make informed trading decisions without jumping between multiple apps and websites.</p><p>I chose to use the <strong>AlphaVantage API (free-tier) </strong>to pull real-time stock data and integrated it into my MCP server, allowing me to analyze stocks with custom-built AI tools. This guide walks you through how I built it, so you can do the same!</p><h4>What This Guide Covers</h4><p>This guide will show you how to build an <strong>MCP server</strong> that can fetch stock market data, analyze trends, and generate trade recommendations. Specifically, you’ll learn:</p><p>✅ <strong>How MCP servers work</strong> and why they’re useful<br>✅ <strong>How to set up your Python environment</strong> for MCP development<br>✅ <strong>How to fetch stock market data</strong> using the AlphaVantage API<br>✅ <strong>How to create MCP tools</strong> that analyze stock trends (e.g., moving averages, RSI)<br>✅ <strong>How to use MCP prompts</strong> to automate common stock analysis tasks<br>✅ <strong>How to run and test your MCP server</strong></p><p>By the end, you’ll have a working <strong>AI-powered stock market analysis tool</strong> that you can use and expand upon!</p><h4>Prerequisite Knowledge</h4><p>You don’t need to be an AI or finance expert to follow this guide, but some basic knowledge will help:</p><p>💡 <strong>Python Basics</strong> — You should know how to install packages, write functions, and work with APIs.<br> 💡 <strong>LLMs &amp; MCP</strong> — A general idea of how large language models work and how they can use external tools (I’ll explain MCP as we go).<br> 💡 <strong>Stock Market Concepts</strong> — You should at least be familiar with terms like <strong>“moving average”</strong> and <strong>“RSI”</strong>. If not, don’t worry — I’ll explain them as we implement them.</p><h3>2. Understanding MCP Servers</h3><p>A <strong>Model Context Protocol (MCP) server</strong> is a specialized system that provides structured data and functionality to <strong>large language models (LLMs)</strong> in a standardized way. Think of it as a <strong>bridge between AI models and external data sources or tools</strong>. Instead of just giving an LLM a static prompt, an MCP server allows the AI to <strong>fetch real-time data, execute computations, and access stored resources</strong> dynamically.</p><p>For example, an MCP server can be used to:</p><ul><li><strong>Fetch stock market data</strong> and calculate trends (like we’re doing in this tutorial).</li><li><strong>Process user inputs</strong> by running tools that perform calculations or retrieve specific data.</li><li><strong>Store and manage contextual information</strong> that the LLM can use during conversations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*BFvPztx4pkleHt9p2DccWw.jpeg" /></figure><p>MCP servers provide three core functionalities:</p><p><strong><em>Resources: Storing and serving file-like data</em></strong></p><p>MCP resources act like <strong>read-only data sources</strong> that provide structured information to an LLM. You can think of them like <strong>REST API GET requests</strong> — they expose data but don’t perform computations.</p><ul><li>Example: A resource could store <strong>user profiles</strong>, <strong>stock price history</strong>, or <strong>configuration settings</strong> that an LLM can load on demand.</li><li>Code Example:</li></ul><pre>@mcp.resource(&quot;config://app&quot;)<br>def get_config() -&gt; str:<br>    return &quot;App configuration here&quot;Resources: Storing and serving file-like data</pre><p><strong><em>Tools: Functions that the LLM can call</em></strong></p><p>MCP <strong>tools</strong> let the AI execute specific tasks — similar to <strong>API POST requests</strong>. These functions can <strong>perform calculations, interact with databases, or even call external APIs</strong>.</p><ul><li>Example: A tool that calculates <strong>BMI</strong>, fetches <strong>stock prices</strong>, or <strong>processes images</strong>.</li><li>Code Example:</li></ul><pre>@mcp.tool()<br>def calculate_bmi(weight_kg: float, height_m: float) -&gt; float:<br>    return weight_kg / (height_m ** 2)</pre><p><strong><em>Prompts: Predefined templates for specific tasks</em></strong></p><p>MCP <strong>prompts</strong> are reusable instruction templates that help the AI perform structured interactions. These prompts guide the LLM in <strong>responding consistently to specific types of requests</strong>.</p><ul><li>Example: A prompt for <strong>code review</strong>, <strong>error debugging</strong>, or <strong>financial analysis</strong>.</li><li>Code Example:</li></ul><pre>@mcp.prompt()<br>def review_code(code: str) -&gt; str:<br>    return f&quot;Please review this code:\n\n{code}&quot;</pre><p>While MCP <strong>resources</strong> and <strong>prompts</strong> are useful, <strong>MCP tools are the most powerful part of the system</strong> — especially for stock market analysis. Tools allow the AI to:</p><p>✅ <strong>Fetch live stock prices</strong> from an API.<br>✅ <strong>Perform calculations like moving averages and RSI</strong> on real-time data. ✅ <strong>Automate complex workflows</strong>, such as generating stock reports or alerts.</p><p>Since we want to build an <strong>AI-driven stock analysis system</strong>, we’ll focus on <strong>creating and using MCP tools</strong> that fetch financial data, process stock trends, and provide AI-powered insights.</p><h3>3. Setting Up the Development Environment</h3><h4><em>System requirements</em></h4><ul><li>Python 3.10 or higher installed.</li><li>You must use the Python MCP SDK 1.2.0 or higher.</li></ul><h4>Set up your environment</h4><p>First, let’s install uv and set up our Python project and environment:</p><pre>powershell -ExecutionPolicy ByPass -c &quot;irm https://astral.sh/uv/install.ps1 | iex&quot;</pre><p>Make sure to restart your terminal afterwards to ensure that the uv command gets picked up.</p><p>Now, let’s create and set up our project:</p><pre># Create a new directory for our project<br>uv init finance<br>cd finance<br><br># Create virtual environment and activate it<br>uv venv<br>.venv\Scripts\activate<br><br># Install dependencies<br>uv add mcp[cli] httpx<br><br># Create our server file<br>new-item finance_server.py</pre><h3>4. Fetching Stock Market Data with AlphaVantage API</h3><p><strong>Alpha Vantage</strong> is a provider of real-time and historical financial market data, offering APIs that deliver information on equities, currencies, cryptocurrencies, and more.</p><p>To access Alpha Vantage’s services, you’ll need to obtain an API key. Start by signing up on their <a href="https://www.alphavantage.co/"><strong><em>website</em></strong></a>, after which you’ll receive a free API key that allows up to 25 requests per day. If your requirements exceed this limit, Alpha Vantage offers premium memberships to accommodate higher usage.</p><p>Once you have your API key, you can fetch intraday stock price data using the TIME_SERIES_INTRADAY endpoint. This API provides intraday time series data, including open, high, low, close, and volume information, updated in real-time. You&#39;ll need to specify parameters such as the stock symbol, the desired interval between data points (options include 1min, 5min, 15min, 30min, and 60min), and your API key. For example, to retrieve 5-minute interval data for the stock symbol &quot;NVDA,&quot; your API call would look like this:</p><pre>https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&amp;symbol=NVDA&amp;interval=5min&amp;apikey=YOUR_API_KEY</pre><h3>5. Implementing MCP Tools for Stock Analysis</h3><h4><strong>Tool 1: Moving Averages Calculation</strong></h4><p>A moving average is calculated by averaging the prices of a security over a specific number of periods, providing a continuous update of the average price.</p><p><strong>Short-Term vs. Long-Term Moving Averages</strong></p><p>Short-term moving averages, such as the 5-day or 10-day averages, react quickly to recent price changes and are useful for capturing immediate market trends. In contrast, long-term moving averages, like the 50-day or 200-day averages, respond more slowly and are better suited for identifying sustained trends over extended periods. The choice between short-term and long-term moving averages depends on the investor’s strategy and the specific insights they seek.</p><p><strong>Implementing the </strong><strong><em>calculate_moving_averages</em> Function</strong></p><pre># Technical Analysis Tools<br>@mcp.tool()<br>def calculate_moving_averages(symbol: str, short_period: int = 20, long_period: int = 50) -&gt; Dict[str, Any]:<br>    &quot;&quot;&quot;<br>    Calculate short and long moving averages for a symbol<br>    <br>    Args:<br>        symbol: The ticker symbol to analyze<br>        short_period: Short moving average period in minutes<br>        long_period: Long moving average period in minutes<br>        <br>    Returns:<br>        Dictionary with moving average data and analysis<br>    &quot;&quot;&quot;<br>    cache_key = f&quot;{symbol}_1min&quot;<br>    <br>    if cache_key not in market_data_cache:<br>        df = AlphaVantageAPI.get_intraday_data(symbol, &quot;1min&quot;, outputsize=&quot;full&quot;)<br>        market_data_cache[cache_key] = MarketData(<br>            symbol=symbol,<br>            interval=&quot;1min&quot;,<br>            data=df,<br>            last_updated=datetime.now()<br>        )<br>    <br>    data = market_data_cache[cache_key].data<br>    <br>    # Calculate moving averages<br>    data[f&#39;SMA{short_period}&#39;] = data[&#39;close&#39;].rolling(window=short_period).mean()<br>    data[f&#39;SMA{long_period}&#39;] = data[&#39;close&#39;].rolling(window=long_period).mean()<br>    <br>    # Get latest values<br>    latest = data.iloc[-1]<br>    current_price = latest[&#39;close&#39;]<br>    short_ma = latest[f&#39;SMA{short_period}&#39;]<br>    long_ma = latest[f&#39;SMA{long_period}&#39;]<br>    <br>    # Determine signal<br>    if short_ma &gt; long_ma:<br>        signal = &quot;BULLISH (Short MA above Long MA)&quot;<br>    elif short_ma &lt; long_ma:<br>        signal = &quot;BEARISH (Short MA below Long MA)&quot;<br>    else:<br>        signal = &quot;NEUTRAL (MAs are equal)&quot;<br>    <br>    # Check for crossover in the last 5 periods<br>    last_5 = data.iloc[-5:]<br>    crossover = False<br>    crossover_type = &quot;&quot;<br>    <br>    for i in range(1, len(last_5)):<br>        prev = last_5.iloc[i-1]<br>        curr = last_5.iloc[i]<br>        <br>        # Golden Cross (short crosses above long)<br>        if prev[f&#39;SMA{short_period}&#39;] &lt;= prev[f&#39;SMA{long_period}&#39;] and curr[f&#39;SMA{short_period}&#39;] &gt; curr[f&#39;SMA{long_period}&#39;]:<br>            crossover = True<br>            crossover_type = &quot;GOLDEN CROSS (Bullish)&quot;<br>            break<br>            <br>        # Death Cross (short crosses below long)<br>        if prev[f&#39;SMA{short_period}&#39;] &gt;= prev[f&#39;SMA{long_period}&#39;] and curr[f&#39;SMA{short_period}&#39;] &lt; curr[f&#39;SMA{long_period}&#39;]:<br>            crossover = True<br>            crossover_type = &quot;DEATH CROSS (Bearish)&quot;<br>            break<br>    <br>    return {<br>        &quot;symbol&quot;: symbol,<br>        &quot;current_price&quot;: current_price,<br>        f&quot;SMA{short_period}&quot;: short_ma,<br>        f&quot;SMA{long_period}&quot;: long_ma,<br>        &quot;signal&quot;: signal,<br>        &quot;crossover_detected&quot;: crossover,<br>        &quot;crossover_type&quot;: crossover_type if crossover else &quot;None&quot;,<br>        &quot;analysis&quot;: f&quot;&quot;&quot;Moving Average Analysis for {symbol}:<br>Current Price: ${current_price:.2f}<br>{short_period}-period SMA: ${short_ma:.2f}<br>{long_period}-period SMA: ${long_ma:.2f}<br>Signal: {signal}<br>Recent Crossover: {&quot;Yes - &quot; + crossover_type if crossover else &quot;No&quot;}<br><br>Recommendation: {<br>    &quot;STRONG BUY&quot; if crossover and crossover_type == &quot;GOLDEN CROSS (Bullish)&quot; else<br>    &quot;BUY&quot; if signal == &quot;BULLISH (Short MA above Long MA)&quot; else<br>    &quot;STRONG SELL&quot; if crossover and crossover_type == &quot;DEATH CROSS (Bearish)&quot; else<br>    &quot;SELL&quot; if signal == &quot;BEARISH (Short MA below Long MA)&quot; else<br>    &quot;HOLD&quot;<br>}&quot;&quot;&quot;<br>    }</pre><p><strong>Detecting Trends and Crossovers: Golden Cross and Death Cross</strong></p><p>Moving average crossovers are significant events that can signal changes in market trends. A “Golden Cross” occurs when a short-term moving average crosses above a long-term moving average, indicating potential bullish momentum. Conversely, a “Death Cross” happens when a short-term moving average crosses below a long-term moving average, suggesting possible bearish trends. These crossovers are closely monitored by traders as they can provide insights into the future direction of asset prices.</p><h4><strong>Tool 2: Relative Strength Index (RSI) Calculation</strong></h4><p><strong>What is RSI and Why It Matters?</strong></p><p>The <strong>Relative Strength Index (RSI)</strong> is a momentum indicator used in technical analysis to measure the speed and change of price movements. It ranges from <strong>0 to 100</strong> and helps traders identify overbought and oversold conditions in a stock or other financial asset.</p><p>RSI is calculated using the ratio of average gains to average losses over a specific period, typically <strong>14 days</strong>. A <strong>high RSI (above 70)</strong> suggests that an asset might be overbought and due for a correction, while a <strong>low RSI (below 30)</strong> indicates that it could be oversold and might rebound.</p><p><strong>Implementing the </strong><strong><em>calculate_rsi</em> Function</strong></p><pre>@mcp.tool()<br>def calculate_rsi(symbol: str, period: int = 14) -&gt; Dict[str, Any]:<br>    &quot;&quot;&quot;<br>    Calculate Relative Strength Index (RSI) for a symbol<br>    <br>    Args:<br>        symbol: The ticker symbol to analyze<br>        period: RSI calculation period in minutes<br>        <br>    Returns:<br>        Dictionary with RSI data and analysis<br>    &quot;&quot;&quot;<br>    cache_key = f&quot;{symbol}_1min&quot;<br>    <br>    if cache_key not in market_data_cache:<br>        df = AlphaVantageAPI.get_intraday_data(symbol, &quot;1min&quot;, outputsize=&quot;full&quot;)<br>        market_data_cache[cache_key] = MarketData(<br>            symbol=symbol,<br>            interval=&quot;1min&quot;,<br>            data=df,<br>            last_updated=datetime.now()<br>        )<br>    <br>    data = market_data_cache[cache_key].data.copy()<br>    <br>    # Calculate price changes<br>    delta = data[&#39;close&#39;].diff()<br>    <br>    # Create gain and loss series<br>    gain = delta.copy()<br>    loss = delta.copy()<br>    gain[gain &lt; 0] = 0<br>    loss[loss &gt; 0] = 0<br>    loss = abs(loss)<br>    <br>    # Calculate average gain and loss<br>    avg_gain = gain.rolling(window=period).mean()<br>    avg_loss = loss.rolling(window=period).mean()<br>    <br>    # Calculate RS and RSI<br>    rs = avg_gain / avg_loss<br>    rsi = 100 - (100 / (1 + rs))<br>    <br>    # Get latest RSI<br>    latest_rsi = rsi.iloc[-1]<br>    <br>    # Determine signal<br>    if latest_rsi &lt; 30:<br>        signal = &quot;OVERSOLD (Potential buy opportunity)&quot;<br>    elif latest_rsi &gt; 70:<br>        signal = &quot;OVERBOUGHT (Potential sell opportunity)&quot;<br>    else:<br>        signal = &quot;NEUTRAL&quot;<br>    <br>    return {<br>        &quot;symbol&quot;: symbol,<br>        &quot;period&quot;: period,<br>        &quot;rsi&quot;: latest_rsi,<br>        &quot;signal&quot;: signal,<br>        &quot;analysis&quot;: f&quot;&quot;&quot;RSI Analysis for {symbol}:<br>{period}-period RSI: {latest_rsi:.2f}<br>Signal: {signal}<br><br>Recommendation: {<br>    &quot;BUY&quot; if latest_rsi &lt; 30 else<br>    &quot;SELL&quot; if latest_rsi &gt; 70 else<br>    &quot;HOLD&quot;<br>}&quot;&quot;&quot;<br>    }</pre><p><strong>Determining Overbought/Oversold Conditions</strong></p><ul><li><strong>RSI &gt; 70</strong> → <strong>Overbought</strong>: The stock might be overvalued, and a price pullback could be coming. Traders may consider selling.</li><li><strong>RSI &lt; 30</strong> → <strong>Oversold</strong>: The stock could be undervalued, suggesting a potential buying opportunity.</li></ul><h4><strong>Tool 3: Trade Recommendation</strong></h4><p>This tool combines information from the other two tools and give recommendation whether to sell, hold or buy the asset.</p><pre>@mcp.tool()<br>def trade_recommendation(symbol: str) -&gt; Dict[str, Any]:<br>    &quot;&quot;&quot;<br>    Provide a comprehensive trade recommendation based on multiple indicators<br>    <br>    Args:<br>        symbol: The ticker symbol to analyze<br>        <br>    Returns:<br>        Dictionary with trading recommendation and supporting data<br>    &quot;&quot;&quot;<br>    # Calculate individual indicators<br>    ma_data = calculate_moving_averages(symbol)<br>    rsi_data = calculate_rsi(symbol)<br>    <br>    # Extract signals<br>    ma_signal = ma_data[&quot;signal&quot;]<br>    ma_crossover = ma_data[&quot;crossover_detected&quot;]<br>    ma_crossover_type = ma_data[&quot;crossover_type&quot;]<br>    rsi_value = rsi_data[&quot;rsi&quot;]<br>    rsi_signal = rsi_data[&quot;signal&quot;]<br>    <br>    # Determine overall signal strength<br>    signal_strength = 0<br>    <br>    # MA contribution<br>    if &quot;BULLISH&quot; in ma_signal:<br>        signal_strength += 1<br>    elif &quot;BEARISH&quot; in ma_signal:<br>        signal_strength -= 1<br>        <br>    # Crossover contribution<br>    if ma_crossover:<br>        if &quot;GOLDEN&quot; in ma_crossover_type:<br>            signal_strength += 2<br>        elif &quot;DEATH&quot; in ma_crossover_type:<br>            signal_strength -= 2<br>            <br>    # RSI contribution<br>    if &quot;OVERSOLD&quot; in rsi_signal:<br>        signal_strength += 1.5<br>    elif &quot;OVERBOUGHT&quot; in rsi_signal:<br>        signal_strength -= 1.5<br>    <br>    # Determine final recommendation<br>    if signal_strength &gt;= 2:<br>        recommendation = &quot;STRONG BUY&quot;<br>    elif signal_strength &gt; 0:<br>        recommendation = &quot;BUY&quot;<br>    elif signal_strength &lt;= -2:<br>        recommendation = &quot;STRONG SELL&quot;<br>    elif signal_strength &lt; 0:<br>        recommendation = &quot;SELL&quot;<br>    else:<br>        recommendation = &quot;HOLD&quot;<br>    <br>    # Calculate risk level (simple version)<br>    risk_level = &quot;MEDIUM&quot;<br>    if abs(signal_strength) &gt; 3:<br>        risk_level = &quot;LOW&quot;  # Strong signal, lower risk<br>    elif abs(signal_strength) &lt; 1:<br>        risk_level = &quot;HIGH&quot;  # Weak signal, higher risk<br>    <br>    analysis = f&quot;&quot;&quot;# Trading Recommendation for {symbol}<br><br>## Summary<br>Recommendation: {recommendation}<br>Risk Level: {risk_level}<br>Signal Strength: {signal_strength:.1f} / 4.5<br><br>## Technical Indicators<br>Moving Averages: {ma_signal}<br>Recent Crossover: {&quot;Yes - &quot; + ma_crossover_type if ma_crossover else &quot;No&quot;}<br>RSI ({rsi_data[&quot;period&quot;]}): {rsi_value:.2f} - {rsi_signal}<br><br>## Reasoning<br>This recommendation is based on a combination of Moving Average analysis and RSI indicators.<br>{<br>    f&quot;The {ma_crossover_type} provides a strong directional signal. &quot; if ma_crossover else &quot;&quot;<br>}{<br>    f&quot;The RSI indicates the stock is {rsi_signal.split(&#39; &#39;)[0].lower()}. &quot; if &quot;NEUTRAL&quot; not in rsi_signal else &quot;&quot;<br>}<br><br>## Action Plan<br>{<br>    &quot;Consider immediate entry with a stop loss at the recent low. Target the next resistance level.&quot; if recommendation == &quot;STRONG BUY&quot; else<br>    &quot;Look for a good entry point on small dips. Set reasonable stop loss.&quot; if recommendation == &quot;BUY&quot; else<br>    &quot;Consider immediate exit or setting tight stop losses to protect gains.&quot; if recommendation == &quot;STRONG SELL&quot; else<br>    &quot;Start reducing position on strength or set trailing stop losses.&quot; if recommendation == &quot;SELL&quot; else<br>    &quot;Monitor the position but no immediate action needed.&quot;<br>}<br>&quot;&quot;&quot;<br>    <br>    return {<br>        &quot;symbol&quot;: symbol,<br>        &quot;recommendation&quot;: recommendation,<br>        &quot;risk_level&quot;: risk_level,<br>        &quot;signal_strength&quot;: signal_strength,<br>        &quot;ma_signal&quot;: ma_signal,<br>        &quot;rsi_signal&quot;: rsi_signal,<br>        &quot;current_price&quot;: ma_data[&quot;current_price&quot;],<br>        &quot;analysis&quot;: analysis<br>    }</pre><h3>6. Creating MCP Prompts for Automated Analysis</h3><ul><li><strong>Prompt 1: Analyze a Single Ticker</strong></li></ul><pre>@mcp.prompt()<br>def analyze_ticker(symbol: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Analyze a ticker symbol for trading opportunities<br>    &quot;&quot;&quot;<br>    return f&quot;&quot;&quot;You are a professional stock market analyst. I would like you to analyze the stock {symbol} and provide trading insights.<br><br>Start by examining the current market data and technical indicators. Here are the specific tasks:<br><br>1. First, check the current market data for {symbol}<br>2. Calculate the moving averages using the calculate_moving_averages tool<br>3. Calculate the RSI using the calculate_rsi tool<br>4. Generate a comprehensive trade recommendation using the trade_recommendation tool<br>5. Based on all this information, provide your professional analysis, highlighting:<br>   - The current market position<br>   - Key technical indicators and what they suggest<br>   - Potential trading opportunities and risks<br>   - Your recommended action (buy, sell, or hold) with a brief explanation<br><br>Please organize your response in a clear, structured format suitable for a professional trader.&quot;&quot;&quot;</pre><ul><li><strong>Prompt 2: Compare Multiple Tickers</strong></li></ul><pre>@mcp.prompt()<br>def compare_tickers(symbols: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Compare multiple ticker symbols for the best trading opportunity<br>    <br>    Args:<br>        symbols: Comma-separated list of ticker symbols<br>    &quot;&quot;&quot;<br>    symbol_list = [s.strip() for s in symbols.split(&quot;,&quot;)]<br>    symbol_section = &quot;\n&quot;.join([f&quot;- {s}&quot; for s in symbol_list])<br>    <br>    return f&quot;&quot;&quot;You are a professional stock market analyst. I would like you to compare these stocks and identify the best trading opportunity:<br><br>{symbol_section}<br><br>For each stock in the list, please:<br><br>1. Check the current market data using the appropriate resource<br>2. Generate a comprehensive trade recommendation using the trade_recommendation tool<br>3. Compare all stocks based on:<br>   - Current trend direction and strength<br>   - Technical indicator signals<br>   - Risk/reward profile<br>   - Trading recommendation strength<br><br>After analyzing each stock, rank them from most promising to least promising trading opportunity. Explain your ranking criteria and why you believe the top-ranked stock represents the best current trading opportunity.<br><br>Conclude with a specific recommendation on which stock to trade and what action to take (buy, sell, or hold).&quot;&quot;&quot;</pre><ul><li><strong>Prompt 3: Build an Intraday Trading Strategy</strong></li></ul><pre>@mcp.prompt()<br>def intraday_strategy_builder(symbol: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Build a custom intraday trading strategy for a specific ticker<br>    &quot;&quot;&quot;<br>    return f&quot;&quot;&quot;You are an expert algorithmic trader specializing in intraday strategies. I want you to develop a custom intraday trading strategy for {symbol}.<br><br>Please follow these steps:<br><br>1. First, analyze the current market data for {symbol} using the market-data resource<br>2. Calculate relevant technical indicators:<br>   - Moving averages (short and long periods)<br>   - RSI<br>3. Based on your analysis, design an intraday trading strategy that includes:<br>   - Specific entry conditions (technical setups that would trigger a buy/sell)<br>   - Exit conditions (both take-profit and stop-loss levels)<br>   - Position sizing recommendations<br>   - Optimal trading times during the day<br>   - Risk management rules<br><br>Make your strategy specific to the current market conditions for {symbol}, not just generic advice. Include exact indicator values and price levels where possible.<br><br>Conclude with a summary of the strategy and how a trader should implement it for today&#39;s trading session.&quot;&quot;&quot;</pre><h3>7. Connecting the MCP Server to the Client (Claude AI Desktop)</h3><p><strong>Complete Code File</strong></p><pre># finance_server.py<br><br>from mcp.server.fastmcp import FastMCP<br>import requests<br>import pandas as pd<br>from dataclasses import dataclass<br>from datetime import datetime<br>from typing import Dict, Any<br><br># Create the MCP server<br>mcp = FastMCP(&quot;AlphaVantageTrader&quot;, dependencies=[&quot;requests&quot;, &quot;pandas&quot;, &quot;tabulate&quot;])<br><br># Constants and configurations<br>API_KEY = &quot;Your API KEY&quot;  # Replace with your actual AlphaVantage API key<br><br>@dataclass<br>class MarketData:<br>    symbol: str<br>    interval: str<br>    data: pd.DataFrame<br>    last_updated: datetime<br>    <br>class AlphaVantageAPI:<br>    @staticmethod<br>    def get_intraday_data(symbol: str, interval: str = &quot;1min&quot;, outputsize: str = &quot;compact&quot;) -&gt; pd.DataFrame:<br>        &quot;&quot;&quot;Fetch intraday data from AlphaVantage API&quot;&quot;&quot;<br>        url = f&quot;https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&amp;symbol={symbol}&amp;interval={interval}&amp;outputsize={outputsize}&amp;apikey={API_KEY}&quot;<br>        <br>        response = requests.get(url)<br>        data = response.json()<br>        <br>        # Check for error responses<br>        if &quot;Error Message&quot; in data:<br>            raise ValueError(f&quot;API Error: {data[&#39;Error Message&#39;]}&quot;)<br>        if &quot;Note&quot; in data:<br>            print(f&quot;API Note: {data[&#39;Note&#39;]}&quot;)<br>            <br>        # Extract time series data<br>        time_series_key = f&quot;Time Series ({interval})&quot;<br>        if time_series_key not in data:<br>            raise ValueError(f&quot;No time series data found for {symbol} with interval {interval}&quot;)<br>            <br>        time_series = data[time_series_key]<br>        <br>        # Convert to DataFrame<br>        df = pd.DataFrame.from_dict(time_series, orient=&quot;index&quot;)<br>        df.index = pd.to_datetime(df.index)<br>        df = df.sort_index()<br>        <br>        # Rename columns and convert to numeric<br>        df.columns = [col.split(&quot;. &quot;)[1] for col in df.columns]<br>        for col in df.columns:<br>            df[col] = pd.to_numeric(df[col])<br>            <br>        return df<br><br># In-memory cache for market data<br>market_data_cache: Dict[str, MarketData] = {}<br><br># Resources<br>@mcp.resource(&quot;config://app&quot;)<br>def get_config() -&gt; str:<br>    &quot;&quot;&quot;Static configuration data&quot;&quot;&quot;<br>    return &quot;App configuration here&quot;<br><br># Technical Analysis Tools<br>@mcp.tool()<br>def calculate_moving_averages(symbol: str, short_period: int = 20, long_period: int = 50) -&gt; Dict[str, Any]:<br>    &quot;&quot;&quot;<br>    Calculate short and long moving averages for a symbol<br>    <br>    Args:<br>        symbol: The ticker symbol to analyze<br>        short_period: Short moving average period in minutes<br>        long_period: Long moving average period in minutes<br>        <br>    Returns:<br>        Dictionary with moving average data and analysis<br>    &quot;&quot;&quot;<br>    cache_key = f&quot;{symbol}_1min&quot;<br>    <br>    if cache_key not in market_data_cache:<br>        df = AlphaVantageAPI.get_intraday_data(symbol, &quot;1min&quot;, outputsize=&quot;full&quot;)<br>        market_data_cache[cache_key] = MarketData(<br>            symbol=symbol,<br>            interval=&quot;1min&quot;,<br>            data=df,<br>            last_updated=datetime.now()<br>        )<br>    <br>    data = market_data_cache[cache_key].data<br>    <br>    # Calculate moving averages<br>    data[f&#39;SMA{short_period}&#39;] = data[&#39;close&#39;].rolling(window=short_period).mean()<br>    data[f&#39;SMA{long_period}&#39;] = data[&#39;close&#39;].rolling(window=long_period).mean()<br>    <br>    # Get latest values<br>    latest = data.iloc[-1]<br>    current_price = latest[&#39;close&#39;]<br>    short_ma = latest[f&#39;SMA{short_period}&#39;]<br>    long_ma = latest[f&#39;SMA{long_period}&#39;]<br>    <br>    # Determine signal<br>    if short_ma &gt; long_ma:<br>        signal = &quot;BULLISH (Short MA above Long MA)&quot;<br>    elif short_ma &lt; long_ma:<br>        signal = &quot;BEARISH (Short MA below Long MA)&quot;<br>    else:<br>        signal = &quot;NEUTRAL (MAs are equal)&quot;<br>    <br>    # Check for crossover in the last 5 periods<br>    last_5 = data.iloc[-5:]<br>    crossover = False<br>    crossover_type = &quot;&quot;<br>    <br>    for i in range(1, len(last_5)):<br>        prev = last_5.iloc[i-1]<br>        curr = last_5.iloc[i]<br>        <br>        # Golden Cross (short crosses above long)<br>        if prev[f&#39;SMA{short_period}&#39;] &lt;= prev[f&#39;SMA{long_period}&#39;] and curr[f&#39;SMA{short_period}&#39;] &gt; curr[f&#39;SMA{long_period}&#39;]:<br>            crossover = True<br>            crossover_type = &quot;GOLDEN CROSS (Bullish)&quot;<br>            break<br>            <br>        # Death Cross (short crosses below long)<br>        if prev[f&#39;SMA{short_period}&#39;] &gt;= prev[f&#39;SMA{long_period}&#39;] and curr[f&#39;SMA{short_period}&#39;] &lt; curr[f&#39;SMA{long_period}&#39;]:<br>            crossover = True<br>            crossover_type = &quot;DEATH CROSS (Bearish)&quot;<br>            break<br>    <br>    return {<br>        &quot;symbol&quot;: symbol,<br>        &quot;current_price&quot;: current_price,<br>        f&quot;SMA{short_period}&quot;: short_ma,<br>        f&quot;SMA{long_period}&quot;: long_ma,<br>        &quot;signal&quot;: signal,<br>        &quot;crossover_detected&quot;: crossover,<br>        &quot;crossover_type&quot;: crossover_type if crossover else &quot;None&quot;,<br>        &quot;analysis&quot;: f&quot;&quot;&quot;Moving Average Analysis for {symbol}:<br>Current Price: ${current_price:.2f}<br>{short_period}-period SMA: ${short_ma:.2f}<br>{long_period}-period SMA: ${long_ma:.2f}<br>Signal: {signal}<br>Recent Crossover: {&quot;Yes - &quot; + crossover_type if crossover else &quot;No&quot;}<br><br>Recommendation: {<br>    &quot;STRONG BUY&quot; if crossover and crossover_type == &quot;GOLDEN CROSS (Bullish)&quot; else<br>    &quot;BUY&quot; if signal == &quot;BULLISH (Short MA above Long MA)&quot; else<br>    &quot;STRONG SELL&quot; if crossover and crossover_type == &quot;DEATH CROSS (Bearish)&quot; else<br>    &quot;SELL&quot; if signal == &quot;BEARISH (Short MA below Long MA)&quot; else<br>    &quot;HOLD&quot;<br>}&quot;&quot;&quot;<br>    }<br><br>@mcp.tool()<br>def calculate_rsi(symbol: str, period: int = 14) -&gt; Dict[str, Any]:<br>    &quot;&quot;&quot;<br>    Calculate Relative Strength Index (RSI) for a symbol<br>    <br>    Args:<br>        symbol: The ticker symbol to analyze<br>        period: RSI calculation period in minutes<br>        <br>    Returns:<br>        Dictionary with RSI data and analysis<br>    &quot;&quot;&quot;<br>    cache_key = f&quot;{symbol}_1min&quot;<br>    <br>    if cache_key not in market_data_cache:<br>        df = AlphaVantageAPI.get_intraday_data(symbol, &quot;1min&quot;, outputsize=&quot;full&quot;)<br>        market_data_cache[cache_key] = MarketData(<br>            symbol=symbol,<br>            interval=&quot;1min&quot;,<br>            data=df,<br>            last_updated=datetime.now()<br>        )<br>    <br>    data = market_data_cache[cache_key].data.copy()<br>    <br>    # Calculate price changes<br>    delta = data[&#39;close&#39;].diff()<br>    <br>    # Create gain and loss series<br>    gain = delta.copy()<br>    loss = delta.copy()<br>    gain[gain &lt; 0] = 0<br>    loss[loss &gt; 0] = 0<br>    loss = abs(loss)<br>    <br>    # Calculate average gain and loss<br>    avg_gain = gain.rolling(window=period).mean()<br>    avg_loss = loss.rolling(window=period).mean()<br>    <br>    # Calculate RS and RSI<br>    rs = avg_gain / avg_loss<br>    rsi = 100 - (100 / (1 + rs))<br>    <br>    # Get latest RSI<br>    latest_rsi = rsi.iloc[-1]<br>    <br>    # Determine signal<br>    if latest_rsi &lt; 30:<br>        signal = &quot;OVERSOLD (Potential buy opportunity)&quot;<br>    elif latest_rsi &gt; 70:<br>        signal = &quot;OVERBOUGHT (Potential sell opportunity)&quot;<br>    else:<br>        signal = &quot;NEUTRAL&quot;<br>    <br>    return {<br>        &quot;symbol&quot;: symbol,<br>        &quot;period&quot;: period,<br>        &quot;rsi&quot;: latest_rsi,<br>        &quot;signal&quot;: signal,<br>        &quot;analysis&quot;: f&quot;&quot;&quot;RSI Analysis for {symbol}:<br>{period}-period RSI: {latest_rsi:.2f}<br>Signal: {signal}<br><br>Recommendation: {<br>    &quot;BUY&quot; if latest_rsi &lt; 30 else<br>    &quot;SELL&quot; if latest_rsi &gt; 70 else<br>    &quot;HOLD&quot;<br>}&quot;&quot;&quot;<br>    }<br><br>@mcp.tool()<br>def trade_recommendation(symbol: str) -&gt; Dict[str, Any]:<br>    &quot;&quot;&quot;<br>    Provide a comprehensive trade recommendation based on multiple indicators<br>    <br>    Args:<br>        symbol: The ticker symbol to analyze<br>        <br>    Returns:<br>        Dictionary with trading recommendation and supporting data<br>    &quot;&quot;&quot;<br>    # Calculate individual indicators<br>    ma_data = calculate_moving_averages(symbol)<br>    rsi_data = calculate_rsi(symbol)<br>    <br>    # Extract signals<br>    ma_signal = ma_data[&quot;signal&quot;]<br>    ma_crossover = ma_data[&quot;crossover_detected&quot;]<br>    ma_crossover_type = ma_data[&quot;crossover_type&quot;]<br>    rsi_value = rsi_data[&quot;rsi&quot;]<br>    rsi_signal = rsi_data[&quot;signal&quot;]<br>    <br>    # Determine overall signal strength<br>    signal_strength = 0<br>    <br>    # MA contribution<br>    if &quot;BULLISH&quot; in ma_signal:<br>        signal_strength += 1<br>    elif &quot;BEARISH&quot; in ma_signal:<br>        signal_strength -= 1<br>        <br>    # Crossover contribution<br>    if ma_crossover:<br>        if &quot;GOLDEN&quot; in ma_crossover_type:<br>            signal_strength += 2<br>        elif &quot;DEATH&quot; in ma_crossover_type:<br>            signal_strength -= 2<br>            <br>    # RSI contribution<br>    if &quot;OVERSOLD&quot; in rsi_signal:<br>        signal_strength += 1.5<br>    elif &quot;OVERBOUGHT&quot; in rsi_signal:<br>        signal_strength -= 1.5<br>    <br>    # Determine final recommendation<br>    if signal_strength &gt;= 2:<br>        recommendation = &quot;STRONG BUY&quot;<br>    elif signal_strength &gt; 0:<br>        recommendation = &quot;BUY&quot;<br>    elif signal_strength &lt;= -2:<br>        recommendation = &quot;STRONG SELL&quot;<br>    elif signal_strength &lt; 0:<br>        recommendation = &quot;SELL&quot;<br>    else:<br>        recommendation = &quot;HOLD&quot;<br>    <br>    # Calculate risk level (simple version)<br>    risk_level = &quot;MEDIUM&quot;<br>    if abs(signal_strength) &gt; 3:<br>        risk_level = &quot;LOW&quot;  # Strong signal, lower risk<br>    elif abs(signal_strength) &lt; 1:<br>        risk_level = &quot;HIGH&quot;  # Weak signal, higher risk<br>    <br>    analysis = f&quot;&quot;&quot;# Trading Recommendation for {symbol}<br><br>## Summary<br>Recommendation: {recommendation}<br>Risk Level: {risk_level}<br>Signal Strength: {signal_strength:.1f} / 4.5<br><br>## Technical Indicators<br>Moving Averages: {ma_signal}<br>Recent Crossover: {&quot;Yes - &quot; + ma_crossover_type if ma_crossover else &quot;No&quot;}<br>RSI ({rsi_data[&quot;period&quot;]}): {rsi_value:.2f} - {rsi_signal}<br><br>## Reasoning<br>This recommendation is based on a combination of Moving Average analysis and RSI indicators.<br>{<br>    f&quot;The {ma_crossover_type} provides a strong directional signal. &quot; if ma_crossover else &quot;&quot;<br>}{<br>    f&quot;The RSI indicates the stock is {rsi_signal.split(&#39; &#39;)[0].lower()}. &quot; if &quot;NEUTRAL&quot; not in rsi_signal else &quot;&quot;<br>}<br><br>## Action Plan<br>{<br>    &quot;Consider immediate entry with a stop loss at the recent low. Target the next resistance level.&quot; if recommendation == &quot;STRONG BUY&quot; else<br>    &quot;Look for a good entry point on small dips. Set reasonable stop loss.&quot; if recommendation == &quot;BUY&quot; else<br>    &quot;Consider immediate exit or setting tight stop losses to protect gains.&quot; if recommendation == &quot;STRONG SELL&quot; else<br>    &quot;Start reducing position on strength or set trailing stop losses.&quot; if recommendation == &quot;SELL&quot; else<br>    &quot;Monitor the position but no immediate action needed.&quot;<br>}<br>&quot;&quot;&quot;<br>    <br>    return {<br>        &quot;symbol&quot;: symbol,<br>        &quot;recommendation&quot;: recommendation,<br>        &quot;risk_level&quot;: risk_level,<br>        &quot;signal_strength&quot;: signal_strength,<br>        &quot;ma_signal&quot;: ma_signal,<br>        &quot;rsi_signal&quot;: rsi_signal,<br>        &quot;current_price&quot;: ma_data[&quot;current_price&quot;],<br>        &quot;analysis&quot;: analysis<br>    }<br><br># Prompts<br>@mcp.prompt()<br>def analyze_ticker(symbol: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Analyze a ticker symbol for trading opportunities<br>    &quot;&quot;&quot;<br>    return f&quot;&quot;&quot;You are a professional stock market analyst. I would like you to analyze the stock {symbol} and provide trading insights.<br><br>Start by examining the current market data and technical indicators. Here are the specific tasks:<br><br>1. First, check the current market data for {symbol}<br>2. Calculate the moving averages using the calculate_moving_averages tool<br>3. Calculate the RSI using the calculate_rsi tool<br>4. Generate a comprehensive trade recommendation using the trade_recommendation tool<br>5. Based on all this information, provide your professional analysis, highlighting:<br>   - The current market position<br>   - Key technical indicators and what they suggest<br>   - Potential trading opportunities and risks<br>   - Your recommended action (buy, sell, or hold) with a brief explanation<br><br>Please organize your response in a clear, structured format suitable for a professional trader.&quot;&quot;&quot;<br><br>@mcp.prompt()<br>def compare_tickers(symbols: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Compare multiple ticker symbols for the best trading opportunity<br>    <br>    Args:<br>        symbols: Comma-separated list of ticker symbols<br>    &quot;&quot;&quot;<br>    symbol_list = [s.strip() for s in symbols.split(&quot;,&quot;)]<br>    symbol_section = &quot;\n&quot;.join([f&quot;- {s}&quot; for s in symbol_list])<br>    <br>    return f&quot;&quot;&quot;You are a professional stock market analyst. I would like you to compare these stocks and identify the best trading opportunity:<br><br>{symbol_section}<br><br>For each stock in the list, please:<br><br>1. Check the current market data using the appropriate resource<br>2. Generate a comprehensive trade recommendation using the trade_recommendation tool<br>3. Compare all stocks based on:<br>   - Current trend direction and strength<br>   - Technical indicator signals<br>   - Risk/reward profile<br>   - Trading recommendation strength<br><br>After analyzing each stock, rank them from most promising to least promising trading opportunity. Explain your ranking criteria and why you believe the top-ranked stock represents the best current trading opportunity.<br><br>Conclude with a specific recommendation on which stock to trade and what action to take (buy, sell, or hold).&quot;&quot;&quot;<br><br>@mcp.prompt()<br>def intraday_strategy_builder(symbol: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Build a custom intraday trading strategy for a specific ticker<br>    &quot;&quot;&quot;<br>    return f&quot;&quot;&quot;You are an expert algorithmic trader specializing in intraday strategies. I want you to develop a custom intraday trading strategy for {symbol}.<br><br>Please follow these steps:<br><br>1. First, analyze the current market data for {symbol} using the market-data resource<br>2. Calculate relevant technical indicators:<br>   - Moving averages (short and long periods)<br>   - RSI<br>3. Based on your analysis, design an intraday trading strategy that includes:<br>   - Specific entry conditions (technical setups that would trigger a buy/sell)<br>   - Exit conditions (both take-profit and stop-loss levels)<br>   - Position sizing recommendations<br>   - Optimal trading times during the day<br>   - Risk management rules<br><br>Make your strategy specific to the current market conditions for {symbol}, not just generic advice. Include exact indicator values and price levels where possible.<br><br>Conclude with a summary of the strategy and how a trader should implement it for today&#39;s trading session.&quot;&quot;&quot;</pre><p><strong>Configure Claude AI Desktop to run MCP Server</strong></p><p>Navigate to the following directory:</p><p><strong>“C:\Users\username\AppData\Roaming\Claude\claude_desktop_config.json”</strong></p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;AlphaVantageTrader&quot;: {<br>      &quot;command&quot;: &quot;uv&quot;,<br>      &quot;args&quot;: [<br>        &quot;run&quot;,<br>        &quot;--with&quot;,<br>        &quot;mcp[cli]&quot;,<br>        &quot;--with&quot;,<br>        &quot;pandas&quot;,<br>        &quot;--with&quot;,<br>        &quot;requests&quot;,<br>        &quot;--with&quot;,<br>        &quot;tabulate&quot;,<br>        &quot;mcp&quot;,<br>        &quot;run&quot;,<br>        &quot;ABSOLUTE PATH TO YOUR SERVER.PY FILE&quot;<br>      ],<br>      &quot;capabilities&quot;: {<br>        &quot;resources&quot;: {<br>          &quot;subscribe&quot;: true,<br>          &quot;listChanged&quot;: true<br>        }<br>      }<br>    }<br>  }<br>}</pre><p><strong>Or just run the following command in your terminal</strong></p><pre>mcp install finance_server.py</pre><p>Now, first exit claude AI destop app and rerun it again. The tools icon should now be available in your claude desktop app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*_8y6_U8nXe5G11lreo8kGA.png" /><figcaption>On the bottom right of the prompt box</figcaption></figure><p>Type in and you are ready to roll.</p><h3>8. Conclusion and Next Steps</h3><p>We have now built a <strong>Model Context Protocol (MCP) server</strong> that provides stock market insights using <strong>AlphaVantage data</strong> and <strong>technical indicators</strong> like <strong>moving averages</strong> and <strong>RSI</strong>. Our MCP server exposes:</p><ul><li><strong>Resources</strong> to fetch stock price data.</li><li><strong>Tools</strong> to calculate indicators like <strong>moving averages</strong> and <strong>RSI</strong>.</li><li><strong>Prompts</strong> that allow interaction with an LLM for insights.</li></ul><p>By integrating this MCP server with <strong>Claude AI Desktop</strong>, we created a powerful system where an LLM can fetch real-time stock data, analyze trends, and assist in trading decisions.</p><h4>How to Extend the MCP Server</h4><p>You can enhance the MCP server by adding more <strong>technical indicators</strong> and <strong>market signals</strong>, such as:</p><ul><li><strong>MACD (Moving Average Convergence Divergence)</strong>: Identifies trend momentum.</li><li><strong>Support &amp; Resistance Levels</strong>: Detects key price levels where buying/selling pressure exists.</li><li><strong>Candlestick Pattern Recognition</strong>: Detects formations like <strong>Doji, Hammer, and Engulfing</strong> patterns for trading signals.</li></ul><p>Example: Adding a <strong>MACD Calculation Tool</strong></p><pre>@mcp.tool()<br>def calculate_macd(prices: list[float], short_window=12, long_window=26, signal_window=9):<br>    &quot;&quot;&quot;Calculate MACD and Signal Line&quot;&quot;&quot;<br>    short_ema = pd.Series(prices).ewm(span=short_window, adjust=False).mean()<br>    long_ema = pd.Series(prices).ewm(span=long_window, adjust=False).mean()<br>    macd = short_ema - long_ema<br>    signal_line = macd.ewm(span=signal_window, adjust=False).mean()<br>    return {&quot;MACD&quot;: macd.tolist(), &quot;Signal Line&quot;: signal_line.tolist()}</pre><h4>Future Enhancements</h4><p>To make the MCP server more powerful, consider these future upgrades:</p><p>✅ <strong>Backtesting Capabilities</strong></p><ul><li>Implement a <strong>backtesting engine</strong> to simulate strategies based on historical data.</li><li>Compare performance across different indicators and timeframes.</li></ul><p>✅ <strong>Integration with Trading Platforms</strong></p><ul><li>Connect to brokers (e.g., <strong>Interactive Brokers, Alpaca, Binance</strong>) for <strong>live trading</strong>.</li><li>Implement <strong>order execution tools</strong> that allow the LLM to suggest trades.</li></ul><p>✅ <strong>Real-Time Data Streaming</strong></p><ul><li>Upgrade the server to <strong>stream real-time stock prices</strong> instead of fetching snapshots.</li><li>Use <strong>WebSockets</strong> for continuous updates.</li></ul><p>✅ <strong>Portfolio Management Features</strong></p><ul><li>Add functions for <strong>risk management</strong> and <strong>position sizing</strong>.</li><li>Implement alerts for <strong>RSI overbought/sold</strong> or <strong>moving average crossovers</strong>.</li></ul><h3>Stay Connected &amp; Keep Innovating!</h3><p>This is just the beginning! If you have any questions, ideas, or just want to chat about AI, trading, or tech — I’d love to connect!</p><p>💼 <strong>LinkedIn</strong> : <a href="https://www.linkedin.com/in/s-hasan-abbas/">Syed Hasan</a><br>🤗 <strong>Hugging Face</strong>: <a href="https://huggingface.co/Syed-Hasan-8503">Syed-Hasan-8503</a><br><strong>GitHub</strong>: <a href="https://github.com/Hasan-Syed25">SyedHasan</a></p><p>Let’s build the future — Learning is all you need.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a2bfb0c3096" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finetuning Llama-3 using ReFT (Representation Fine-Tuning) Technique]]></title>
            <link>https://medium.com/@syed_hasan/finetuning-llama-3-using-reft-representation-fine-tuning-technique-00f4fe1f497c?source=rss-2a79006f7e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/00f4fe1f497c</guid>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[peft]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Syed Hasan]]></dc:creator>
            <pubDate>Mon, 29 Apr 2024 16:46:20 GMT</pubDate>
            <atom:updated>2024-04-29T16:46:20.929Z</atom:updated>
            <content:encoded><![CDATA[<p>A complete guide on how to fine-tune llama-3–8b using ReFT Technique</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8riqVHSYo2uCS0l6" /><figcaption>Bing Image Generator</figcaption></figure><h3>Introduction</h3><p>Parameter-efficient fine-tuning (PEFT) approaches aim to adjust large langauge models through weight updates that involve only a few parameters. Nonetheless, the majority of the previous studies on interpretability have demonstrated that the representations contain a lot of semantic information, implying that editing representations might be a more effective option. Here is where the Representation Finetuning (ReFT) methods comes in. Infact, LoReFT (Part of the ReFT family) is a drop-in replacement for existing PEFTs and learns interventions that are <strong>10x–50x</strong> more parameter-efficient than prior state-of-the-art PEFTs.</p><p>In this regard, <strong>Zhengxuan Wu et al’s </strong>paper suggests that hallmark of current state-of-the-art PEFTs is that they modify weights rather than representations. However, their work has shown that editing representations might be a more powerful and efficient alternative to weight updates.</p><h3>ReFT (Representation Fine-Tuning)</h3><p>Before jumping into ReFT, we first need to understand what is meant by <strong>Representations. </strong>We know that language model produces contextualised representations of sequences of tokens. Given a sequence of n input tokens x = (x1, . . . , xn), the model first embeds these into a list of representations. Then, model layers successively compute the j-th list of hidden representations h (j) as a function of the previous list of hidden representations h (j−1) . Each hidden representation is a vector. The LM uses the final hidden representations to produce its predictions.</p><p><strong>ReFT’s motivation</strong> originates from the concept of <strong>intervention-based model interpretability</strong>, which stresses altering representations rather than weights. This concept is based on the<strong> linear representation hypothesis</strong>, which states that concepts are encoded in linear subspaces of neural network representations. <br> <br>In this<strong> </strong><a href="https://arxiv.org/pdf/2404.03592"><strong>paper</strong></a>, they decided to use <strong>distributed interchange intervention</strong> operation to make a new parameter-efficient method for adapting language models for downstream tasks. If you want to dive deeper into the concept, feel free to refer to their<strong> </strong><a href="https://arxiv.org/pdf/2404.03592"><strong>paper</strong></a>.</p><h3>PyReFT</h3><p><a href="https://github.com/stanfordnlp/pyreft/tree/main"><strong>PyReFT</strong></a>, is a representation fine-tuning (ReFT) library that supports adapting internal language model representations via trainable interventions. With fewer fine-tuning parameters and more robust performance, Pyreft can boost fine-tuning efficiency, decrease fine-tuning cost, while opening the doors to study the interpretability of adapting parameters.</p><p>Pyreft supports:</p><ul><li>Finetuning any pretrained LMs on HuggingFace with ReFT</li><li>Setting ReFT hyperparameters via configs</li><li>Sharing the fine-tuned results easily to HuggingFace</li></ul><h3>Fine-Tuning Llama-3 using PyReFT</h3><p>I have finetuned Llama-3–8b for 1 epoch on a 10k subset of teknium/OpenHermes-2.5 dataset due to lack of compute resources. Feel free to try it out on the full dataset.</p><h4>Install Dependencies</h4><p>First step would be to install the Pyreft library. If already installed, pyreft will be imported.</p><pre>try:<br>    import pyreft<br><br>except ModuleNotFoundError:<br>    !pip install git+https://github.com/stanfordnlp/pyreft.git</pre><p>Pip install the latest version of transformers or the version that supports llama-3. Moreover, you will be requiring bitsandbytes library as well.</p><pre>!pip install -q git+https://github.com/huggingface/transformers<br>!pip install -q bitsandbytes</pre><p>Make sure your huggingface has access to the gated Llama-3 models and you have to be logged in to your huggingface account. Use the code snippet below.</p><pre>from huggingface_hub import notebook_login<br>notebook_login()</pre><h4>Load Model and Tokenizer</h4><p>Next step would be to set the prompt template for training. Since we will be using the base model, we need to add the special tokens so that the model can learn to stop and do not keep on generating text. Load the model and the tokenizer using the code snippet below.</p><pre>import torch, transformers, pyreft<br>device = &quot;cuda&quot;<br><br>prompt_no_input_template = &quot;&quot;&quot;&lt;|begin_of_text|&gt;&lt;|start_header_id|&gt;user&lt;|end_header_id|&gt;%s&lt;|eot_id|&gt;&lt;|start_header_id|&gt;assistant&lt;|end_header_id|&gt;&quot;&quot;&quot;<br><br>model_name_or_path = &quot;meta-llama/Meta-Llama-3-8B&quot;<br>model = transformers.AutoModelForCausalLM.from_pretrained(<br>    model_name_or_path, torch_dtype=torch.bfloat16, device_map=device, trust_remote_code=True)<br><br># # get tokenizer<br>tokenizer = transformers.AutoTokenizer.from_pretrained(<br>    model_name_or_path, model_max_length=2048, <br>    padding_side=&quot;right&quot;, use_fast=False)<br>tokenizer.pad_token = tokenizer.eos_token</pre><h4>Prepare Model for ReFT FineTuning</h4><p>Set up the pyreft configurations for the model and then use pyreft.get_reft_model() method to get the model ready for representation fine-tuning. For config, we will be applying a single rank-4 LoReFT intervention at 15-th layer to the residual stream of the last prompt token.</p><pre># get reft model<br>reft_config = pyreft.ReftConfig(representations={<br>    &quot;layer&quot;: 8, &quot;component&quot;: &quot;block_output&quot;,<br>    &quot;low_rank_dimension&quot;: 4,<br>    &quot;intervention&quot;: pyreft.LoreftIntervention(embed_dim=model.config.hidden_size,<br>    low_rank_dimension=4)})<br>reft_model = pyreft.get_reft_model(model, reft_config)<br>reft_model.set_device(&quot;cuda&quot;)<br>reft_model.print_trainable_parameters()</pre><h4>Prepare Dataset</h4><p>Prepare the dataset for fine-tuning. I have used a 10k subset of OpenHermes-2.5 dataset. Since Reft Trainer expects the data to be in specific format, we will use pyreft.make_last_position_supervised_data_module() for preparing the data.</p><pre>dataset_name = &quot;teknium/OpenHermes-2.5&quot;<br>from datasets import load_dataset<br><br>dataset = load_dataset(dataset_name, split=&quot;train&quot;)<br>dataset = dataset.select(range(10_000))<br><br>data_module = pyreft.make_last_position_supervised_data_module(<br>    tokenizer, model, [prompt_no_input_template % row[&quot;conversations&quot;][0][&quot;value&quot;] for row in dataset], <br>    [row[&quot;conversations&quot;][1][&quot;value&quot;] for row in dataset])</pre><h4>Start Training</h4><p>Now we will set up the training args for the pyreft.ReftTrainerForCausalLM(). Feel free to change it according to ypur own usecase and compute resources. I will be training the model for 1 epoch only. I tried to integrate wandb but I think there is currently an issue with integration of wandb.</p><pre># train<br>training_args = transformers.TrainingArguments(<br>    per_device_train_batch_size = 4,<br>    gradient_accumulation_steps = 8,<br>    warmup_steps = 100,<br>    num_train_epochs = 1,<br>    learning_rate = 5e-4,<br>    bf16 = True,<br>    logging_steps = 1,<br>    optim = &quot;paged_adamw_32bit&quot;,<br>    weight_decay = 0.0,<br>    lr_scheduler_type = &quot;cosine&quot;,<br>    output_dir = &quot;outputs&quot;,<br>    report_to=[]<br>)<br><br>trainer = pyreft.ReftTrainerForCausalLM(model=reft_model, tokenizer=tokenizer, args=training_args, **data_module)<br><br>_ = trainer.train()</pre><p>Once you are done with the training, save the intervention block to the directory.</p><pre>reft_model.save(<br>    save_directory=&quot;./reft_to_share&quot;, <br>)</pre><h3>Inference</h3><p>For doing inference, set device to cuda. Load the base model and prepare the reft model by merging the intervention block with it. Then shift the reft model to cuda otherwise inference will not be possible.</p><pre>import torch, transformers, pyreft<br>device = &quot;cuda&quot;<br><br>model_name_or_path = &quot;meta-llama/Meta-Llama-3-8B&quot;<br>model = transformers.AutoModelForCausalLM.from_pretrained(<br>    model_name_or_path, torch_dtype=torch.bfloat16, device_map=device)<br><br>reft_model = pyreft.ReftModel.load(<br>    &quot;Syed-Hasan-8503/Llama-3-openhermes-reft&quot;, model, from_huggingface_hub=True<br>)<br><br>reft_model.set_device(&quot;cuda&quot;)</pre><p>Set up the an instruction of your choice and run the code snippet below. <strong>Congrats! </strong>you just infered your first reft finetuned model.</p><pre>instruction = &quot;A rectangular garden has a length of 25 feet and a width of 15 feet. If you want to build a fence around the entire garden, how many feet of fencing will you need?&quot;<br><br># tokenize and prepare the input<br>prompt = prompt_no_input_template % instruction<br>prompt = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(device)<br><br>base_unit_location = prompt[&quot;input_ids&quot;].shape[-1] - 1  # last position<br>_, reft_response = reft_model.generate(<br>    prompt, unit_locations={&quot;sources-&gt;base&quot;: (None, [[[base_unit_location]]])},<br>    intervene_on_prompt=True, max_new_tokens=512, do_sample=True, <br>    eos_token_id=tokenizer.eos_token_id, early_stopping=True<br>)<br>print(tokenizer.decode(reft_response[0], skip_special_tokens=True))</pre><h3>Conclusion</h3><p>Considering the pace we are moving at in this realm of AI, there will surely be better fine-tuning techniques in the future but only those will remain which saves compute resources while showcasing SoTA performance as compared to other techniques. ReFT is surely a hint in that direction if not better.</p><p>Exciting times ahead!</p><p><em>Feel free to reach out to me in case of any queries</em></p><p>Connect with me on</p><p>LinkedIn 👋 : <a href="http://www.linkedin.com/in/hasan-abbas-564427237"><strong>Syed Hasan</strong></a></p><p>Hugging Face 🤗: <a href="https://huggingface.co/Syed-Hasan-8503"><strong>Syed-Hasan-8503</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00f4fe1f497c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding LLM Performance: A Deep Dive into Benchmarking]]></title>
            <link>https://medium.com/@syed_hasan/decoding-llm-performance-a-deep-dive-into-benchmarking-79fcb4316573?source=rss-2a79006f7e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/79fcb4316573</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[llm-benchmarks]]></category>
            <dc:creator><![CDATA[Syed Hasan]]></dc:creator>
            <pubDate>Sun, 10 Mar 2024 10:31:47 GMT</pubDate>
            <atom:updated>2024-03-10T10:31:47.539Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4XiN7ZoxSsRYCG5CtZ03jg.jpeg" /></figure><h3><strong>Introduction</strong></h3><p>Large Language Models (LLMs) are advanced artificial intelligence systems that are being deployed for almost all the problems that you can probably think of. The reason being that they are capable of understanding and generating human-like text at a massive scale. They can think like humans, deduce like humans and can ultimately reach to a conclusion by themselves. Fascinating! isn’t it?</p><p>They have applications in fields like customer service, content generation, language translation, and even scientific research. Ensuring the reliability and robustness of LLMs is crucial for their development and deployment. However, one cannot always check the content generated by these LLMs or how good they are in a task-specific domain manually.</p><p>Here is where the <strong>benchmarking</strong> comes into action. <strong>Benchmarking</strong> involves testing LLMs across diverse datasets and scenarios to identify their strengths, weaknesses, biases, and limitations. These tests help scientists and researchers measure the abilities of LLMs better , making them work better in real life . They also help AI get better by pushing the limits of what it can understand and how it can think .</p><p><em>This Blog is a joint venture between me and my colleague </em><a href="https://www.linkedin.com/in/muhammad-bin-usman/"><em>Muhammad bin Usman</em></a><em>.</em></p><h3><strong>Navigating the LLM Benchmark Landscape</strong></h3><p><strong>HumanEval:</strong> HumanEval is a set of <strong>164 handwritten programming</strong> problems. Each problem includes a function signature, docstring, body, and several unit tests, with an average of 7.7 tests per problem. The tasks range from simple string manipulation to more complex algorithms such as sorting or graph traversal. Each task also includes a solution implemented in Python, which can be used to evaluate the correctness of generated solutions. Running this benchmark on your LLM will provide a realistic assessment of how well a model can generate an accurate code.</p><p><strong>HumanEvalPlus:</strong> HumanEvalPlus is the same as HumanEval, but the only difference being that it has dditional unit tests (80x of the original HumanEval) for each of the 164 problems. The generation and evaluation follows the same approach as HumanEval.</p><p><strong>HumanEvalPack:</strong> HumanEvalPack is an extension of OpenAI’s HumanEval to cover 6 total languages across 3 tasks. The evaluation suite is fully created by humans. This dataset offers a wider range of challenges compared to the original HumanEval, allowing for more comprehensive evaluation. The 6 languages are python, js, java, go, cpp and rust . And the 3 tasks that we will be discussing here are:</p><ul><li><strong>HumanEvalFix:</strong> In this task models are provided with a solution with a subtle bug and several unit tests. The task is to fix the function.</li><li><strong>HumanEvalExplain:</strong> In this task, models must explain a HumanEval solution and then reproduce the solution using just their own explanation. As a result, it is necessary to perform two runs. The first generates descriptions, while the second loads them, develops solutions, and scores them.</li><li><strong>HumanEvalSynthesize:</strong> This is like HumanEval but with human translations for <strong>JavaScript, Java, Go, C++ and Rust.</strong></li></ul><p><strong>Instruct Human Eval:</strong> <strong>164</strong> handwritten Python programming problems accompanied by an instruction , a function signature, and many unit tests.</p><p>This evaluation suite is similar to HumanEval, however it focuses on instruction-tuned models. Each prompt is composed of a command followed by a context, separated by delimiter tokens.</p><p><strong>MBPP (Mostly Basic Python Problems Dataset):</strong> consists of 1,000 mostly simple Python programming challenges aimed to be solved by beginning programmers. Each challenge includes a task description in English, a solution, and <strong>3</strong> automated test cases.</p><p><strong>MBPP+:</strong> MBPP with additional unit tests <strong>(35x of the original MBPP)</strong> for each of the 164 problems.</p><p><strong>DS-1000 (Stanford Question Answering Dataset):</strong> A code generation benchmark with <strong>1000 data science questions </strong>from <strong>7 </strong>Python libraries that</p><ul><li>Portrays diverse, realistic, and practical use cases</li><li>Provides a reliable metric</li><li>Protects against memorization by perturbing questions.</li></ul><p><strong>MultiPL-E (Multi-Programming Language Evaluation of Large Language Models of Code): </strong>A<strong> </strong>benchmark for evaluating large language models for code generation that works with <strong>18</strong> different programming languages. It employs small compilers to translate the OpenAI “HumanEval” Python benchmark into other languages. Hence, the LLMs’ code generation capabilities can be tested across on multiple programming languages</p><p><strong>EQ-Bench: </strong>is an emotional intelligence benchmark for LLMs. It assesses the ability of LLMs to understand complex emotions and social interactions by asking them to predict the intensity of emotional states of characters in a dialogue.</p><p><strong>OpenLLM Suite</strong></p><ul><li><strong>ARC: </strong>stands for <strong>AI2 Reasoning Challenge.</strong> ARC is a dataset designed to test an LLM’s ability to perform elementary science reasoning. The ARC dataset consists of <strong>7,787</strong> science exam questions drawn from a variety of sources, including science questions. These are text-only, English language exam questions that span several grade levels. Each question has a multiple choice format. The questions are sorted into a Challenge Set of 2,590 <strong>“hard”</strong> questions and an <strong>“Easy”</strong> Set of 5,197 questions.</li><li><strong>HellaSwag: </strong>HellaSwag is a benchmark designed to test an LLM’s ability to understand and reason about everyday situations that involve common sense knowledge. It consists of multiple-choice questions where the answers are not explicitly stated in the text but require understanding contextual information and common sense.</li><li><strong>MMLU: </strong>Massive Multitask Language Understanding or MMLU is a benchmark which measures the model’s performance in zero-shot environment. This benchmark covers almost 57 subjects across STEM, humanities, social sciences and more. The granularity and vastness of the subjects makes this benchmark ideal for identifying a model’s blind spots.</li><li><strong>Winogrande: </strong>Winogrande assesses the model on common sense reasoning tasks. It consists of <strong>44k questions </strong>on which it measures the model’s performance. It is based on the <strong>Winograd Schema Challenge. </strong>This challenge proposed the following advantages to the user of this dataset <strong>1) </strong>Knowledge and commonsense reasoning are required to solve them. <strong>2) </strong>Questions<strong> </strong>may<strong> </strong>involve anything from simple cause-and-effect relationships to complex narratives of events. <strong>3)</strong> They may be constructed to test reasoning ability in specific domains. <strong>4)</strong> There is no need for human judges.</li><li><strong>GSM8K: </strong>Grade School Math or GSM8K benchmark measures the model performance on math problems having the same difficulty level as that of the grade school. These problems take between 2 and 8 steps to solve, and solutions primarily involve performing a sequence of elementary calculations using basic arithmetic operations (+ − ×÷) to reach the final answer.</li><li><strong>TruthfulQA: </strong>TruthfulQA as the name suggests, bench the model on the basis of how much truth it provides in its answers. The benchmark comprises <strong>817 </strong>questions that span <strong>38</strong> categories, including health, law, finance and politics.</li></ul><p><strong>Nous Benchmark Suite</strong></p><ul><li><strong>AGIEVAL: </strong>AGIEVAL assesses the foundational models on human centric exams such as college entrance exams, law school admission tests, math competitions, and lawyer qualification tests. This benchmark is derived from 20 official, public, and high-standard admission and qualification exams intended for general human test-takers.</li><li><strong>GPT4ALL: </strong>GPT4ALL is basically a framework that supports running a wide range of LLMs locally. And it tests the model on its own set of benchmarks. Following benchmarks are included: <strong>1) BoolQ</strong> (BoolQ is a question-answering dataset for yes/no questions containing 15942 examples) <strong>2) PIQA</strong> (Questions requiring this kind of physical commonsense pose a challenge to state-of-the-art natural language understanding systems.) <strong>3) WinoGrande</strong> (Where the goal is to choose the right option for a given sentence that requires commonsense reasoning.) <strong>4) OBQA</strong> also known as <strong>OpenBookQA</strong></li><li><strong>TRUTHFUL-QA: </strong>TruthfulQA has been discussed above.</li><li><strong>BIGBENCH: Big-Bench or Beyond the Imitation Game </strong>benchmark quantifies and extrapolate the capabilities of LLMs on diverse task topics like drawing problems from linguistics, childhood development, math, common-sense reasoning, biology, physics, social bias, software development, and beyond.</li></ul><h3>Running LLM Evaluations</h3><p>But just writing about the evals isn’t going to cut it out in today’s day and age when everyone needs code or some sort of implementation guide. We will be discussing different platforms to run these evals.</p><h4><strong>Coding Evaluation Benchmarks</strong></h4><p>For evaluating the models on coding tasks or specifically coding LLMs, <a href="https://github.com/bigcode-project/bigcode-evaluation-harness"><strong>bigcode-evaluation-harness</strong></a><strong> </strong>is the way to go here. A really easy and effective framework for the evaluation of code generation models. It supports multiple tasks but some of the common ones are:</p><ul><li><strong>HumanEval</strong></li><li><strong>HumanEval+</strong></li><li><strong>InstructHumanEval</strong></li><li><strong>APPS</strong></li><li><strong>MBPP</strong></li><li><strong>MBPP+</strong></li><li><strong>DS-1000</strong></li></ul><h4>Setup</h4><pre>git clone https://github.com/bigcode-project/bigcode-evaluation-harness.git<br>cd bigcode-evaluation-harness</pre><pre>pip install -e .</pre><h4>Huggingface CLI Login</h4><pre>huggingface-cli login</pre><h4>Example Generation</h4><pre>accelerate launch  main.py \<br>  --model &lt;MODEL_NAME&gt; \<br>  --tasks &lt;TASK_NAME&gt; \<br>  --limit &lt;NUMBER_PROBLEMS&gt; \<br>  --max_length_generation &lt;MAX_LENGTH&gt; \<br>  --temperature &lt;TEMPERATURE&gt; \<br>  --do_sample True \<br>  --n_samples 100 \<br>  --batch_size 10 \<br>  --precision &lt;PRECISION&gt; \<br>  --allow_code_execution \<br>  --save_generations</pre><p>For more details, you can see their github repository =&gt; <a href="https://github.com/bigcode-project/bigcode-evaluation-harness"><strong>bigcode-evaluation-harness</strong></a></p><p><strong>Evaluation Result Format</strong></p><p>After evaluation has been completed, you can see the detailed results as well generations for each task in a separate file inside big code harness directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*dvbRgZ51W3vUpbwQzSLNAw.png" /><figcaption>Evaluation for Starcoder2-chat on HumanEval</figcaption></figure><h4><strong>NOUS and Open LLM Benchmarks</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zmarCUZ5oimhD56tAtTzGw.png" /><figcaption>LLM AUTOEVAL COLAB</figcaption></figure><p>For Nous and Open LLM benchmarks, we have an easy way out. Big shoutout to <a href="https://github.com/mlabonne/"><strong>Maxime Labonne</strong></a><strong>’s </strong><a href="https://github.com/mlabonne/llm-autoeval"><strong>LLM AutoEval</strong></a><strong>. </strong>LLM AutoEval simplifies the process of evaluating LLMs using a convenient <a href="https://colab.research.google.com/drive/1Igs3WZuXAIv9X0vwqiE90QlEPys8e8Oa?usp=sharing"><strong>Colab notebook</strong></a>. You just need to specify the name of your model, a GPU, and press run! We have different leaderboards for both of these benchmarks.</p><ul><li><a href="https://huggingface.co/spaces/mlabonne/Yet_Another_LLM_Leaderboard"><strong>YALL — Yet Another LLM Leaderboard</strong></a>, mlabonne’s leaderboard made with the gists produced by LLM AutoEval.</li><li><a href="https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard"><strong>Open LLM Leaderboard</strong></a></li></ul><h3>Conclusion</h3><p>So, the big picture here is that figuring out how good these super-powered language models, or LLMs for short, really are is key to making them even better and putting them to good use. Benchmarks are basically like tests that challenge these LLMs in different areas, from writing code to answering science questions, to see what they do well and where they stumble. This article explored a whole bunch of these benchmarks, from code-focused ones to tests that see if the LLMs can understand common sense or follow a scientific train of thought. On top of that, it even threw in some pointers on how to run these tests yourself using tools like bigcode-evaluation-harness and LLM AutoEval. By using these benchmarks and tools, we can keep pushing these LLMs to be smarter and more helpful in the real world.</p><p>Hope this blog post helped you dive deeper into the world of LLM Benchmarks! If you’re interested in learning more about AI, check out my Linkedin and AI newsletter.</p><p><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/hasan-abbas-564427237/">Syed Hasan</a></p><p><strong>AI newsletter</strong>: <a href="https://rethinkai.substack.com/">Rethink AI</a></p><p>Feel free to reach out and connect with me or my colleague <a href="https://www.linkedin.com/in/muhammad-bin-usman/"><em>Muhammad bin Usman</em></a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79fcb4316573" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AutoEncoders: Theory + PyTorch Implementation]]></title>
            <link>https://medium.com/@syed_hasan/autoencoders-theory-pytorch-implementation-a2e72f6f7cb7?source=rss-2a79006f7e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2e72f6f7cb7</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[implementation]]></category>
            <category><![CDATA[theory]]></category>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Syed Hasan]]></dc:creator>
            <pubDate>Sat, 24 Feb 2024 08:29:00 GMT</pubDate>
            <atom:updated>2024-02-24T08:29:00.174Z</atom:updated>
            <content:encoded><![CDATA[<p>Everything you need to know about Autoencoders (Theory + Implementation)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*duawbNnWPSRynrg3.png" /></figure><p>This blog is a joint venture between me and my colleague <a href="https://www.linkedin.com/in/zaiinulabideen/"><strong>Zain ul Abideen</strong></a>.</p><h3>Autoencoder</h3><p><strong>Autoencoders</strong> are a specific type of feedforward neural networks where the input is the same as the output. They compress the input into a lower-dimensional latent representation and then reconstruct the output from this representation. An autoencoder consists of 3 components: encoder, latent representation, and decoder. The encoder compresses the input and produces the representation, the decoder then reconstructs the input only using this representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*32-VK98ppmMz-Ogj.png" /><figcaption>Overview of AE</figcaption></figure><p>An autoencoder consists of an encoder that maps the input <strong>x</strong> to a lower-dimensional feature vector <strong>z</strong>, and a decoder that reconstructs the input <strong>x`</strong> from <strong>z</strong>. We train the model by comparing <strong>x</strong> to <strong>x`</strong> and optimizing the parameters to increase the similarity between <strong>x</strong> and <strong>x`</strong>. The above figure displays the reconstruction loss of the autoencoder as well. The encoder consists of normal Conv2D operations and the decoder consists of upsampling and transpose convolution.</p><p>Autoencoders are mainly used for <strong>dimensionality reduction </strong>(or compression) with a couple of important properties:</p><ul><li>Autoencoders are only able to meaningfully compress data similar to what they have been trained on. Since they learn features specific for the given training data, they are different than a standard data compression algorithm like gzip. So we can’t expect an autoencoder trained on handwritten digits to compress landscape photos.</li><li>The output of the autoencoder will not be exactly the same as the input, it will be a close but degraded representation. If you want lossless compression they are not the way to go.</li><li>To train an autoencoder we don’t need to do anything fancy, just throw the raw input data at it. Autoencoders are considered an unsupervised learning technique since they don’t need explicit labels to train on. But to be more precise they are self-supervised because they generate their own labels from the training data.</li></ul><p>There are <strong>4 hyperparameters</strong> that we need to set before training an autoencoder:</p><ul><li><strong>Dimension of Latent representation:</strong> number of nodes in the middle layer. Smaller size results in more compression.</li><li><strong>Number of layers:</strong> the autoencoder can be as deep as we like. In the figure above we have 2 layers in both the encoder and decoder, without considering the input and output.</li><li><strong>Number of nodes per layer:</strong> the autoencoder architecture we’re working on is called a stacked autoencoder since the layers are stacked one after another. The number of nodes per layer decreases with each subsequent layer of the encoder, and increases back in the decoder. Also, the decoder is symmetric to the encoder in terms of layer structure. As noted above this is not necessary and we have total control over these parameters.</li><li><strong>Loss function:</strong> we either use mean squared error (MSE) or binary cross entropy. If the input values are in the range [0, 1] then we typically use cross-entropy, otherwise, we use the mean squared error.</li></ul><h3>Transposed Convolution and Upsampling</h3><p>Transposed convolution and upsampling are both techniques used in decoder for increasing the spatial resolution of feature maps. Both are widely used, but there are a few differences between them which we will discuss here.</p><p><strong>Transposed convolution</strong>, often referred to as<strong> “deconvolution”</strong>, is a learnable operation that resembles convolution but with some differences. It is used to increase the spatial resolution of feature maps. In transposed convolution, the filter weights are learned during training, allowing the network to adaptively learn the upsampling process. It involves sliding a learnable filter over the input feature map, and instead of computing the dot product between the filter and the input, it computes the dot product between the filter and the output. Transposed convolution introduces additional learnable parameters, making it more flexible but potentially leading to more model complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/0*Efq8Q9qa0Kzz1RpX.png" /></figure><p>The transpose of convolving a 3 × 3 kernel over a 4 × 4 input using unit strides (i.e., i = 4, k = 3, s = 1 and p = 0)</p><p><strong>Upsampling</strong> is a non-learnable operation that simply increases the size of feature maps. It’s a deterministic process that does not involve learnable parameters. Upsampling methods include nearest-neighbor upsampling, bilinear upsampling, and more advanced techniques like pixel shuffling. Nearest-neighbor upsampling replicates the values of the nearest pixel, while bilinear upsampling takes weighted averages of surrounding pixels to compute new values. Upsampling does not introduce new learnable parameters and is computationally less expensive than transposed convolution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*LSr-ouPpWBxNXvZK.png" /><figcaption>Upsampling operation</figcaption></figure><p>To sum it up the major differences between them are:</p><ul><li>Transposed convolution involves learnable filter weights, allowing the network to adapt the upsampling process during training. Upsampling does not introduce learnable parameters; it’s a fixed operation.</li><li>Transposed convolution introduces additional parameters, potentially leading to a more complex model. Upsampling is computationally less expensive as it does not involve learning new parameters.</li><li>Transposed convolution can learn more intricate upsampling patterns, potentially capturing complex relationships in the data. Upsampling methods like bilinear or nearest-neighbor are fixed and do not adapt to data patterns.</li><li>Conv2DTranspose results in Checkerboard artifacts but upsampling doesn’t.</li></ul><h3>Variants of AE</h3><p>Autoencoders, a class of neural networks, have evolved into a diverse family of variants, each tailored to specific data types and tasks. Convolutional autoencoders leverage convolutional layers to excel in image-related tasks, capturing spatial relationships effectively. Sparse autoencoders introduce sparsity constraints on the latent space activations, aiding feature learning and dimensionality reduction. Denoising autoencoders tackle noise by training on corrupted versions of input data, leading to robust feature extraction. Contractive autoencoders include penalty terms in the loss function to enhance stability and reduce sensitivity to input variations. Stacked autoencoders combine multiple layers of autoencoders to create deep architectures for hierarchical feature learning. Finally, variational autoencoders (VAEs) inject probabilistic elements into the latent space, enabling data generation and intricate feature disentanglement. Now, we will go over a few details of Sparse AE and Denoising AE.</p><h3>Sparse AE</h3><p>A sparse autoencoder is simply an autoencoder whose training criterion involves a sparsity penalty. In most cases, we would construct our loss function by penalizing activations of hidden layers so that only a few nodes are encouraged to activate when a single sample is fed into the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/0*Zlw6YG9s8nL8JTIK.png" /><figcaption>Sparse AE</figcaption></figure><p>So, in sparse autoencoder we add L1 penalty to the loss to learn sparse feature representations. L1 regularization adds “absolute value of magnitude” of coefficients as penalty term. Although L1 and L2 can both be used as regularization term, the key difference between them is that L1 regularization tends to shrink the penalty coefficient to zero while L2 regularization would move coefficients towards zero but they will never reach. Thus L1 regularization is often used as a method of feature extraction. Hence the loss function will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/0*FfUAFQxja8EUqzpu.png" /><figcaption>Loss function</figcaption></figure><h3>Denoising AE</h3><p>A Denoising Autoencoder is a modification on the autoencoder to prevent the network learning the identity function. Specifically, if the autoencoder is too big, then it can just learn the data, so the output equals the input, and does not perform any useful representation learning or dimensionality reduction. Denoising autoencoders solve this problem by corrupting the input data on purpose, adding noise or masking some of the input values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*yLpQRWV8tX2V4qpO.png" /><figcaption>Denoising AE</figcaption></figure><h3>Building AE using Pytorch</h3><p>Now, let’s start building a very simple autoencoder for the MNIST dataset using Pytorch. The MNIST dataset is a widely used benchmark dataset in machine learning and computer vision. It consists of a collection of 28x28 grayscale images of handwritten digits (0–9). The dataset is divided into a training set with 60,000 images and a test set with 10,000 images. It’s often employed to evaluate the performance of various neural network architectures and algorithms for digit recognition tasks.</p><p>First of all, we will import libraries like torch, numpy, and matplotlib.</p><pre>import torch<br>import torch.nn as nn<br>import matplotlib.pyplot as plt<br>import time<br>import torch.nn.functional as F<br>from torchvision import datasets<br>from torchvision import transforms<br>from torch.utils.data import DataLoader<br>from torch.utils.data import SubsetRandomSampler<br>from torch.utils.data import sampler<br>import numpy as np<br>import matplotlib.colors as mcolors</pre><p>Then, we will set some hyperparameters like learning rate, batch size, number of epochs and number of classes.</p><pre># Hyperparameters<br>RANDOM_SEED = 49<br>LEARNING_RATE = 0.0005<br>BATCH_SIZE = 256<br>NUM_EPOCHS = 30<br>NUM_CLASSES = 10</pre><p>In the following code snippet, we are downloading the MNIST dataset and setting the training and testing data loader with batch size 256.</p><pre>def get_dataloaders_mnist(batch_size, num_workers=0,<br>                          train_transforms=None, test_transforms=None):</pre><pre>    if train_transforms is None:<br>        train_transforms = transforms.ToTensor()</pre><pre>    if test_transforms is None:<br>        test_transforms = transforms.ToTensor()<br>    train_dataset = datasets.MNIST(root=&#39;data&#39;,<br>                                  train=True,<br>             transform=train_transforms,download=True)<br>    valid_dataset = datasets.MNIST(root=&#39;data&#39;,<br>                                   train=True,<br>                                   transform=test_transforms)<br>    test_dataset = datasets.MNIST(root=&#39;data&#39;,<br>                                  train=False,<br>                                  transform=test_transforms)<br>    train_loader = DataLoader(dataset=train_dataset,<br>                              batch_size=batch_size,<br>                              num_workers=num_workers,<br>                              shuffle=True)<br>    test_loader = DataLoader(dataset=test_dataset,<br>                             batch_size=batch_size,<br>                             num_workers=num_workers,<br>                             shuffle=False)</pre><pre>    return train_loader, test_loader</pre><pre>train_loader, valid_loader, test_loader = get_dataloaders_mnist(batch_size=BATCH_SIZE,<br>    num_workers=2)</pre><p>Let’s check the image batch dimensions and image label dimensions.</p><pre># Checking the dataset<br>print(&#39;Training Set:\n&#39;)<br>for images, labels in train_loader:<br>    print(&#39;Image batch dimensions:&#39;, images.size())<br>    print(&#39;Image label dimensions:&#39;, labels.size())<br>    print(labels[:10])<br>    Break</pre><pre># Output<br>Training Set:<br>Image batch dimensions: torch.Size([256, 1, 28, 28])<br>Image label dimensions: torch.Size([256])<br>tensor([7, 8, 5, 8, 5, 6, 4, 8, 5, 4])</pre><p>Now, we are going to develop the model. The encoder uses four convolution layers with leaky relu as activation. The decoder has four transpose convolution layers and a trimming layer to get the generated image in (28,28) dimension.</p><pre>class AutoEncoder(nn.Module):<br>    def __init__(self):<br>        super().__init__()</pre><pre>        self.encoder = nn.Sequential(<br>                nn.Conv2d(1, 32, stride=(1, 1), kernel_size=(3, 3),     padding=1),<br>                nn.LeakyReLU(0.01),<br>                nn.Conv2d(32, 64, stride=(2, 2), kernel_size=(3, 3), padding=1),<br>                nn.LeakyReLU(0.01),<br>                nn.Conv2d(64, 64, stride=(2, 2), kernel_size=(3, 3), padding=1),<br>                nn.LeakyReLU(0.01),<br>                nn.Conv2d(64, 64, stride=(1, 1), kernel_size=(3, 3), padding=1),<br>                nn.Flatten(),<br>                nn.Linear(3136, 2)<br>        )<br>        self.decoder = nn.Sequential(<br>                torch.nn.Linear(2, 3136),<br>                Reshape(-1, 64, 7, 7),<br>                nn.ConvTranspose2d(64, 64, stride=(1, 1), kernel_size=(3, 3), padding=1),<br>                nn.LeakyReLU(0.01),<br>                nn.ConvTranspose2d(64, 64, stride=(2, 2), kernel_size=(3, 3), padding=1),<br>                nn.LeakyReLU(0.01),<br>                nn.ConvTranspose2d(64, 32, stride=(2, 2), kernel_size=(3, 3), padding=0),<br>                nn.LeakyReLU(0.01),<br>                nn.ConvTranspose2d(32, 1, stride=(1, 1), kernel_size=(3, 3), padding=0),<br>                Trim(),  # 1x29x29 -&gt; 1x28x28<br>                nn.Sigmoid()<br>                )</pre><pre>    def forward(self, x):<br>        x = self.encoder(x)<br>        x = self.decoder(x)<br>        return x</pre><pre>model = AutoEncoder()<br>optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE)</pre><p>The training part starts now. We will use Adam optimizer and train for 30 epochs. We will log the training loss per batch and training loss per epoch for the visualization.</p><pre>def train_autoencoder(num_epochs, model, optimizer,<br>                         train_loader, loss_fn=None,<br>                         logging_interval=100,<br>                         skip_epoch_stats=False,<br>                         save_model=None):</pre><pre>    log_dict = {&#39;train_loss_per_batch&#39;: [],<br>                &#39;train_loss_per_epoch&#39;: []}</pre><pre>    if loss_fn is None:<br>        loss_fn = F.mse_loss</pre><pre>    start_time = time.time()<br>    for epoch in range(num_epochs):</pre><pre>        model.train()<br>        for batch_idx, (features, _) in enumerate(train_loader):</pre><pre>            # FORWARD AND BACK PROP<br>            logits = model(features)<br>            loss = loss_fn(logits, features)<br>            optimizer.zero_grad()</pre><pre>            loss.backward()</pre><pre>            # UPDATE MODEL PARAMETERS<br>            optimizer.step()</pre><pre>            # LOGGING<br>            log_dict[&#39;train_loss_per_batch&#39;].append(loss.item())</pre><pre>            if not batch_idx % logging_interval:<br>                print(&#39;Epoch: %03d/%03d | Batch %04d/%04d | Loss: %.4f&#39;<br>                      % (epoch+1, num_epochs, batch_idx,<br>                          len(train_loader), loss))</pre><pre>        if not skip_epoch_stats:<br>            model.eval()</pre><pre>            with torch.set_grad_enabled(False):  # save memory during inference</pre><pre>                train_loss = compute_epoch_loss_autoencoder(<br>                    model, train_loader, loss_fn)<br>                print(&#39;***Epoch: %03d/%03d | Loss: %.3f&#39; % (<br>                      epoch+1, num_epochs, train_loss))<br>                log_dict[&#39;train_loss_per_epoch&#39;].append(train_loss.item())</pre><pre>        print(&#39;Time elapsed: %.2f min&#39; % ((time.time() - start_time)/60))</pre><pre>    print(&#39;Total Training Time: %.2f min&#39; % ((time.time() - start_time)/60))<br>    if save_model is not None:<br>        torch.save(model.state_dict(), save_model)</pre><pre>    return log_dict</pre><pre>log_dict = train_autoencoder(num_epochs=NUM_EPOCHS, model=model,<br>                                optimizer=optimizer,<br>                                train_loader=train_loader,<br>                                skip_epoch_stats=True,<br>                                logging_interval=250)</pre><p>Plotting the training loss against iterations is shown below. We only trained for 30 epochs. As the loss seems to be decreasing, further iterations will give a better performing model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*NkUEPk5RfJ-lgrNE.png" /><figcaption>Plot of Training Loss and Epochs</figcaption></figure><p>Lets plot the latent space of the autoencoder while highlighting the labels of numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/0*NZYG8cb1GoC_XcRS.png" /><figcaption>Latent space of AE</figcaption></figure><p>The generated images by our model look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*gE31AQ6JIFmLzc-3.png" /><figcaption>Original and Generated images</figcaption></figure><p>The top line shows the original images and the bottom line shows the images generated by the autoencoder. Original images are crisp and sharp while the generated images are blurry.</p><h3>Limitations of Autoencoders</h3><p>Though autoencoders have a lot of applications in the aspect of data compression and feature learning but they are deterministic models, prone to overfitting, and computationally expensive when dealing with large and complex datasets. Let me explain each drawback one by one.</p><p>The simple question that comes to mind is why are they deterministic and why not generative? The answer is that autoencoders do not explicitly model the data distribution or learn the true probability distribution of the input data. While they can be used to generate reconstructions of the input data, they do not inherently learn to generate entirely new data samples from scratch. The primary objective of autoencoders is to capture the most informative and relevant features in the data and produce accurate reconstructions. The latent space learned by autoencoders does not follow any specific probability distribution.</p><p>Sampling from the vanilla autoencoders is also difficult because its learned distribution is oddly shaped, discontinuous, and not centered at (0,0). There are areas called as holes with no points between the images of different types. Thus, if a point is randomly picked up from this empty space, it is not certain whether the desired images will get created. Autoencoder has no way to ensure that the points in the latent space are continuous in nature.</p><p>The autoencoders also face the problem of overfitting where the model learns to capture noise or other artifacts in the training data that do not generalize well to new data. Though there are a few solutions to this problem that include using dropout after the input or adding noise to the input to learn to denoise the image (Denoising Autoencoder). In this way, the model is more robust and does not completely depend on specific features. There is also a possibility of adding L1 penalty to the loss so that the model learns sparse feature representations (Sparse Autoencoder).</p><h3>Conclusion</h3><p>In conclusion, autoencoders are neural network architectures that excel in unsupervised learning tasks by efficiently encoding and decoding imput data representations. They have wide-ranging applications in data <strong>compression</strong>, <strong>denoising,</strong> <strong>feature learning</strong>, and <strong>anomaly detection</strong>, making them valuable tools across various domains including image and text processing. Despite their simplicity, autoencoders offer significant potential for enhancing data analysis and representation learning.</p><p><em>Also, feel free to drop me or my colleague </em><a href="https://www.linkedin.com/in/zaiinulabideen/"><strong><em>Zain ul Abideen</em></strong></a><strong> </strong><em>a message or:</em></p><ol><li>Connect and reach me on<strong> </strong><a href="http://www.linkedin.com/in/s-hasan-abbas"><strong>LinkedIn</strong></a><strong> </strong>and <a href="https://twitter.com/hasansyed_AI"><strong>Twitter</strong></a></li><li>Follow me on 📚 <a href="https://medium.com/@hasansyed8505"><strong>Medium</strong></a></li><li>Subscribe to my 📢 weekly <a href="https://rethinkai.substack.com/"><strong>AI newsletter</strong></a>!</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2e72f6f7cb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring SLM Giants: A comparative analysis of SOTA Small Language Models]]></title>
            <link>https://medium.com/@syed_hasan/exploring-slm-giants-a-comparative-analysis-of-sota-small-language-models-ad6a1fb7563b?source=rss-2a79006f7e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad6a1fb7563b</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[comparison]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[prompt-response]]></category>
            <category><![CDATA[exploration]]></category>
            <dc:creator><![CDATA[Syed Hasan]]></dc:creator>
            <pubDate>Fri, 16 Feb 2024 18:06:52 GMT</pubDate>
            <atom:updated>2024-02-16T18:06:52.273Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XV975VAyUWphXIVzlOT-aA.jpeg" /><figcaption><a href="https://www.unite.ai/small-but-mighty-small-language-models-breakthroughs-in-the-era-of-dominant-large-language-models/">Source</a></figcaption></figure><p>Small Language Models (SLMs) have been the talk of the town for some time now. Different models are being released almost everyday with the focus to achieve on par results with Large Language Models (LLMs). However, in terms of computational and memory cost, SLMs are already ahead. For sometime they have been regarded as only the smaller versions of the LLMs but now the conditions have changed. SLMs are getting better and better with each passing day and their results are somewhat comparable with the LLMs. Now the question arises: <strong>Which SLM is the best? </strong>To answer this question, I compared the performance of these small language models (<strong>Stable LM, Tiny LLama, MINI CPM, and QWEN 1.5</strong>). It was necessary to submit each model to a number of benchmark tests that focused on different NLP tasks. These tasks comprised<strong> emotional</strong> <strong>intelligence evaluation, code generation, text summarization and narrative composition.</strong> By looking at the findings of the evaluation, I found that one model consistently outperformed the other across all tasks, while one consistently performed poorly. The two models were comparable to each other and generated similar responses.</p><p>This blog is a joint venture between me and my colleague <a href="https://www.linkedin.com/in/zaiinulabideen/"><strong>Zain ul Abideen</strong></a>.</p><h3>Advantages of SLMs</h3><p>Before jumping onto the comparison of these SLMs, it is necessary for us to understand what advantages does SLMs have over LLMs. The list is long but some of the most important aspects include:</p><ul><li><strong>Lower computational requirements:</strong> This is because SLMs are often less resource intensive and demand less memory and computing power than LLMs. This allows for their utilization on devices with limited resources and also in environments where compute resource would otherwise be limited.</li><li><strong>Faster training times:</strong> With the lesser number of parameter to optimize during the training, SLMs generally converge faster than LLMs, consequently leading to the quicker and better iterations.</li><li><strong>Cost savings:</strong> The cost of small models usually is lower than what you would pay for the larger ones for both training and usage. The licensing fees could be reduced or probably the small models can be deployed and maintained at very minimized costs.</li><li><strong>Deployment on Cutting-Edge Devices: </strong>Another area where SLMs are more effective than LLMs is on cutting-edge devices, which have resource-limited hardware and they need the optimized computation to make the interface attractive for users. The devices that can be categorized among such examples include <strong>smartphones, wearables, and IoT gadgets.</strong></li></ul><h3>Testing Conditions</h3><p>Prior to conducting comparative analysis of small language models (SLMs), several preconditions were met to ensure consistency and fairness. Specifically, these conditions were:</p><ol><li>All models be instantiated in a conversational format (Chat Models), capable of engaging in dialogues with human.</li><li>The total parameter count for each SLM must not exceed <strong>2 billion</strong>, thereby focusing on truly compact architectures.</li><li>Every model was presented with identical prompts for each task, avoiding any preceding conversation history or context. This approach aimed to minimize bias and ensure that each SLM’s response was solely dependent on the given input.</li></ol><p>Adherence to these conditions would most probably have resulted in unbiased responses from SLMs. Since nothing is perfect, hence the term probably.</p><h3>Comparison</h3><p>Now, we are gonna compare these four LLMs:</p><ul><li>Stable LM-2 1.6 B</li><li>Tiny LlaMA chat 1.1B</li><li>QWEN-1.5 chat 1.8B</li><li>MiniCPM-2B</li></ul><p>across different prompts and we will also rate their responses along with reasoning for each response. We will be doing evaluation on the basis of <strong>emotional</strong> <strong>intelligence, code generation, text summarization and narrative composition.</strong></p><h4>Emotional Intelligence Evaluation</h4><p>We will be using 3 prompts for emotional intelligence evaluation. These prompts are:</p><p><strong>Prompt 1: </strong>Examine the emotion and sentiment expressed in the following movie review excerpt: “The acting was superb, but the plot was predictable and lackluster.” Determine if the overall impression conveyed by the statement leans more towards being positive, negative, or neutral.</p><p><strong>Prompt 2: </strong>Describe two scenarios where understanding customer emotions could significantly contribute to improving business outcomes. Suggest a potential solution involving emotion detection technology for each situation.</p><p><strong>Prompt 3: </strong>Based on the weather conditions described below, predict the likely mood of the speaker: “A heavy blanket of clouds smothered the sky, casting an eerie gray pallor over the once vibrant cityscape. Raindrops pattered against windows with rhythmic monotony, creating a somber symphony that echoed the residents’ melancholic spirits.”</p><p>Few of the screenshots are attached below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HFqAmbGMnipLdWbZ4v0kAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J1z1N1iMmi5SH_bIjOaAPA.png" /></figure><ul><li><strong>Stable LM-2 1.6 B: </strong>Across all three prompts, the responses generated by Stable LM were given a rating of 9/10. The main reason being that it remained consistent in its response, disected the prompt appropriately and had depth in its answer</li><li><strong>Tiny LlaMA chat 1.1B: </strong>The responses generated by this model were ranked 8/10. It provided accurate answers but were over-simplified and depth was missing which is considered important in terms of emotional intelligence</li><li><strong>QWEN-1.5 chat 1.8B: </strong>Its responses have been given the same rating as that of Stable LM-2 i.e. 9/10. It provided very descriptive and precise answers and maintained a balanced perspective</li><li><strong>MiniCPM-2B: </strong>For the first prompt, the model couldn’t perform well (Rating 7/10) but for the remaining two prompts, the results were on par and were given a rating of 9/10. The reason for low rating of first prompt was vague arguments and the model was not confident in its response.</li></ul><h4>Narrative Composition/Story Writing</h4><p>We have done this evaluation on a single prompt and have ranked the response based on the storyline and details incorporated by each response.</p><p>Some of the screenshots of responses are atttached below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ni5pPTHyKdRg2h8Goi4M3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdrJ9n4oofmctwmE0ZTkYw.png" /></figure><p><strong>Prompt: </strong>In a sleepy town where nothing ever happens, ordinary citizens start developing extraordinary powers overnight — an elderly woman gains telekinesis, a schoolboy acquires super strength, and a timid girl suddenly becomes invisible. As everyone grapples with their newfound abilities, tensions rise, fueling fear and prejudice among neighbors. Write a poignant story exploring themes of acceptance, change, and community in this magical setting.</p><ul><li><strong>Stable LM-2 1.6 B: </strong>Rating 9/10. Consistent pacing, good balance of emotion and action, and solid exploration of the themes.</li><li><strong>Tiny LlaMA chat 1.1B: </strong>Rating 8/10. Heartwarming portrayal of acceptance, change, and community. Somewhat predictable yet still engaging, with room for improvement in terms of descriptiveness and complexity of subplots.</li><li><strong>QWEN-1.5 chat 1.8B: </strong>Rating 6/10. There were disparities in tone. There was no linkage between emotional growth and better community issues.</li><li><strong>MiniCPM-2B: </strong>Rating 8/10. It is the conflict resolution, character development, and good theme integration which make the work engaging. The use of subtleness and complexity could help to create the suspense prior to the revelations of the super powers.</li></ul><h4>Code Generation</h4><p>For code generation, we have evaluated the models on 2 prompts</p><p><strong>Prompt 1: </strong>Develop a lightweight microservice written in Go or Rust that resizes incoming JPG images to specified dimensions using OpenCV or any alternative computer vision library. Optimize the solution for minimal latency and memory footprint.</p><p><strong>Prompt 2: </strong>Given a database schema consisting of two tables: “Orders” (OrderID int PRIMARY KEY, CustomerName varchar(50)) and “OrderDetails” (DetailID int PRIMARY KEY, OrderID int, ProductName varchar(50), Quantity int, UnitPrice decimal(18,2)), write an SQL query to retrieve the total revenue for each customer who has placed orders. Format the output as follows: CustomerName, TotalRevenue, where TotalRevenue represents the sum of all products’ prices multiplied by quantities ordered by that customer. Display customers with zero sales too. Sort the final result set alphabetically by customer name.</p><p>Some of the screenshots of the responses are attached below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgqe1hr0wlMh_9Exsa9FqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h0eR755yt8CHYwIWEXf2Ug.png" /></figure><ul><li><strong>Stable LM-2 1.6 B: </strong>Rating 9/10. Stable LM mostly generated the right code but on some instances left the space empty for the user to fill where the main logic should be written.</li><li><strong>Tiny LlaMA chat 1.1B: </strong>Rating 6.5/10. It could not perform well on both the coding tasks specifically in SQL query.</li><li><strong>QWEN-1.5 chat 1.8B: </strong>Rating 7/10. This model generated the worst response for SQL query. But performed relatively well for the Go microservice.</li><li><strong>MiniCPM-2B: </strong>Rating 8.5/10. Performed well on both prompts. Generated a slightly better response for Go Microservice prompt.</li></ul><h4>Text Summarization</h4><p>For this task, I have picked up a random article from the web having approximately 4500 tokens. The article is about <a href="https://www.bu.edu/wcp/Papers/Bioe/BioeMcGe.htm">Ethical Assessment of Implantable Brain Chips</a></p><p>Some screenshots are attached below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tq_f0VlWEF-l1vAzvk7ppw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1re4UjQp14HY7PsHxpreDg.png" /></figure><ul><li><strong>Stable LM-2 1.6 B: </strong>Rating 7/10.It touches on almost all the important points of the original text, but misses some nuances about the potential societal implications of the technology.</li><li><strong>Tiny LlaMA chat 1.1B: </strong>Rating 8/10.<strong> </strong>It covers all the relevant topics and adds valuable context to some of the issues raised in the original text.</li><li><strong>QWEN-1.5 chat 1.8B: </strong>Rating 0/10. No text generated due to fixed context length (2048) of the model.</li><li><strong>MiniCPM-2B: </strong>Rating 9/10.<strong> </strong>The response generated by this model is the strongest, as it comprehensively addresses the topic and offers insightful commentary on the ethical and societal implications of implantable brain chips.</li></ul><h3>Conclusion</h3><p>After the comparative evaluation and performance assessment of<strong> Stable LM-2, Tiny LLama, MINI CPM and QWEN 1.5</strong>, it was found that Stable LM-2 outperformed others. Its emotional intelligence, coding exercises, text summarization, and story writing abilities demonstrated its competence.</p><p>In the other end of the game play, Tiny llama had been trailing behind its competitors, being beaten on almost each task. Through splashes of brilliance, it was able to keep up with the rest of the contenders, earning its place as the least efficient model.</p><p>As for MINI CPM and QWEN 1.5, the study indicated that their performances were quite the same through most of the tests. Besides not being able to surpass Stable LM-2, both of them exhibited flair in some areas and therefore could be utilized alongside each other according to the user case requirements or availability of resources.</p><p>For complete responses for each prompt and detailed responses, visit <a href="https://docs.google.com/spreadsheets/d/1qSF0PAEzrPUbkQODNlV808N8II-oowCRLmAgZpXX5V4/edit?usp=sharing"><strong>Analysis Report.</strong></a></p><p>Reach out to my colleague: <a href="https://www.linkedin.com/in/zaiinulabideen/"><strong>Zain ul Abideen</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad6a1fb7563b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>