<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: sangjun_park</title>
    <description>The latest articles on DEV Community by sangjun_park (@bullmouse).</description>
    <link>https://dev.to/bullmouse</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1010880%2F5ebb0127-7fed-4d27-82b3-8ec16208b1d6.jpg</url>
      <title>DEV Community: sangjun_park</title>
      <link>https://dev.to/bullmouse</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/bullmouse"/>
    <language>en</language>
    <item>
      <title>AI Paper Review: ORPO - Monolithic Preference Optimization without Reference Model</title>
      <dc:creator>sangjun_park</dc:creator>
      <pubDate>Wed, 01 Jan 2025 15:00:54 +0000</pubDate>
      <link>https://dev.to/bullmouse/ai-paper-review-24l4</link>
      <guid>https://dev.to/bullmouse/ai-paper-review-24l4</guid>
      <description>&lt;p&gt;(Please note that this content was translated using GPT-o1, so there might be some mistakes or inaccuracies in the translation.)&lt;/p&gt;

&lt;p&gt;paper link: &lt;a href="https://arxiv.org/abs/2403.07691" rel="noopener noreferrer"&gt;https://arxiv.org/abs/2403.07691&lt;/a&gt; &lt;/p&gt;

&lt;h1&gt;
  
  
  Overview
&lt;/h1&gt;

&lt;p&gt;First, let’s interpret the title and understand what it means:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Monolithic Preference Optimization:&lt;/strong&gt;  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Monolithic&lt;/strong&gt; -&amp;gt; Refers to working as one large, single-structure system rather than separating multiple modules or elements.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Preference Optimization&lt;/strong&gt; -&amp;gt; Refers to the process of optimizing around a specific goal or criterion (e.g., user preference, satisfaction) that the user desires.
&lt;/li&gt;
&lt;li&gt;In other words, it means &lt;strong&gt;optimizing preferences within a single system&lt;/strong&gt; without separate sub-modules.&lt;/li&gt;
&lt;/ul&gt;




&lt;h1&gt;
  
  
  Abstract
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;SFT (Supervised Fine-Tuning):&lt;/strong&gt; A process in which a pre-trained language model (such as GPT, Llama, etc.) undergoes additional supervised learning on a specific task or domain -&amp;gt; leads to better performance on the given task.
&lt;/li&gt;
&lt;li&gt;SFT plays a key role in &lt;strong&gt;preference alignment&lt;/strong&gt;, and even a small penalty for undesired generation styles is sufficient.

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Preference Alignment:&lt;/strong&gt; Training a language model to generate responses in line with a specific standard (e.g., user preferences, task requirements). For example, if a user demands concise and clear answers, the model is trained to produce them. Conversely, providing excessive information or ambiguous answers is considered a &lt;strong&gt;“non-preferred generation style.”&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;strong&gt;Main results&lt;/strong&gt;:

&lt;ul&gt;
&lt;li&gt;Up to &lt;strong&gt;12.20%&lt;/strong&gt; improvement on AlpacaEval 2.0&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;66.19%&lt;/strong&gt; on IFEval&lt;/li&gt;
&lt;li&gt;Achieved &lt;strong&gt;7.32&lt;/strong&gt; on MT-Bench&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;




&lt;h1&gt;
  
  
  1 Introduction
&lt;/h1&gt;

&lt;h3&gt;
  
  
  Limitations of the Existing Approach
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Pre-trained Language Models (PLMs)&lt;/strong&gt;, trained on large-scale data such as web text or textbooks, demonstrate excellent performance on various NLP tasks. However, for practical applications, additional tuning such as &lt;strong&gt;Instruction Tuning&lt;/strong&gt; or &lt;strong&gt;Preference Alignment&lt;/strong&gt; is needed.

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Instruction Tuning:&lt;/strong&gt; A process where the model is trained to generalize to new tasks given instructions in natural language. It uses a unified dataset so that it can handle various inputs and produce outputs accordingly. As a result, the model acquires zero-shot or few-shot capabilities.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Preference Alignment:&lt;/strong&gt; Uses paired preference data to align models with human values. RLHF (reinforcement learning from human feedback) and DPO (directly adjusting the output probability distribution using preference data) fall under this category.
&lt;/li&gt;
&lt;li&gt;Traditional preference alignment generally follows a multi-step process (SFT -&amp;gt; reward model training -&amp;gt; reinforcement learning), thus requiring an additional reference model and a supervised fine-tuning phase.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;h3&gt;
  
  
  A New Approach
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;A new method called ORPO (Odds Ratio Preference Optimization) is proposed as a novel &lt;strong&gt;monolithic&lt;/strong&gt; alignment approach. Unlike existing methods, it can effectively suppress undesired generation styles without the need for a preparatory SFT stage or a reference model. It utilizes resources efficiently while implementing preference alignment.
&lt;/li&gt;
&lt;li&gt;ORPO demonstrates strong performance on leaderboards for the Phi-2, Llama-2, and Mistral models. It has also outperformed existing methods (RLHF, DPO) on various benchmarks such as AlpacaEval 2.0 and IFEval.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff00ozyo98u059r80goxw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff00ozyo98u059r80goxw.png" alt="2024-12-28-8-08-40" width="613" height="530"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The figure above, based on AlpacaEval 2.0, shows the results of fine-tuning Llama-2 (7B) and Mistral (7B) using different algorithms. It displays the win rate (%) of each model, comparing RLHF (in red), DPO (in green), and ORPO (in blue). From this, we can see that ORPO outperforms RLHF and DPO.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://ibb.co/Fmv1xdZ" rel="noopener noreferrer"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftu8pdwweqv0u7rp4otre.png" alt="2024-12-28-8-09-18" width="640" height="244"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This graph compares three alignment methods—RLHF, DPO, and ORPO.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;RLHF:&lt;/strong&gt; After the SFT phase, a reward model is built, and the model is fine-tuned via policy gradient based on feedback from that reward model. RLHF needs a reference model and a policy, making it a relatively complex multi-stage process.  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Reward Model:&lt;/strong&gt; Trained from human feedback -&amp;gt; provides a score for how “good” a model output is.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Policy Gradient:&lt;/strong&gt; The central algorithm for reinforcement learning. It updates the current language model (policy) based on the reward signal from the reward model.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reference Model:&lt;/strong&gt; A fixed model that serves as a baseline for the current policy. By comparing policy and reference, one can calculate the KL-divergence to ensure that the policy does not deviate too far from the reference.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;&lt;strong&gt;DPO:&lt;/strong&gt; Compared to RLHF, it has a simplified process that uses preference data to train the language model. Typically, DPO does not use a separate reference model, although in some implementations, the model from the SFT stage is designated as the reference, or a reference model is employed to provide additional stability.  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;DPO updates the model by leveraging the log odds ratio between accepted and rejected responses. Accepted responses get a strong positive signal, while rejected responses get a weaker penalty.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;strong&gt;ORPO:&lt;/strong&gt; A new method of aligning the language model with human preferences using preference data. Like DPO, it uses log odds ratio but does not rely on a reference model, directly learning from preference data. Additionally, it performs odds-ratio-based optimization right after SFT, so no additional multi-stage process is needed.&lt;/p&gt;&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://imgbb.com/" rel="noopener noreferrer"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgpidxokac1ghs48xic4g.png" alt="2024-12-28-10-29-51" width="127" height="56"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The figure above explains how log odds ratio optimization works. Good responses get a strong adaptation signal, whereas poor responses get a weaker penalty, reflecting these differences in the model’s gradient updates.&lt;/li&gt;
&lt;/ul&gt;




&lt;h1&gt;
  
  
  2 Related Works
&lt;/h1&gt;

&lt;h3&gt;
  
  
  Connections to Reinforcement Learning
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;RLHF&lt;/strong&gt; uses a Bradley-Terry model to calculate the probability of one response competing against another, training a reward model to maximize the score of the selected response. PPO (Proximal Policy Optimization) is a typical RL algorithm used here, enabling the model to learn from human preferences. This is proven to be scalable and general for instruction-following language models, extended further by RLAIF.

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;PPO (Proximal Policy Optimization):&lt;/strong&gt; A reinforcement learning update algorithm that restricts large updates to the current policy (the language model) by clipping, making it less sensitive and more stable than some other RL methods.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;RLAIF:&lt;/strong&gt; While RLHF requires human evaluators to rank or compare outputs, RLAIF uses a language model instead of humans to evaluate responses and train the reward model. This reduces costs and can be applied to larger data.
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;However, RLHF suffers from instability in PPO, requiring extensive hyperparameter search, and a reward model’s sensitivity also causes challenges. Hence, more stable preference-alignment algorithms are needed.&lt;/li&gt;

&lt;/ul&gt;

&lt;h3&gt;
  
  
  Without a Reward Model
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Various methods have been studied for performing preference alignment without a separate reward model:

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;DPO (Direct Policy Optimization):&lt;/strong&gt; Integrates reward modeling into the preference learning stage. Preference data forces the probability of favorable responses to exceed that of unfavorable ones.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;IPO (Identity Preference Optimization):&lt;/strong&gt; Developed to avoid overfitting problems that may arise in DPO, placing less emphasis on the relative gap and more on maintaining consistent baselines.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;KTO (Kahneman-Tversky Optimization):&lt;/strong&gt; An approach grounded in the behavioral economics theories of Kahneman and Tversky. Unlike RLHF or DPO, it does not rely on comparison data but instead incorporates cognitive biases inherent to human decision-making.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;ULMA (Unified Language Model Alignment):&lt;/strong&gt; A unified approach to aligning language models that features a consistent training framework and varied data. It’s said to be efficient, with simpler data preparation and a universal training structure for easier extension.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;h3&gt;
  
  
  SFT (Supervised Fine-Tuning) Revisited
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Preference alignment methods often rely on SFT as a stable starting point between the original and actively updated policies.
&lt;/li&gt;
&lt;li&gt;In RLHF, the SFT model is considered the baseline policy, and empirical results also suggest that SFT is important in non-RL alignment approaches.
&lt;/li&gt;
&lt;li&gt;Some research shows that performing SFT with a carefully curated dataset alone can yield a human-aligned language model.
&lt;/li&gt;
&lt;li&gt;Even a small set of meticulously filtered data can produce a useful language model assistant, or one can iteratively select self-generated model outputs to refine alignment. In some cases, using only a portion of a preference dataset—carefully chosen—can suffice.
&lt;/li&gt;
&lt;li&gt;However, theoretical and empirical work on how SFT integrates with preference alignment is limited.&lt;/li&gt;
&lt;/ul&gt;




&lt;h1&gt;
  
  
  3 The Role of Supervised Fine-Tuning
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;This study examines the role of Supervised Fine-Tuning as the initial step for preference alignment. SFT is crucial for adapting a pre-trained language model to a desired domain by increasing the log probability of related tokens. However, it can also inadvertently increase the likelihood of undesired styles. Thus, we need to maintain the domain-adaptation effect of SFT while distinguishing and reducing undesired generation styles.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://imgbb.com/" rel="noopener noreferrer"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffyvtjtgsgmva4971lebp.png" alt="2024-12-30-5-55-16" width="576" height="618"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The above figure shows the log probability of accepted vs. rejected responses while SFT is being performed on OPT-250M using the HH-RLHF dataset. Over training, both accepted and rejected responses’ log probabilities increase. Ideally, we would see an increase in accepted responses’ log probabilities while rejected responses remain low, but this figure shows otherwise.
&lt;/li&gt;
&lt;li&gt;In other words, while SFT helps domain adaptation, additional measures are needed to suppress undesired response styles.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  No Direct Penalty from Cross-Entropy
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Cross-entropy loss penalizes low logit values for reference (correct) tokens. Mathematically, it can be expressed as shown in the figure below.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://imgbb.com/" rel="noopener noreferrer"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frzyp3u7zu5g2cpgfx6ip.png" alt="2024-12-30-9-18-15" width="567" height="263"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;yᵢ&lt;/strong&gt;: A boolean that indicates if the token is the correct token (1 if correct, 0 if not).
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;pᵢ&lt;/strong&gt;: The predicted probability that the token is correct (between 0 and 1).
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;m&lt;/strong&gt;: The length of the sequence. For instance, if the input sentence is “Hello World,” m=2 by word, m=11 by character.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;|V|&lt;/strong&gt;: The vocabulary size of the model.
&lt;/li&gt;
&lt;li&gt;Cross-entropy aims to maximize log(pᵢ) only for the correct token yᵢ=1. For the other tokens yᵢ=0, there is no additional suppression effect.
&lt;/li&gt;
&lt;li&gt;Consequently, the log probability of rejected responses can increase as well, which is undesirable from a preference alignment standpoint.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Generalization Across Two Response Styles
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;SFT alone does not resolve the over-adjustment of accepted vs. rejected responses, as demonstrated in the study below:

&lt;ul&gt;
&lt;li&gt;Fine-tuning an OPT-350M model on the HH-RLHF dataset using accepted responses only.
&lt;/li&gt;
&lt;li&gt;Monitoring the log probability of rejected responses showed that both accepted and rejected responses increased.
&lt;/li&gt;
&lt;li&gt;This indicates that while cross-entropy loss effectively orients the model toward conversational (or domain-specific) data, it does not penalize undesired responses, so rejected responses can end up with higher log probability than accepted ones.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;h3&gt;
  
  
  Penalizing Undesired Generations
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Past research indicates that adding a penalty term to the loss function for undesired outputs can mitigate degenerative effects.

&lt;ul&gt;
&lt;li&gt;Example: To prevent repetitive outputs, one might add a penalty term for assigning high probability to tokens that appear frequently in the recent context.
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;Building on the idea that dynamic penalization of rejected responses is effective, we designed a unified preference-alignment method that penalizes undesired responses on the fly.&lt;/li&gt;

&lt;/ul&gt;




