<?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 OpenMMLab on Medium]]></title>
        <description><![CDATA[Stories by OpenMMLab on Medium]]></description>
        <link>https://medium.com/@openmmlab?source=rss-7b857bec476d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GJ3FIwXgnItx-pY22aSbqg.png</url>
            <title>Stories by OpenMMLab on Medium</title>
            <link>https://medium.com/@openmmlab?source=rss-7b857bec476d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 06 Apr 2026 00:22:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@openmmlab/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[InternLM3 Open Source: Achieving High-Performance Models with 4T Data]]></title>
            <link>https://openmmlab.medium.com/internlm3-open-source-achieving-high-performance-models-with-4t-data-c18e94bd5c6a?source=rss-7b857bec476d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c18e94bd5c6a</guid>
            <dc:creator><![CDATA[OpenMMLab]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 10:33:58 GMT</pubDate>
            <atom:updated>2025-01-16T11:37:36.953Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Written by InternLM Team</blockquote><p>On January 15, Shanghai AI Lab announced a major upgrade to the InternLM model with the release of InternLM3. By refining its data framework, InternLM3 significantly improved data efficiency and achieved a leap in IQPT (Intelligence Quality per Token).</p><p>The InternLM3–8B-Instruct, trained with only 4T of data, outperformed other open-source models of the similar scale while cutting training costs by over 75%. Additionally, for the first time, IntenLM3 integrates routine conversational capabilities with deep thinking in a general-purpose model, enabling it to handle a wider range of real-world scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kMe3eafKUBczk6w4" /></figure><p>Demo page: <a href="https://internlm-chat.intern-ai.org.cn">https://internlm-chat.intern-ai.org.cn</a></p><p>HuggingFace: <a href="https://huggingface.co/internlm">https://huggingface.co/internlm/internlm3-8b-instruct</a></p><p>GitHub: <a href="https://github.com/InternLM/InternLM">https://github.com/InternLM/InternLM</a></p><h3>High IQPT drives high-performance reasoning</h3><p>Data is a key driver for enhancing large model capabilities. Currently, most popular open-source models rely on expanding the scale of pretraining data to improve performance, with datasets typically approaching 20T tokens. This approach, however, leads to a linear increase in training costs and raises industry-wide concerns about data bottlenecks and the sustainability of the Scaling Law.</p><p>Our research team believes that improving data quality offers far greater benefits than merely increasing data volume.The data IQPT (Intelligence Quality per Token) is the core of data quality, i.e., the logic, complexity, and inspiration embedded in the thinking process of data. To this end, we proposes a large-scale data streamlined framework, which substantially improves the quality of training data.</p><p>In practice, InternLM3 achieved the performance of popular open-source models trained on 18T tokens by using only 4T tokens of pretraining data. Enhancing the performance of models by improving the data IQPT brings a new research paradigm for breaking the Scaling Law.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w7Oz1sZi_a-JJf0G" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CU-UF9k9i4BzeFsW" /></figure><p>To better evaluate the impact of data IQPT, we quantified the metric by defining IQPT as the ratio of a model’s average performance to the amount of training data. This provides a measure of the “return on investment” for large model training data. Compared to leading open-source models of similar scale, using Llama3.1 as a benchmark, the data IQPT of InternLM3 is more than 4 times higher.</p><p>Through the data streamlined framework, we significantly improved data efficiency for InternLM3, achieving a substantial increase in IQPT. This framework consists of two key components:</p><ul><li><strong>Intelligent Data Processing</strong>: To enable fine-grained data handling, we divided the data into millions of domains. Using self-evolution techniques for intelligent agents, large-scale automated quality checks were implemented. Based on misclassifications, reflections were made, and customized processing was applied to each domain.</li><li><strong>Synthesis of High-Value Data</strong>: By integrating general and specialized models, we rapidly iterated synthesis algorithms, then selected data to train specialized models. Through material mining in vast amounts of natural data, improved tree-search strategies, and multi-dimensional quality validation, we synthesized a large volume of rich, high-quality data.</li></ul><p>Using the OpenCompass open-source evaluation framework, we conducted evaluations on InternLM3 and other models with a reproducible, unified method. The evaluation utilized over ten authoritative benchmark sets, including CMMLU, GPQA, and others, covering various performance dimensions such as reasoning, mathematics, programming, instruction-following, long texts, dialogue, and overall performance. The results show that InternLM3 outperforms similar open-source models on most benchmarks, with overall performance closely matching GPT-4o-mini.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SHZU0lo4FUuFFMjb" /></figure><h3>Fusion of Deep Thinking and General Conversation</h3><p>Exploring general artificial intelligence through the “general-specialized integration” approach relies on synchronously enhancing deep reasoning and domain-generalization capabilities. With the release of InternLM3 for the first time, deep reasoning and general conversational abilities have been integrated into a single general-purpose model, enabling it to handle a broader range of real-world scenarios.</p><p>Due to the significant differences in data styles between deep reasoning and general conversation, the industry often develops specialized models for reasoning tasks. Previously, the Shanghai AI Lab introduced InternThinker, a high-performing reasoning model capable of long-form reasoning, self-reflection, and correction during inference, outperforming o1-preview on mathematical competition benchmarks.</p><p>Following the “general-specialized integration” approach, we explored methods for training on a fusion of different data types. This enables to combine general conversational and deep reasoning abilities seamlessly. By leveraging system prompts, users can switch the model between conversational and reasoning modes with a single command, endowing the general-purpose model with deep thinking capabilities.</p><p>In the post-training phase, we developed task-driven and knowledge-system-driven synthetic data strategies. This includes instruction annotation and synthesis based on the World Knowledge Tree and high-quality response generation using multi-agent techniques. By maximizing the potential of real and synthetic user instructions, we categorized multi-task scenarios with fine granularity, creating hundreds of thousands of high-quality fine-tuning instruction datasets, which significantly improved the model’s conversational experience.</p><p>As shown in the diagram below, during inference tasks, users can switch InternLM3 from general conversation mode to deep reasoning mode with a single click.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LeF-6qXYyRj5-m-o" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c18e94bd5c6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Announcing XTuner: An Efficient Finetune Toolkit for LLM]]></title>
            <link>https://openmmlab.medium.com/announcing-xtuner-an-efficient-finetune-toolkit-for-llm-757ddc9587c3?source=rss-7b857bec476d------2</link>
            <guid isPermaLink="false">https://medium.com/p/757ddc9587c3</guid>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[OpenMMLab]]></dc:creator>
            <pubDate>Fri, 01 Sep 2023 11:01:11 GMT</pubDate>
            <atom:updated>2023-09-01T11:01:11.267Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*Y7IBrQcAANYJNFRqcFwF0Q.png" /></figure><p>The advent of ChatGPT has provided a glimpse into the dawn of general artificial intelligence. Meanwhile, tech companies are making their own large language models open source one after another.</p><p>However, the high hardware costs associated with large models often pose a significant barrier to many researchers.</p><p>To democratize access to these powerful models and empower various industries, Shanghai Artificial Intelligence Laboratory has developed XTuner, a low-cost toolkit for training large models. <strong>With XTuner, 8GB GPU memory is all you need to create your own AI assistant.</strong></p><p><a href="https://github.com/InternLM/xtuner">https://github.com/InternLM/xtuner</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vopYSxEPrC_XrqO1" /></figure><p>XTuner offers a wealth of features that can be freely composed and matched. In addition to standalone functions, XTuner introduces three breakthrough technologies allowing developers to truly work “data-centric”:</p><ol><li><strong>Efficient Data Engine</strong>: XTuner supports several popular open-source dataset formats and allows for mixed usage:</li></ol><p>Alpaca format</p><p>MOSS format</p><p>Gunacao format</p><p>OpenAI format</p><p>…and more being added continuously</p><pre>pip install xtuner<br><br># To train data in a mixture of Alpaca and Gunacao datasets<br>xtuner train internlm_7b_qlora_alpaca_enzh_oasst1_e3</pre><p>Also, XTuner offers full decoupling for different dataset formats based on the characteristics of LLM-Training data. This allows fine-tuning without disrupting the dialogue templates of Chat models.</p><p><strong>2. Multiple Training Engines</strong>: XTuner pioneers the integration of HuggingFace and OpenMMLab, balancing usability and configurability. It supports both MMEngine Runner and HuggingFace Trainer. Thus, developers with deep customization needs can flexibly configure according to their habits.</p><pre>pip install xtuner<br><br># To use MMEngine Runner for training<br>xtuner train internlm_7b_qlora_oasst1_e3<br><br># To use HuggingFace Trainer for training<br>xtuner train internlm_7b_qlora_oasst1_e3_hf</pre><p><strong>3. One-click Training Start</strong>: XTuner integrates standard procedures for incremental pre-training, single-round &amp; multi-round dialogue instruction tuning. Developers only need to focus on the data. Furthermore, XTuner incorporates technologies like QLoRA, DeepSpeed, and FSDP, offering solutions for varying model sizes under different hardware specifications. Just 8GB GPU memory can fine-tune a 7B model.</p><pre>pip install &#39;xtuner[deepspeed]&#39;<br><br># Fine-tuning a Llama2-7B model with only 8GB GPU memory<br>xtuner train llama2_7b_qlora_oasst1_512_e3 --deepspeed deepspeed_zero2</pre><p>Developers can focus on the data and leave the rest to XTuner, freeing up more energy to explore the vast universe of large models!</p><p>With XTuner, developers can add plugins to large models to supplement their capabilities, or even gain some skills exclusive to ChatGPT. XTuner provides a rich selection of large model plugins on the HuggingFace Hub. Feel free to download and try them out!</p><p><a href="https://huggingface.co/xtuner">https://huggingface.co/xtuner</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4Rb4mPvfEMbal-A8" /></figure><p>Inspired by Pac-Man, the XTuner logo reflects a playful spirit. The development team and the open-source community aim to have fun exploring large models and developing a variety of entertaining applications. Your ideas are always welcome in the XTuner discussions, where you can find like-minded partners. The XTuner team will continue to replicate popular community projects at a low cost, inviting more people to ride the wave of large models.</p><p><a href="https://github.com/InternLM/xtuner">https://github.com/InternLM/xtuner/discussions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=757ddc9587c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The AI New Era: How Should Large Models “Rack Their Brains”]]></title>
            <link>https://openmmlab.medium.com/the-ai-new-era-how-should-large-models-rack-their-brains-1ee6c86545f1?source=rss-7b857bec476d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ee6c86545f1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[OpenMMLab]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 11:01:37 GMT</pubDate>
            <atom:updated>2023-08-24T11:01:37.311Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*bjshERc4SjpePzL4W7sdFw.png" /></figure><blockquote>Welcome to follow the official <a href="https://twitter.com/OpenMMLab">OpenMMLab Twitter</a> account to stay updated with our latest news.</blockquote><p>As ChatGPT is launched, Large Language Models (LLMs) have been garnering significant attention in the AI field. However, despite their impressive capabilities, LLMs still face substantial challenges in handling complex multi-step reasoning tasks, such as mathematical applications and common-sense reasoning. This has led to the inclusion of more complex reasoning datasets like GSM8k and MATH in the evaluations of large models.</p><p>To address the shortcomings of LLMs in complex reasoning, researchers have been actively developing innovative techniques. Among these attempts, the “Chain-of-Thought Prompting” technique has gained special attention. This approach aims to guide the model in breaking down complex multi-step problems into more manageable intermediate steps, aiding the model in better understanding and solving problems accurately. Practical results have shown significant advancements in various reasoning tasks, especially arithmetic reasoning, through the application of Chain-of-Thought Prompting.</p><h3>What is Chain of Thought？</h3><p>Imagine a scenario where a teacher presents a challenging thinking and reasoning problem to a student named Tom: &quot;In a cage on a farm, there are a total of chickens and rabbits, totaling 36 animals. The total number of legs is 100. Determine how many chickens and rabbits there are.&quot; Suppose Tom doesn&#39;t have paper and pen and must provide an answer directly. He attempts: &quot;There are 20 chickens and 16 rabbits.&quot; ❌ , Unfortunately, there&#39;s an error in his mental calculation.</p><p>The teacher gives Tom a second chance, allowing him to solve the problem step by step using paper and pen. Tom records the intermediate steps:</p><pre>Let x be the number of chickens, and y be the number of rabbits.<br>x + y = 36 (total number of animals is 36)<br>2x + 4y = 100 (total number of legs is 100)<br>Solve the first equation for one variable, for example, x = 36 - y.<br>Substitute the value of x into the second equation:<br>2(36 - y) + 4y = 100<br>72 - 2y + 4y = 100<br>2y = 28<br>y = 14<br>Substitute the value of y back into the first equation to find x:<br>x = 36 - 14<br>x = 22<br>Hence, the answer is:<br>There are 22 chickens and 14 rabbits. ✅</pre><p>Through step-by-step reasoning, Tom successfully arrives at the correct answer and earns the teacher’s approval :&gt;</p><p>Similarly, when using large language models, you can prompt them step by step, just like the teacher helped Tom, guiding the model to solve complex problems. This is the essence of the earliest Chain of Thought : few-shot Chain of Thought. It involves prompting the model with a few-shot example that includes intermediate reasoning steps before the answer. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*3YISGB1QUshtnIa6" /></figure><h3>Few-Shot CoT：Unveiling the Chain of Thought</h3><p><strong><em>Chain of Thought Prompting Elicits Reasoning in Large Language Models.</em></strong></p><p>The early version of Chain of Thought is suitable for Few-Shot prompts. Compared to standard Few-Shot prompts, Chain of Thought Few-Shot prompts only add reasoning steps before the answer. For instance, an original prompt might look like:</p><p><strong>Sample problem + Answer + Actual problem</strong></p><p>The input to the model directly yields the problem’s answer. With the addition of Chain of Thought to the prompt, it becomes:</p><p><strong>Sample problem + Sample reasoning steps + Answer + Actual problem</strong></p><p>The <strong>sample reasoning steps</strong> are the <strong>Chain of Thought</strong> used to solve the original problem. This guides the model to generate intermediate steps before outputting the answer, breaking down the original problem into multiple sub-problems and aiding the model’s “<strong>thinking</strong>”. Not only does this method significantly enhance the model’s reasoning ability without requiring model modifications, but it also yields immediate effects. On the PaLM-540B dataset, there was an almost threefold improvement using Chain of Thought compared to the traditional method of boosting model performance through fine-tuning. Chain of Thought can be seen as opening new doors for enhancing large model reasoning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*YT5tnOJlq7ZF4QIB" /></figure><p>So, are there any simpler ways to implement the Chain of Thought, and is there a Zero-Shot version of the Chain of Thought implementation? Indeed, there is.</p><h3>Zero-Shot CoT：Simple yet Effective</h3><p><strong><em>Large Language Models Are Zero-Shot Reasoners</em></strong></p><p>Perhaps the simplest CoT method:</p><p>You can easily implement a Zero-Shot CoT prompt by simply adding “<strong>Let’s think step by step</strong>” after the question. This effortlessly implements a zero-shot Chain of Thought prompt without requiring additional samples. It clearly instructs the model to think through the problem step by step, enhancing its problem-solving capabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/0*w_0NOZfIFSajxsCN" /></figure><p>This is a simple and effective way to enhance the model’s reasoning abilities, akin to how the teacher helped Tom by breaking down and solving the problem step by step. When using large models, this approach serves as a tool to prompt the model to decompose and answer complex questions.</p><p>For the same <strong>MultiArith</strong> dataset, the paper experimented with various similar prompts, showing varying effects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*FWqSN3tO3afL-shB" /></figure><p>Thus, in practice, when employing the Zero-Shot CoT approach for reasoning tasks, it’s essential to experiment with various prompts tailored to the dataset’s characteristics.</p><h3>Self-Consistency (SC): Multi-Path Reasoning + Voting Mechanism</h3><p><strong><em>Self-Consistency Improves Chain of Thought Reasoning in Language Models.</em></strong> The SC method, developed by the Google Brain team, enhances reasoning accuracy by generating multiple different reasoning paths for a given problem and voting for the most frequent answer among these paths.</p><p>In the SC method, for a single problem, multiple CoT results are generated. This is equivalent to having the model generate reasoning steps and answers multiple times. The final answer is obtained through majority voting. For example, if k = 3, the generated paths and answers could be 18, 18, and 26. Taking the majority yields 18.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j_Io0vEQmNSnncf9" /></figure><p>This method excels in complex reasoning tasks; however, compared to the regular CoT approach, it requires more time and resources. Does this mean that the more samples are taken, the better the effect?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xs1lHnW4GFcvfNr8" /></figure><p>According to experimental results from the paper, the performance improvement of the SC method starts to plateau when the sampling count “k” ranges from 20 to 40 in various reasoning datasets. In most cases, the datasets tend to saturate at around 40 samples. However, conducting 40 samples requires significant resource consumption. Therefore, when using the SC method, it’s important to choose an appropriate sampling count based on the specific needs and available resources. This allows for a balance between effect enhancement and resource utilization.</p><h3>Tree-of-Thoughts (ToT)：Multi-dimensional Thinking for Comprehensive Problem Solving</h3><p><strong><em>Tree of Thoughts: Deliberate Problem Solving with Large Language Models</em></strong></p><p>The ToT method differs from traditional CoT approaches. It allows models to consider multiple different reasoning paths concurrently. It involves evaluating multiple segments of reasoning processes and making global choices through foresight or backtracking when necessary. This results in the formation of a tree-like reasoning structure, as depicted on the right side of the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SYOuq8LDaJjLwIL4" /></figure><p>Specifically, it comprises the following four stages:</p><ol><li><strong>Thought Decomposition</strong> Based on the nature of the problem, the problem is broken down into multiple intermediate steps. Each step could be a phrase, equation, or writing plan, depending on the problem’s characteristics.</li><li><strong>Thought Generation</strong> Assuming that solving the problem requires “k” steps, there are two methods to generate the reasoning content for each step:</li></ol><blockquote>Independent Sampling: For each state, the model independently extracts “k” reasoning contents from the CoT prompts, without relying on other reasoning contents.</blockquote><blockquote>Sequential Generation: Sequentially using prompts to guide the generation of reasoning content step by step, where each reasoning content might depend on the previous one.</blockquote><p><strong>3. Heuristic Evaluation</strong> Heuristic methods are used to evaluate the contribution of each generated reasoning content to problem solving. This self-assessment is based on the language model’s self-feedback, achieved by designing prompts that allow the model to score multiple generated results.</p><p><strong>4. Search Algorithm</strong> Based on the methods for generating and evaluating reasoning content, an appropriate search algorithm is chosen. For example, breadth-first search (BFS) or depth-first search (DFS) can be used to systematically explore the tree of thoughts, including foresight and backtracking.</p><p>Using the example of the 24-Game, where the task is to determine if four given integer values can be combined using +, -, ×, and ÷ operations to yield a result of 24, the ToT method can be applied as follows:</p><ol><li>It can be divided into three steps, with each step representing an intermediate equation. For example, given the numbers 4 9 10 13, the following three steps solve the problem:</li></ol><p>13 - 9 = 4 (left: 4 4 10);</p><p>10 - 4 = 6 (left: 4 6);</p><p>4 * 6 = 24 (left: 24)</p><p>2. In each step, the process of generating multiple candidates using a few-shot prompt method (as shown in (a) below) is used.</p><p>3. For each candidate in each step, the process described in (b) is employed to evaluate the candidates using the model. This involves evaluating whether the remaining numbers 10, 13, and 13 can yield a possible result of 24 pointsImpossible. The next step begins with candidates that have higher scores.</p><p>4. Steps 2 and 3 are carried out for each step to generate intermediate equations and perform evaluations.</p><p>5. A breadth-first search (BFS) is conducted to sample feasible solution paths (shown in green).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fbc9Ol9rWIYAI4OG" /></figure><p>Regarding the effectiveness of ToT, taking the 24-Game as an example, when using the GPT-4 model as the base model, the performance of ToT is significantly superior to general CoT methods. In this scenario, SC and Few-Shot CoT achieve less than 10% accuracy on the task, while ToT achieves an accuracy of 74%:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/0*eDIEYMi4gqUpUoix" /></figure><p>However, in terms of task usability, employing the ToT method requires familiarity with the task and the ability to break it down into logical and manageable steps. Furthermore, it necessitates the design of corresponding generation and evaluation methods for each step of the task. Finally, DFS or BFS techniques are used for sampling solutions. Additionally, it’s crucial to have a strong grasp of following prompt instructions in the base model, much like the GPT-4 model used by the authors of the paper. If you can meet these requirements, ToT could serve as a powerful tool for solving complex problems.</p><h3>Make your model even stronger</h3><p><strong>OpenCompass</strong> is a comprehensive evaluation platform for large models launched by the Shanghai Artificial Intelligence Laboratory. OpenCompass currently supports a range of CoT (Chain-of-Thought) techniques, including those mentioned earlier, from <strong>Zero-Shot CoT</strong> to <strong>Tree-of-Thoughts</strong>.</p><p>Leveraging OpenCompass’ extensive evaluation capabilities, you can effortlessly conduct diverse CoT evaluations on over 300,000 questions from 50+ datasets for more than 20 open-source large models and OpenAI API models. Below is an example of testing SC method on the GSM8k dataset using OpenCompass:</p><pre># Configuration for SC version of gsm8k test can be found in:<br># opencompass.configs.datasets.gsm8k.gsm8k_gen_a3e34a.py.<br><br>gsm8k_infer_cfg = dict(<br>    inferencer=dict(<br>        type=SCInferencer, # Replace GenInferencer with SCInferencer<br>        # Set generation parameters to ensure diverse model outputs, currently applicable for models loaded from HuggingFace.<br>        generation_kwargs=dict(do_sample=True, temperature=0.7, top_k=40),<br>        sc_size=SAMPLE_SIZE # Number of SC paths to sample<br>    )<br>)<br><br>gsm8k_eval_cfg = dict(sc_size=SAMPLE_SIZE)</pre><p>In addition to implementing these methods, OpenCompass has introduced some new features. For instance, while the <a href="https://github.com/princeton-nlp/tree-of-thought-llm/tree/master">official ToT repository</a> currently only supports OpenAI API models,<strong> OpenCompass extends this support to common open-source large models. This makes it easy to experiment with customizations and classic datasets across models of different scales and types.</strong></p><p>Below is a comparison of SC and ToT evaluation results obtained using OpenCompass:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8FSBXdJ9pbknWvVu" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IDXowVNdaqnpP1XC" /></figure><p>OpenCompass aims to integrate the powerful tool of CoT to help the community unlock the immense potential of large language models across various tasks. With more researchers and practitioners joining the effort, AI technology is expected to become smarter, more efficient, and more practical in the future.</p><p>OpenCompass Project Link:</p><p><a href="https://github.com/internLM/OpenCompass/">https://github.com/internLM/OpenCompass/</a></p><p>CoT Tutorial: <a href="https://opencompass.readthedocs.io/zh_CN/latest/prompt/chain_of_thought.html">https://opencompass.readthedocs.io/zh_CN/latest/prompt/chain_of_thought.html</a></p><p>Large Model Leaderboard: <a href="https://opencompass.org.cn/leaderboard-llm">https://opencompass.org.cn/leaderboard-llm</a></p><p>Welcome everyone to submit evaluation applications on OpenCompass :</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ee6c86545f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benchmarking the multi-modal capability of Bard with MMBench]]></title>
            <link>https://openmmlab.medium.com/benchmarking-the-multi-modal-capability-of-bard-with-mmbench-383bdf0913b9?source=rss-7b857bec476d------2</link>
            <guid isPermaLink="false">https://medium.com/p/383bdf0913b9</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mmbench]]></category>
            <category><![CDATA[bard-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[OpenMMLab]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 02:57:24 GMT</pubDate>
            <atom:updated>2023-08-18T02:57:24.066Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*CjAQtf1OKGC69K-qTBUDkQ.jpeg" /></figure><p>In March 2023, Google launched Bard, a lightweight and optimized version of LaMDA based on Transformer. Similar to ChatGPT, Bard is a close-sourced model and provide service to users via web UI. In July 2023, Google announced the latest update of Bard, which is capable of processing image input. In order to provide an overview of Bard’s multi-modal ability, we evaluate it on the test split of MMBench as below and compare it with other state-of-the-art VLMs.</p><p>Project: <a href="https://opencompass.org.cn/MMBench">https://opencompass.org.cn/MMBench</a></p><h3>Evaluation Setting</h3><p>The test split of MMBench includes 1798 questions. During testing, we find that Bard refuses to process images containing human faces. For a fair comparison, we remove questions that Bard refuse to answer and discard questions that evaluate four human-related capabilities (Image Emotion, Identity Reasoning, Social Relation, and Action Recognition) in the test split. After filtering, we build a subset of 1226 samples and 16 leaf ability dimensions.</p><h3>Quantitative Results</h3><p>We compare Bard with two state-of-the-art VLMs that perform well on MMBench, namely Shikra and Otter-I. The result is shown in the figure below. Bard attains an impressive overall accuracy of 51%, positioning itself among the top-tier VLMs proposed to date. Notably, Bard excels in answering questions that involve common sense reasoning. It achieves 62.3% accuracy on Nature Relation questions and 45.2% accuracy on Physical Relation questions, outperforming its counterparts, <em>e.g.</em>, Otter-I and Shikra, by a substantial margin. Meanwhile, an analysis reveals that Bard’s performance is comparatively lower in tasks requiring spatial perception, such as Spatial Relationship and Object Localization. This observation aligns with expectations, considering that Shikra incorporates visual grounding tasks into its training data to enhance its localization capabilities, a facet potentially not integrated into Bard’s training process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/0*6ME6cWW2oqKDW5B_" /></figure><h3>Qualitative Results</h3><p>To complement the quantitative analysis, we also provide some qualitative examples of Bard. Some good cases are demonstrated in the figure below. In the left-hand example, Bard adeptly processes intricate scenes, distills key information, and arrives at a reasonable conclusion. Notably, the majority of VLMs subjected to our testing fail to deliver the correct response to this particular question. In the right-hand example, Bard recognizes the correct concept from cartoon, sidestepping any potential confusion arising from the harmonious interaction between a snake and a mouse. This highlights Bard’s exceptional common sense reasoning ability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SXQ3udu5Vy2EnX5I" /></figure><p>In the next figure, we present illustrative examples that highlight Bard’s performance shortcomings. These instances originate from both image style and image quality tasks. The former entails the model to discern image categories, while the latter involves assessing visual attributes, such as brightness, across a pair of images. A shared characteristic between these tasks is the insignificance of image content concerning the task’s objectives. Bard performs bad on the two tasks, achieving 50% and 7% accuracy on each tasks respectively. The accompanying tables within these cases visually demonstrate Bard’s tendency to excessively focus on semantic concepts and depicted objects within the provided text and image, leaving it struggling to effectively address inquiries regarding holistic styles and attributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H08y6yG73nqhHnW0" /></figure><h3>Bard Provides well-structured Responses</h3><p>Last but not least, in all the aforementioned examples, Bard consistently delivers well-structured responses, frequently utilizing bullet-point lists and tables to enhance clarity. Moreover, across a majority of the questions, Bard adheres to a consistent response format: presenting the predicted option initially, subsequently offering a comprehensive rationale, and culminating by enumerating the reasons for the incorrectness of alternative choices. From the perspective of being a chatbot, Bard undeniably stands out as one of the most exceptional multi-modal chatbots.</p><h3>A Brief Intro of MMBench</h3><p>MMBench is a multi-modality benchmark released in early July 2023, which includes <strong>~3000 </strong>multiple choice questions to evaluate over <strong>20 </strong>different multi-modal capabilities. Since the benchmark release, more than <strong>200 </strong>submissions have been received, and the leaderboard has covered <strong>15 VLMs</strong> till now. More information:</p><p>Project: <a href="https://opencompass.org.cn/MMBench">https://opencompass.org.cn/MMBench</a></p><p>Paper: <a href="https://arxiv.org/pdf/2307.06281.pdf">https://arxiv.org/pdf/2307.06281.pdf</a></p><p>Codebase: <a href="https://github.com/InternLM/opencompass">https://github.com/InternLM/opencompass</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=383bdf0913b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Faster and More Efficient 4-bit quantized LLM Model Inference]]></title>
            <link>https://openmmlab.medium.com/faster-and-more-efficient-4-bit-quantized-llm-model-inference-a27d35a66c29?source=rss-7b857bec476d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a27d35a66c29</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[OpenMMLab]]></dc:creator>
            <pubDate>Wed, 16 Aug 2023 03:53:05 GMT</pubDate>
            <atom:updated>2023-08-16T03:53:05.040Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://github.com/InternLM/lmdeploy">LMDeploy</a> has released an exciting new feature — 4-bit quantization and inference. This not only trims down the model’s memory overhead to just 40% of what FP16 inference would take, but more importantly, with extreme optimized kernel, the inference performance has not been compromised. Instead, it’s more than three times the speed of FP16 inference on Gerforce RTX 4090.</p><p>We conducted benchmarks on both Llama-2–7B-chat and Llama-2–13B-chat models, utilizing with 4-bit quantization and FP16 precision respectively. The throughput for generating completion tokens was measured by setting a single prompt token and generating 512 tokens in response. All the results was measured for single batch inference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9oWswTi8uI8-WHch" /></figure><p>As shown in the diagram, 4-bit inference with LMDeploy achieves 3.16 times faster than FP16 inference. And it outperforms other extradinary competitors by a margin of around 30% to 80%.</p><p>As for memory overhead, we tested scenarios with context window sizes of 1024, 2048 and 4096 respectively. The 4-bit 7B model can easily be accommodated by a single Geforce RTX 3060.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4WZstjPzpKw7yYrs" /></figure><p>For more detailed test results, please refer to the <a href="https://aicarrier.feishu.cn/docx/EwTpdiwloopogSxhnlycjQjLnEh#FnSAdijWbovRIbxCEZNcGRjxnsd">benchmark</a> section of this article.</p><h3>Quick Start</h3><h3>Installation</h3><p>The minimum requirement for performing 4-bit LLM model inference with LMDeploy on NVIDIA graphics cards is sm80, which includes models such as the A10, A100, and Geforce RTX 30/40 series.</p><p>Before proceeding with the inference, please ensure that lmdeploy(&gt;=v0.0.5) is installed.</p><pre>pip install lmdeploy</pre><h3>Get 4-bit quantized model</h3><p>You can visit<a href="https://huggingface.co/lmdeploy"> LMDeploy’s model zoo</a> to download pre-quantized 4-bit models.</p><pre>git-lfs install<br>git clone https://huggingface.co/lmdeploy/llama2-chat-7b-w4</pre><p>Alternatively, you can quantize the model weights to 4-bit by following the instructions presented in <a href="https://github.com/InternLM/lmdeploy#quantization">this</a> guide.</p><h3>Inference</h3><pre>## Convert the model&#39;s layout and store it in the default path, ./workspace.<br>python3 -m lmdeploy.serve.turbomind.deploy \<br>    --model-name llama2 \<br>    --model-path ./llama2-chat-7b-w4 \<br>    --model-format awq \<br>    --group-size 128<br><br>## inference<br>python3 -m lmdeploy.turbomind.chat ./workspace</pre><h3>Serve with gradio</h3><p>If you wish to interact with the model via web ui, please initiate the gradio server as indicated below:</p><pre>python3 -m lmdeploy.serve.gradio.app ./workspace --server-ip {ip_addr} --server-port {port}</pre><p>Subsequently, you can open the website http://{ip_addr}:{port} in your browser and interact with the model</p><h3>Benchmark</h3><p>LMDeploy uses two evaluation metrics to measure the performance of the inference API, namely <strong>completion token throughput </strong>(also known as output token throughput) and <strong>request throughput</strong>. The former tests the speed of generating new tokens, given specified number of prompt token and completion token, while the latter measures the number of requests processed per minute under real dialogue data.</p><h3>Completion token throughput</h3><p>We utilized lmdeploy’s <a href="https://github.com/InternLM/lmdeploy/blob/main/benchmark/profile_generation.py">profile_generation.py</a> to test the token generation throughput and memory usage of the 4-bit and 16-bit Llama-2–7B-chat models under different batches on an A100–80G. The number of prompt tokens and completion tokens were set to 1 and 512, respectively.</p><p>The comparison results for throughput and GPU memory usage are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FkAV2GFrcWmIe8EL" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NJCq5wEmV7v2xCLC" /></figure><h3>Request throughput</h3><p>We also tested the request throughput of the 4-bit and 16-bit Llama-2–7B-chat by lmdeploy’s <a href="https://github.com/InternLM/lmdeploy/blob/main/benchmark/profile_throughput.py">profile_throughput.py</a> on an A100–80G GPU. The comparison results are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gd2I01EoOKs8B7iv" /></figure><h3>More</h3><p>In addition to 4-bit quantization, LMDeploy also supports int8 quantization for k/v cache. We believe that the combination of these two will further improve inference performance. More detailed performance evaluation will be reported soon. Welcome to follow <a href="https://github.com/InternLM/lmdeploy">https://github.com/InternLM/lmdeploy</a> to stay up-to-date with the latest news!</p><p>The more you star, the more you get :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a27d35a66c29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thoroughly evaluate AX620A from the perspective of security industry]]></title>
            <link>https://openmmlab.medium.com/thoroughly-evaluate-ax620a-from-the-perspective-of-security-industry-d12c3175516a?source=rss-7b857bec476d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d12c3175516a</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[chips]]></category>
            <dc:creator><![CDATA[OpenMMLab]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 10:48:19 GMT</pubDate>
            <atom:updated>2023-08-10T11:00:04.116Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*VHuzwL6x3JSWRuoF" /></figure><p>We’ll thoroughly evaluate AX620A from the perspective of security and defense business as a third-party <a href="https://platform.openmmlab.com/deploee">Deploee</a>. We’ll test and assess AX620A’s performance in various dimensions such as model design, inference, and SDK. We will also provide corresponding test source code and running logs. We hope this information will provide valuable insights for chip selection.</p><p><a href="https://platform.openmmlab.com/deploee">OpenMMLab Platform Link</a></p><h3>Product Introduction</h3><p>AX620A is the second-generation visual chip launched by AXERA, configured with a 4-core Cortex-A7 CPU and 3.6Tops@int8 NPU computing power.</p><p>In int4 mode, AX620A’s computing power will be promoted to 14.4 Topps. However, int4 has the specific requirements for model design, and the official open-source documentation has not clarified the usage. We did not consider this part in this test.</p><p>Pure computing units cannot be tested practically. Therefore, we chose the Maix-III AXera-Pi, a development board designed by sipeed based on the AX620A chip. As of August 7, 2023, the retail price of the core board is less than $40. The singeboard(core board+baseboard) comes with a USB3.0 baseboard, core board, WIFI module, Ethernet interface, camera, and a 5-inch display screen, making it fully functional and convenient for work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8xF4IopG1-m7YJ5d" /></figure><p>After acquiring the device, we first tested its CPU performance using the testing tool megpeak, a tool capable of measuring peak computational performance that supports arm, x86, and OpenCL architectures.</p><p>In this test, we modified CMakeLists.txt, and the gcc compilation parameters and explanations are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RZKi_OBSsVVwWfjyuCKLZw.png" /></figure><p>Here’s what we got:</p><pre>there are 4 cores, currently use core id :0<br><br>bandwidth: 1.861453 Gbps<br>padal throughput: 5.411672 ns 0.739143 GFlops latency: 6.405562 ns :<br>padd throughput: 1.509807 ns 2.649345 GFlops latency: 5.024015 ns :<br>mla_s32 throughput: 5.275521 ns 1.516438 GFlops latency: 5.290761 ns :<br>mlal_s8 throughput: 2.923057 ns 5.473721 GFlops latency: 5.025521 ns :<br>mlal_s16 throughput: 2.770953 ns 2.887093 GFlops latency: 5.106042 ns :<br>mlal_s16_lane throughput: 2.765276 ns 2.893020 GFlops latency: 5.027750 ns :<br>mla_f32 throughput: 5.354490 ns 1.494073 GFlops latency: 10.047442 ns :<br>mul_s32 throughput: 5.393568 ns 0.741624 GFlops latency: 5.274667 ns :<br>mul_f32 throughput: 5.387370 ns 0.742477 GFlops latency: 5.398443 ns :<br>cvt throughput: 5.377729 ns 0.743808 GFlops latency: 5.352896 ns :<br>qrdmulh throughput: 5.275443 ns 0.758230 GFlops latency: 5.353959 ns :<br>rshl throughput: 2.763766 ns 1.447301 GFlops latency: 5.023833 ns :</pre><p>The results we obtained are:</p><ul><li>The actual memory bandwidth is 1.86 Gbps. Actual memory provided by the device is 1.2GB</li><li>For int8 multiplication, the 4-core CPU can provide a total of 22 gflops of computing power, 3.7 times that of fp32 multiplication</li></ul><p>Users can estimate the execution time of image processing code based on these data — assuming memory movement and calculation are well optimized and do not interfere — such as dividing the computation by 1.49 gflops if there is a significant amount of fp32 computation, or dividing by memory bandwidth if the main operation is memory copying.</p><p>Next, we begin evaluating NPU performance. AX620A supports 1_1 mode, where half of the computing power is used for night vision enhancement, and the other half for AI computation. Considering that security scenarios usually require enhanced image quality at night, all our subsequent tests will enable 1_1 mode. If you need to compare qps with other similar chips, AX620A’s results need to be multiplied by 2.</p><h3>Single Operator Test</h3><p>AX620A’s model conversion tool is called pulsar, a python script inside a docker image. Currently, pulsar supports 46 kinds of onnx operators. The complete support list can be found here: <a href="https://pulsar-docs.readthedocs.io/zh_CN/latest/appendix/op_support_list.html">onnx support list</a>.</p><h3>Testing Process</h3><p>Although we can not test every operator, just like GEMM can be broken down into multiple GEPP/GEBPs, operators can also be broken down into basic operations. Based on the calculation process, we classified these 46 onnx operators into 9 categories and selected one from each category for testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vISPZ0VMLtDjxsbB4Xay9w.png" /></figure><p>Next, we used torch2onnx to generate corresponding onnx models for these 9 operators.</p><p>Due to the numerous operator parameters, to avoid excessively long test time, we fixed the input shape of conv at 224x224, while other models were tested at three different scales: 112x112, 384x256, and 1080x1920. Eventually, we obtained 170 single-operator onnx models. The torch code to generate these models can be found here: <a href="https://github.com/tpoisonooo/deploee-benchmark/tree/main/operator">github link</a>.</p><p>Then, we used pulsar to convert these onnx operators. We successfully converted 139 models, and 28 models had clear error logs during the conversion process, including one softmax conversion that got stuck.</p><p>Finally, in the successfully run models, we measured the different operators’ energy efficiency ratio, an indicator showing the number of MACs (multiply-accumulate) completed per microsecond. We sorted by energy efficiency ratio, and here are some of the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZIsCmsg4F7UIJQCcprRctA.png" /></figure><h3>Result Analysis</h3><p>The test results are consistent with the official Efficient Operator <a href="https://pulsar-docs.readthedocs.io/zh_CN/latest/appendix/efficient_op_design_guides.html">Design Guidelines</a>, and we observed more phenomena:</p><ul><li>When stride=2, the efficiency of conv7x7 surpassed conv3x3</li><li>Using conv1x1 instead of gemm can make better use of NPU</li><li>The overhead of binary operations like add is not low</li></ul><p>The complete test results, including the conversion process logs, statistical tables, and execution scripts, can be found here: <a href="https://github.com/tpoisonooo/deploee-benchmark/blob/main/ax620a/opr_test.md">https://github.com/tpoisonooo/deploee-benchmark/blob/main/ax620a/opr_test.md</a></p><p>The user can adjust the parameters of the model according to mac_util and efficiency in the table.</p><h3>Model Testing</h3><p>The hardware model library contains 640 onnx models converted by OpenMMLab algorithms. These models are related to various tasks such as 3D detection, segmentation, key point recognition, OCR, etc. They are very suitable for testing the completeness of the vision chip software stack.</p><p>Since AX620A does not support dynamic shape, it can not support models like mmdet3d-voxel, mmaction, and LLaMa. Therefore, we have selected 318 fixed input size onnx models for testing.</p><p>However, during the conversion process of some models, errors occurred due to some operators not being implemented. Here are the cases where many operators are missing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*IiE9H8XJGMlDtWzO9KE0UQ.png" /></figure><p>In the end, we successfully converted 60 models. Now let’s take a look at the running time of the resnet series models on AX620A:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*yMtLEEEYNgJv-yBRAk62-w.png" /></figure><p>Compared to resnet50’s runtime of over 100ms on the Jetson Nano, the speed of axera-pi has increased 5 times, and its retail price is only 1/2 of the former, showing obvious cost performance.</p><p>The onnx models used for testing can be searched and downloaded in the hardware model library. Execution logs and results have been published at the following link: <a href="https://github.com/tpoisonooo/deploee-benchmark/blob/main/ax620a/model_test.md">https://github.com/tpoisonooo/deploee-benchmark/blob/main/ax620a/model_test.md</a></p><h3>SDK Evaluation</h3><p>Visual SDK is usually composed of multiple pipelines. Its inputs are images or videos, and the outputs are structured data. Since image decoding is often not a performance bottleneck, when developing a visual SDK, we need to consider video decoding, image operations, and compatibility with the pipeline.</p><h3>Decoding</h3><p>In the field of security, the most commonly used video formats are h.264 and h.265, mainly adopting main or high profile, with a standard size of 1088x1920. Although the video frame rate used in our tests is 60fps, this will not affect our final conclusion.</p><pre>$ ffmpeg -i 1088x1920.h264<br>..<br>    Stream #0:0: Video: h264 (High 10), yuv420p10le(progressive), 1920x1088 [SAR 136:135 DAR 16:9], 57 fps, 59.94 tbr, 1200k tbn, 119.88 tbc</pre><p>We made slight modifications to the ax-pipeline source code to test the peak decoding speed in different situations (such as output scaling, cropping, flipping, etc.). This is because, in practical business, the width and height of the video are not fixed. In some chip implementations, correcting video output may cause a decrease in decoding speed, while using smaller video sizes can speed up decoding. Therefore, we need to take these situations into account when testing decoding speed. Here are the test results we obtained on the AX620A:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*WE5JGM10TJshaxtq6jEEoA.png" /></figure><p>As mentioned above, we can see that the video decoding speed of AX620A is almost stable at 60fps and is not affected by image processing operations.</p><h3>Image Processing Support</h3><p>The second factor affecting pipeline throughput is image processing speed. Take common face recognition as an example. Before recognition, it is necessary to correct the face image. At this time, whether you can use the CPU and NPU to efficiently achieve perspective transformation may determine the maximum throughput of the pipeline. The following table lists the image processing operators provided by AX620A in IVPS (Video Image Processing Subsystem). Users can consult the complete documentation at the following link: <a href="https://github.com/sipeed/axpi_bsp_sdk/tree/main/docs">https://github.com/sipeed/axpi_bsp_sdk/tree/main/docs</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*Cqw6HTH2SrAUpB1ux8m8Xg.png" /></figure><p>Due to the lack of WarpPerspective and TopK, to deploy a complete face business, it may be necessary to adjust the image correction and feature engineering implementation.</p><h3>Conclusion</h3><p>From the perspective of security industry, we have conducted a comprehensive test of AX620A, covering various evaluation indicators such as CPU, operators, models, and SDK, and provided detailed operation logs and script support for this.</p><p>According to the experimental results, we have reached the following conclusions:</p><ol><li>Cost Performance: ★★★★★</li></ol><p>AX620A has strong performance. In comparison with the Jetson Nano’s contemporaneous product, it achieves more than a 5-fold performance improvement at less than 1/2 of its retail price and with 50% of its own computing power.</p><p>2. Usability: ★★★★☆</p><p>Pulsar is implemented based on Docker, and users can use it directly without complicated installation and configuration. At the same time, AX620A provides complete samples and documentation, providing good support for users. However, the lack of chip architecture documentation makes AX620A slightly deficient in transparency.</p><p>3. Model Compatibility: ★★★☆☆ AX620A has limited support for dynamic shape; a few models cannot be converted within 2 hours, reflecting room for improvement in compatibility.</p><p>4. CV Operators and Decoding Support: ★★★☆☆</p><p>AX620A can meet basic computer vision operators and decoding needs, but the API has usage restrictions.</p><p>If AX620A can further optimize pulsar, improve model compatibility, etc., it has the potential to become a perfect vision NPU chip. We have learned from industry channels that these issues have been resolved in AXERA’s third-generation vision chip AX650N, and we are looking forward to its performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d12c3175516a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Llama-2 models easily with LMDeploy!]]></title>
            <link>https://openmmlab.medium.com/deploy-llama-2-models-easily-with-lmdeploy-1cb001d70290?source=rss-7b857bec476d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cb001d70290</guid>
            <dc:creator><![CDATA[OpenMMLab]]></dc:creator>
            <pubDate>Wed, 02 Aug 2023 11:09:57 GMT</pubDate>
            <atom:updated>2023-08-02T11:09:57.018Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*lTrvsc3gzGBzgeDy" /></figure><p>This article will guide you on how to quickly deploy the Llama-2 models with <a href="https://github.com/InternLM/lmdeploy">LMDeploy</a>.</p><p>There are 3 types of Llama-2 models that have been open-sourced so far: 7B, 13B, and 70B. Comparing to Llama-1, the 7B and 13B structures remain unchanged, while the 70B adjusts it, replacing Multi-Head Attention with Grouped-Query Attention. Overall, it’s not too difficult to implement. Let’s get started!</p><h3>The LMDeploy’s Journey with Llama-2</h3><h3>Getting Started: 7B/13B</h3><p>Meta provides Llama-2 7B and 13B conversation models with context window size 4096. As they have the same structure as Llama, all we need to do is to add the Llama-2 chat template in LMDeploy.</p><p>Tip: LMDeploy can deploy any language models with the same structure as Llama or Llama-2. Feel free topull PRs about their chat template to LMDeploy :)</p><p>The installation of LMDeploy is very simple:</p><pre>pip install lmdeploy</pre><p>By following the steps below, you will be able to interact with it via the command line:</p><pre>python3 -m lmdeploy.serve.turbomind.deploy llama2 //the/path/of/llama-2-chat-7b-hf<br>python3 -m lmdeploy.turbomind.chat ./workspace</pre><p>Launch the triton inference server to serve the model:</p><pre>tritonserver --model-repository=./workspace/model_repository/ --allow-grpc=1 --grpc-port=33337</pre><p>If you want to use the webui chat window, you can do the following:</p><pre>python3 -m lmdeploy.app {tritonserver_ip_addr}:33337</pre><p>Open the webpage <a href="https://localhost:6006/">https://localhost:6006</a> in your browser, and you can chat with AI assistant online.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FaIAz2s73DrwSLOW" /></figure><p>LMDeploy has outstanding inference performance, outperforming similar open-source projects in output token throughput and request throughput metrics. Among them, output token throughput measures the token generation speed under fixed input and output tokens. Request throughput tests the number of requests processed per minute under real conversation scenario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kbYQp7tZx8hCmV7Q" /></figure><p>The above diagram shows output token throughput when the input and output tokens are (2048, 2048). It can be concluded that LMDeploy is about 5% — 15% higher than DeepSpeed overall and outperforms the official facebook Llama-2 inference by up to 5x.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/0*_etv1XNXwXKRNGMp" /></figure><p>In terms of request throughput, LMDeploy is about 30% higher than vLLM.</p><h3>Advancing: 70B</h3><p>Llama-2 70B uses GQA (Grouped-Query Attention). As shown in the following diagram, GQA divides query heads into groups, each of which shares a single key head and value head. When the number of groups equals the number of query heads, it becomes MHA (Multi-Head Attention). When the group is 1, it is MQA (Multi-Query Attention).</p><p>According to the literature, GQA is close to MHA in terms of model capability while being as efficient as MQA in terms of inference speed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/0*hfTjRf_UAODMYaI-" /></figure><p>使用 MHA 结构的自回归模型，在推理过程中，会维护一个巨大的 k/v cache。它的内存开销公式为：</p><p>Auto-regressive models using MHA structure maintain a large k/v cache during the inference process. Its memory overhead formula is:</p><pre>batch * max_seq_len * n_heads * head_dim * sizeof(half) * 2</pre><p>而对于 GQA 来说，k/v cache 的内存开销公式变成：</p><p>While for GQA, the formula becomes:</p><pre>batch * max_seq_len * n_kv_heads * head_dim * sizeof(half) * 2</pre><p>n_heads / n_kv_heads is the size of the group. As you can see, using GQA can reduce the k/v cache to 1/group of MHA. This is very beneficial for attention, which is memory-intensive computation.</p><p>LMDeploy has implemented GQA and supports tensor parallelism. The deployment method is similar to that of 7B. You just need to set the tensor parallel parameter to 8 when converting the model structure. For more details, please refer to <a href="https://github.com/InternLM/lmdeploy/blob/main/docs/zh_cn/serving.md">serving</a>.</p><h3>LMDeploy’s Special Features</h3><h3>Interactive mode Inference: No More Paying for Conversation History</h3><p>In multi-turn conversation scenarios, most inference engines require users to send the prompt as well as the past conversation history to the server. This means that users have to pay for the history in each round of the conversation. LMDeploy can cache all attention k/v of the conversation, thus avoiding repetitive processing of historical conversations. We call this procedure interactive mode, which can greatly reduce the latency of generating the first token, especially for long conversation history.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9NHUZi_J3N-Yni7R" /></figure><h3>Persistent Batch: The key to high throughput</h3><p>LMDeploy models the inference of a conversational LLM as a persistently running batch whose lifetime spans the entire serving process. To put it simply:</p><ul><li>- The persistent batch as N pre-configured batch slots.</li><li>- Requests join the batch when there are free slots available. A batch slot is released and can be reused once the generation of the requested tokens is finished.</li><li>- The batch grows or shrinks automatically to minimize unnecessary computations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*KdOc9uamQ9Ws7C3VL2mWcw.gif" /></figure><h3>Conclusion</h3><p>Other exciting features of LMDeploy are still under intense development. Welcome to follow our project at <a href="https://github.com/InternLM/lmdeploy">https://github.com/InternLM/lmdeploy</a> for the latest updates!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cb001d70290" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[It’s 2023. Is PyTorch’s FSDP the best choice for training large models?]]></title>
            <link>https://openmmlab.medium.com/its-2023-is-pytorch-s-fsdp-the-best-choice-for-training-large-models-fe8d2848832f?source=rss-7b857bec476d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe8d2848832f</guid>
            <dc:creator><![CDATA[OpenMMLab]]></dc:creator>
            <pubDate>Tue, 01 Aug 2023 09:03:47 GMT</pubDate>
            <atom:updated>2023-08-01T09:28:54.649Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*YSYEALyE_fAxjgp2UzY0yA.jpeg" /></figure><p>The wave of large model training initiated by ChatGPT has made many eager to try their hand at training large models. When looking for training baselines, you’ve surely noticed that the codebase for training large models tends to use frameworks like <a href="https://www.deepspeed.ai/">DeepSpeed</a> (<a href="https://github.com/open-mmlab/mmengine">MMEngine v0.8.0 </a>also supports it, allowing one-click switching for convenience!) or ColossalAI (MMEngine will support it in the next version!), with scant regard for PyTorch’s native FSDP (FullyShardedDataParallel). But why is this? Is FSDP not memory-efficient enough? Is it too slow for training? Or is it simply inconvenient to use? Read on, and I’m sure you’ll gain some insights.</p><h3>Background of FSDP</h3><p>FSDP’s implementation was inspired by FairScale. When developing large features, PyTorch typically creates a new library to provide some experimental support and collect user feedback, such as FairScale, Dynamo (the cornerstone of PyTorch 2.0), and torchdistx. Once the feature becomes more mature, it may be incorporated into PyTorch. Compared to the brief introduction of FSDP in PyTorch’s official tutorial, FairScale has done a much better job. Before we start the introduction, here is an introduction by FairScale, and it’s worth considering: do you really need FSDP? (This is also true for other large-scale training frameworks)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/0*lJPXccwMtoDkrkGd" /></figure><h3>Introduction to the ZeRO Series</h3><p>Having seen the above figure, you’ll notice that FairScale defines FSDP as ZeRO3. Considering that some may not be familiar with the ZeRO series of large model optimization strategies, let me give a brief introduction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/0*NYSIXYtu-KIEiCae" /></figure><p>During model training, memory usage can be largely divided into three parts: activation values, model weights, gradients, and optimizer states. For vision models, activation values take up most of the memory, so mixed-precision training can significantly reduce memory usage (fp16). However, for large language models or multimodal models, optimizing the memory usage of the latter three becomes more important.</p><p>Taking PyTorch as an example, when you use DistributedDataParallel, it allocates memory for model parameters, gradients, and optimizer states in each process and synchronously updates this data during training. Although this approach can speed up training through data parallelism, its memory allocation strategy is evidently poor. Since the parameters in each process are the same, why should each process save the complete set of parameters? Thus, ZeRO advocates that each process should only save a part of the parameters, gathering them into all processes when needed. ZeRO has three stages of optimization strategies:</p><p>ZeRO1: Sharding only the optimizer state</p><p>ZeRO2: Sharding both the optimizer state and gradients</p><p>ZeRO3: Sharding optimizer state, gradients, and model parameters</p><p>Take a model with 7.5B (φ) parameters as an example, let’s briefly calculate the memory usage of model parameters, gradients, and optimizer states:</p><p><strong>fp32 training:</strong></p><p>The model parameter size is φ, the gradient size is also φ, and in the case of using Adam, the optimizer state is 2φ. If it’s standard fp32 training, then the actual memory used is (1 + 1 + 2)φ * 4: 16φ bytes (4 is the memory size occupied by fp32 data).</p><p><strong>fp16 training:</strong></p><p>If mixed-precision training is enabled, to ensure the precision of parameter updates, the optimizer state needs to remain in fp32, and an additional copy of fp32 model parameters needs to be stored. Therefore, memory usage is 2φ(model parameters) + 2φ(model gradients) + 8φ(optimizer state) + 4φ(copy of fp32 model parameters stored in optimizer in the DeepSpeed implementation): 16φ bytes.</p><p>From this perspective, it’s clear why the memory usage of a 7.5B model can be as high as 120B, and why the ZeRO series is so effective.</p><h3>FSDP — ZeRO3?</h3><p>Returning to the main topic, FairScale says that FSDP is equivalent to ZeRO3’s optimization. Let’s understand this through a simple example (in this example, the optimizer is SGD because PyTorch’s Adam has been heavily optimized and its actual memory usage is much higher than theoretical). Before the official test, let’s look at the tests of single device fp32 training, single device fp16 training, and DDP fp16 training:</p><h3>Single device fp16 + fp32</h3><pre>class Layer(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br>        self.linear = nn.Sequential(<br>            *(nn.Linear(10000, 10000) for _ in range(10))<br>        )<br><br>    def forward(self, x):<br>        return self.linear(x)<br><br>def test_fp32():<br>    model = Layer().cuda()<br>    optimizer = SGD(model.parameters(), lr=0.1, momentum=0.9)<br>    data = torch.ones(10000).cuda()<br>    for i in range(10):<br>        optimizer.zero_grad()<br>        output = model(data)<br>        loss = output.sum()<br>        loss.backward()<br>        optimizer.step()<br>        memory = max_memory_allocated()<br>        print(f&#39;step memory allocate: {memory / 1e9:.3f}G&#39;)<br><br>def test_fp16():<br>    torch.cuda.init()<br>    model = Layer().cuda()<br>    optimizer = SGD(model.parameters(), lr=0.1, momentum=0.9)<br>    data = torch.ones(10000).cuda()<br>    for _ in range(10):<br>        with autocast(device_type=&#39;cuda&#39;):<br>            optimizer.zero_grad()<br>            output = model(data)<br>            loss = output.sum()<br>            loss.backward()<br>            optimizer.step()<br>        memory = max_memory_allocated()<br>        print(f&#39;memory allocated: {memory / 1e9:.3f}G&#39;)</pre><p>After running the code, we find that the memory usage is as follows:</p><p><strong>fp32: 12.035G</strong></p><p><strong>fp16: 14.035G</strong></p><p>What? Does amp use an additional 2G of memory? How is this calculated? This comes down to the implementation of amp. PyTorch’s amp doesn’t change the type of model weights, so they’re still stored in fp32,but it converts the fp32 weights to fp16 before and after the forward/backward for the whitelisted operators to calculate the fp16 activation and gradients. The fp16 gradients are further converted to fp32 to ensure the precision of parameter updates. But if both the weights and gradients remain in fp32 and the optimizer state is unchanged, why is an additional 2G used? The reason is that the fp16 weights during forward and backward operations are cached, which is implemented in the amp’s C++ code. The cached fp16 gradients are the source of the extra 2G.</p><p>To save this part of the parameters, you need to pass cache_enabled=False to autocast.</p><pre>def test_fp16():<br>    torch.cuda.init()<br>    model = Layer().cuda()<br>    optimizer = SGD(model.parameters(), lr=0.1, momentum=0.9)<br>    data = torch.ones(10000).cuda()<br>    for _ in range(10):<br>        with autocast(device_type=&#39;cuda&#39;, cache_enabled=False):<br>            optimizer.zero_grad()<br>            output = model(data)<br>            loss = output.sum()<br>            loss.backward()<br>            optimizer.step()<br>        memory = max_memory_allocated()<br>        print(f&#39;memory allocated: {memory / 1e9:.3f}G&#39;)</pre><p>As a result, the memory consumption is 12.235G, which is basically consistent with fp32 and meets expectations.</p><h3>DDP Training</h3><p>DDP just creates and updates the model in each process, so memory usage should still be around 12G, right?</p><pre>def _test_ddp_fp16():<br>    rank = dist.get_rank()<br>    model = DistributedDataParallel(Layer().cuda())<br>    optimizer = SGD(model.parameters(), lr=0.1, momentum=0.9)<br>    data = torch.ones(10000).cuda()<br>    for _ in range(10):<br>        with autocast(device_type=&#39;cuda&#39;, cache_enabled=False):<br>            optimizer.zero_grad()<br>            output = model(data)<br>            loss = output.sum()<br>            loss.backward()<br>            optimizer.step()<br>        memory = max_memory_allocated()<br>        if rank == 0:<br>            print(f&#39;memory allocated: {memory / 1e9:.3f}G&#39;)</pre><p>However, the result is:</p><p><strong>16.036G</strong></p><p>The principle is simple. DDP requires a bucket for gradient computation and gradient synchronization, and the bucket retains a copy of the gradient, so it consumes about 4G more memory.</p><h3>FSDP Training</h3><p>When using FSDP, we need to configure the auto_wrap_policy parameter to choose the model sharding strategy, otherwise the memory optimization can only reach the level of ZeRO-stage1. The configuration of auto_wrap_policy and its corresponding principle will be explained in detail in the following sections.</p><pre>from torch.distributed.fsdp.wrap import _module_wrap_policy<br><br>def _test_fsdp_fp16():<br>    rank = dist.get_rank()<br>    fsdp_model = FullyShardedDataParallel(<br>        module=Layer(), device_id=rank,<br>        auto_wrap_policy=partial(<br>            _module_wrap_policy,<br>            module_classes=nn.Linear))<br>    optimizer = SGD(fsdp_model.parameters(), lr=0.1, momentum=0.9)<br>    data = torch.ones(10000).cuda()<br>    for _ in range(10):<br>        optimizer.zero_grad()<br>        output = fsdp_model(data)<br>        loss = output.sum()<br>        loss.backward()<br>        optimizer.step()<br>        memory = max_memory_allocated()<br>        if rank == 0:<br>            print(f&#39;step memory allocate: {memory / 1e9:.3f}G&#39;)<br>        torch.cuda.reset_max_memory_allocated()</pre><p>The result is 1.524G, which is basically equivalent to the memory optimization effect of ZeRO3.</p><p>Analysing the memory usage here is to help you look at memory optimization rationally when switching from DDP to FSDP.</p><h3>FSDP Sharding Strategy</h3><p>In the previous section, we mentioned that we need to specify the model sharding strategy through the auto_wrap_policy. So how does this parameter work? And why can the optimization only reaches ZeRO-stage1 without configuring this parameter?</p><p>Similar to DistributedDataParallel, FSDP also uses a model wrapper: <a href="https://pytorch.org/docs/stable/fsdp.html#module-torch.distributed.fsdp">FullyShardedDataParallel</a> to implement the logic of parameter slicing. The Wrapped module will become the root fsdp module, and the root fsdp module will recursively wrap the submodule into a child fsdp module according to the user-defined auto_wrap_policy when building:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QQe11SjXjds8dksb" /></figure><p>Take the officially implemented _module_wrap_policy as an example, where the key parameter module_classes is used to indicate which type of submodule should be wrapped into a child fsdp module.</p><pre>def _module_wrap_policy(<br>    module: nn.Module,<br>    recurse: bool,<br>    nonwrapped_numel: int,<br>    module_classes: Set[Type[nn.Module]],<br>) -&gt; bool:<br>    &quot;&quot;&quot;<br>    This auto wrap policy wraps every module that is an instance of any type in<br>    ``module_classes`` as its own FSDP instance. The root module given by<br>    ``module`` is always wrapped as an FSDP instance regardless. Since the<br>    wrapping proceeds bottom up, each FSDP instance manages the parameters in<br>    its subtree excluding any already managed by a child FSDP instance.<br><br>    Args:<br>        module (nn.Module): Current module being considered.<br>        recurse (bool): If ``False``, then this function must decide whether<br>            ``module`` should be wrapped as an FSDP instance or not. If<br>            ``True``, then the function is still recursing down the module<br>            tree as a part of the DFS.<br>        nonwrapped_numel (int): Parameter numel not yet wrapped.<br>        module_classes (Set[Type[nn.Module]]): Set of module classes that are<br>            wrapped as FSDP instances.<br><br>    Returns:<br>        ``True`` if ``recurse=True``, and whether ``module`` should be wrapped<br>        if ``recurse=False``.<br>    &quot;&quot;&quot;<br>    if recurse:<br>        return True  # always recurse<br>    if inspect.isclass(module_classes):<br>        module_classes = (module_classes, )<br>    return isinstance(module, tuple(module_classes))</pre><p>In the previous section, we specified it as nn.Linear, which means each nn.Linear will be wrapped into a child fsdp module.</p><p>All fsdp modules will trigger parameter unsharding (all gather) and sharding during the forward process.</p><ol><li>The forward of the root fsdp module will gather the parameters of different processes in the pre-forward stage and register some pre-backward-hook and post-backward-hook. Then it releases parameters that do not belong to the current rank in the post-forward stage. The pre-backward-hook will gather the parameters again before executing backward, and the post-backward-hook is responsible for implementing gradient reduce-scatter, that is, gradient synchronization + gradient distribution.</li></ol><p>It should be noted that the fsdp-module forward will not further gather the parameters of the child fsdp module.</p><p>Compared with the child fsdp module, the forward of the root fsdp module will also do some additional work such as cuda stream initialization, which is not further discussed here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sDwAl8yG1V32fWpr" /></figure><p>2. The forward of the child fsdp module</p><p>The main logic is basically the same as the root fsdp module</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rpaw1RpaxWIjKl1t" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rrj6yHiD-JEZtkkd" /></figure><p>It can be seen that each time the fsdp module only gathers part of the parameters, which is in line with our expectations. So what if we don’t set auto_wrap_policy? That is, there are no child fsdp modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vNGt-F3BFhcIo7gD" /></figure><p>During the forward stage of the root fsdp module, it will directly gather all the parameters, which means that it is impossible to achieve the memory saving through parameter slicing in ZeRO-stage3. However, the slicing of gradients and optimizer states in ZeRO1 and ZeRO2 can still be achieved. The reason is that the post-backward-hook is still registered during the forward stage, so the logic of gradient reduce-scatter will still work. When building the Optimizer, the parameters of the root fsdp module are passed in, so the optimizer will directly update the sliced parameters and record the state of the sliced parameters, so the optimization of the sliced state of the optimizer is also effective.</p><p>auto_wrap_policy needs to follow a certain interface specification, that is, accept the following parameters:</p><ul><li><strong>module</strong>: the module accessed when recursively traversing the submodule</li><li><strong>recurse</strong>: Whether to further recursively wrap the submodule of child fsdp module submodule to child fsdp module</li><li><strong>nonwrapped_numel</strong>: The meaning of this parameter is the parameter quantity of the current module that does not need to be sliced. What are the parameters that do not need to be sliced? Generally speaking, it includes two parts, namely the already sliced parameters and the parameters that the user specifies to be ignored (ignored_params). Based on this parameter, a size-based wrap policy can be implemented, such as the officially implemented size_based_auto_wrap_policy.</li></ul><p>FSDP gives users the right to configure the auto_wrap_policy parameter, which has indeed improved its flexibility, but it has also invisibly increased the learning cost of FSDP.For example, what effect will auto_wrap_policy have, what is the meaning of its several input parameters. Users may feel puzzled when they get start with FSDP.</p><p>However, if the cost of using FSDP is limited to this, I believe everyone is still willing to learn and use it. However, some implicit conventions and some strange errors are really discouraging.</p><h3>The painful lessons learned from experimenting with FSDP</h3><h3>Risks of Replacing Submodules</h3><p>In the previous section, we mentioned that FSDP replaces submodules with child FSDP modules after wrapping. You might wonder, what will happen if the parent module accesses some attributes or methods of the submodule? Will an AttributeError be raised ?</p><pre>def __getattr__(self, name: str) -&gt; Any:<br>&quot;&quot;&quot;Forward missing attributes to the wrapped module.&quot;&quot;&quot;<br>try:<br>    return super().__getattr__(name) # defer to nn.Module&#39;s logic<br>except AttributeError:<br>    return getattr(self._fsdp_wrapped_module, name)</pre><p>This way, it looks for undefined attributes in the submodule. However, this still poses risks.</p><ol><li>If the attribute you access happens to have the same name as an attribute in the FSDP, you might access the wrong attribute.</li><li>If you directly access the submodule’s parameter and perform some operations on it. Since parameters are gathered during the forward stage, what you get directly at this point is a sharded parameter, which will probably throw an error.</li><li>If you happen not to directly call the __call__ method of the child fsdp module, for example in this situation:</li></ol><pre>class Layer(nn.Module):<br>    def __init__(self, *args, **kwargs) -&gt; None:<br>        super().__init__(*args, **kwargs)<br>        self.processor = nn.Linear(1, 1)<br>        self.linear1 = nn.Linear(1, 1)<br>        self.linear2 = nn.Linear(1, 1)<br><br>    def forward(self, x):<br>        return self.linear1(x) + self.linear2(x)<br><br>class ToyModel(nn.Module):<br>    def __init__(self, *args, **kwargs) -&gt; None:<br>        super().__init__(*args, **kwargs)<br>        self.linear = nn.Linear(1, 1)<br>        self.layer = Layer()  # 会被 auto wrap policy 指定为 child fsdp module<br><br>    def forward(self, x):<br>        y = self.linear(self.layer.processor(x))<br>        return self.layer(y)</pre><p>Suppose Layer is wrapped as an fsdp module and self.layer.processor is directly called by ToyModel.forward, an error will be raised since the Layer.forward has not been called an the parameters of processor still remain sharded.</p><p>Or in this case:</p><pre>class A:<br>    ...<br>    def loss(self, inputs: torch.Tensor, data_samples: List[DataSample]) -&gt; dict:<br>        feats = self.extract_feat(inputs)<br>        return self.head.loss(feats, data_samples)<br>    <br>class B:<br>    ...<br>    def loss(self, feats: Tuple[torch.Tensor], data_samples: List[DataSample],  **kwargs) -&gt; dict:<br>        cls_score = self(feats)  # 没有走 FSDP 的 forward<br>        losses = self._get_loss(cls_score, data_samples, **kwargs)<br>        return losses</pre><p>class B is a submodule head of class A, and A will call self.head.loss. If class B is wrapper as a child fsdp module, the sharded tensor will no be gathered when calling self.head.loss, then a corresponding error will be raised.</p><h3>Optimizer with Multiple Parameter Groups</h3><p>PyTorch’s optimizer supports setting different learning rates, momentum, and other hyperparameters for different parameters in the model. The setup process looks something like this:</p><pre>param_groups = []<br>for module in model.modules():<br>    if isinstance(module, nn.BatchNorm2d):<br>        param_groups.append({&#39;param&#39;: module.weight, lr=0.01})<br>        param_groups.append({&#39;param&#39;: module.bias, lr=0.1})<br>    elif:<br>    <br>optimizer = SGD(param_groups, lr=0.1)</pre><p>However, the problem is, prior to PyTorch 2.0, once the root fsdp module and child fsdp module are built, it deletes the original parameters, such as bn.weights, bn.bias, and converts all the unsliced parameters under the fsdp module into a large flatten parameter.</p><p>For example, in the previous chapter’s example, if no auto_wrap_policy is specified, only the outermost root fsdp module will be retained. Then, all the parameters of the linear layers will be reconstructed into a large flatten parameter, placed under the root_fsdp_module:</p><pre>        rank = dist.get_rank()<br>        fsdp_model = FullyShardedDataParallel(<br>            module=Layer(), device_id=rank,<br>            # auto_wrap_policy=partial(<br>            #     _module_wrap_policy,<br>            #     module_classes=nn.Linear),<br>        )<br>        print(list(fsdp_model.parameters()))</pre><p>At this point, each rank will only print out one parameter:</p><pre>[Parameter containing:<br>Parameter(FlatParameter([-4.6519e-05, -6.2861e-03,  3.9519e-03,  ..., -3.2763e-03,<br>                7.1111e-04, -8.2136e-03], device=&#39;cuda:3&#39;, requires_grad=True))]</pre><p>Therefore, before PyTorch 2.0, once FSDP was used, it was difficult to set different learning rates for each parameter because multiple parameters would be merged into one after fsdp wrap. The subsequent gradient shard and parameter updates are also based on the flatten tensor.</p><p>Since parameter updates are also based on the flatten tensor, FSDP requires consistent dtype and requires_grad attributes of each parameter under the same fsdp module, otherwise,Parameters cannot compose a large flatten tensor.</p><p>PyTorch 2.0 added a use_orig_params parameter to FSDP. When this parameter is turned on, FSDP will not delete the original parameters during the wrap process. The memory of the original parameters point to some area of the flatten params.</p><p>This is a great update. Without introducing additional GPU memory consumption, users can still access the original parameters and set different optimizer hyperparameters for them. With the introduction of this parameter, in theory, the restriction on the uniformity of the requires_grad attribute of all parameters under the same FSDP module should also be lifted. Unfortunately, PyTorch 2.0 did not adjust this part of the logic, but this issue has been fixed on the main branch, and it is believed that the upcoming PyTorch 2.1 will be able to solve this pain point.</p><h3>Stability of FSDP Interface</h3><p>Although as early as PyTorch 1.11, FSDP was already a beta feature, to this day, the FSDP module is still in a state of rapid iteration. In February 2023, the developers of FSDP initiated a discussion, introducing some design concepts and internal restructuring.</p><p>In addition, the external interface of FSDP is updated relatively quickly. When you open the API documentation of PyTorch FSDP, you will find that many interfaces are marked as deprecated. However, overall, the new interface is indeed much easier to use and more flexible than the old one. The integration of FSDP by<a href="https://github.com/open-mmlab/mmengine"> MMEngine</a> is also based on the new interface.</p><h3>Conclusion</h3><ol><li>FSDP, in terms of memory savings, is indeed equivalent to ZeRO3, but it should be noted that when mixed-precision training (autocast) is enabled, cache_enabled needs to be set to False.</li><li>FSDP has a higher learning curve in terms of ease of use. Users need to understand the logic of FSDP wrapping modules, the role of auto_wrap_policy, and some limitations. Unexpected errors are prone to happen if users do not have an overall understanding about FSDP . The error messages and the actual cause of the error may not be highly related, making it difficult to debug.</li><li>PyTorch 2.0 has greatly improved the usability of FSDP through the use_ori_params parameter, but the restriction on the uniformity of the requires_grad attribute still exists. To solve this problem, you can wait for the PyTorch 2.1 update and specify use_orig_params=True. But if you want to solve this temporarily, you need to make some changes to auto_wrap_policy . Since this is based on the internal agreement of FSDP, it may not be very stable, so I won&#39;t go into details here.</li></ol><p>In general, FSDP leaves something to be desired in terms of ease of use, but in terms of flexibility, it gives users more room for operation. However, with the continuous iteration of PyTorch, FSDP is expected to become as easy to use as DDP. MMEngine will also closely follow the updates of FSDP, aiming to lower the entry threshold while maintaining flexibility and summarizing a set of simple, easy-to-configure best practices.</p><p>If you’re interested, feel free to encourage more updates. If there’s an opportunity, we can further discuss the design philosophy of FSDP, the construction logic of flatten params, the rules for parameter slicing, and the parallel methods for gradient computation and synchronization in FSDP. Let’s exchange ideas on how to tackle the errors thrown by FSDP (hopefully, with fewer rounds of debugging after PyTorch updates).</p><p>What? You also want to get a comprehensive analysis of DeepSpeed, ColossalAI, and FSDP? MMEngine also supports DeepSpeed from version v0.8.0, and we will bring an introduction to DeepSpeed next time. Please pay more attention to MMEngine and give it a star. We believe that in the near future, you will be able to switch freely between FSDP, DeepSpeed, and ColossalAI with just a few lines of code and experience the pros and cons of various training frameworks yourself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe8d2848832f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-tuning Llama2 takes less than 200 lines of code!]]></title>
            <link>https://openmmlab.medium.com/fine-tuning-llama2-takes-less-than-200-lines-of-code-b93dd91f9541?source=rss-7b857bec476d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b93dd91f9541</guid>
            <dc:creator><![CDATA[OpenMMLab]]></dc:creator>
            <pubDate>Thu, 27 Jul 2023 02:51:02 GMT</pubDate>
            <atom:updated>2023-07-27T02:51:02.551Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*eqGFoVljTbxc2nKYZ3CdHg.png" /></figure><p>Last week, Meta AI released their next generation large language model: <a href="https://ai.meta.com/llama/">Llama 2</a>. They open-sourced the model, training, and inference scripts, with the model even available in a Hugging Face version. They’ve really done an excellent job of thinking about regular users while open-sourcing conscientiously, which is incredibly cool. As soon as I heard the news, I rushed into the official repository, <a href="https://github.com/facebookresearch/llama-recipes/">llama2-recipes</a>, planning to experience the training process of Llama 2.</p><p>During my first experience, it was clear that the code release was somewhat rushed, and I ran into a few minor issues. The model stopped converging after only a few iterations. Upon carefully reviewing the code, I found a small mistake. They updated the epoch-based scheduler as if it were step-based, which led to the learning rate decreasing too rapidly. After only a few iterations, the learning rate was almost zero. So, I quickly reported this issue to the official team: <a href="https://github.com/facebookresearch/llama-recipes/issues/27">https://github.com/facebookresearch/llama-recipes/issues/27</a></p><p>The official response was incredibly fast and they fixed the issue the very next day: <a href="https://github.com/facebookresearch/llama-recipes/pull/28">https://github.com/facebookresearch/llama-recipes/pull/28</a></p><p>Anyone who has encountered similar issues can update their code to ensure the problem is resolved.</p><p>After solving this minor issue, Llama2 was able to train normally. Great works for Meta AI! star++</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/0*hjHkBlXBUZaBViBq" /></figure><p>After this minor incident, I got a good handle on the Llama2 training process. As stated in the paper, it is trained using FSDP. Wait, FSDP, isn’t <a href="https://github.com/open-mmlab/mmengine">MMEngine v0.8.0</a> also supporting FSDP training? So, I implemented the Llama2 training process based on the new features of MMEngine. See the complete training example at: <a href="https://github.com/open-mmlab/mmengine/tree/main/examples/llama2">https://github.com/open-mmlab/mmengine/tree/main/examples/llama2</a></p><h3>Implementing the Dataset</h3><p>We directly referred to the implementation of the <a href="https://github.com/facebookresearch/llama-recipes/blob/1e0f8a1fb77b9ddccf649970f632dd606a22bd06/ft_datasets/alpaca_dataset.py#L28">alpaca dataset</a> in llama-recipe.</p><h3>Building the FSDPStrategy</h3><p>The constructor of FSDPStrategy initializes distributed environment, random seeds, and other environmental variables, so it needs to be done first. Strategy is a feature introduced in MMEngine v0.8.0, aimed at solving some issues with large model training. For a detailed explanation of Strategy, you can look forward to subsequent articles~</p><pre>strategy = FSDPStrategy(<br>    model_wrapper=dict(<br>        auto_wrap_policy=partial(<br>            transformer_auto_wrap_policy,<br>            transformer_layer_cls={LlamaDecoderLayer})),<br>    state_dict_cfg=&#39;full&#39;,<br>    env_kwargs=dict(randomness=dict(seed=42)))</pre><h3>Building the dataloader and model</h3><p>The configuration is completely copied from the official repo. It’s worth noting that the official repo by default enables bf16 training with full parameters, without the need for mixed precision training.</p><pre># Prepare model<br>tokenizer = LlamaTokenizer.from_pretrained(args.checkpoint)<br>tokenizer.add_special_tokens({&#39;pad_token&#39;: &#39;&lt;PAD&gt;&#39;})<br>model = LlamaForCausalLM.from_pretrained(args.checkpoint)<br>model.to(torch.bfloat16)<br>model.train()<br><br># Prepare dataset<br>train_dataset = AlpacaDataset(<br>    tokenizer=tokenizer, data_path=args.data_root)<br>train_dataloader = DataLoader(<br>    train_dataset,<br>    batch_size=args.batch_size,<br>    sampler=DefaultSampler(train_dataset, seed=0),<br>    collate_fn=default_data_collator,<br>    drop_last=True)</pre><h3>Preparing optimizer and scheduler</h3><p>The configuration aligns with the official repo, using AdamW and StepLR. The model, scheduler, and optimizer are then passed to the strategy to handle the FSDP related logic.</p><pre>optim_cfg = dict(<br>    optimizer=dict(type=AdamW, lr=1e-4, weight_decay=0.0),<br>    accumulative_counts=ORI_BATCH_SIZE / args.batch_size)<br>scheduler_cfgs = [dict(type=StepLR, step_size=1, gamma=0.85)]<br>model, optimizer, schedulers = strategy.prepare(<br>    model,<br>    optim_wrapper=optim_cfg,<br>    param_scheduler=scheduler_cfgs,<br>    dispatch_kwargs=dict(max_iters=max_iters, max_epochs=args.max_epoch))</pre><h3>Customizing the train-loop</h3><p>By using the strategy, we can break away from Runner and freely implement the training logic. Doesn’t it feel similar to native PyTorch?</p><pre>for epoch in range(args.max_epoch):<br>    for idx, inputs in enumerate(train_dataloader):<br>        # Convert inputs to target device.<br>        inputs = apply_to(inputs, lambda m: isinstance(m, torch.Tensor),<br>                          lambda m: m.cuda())<br><br>        loss = model(**inputs).loss<br>        optimizer.update_params(loss)<br><br>        max_memory = torch.cuda.max_memory_allocated()<br>        strategy.logger.info(f&#39;Epoch: {epoch+1}/{args.max_epoch}, &#39;<br>                             f&#39;Iter: {idx+1}/{epoch_length}, &#39;<br>                             f&#39;Loss: {loss.item():.3f}, &#39;<br>                             f&#39;Lr: {optimizer.get_lr()[&quot;lr&quot;][0]:.6f} &#39;<br>                             f&#39;Memory: {max_memory/1e9:.3f}G&#39;)<br>        visualizer.add_scalars({&#39;loss&#39;: loss.item()})<br><br>        torch.cuda.reset_peak_memory_stats()<br><br>    for scheduler in schedulers:<br>        scheduler.step()<br><br>    save_dir = f&#39;{args.output_dir}/epoch_{epoch+1}&#39;<br>    state_dict = model.state_dict()<br><br>    if is_main_process():<br>        model.save_pretrained(save_dir, state_dict=state_dict)<br>        tokenizer.save_pretrained(save_dir)</pre><p>However, leaving the Runner also has some drawbacks. We have to manually update the learning rate, print logs, record logs, and save weights.</p><h3>In conclusion</h3><p>Users who are interested can come to <a href="https://github.com/open-mmlab/mmengine">MMEngine</a> and try out the training examples. We welcome plenty of feedback. If you are interested in DeepSpeed and ColossalAI, we will also provide examples of fine-tuning with DeepSpeed and ColossalAI as soon as possible.</p><p><a href="https://github.com/open-mmlab/mmengine">MMEngine</a>：<a href="https://github.com/open-mmlab/mmengine">https://github.com/open-mmlab/mmengine</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/0*Iau1uSVkRbb38jIs" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b93dd91f9541" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Join OpenMMLab Codecamp: Harness Your Coding Skills and Shape the Future of Open Source!]]></title>
            <link>https://openmmlab.medium.com/join-openmmlab-codecamp-harness-your-coding-skills-and-shape-the-future-of-open-source-4741d9aa1f6c?source=rss-7b857bec476d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4741d9aa1f6c</guid>
            <dc:creator><![CDATA[OpenMMLab]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 08:47:44 GMT</pubDate>
            <atom:updated>2023-07-24T08:47:44.897Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*D3n_Y9cPuVtnDOXGVeQ6nw.jpeg" /></figure><p>Want to improve programming skills?</p><p>Want to contribute to open source projects with global developers? Eager to understand the latest technology trends but lacking hands-on projects? Has it been ten years since AlexNet was released, yet you are still only practicing with local development? In today’s wave of open source, are you only utilizing git clone to use GitHub’s open source libraries? Here comes your chance,<strong> the </strong><a href="https://openmmlab.com/activity/codecamp"><strong>OpenMMLab Code Camp </strong></a><strong>will officially kick off on July 20th!</strong></p><p>We offers<strong> 10 directions</strong>, <strong>150+ tasks</strong> of varying difficulties.</p><p>Including but not limited to foundational library (MMEngine), object detection (MMDetection), 3D object detection (MMDetection3D), pre-training + multimodal (MMPreTrain), AIGC (MMagic), deployment (MMDeploy), pose estimation (MMPose), semantic segmentation (MMSegmentation), action recognition (MMAction2) among various other fields.</p><p>Moreover, we released cooperation task with Seeed Studio and Extreme Mart platform which provide extra gift (Jetson Nano is waiting for you). Meanwhile, you also have the opportunity to design and create your own innovative applications under DIY tasks.</p><p>Getting started by contributing to open-source frameworks and experiencing the charm of openness.</p><p><strong>We sincerely invite all AI learners, researchers, and practitioners to participate in this event.</strong></p><p><strong>You will gain：</strong></p><ul><li>Deeply participate in the construction of well-known open-source projects.</li><li>10+ fields with 150+ tasks of varying difficulties, providing a richer project development experience.</li><li>One-on-one guidance from repo maintainers, developers, helping you tackle challenges and accumulate project experience.</li><li>Charming electronic prizes, OpenMMLab certificates, limited-edition merchandise, and fast-track interviews.</li><li>Participate in projects remotely, with freedom to schedule your time.</li></ul><p>Click the link, pick tasks and join us!</p><p><a href="https://openmmlab.com/activity/codecamp">https://openmmlab.com/activity/codecamp</a></p><p>Questions？</p><p>Join Discord for Discussion：<a href="https://discord.gg/KuWMWVbCcD">https://discord.gg/KuWMWVbCcD</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*mcmOeVdqx8MQYvqgxsUvPw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4741d9aa1f6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>