<?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 Guangyao Quan on Medium]]></title>
        <description><![CDATA[Stories by Guangyao Quan on Medium]]></description>
        <link>https://medium.com/@guangyaoquan?source=rss-ab9073604f0b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xMcSWkE_vj7oQqWdV8_Udw.jpeg</url>
            <title>Stories by Guangyao Quan on Medium</title>
            <link>https://medium.com/@guangyaoquan?source=rss-ab9073604f0b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:56:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@guangyaoquan/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[LLaMA by Meta: A Foundation Model]]></title>
            <link>https://medium.com/@guangyaoquan/llama-by-meta-a-small-giant-d75a20e5546a?source=rss-ab9073604f0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d75a20e5546a</guid>
            <category><![CDATA[a-review-of-llama]]></category>
            <category><![CDATA[paper-reading]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[seminar-report]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Guangyao Quan]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 14:32:17 GMT</pubDate>
            <atom:updated>2024-03-08T20:34:08.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="https://stock.adobe.com/images/white-llama-wearing-blue-glasses-generative-ai/565740155?start-checkout=1&amp;content-id=565740155"><img alt="" src="https://cdn-images-1.medium.com/max/540/1*aS1-_ec4LfXlvdMjSdxg8A.jpeg" /></a><figcaption>Llama wearing sunglasses ©AdobeStock</figcaption></figure><p>Recent research in the field of large language models (LLMs) has increasingly focused on the <a href="https://doi.org/10.48550/arXiv.2001.08361">correlation between model scaling and performance enhancement</a>, particularly in the context of <a href="https://doi.org/10.48550/arXiv.2005.14165">few-shot learning</a> capabilities. Notably, a subset of this research posits a <a href="https://doi.org/10.48550/arXiv.2203.15556">counterintuitive finding</a>: optimal performance within a constrained computational budget may not be achieved by simply maximizing model size. Rather, more modestly-sized models, when trained on expansive datasets, can yield superior results. This revelation prompts an inquiry into the existence of versatile LLMs adaptable to varying computational constraints.</p><p>Addressing this query, the introduction of the <a href="https://llama.meta.com/">LLaMA</a> (Language Model by Meta AI) framework marks a significant development. LLaMA comprises a suite of foundation language models with a parameter range spanning from 7B to 65B. A distinctive feature of these models is their training regimen: they are exclusively trained on publicly available datasets, encompassing trillions of tokens. This approach is in stark contrast to models reliant on proprietary or inaccessible data sources, positioning LLaMA as a notable contribution to the landscape of scalable, accessible language modeling.</p><p>In the ensuing sections of this review article, we will delve into key highlights from the <a href="https://doi.org/10.48550/arXiv.2302.13971">original publication by Meta AI</a>. This exploration will encompass a detailed examination of the seminal contributions, methodological innovations, and empirical findings presented in their work.</p><p>Key areas of focus will include:</p><ol><li><strong>Architectural Innovations</strong></li><li><strong>Training Methodology</strong></li><li><strong>Performance Evaluation</strong></li><li><strong>Ethical Considerations</strong></li></ol><p>Following a thorough review of the article, we will broaden our analysis to include a comprehensive discourse on the applications and implications of this research.</p><h3>Architecture</h3><p>The network is based on the well-known <a href="https://doi.org/10.48550/arXiv.1706.03762">transformer architecture</a>. But several improvements inspired by other works have been leveraged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*dvT4PwYcFStHjDXqB81M9w.png" /><figcaption>A classical overview of the Transformer architecture (<a href="https://doi.org/10.48550/arXiv.2106.04554">https://doi.org/10.48550/arXiv.2106.04554</a>)</figcaption></figure><p>Inspired by <a href="https://doi.org/10.48550/arXiv.2005.14165">GPT-3</a>, <strong>pre-normalization</strong> in transformer sub-layers uses <a href="https://doi.org/10.48550/arXiv.1910.07467">RMSNorm</a> (Root Mean Square Layer Normalization) instead of the traditional output normalization to enhance training stability. RMSNorm, an extension of Layer Normalization (<a href="https://doi.org/10.48550/arXiv.1607.06450">LayerNorm</a>), is adopted due to its lower computational overhead compared to LayerNorm, which can be slow and costly. RMSNorm, which omits the mean statistic calculation integral to LayerNorm, delivers comparable performance while reducing runtime by 7% to 64%.</p><p><a href="https://doi.org/10.48550/arXiv.2104.09864"><strong>Rotary Embeddings</strong></a><strong> </strong>inspired by <a href="https://doi.org/10.5281/zenodo.5297715">GPTNeo</a><strong> </strong>remove the absolute positional embeddings and add rotary positional embeddings (RoPE) at each layer of the network. RoPE, is a type of position embedding which encodes absolute positional information with rotation matrix and naturally incorporates explicit relative position dependency in self-attention formulation.</p><p>The <a href="https://akgeni.medium.com/llama-concepts-explained-summary-a87f0bd61964">advantages of RoPE</a> are:</p><ul><li>Can be expanded to any sequence lengths</li><li>Decaying inter-token dependency with increasing relative distances.</li><li>Capability of equipping the linear self-attention with relative position encoding.</li><li>The key idea is to encode relative position by multiplying the context representations with a rotation matrix. RoPE decays with the relative distance increased, which is desired for natural language encoding.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*meJpOzJwtovclREzHyqMRA.png" /><figcaption>Implementation of RoPE (<a href="https://doi.org/10.48550/arXiv.2104.09864">https://doi.org/10.48550/arXiv.2104.09864</a>)</figcaption></figure><p><a href="https://doi.org/10.48550/arXiv.2002.05202"><strong>SwiGLU</strong></a> activation function inspired by <a href="https://doi.org/10.48550/arXiv.2204.02311">PaLM</a> replaces the <a href="https://doi.org/10.48550/arXiv.1803.08375">ReLU</a> to improve the performance. The main advantages of SwiGLU over other activation functions are:</p><ul><li>Smoothness: SwiGLU is smoother than ReLU, which can lead to better optimization and faster convergence.</li><li>Non-monotonicity: SwiGLU is non-monotonic, which allows it to capture complex non-linear relationships between inputs and outputs.</li><li>Gating: SwiGLU uses a gating mechanism, which allows it to selectively activate neurons based on the input it receives. This can help to reduce overfitting and improve generalization.</li><li>Performance: SwiGLU has been shown to outperform other activation functions, including Swish and GLU, in a variety of tasks.</li></ul><pre>def sigmoid(x):<br>  return  1/(1 + np.exp(-x))<br><br>def swish(x):<br>  return x*sigmoid(x)<br><br># SwiGLU is a combination of Swish and GLU activation functions.<br># In SwiGLU, the Swish function is used to gate the linear function of GLU. <br># This allows SwiGLU to capture the advantages of both Swish and GLU, while overcoming their respective disadvantages.<br># SwiGLU has been shown to outperform both Swish and GLU in a variety of tasks, including image classification, language modeling, and machine translation.<br><br># Python Implementation of SwiGLU (https://github.com/Rishit-dagli/GLU/blob/main/glu_tf/glu.py)<br>class SwiGLU(tf.keras.layers.Layer):<br>    def __init__(self, bias=True, dim=-1, **kwargs):<br>        super(SwiGLU, self).__init__(**kwargs)<br>        self.bias = bias<br>        self.dim = dim<br>        self.dense = tf.keras.layers.Dense(2, use_bias=bias)<br><br>    def call(self, x):<br>        out, gate = tf.split(x, num_split=2, axis=self.dim)<br>        gate = tf.keras.activations.swish(gate)<br>        x = tf.multiply(out, gate)<br>        return x</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*044NRVoDONyXvodC3O_T9w.png" /><figcaption>SwiGLU</figcaption></figure><h3>Training</h3><p>Let’s begin by examining the dataset utilized in the training process. This dataset is characterized by its diversity, spanning several domains, and is publicly available, making it suitable for open-source projects. It comprises approximately 1.4 trillion tokens sourced from seven primary collections as illustrated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OJXDCt2XNqy6AWwyXXckiA.png" /><figcaption>Pre-training data (<a href="https://doi.org/10.48550/arXiv.2302.13971">https://doi.org/10.48550/arXiv.2302.13971</a>)</figcaption></figure><p>The dataset was processed using the <a href="https://doi.org/10.48550/arXiv.1508.07909">byte-pair encoding (BPE)</a> algorithm, as implemented by <a href="https://github.com/google/sentencepiece">SentencePiece</a>. This approach involves tokenizing the data by splitting all numbers into individual digits and reverting to bytes to handle unknown UTF-8 characters effectively. It is important to note that each token in the dataset was used only once during the training phase, with the exception of content from <em>Wikipedia</em> and <em>Books</em>. These two domains underwent approximately two epochs of training, highlighting their significance in the dataset’s composition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R7GbMYPU44kxd8OYxVwjAQ.png" /><figcaption>Model sizes, architectures, and optimization hyper-parameters (<a href="https://doi.org/10.48550/arXiv.2302.13971">https://doi.org/10.48550/arXiv.2302.13971</a>)</figcaption></figure><p>Moving on to the specifics of the training process, the chosen optimizer was <a href="https://doi.org/10.48550/arXiv.1711.05101">AdamW</a>, accompanied by a set of hyper-parameters tailored to optimize performance. These parameters include Beta_1 set at 0.9 and Beta_2 at 0.95, indicating the momentum terms for the optimizer. A cosine learning rate schedule was implemented, where the final learning rate is adjusted to 10% of the maximum learning rate, facilitating a gradual reduction in learning rate over time. Additionally, a weight decay of 0.1 was applied to regularize and prevent overfitting, while <a href="https://doi.org/10.48550/arXiv.1211.5063">gradient clipping</a> was capped at 1.0 to maintain the stability of the training. The training began with a warm-up period of 2000 steps to gradually increase the learning rate from zero, preventing abrupt adjustments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*qayJLDgHj_VB8Urw6gPg8w.png" /><figcaption>Gradient clipping (<a href="https://doi.org/10.48550/arXiv.1211.5063">https://doi.org/10.48550/arXiv.1211.5063</a>)</figcaption></figure><p>To enhance the efficiency of the training process, several key improvements were incorporated:<br>1. The implementation of <a href="https://doi.org/10.48550/arXiv.2205.14135">causal multi-head attention</a> from the <a href="https://github.com/facebookresearch/xformers">xformers</a> library played a critical role in reducing memory usage and runtime. This was achieved by avoiding the computation of attention weights and key-query scores that are unnecessary due to the causal nature of the language modeling task.<br>2. Activation checkpointing significantly reduced the computational overhead during the backward pass. By saving only the activations that are costly to compute, such as the outputs of linear layers, a balance was struck between speed and memory usage. This optimization was made possible through manual implementation of the backward function for transformer layers, deviating from the standard PyTorch <a href="https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html">autograd</a>.<br>3. <a href="https://doi.org/10.48550/arXiv.2205.05198">Model and sequence parallelism</a> techniques were employed to minimize the memory footprint of the model, allowing for more complex models to be trained on available hardware.<br>4. The process also optimized the overlap between computation and communication tasks, particularly the activations computation and the data exchange between GPUs over the network due to <a href="https://pytorch.org/docs/stable/distributed.html">all_reduce</a> operations. This overlapping ensured more efficient use of resources and reduced training time.</p><h3>Evaluation</h3><p>In the evaluation phase after the pre-training, the model was tested across a variety of zero-shot and few-shot tasks, spanning free-form generation and multiple-choice formats, on a total of 20 benchmarks.</p><p>In the zero-shot setting, the model is presented with a textual task description and a test example, from which it is expected to generate an open-ended answer or rank proposed answers without any prior examples. Conversely, the few-shot approach involves providing the model with a handful of examples (ranging from 1 to 64) for a given task, along with a test example. The model then uses this context to generate answers or rank different options, leveraging the provided examples to better understand and respond to the task at hand.</p><pre>#Examples (https://machinelearningmastery.com/what-are-zero-shot-prompting-and-few-shot-prompting/)<br><br># Zero-Shot Prompting<br>Classify the text into positive, neutral or negative:<br>Text: That shot selection was awesome.<br>Classification:<br><br># Few-Shot Prompting<br>Text: Today the weather is fantastic<br>Classification: Pos<br>Text: The furniture is small.<br>Classification: Neu<br>Text: I don&#39;t like your attitude<br>Classification: Neg<br>Text: That shot selection was awful<br>Classification:</pre><p>A key feature of the multiple-choice tasks is the method used to select the most suitable completion from a set of given options. This is based on the context provided, <a href="https://zenodo.org/records/10600400">where the completion with the highest likelihood, normalized by the number of characters in the completion</a>, is chosen. However, for certain benchmarks like OpenBookQA and BoolQ, the selection is made based on the <a href="https://doi.org/10.48550/arXiv.2005.14165">likelihood ratio of the completion given the context versus the completion given a generic “Answer:” prompt</a>. This nuanced approach ensures that the chosen answer is not only contextually relevant but also efficiently sized.</p><p>While a comprehensive breakdown of the results on each benchmark is beyond the scope of this summary, it is important to highlight the overall trends observed during training. The model’s performance on most benchmarks showed a steady improvement, closely aligning with the decrease in training perplexity. This indicates that, as the model became more proficient at predicting the next token in the training dataset (i.e., lower perplexity), its ability to accurately perform on the evaluation tasks also enhanced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*clELJsXybfCVNwWAtxhkPQ.png" /><figcaption>Training loss over train tokens for the 7B, 13B, 33B, and 65 models (<a href="https://doi.org/10.48550/arXiv.2302.13971">https://doi.org/10.48550/arXiv.2302.13971</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aDtuaoPsR2TAd0V6kTL0Yg.png" /><figcaption>Zero-shot performance on Common Sense Reasoning tasks (<a href="https://doi.org/10.48550/arXiv.2302.13971">https://doi.org/10.48550/arXiv.2302.13971</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*277fdk0Qbdm3LCo-n0XnFg.png" /><figcaption>NaturalQuestions (<a href="https://doi.org/10.48550/arXiv.2302.13971">https://doi.org/10.48550/arXiv.2302.13971</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fd1ek33_x8XKtvXd1CyVGQ.png" /><figcaption>TriviaQA (<a href="https://doi.org/10.48550/arXiv.2302.13971">https://doi.org/10.48550/arXiv.2302.13971</a>)</figcaption></figure><p>However, exceptions were noted in the performance trends on the <em>SIQA</em> and <em>WinoGrande</em> benchmarks. Specifically, the <em>SIQA</em> benchmark exhibited significant variance in performance, suggesting that it may not be a reliable measure of the model’s capabilities. On the <em>WinoGrande</em> benchmark, there was a lack of correlation between training perplexity and performance, with models of different sizes (LLaMA-33B and 65B) showing similar performance levels during training. This could indicate that factors other than perplexity, such as the model’s understanding of complex reasoning or specific task nuances, play a critical role in performance on certain benchmarks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D0cspX-_4LX47gDaf36qMQ.png" /><figcaption>Evolution of performance on question answering and common sense reasoning during training (<a href="https://doi.org/10.48550/arXiv.2302.13971">https://doi.org/10.48550/arXiv.2302.13971</a>)</figcaption></figure><p>The experimentation with <strong>instruction fine-tuning</strong> has highlighted its potential to significantly enhance model performance, particularly in the context of the <em>Massive Multitask Language Understanding (MMLU)</em> tasks. Despite the non-fine-tuned LLaMA-65B model’s proficiency in following basic instructions, fine-tuning on a minimal set of instruction data led to notable improvements.</p><p>Fine-tuning in the context of large language models (LLMs) diverges from traditional approaches, which typically only necessitate input and output pairs. For LLMs, the process is augmented by the inclusion of explicit instructions. This additional layer guides the model more precisely, enabling it to understand and execute tasks with greater accuracy.</p><pre>{<br> &quot;instruction&quot;: &quot;Generate advertising slogans for a given product&quot;,<br> &quot;input&quot;: &quot;Amazon Prime&quot;,<br> &quot;output&quot;: &quot;Amazon Prime - Beyond Fast. Prime Vast. Delight at Every Click.&quot;<br>}</pre><p>A key insight from these experiments is that instruction fine-tuning does not require extensive datasets. Around 1,000 data points are often sufficient to yield significant improvements. This efficiency can be attributed to two main factors:</p><p>1. <strong>High Data Quality</strong>: The effectiveness of fine-tuning is heavily dependent on the quality of the instruction data. High-quality data ensures that the model learns valuable patterns and instructions, which translates to better performance on specific tasks. It’s crucial that the instruction data is carefully curated to maximize its instructional value.</p><p>2. <strong>Strong Baseline Model</strong>: The existing capabilities of the baseline model, such as the LLaMA-65B, play a crucial role in the success of instruction fine-tuning. A model with a solid foundation in language understanding and generation can leverage small amounts of high-quality instruction data to significantly improve its ability to follow complex instructions and perform specialized tasks.</p><p>However, it’s important to approach instruction fine-tuning with caution, as overloading the model with excessive instruction data could inadvertently bias it, potentially compromising its generalizability or performance on other tasks. This delicate balance emphasizes the importance of strategic data selection and the inherent strengths of the underlying model in achieving optimal fine-tuning outcomes.</p><h3>Ethics</h3><p>LLMs have the capacity to reflect and even magnify biases present in their training data, potentially leading to the generation of harmful or offensive content. Given that a substantial portion of the LLaMA model’s training corpus originates from internet sources, there exists a tangible risk that LLaMA could produce such content. This concern has been substantiated through evaluations using the LLaMA-65B model across various benchmarks.</p><p>Key observations from these benchmarks include:<br>- A correlation between model size and the propensity to generate toxic responses has been noted, particularly in response to respectful prompts within the <em>RealToxicityPrompts</em> benchmark. The “respectful” versions are prompts starting with “Complete the following sentence in a polite, respectful, and unbiased manner:”, and “Basic” is without it. This suggests that as LLMs increase in size, their potential for generating inappropriate content may also rise.<br>- When tested against the <em>CrowS-Pairs</em> benchmark, LLaMA exhibited a noticeable bias in the category of religion. This bias is thought to originate from the <em>CommonCrawl</em> data, despite rigorous efforts to filter out biased content during the training data preparation phase.<br>- On the <em>WinoGender</em> benchmark, which tests a model’s ability to perform co-reference resolution using pronouns like “their,” “them,” and “someone,” LLaMA demonstrated superior performance. This indicates a strength in understanding and using gender-neutral pronouns correctly.<br>- However, the <em>TruthfulQA</em> benchmark revealed a tendency for LLaMA to “hallucinate” or generate incorrect answers, highlighting an area where the model’s reliability in generating factually accurate content could be improved.</p><p>These findings underscore the importance of ongoing efforts to mitigate biases and ensure the ethical use of LLMs. The goal is to balance the benefits of broad knowledge representation with the imperative to prevent the propagation of harmful biases.</p><h3>Conclusions</h3><p>The LLaMA model represents a significant advancement within NLP and LLMs, achieving SOTA performance by training exclusively on publicly available data, without resorting to proprietary datasets. Looking forward, the development team is committed to enhancing the model’s robustness and addressing key challenges such as toxicity and bias. Additionally, there is an interest in exploring fine-tuning techniques based on instructional data to further improve the model’s capabilities. Plans are also underway to develop and release larger versions of the model trained on even more comprehensive pretraining corpora. The <a href="https://llama.meta.com/llama2">LLaMA 2</a> is now also licensed for both research and commercial use as the most current research outcome after LLaMA by Meta.</p><p>Its development and application span various aspects, each with distinct impacts and potential uses.</p><ol><li><strong>Educational and Research Applications</strong><br>In educational contexts, LLaMA can serve as an advanced tool for personalized learning, offering detailed explanations and tutorials on a wide range of subjects. Its ability to understand and generate natural language allows it to interact with students in a more engaging and accessible manner. For researchers, LLaMA&#39;s capabilities in processing and summarizing large datasets can aid in literature review, hypothesis generation and data analysis.</li><li><strong>Technology and Development</strong><br>LLaMA&#39;s sophisticated understanding of code and natural language makes it an invaluable resource for developers, particularly in code generation, debugging, and documentation. Its proficiency in languages like those present in the GitHub dataset enables it to suggest code optimizations and alternatives, reducing development time and improving software quality.</li><li><strong>Ethical Considerations and Bias Mitigation</strong><br>The ethical implications of LLaMA&#39;s deployment are profound. While it has the potential to democratize access to information and automate complex tasks, there is a critical need for vigilance against the biases inherent in its training data. The model&#39;s tendency to amplify existing biases, especially those related to toxicity and fairness, necessitates ongoing efforts to refine its outputs and ensure they are respectful and unbiased. This includes specialized fine-tuning and the development of mechanisms to detect and mitigate harmful content generation.</li><li><strong>Business and Customer Service </strong><br>LLaMA can revolutionize customer service and business processes by powering chatbots and virtual assistants capable of understanding and responding to complex queries in real-time. Its ability to generate human-like text and understand instructions makes it an excellent tool for automating responses, personalized marketing, and content creation, thereby enhancing customer engagement and operational efficiency.</li><li><strong>Future Directions and Improvements</strong><br>The continuous refinement of LLaMA, through fine-tuning on instructional data and the implementation of efficient training methodologies, shows promise for further improvements in performance and applicability. These advancements could lead to more context-aware models capable of tackling a broader range of tasks.</li></ol><p>In conclusion, LLaMA embodies the cutting-edge of AI research, offering vast potential across numerous fields. However, its application must be guided by ethical considerations, aiming to leverage its capabilities for societal benefit while diligently addressing the challenges posed by bias and fairness.</p><p>Note:</p><ol><li>All sources are to be referenced as hyperlinks or marked with links in this article.</li><li>This article is a seminar report in blogpost-style for Master-Seminar — Advanced Techniques in Natural Language Processing (IN2107, IN4443) at Technical University of Munich.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d75a20e5546a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>