&lt;h1&gt;
  
  
  4 Odds Ratio Preference Optimization
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;Now we introduce a new algorithm called ORPO for preference alignment. This algorithm adds an odds-ratio-based penalty to the usual negative log-likelihood (NLL) loss so that the model effectively differentiates between preferred and non-preferred responses.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  4.1 Background
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://imgbb.com/" rel="noopener noreferrer"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5xt51gkyg17dtbgrku01.png" alt="2024-12-31-7-12-57" width="443" height="100"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The above formula calculates the average log likelihood of the output sequence y given the input sequence x.

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;y:&lt;/strong&gt; The output sequence, consisting of m tokens.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;x:&lt;/strong&gt; The input sequence.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Pθ(yₜ | x, y₍ₜ₎):&lt;/strong&gt; The probability that the t-th token yₜ in the output sequence y is generated given the input x and the previous tokens y₍ₜ₎.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;m:&lt;/strong&gt; The length (in tokens) of the output sequence y.
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;Essentially, the log probability of the entire sequence is summed across tokens and then averaged to avoid dependence on sequence length.&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://imgbb.com/" rel="noopener noreferrer"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1h15x91is99c63ob0aho.png" alt="Pasted-image-20241231192528" width="447" height="87"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;odds:&lt;/strong&gt; The ratio between the probability that y is generated and that it is not generated, indicating the relative likelihood of generation. If the generation probability is Pθ(y | x), then its non-generation probability is 1 - Pθ(y | x).
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;oddsθ(y | x) = k&lt;/strong&gt;: Means that for a given input x, the model θ finds y k times more likely than not-y.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://imgbb.com/" rel="noopener noreferrer"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F12mttnroefsb3ft9r3k5.png" alt="2024-12-31-7-33-34" width="449" height="73"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The odds ratio between a winning response yw (accepted) and a losing response yl (rejected) indicates how much more preferred yw is over yl.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  4.2 Objective Function of ORPO
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Objective Function:&lt;/strong&gt; In machine learning or optimization problems, this is the function that the model aims to optimize during training.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://imgbb.com/" rel="noopener noreferrer"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4nnhr0kyy6bjymp1sbjg.png" alt="2024-12-31-7-40-30" width="442" height="59"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;LSFT&lt;/strong&gt;: The SFT loss term in the ORPO objective function.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;LOR&lt;/strong&gt;: The term that maximizes the odds ratio between accepted responses and rejected responses. “OR” stands for “Odds Ratio.”
&lt;/li&gt;
&lt;li&gt;λ: A hyperparameter that controls the relative importance of the two loss terms.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;E(x,yw,yl)&lt;/strong&gt;: The expected value over the probability distribution of (x, yw, yl).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://imgbb.com/" rel="noopener noreferrer"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fklcp040j4rzdp2nw98f6.png" alt="2025-01-01-2-47-57" width="454" height="80"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;LOR&lt;/strong&gt;: Encourages a higher log odds ratio between yw (preferred) and yl (non-preferred). It wraps the log odds ratio with the log sigmoid function, so we minimize &lt;strong&gt;LOR&lt;/strong&gt; by increasing the log odds ratio between yw and yl.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;σ:&lt;/strong&gt; By wrapping the log ratio in a sigmoid function, we ensure smoothness and differentiability. Large input values approach 1, while small inputs approach 0. Consequently, LOR ranges from 0 to +∞ and we want to push it closer to 0.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  4.3 Gradient of ORPO
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;The gradient of LOR (∇θLOR) shows that using an odds-ratio-based loss is justified for preference alignment. The gradient effectively adjusts the probability difference between the winning and losing responses.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://imgbb.com/" rel="noopener noreferrer"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbkpzl5pbaiz9xd6volb4.png" alt="Pasted-image-20250101154112" width="451" height="60"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The gradient of LOR is described as the product of δ(d) and h(d).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://imgbb.com/" rel="noopener noreferrer"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6vz2naeqwszoaj09rsuk.png" alt="Pasted-image-20250101154241" width="445" height="101"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;δ(d) is a penalty term that suppresses non-preferred responses.
&lt;/li&gt;
&lt;li&gt;In the extreme, if oddsθ(yw|x) ≈ oddsθ(yl|x) (i.e., when the odds of the winning and losing responses are similar), δ(d) approaches 1/2.
&lt;/li&gt;
&lt;li&gt;Conversely, if oddsθ(yw|x) ≫ oddsθ(yl|x), meaning the winning response has a much higher odds than the losing response, δ(d) approaches 0.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://imgbb.com/" rel="noopener noreferrer"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxenv4shuisu99iadonpf.png" alt="2025-01-01-3-47-59" width="432" height="99"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;h(d) updates the parameters θ in a way that raises the probability of the desired label yw and lowers that of yl.
&lt;/li&gt;
&lt;li&gt;Because ∇θlog p(θ) = (1/p(θ))∇θp(θ), when Pθ(yw|x) is already high, the update magnitude is larger. Conversely, if Pθ(yw|x) is small, the update magnitude is smaller. Intuitively, “if the model is already confident about yw, a small parameter change could significantly alter that probability, so we apply a larger update.”
&lt;/li&gt;
&lt;li&gt;1 − Pθ(yw|x) is the probability that yw has not yet occurred. As Pθ(yw|x) grows, the update scale increases, and as it decreases, the scale shrinks.
&lt;/li&gt;
&lt;li&gt;For yl, a negative sign is applied, so it is updated in the opposite direction of yw.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Why “the higher the probability, the larger the update”?
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;ORPO aims to widen the gap between the probabilities of yw (preferred) and yl (non-preferred). That is, it makes the good better and the bad worse.&lt;/li&gt;
&lt;/ul&gt;




&lt;h1&gt;
  
  
  5 Experimental Settings
&lt;/h1&gt;

&lt;h2&gt;
  
  
  5.1 Training Setup
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Model
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;We scale the OPT model from 125M to 1.3B parameters and compare four methods:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Supervised Fine-Tuning (SFT)&lt;/li&gt;
&lt;li&gt;Proximal Policy Optimization (PPO)&lt;/li&gt;
&lt;li&gt;Direct Policy Optimization (DPO)&lt;/li&gt;
&lt;li&gt;Odds Ratio Preference Optimization (ORPO)
&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The PPO and DPO models are trained on accepted responses for a single epoch, starting from the SFT model, using the TRL library.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We denote this by adding a “+” (e.g., +DPO).&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;Additionally, the following models are included in the training:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Phi-2 (2.7B): A pre-trained language model with strong downstream performance&lt;/li&gt;
&lt;li&gt;Llama2 (7B)&lt;/li&gt;
&lt;li&gt;Mistral (7B)&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;h3&gt;
  
  
  Dataset
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Each training configuration and model is tested on two datasets:

&lt;ul&gt;
&lt;li&gt;Anthropic’s HH-RLHF&lt;/li&gt;
&lt;li&gt;Binarized UltraFeedback
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;We filter out cases where yw = yl (preferred and non-preferred are identical) or where yw or yl is empty.&lt;/li&gt;

&lt;/ul&gt;

&lt;h3&gt;
  
  
  Reward Model
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;We train separate reward models for OPT-350M and OPT-1.3B.&lt;/li&gt;
&lt;li&gt;The objective function of the reward model is as follows:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://imgbb.com/" rel="noopener noreferrer"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fox0delyi9e1gc7gvbwp7.png" alt="2025-01-01-5-14-19" width="449" height="69"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;By taking the difference between the scores of preferred and non-preferred responses and passing it through a sigmoid, the output is close to 1 if the difference is large and positive, approaching 0 otherwise. Taking the log of this value ranges from 0 to negative infinity, reflecting the reward difference.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  5.2 Leaderboard Evaluation Summary
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;AlpacaEval Evaluation:&lt;/strong&gt; We compare ORPO to other instruction-tuned models on the AlpacaEval1.0/2.0 benchmarks.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Models under comparison: Llama-2 Chat (7B, 13B), Zephyr (α, β)&lt;/li&gt;
&lt;li&gt;AlpacaEval1.0: Uses GPT-4 as an evaluator, checking if a model’s response is preferred over text-davinci-003.&lt;/li&gt;
&lt;li&gt;AlpacaEval2.0: Uses GPT-4-turbo to check if a model’s response is preferred over GPT-4 responses.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;strong&gt;MT-Bench Evaluation:&lt;/strong&gt; This benchmark assesses how well the model follows instructions in multi-turn conversations. GPT-4 is used as the evaluator to judge the quality of answers to challenging questions.&lt;/p&gt;&lt;/li&gt;

&lt;/ul&gt;




&lt;h1&gt;
  
  
  6 Results and Analysis
&lt;/h1&gt;

&lt;h2&gt;
  
  
  6.1 Performance of ORPO
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Compared to RLHF or DPO, ORPO enables the model to learn user preferences more quickly and stably.&lt;/li&gt;
&lt;li&gt;Even with a small amount of data and limited training, it achieves high-level instruction-following performance (shown in Llama-2, Mistral, Phi-2, etc.).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  6.2 Single-Turn Instruction-Following
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Applying ORPO to Phi-2 (2.7B) significantly boosts its AlpacaEval score, surpassing Llama-2 Chat 7B performance (71.80%, 6.35% -&amp;gt; Llama-2 Chat 7B is 71.34%, 4.96%).&lt;/li&gt;
&lt;li&gt;Applying ORPO to Llama-2 (7B) outperforms Llama-2 Chat 7B and 13B RLHF versions in AlpacaEval (81.26%, 9.44%).&lt;/li&gt;
&lt;li&gt;Applying ORPO to Mistral (7B) produces Mistral-ORPO-α (7B) and β (7B), which rival or outperform the Zephyr series in single-turn tasks.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  6.3 Multi-Turn Instruction-Following
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;According to MT-Bench, the Mistral-ORPO series (7B) achieves quite competitive scores (7.23–7.32) compared to larger or commercial models such as Llama-2-Chat 70B and Claude.&lt;/li&gt;
&lt;li&gt;This suggests that even single-turn training data can help the model generalize to multi-turn dialogues.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  6.4 Win Rate from the Reward Model Perspective
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;On OPT (125M, 350M, 1.3B), ORPO achieves a much higher win rate compared to SFT, PPO, or DPO.&lt;/li&gt;
&lt;li&gt;The larger the model, the more ORPO outperforms DPO (e.g., 70.9% vs. DPO at OPT-1.3B).&lt;/li&gt;
&lt;li&gt;ORPO reliably obtains higher rewards across different datasets (UltraFeedback, HH-RLHF).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  6.5 Lexical Diversity Analysis
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;ORPO-trained models exhibit slightly lower per-input diversity compared to DPO (i.e., they provide more consistent responses for a given prompt), but higher across-input diversity overall.&lt;/li&gt;
&lt;li&gt;This indicates that ORPO is producing more optimized answers for each individual request while maintaining varied response patterns across multiple inputs.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In summary, ORPO is an efficient and stable method compared to previous approaches (DPO, RLHF, PPO) and achieves improved instruction-following and reward gains across various model sizes. It also balances intra-prompt consistency with inter-prompt variability, producing responses that better meet users’ demands.&lt;/p&gt;




&lt;h1&gt;
  
  
  7 Discussion
&lt;/h1&gt;

&lt;h2&gt;
  
  
  7.1 Comparison to Probability Ratio
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Odds Ratio vs. Probability Ratio
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Traditional preference alignment methods often apply probability ratios (PR) within SFT.&lt;/li&gt;
&lt;li&gt;ORPO, however, adopts the odds ratio (OR), which offers the following advantages over probability ratio:

&lt;ul&gt;
&lt;li&gt;Odds ratio is more responsive to model understanding of preference.&lt;/li&gt;
&lt;li&gt;Using a probability ratio can lead to overly strong suppression of non-preferred responses.&lt;/li&gt;
&lt;li&gt;The odds ratio avoids extreme suppression, enabling stable co-training of SFT and preference alignment.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;h3&gt;
  
  
  Experimental Simulation
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Drawing random probability pairs (X₁, X₂), computing both PR and OR, and then comparing log-scale distributions shows that:

&lt;ul&gt;
&lt;li&gt;PR yields a sharper, more skewed distribution,&lt;/li&gt;
&lt;li&gt;OR, by contrast, is smoother and more spread out.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;When minimizing log sigmoid loss in preference alignment, PR can overly suppress non-preferred tokens, causing abnormal model convergence.&lt;/li&gt;

&lt;/ul&gt;

&lt;h3&gt;
  
  
  Conclusion: Why Odds Ratio is More Suitable
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;In the SFT-inclusive preference alignment setting, moderate “prioritization” outperforms harsh suppression.&lt;/li&gt;
&lt;li&gt;Probability ratio triggers excessive suppression, so ORPO chooses odds ratio to properly reduce non-preferred responses and promote preferred ones.&lt;/li&gt;
&lt;li&gt;This prevents undue logit flattening (which degrades quality) and lets SFT + preference alignment proceed in harmony.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Minimizing LOR
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Reflecting Preferences During ORPO Training
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Visualization of the training process under ORPO reveals that while preferred responses maintain or increase their log probabilities, undesired ones progressively decline.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Changes in Log Odds Ratio
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;As the log odds ratio rises, log probabilities of undesired responses steadily drop. Hence, ORPO retains the domain-adaptation benefit of SFT while reducing the likelihood of undesirable outputs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Effect of λ Parameter
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;By varying λ in ORPO’s loss function, one can analyze how the gap in log probability between preferred and non-preferred responses changes. A larger λ results in stronger suppression of undesired responses, whereas a smaller λ applies milder suppression.&lt;/li&gt;
&lt;/ul&gt;




&lt;h1&gt;
  
  
  8 Conclusion
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;This paper revisited the role of SFT and introduced a single-stage preference alignment method called ORPO, which forgoes a reference model and integrates preference alignment directly.
&lt;/li&gt;
&lt;li&gt;Compared to SFT or RLHF, ORPO was consistently more preferred by reward models at all scales.
&lt;/li&gt;
&lt;li&gt;ORPO’s win rate against DPO also increases as model size grows.
&lt;/li&gt;
&lt;li&gt;Specifically, testing on 2.7B and 7B models showed that ORPO exceeds large models on the AlpacaEval metric, and Mistral-ORPO-α and β achieved 11.33% and 12.20% gains on AlpacaEval2.0 and 7.23 and 7.32 on MT-Bench, demonstrating both efficiency and efficacy.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Limitations
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;While we compared DPO and RLHF, we have not covered a more extensive range of preference alignment algorithms.
&lt;/li&gt;
&lt;li&gt;Future work will explore models beyond 7B and validate generalization across multiple domains and data quality settings.
&lt;/li&gt;
&lt;li&gt;Additionally, we plan to deepen our analysis of how ORPO affects the internal workings of pre-trained models across subsequent preference alignment stages.&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    <item>
      <title>How to use CleanLab wisely</title>
      <dc:creator>sangjun_park</dc:creator>
      <pubDate>Fri, 08 Nov 2024 09:44:08 +0000</pubDate>
      <link>https://dev.to/bullmouse/how-to-use-cleanlab-wisely-5epf</link>
      <guid>https://dev.to/bullmouse/how-to-use-cleanlab-wisely-5epf</guid>
      <description>&lt;p&gt;Data quality plays an important role in model performance. While sophisticated algorithms continue to emerge, the axiom "garbage in, garbage out" remains true. CleanLab emerges as a groundbreaking solution to this persistent challenge, offering a systematic approach to identifying and correcting label errors in datasets. &lt;br&gt;
The CleanLab represents a paradigm shift in data quality management by implementing confident learning algorithms. This framework automatically identifies potential label errors. So, I search several models to identify through using CleanLab to figure out which one could be the best to enhance the performance. &lt;/p&gt;
&lt;h3&gt;
  
  
  Linear Models
&lt;/h3&gt;

&lt;p&gt;Linear models play a crucial role in CleanLab's data cleaning framework. Their effectiveness stems from several key characteristics that make them particularly valuable for identifying label errors and ensuring data quality. &lt;/p&gt;

&lt;p&gt;Linear models are quite effective in CleanLab. Especially, the robust baseline performance are quite stable and they have reliable probability estimates.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;sklearn.linear_model&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;LogisticRegression&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;cleanlab.classification&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;CleanLearning&lt;/span&gt;

&lt;span class="c1"&gt;# Creating an interpretable linear model
&lt;/span&gt;&lt;span class="n"&gt;linear_model&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;LogisticRegression&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;C&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;1.0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;class_weight&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;balanced&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;random_state&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# Integrating with CleanLab
&lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;CleanLearning&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;linear_model&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  SVM
&lt;/h3&gt;

&lt;p&gt;support vector machine (SVM) is a powerful supervised learning algorithm used for classification and regression tasks. It's particularly effective in high-dimensional spaces and is widely used in various machine learning applications &lt;/p&gt;

&lt;p&gt;The key concepts of SVM are &lt;strong&gt;Margin, Support Vectors, and the Kernel Trick&lt;/strong&gt;. Margin is the distance between the decision boundary and the nearest data points. The SVM aims to maximize this margin. and Larger margins generally lead to better generalization. Support Vectors points closest to the decision boundary. This is the critical points that define the margin. And only these points affect the devision boundary. Finally, the Kernel Trick Transforms non-linear problems into linear ones. And it maps data into higher-dimensional space.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# Common kernel options in sklearn
&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;sklearn.svm&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;SVC&lt;/span&gt;

&lt;span class="c1"&gt;# Linear kernel
&lt;/span&gt;&lt;span class="n"&gt;linear_svm&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;SVC&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;kernel&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;linear&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# RBF (Gaussian) kernel
&lt;/span&gt;&lt;span class="n"&gt;rbf_svm&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;SVC&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;kernel&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;rbf&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# Polynomial kernel
&lt;/span&gt;&lt;span class="n"&gt;poly_svm&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;SVC&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;kernel&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;poly&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;degree&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Random Forest Classifier
&lt;/h3&gt;

&lt;p&gt;Random Forest Classifier is particularly effective in CleanLab due to its ensemble nature and robust probability estimates. Multiple decision trees provide robust predictions. And this naturally handling the outliers and noise.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;sklearn.ensemble&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;RandomForestClassifier&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;cleanlab.classification&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;CleanLearning&lt;/span&gt;

&lt;span class="c1"&gt;# Basic setup
&lt;/span&gt;&lt;span class="n"&gt;rf_model&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;RandomForestClassifier&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;n_estimators&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;max_depth&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;None&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;min_samples_split&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;min_samples_leaf&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;bootstrap&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;random_state&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# Integration with CleanLab
&lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;CleanLearning&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;rf_model&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  XGBoost
&lt;/h3&gt;

&lt;p&gt;XGBoost is an ensemble learning technique that builds models sequentially. And each new model tries to correct errors made by previous models. Gradient boosting uses gradient descent to minimize errors. And combines weak learners into a strong predictor.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;xgboost&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;xgb&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;cleanlab.classification&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;CleanLearning&lt;/span&gt;

&lt;span class="c1"&gt;# Basic XGBoost setup
&lt;/span&gt;&lt;span class="n"&gt;xgb_model&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;xgb&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;XGBClassifier&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;n_estimators&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;        &lt;span class="c1"&gt;# Number of boosting rounds
&lt;/span&gt;    &lt;span class="n"&gt;learning_rate&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;0.1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;       &lt;span class="c1"&gt;# Step size shrinkage
&lt;/span&gt;    &lt;span class="n"&gt;max_depth&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;             &lt;span class="c1"&gt;# Maximum tree depth
&lt;/span&gt;    &lt;span class="n"&gt;min_child_weight&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;      &lt;span class="c1"&gt;# Minimum sum of instance weight
&lt;/span&gt;    &lt;span class="n"&gt;subsample&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;0.8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;           &lt;span class="c1"&gt;# Subsample ratio of training instances
&lt;/span&gt;    &lt;span class="n"&gt;colsample_bytree&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;0.8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;    &lt;span class="c1"&gt;# Subsample ratio of columns
&lt;/span&gt;    &lt;span class="n"&gt;objective&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;binary:logistic&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;  &lt;span class="c1"&gt;# Objective function
&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Soft Voting Ensemble
&lt;/h3&gt;

&lt;p&gt;Finally, we can make soft voting ensemble to make cleanlab more effectively. Soft voting combines probability predictions from multiple models by averaging their predicted probabilities. rather than just taking the majority vote of predicted classes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;sklearn.ensemble&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;VotingClassifier&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;sklearn.svm&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;SVC&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;sklearn.linear_model&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;LogisticRegression&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;sklearn.ensemble&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;RandomForestClassifier&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;xgboost&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;xgb&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;cleanlab.classification&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;CleanLearning&lt;/span&gt;

&lt;span class="c1"&gt;# Initialize base models
&lt;/span&gt;&lt;span class="n"&gt;svm_model&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;SVC&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;probability&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;kernel&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;rbf&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;rf_model&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;RandomForestClassifier&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n_estimators&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;xgb_model&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;xgb&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;XGBClassifier&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n_estimators&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;lr_model&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;LogisticRegression&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

&lt;span class="c1"&gt;# Create voting classifier
&lt;/span&gt;&lt;span class="n"&gt;ensemble&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;VotingClassifier&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;estimators&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;svm&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;svm_model&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
        &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;rf&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;rf_model&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
        &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;xgb&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;xgb_model&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
        &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;lr&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;lr_model&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;],&lt;/span&gt;
    &lt;span class="n"&gt;voting&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;soft&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# Integrate with CleanLab
&lt;/span&gt;&lt;span class="n"&gt;cl_ensemble&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;CleanLearning&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ensemble&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>The Method of Tokenizing: In the Perspective of Sparse Embedding</title>
      <dc:creator>sangjun_park</dc:creator>
      <pubDate>Mon, 28 Oct 2024 00:55:16 +0000</pubDate>
      <link>https://dev.to/bullmouse/the-method-of-tokenizing-in-the-perspective-of-sparse-embedding-181</link>
      <guid>https://dev.to/bullmouse/the-method-of-tokenizing-in-the-perspective-of-sparse-embedding-181</guid>
      <description>&lt;p&gt;(In progress)&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Poly-Encoder</title>
      <dc:creator>sangjun_park</dc:creator>
      <pubDate>Fri, 18 Oct 2024 11:55:39 +0000</pubDate>
      <link>https://dev.to/bullmouse/poly-encoder-39ig</link>
      <guid>https://dev.to/bullmouse/poly-encoder-39ig</guid>
      <description>&lt;h3&gt;
  
  
  Introduction
&lt;/h3&gt;

&lt;p&gt;Poly Encoder is a neural network architecture used in dialogue systems and information retrieval. Developed by Facebook AI Research in 2020, it combines the strengths of Bi-encoders and Cross-encoders to improve performance and efficiency. &lt;/p&gt;

&lt;h3&gt;
  
  
  Why are we using Poly-Encoder?
&lt;/h3&gt;

&lt;p&gt;The most convincing reason why we are using Poly-encoder is to improve the performance. Poly encoder offers a balance between the speed of Bi-encoders and the accuracy of Cross-encoders. This makes it particularly effective for tasks that require both efficiency and precision. &lt;/p&gt;

&lt;p&gt;Let's Compare to Cross-encoders and Bi-encoders to know which one would be the best for you.&lt;/p&gt;

&lt;h5&gt;
  
  
  Bi-encoders
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Speed:&lt;/strong&gt; Very fast &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Accuracy:&lt;/strong&gt; Lower compared to Cross-Encoders. They lack direct interaction between query and candidates, potentially missing nuanced relationships. 
##### Cross-encoders &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Speed:&lt;/strong&gt; Very Slow, especially with large candidate sets. They process query and each candidate together, requiring separate computation for each pair.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Accuracy:&lt;/strong&gt; Very High. Much better than Bi-Encoders or Poly-encoders. Direct interaction between query and candidates allows for capturing complex relationships 
##### Poly-encoders &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Speed:&lt;/strong&gt; Medium. Faster than Cross-encoders and slightly slower than Bi-encoders.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Accuracy:&lt;/strong&gt; Better than Bi-encoders and approaching that of Cross-encoders. The multiple code vectors and attention mechanism allow for more nuanced matching. &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Poly Encoders achieve this balance through Pre-computation, Attention Mechanism, and Multiple code vectors&lt;/strong&gt; &lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  The Structure of Poly-Encoder
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6m283ev9fyj4ztsfv6so.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6m283ev9fyj4ztsfv6so.png" alt="Poly-Encoder 1" width="800" height="585"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This diagram illustrates the architecture of Poly-Encoder model, which is designed for efficient and effective text matching.  &lt;/p&gt;

&lt;h4&gt;
  
  
  Context Encoder
&lt;/h4&gt;

&lt;p&gt;In Context Encoder, it takes multiple inputs (such as In_x 1, In_x 2, ..., In_x N_x). Then it processes these inputs to produce multiple output embeddings (such as Out_x 1, Out_x 2, ..., Out_x N_x). These outputs represent different aspects or features or input context. &lt;/p&gt;

&lt;h4&gt;
  
  
  Query Codes
&lt;/h4&gt;

&lt;p&gt;This is a set of learnable vectors(Code 1, ..., Code m). And These act as global features that the model learns to extract from the context. &lt;/p&gt;

&lt;h4&gt;
  
  
  Attention Mechanism
&lt;/h4&gt;

&lt;p&gt;For each query code, an attention mechanism is applied over the context encoder outputs. Attention Mechanism produces. This produces a set of embeddings (Emb 1, ..., Emb m) that capture different aspects of the context relevant to each query code.  &lt;/p&gt;

&lt;h4&gt;
  
  
  Context Embedding (Ctxt Emb)
&lt;/h4&gt;

&lt;p&gt;This is another attention mechanism combines the embeddings from the previous step into a single context embedding. This embedding represents the entire context, weighted by its relevance to the query. &lt;/p&gt;

&lt;h4&gt;
  
  
  Candidate Encoder
&lt;/h4&gt;

&lt;p&gt;This is similar to the context encoder, but processes candidate responses. The outputs(Out_y 1, Out_y 2, ..., Out_y N_y) represent features of the candidate.&lt;/p&gt;

&lt;h4&gt;
  
  
  Candidate Aggregator
&lt;/h4&gt;

&lt;p&gt;It combines the candidate encoder outputs into a single candidate embedding (Cand emb) &lt;/p&gt;

&lt;h4&gt;
  
  
  Scoring
&lt;/h4&gt;

&lt;p&gt;The final score is computed by combining the context embedding and the candidate embedding. This score represents the relevance or match between the context and the candidate. &lt;/p&gt;

</description>
    </item>
    <item>
      <title>Overview of Retrieval-Augmented Generation (RAG)</title>
      <dc:creator>sangjun_park</dc:creator>
      <pubDate>Fri, 11 Oct 2024 05:44:06 +0000</pubDate>
      <link>https://dev.to/bullmouse/overview-of-retrieval-augmented-generation-rag-4ik9</link>
      <guid>https://dev.to/bullmouse/overview-of-retrieval-augmented-generation-rag-4ik9</guid>
      <description>&lt;p&gt;(in progress)&lt;/p&gt;

</description>
    </item>
    <item>
      <title>BERT, roBERTa, ELECTRA Overview</title>
      <dc:creator>sangjun_park</dc:creator>
      <pubDate>Fri, 27 Sep 2024 10:13:51 +0000</pubDate>
      <link>https://dev.to/bullmouse/bert-bidirectional-encoder-representations-from-transformers-4il8</link>
      <guid>https://dev.to/bullmouse/bert-bidirectional-encoder-representations-from-transformers-4il8</guid>
      <description>&lt;p&gt;(in progress)&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Basic Linux for AI Developers</title>
      <dc:creator>sangjun_park</dc:creator>
      <pubDate>Fri, 13 Sep 2024 04:09:49 +0000</pubDate>
      <link>https://dev.to/bullmouse/basic-linux-for-ai-developers-in-progress-2kf9</link>
      <guid>https://dev.to/bullmouse/basic-linux-for-ai-developers-in-progress-2kf9</guid>
      <description>&lt;h2&gt;
  
  
  1. Brief Introduction to Linux
&lt;/h2&gt;

&lt;p&gt;Linux is a crucial OS for AI development due to its open-source nature, stability, efficiency, and compatibility with AI frameworks. It offers scalability, strong community support, and cost-effectiveness, making it an ideal platform for AI projects from development to deployment. &lt;/p&gt;

&lt;h2&gt;
  
  
  2. Essential Linux Commands
&lt;/h2&gt;

&lt;p&gt;There are lots of commands in linux, However, I'll introduce something that is used most commonly. &lt;/p&gt;

&lt;h4&gt;
  
  
  Navigating the file system: ls, cd, pwd &amp;amp; permission command: chmod, chown
&lt;/h4&gt;

&lt;h5&gt;
  
  
  ls
&lt;/h5&gt;

&lt;p&gt;the &lt;strong&gt;'ls'&lt;/strong&gt; command in Linux stands for &lt;strong&gt;"list"&lt;/strong&gt; and is used to display the contents of a directory. It shows the files, directories, and sometimes additional details such as file permissions, size, and modification date. &lt;/p&gt;

&lt;p&gt;Here are some example of basic structure of files and directories.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="n"&gt;project&lt;/span&gt;&lt;span class="p"&gt;/&lt;/span&gt;
&lt;span class="err"&gt;├──&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;/&lt;/span&gt;
&lt;span class="err"&gt;│&lt;/span&gt;   &lt;span class="err"&gt;├──&lt;/span&gt; &lt;span class="n"&gt;dataset&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;csv&lt;/span&gt;
&lt;span class="err"&gt;│&lt;/span&gt;   &lt;span class="err"&gt;├──&lt;/span&gt; &lt;span class="n"&gt;processed_data&lt;/span&gt;&lt;span class="p"&gt;/&lt;/span&gt;
&lt;span class="err"&gt;│&lt;/span&gt;   &lt;span class="err"&gt;└──&lt;/span&gt; &lt;span class="n"&gt;raw_data&lt;/span&gt;&lt;span class="p"&gt;/&lt;/span&gt;
&lt;span class="err"&gt;├──&lt;/span&gt; &lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;/&lt;/span&gt;
&lt;span class="err"&gt;│&lt;/span&gt;   &lt;span class="err"&gt;└──&lt;/span&gt; &lt;span class="n"&gt;model_v1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;h5&lt;/span&gt;
&lt;span class="err"&gt;├──&lt;/span&gt; &lt;span class="n"&gt;scripts&lt;/span&gt;&lt;span class="p"&gt;/&lt;/span&gt;
&lt;span class="err"&gt;│&lt;/span&gt;   &lt;span class="err"&gt;└──&lt;/span&gt; &lt;span class="n"&gt;train&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;py&lt;/span&gt;
&lt;span class="err"&gt;├──&lt;/span&gt; &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;gitignore&lt;/span&gt;
&lt;span class="err"&gt;├──&lt;/span&gt; &lt;span class="nc"&gt;README&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;md&lt;/span&gt;
&lt;span class="err"&gt;└──&lt;/span&gt; &lt;span class="n"&gt;venv&lt;/span&gt;&lt;span class="p"&gt;/&lt;/span&gt;
    &lt;span class="err"&gt;├──&lt;/span&gt; &lt;span class="n"&gt;bin&lt;/span&gt;&lt;span class="p"&gt;/&lt;/span&gt;
    &lt;span class="err"&gt;├──&lt;/span&gt; &lt;span class="n"&gt;include&lt;/span&gt;&lt;span class="p"&gt;/&lt;/span&gt;
    &lt;span class="err"&gt;├──&lt;/span&gt; &lt;span class="n"&gt;lib&lt;/span&gt;&lt;span class="p"&gt;/&lt;/span&gt;
    &lt;span class="err"&gt;└──&lt;/span&gt; &lt;span class="n"&gt;pyvenv&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;cfg&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we type 'ls' in this case,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;ls&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It will show like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nv"&gt;$ &lt;/span&gt;&lt;span class="nb"&gt;ls 
&lt;/span&gt;data models scripts .gitignore README.md venv
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, we'll now use &lt;strong&gt;ls -l&lt;/strong&gt; command to watch some detailed view of the directories and files.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nv"&gt;$ &lt;/span&gt;&lt;span class="nb"&gt;ls&lt;/span&gt; &lt;span class="nt"&gt;-l&lt;/span&gt; 
drwxr-xr-x 2 user user 4096 Sep 21 12:34 data 
drwxr-xr-x 2 user user 4096 Sep 21 12:35 models 
drwxr-xr-x 2 user user 4096 Sep 21 12:36 scripts 
&lt;span class="nt"&gt;-rw-r--r--&lt;/span&gt; 1 user user 220 Sep 21 12:33 .gitignore 
&lt;span class="nt"&gt;-rw-r--r--&lt;/span&gt; 1 user user 345 Sep 21 12:33 README.md 
drwxr-xr-x 6 user user 4096 Sep 21 12:37 venv
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In Linux, file permissions are represented by string of 10 characters that control who can read, write, or execute a file or directory.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;drwxr-xr-x

&lt;span class="c"&gt;# we can separate this by&lt;/span&gt;
1 3.  3.  3.  chars
d rwx r-x r--
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;First character(d) represents the &lt;strong&gt;type of file&lt;/strong&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;d:&lt;/strong&gt; directory &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;-:&lt;/strong&gt; regular file (non-directory) &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;l:&lt;/strong&gt; symbolic link (special type of file that acts as a reference or pointer to another file or directory)&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;Next three characters(rwx) represents the &lt;strong&gt;permissions for the owner.&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;r: stands for &lt;strong&gt;read&lt;/strong&gt; permission&lt;/li&gt;
&lt;li&gt;w: stands for &lt;strong&gt;write&lt;/strong&gt; permission&lt;/li&gt;
&lt;li&gt;x: stands for &lt;strong&gt;execute&lt;/strong&gt; permission (for directories, it means the ability to list or traverse the directory)&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;Next three characters(r-x) represents the &lt;strong&gt;permissions for the group.&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;r, w, x:&lt;/strong&gt; same meaning as I explained it before &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;-:&lt;/strong&gt; no permission. In this case, there are '-' in second one so it means it doesn't have any write permission.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;Final three characters(r--) represents the permissions for others. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;In this case, the others have only read permission and don't have any write or execute permission.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;h5&gt;
  
  
  chmod
&lt;/h5&gt;

&lt;p&gt;this command stands for &lt;strong&gt;"change mode"&lt;/strong&gt;. It's a command used in Unix and Unix-like operating systems to change the access permissions of file system objects(files and directories). &lt;/p&gt;

&lt;p&gt;chmod allows to set permissions for three categories of users. &lt;strong&gt;The 'owner', 'group', and 'others'.&lt;/strong&gt; And for each category, you can set three types of permissions which is called &lt;strong&gt;Read(r), Write(w), and Execute(x).&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;The method of using chmod has two types of things. The first one is &lt;strong&gt;symbolic method&lt;/strong&gt;, and the second one is &lt;strong&gt;numeric method&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;The format of symbolic method is like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;Format: &lt;span class="nb"&gt;chmod&lt;/span&gt; &lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;who&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt; &lt;span class="o"&gt;[&lt;/span&gt;operation] &lt;span class="o"&gt;[&lt;/span&gt;permissions] filename
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Who: &lt;strong&gt;u&lt;/strong&gt; (user/owner), &lt;strong&gt;g&lt;/strong&gt; (group), &lt;strong&gt;o&lt;/strong&gt; (others), &lt;strong&gt;a&lt;/strong&gt; (all) &lt;/li&gt;
&lt;li&gt;Operation: &lt;strong&gt;+&lt;/strong&gt; (add), &lt;strong&gt;-&lt;/strong&gt; (remove), &lt;strong&gt;=&lt;/strong&gt; (set exactly)&lt;/li&gt;
&lt;li&gt;Permissions: &lt;strong&gt;r&lt;/strong&gt; (read), &lt;strong&gt;w&lt;/strong&gt; (write), &lt;strong&gt;x&lt;/strong&gt; (execute)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  For example, 
&lt;/h2&gt;

&lt;p&gt;&lt;br&gt;
 &lt;code&gt;chmod u+x file.sh&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;h2&gt;
  
  
    (Add execute permission for the owner in file.sh) 
&lt;/h2&gt;

&lt;p&gt;&lt;br&gt;
 &lt;code&gt;chmod go-rw file.txt&lt;/code&gt;&lt;br&gt;
&lt;br&gt;
 (Remove read and write permissions for group and others)&lt;/p&gt;

&lt;p&gt;The format of numeric method is like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;Format: &lt;span class="nb"&gt;chmod&lt;/span&gt; &lt;span class="o"&gt;[&lt;/span&gt;assigned_3_numbers] filename
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each permission is assigned a number: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Read (r) = 4&lt;/li&gt;
&lt;li&gt;Write (w) = 2 &lt;/li&gt;
&lt;li&gt;Execute (x) = 1&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And sum these numbers for each category(owner, group, others).&lt;/p&gt;

&lt;h2&gt;
  
  
  For example, 
&lt;/h2&gt;

&lt;p&gt;&lt;br&gt;
 &lt;code&gt;chmod 755 file.sh&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- **Owner:** 7 (4+2+1 =&amp;gt; read, write, and execute)
- **Group:** 5 (4+1 =&amp;gt; read, execute) 
- **Others:** 5 (4 + 1 =&amp;gt; read, execute) 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  There are some command like this.
&lt;/h2&gt;

&lt;p&gt;&lt;br&gt;
 &lt;code&gt;chmod -R 755 directory&lt;/code&gt;&lt;br&gt;
&lt;br&gt;
 (Recursively set permissions for a directory and its contents)&lt;/p&gt;
&lt;h5&gt;
  
  
  chown
&lt;/h5&gt;

&lt;p&gt;this command stands for &lt;strong&gt;"change owner"&lt;/strong&gt;. It's a command used in Unix and Unix-like OS to change the owner and group of files and directories. "chown" command allows to change the user owner, or the group owner, or both the user and group owners simultaneously. &lt;/p&gt;

&lt;p&gt;The basic syntax of the chown command is like this:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;chown&lt;/span&gt; &lt;span class="o"&gt;[&lt;/span&gt;options] &amp;lt;owner&amp;gt;:&amp;lt;group&amp;gt; &amp;lt;file/directory&amp;gt;&lt;span class="sb"&gt;`&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&amp;lt;owner&amp;gt;:&lt;/strong&gt; The new owner of the file or directory.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&amp;lt;group&amp;gt;:&lt;/strong&gt; (Optional) The new group for the file or directory. &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&amp;lt;file/directory&amp;gt;:&lt;/strong&gt; The file or directory whose ownership you want to change.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;[options]:&lt;/strong&gt; additional flags or parameters that modify the behavior of the command.
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here are some of the examples that could explain chown well.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;example 1: Change the Owner of a Single File&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;sudo chown &lt;/span&gt;user1 file1.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command changes the owner of &lt;strong&gt;file1.txt&lt;/strong&gt; to &lt;strong&gt;user1&lt;/strong&gt; while keeping the group unchanged. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;example 2: Change Both Owner and Group of a File&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;sudo chown &lt;/span&gt;user1:group1 file1.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This changes the owner of &lt;strong&gt;file1.txt&lt;/strong&gt; to &lt;strong&gt;user1&lt;/strong&gt; and the group to &lt;strong&gt;group1.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;example 3: Change Ownership of All Files in a Directory Recursively&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;sudo chown&lt;/span&gt; &lt;span class="nt"&gt;-R&lt;/span&gt; user1:group1 /home/user1/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command changes ownership for all files and subdirectories within &lt;strong&gt;/home/user1/&lt;/strong&gt;, making &lt;strong&gt;user1&lt;/strong&gt; the owner and &lt;strong&gt;group1&lt;/strong&gt; the group for every item inside the directory.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;example 4: Change Ownership Using a Reference File&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;sudo chown&lt;/span&gt; &lt;span class="nt"&gt;--reference&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;ref_file.txt target_file.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command changes the ownership of &lt;strong&gt;target_file.txt&lt;/strong&gt; to match the ownership of &lt;strong&gt;ref_file.txt.&lt;/strong&gt; It's useful if you want to apply the same ownership attributes as a reference file. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;example 5: Suppress Errors During Ownership Change:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;sudo chown&lt;/span&gt; &lt;span class="nt"&gt;-f&lt;/span&gt; user1:group1 /some/protected/file
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;-f option:&lt;/strong&gt; forces the command to ignore errors, such as permission issues, and completes the operation without displaying error messages. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;example 6: Verbose Output to See What's Being Changed:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;sudo chown&lt;/span&gt; &lt;span class="nt"&gt;-v&lt;/span&gt; user1:group1 file1.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command displays a message for each file whose ownership is changed, providing a clear overview of the modification. &lt;/p&gt;

&lt;h4&gt;
  
  
  File and directory manipulation: mkdir, touch, cp, mv, rm
&lt;/h4&gt;

&lt;h5&gt;
  
  
  mkdir
&lt;/h5&gt;

&lt;p&gt;The command &lt;strong&gt;'mkdir'&lt;/strong&gt; stands for &lt;strong&gt;"make directory"&lt;/strong&gt;. It's used in command-line interfaces to create a new directory (folder) in a file system. The purpose of &lt;strong&gt;'mkdir'&lt;/strong&gt; is to create one or more new directories. If you want to use 'mkdir', just typically type 'mkdir' followed by the name of the directory named "new_folder" in your current location. &lt;/p&gt;

&lt;p&gt;There are several ways to make directory with using &lt;strong&gt;"mkdir"&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Create a single directory&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;mkdir &lt;/span&gt;documents
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Create multiple directories at once:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;mkdir &lt;/span&gt;photos videos music
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Create a directory with spaces in the name:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;mkdir&lt;/span&gt; &lt;span class="s2"&gt;"My Projects"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Viewing and editing file contents: cat, less, nano
&lt;/h4&gt;

&lt;h5&gt;
  
  
  cat
&lt;/h5&gt;

&lt;p&gt;The &lt;strong&gt;'cat'&lt;/strong&gt; command is a versatile utility in Unix-like operating systems. The 'cat' stands for &lt;strong&gt;"concatenate"&lt;/strong&gt;, which hints at its core functionality. And it's commonly used to display the contents of a file on the terminal. &lt;/p&gt;

&lt;p&gt;The Basic syntax looks like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;cat&lt;/span&gt; &lt;span class="o"&gt;[&lt;/span&gt;options] &lt;span class="o"&gt;[&lt;/span&gt;file&lt;span class="o"&gt;(&lt;/span&gt;s&lt;span class="o"&gt;)]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The key functions of &lt;strong&gt;'cat'&lt;/strong&gt; is like: display file contents, concatenate multiple files, create new files, and append content to existing files &lt;/p&gt;

&lt;p&gt;for example, here are some of the examples of 'cat' &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;a) View a file's contents&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;cat &lt;/span&gt;myfile.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;b) Display contents of multiple files&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;cat &lt;/span&gt;file1.txt file2.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;c) Create a new file with content&lt;/strong&gt; (You can then type content and press Ctrl+D to save and exit)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;cat&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; newfile.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;d) Append content to an existing file&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;cat&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt; existingfile.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;e) Display file with line numbers:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;cat&lt;/span&gt; &lt;span class="nt"&gt;-n&lt;/span&gt; myfile.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  less
&lt;/h5&gt;

&lt;p&gt;The 'less' command is &lt;strong&gt;another utility for viewing file contents in Unix-like operating systems, but it offers more advanced features&lt;/strong&gt; compared to &lt;strong&gt;'cat'&lt;/strong&gt;. &lt;strong&gt;'less'&lt;/strong&gt; is a pager program that allows you to view the contents of a file one screen at a time. &lt;/p&gt;

&lt;p&gt;Here are some of the examples &lt;/p&gt;

&lt;p&gt;Viewing a File:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;less filename.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command opens filename.txt in less mode, allowing to navigate through the file using keyboard shortcuts. &lt;/p&gt;

&lt;p&gt;if you want to view multiple files, you can use it like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;less file1.txt file2.txt file3.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This allows you to view multiple files in sequence. Press &lt;strong&gt;':n'&lt;/strong&gt; to move to the next file and &lt;strong&gt;':p'&lt;/strong&gt; to go to the previous file. &lt;/p&gt;

&lt;p&gt;if you want to view compressed files,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;less file.gz
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;'less' can directly read compressed files without needing to decompress them first.&lt;/p&gt;

&lt;p&gt;you can also display line numbers such as using like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;less &lt;span class="nt"&gt;-N&lt;/span&gt; filename.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This shows line numbers alongside the content.&lt;/p&gt;

&lt;p&gt;If you want to start at a specific line, you can try like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;less +100 filename.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This highlights all occurrences of "search term" in the file.&lt;/p&gt;

&lt;p&gt;Read from standard input&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;command&lt;/span&gt; | less
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This allows you to pipe the output of another command into 'less' for easier viewing.&lt;/p&gt;

&lt;h5&gt;
  
  
  nano
&lt;/h5&gt;

&lt;p&gt;The 'nano' command is a simple, user-friendly text editor for Unix-like operating systems. It's often considered easier to use than more complex editors like vim or emacs, making it a good choice for beginners or for quick edits. &lt;/p&gt;

&lt;p&gt;Here's an overview of the 'nano' command. The basic usage is look like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;nano filename.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This opens the file 'filename.txt' in the nano editor. If the file doesn't exist, nano will create it. &lt;/p&gt;

</description>
    </item>
    <item>
      <title>Transformer Deep Dive</title>
      <dc:creator>sangjun_park</dc:creator>
      <pubDate>Fri, 06 Sep 2024 07:58:20 +0000</pubDate>
      <link>https://dev.to/bullmouse/transfomer-deep-dive-2ib9</link>
      <guid>https://dev.to/bullmouse/transfomer-deep-dive-2ib9</guid>
      <description>&lt;h2&gt;
  
  
  1. Introduction
&lt;/h2&gt;

&lt;p&gt;Transformers have become one of the most important concepts in Natural Language Processing (NLP), emerging as a response to key limitations in existing approaches. The architecture addresses several challenges faced by earlier models like Recurrent Neural Networks (RNNs) and Long Short-Term Memory (LSTM) networks:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Sequential processing bottleneck:&lt;/strong&gt; RNNs and LSTMs process input sequences one element at a time, limiting their efficiency. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Long-range dependencies:&lt;/strong&gt; These earlier models struggled to capture relationships between distant elements in a sequence. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Attention mechanism potential:&lt;/strong&gt; Previous research showed that attention mechanisms could improve sequence modeling. Transformers explored whether attention alone could replace recurrent structures.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Training efficiency:&lt;/strong&gt; The Transformer architecture enables faster and more efficient training on large datasets compared to its predecessors.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By tackling these issues, Transformers revolutionized NLP tasks, offering improved performance and scalability.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Main Concept of Transformer
&lt;/h2&gt;

&lt;h3&gt;
  
  
  2-1. Attention Mechanism
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftwy4fs9xzpee2jsu2xcq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftwy4fs9xzpee2jsu2xcq.png" alt="Attention Mechanism" width="436" height="226"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The attention mechanism in Transformers is inspired by human cognitive processes. Just as humans focus on specific, relevant parts of information when processing complex input, the attention mechanism allows the model to do something similar: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;1. selective focus:&lt;/strong&gt; It enables the model to "pay attention" to certain parts of the input sequence more than others &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;2. Importance weighting:&lt;/strong&gt; The mechanism assigns different weights to different parts of the input, emphasizing more relevant or important information. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;3. Context-dependent processing:&lt;/strong&gt; Unlike fixed weighting, the importance of each part can change based on the current context or task &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;4. Efficient information extraction:&lt;/strong&gt; This selective focus helps the model efficiently extract and utilize the most relevant information from the entire input sequence. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;5. Improved handling of long-range dependencies:&lt;/strong&gt; By directly connecting different positions in the sequence, attention helps capture relationships between distant elements more effectively than sequential processing. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  2-1-1. Self-Attention
&lt;/h4&gt;

&lt;p&gt;Self-attention is a mechanism that allows a model to focus on different parts of an input sequence when processing each element of that same sequence. &lt;strong&gt;The key distinction between conventional attention and self-attention lies in the reference point.&lt;/strong&gt; In self-attention, each element in the sequence attends to every other element within the same sequence. This means that the input and the reference sequence are identical, which is the defining characteristic of self-attention. &lt;/p&gt;

&lt;p&gt;Then why we need self-attention over normal attention? There are several reasons why we are using self attention. &lt;/p&gt;

&lt;p&gt;First reason is &lt;strong&gt;capturing intra-sequence dependencies.&lt;/strong&gt; Self-attention allows each element to directly interact with every other element in the sequence. This helps in capturing long-range dependencies within the input. which is crucial for understanding context in language. &lt;/p&gt;

&lt;p&gt;The second reason for using self-attention is its ability to enable &lt;strong&gt;parallelization&lt;/strong&gt;. Unlike RNNs, self-attention can be computed for all elements in parallel, which significantly improves computational efficiency. While there are other forms of attention, such as cross-attention used in encoder-decoder architectures, self-attention offers unique advantages. In cross-attention, it's possible to calculate the relevance between encoder states and decoder states. However, the encoder-decoder model tends to operate more sequentially rather than in parallel. Self-attention, by contrast, allows for parallel processing within a single sequence, making it particularly well-suited for modern, high-performance computing architectures. &lt;/p&gt;

&lt;p&gt;Also, There are no sequential bottleneck in self-attention. Normal attention in seq2seq models often relies on sequential processing of inputs. However, self-attention removes this bottleneck, allowing for more efficient processing of long sequences.&lt;/p&gt;

&lt;h4&gt;
  
  
  2-1-2. Multi-Head Attention
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flkert1ygb5yr7pyhlmsi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flkert1ygb5yr7pyhlmsi.png" alt="Multi-Head Attention" width="576" height="746"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Next, we'll be looking for multi-head attention and why we need this mechanism. Multi-head attention &lt;strong&gt;extends the idea of single-head attention by running multiple attention heads in parallel on the same input sequence.&lt;/strong&gt; This allows the model to learn different types of relationships and patterns within the input data simultaneously, thereby considerably enhancing the expressive power of the model as compared to using just a single attention head. &lt;/p&gt;

&lt;p&gt;Multi-head attention enhances the normal attention mechanism by &lt;strong&gt;utilizing multiple sets&lt;/strong&gt; of learnable Query (Q), Key (K), and Value (V) matrices instead of a single set. This approach offers two key advantages. Firstly, it &lt;strong&gt;enables parallel processing,&lt;/strong&gt; potentially increasing computational speed compared to normal attention. Secondly, &lt;strong&gt;it allows the model to simultaneously focus on different aspects of the input.&lt;/strong&gt; By creating several sets of Q, K, and V matrices, multi-head attention can capture various facets of the input in parallel, facilitating the learning of diverse features and relationships within the data. This capability typically results in improved model performance, particularly for complex tasks such as machine translation. While multi-head attention does require more computational resources, the enhanced results it produces often justify this additional cost.&lt;/p&gt;

&lt;h3&gt;
  
  
  2-2. Positional Encoding
&lt;/h3&gt;

&lt;p&gt;It's true that the Transformer model can process input in parallel, making it faster than sequential models like RNNs or LSTMs. However, this parallel processing means the Transformer can't inherently capture the sequence of words. To address this, we need to add positional information separately. Word position is crucial because changing the order of words can alter the sentence's meaning. &lt;/p&gt;

&lt;p&gt;When applying positional encoding, we must consider two key factors. First, each position should have a unique identifier that remains consistent regardless of the sequence length or input. This ensures the positional embedding works identically even if the sequence changes. Second, we must be careful not to make the positional values too large, as this could overshadow the semantic or syntactic information, hindering effective training in the attention layer.  &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc5w7yudsiq5d92r2crb0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc5w7yudsiq5d92r2crb0.png" alt="Sine &amp;amp; Cosine Functions" width="721" height="268"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A technique that addresses the factors mentioned earlier is the use of &lt;strong&gt;Sine &amp;amp; Cosine Functions&lt;/strong&gt; for positional encoding. This approach offers several advantages. Firstly, sine and cosine functions always maintain values between -1 and 1, ensuring that the positional encoding doesn't overshadow the input embeddings. While sigmoid functions also satisfy this constraint, they're less suitable because the gap between values for adjacent positions can become extremely small. &lt;/p&gt;

&lt;p&gt;Some might worry that different positions could yield identical values. However, this concern is mitigated by using multiple sine and cosine functions of different frequencies to create a vector representation for each position. By increasing the frequency of these functions, we can create more varied encodings, making it highly unlikely for different positions to have the same representation. &lt;/p&gt;

&lt;p&gt;The equation to represent different frequencies depends on position and dimension looks like this. The &lt;strong&gt;i&lt;/strong&gt; means position, and &lt;strong&gt;d&lt;/strong&gt; means the number of dimensions.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbboyorcbtpiqcrkwr0aq.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbboyorcbtpiqcrkwr0aq.jpeg" alt="Sine &amp;amp; Cosine Equation" width="800" height="357"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  2-3. Encoder-Decoder
&lt;/h3&gt;

&lt;p&gt;The Transformer architecture consists of two main components: the Encoder and Decoder. &lt;/p&gt;

&lt;h4&gt;
  
  
  2-3-1. Encoder
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7q6ggerkvwb9flf866zu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7q6ggerkvwb9flf866zu.png" alt="Encoder" width="328" height="399"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The encoder processes the input sequence, which is composed of multiple identical layers. Each layer has two sub-layers. The first sub-layer is the Multi-Head Attention mechanism. After this mechanism, the second sub-layer, a feedforward neural network, is applied sequentially. Both the multi-head self-attention and feedforward neural network are followed by a residual connection and layer normalization. The entire process within each encoder layer looks like this: &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Input → Multi-head Self-Attention → Add &amp;amp; Norm → Feedforward NN → Add &amp;amp; Norm → Output&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This entire process is then repeated for each subsequent encoder layer in the stack. And, I'll discuss in detail about an Add(Residual Connection) &amp;amp; Norm(Layer Normalization) in detail.&lt;/p&gt;

&lt;h5&gt;
  
  
  2-3-1-1. Residual Connections
&lt;/h5&gt;

&lt;p&gt;Residual connections, also known as "skip connections" or "shortcut connections", serve to preserve information flow in neural networks. These connections allow unmodified input information to pass directly through the network, helping to retain important features from the original input that might otherwise be lost through multiple-layer transformations. Crucially, this approach helps mitigate the difficulty of learning in deep neural networks by providing a direct path for information and gradients to flow.&lt;/p&gt;

&lt;h5&gt;
  
  
  2-3-1-2. Layer Normalization
&lt;/h5&gt;

&lt;p&gt;Layer normalization is applied in the "Add &amp;amp; Norm" step of Transformers to stabilize learning, reduce training time, and decrease dependence on careful initialization. It works by Calculating mean and variance across the last dimension which is also called the feature dimension. And then normalizing the input using these statistics. Finally, it scales and shifts the result with learnable parameters. This process helps maintain consistent value scales throughout the network. allowing each layer to learn more effectively and independently. &lt;/p&gt;

&lt;h4&gt;
  
  
  2-3-2. Decoder
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8y0n2mvj1h8s2806f4zq.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8y0n2mvj1h8s2806f4zq.jpg" alt="Transformer Decoder" width="296" height="863"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The Transformer's decoder generates the output sequence, differing from the encoder in key aspects. It operates sequentially rather than in parallel, employs both self-attention and cross-attention mechanisms, and uses masked self-attention to preserve the autoregressive property. The decoder maintains a causal dependency on previous outputs and includes an additional output projection layer. These distinctions enable the decoder to produce coherent outputs based on the encoded input.&lt;/p&gt;

&lt;h5&gt;
  
  
  2-3-2-1. Masked Multi-Head Attention
&lt;/h5&gt;

&lt;p&gt;The first thing we want to discuss in the decoder is &lt;strong&gt;Masked Multi-Head Attention&lt;/strong&gt;. This structure is primarily to maintain the autoregressive property during training and inference. The decoder generates output tokens once at a time, from left to right. Each token should only depend on previously generated tokens. Also, the model can only attend to previous tokens in the sequence, not the future ones. This approach allows the model to be trained in a way that mimics the inference process, where future tokens are unknown. and it also allows parallel computation during training.&lt;/p&gt;

&lt;h5&gt;
  
  
  2-3-2-2. Multi-Head Attention for Decoder
&lt;/h5&gt;

&lt;p&gt;In the Transformer architecture, the interaction between the encoder and decoder is facilitated by a critical mechanism known as cross-attention. This process utilizes queries derived from the decoder and key-value pairs obtained from the encoder, serving as a vital link between the two components. The queries, originating from the current decoder layer, represent the specific information the decoder seeks at each step of the output generation. Conversely, the keys and values, products of the encoder's processing, encapsulate the essence of the input sequence. &lt;/p&gt;

&lt;p&gt;This intricate interplay allows the decoder to align its output generation with the most relevant elements of the input. By doing so, it captures and leverages the context from the entire input sequence, rather than being limited to a narrow window of information. The beauty of this mechanism lies in its dynamic nature; for each output token being generated, the decoder can shift its focus to different parts of the input, ensuring that the most pertinent information is always at the forefront of the generation process.&lt;br&gt;
Essentially, this attention mechanism acts as a sophisticated bridge between the input—the source sequence meticulously processed by the encoder—and the output, which the decoder generates one token at a time. This bridging effect is crucial in enabling the Transformer to perform complex tasks such as translation, summarization, or question-answering with remarkable accuracy and contextual awareness. It allows the model to maintain a nuanced understanding of the input throughout the entire generation process, ensuring that each output token is produced with consideration of the full context provided by the input sequence.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. Conclusion
&lt;/h2&gt;

&lt;p&gt;The Transformer architecture represents a significant leap forward in natural language processing, addressing key limitations of previous models like RNNs and LSTMs. Its core innovations – the self-attention mechanism, multi-head attention, and positional encoding – have revolutionized how machines process and understand language. &lt;/p&gt;

&lt;p&gt;These innovations have not only improved performance on various NLP tasks but have also paved the way for larger, more powerful language models. The Transformer's scalability and efficiency have become the foundation for models like BERT, GPT, and their successors, driving rapid advancements in the field.&lt;/p&gt;

&lt;p&gt;As NLP continues to evolve, the principles introduced by the Transformer architecture remain central to cutting-edge research and applications, underscoring its lasting impact on the field of artificial intelligence.&lt;/p&gt;

&lt;h2&gt;
  
  
  Reference
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://en.wikipedia.org/wiki/Attention_(machine_learning)" rel="noopener noreferrer"&gt;https://en.wikipedia.org/wiki/Attention_(machine_learning)&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Transformer_(deep_learning_architecture)" rel="noopener noreferrer"&gt;https://en.wikipedia.org/wiki/Transformer_(deep_learning_architecture)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://aiml.com/what-is-multi-head-attention-and-how-does-it-improve-model-performance-over-single-attention-head/" rel="noopener noreferrer"&gt;https://aiml.com/what-is-multi-head-attention-and-how-does-it-improve-model-performance-over-single-attention-head/&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a href="https://voidism.github.io/notes/2020/01/26/What-has-the-positional-embedding-learned/" rel="noopener noreferrer"&gt;https://voidism.github.io/notes/2020/01/26/What-has-the-positional-embedding-learned/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    <item>
      <title>Exploring Sequence Transformation Models in NLP: An Overview of Seq2Seq, RNN, LSTM, and GRU</title>
      <dc:creator>sangjun_park</dc:creator>
      <pubDate>Fri, 30 Aug 2024 08:48:24 +0000</pubDate>
      <link>https://dev.to/bullmouse/two-types-of-visualize-embedding-pca-and-t-sne-5ang</link>
      <guid>https://dev.to/bullmouse/two-types-of-visualize-embedding-pca-and-t-sne-5ang</guid>
      <description>&lt;h2&gt;
  
  
  1. Introduction
&lt;/h2&gt;

&lt;p&gt;In mathematics, a sequence transformation is an operator acting on a given space of sequences (a sequence space). Sequence transformations include linear mappings such as convolution with another sequence and resummation of a sequence, and more generally, are commonly used for series acceleration. &lt;/p&gt;

&lt;p&gt;I’ll discuss four types of sequence transformation models: Seq2Seq, RNN, LSTM, and GRU, and how they are constructed.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Seq2Seq
&lt;/h2&gt;

&lt;p&gt;The Seq2Seq model is a type of machine learning approach used in NLP. It can be applied to various tasks, including language translation, image captioning, conversational models, and text summarization. Seq2Seq works by transforming one sequence into another, enabling these diverse applications.  &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn5xqo0knzkiqbzj3yl11.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn5xqo0knzkiqbzj3yl11.png" alt="Encoder Example" width="800" height="224"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There are three kinds of architecture in the Seq2Seq model. The first one is an &lt;strong&gt;'Encoder'&lt;/strong&gt;. The encoder is responsible for processing the input sequence and capturing its essential information, which is stored as the hidden state of the network and in a model with an attention mechanism, a context vector. The context vector is the weighted sum of the input hidden states and is generated for every time instance in the output sequences. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmbtrk0i5kdsu8kescy8x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmbtrk0i5kdsu8kescy8x.png" alt="Decoder Example" width="800" height="343"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;decoder&lt;/strong&gt; takes the context vector and hidden states from the encoder to generate the final output sequence. It operates in an autoregressive manner, producing one element of the output sequence at a time. &lt;/p&gt;

&lt;p&gt;At each step, it considers the previously generated elements, the context vector, and the input sequence information to predict the next element in the sequence. &lt;/p&gt;

&lt;p&gt;In models with an attention mechanism, the context vector and hidden state are combined into an attention vector, which serves as input to the decoder. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5ytd1qsrxrf3a4letxez.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5ytd1qsrxrf3a4letxez.png" alt="Seq2Seq Model: Attention" width="800" height="434"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Finally, we'll be looking for the &lt;strong&gt;Attention&lt;/strong&gt; mechanism. In the basic Seq2Seq architecture, there are some limitations where a longer input sequence results in the hidden state output of the encoder becoming irrelevant to the decoder.  &lt;/p&gt;

&lt;p&gt;It enables the model to &lt;strong&gt;selectively focus&lt;/strong&gt; on different parts of the input sequence during the decoding process. At each decoder step, an alignment model calculates the attention to hidden vectors as input. An alignment model is another neural network model that is trained jointly with the seq2seq model used to calculate how well an input, represented by the hidden state, matches with the previous output, represented by the attention hidden state.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. RNN
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Recurrent neural networks(RNNs)&lt;/strong&gt; are a class of artificial neural networks for sequential data processing. &lt;/p&gt;

&lt;p&gt;RNNs process data across multiple time steps, making them well-adapted for modeling and processing text, speech, and time series. &lt;/p&gt;

&lt;p&gt;The fundamental building block of an RNN is the recurrent unit. This unit maintains a hidden state, essentially a form of memory, which is updated at each step based on the current input and the previous hidden state.   &lt;/p&gt;

&lt;h3&gt;
  
  
  3-1. Configuration of RNN
&lt;/h3&gt;

&lt;p&gt;An RNN-based model can be factored into two parts: Configuration and Architecture. Multiple RNNs can be combined in a data flow, and the data flow itself is the configuration. Each RNN itself may have any architecture, including LSTM, GRU, etc. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgb6er7t8dza06trmiiih.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgb6er7t8dza06trmiiih.png" alt="Standard RNN" width="682" height="225"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Standard
&lt;/h4&gt;

&lt;p&gt;RNN comes in many variants. A definition of RNN is something like the image below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F35mfv5qc0kvod8ank42l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F35mfv5qc0kvod8ank42l.png" alt="RNN standard equation" width="800" height="317"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In other words, it is a neural network that &lt;strong&gt;maps an input x_t into an output y_t with the hidden vector h_t&lt;/strong&gt; playing the role of "memory", a partial record of all previous input-output pairs. At each step, it transforms input to output and modifies its "memory" to help it to better perform future processing.&lt;/p&gt;

&lt;h4&gt;
  
  
  Stacked RNN
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6mbyrfi24x8sv7cvdwse.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6mbyrfi24x8sv7cvdwse.png" alt="Stacked RNN" width="800" height="392"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A stacked RNN, or deep RNN, is composed of multiple RNNs stacked one above the other. Abstractly, it is structured as follows&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6ytonm13utpbqwpfxtah.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6ytonm13utpbqwpfxtah.jpeg" alt="Stacked RNN Equation" width="800" height="786"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;and each layer operates as a stand-alone RNN, and each layer's output sequence is used as the input sequence to the layer above. There is no conceptual limit to the depth of the RNN.&lt;/p&gt;

&lt;h4&gt;
  
  
  Bi-directional
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2z3tkngx69ew0ayiypnp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2z3tkngx69ew0ayiypnp.png" alt="Bi-directional" width="640" height="314"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A bi-directional RNN is composed of two RNNs, one processing the input sequence in one direction, and another in the opposite direction. Abstractly, it is structured as follows: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnyawtgaxk2n8bgc229kw.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnyawtgaxk2n8bgc229kw.jpeg" alt="Bi-directional RNN equation" width="800" height="584"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Bidirectional RNN allows the model to process a token both in the context of what came before it and what came after it. By stacking multiple bidirectional RNNs together, the model can process a token increasingly contextually. &lt;/p&gt;

&lt;h3&gt;
  
  
  3-2. Architecture of RNN
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Fully recurrent
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fagi7idsyv7lcsww35wl5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fagi7idsyv7lcsww35wl5.png" alt="Fully recurrent model" width="420" height="481"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Fully recurrent neural networks (FRNN) connect the outputs of all neurons to the inputs of all neurons. In other words, it is a fully connected network. This is the most general neural network topology because all other topologies can be represented by setting some connection weights to zero to simulate the lack of connections between those neurons.&lt;/p&gt;

&lt;h4&gt;
  
  
  Hopfield
&lt;/h4&gt;

&lt;p&gt;The Hopfield network is an RNN in which all connections across layers are equally sized. It requires stationary inputs and is thus not a general RNN, as it does not process sequences of patterns. However, it guarantees that it will converge. &lt;/p&gt;

&lt;h4&gt;
  
  
  Elman networks and Jordan networks
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzopbnzu69a46ifm9ycd6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzopbnzu69a46ifm9ycd6.png" alt="Elman networks and Jordan networks" width="673" height="745"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;An Elman network is a three-layer network (arranged horizontally as x, y, and z in the illustration) with the addition of a set of context units (u in the illustration). The middle (hidden) layer is connected to these context units fixed with a weight of one. &lt;/p&gt;

&lt;p&gt;At each time step, the input is fed forward and a learning rule is applied. The fixed back-connections save a copy of the previous values of the hidden units in the context units (since they propagate over the connections before the learning rule is applied). Thus the network can maintain a sort of state, allowing it to perform tasks such as sequence prediction that are beyond the power of standard multilayer perceptron. &lt;/p&gt;

&lt;p&gt;Jordan networks are similar to Elman networks. The context units are fed from the output layer instead of the hidden layer. The context units in a Jordan network are also called the state layer. They have a recurrent connection to themselves. &lt;/p&gt;

&lt;p&gt;Elman and Jordan's networks are also known as "Simple recurrent networks (SRN)" &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs115gsyh2x14xrfvikyc.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs115gsyh2x14xrfvikyc.jpeg" alt="Elman &amp;amp; Jordan" width="800" height="586"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;x&lt;/strong&gt;: input vector &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;h&lt;/strong&gt;: hidden layer vector &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;y&lt;/strong&gt;: output vector &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;W, U and b&lt;/strong&gt;: parameter matrices and vector &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;sigma-h and sigma-y&lt;/strong&gt;: Activation functions&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  4. LSTM
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F61a5jwgch842m74xe2s7.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F61a5jwgch842m74xe2s7.jpeg" alt="LSTM" width="800" height="412"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Long short-term memory (LSTM)&lt;/strong&gt; is a type of recurrent neural network (RNN) aimed at dealing with the vanishing gradient problem present in traditional RNNS. Its relative insensitivity to gap length is its advantage over other RNNS. It aims to provide a short-term memory for RNN that can last thousands of timesteps, thus "long short-term memory". The name is made in analogy with long-term memory and short-term memory and their relationship, studied by cognitive psychologists since the early 20th century.  &lt;/p&gt;

&lt;p&gt;A common LSTM unit is composed of a &lt;strong&gt;cell&lt;/strong&gt;, an &lt;strong&gt;input gate&lt;/strong&gt;, an &lt;strong&gt;output gate&lt;/strong&gt;, and a &lt;strong&gt;forget gate&lt;/strong&gt;. The cell remembers values over arbitrary time intervals and the three gates regulate the flow of information into and out of the cell.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Forget gates:&lt;/strong&gt; Decide what information to discard from the previous state by mapping the previous state and the current input to a value between 0 and 1. A rounded value of 1 means to keep the information, and a value of 0 means to discard it. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Input gates:&lt;/strong&gt; decide which pieces of new information to store in the current cell state, using the same system as forget gates. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Output gates:&lt;/strong&gt; control which pieces of information in the current cell state to output by assigning a value from 0 to 1 to the information, considering the previous and current states. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Selectively outputting relevant information from the current state allows the LSTM network to maintain useful, long-term dependencies to make predictions, both in current and future time steps. &lt;/p&gt;

&lt;h2&gt;
  
  
  5. GRU
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fon3tczp4xi01hhahtmkz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fon3tczp4xi01hhahtmkz.png" alt="GRU" width="640" height="285"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gated recurrent unit (GRU)&lt;/strong&gt; was designed as a simplification of LSTM. They are used in the full form and several further simplified variants. They have fewer parameters than LSTM, as they lack an output gate.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. Conclusion
&lt;/h2&gt;

&lt;p&gt;In this article, we explored four different types of sequence transformation models: Seq2Seq, RNN, LSTM, and GRU. Each of these models has its unique strengths and applications in the field of natural language processing (NLP) and other domains involving sequential data. &lt;/p&gt;

&lt;p&gt;Choosing the right model depends on the specific task at hand. For tasks requiring long-term dependencies, LSTMs, and GRUs may be more appropriate, while Seq2Seq models excel in tasks that involve mapping one sequence to another, particularly when enhanced with attention mechanisms.&lt;/p&gt;

&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://en.wikipedia.org/wiki/Seq2seq" rel="noopener noreferrer"&gt;https://en.wikipedia.org/wiki/Seq2seq&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;
&lt;a href="https://en.wikipedia.org/wiki/Sequence_transformation" rel="noopener noreferrer"&gt;https://en.wikipedia.org/wiki/Sequence_transformation&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Recurrent_neural_network" rel="noopener noreferrer"&gt;https://en.wikipedia.org/wiki/Recurrent_neural_network&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    <item>
      <title>Data Visualization: How the Skewness and Kurtosis Lead Visual Distortion</title>
      <dc:creator>sangjun_park</dc:creator>
      <pubDate>Fri, 23 Aug 2024 09:51:09 +0000</pubDate>
      <link>https://dev.to/bullmouse/data-visualization-how-the-skewness-and-kurtosis-lead-visual-distortion-4fco</link>
      <guid>https://dev.to/bullmouse/data-visualization-how-the-skewness-and-kurtosis-lead-visual-distortion-4fco</guid>
      <description>&lt;h2&gt;
  
  
  1. Introduction
&lt;/h2&gt;

&lt;p&gt;Data Visualization is one of the most important parts of modern society. So, it is also important to clearly show data distribution and how to show it without distortion. However, In some cases, data visualizations are distorted to mislead people intentionally. There are lots of cases to explain about this problem. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmhtolty1xdbilbq2mem3.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmhtolty1xdbilbq2mem3.jpeg" alt="Image description" width="800" height="451"&gt;&lt;/a&gt;&lt;br&gt;
￼&lt;br&gt;
This image is an example of how data can be intentionally misleading. Tim Cook presented a graph of cumulative iPhone sales, which at first glance may not seem distorted, especially since the title clearly states “Cumulative iPhone Sales.” However, the graph inherently shows an upward trend due to the nature of cumulative data, which can create a misleading impression of continuous growth, regardless of the actual sales rate. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvw8batfdg5te74cgjkvn.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvw8batfdg5te74cgjkvn.jpeg" alt="Image description" width="800" height="422"&gt;&lt;/a&gt;&lt;br&gt;
￼&lt;br&gt;
This graph reveals declining iPhone sales, but it’s difficult to discern this from the graph that Tim Cook presented. As illustrated in this case, data is sometimes selectively presented to create a more favorable impression, leading others to interpret it in a way that benefits the presenter.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2et116ksdt5qt554rvdd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2et116ksdt5qt554rvdd.png" alt="Image description" width="663" height="370"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here are some other examples that can lead to misleading judgments. Jason E. Chaffetz, a former U.S. representative for Utah’s 3rd congressional district, presented a graph suggesting that there are more abortions than cancer screening and prevention services. However, this graph is highly distorted because it doesn’t accurately reflect the absolute figures. According to Chaffetz’s version, there were 327,000 abortions in 2013, while cancer screenings numbered 935,573—nearly three times the number of abortions. As a result, the graph presented in the “Honest Version” is much more accurate than Chaffetz’s version. &lt;/p&gt;

&lt;h2&gt;
  
  
  2. Definition
&lt;/h2&gt;

&lt;p&gt;Now, I'll discuss about the definition of 'Skewness', and 'Kurtosis'. And why these two things can distort data.&lt;/p&gt;

&lt;h3&gt;
  
  
  2.1. Skewness
&lt;/h3&gt;

&lt;p&gt;Skewness is a statistical measure that describes the asymmetry of a distribution around its mean. In other words, it indicates whether the data points in a dataset are distributed evenly on both sides of the mean or if they tend to cluster more on one side.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj835kg9d5gxyqvr3sug0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj835kg9d5gxyqvr3sug0.png" alt="Image description" width="446" height="159"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;There are two types of skewness to consider. The first is ‘Negative Skew (Left Skew),’ where the distribution is negatively skewed when the tail on the left side (lower values) is longer or fatter than the right side. In this case, most data points cluster on the right side of the distribution, with fewer smaller values extending the tail to the left. The second type is ‘Positive Skew (Right Skew),’ which is essentially the opposite. Here, most data points cluster on the left side of the distribution, with fewer larger values extending the tail to the right.&lt;/p&gt;

&lt;h3&gt;
  
  
  2.2. Kurtosis
&lt;/h3&gt;

&lt;p&gt;Kurtosis is a statistical measure that describes the "tailedness" or the shape of a distribution's tails about its overall shape, particularly compared to a normal distribution. It provides insight into the extremity of deviations (outliers) in a dataset. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flzykatdh9prlfo8y0zfu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flzykatdh9prlfo8y0zfu.png" alt="Image description" width="800" height="450"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;This graph illustrates the concept of kurtosis by comparing different types of distributions. It shows three curves representing different levels of kurtosis relative to the normal distribution. &lt;/p&gt;

&lt;p&gt;First, let’s discuss positive kurtosis, also known as leptokurtic. A leptokurtic distribution has a taller and sharper peak than a normal distribution. It exhibits higher peaks and more extreme outliers, indicating that the data is more concentrated around the mean with a greater occurrence of extreme values.&lt;/p&gt;

&lt;p&gt;On the other hand, negative kurtosis, also referred to as platykurtic, is the opposite of leptokurtic. A platykurtic distribution is flatter and broader than a normal distribution, with a lower peak and thinner tails. Distributions with negative kurtosis have fewer outliers and a more even spread of data values, indicating that the data is more evenly distributed with fewer extreme values.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Problem &amp;amp; Solving
&lt;/h2&gt;

&lt;h3&gt;
  
  
  3.1. The Perspective of Skewness
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8twm0bqdks9x5sf68kh7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8twm0bqdks9x5sf68kh7.png" alt="Image description" width="800" height="395"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;This image illustrates how skewness affects the relationship between the mean, median, and mode. In a symmetrical distribution, the mean, median, and mode are nearly the same. However, in a negatively skewed distribution, the mean and median are lower than the mode, which might lead to the misconception that the mean and median are higher than they are. Conversely, in a positively skewed distribution, the mean and median are greater than the mode, with the mean being significantly higher than the median. &lt;/p&gt;

&lt;p&gt;Furthermore, extreme skewness can cause people to focus on the minority of the data rather than the majority. For instance, in a dataset with high positive skewness, most of the data is concentrated on the left side of the histogram, while a long tail extends to the right, representing a few high-value outliers. Conversely, in a dataset with high negative skewness, the histogram shows most of the data concentrated on the right, with a long tail extending to the left. These outliers can complicate decision-making. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fssjpp7p1nkthrzqhxu3o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fssjpp7p1nkthrzqhxu3o.png" alt="Image description" width="591" height="364"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To address this issue, &lt;strong&gt;log transformations or exponential transformations&lt;/strong&gt; can be applied to reduce skewness and minimize distortion. Additionally, providing further context can help ensure a more accurate interpretation of the data. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Log transformation&lt;/strong&gt; is a common technique used to normalize a positively skewed distribution, where the tail extends to the right. The logarithm function compresses large values into a smaller range— for example, log(1000) = 3 while log(10) = 1, reducing the difference between large numbers. At the same time, smaller values are spread out more after the transformation. This effect narrows the distribution, reduces the tail, and results in a more symmetric distribution.  &lt;/p&gt;

&lt;p&gt;Unlike log transformations, which are commonly used to reduce skewness in a distribution, &lt;strong&gt;exponential transformations&lt;/strong&gt; take the opposite approach. Although less common for reducing skewness, exponential transformations can be useful in specific contexts where increasing skewness or spreading out the data more widely is necessary. Therefore, they are generally more applicable when dealing with negatively skewed data.&lt;/p&gt;

&lt;h3&gt;
  
  
  3.2. The Perspective of Kurtosis
&lt;/h3&gt;

&lt;p&gt;Kurtosis, like skewness, can also lead to visual distortions in data. For example, when kurtosis values are very high, the data may appear more extreme or prone to outliers, as the heavy tails suggest a higher frequency of extreme values. This could result in an overestimation of risk or variability in the data.&lt;/p&gt;

&lt;p&gt;On the other hand, low kurtosis can make the data appear more uniform or less extreme, potentially leading to an underestimation of the presence of outliers or variability.&lt;/p&gt;

&lt;p&gt;To prevent misleading conclusions, it’s important to annotate or explain the presence of high or low kurtosis when visualizing data. This helps viewers interpret the data more accurately. Alternatively, outliers that contribute to very high kurtosis can be adjusted or removed, but this process must be approached with caution and a thorough understanding of the impact on the analysis.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Conclusion
&lt;/h2&gt;

&lt;p&gt;It can be easy to lead people in a desired direction by distorting data. Therefore, we must strive to minimize data distortion and provide users with visualizations that convey the most accurate information possible. However, there are times when we unintentionally present information that could lead others to misunderstand. The most notable examples of this are skewness and kurtosis.&lt;/p&gt;

&lt;p&gt;For this reason, we have closely examined how skewness and kurtosis can distort data and explored the methods to prevent such distortions.&lt;/p&gt;

&lt;h3&gt;
  
  
  Reference
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.linkedin.com/pulse/three-keys-clear-honest-data-visualization-part-2-know-kutyn/" rel="noopener noreferrer"&gt;https://www.linkedin.com/pulse/three-keys-clear-honest-data-visualization-part-2-know-kutyn/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.motherjones.com/kevin-drum/2015/09/lying-charts-anti-abortion-edition/" rel="noopener noreferrer"&gt;https://www.motherjones.com/kevin-drum/2015/09/lying-charts-anti-abortion-edition/&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;
&lt;a href="https://en.wikipedia.org/wiki/Jason_Chaffetz" rel="noopener noreferrer"&gt;https://en.wikipedia.org/wiki/Jason_Chaffetz&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;
&lt;a href="https://en.wikipedia.org/wiki/Skewness" rel="noopener noreferrer"&gt;https://en.wikipedia.org/wiki/Skewness&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;
&lt;a href="https://en.wikipedia.org/wiki/Kurtosis" rel="noopener noreferrer"&gt;https://en.wikipedia.org/wiki/Kurtosis&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;
&lt;a href="https://dynamox.net/en/blog/vibration-analysis-metrics-kurtosis-and-skewness" rel="noopener noreferrer"&gt;https://dynamox.net/en/blog/vibration-analysis-metrics-kurtosis-and-skewness&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a href="https://discuss.boardinfinity.com/t/how-to-transform-the-data-to-make-normally-distributed/6716" rel="noopener noreferrer"&gt;https://discuss.boardinfinity.com/t/how-to-transform-the-data-to-make-normally-distributed/6716&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    <item>
      <title>Thinking About Multi-head attention and why we need it</title>
      <dc:creator>sangjun_park</dc:creator>
      <pubDate>Fri, 16 Aug 2024 01:10:22 +0000</pubDate>
      <link>https://dev.to/bullmouse/multi-head-oj3</link>
      <guid>https://dev.to/bullmouse/multi-head-oj3</guid>
      <description>&lt;h2&gt;
  
  
  Transformer Model
&lt;/h2&gt;

&lt;p&gt;Before explaining the concept of Multi-Head Attention, we first need to know about the &lt;strong&gt;Transformer model&lt;/strong&gt;, which is superior to Multi-Head Attention. &lt;/p&gt;

&lt;p&gt;Researchers at Google developed the transformer model and it is proposed in a 2017 paper "Attention is All You Need". The Text is converted to a numerical representation called &lt;strong&gt;tokens&lt;/strong&gt;, and each token is converted into a vector by looking up from a &lt;strong&gt;word embedding table&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;In NLP, the word embedding is a representation of a word. Typically, the representation is a real-valued vector that encodes the meaning of the word in such a way that the words that are closer in the vector space are expected to be similar in meaning. &lt;/p&gt;

&lt;p&gt;The goal of word embedding is to capture the semantic meaning of words. &lt;/p&gt;

&lt;p&gt;Before transformer models, there are several kinds of NLP models such as RNNs, LSTMs, or GRUs. However, these models had several limitations. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Sequential Processing:&lt;/strong&gt; RNNs process tokens in sequence, which makes them slow and difficult to parallelize.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Long-Range Dependencies:&lt;/strong&gt; RNNs struggle to capture dependencies between distant tokens due to the vanishing gradient problem.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Fixed-Length Contexts:&lt;/strong&gt; RNNs generally rely on fixed-length context windows, limiting their ability to handle varying context lengths effectively.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The transformer model addresses these limitations using a &lt;strong&gt;self-attention&lt;/strong&gt; mechanism and fully parallelizable architecture. &lt;/p&gt;

&lt;h2&gt;
  
  
  Self-Attention mechanism
&lt;/h2&gt;

&lt;h3&gt;
  
  
  concept
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Attention:&lt;/strong&gt; In the context of neural networks, it refers to the ability to focus on specific parts of the input sequence when producing each element of the output. It allows the model to weigh the importance of the different words (or tokens) in a sequence relative to each other. In the context of sequence-to-sequence models, attention typically involves focusing on different parts of the encoder's output when generating each word in the decoder's output. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Self-Attention:&lt;/strong&gt; specific type of attention where each word in the sequence attends to every other word, including itself. This helps the model understand the relationships between words in the context of the entire sequence. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The key difference between attention and self-attention lies in the scope of the elements. For example, In the sentence "The cat sat on the mat", self-attention allows the word "cat" to focus on "sat" and "mat" to understand its context better, rather than considering only adjacent words.&lt;/p&gt;

&lt;p&gt;For each word in input sequences, the self-attention mechanism computes three vectors &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Query(Q):&lt;/strong&gt; Represents the word we are currently focusing on. In the Self-Attention mechanism, we make a Query vector based on each word of the input sequence. &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Key(K):&lt;/strong&gt; Represents the words we are comparing against. It compares to the Query vector so that we can calculate how important this word(K) is compared to the target(Q). &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Value(V):&lt;/strong&gt; Contains the actual information of the words. It is calculated by the weight of Attention and used as a final result.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These vectors are not directly generated from the input word embeddings. instead, they are created learnable weight matrices.  &lt;/p&gt;

&lt;p&gt;We multiply between input embedding X and the weight matrix (W_Q, W_K, W_V) to make the vector of Q, K, and V.&lt;/p&gt;

&lt;p&gt;Now we need to Calculate Attention Scores. Q, K, and V vectors are generated from the input embeddings using the respective weight matrices W_Q, W_K, and W_V. &lt;/p&gt;

&lt;p&gt;The attention score for each pair of words is calculated by taking the dot product of the Query vector for one word with the Key vector of another word. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffbzvgnurlnvow6f98gae.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffbzvgnurlnvow6f98gae.png" alt="Image description" width="374" height="52"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Qi:&lt;/strong&gt; the Query vector for the i-th word. &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Kj:&lt;/strong&gt; the Key vector for the j-th word. &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;dot product:&lt;/strong&gt; measures the similarity between the Query and Key vectors, determining how much one word is related to another &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To prevent the dot products from becoming too large and destabilizing the softmax function, the scores are scaled by the square root of the dimension of the Key vectors (dk).  &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh5unffcyzibq9d5cc90t.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh5unffcyzibq9d5cc90t.png" alt="Image description" width="349" height="90"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Finally, we'll apply the &lt;strong&gt;softmax&lt;/strong&gt; function. The scaled attention scores are then passed through a softmax function. The softmax function converts these scores into a probability distribution, where the scores sum to 1. Softmax essentially normalizes the scores, making it easier to interpret them as &lt;strong&gt;attention weights&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm7j4ic3pfjiibacfy0a4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm7j4ic3pfjiibacfy0a4.png" alt="Image description" width="411" height="93"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Generate Output
&lt;/h3&gt;

&lt;p&gt;after calculating attention weights, the next step is to generate the output for the self-attention mechanism. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fudp7kht96ygbnm9n95xq.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fudp7kht96ygbnm9n95xq.jpeg" alt="Image description" width="800" height="91"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;for each value of j from 1 to n, the summation notation means to calculate the expression of Attention Weights and jth of V(Value). &lt;/p&gt;

&lt;h3&gt;
  
  
  Multi-Head Attention Extension
&lt;/h3&gt;

&lt;p&gt;In Multi-Head Attention, each head performs its own self-attention calculation independently, and then the output of all heads is concatenated and then linearly transformed to produce the final output. &lt;/p&gt;

&lt;p&gt;This is the formula for Multi-Head attention extension. &lt;/p&gt;

&lt;p&gt;Let's Imagine that there are h heads, each head produces an output, which we can denote as: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;head 1, head 2, ..., head h &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;and each of these outputs (from head 1 to head h) is a vector of the same dimension, let's say d-k. The idea of concatenation is to take these h vectors and combine them into a single, longer vector. The reason why we are using d-k is because we divide d-model by h.  &lt;/p&gt;

&lt;p&gt;for example, let's suppose there are d-model, which is the dimensionality of the input vectors to the model. For example, if each word in the input sequence is represented by a 512-dimensional vector, then d-model = 512. &lt;/p&gt;

&lt;p&gt;h is the number of attention heads. For example, if you have 8 heads, then h = 8. We need to figure out the dimensions of the head. and it could be calculated by 512 / 8 = 64. and we called this d-k.&lt;/p&gt;

&lt;p&gt;Each head independently processes the input sequence through the Linear Projections and Attention Mechanism.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6h6w7n54un5u7c1eubx4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6h6w7n54un5u7c1eubx4.png" alt="Image description" width="800" height="413"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;This image shows the best example of explaining the concatenation and linearly-transformed.  &lt;/p&gt;

&lt;p&gt;After we apply the linear transformation, it is ready for subsequent layers in the Transformer model. &lt;/p&gt;

&lt;h2&gt;
  
  
  Why do we need Multi-Head Attention?
&lt;/h2&gt;

&lt;p&gt;The primary reasons for using Multi-Head Attention are related to the ability to capture complex patterns, improve model performance, and provide richer, more context-aware representations of the input data. &lt;/p&gt;

&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://en.wikipedia.org/wiki/Transformer_(deep_learning_architecture)" rel="noopener noreferrer"&gt;https://en.wikipedia.org/wiki/Transformer_(deep_learning_architecture)&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.adityaagrawal.net/blog/deep_learning/attention" rel="noopener noreferrer"&gt;https://www.adityaagrawal.net/blog/deep_learning/attention&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    <item>
      <title>Thinking about JavaScript Libraries and Frameworks for User Interface</title>
      <dc:creator>sangjun_park</dc:creator>
      <pubDate>Thu, 19 Jan 2023 01:53:29 +0000</pubDate>
      <link>https://dev.to/bullmouse/thinking-about-javascript-libraries-and-frameworks-for-user-interface-1799</link>
      <guid>https://dev.to/bullmouse/thinking-about-javascript-libraries-and-frameworks-for-user-interface-1799</guid>
      <description>&lt;h2&gt;
  
  
  Before to begin
&lt;/h2&gt;

&lt;p&gt;There are lots of libraries and frameworks in javascript. But I questioned myself. ‘Do I know about the difference between them?’ I was not sure about it. So I decided to discover the history of javascript and why some kind of the libraries or frameworks such as jQuery, React, Vue, Angular, and Svelte was made.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Birth of JavaScript
&lt;/h2&gt;

&lt;p&gt;The creator of JavaScript was Brendan Ike. According to &lt;a href="https://fossbytes.com/who-is-brendan-eich/" rel="noopener noreferrer"&gt;this website,&lt;/a&gt; The reason why he wants to make JavaScript was to validate user input on websites. Nowadays,&lt;a href="https://developer.mozilla.org/ko/docs/Learn/JavaScript/First_steps/What_is_JavaScript" rel="noopener noreferrer"&gt; JavaScript can help complex features inside of web browsers such as interacting with users or renewing something periodically.&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Some people just compare HTML, CSS, and JS to nouns, adjectives, and verbs. I also agree about this opinion. JavaScript could make web browsers more dynamic.&lt;/p&gt;

&lt;h2&gt;
  
  
  jQuery
&lt;/h2&gt;

&lt;h3&gt;
  
  
  jQuery: write less, do more
&lt;/h3&gt;

&lt;p&gt;Then, why jQuery was made? Did VanillaJS doesn’t work properly? I was curious about this question so I searched the jQuery website to find the truth. According to &lt;a href="https://jquery.com/" rel="noopener noreferrer"&gt;this website,&lt;/a&gt; they said jQuery is a fast, small, and feature-rich JavaScript library.&lt;/p&gt;

&lt;p&gt;In 2006, John Resig was a web designer who processed his project. He was frustrated with writing JavaScript because of its difficulty. For example, the compatibility of the browser was difficult to manage. There are some separate codes only for IE(Internet Explorer), Chrome, of Firefox. This compatibility issue makes him frustrated. Not only about just compatibility issues, but also the grammatical things were more simple rather than JavaScript.&lt;/p&gt;

&lt;p&gt;So he made jQuery, the simple and powerful JavaScript library to use. This powerful tool could solve compatibility issues easily. And that makes web developers more productive rather than just using JavaScript.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Weakness of jQuery
&lt;/h3&gt;

&lt;p&gt;However, &lt;a href="https://www.zerocho.com/category/jQuery/post/57b356d4d841141500b31e1e" rel="noopener noreferrer"&gt;one of the problems with using jQuery was the speed.&lt;/a&gt; The speed in jQuery is really slow compared to using only JavaScript. Especially using jQuery to make an animation. Also, &lt;a href="https://www.zerocho.com/category/jQuery/post/57b356d4d841141500b31e1e" rel="noopener noreferrer"&gt;maintaining the code of jQuery is more difficult than just using JavaScript. &lt;/a&gt;Some people might think maintaining jQuery is easier because of its simple code. However, because of that, some people just duplicate the code in jQuery and that makes it more difficult to maintain. This causes jQuery easy to make spaghetti code, which makes maintainability terrible.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why we don’t use jQuery more than before?
&lt;/h3&gt;

&lt;p&gt;First, &lt;a href="https://velog.io/@sy3783/jQuery1.-%EB%8D%94-%EC%9D%B4%EC%83%81-%EC%A0%9C%EC%9D%B4%EC%BF%BC%EB%A6%AC%EB%A5%BC-%EC%82%AC%EC%9A%A9%ED%95%98%EC%A7%80-%EC%95%8A%EB%8A%94-%EC%9D%B4%EC%9C%A0" rel="noopener noreferrer"&gt;the browser compatibility is good enough.&lt;/a&gt; So that makes jQuery not useful rather than before. One of the reasons why jQuery was made was the compatibility issue(especially, the cross-browsing issue). Nowadays, this issue is not as important as before.&lt;/p&gt;

&lt;p&gt;Also, most features in jQuery can be implemented in VanillaJS or TypeScript. However, &lt;a href="https://javascript.plainenglish.io/why-i-decided-to-break-up-with-jquery-d597d4b8c84f" rel="noopener noreferrer"&gt;jQuery is the library that is built over JavaScript with ‘Wrapping’.&lt;/a&gt; And this feature makes it slower than VanillaJS. jQuery is not a library related to optimization.&lt;/p&gt;

&lt;p&gt;And the most important thing is the reason we use not jQuery but some other framework or library is ‘Virtual DOM’, which makes it more powerful to build front-end things.&lt;/p&gt;

&lt;h2&gt;
  
  
  Virtual DOM
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://en.wikipedia.org/wiki/Virtual_DOM" rel="noopener noreferrer"&gt;According to Wikipedia, &lt;/a&gt;a virtual DOM is a lightweight JavaScript representation of the Document Object Model(DOM) used in declarative web frameworks such as React, Vue, and Elm. However, Before doing some research about virtual DOM, I need to know what exactly the ‘DOM’ is.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is DOM?
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction" rel="noopener noreferrer"&gt;‘DOM’ is the data representation of the objects that comprise the structure and content of a document on the web.&lt;/a&gt; It is a kind of programming interface for web documents. and it represents the page so that programs can change the document structure, style, and content&lt;/p&gt;

&lt;p&gt;And we can access this DOM in JavaScript. Not only just for access but also can manipulate using the DOM and scripting languages like JavaScript.&lt;/p&gt;

&lt;p&gt;DOM’s structure is represented by a ‘&lt;a href="https://wit.nts-corp.com/2019/02/14/5522" rel="noopener noreferrer"&gt;Node Tree’.&lt;/a&gt; In this tree, one parent node can get several child nodes. But it doesn’t mean DOM is the same as HTML. DOM is just a valid HTML document interface. During creating DOM, the browser figures out the things that are not correct HTML code. Also, DOM is neither the things that the user can see in the browser. What exactly the user can see is the ‘Render Tree’, which is combined with DOM and CSSOM. ‘display: none’ is one of the most representative things to understand the difference between DOM and Render Tree. It doesn’t render when some elements have ‘display: none’. However, DOM doesn’t care about what the property of CSS is.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why do we need Virtual DOM then?
&lt;/h3&gt;

&lt;p&gt;First of all, DOM is structured by Tree Node. So it is easy for us to understand. &lt;a href="https://doqtqu.tistory.com/316" rel="noopener noreferrer"&gt;But lots of nodes makes DOM slower, and there could be more error when we update DOM. &lt;/a&gt;Furthermore, recent modern app use SPA(Single Page Application), which means only one page is configured for the whole application. Therefore, the source of HTML is quite huge because lots of dynamic features are inside of it. Furthermore, there are also some problems that we need to rerender consistently.&lt;/p&gt;

&lt;p&gt;Some people might think that just rerendering DOM doesn’t take lots of effort. However, the thing when we write this code like this should have happened like this.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;document.getElementById('some-id').innerValue = 'updated value';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;the Browser parses the HTML and figures out where exactly the node has the same ID compared to this code.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;remove the child element which is related to this element.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;update this element to ‘updated value’&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;calculate the CSS about the parent and child nodes.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;finally, it is painted in the display of the browser.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So many things happened during updating the value of the DOM. Entire things have been changed even if it is not necessary, and the browser needs to calculate and update the new layout. C&lt;a href="https://doqtqu.tistory.com/316" rel="noopener noreferrer"&gt;hanging the layout should need a complex algorithm to change. And it also affects performance.&lt;/a&gt; Especially, when it comes to rendering 10 times, the browsers also update the new render tree 10 times. And &lt;a href="https://devlibrary00108.tistory.com/46" rel="noopener noreferrer"&gt;when the size of the DOM is huge, It is quite complex to find which DOM has been changed and should be rerendered.&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So, Here the Virtual DOM comes! 😁&lt;/p&gt;

&lt;p&gt;Virtual DOM is quite lightweight. The concept of virtual DOM is like a concept of abstraction of HTML DOM, &lt;a href="https://devlibrary00108.tistory.com/46" rel="noopener noreferrer"&gt;but it is already an abstract concept so it could be lightweight and also it is separated from the browser’s real DOM.&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Because the virtual DOM didn’t truly rerender in the browser, it is relatively fast compared to the real DOM. After the data update, &lt;a href="https://doqtqu.tistory.com/316" rel="noopener noreferrer"&gt;there are three steps to rerender through the virtual DOM.&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;The entire UI is re-rendered through virtual DOM. This virtual DOM is now current(relatively fast compared to real DOM).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Calculating the difference between the previous virtual DOM(it is equal to the real DOM) and the current virtual DOM.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;After the calculation is completed, DOM only changes the real DOM about the thing that has been changed.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;These 3 steps of the process are called ‘Reconciliation’ in React.&lt;/p&gt;

&lt;h2&gt;
  
  
  Angular: I’ll use Incremental DOM!
&lt;/h2&gt;

&lt;p&gt;From now, I was talking about the virtual DOM. However, virtual DOM is not the only way to solve the problem of the performance of re-rendering. What makes the difference between Incremental DOM and virtual DOM? And why the Angular.js using Incremental DOM?&lt;/p&gt;

&lt;h3&gt;
  
  
  What is Incremental DOM?
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://ui.toast.com/posts/ko_20210819" rel="noopener noreferrer"&gt;Incremental DOM gives us a more simple way of approach than a virtual DOM.&lt;/a&gt; There are no virtual things in memory in incremental DOM. They just use a real DOM to find the difference.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://ui.toast.com/posts/ko_20210819" rel="noopener noreferrer"&gt;Incremental DOM compiles all the components through the chunks of instruction.&lt;/a&gt; This instruction created a DOM tree and find out what the difference is.&lt;/p&gt;

&lt;p&gt;Hmm. Okay. Incremental DOM looks more simple. Because they don’t need to make a virtual DOM. Instead of that, they use a real In-Memory DOM that was used before. Then, what makes the Incremental DOM special?&lt;/p&gt;

&lt;p&gt;Actually. that was the point. &lt;a href="https://ui.toast.com/posts/ko_20210819" rel="noopener noreferrer"&gt;It is more efficient to use memory because we don’t need to make a virtual DOM.&lt;/a&gt; it also means that we don’t need to copy the real DOM to re-render the application UI. So it decreases the usage of memory a lot.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://ui.toast.com/posts/ko_20210819" rel="noopener noreferrer"&gt;Also, There is ‘Tree Shaking’ in Incremental DOM.&lt;/a&gt; Tree Shaking is a kind of stage that removes some code that is not useful during the build process. Therefore, Incremental DOM can remove some instructions that are not used right now by the Components. However, it is impossible to do tree-shaking when some kind of framework or library uses virtual DOM. because virtual DOM is used by an interpreter. But Incremental DOM can do a Tree-Shaking when it comes to compiling the code.&lt;/p&gt;

&lt;h3&gt;
  
  
  So, What’s Better? Incremental DOM or Virtual DOM?
&lt;/h3&gt;

&lt;p&gt;The answer is ‘&lt;a href="https://ui.toast.com/posts/ko_20210819" rel="noopener noreferrer"&gt;It depends&lt;/a&gt;’. There are some trade-offs between incremental DOM and virtual DOM. If some project has a highly important about using memory, then Incremental DOM would be better. However, if speed is more important than memory usage, then virtual DOM would be the better choice.&lt;/p&gt;

&lt;h2&gt;
  
  
  React vs Vue: What’s the difference?
&lt;/h2&gt;

&lt;p&gt;Nowadays(in 2023), React and Vue are the two most popular frameworks or libraries in JavaScript. They both use virtual DOM, and they are both component-based. So you can reuse components in other projects and build more flexible development because of capsulation and ease of expansion.&lt;/p&gt;

&lt;p&gt;Then, What makes React and Vue different?&lt;/p&gt;

&lt;h3&gt;
  
  
  Vue: Single File Component
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://rma7.tistory.com/65" rel="noopener noreferrer"&gt;Vue.js is a framework based on a single file component.&lt;/a&gt; So, they just put HTML, CSS, and JavaScript in only one file which extension is ‘.vue’. This could make the production and maintenance of the project easier, and also it is easy to cooperate with this framework. Vue is also HTML based and they use a ‘template’ which is a kind of grammatical thing in Vue. Many people said it is easy to learn because the grammar in Vue.js is based on HTML.&lt;/p&gt;

&lt;h3&gt;
  
  
  React: Separate Each File
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://erwinousy.medium.com/%EB%82%9C-react%EC%99%80-vue%EC%97%90%EC%84%9C-%EC%99%84%EC%A0%84%ED%9E%88-%EA%B0%99%EC%9D%80-%EC%95%B1%EC%9D%84-%EB%A7%8C%EB%93%A4%EC%97%88%EB%8B%A4-%EC%9D%B4%EA%B2%83%EC%9D%80-%EA%B7%B8-%EC%B0%A8%EC%9D%B4%EC%A0%90%EC%9D%B4%EB%8B%A4-5cffcbfe287f" rel="noopener noreferrer"&gt;Unlike Vue.js, React separate the file into ‘.js’ and ‘.css’&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;There are a lot more differences compared to Vue.js and React.js. Supposed we need to mutate data. In Vue, we must create data objects and then freely update data. Whereas in React, we create the object which is called ‘state’. and also we need more stuff to do if we want to update it.&lt;/p&gt;

&lt;p&gt;In conclusion, Vue looks more strict than react to use, and React looks more flexible than Vue. So, If you want to build a large-scale application, React would be a better choice than Vue. However, Vue seems like easier to learn than React. And also it seems like it is faster to build an application. So If you want to build a small app as fast as possible, then Vue would be a much better choice than react.&lt;/p&gt;

&lt;h2&gt;
  
  
  Binding Methods
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Two-way Data Binding vs One-way Data Binding
&lt;/h3&gt;

&lt;p&gt;One thing that makes react differently compared to Angular and Vue is the ‘Binding Method’. Binding Method is a kind of policy about data interaction between a child component and a parent component. Only Angular uses Two-way Data Binding whereas React, Angular, and Vue all use One-way Data Binding.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://gitnyang.tistory.com/67" rel="noopener noreferrer"&gt;In Two-way Data Binding, data flows each direction.&lt;/a&gt; What I mean is both parent components to child components and vice versa. Model and View watch each other so that if one of them changes its data, then the other one changes it directly. However, because of this, it is more difficult than One-way Data Binding to know which direction the change of data comes from.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://gitnyang.tistory.com/67" rel="noopener noreferrer"&gt;However, In One-Way Data Binding, data only flows in one way.&lt;/a&gt; For example in React, If they manage state, then they use props so that there could be some data flow from the parent component to the child component. So that we can predict the flow of data more clearly. But One-Way Data Binding doesn’t mean that we cannot send data from the child component to the parent component. If the parent component sends the handler function to the child component, and when the event happened in the child component, then the child can change the state through the function that the parent component gives. And this is also called ‘Lifting State Up’.&lt;/p&gt;

&lt;h2&gt;
  
  
  Svelte: Write less
&lt;/h2&gt;

&lt;p&gt;Svelte was born in 2016, and it is an open-source front-end framework. &lt;a href="https://svelte.dev/" rel="noopener noreferrer"&gt;On this website,&lt;/a&gt; we can clearly understand why this framework was born.&lt;/p&gt;

&lt;p&gt;One of the most popular features in Svelte is ‘write less code’. looks quite similar compared to jQuery. We can build boilerplate-free components using languages that we already know such as HTML, CSS, and JavaScript through Svelte. Boilerplate code means the thing that could be reused repeatedly. However, it is quite uncomfortable when someone refactors those things.&lt;/p&gt;

&lt;p&gt;Also, Svelte has ‘No virtual DOM’ compare to React. We already know what is not a good thing when we use a virtual DOM. Unlike React or Vue, Svelte is a kind of compiler whereas virtual DOM is an interpreter. So, the Svelte can interpret the code during build time. And that makes less code. On the other side, React and Vue interprets the code during the run-time.&lt;/p&gt;

&lt;p&gt;And the last thing that makes Svelte more powerful is ‘Truly reactive’. There are no complex state management libraries compared to React. So Svelte can brings reactivity to JavaScript itself.&lt;/p&gt;

&lt;p&gt;However, there are some challenging things to using Svelte as a production stage. &lt;a href="https://blog.logrocket.com/why-people-arent-switching-to-svelte-yet/" rel="noopener noreferrer"&gt;Here&lt;/a&gt; is a good article to read about why people aren’t switching to Svelte yet.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Thank you to read my article. I was born and live in South Korea so my English sometimes looks terrible. If you notice some kind of things that make some trouble such as grammatical errors or incorrect information, please leave a comment below or send mail to me 😌.&lt;/p&gt;

</description>
      <category>indiegames</category>
      <category>gamedev</category>
      <category>discuss</category>
      <category>showdev</category>
    </item>
  </channel>
</rss>
