<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Thirumalai Kumar on Medium]]></title>
        <description><![CDATA[Stories by Thirumalai Kumar on Medium]]></description>
        <link>https://medium.com/@gglrthiru?source=rss-6c58aa90b315------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1-Bq2JAqQyJWa6_vdzo_-g.jpeg</url>
            <title>Stories by Thirumalai Kumar on Medium</title>
            <link>https://medium.com/@gglrthiru?source=rss-6c58aa90b315------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:01:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gglrthiru/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Thinking from first principles POV for Deepseek-R1 series — Deepseek -V2]]></title>
            <link>https://medium.com/@gglrthiru/thinking-from-first-principles-pov-for-deepseek-r1-series-deepseek-v2-90ce4adf9f5e?source=rss-6c58aa90b315------2</link>
            <guid isPermaLink="false">https://medium.com/p/90ce4adf9f5e</guid>
            <category><![CDATA[deepseek-r1]]></category>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[deepseek-v3]]></category>
            <category><![CDATA[deepseek-llm]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Thirumalai Kumar]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 12:05:14 GMT</pubDate>
            <atom:updated>2025-04-13T12:05:14.659Z</atom:updated>
            <content:encoded><![CDATA[<h3>Thinking from first principles POV for Deepseek-R1 series — Deepseek -V2</h3><h4>Introduction</h4><p>Hi folks!!! Welcome to my Deepseek-R1 series, This blog post is continuation of my series which started from Deepseek-V1. This blog post has several prerequisites to continue with:</p><ol><li>Understanding of Deepseek-V1 paper: If you don’t know, please check my previous blog post in this series <a href="https://medium.com/@gglrthiru/thinking-from-first-principles-pov-for-deepseek-r1-series-deepseek-v1-ac949831f0ac">here</a>.</li><li>Basic understanding of what is KV-Cache and how does it work?: Check this blog posts <a href="https://medium.com/@aisagescribe/ace-ai-interview-series-22-understanding-kv-cache-efc418dbc0c0">here</a> and <a href="https://medium.com/@gosshhh9/simple-implementation-of-kv-cache-from-scratch-917813875ece">here</a>. Also check Umar Jamil’s wonderful video on how to develop a KV-cache from scratch <a href="https://www.youtube.com/watch?v=oM4VmoabDAI&amp;t=6701s">here</a>.</li><li>Basic understanding of mixture of experts and how does it work? : Check hugging face’s wonderful post on mixture of experts from Mixtral paper <a href="https://huggingface.co/blog/moe">here</a>.</li></ol><p>If you do not any of the followings, please follow the given links to understand the concepts before diving into this deepseek-v2 blog. This paper has worked on top of these techniques and improved it for their needs.</p><p>Also please be aware that this blog post includes advanced mathematics which might take a week of paperwork to understand intuitively. It took me roughly 2 weeks of time to intuitively understand all the math in this paper.</p><h4>What is this paper about?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQZO0k-wJ5F990EdY_amdw.png" /><figcaption>Architecture of Deepseek-v2</figcaption></figure><p>Deepseek-v2 is a mixture of experts models in the deepseek series. It has 236 billion parameters among which only 21 billion parameters are activated per token. It has a context length of 128k. Thanks to their architectural innovation, this model is both economical in training and faster in inference.</p><p>So, There are 2 major architectural changes in this model:</p><ol><li>Multihead latent attention which improves the speed by compressing the KV-cache solving the long standing problem of KV-Cache size issues in model.</li><li>Instead of a normal MoE like GShard, They created their own variant called DeepseekMoE which speeds up both training and inference.</li></ol><p>Compared to the previous generation Flagship model deepseek-67B, This model Deepseek-v2 consumes 42.5% less GPU hours per trillion token. Also the KV-cache consumption has been reduced by 93.3% and also increased throughput by 5.76 times. The model has been pretrained on 8.1 Trillion tokens. It is then later finetuned by SFT and RL for helpfulness and harmlessness.</p><h4>What is this problem that this paper solves?</h4><p>The LLMs started showing emergent capabilites when it’s number of parameters are increased. This comes with a caveat, It needs large computing resources and has decreased throughput.</p><p>It solves the above mentioned problem by their novel architectural design:</p><ol><li>In the context of attention mechanism, The major problem was KV-cache, The KV-cache grows in size which increases the latency during inference. Multiple attempts were made before to solve this problem but every approach traded performance for speed. Here in this paper, They designed a new approach called <strong>MultiHead Latent Attention.</strong> This MLA achieves the balance between two: performance and speed.</li><li>In the context of FFN, This paper follows their own variant of mixture of experts called Deepseek MoE.</li></ol><p><strong>Are there any changes in the dataset?</strong></p><p>The previous generation of models was trained on 2 Trillion tokens of data in their pretraining stage. Now they constructed a new pretraining dataset with 8.1 trillion tokens. They have added more high quality chinese language to the already existing pretraining data.</p><p>For the finetuning stage, They use their custom made 1.5 million conversational data. This dataset is used in SFT and RL stages.</p><h3>Architecture of Deepseek-v2</h3><p>Deepseek-v2 follows the same architecture of deepseek-67B except 2 changes which are:</p><p>i) Multihead latent attention instead of normal multi head attention.</p><p>ii) DeepseekMoE instead of normal mixture of experts.</p><p>Let’s deepdive into these two architectural changes one-by-one.</p><h4>1. Multi Head Latent Attention</h4><p>The real problem in the context of attention mechanism while scaling up is their KV-cache. The KV-cache size grows so huge and becomes a bottleneck during inference. To solve this problem, multiple attempts were by different people, some notable contributions are: Multi Query attention, Grouped query attention, etc;. But all these contributions traded performance for speed. They did achieve a faster implementation and solved the problem for scaling but they lost the accuracy of MHA.</p><p>The Multi head latent attention(MLA) achieves better performance than MHA and still uses 93.3% less KV-cache.</p><p><strong>Comparison between Multi head attention and Multi head latent attention</strong></p><p>First, we describe how normal multi head attention works and then we go for multi head latent attention to better understand the changes that has been made.</p><blockquote>Abbreviations:</blockquote><blockquote>d =&gt; Embedding dimension</blockquote><blockquote>n_h =&gt; Number of heads</blockquote><blockquote>d_h =&gt; head dimension</blockquote><blockquote>h_t =&gt; t-th token input at an attention layer</blockquote><p>The above given abbreviation dict will grow but for now, This is enough.</p><p>In normal multi head attention, We first divide the embedding dimension <strong>“d”</strong> with the number of heads <strong>“n_h” </strong>to get the head dimension <strong>“d_h”</strong>. Then standard MHA produces <strong>q_t, k_t, v_t </strong>which are query, key and value matrices by multiplying dot products of weight matrices: <strong>W_q, W_k and W_v</strong> with the input <strong>“h_t”.</strong></p><p>Let’s do these matrix multiplication with an example, Assume we are operating on a 1billion parameter model.</p><p>number_of_layers (l) = 24, embedding_dimension (d) = 2048, number_of_heads (n_h) = 64, head_dimension (d_h) = 32, Context_length (c_l) = 512</p><p>Let’s keep the context length smaller for now for better understanding, In real world the context length will be of size 128k or even more than that.</p><blockquote>q_t = W_q * h_t</blockquote><blockquote>k_t = W_k * h_t</blockquote><blockquote>v_t = W_v * h_t</blockquote><p>From above configuration,</p><p>h_t will be of shape (1, 512, 2048)</p><p>W_q will be of shape (1, 512, 2048)</p><p>q_t = W_q * h_t(transpose)</p><p>Now, q_t will be of shape (1, 512, 2048). Similar matrix operations for keys and values leads to k_t and v_t with same shapes (1, 512, 2048). After this, the QKV vectors are divided into their respective number of heads.</p><p>Here, n_h = 64, So now the shape of QKV will be (1, 512, 64, 32) which is then transposed to (1, 64, 512, 32). Now the attention scores are calculated by <strong>(q_t * k_t(transpose))</strong></p><p>The output of attention will be of shapes (1, 64, 512, 512). This attention score is then multiplied with the value vector to get the final output vector which will be of shape (1, 512, 2048).</p><p>Now, let calculate the size of KV-cache in normal multi head attention. The formula to calculate the size of kv cache is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/111/1*CYkXY6-t2qkam5o8frVcdg.png" /></figure><p>From the above equation and configuration of the model, we can find that the size of KV-cache is 98304. So, KV-cache memory per token is 192KB. Now for a context length of 512, The KV-cache memory per token will be 98.304 MB. Now lets check for real world usecase, If the context length is 128000, the kv-cache memory will be 24GB.</p><p>So, Now we know what really is the problem and let’s see how Multihead latent attention solves it by reducing the kv-cache size by 93.3%.</p><p>As we are clear with normal multi head attention, We now deepdive into multi-head latent attention. What we do here is we learn several compression and decompression matrices.</p><p>Equation given in paper:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/1*mZWXr9mRgFKdPMH9-0imvA.png" /></figure><p>We calculate the compressed KV cache by using the down-projection weight matrix DKV with the input h_t. This compressed KV-cache representation is then used to get the decompressed KV cache independently by using up-projection weight matrix for key and value separately.</p><p>The size of compressed kv caches is always less than embedding dimension “d”. The size of compressed kv cache is denoted by <strong>d_c. </strong>Dot product between the compressed matrix and up-projection matrix leads to decoding of key and value from their compressed latent space <strong>“d_c”</strong> to their respective head counts and head dimension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*8-CuaqnV0MU8EcoVJJGruQ.png" /><figcaption>shape of up-projection and down-projection matrices</figcaption></figure><p>We also compress queries to save the activation memory(The memory consumed to store intermediate outputs for quicker backpropagation.) . The compression factor for KV-cache and queries differ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*8zNBY3bbEkVi0bpzQa2uGg.png" /><figcaption>Compression for queries</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/126/1*6BX0o41_auywc9Y3uPjTkQ.png" /><figcaption>The shape of compressed queries</figcaption></figure><p>Now how do we add positional information to query and key. Deepseek-v2 uses same training strategy and techniques. It follows the Rotary positional embedding for positional encoding. But the problem here is we can’t let the compressed queries and keys to carry the RoPE embedding since this will cause problem in decompression. What we do is a new strategy called <strong><em>“Decoupled RoPE”.</em></strong></p><h4><strong>Decoupled Rotary Positional Embedding</strong></h4><p>We solve the positional encoding problem by additional multi head queries and shared keys to carry RoPE embedding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*AWuNk7cEw1SJGqHCYRyHpQ.png" /><figcaption>The decoupled queries and keys are represented like this</figcaption></figure><p>The decoupled query is extracted from compressed query by learning a weight matrix QR. The input h_t is shared with weight matrix KR to create shared decoupled key. RoPE is applied to these decoupled query and key matrices.</p><p>After applying RoPE to these decoupled query and keys, they are then concatenated with decompressed queries and keys above. These concatenated matrices are then used to calculate attention scores which are then used to calculate the output. The attention score formula is modified as required:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*wonTVGSPJCD2fpdosx_S7g.png" /><figcaption>Attention score formula for MLA</figcaption></figure><p>The dot product of RoPE concatenated queries and keys are divided by square root of sum of head dimension and head dimension of decoupled queries and keys for scaling which makes sure that the variance doesn’t explode. This attention score is then multiplied with values matrix that creates the output matrix “O”.</p><h3><strong>2. Deepseek-MoE</strong></h3><p>DeepSeekMoE is a Mixture-of-Experts (MoE) architecture designed to train strong models economically. It achieves efficiency and performance by introducing two main innovations:</p><ol><li><strong>Finer Expert Segmentation:</strong> Experts are divided into smaller, specialized units. This finer granularity promotes more accurate knowledge acquisition because each expert can specialize in a narrower domain.</li><li><strong>Shared versus Routed Experts:</strong> Some experts are shared (used universally) while others are routed selectively using a top–K mechanism. Shared experts help mitigate redundancy, and routed experts provide specialization.</li></ol><p>Moreover, the framework incorporates a <strong>device-limited routing strategy</strong> to minimize inter-device communication and several auxiliary loss functions to enforce load balance across experts, devices, and communications. Finally, a token-dropping strategy is applied to manage computation when loads are uneven.</p><h3>Basic Architecture of the FFN</h3><p>For each token <em>t</em> in the input sequence, the feedforward network (FFN) output h_t′ is computed using contributions from both the shared experts and the routed experts. The formulation is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*keklppZdysUjqBdannQstw.png" /></figure><p>where:</p><ul><li><strong>u_t​:</strong> The input token’s hidden state.</li><li><strong>N_s and N_r</strong> The numbers of shared and routed experts, respectively.</li><li><strong>FFN⁡(s)i(⋅) and FFN⁡(r)i(⋅):</strong> The feedforward operations for the i-th shared and routed expert.</li><li><strong>g_{i,t}​:</strong> A gating function that controls whether (and how much) the output from the i-th routed expert contributes for token <em>t</em>.</li></ul><h3>Explanation and Intuition</h3><ul><li><strong>Residual Connection:</strong> The original token representation u_t​ is added to the sum of expert contributions. This “skip connection” ensures that even if no experts are activated, the input is preserved.</li><li><strong>Shared Experts:</strong> All shared experts process each token unconditionally. Their outputs are summed (after being scaled by the number N_s​) to add a consistent, general representation.</li><li><strong>Routed Experts:</strong> For routed experts, each expert’s contribution is scaled by a gating value g_{i,t}​. These experts are only partially activated per token — only a subset (determined by a top–K selection) has nonzero g_{i,t}​.</li></ul><p>The intention is to combine a broad, general view (shared experts) with highly specialized processing (routed experts) for each token.</p><h3>Gating Mechanism for Routed Experts</h3><p>The gating mechanism ensures that each token only consults the most relevant routed experts. It is defined by the following equations:</p><h3>Token–to–Expert Affinity</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*VX59QDEj3Ghzq-NN_zmusg.png" /></figure><ul><li><strong>e_i​:</strong> The centroid (or representative vector) of the iiith routed expert.</li><li><strong>Dot product​:</strong> Measures the affinity between the token representation and the expert’s “profile.”</li><li><strong>Softmax:</strong> Normalizes these affinities into probabilities or scores that sum to 1 over all experts. It ensures that experts with higher affinity values stand out.</li></ul><h3>Top–K Selection Gate</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*AUTHhVfUsNIHrK7OXbiBLg.png" /></figure><ul><li><strong>Top–K Selection:</strong> From all N_r​ routed experts, only the K_r​ experts with the highest affinity scores for token <em>t</em> are activated.</li><li><strong>Gating Value Assignment:</strong> For experts that are chosen, the gate g_{i,t}​ equals the affinity s_{i,t}​. For all other experts, the contribution is 0.</li></ul><h3>Intuition Behind the Gating Mechanism</h3><ul><li><strong>Selective Activation:</strong> The top–K rule (with K_r​) ensures that each token is processed only by the experts that are most relevant according to their learned centroids.</li><li><strong>Efficiency:</strong> By activating only the best candidates, the model saves computation and avoids unnecessary communication when distributed across devices.</li><li><strong>Dynamic Routing:</strong> The Softmax–based affinity calculation allows the routing to be learned and adjusted during training so that different tokens find their most suitable experts over time.</li></ul><h3>Device-Limited Routing</h3><p>When deploying the MoE architecture on multiple devices, communication overhead becomes a critical issue. The proposed <strong>device-limited routing</strong> mechanism addresses this:</p><ul><li><strong>Problem Statement:</strong> In expert parallelism, routed experts may be spread over many devices. If a token’s selected experts span too many devices, the communication cost (transferring hidden states between devices) increases.</li></ul><p><strong>Solution:</strong></p><ul><li><strong>Step 1:</strong> For each token, select <em>M</em> devices that hold experts with the highest affinity scores.</li><li><strong>Step 2:</strong> Apply the top–K selection only among the experts on these <em>M</em> devices.</li></ul><p>The mechanism ensures that each token’s processing is confined to experts distributed over a limited number of devices (ideally M≥3). This strategy aligns the system’s performance with that of unrestricted top–K routing while reducing cross-device communication.</p><h3>Why It Matters</h3><ul><li><strong>Reduced Communication Costs:</strong> By bounding the number of devices participating in the computation for any single token, this method limits the potential bottlenecks from uneven data exchange.</li><li><strong>Scalability:</strong> It ensures that even as the model scales up (with many experts) the inter-device communication stays manageable.</li></ul><h3>Auxiliary Losses for Load Balance</h3><p>While the selective routing mechanism improves efficiency, it can lead to unbalanced loads where some experts or devices receive far more tokens than others. Unbalanced loads can slow down training or even lead to “routing collapse,” where certain experts are underutilized. DeepSeekMoE introduces three auxiliary loss functions to combat these problems:</p><h4>Expert-Level Balance Loss</h4><p>The expert-level balance loss ensures that each individual routed expert receives a roughly equal share of tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*V_lpyczVMu1XQ8ZbVm-EXA.png" /></figure><ul><li><strong>α1​:</strong> A hyperparameter controlling the strength of the balance loss.</li><li><strong>f_i​:</strong> A normalized count indicating the fraction of tokens routed to expert i.</li><li>The indicator function 1(⋅) returns 1 if token <em>t</em> selects expert <em>i</em> and 0 otherwise.</li><li>The normalization factor ensures that the load is scaled relative to the total number of tokens and the expected number of activations.</li><li><strong>P_i​:</strong> The average affinity score (or “priority”) that expert <em>i</em> receives across all tokens.</li></ul><h4>Intuition</h4><p>This loss term penalizes situations where some experts are overly popular or completely ignored by:</p><ul><li>Forcing a more even distribution of tokens across experts,</li><li>Ensuring that each expert is adequately trained and utilized.</li></ul><h4>Device-Level Balance Loss</h4><p>The device-level balance loss targets load imbalances across devices rather than individual experts. Experts are grouped by the device they reside on. The devices are divided into D groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*7ZS0qbLbcWwVMz3mIaHwmQ.png" /></figure><p>where:</p><ul><li><strong>α2: </strong>Hyper parameter called device level balance factor.</li><li><strong>D:</strong> Total number of devices.</li><li><strong>E_i:</strong> The set of experts deployed on device <em>i</em>.</li><li><strong>f’_i′​:</strong> The average load on device <em>i</em>, aggregated over all experts on that device.</li><li><strong>P’_i′​:</strong> The aggregate affinity score for device <em>i</em>.</li></ul><h4>Intuition</h4><p>By penalizing imbalances at the device level, the loss function encourages that:</p><ul><li>No single device becomes a bottleneck because it handles too many tokens,</li><li>Computation and communication loads are spread evenly across the available hardware, which is crucial for maintaining speed and scalability.</li></ul><h3>Communication Balance Loss</h3><p>Even after routing tokens to a limited number of devices, the amount of data (i.e., the number of tokens or hidden states) transmitted between devices can vary widely. The communication balance loss is designed to even out this inter-device communication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*fzLlxFGVAJmfdgxi5oGQ5g.png" /></figure><ul><li><strong>α3​:</strong> Communication balance hyperparameter.</li><li><strong>MT:</strong> The maximum number of hidden states that a device is allowed to send.</li><li><strong>f’’_i’’​:</strong> A normalized count representing how many tokens are sent to device <em>i</em>.</li><li><strong>P’’_i’’:</strong> Similar to the device-level aggregate affinity, representing the “demand” on device <em>i</em> in terms of expert activations.</li></ul><h4>Intuition</h4><ul><li><strong>Balanced Communication Load:</strong> This loss term incentivizes the system to distribute the “sending” and “receiving” load evenly among devices.</li><li><strong>Practical Efficiency:</strong> By ensuring that no device is overwhelmed with messages from other devices, the overall communication efficiency is maintained even during training on large-scale, distributed hardware.</li></ul><h3>Token-Dropping Strategy</h3><p>Even with auxiliary losses designed to balance loads, perfect balancing is hard to achieve in practice. Therefore, DeepSeekMoE incorporates a <strong>token-dropping strategy.</strong></p><ul><li><strong>Computational Budget:</strong> Each device is assigned an average computational budget (set to a capacity factor of 1.0). This defines how many tokens’ hidden states a device can process.</li><li><strong>Token Dropping:</strong> If a device receives more tokens than its computational budget allows, tokens with the lowest affinity scores on that device are dropped.</li><li><strong>Guarantee for Training Consistency:</strong> Tokens from roughly 10% of the training sequences are always retained to ensure that enough data is seen during training — this prevents complete data starvation on some sequences.</li><li><strong>Flexibility for Inference:</strong> During inference, the token-dropping mechanism can be applied or adjusted according to efficiency requirements while maintaining consistency with the training procedure.</li></ul><h4>Intuition</h4><ul><li><strong>Avoiding Wastage:</strong> The token-dropping strategy prevents excessive computation on tokens that contribute little to the model’s output (i.e., those with low affinity scores).</li><li><strong>Efficiency:</strong> It trims the workload dynamically during training to prevent overloading devices, thereby ensuring that the available computational resources are used more effectively.</li><li><strong>Stability:</strong> By retaining a minimum percentage of tokens, the strategy guards against potential training instabilities that might arise from overly aggressive dropping.</li></ul><h3>Conclusion</h3><p>These are the major architectural changes that was published deepseek-v2. They still used the same training strategy from deepseek-67B, still using HAI-LLM implementation for training deepseek-v2 in a distributed way. This blog covers the entire new things that were invented in the deepseek-v2 paper. To understand the training mechanisms and strategies please refer my previous blog post on <a href="https://medium.com/@gglrthiru/thinking-from-first-principles-pov-for-deepseek-r1-series-deepseek-v1-ac949831f0ac">Deepseek-v1</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90ce4adf9f5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thinking from first principles POV for Deepseek-R1 series — Deepseek-V1]]></title>
            <link>https://medium.com/@gglrthiru/thinking-from-first-principles-pov-for-deepseek-r1-series-deepseek-v1-ac949831f0ac?source=rss-6c58aa90b315------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac949831f0ac</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[reasoning-model]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[deepseek-r1]]></category>
            <dc:creator><![CDATA[Thirumalai Kumar]]></dc:creator>
            <pubDate>Sun, 30 Mar 2025 09:10:35 GMT</pubDate>
            <atom:updated>2025-03-30T09:10:35.804Z</atom:updated>
            <content:encoded><![CDATA[<h3>Thinking from first principles POV for Deepseek-R1 series — Deepseek-V1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z10Nd7VBIMe2cLAMNJ-XAA.png" /></figure><h3>Introduction</h3><p>Hey folks, How you doing!! 😉, It’s Thiru here. I have been trying to learn about how to develop Deepseek-R1(Well!! at least a mere tiny version of it as I’m GPU POOR 😏). In order to understand how Deepseek-R1 became great success, You need to understand two things: GRPO and Deepseek-V3. In order to understand Deepseek-v3, we need to clearly understand how their scaling ideas originated. The scaling idea for LLMs was first rethought in Deepseek-V1. So, I read the entire Deepseek-V1 paper last week trying to fathom out their core ideas and working principles.</p><p>This week, I will be covering the entire Deepseek-v1 paper and in coming weeks will be covering the subsequent papers: Deepseek-v2, Deepseek-v3 and Deepseek-R1 finally. I thought covering from the ground up will provide more information on how this model was invented iteratively. Also, All these papers introduced new techniques which can be implemented in real life production scenarios to achieve optimal results.</p><p><strong>Structure of this Article</strong></p><p>⚠️ This article is a long read, There is no tl;dr version since this is a series in detail.</p><p>This article has 2 sections. The first section covers: implementation details of Deepseek-V1 model and the second section covers what are the novel techniques explored and invented in this paper.</p><p><strong>Section -I</strong></p><ol><li>What this Deepseek-v1 paper primarily focusses on?</li><li>How was the pretraining dataset for Deepseek-v1 created?</li><li>Architecture of Deepseek-V1</li><li>Hyperparameters of Deepseek-V1</li><li>Infrastructure for Deepseek-V1</li></ol><p><strong>Section — II</strong></p><ol><li>Scaling laws for LLMs</li><li>Scaling Hyperparameters in detail</li><li>Scaling Model/Data allocation in detail</li></ol><p>Well this article will be pretty lengthy, Stay with me. I will explain all things intuitively and also give an real life example of how to use these scaling laws for a given dataset.</p><h3>Section — I</h3><h3><strong>What this Deepseek-v1 paper primarily focuses on?</strong></h3><p>The papers that released before deepseek-v1 never focused on scaling laws for LLMs. Also the scaling laws of that time were not LLM focused instead they were focused on old architectures like CNN, LSTM, RNN, etc;.</p><blockquote>📓 Well, what is a scaling law?</blockquote><blockquote>A scaling law is a systematic approach to determine the size of data, size of model and size of compute used.</blockquote><p>There was a necessity to rethink the scaling law that already existed with a focus on LLM. This paper primarily focuses on inventing a new scaling law for LLMs. They did invent one by doing a lot of empirical analysis and fitting a simple regression models to regress the formulae for us.</p><p>A perfect example of older scaling law is <strong>Compoung scaling </strong>introduced by <strong>Mingxing Tan </strong>and <strong>Quoc V. Le </strong>in their ground breaking paper<a href="https://arxiv.org/pdf/1905.11946"> <strong><em>EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks</em></strong></a><strong><em>. </em></strong>Their compound scaling is still being used for scaling convolutional neural networks and other related architectures. (😉One of my favorite papers and technique, Must read…)</p><p>From here, This paper sets the context of what they have worked on.</p><h3><strong>How was the pretraining dataset for Deepseek-v1 created?</strong></h3><p>The task was to improve the quality and richness of the pretraining dataset. They have created the pretraining dataset of 2 Trillion tokens using common crawl dump. In order to ensure quality and richness, They have setup a 3 stage pipeline:</p><p>i) Deduplication</p><p>ii) Filtering</p><p>iii) Remixing</p><blockquote>Explaining all these stages of cleaning and preprocessing dataset will be covered in a separate blog as it has its own depth of information. This blog series will primarily focus on the techniques and training strategies introduced in each deepseek papers</blockquote><p><strong>Deduplication</strong> includes algorithms like MinHash and Locality sensitive hashings to remove duplicates from the dataset. Here the deduplication is applied to both levels: Individual documents and entire dataset. After deduplicating the common crawl dump 89.8% of the dataset gets removed and only 10.2% remains.</p><p><strong>Filtering</strong> assures the quality of the dataset both like semantically and linguistic way. It is also applied in both levels just like deduplication.</p><p><strong>Remixing </strong>ensures the proper representation of all domains within the dataset.</p><p>Lastly, The tokenizer used to train the LLM is the same Byte Pair Encoding. Pre-tokenization is done to prevent mixing of CJK(Chinese-Japanese-Korean) symbols. After all these cleaning and remixings, A dataset of size 24GB is made. The tokenizer was trained on this dataset with a vocab size of 102400.</p><p>Initially the vocab size was 100000 with additional 15 special tokens totalling to 100015 but eventually to cope up with any additional tokens required, the vocab size was boosted to 102400.</p><h3><strong>Architecture of DeepSeek-V1</strong></h3><p>The deepseek-v1 model follows the design of the llama model. It has RMS-Norm for pre-normalization, uses Swi-GLU as activation in feedforward network, Rotary embedding for positional encoding and grouped query attention to reduce inference cost.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17dc17f1d3cc41028423ebaec60cf0d3/href">https://medium.com/media/17dc17f1d3cc41028423ebaec60cf0d3/href</a></iframe><p>There is one major difference though if you see the above table, Deepseek-V1 increases the depth of the network rather than the width of the intermediate feed forward layers.</p><p>If you note the table, The 7B parameter model uses normal multi-head attention but the 67B parameter model uses Grouped Query Attention. The reason this is used only for 67B is because it has its usage only when the number of heads is greater than 32. Grouped query attention is just mixture of both multi-head attention and multi-query attention.</p><p>Also you can consider if n_heads equals to n_kv_heads, The system fallsback to normal multi-head attention and if not, It goes for grouped query attention. In order to learn much more in depth, I would request you folks to read this wonderful <a href="https://medium.com/@maxshapp/grouped-query-attention-gqa-explained-with-code-e56ee2a1df5a">article</a>.</p><h3><strong>Hyperparameters of Deepseek-v1</strong></h3><p>Standard deviation to initiate the weights of the network: 0.006</p><p>The optimizer used is Adam with weight decay for regularization. It uses a Beta_1 of 0.9, Beta_2 of 0.95 and weight decay of 0.1.</p><p>They have also made use of multi-step learning rate scheduler rather than cosine annealing.</p><p>The conditions of multi-step lr scheduler:</p><ol><li>Raise to the maximum value at 2000 warmup steps.</li><li>Decrease to 31.6% of the max value once 80% of tokens are processed.</li><li>Decrease to 10% of the max value once 90% of tokens are processed.</li><li>The gradients are clipped to 1.0 to prevent gradient overflow.</li></ol><h3><strong>Infrastructure of Deepseek-V1</strong></h3><p>Here they have used and experimented a lot of new tools and techniques of that time. I’m not going in details about all these techniques mentioned here, Each technique has more details to cover, I will attach their respective blogs, You can refer it there.</p><ul><li>They have first used a closed source LLM training framework called <a href="https://github.com/HFAiLab/hai-platform">HAI-LLM</a> which uses data parallelism, tensor parallelism, sequence parallelism and 1F1B parallelism.</li><li>Along with all those mentioned above flash attention and zero-1 optimizer are used for speedups and properly manage memories.</li><li>Model is actually trained in FP-16 but the accumulation is done in FP32 precision.</li><li>Computations and communications are all overlapped to reduce the overhead.</li></ul><h3>Section — II</h3><p>This section covers the novel scaling frameworks introduced in the paper. There are 2 scaling frameworks introduced in this paper: One for hyper parameters and another for Model/Data allocation strategy. I will cover both in detail and also use a scaling method to deduce the architecture of the model from just the number of tokens in the training data.</p><h4>Scaling laws for Hyper parameters</h4><p>The research on scaling laws are very old, They were introduced before transformers came into the context. The old law suggests that increasing the compute budget increase the model performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*BiLGmh0nfno_rQ3Tc8_0oA.png" /></figure><p>The old scaling laws aren’t applicable for modern day LLMs. Moreover the old studies didn’t do any research with hyper parameters. So, We don’t know whether the models with different compute budgets achieve same performance.</p><p>After extensive research, deepseek team found that there is a power law relationship between Compute budget, Batch size and Learning rate. With this power law equation one can find an optimal hyper parameters for their own compute budget.</p><p>They follow an approach called IsoFlop from <a href="https://medium.com/aiguys/chinchilla-training-compute-optimal-large-language-models-a922a0d9eebb">Chinchila</a>. Isoflop profile approach means keeping the Number of flops per token constant for distinct model sizes. Replacing the “6N” with “M” in the above equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*I0pumo_gspMVAEO3ItvJ0g.png" /></figure><p>Firstly a grid search was performed with low compute budget range from <strong>1e17 to 1e20. </strong>The model was trained with different combinations of hyper parameters. The actual range was <strong>1e17 to 2e19.</strong></p><p>All the setups of different combinations shared a same initial stage to save cost. Considering the large parameter space, Only the parameters that led to a generalization error not more than 0.25% of its combinational minimum was selected.</p><p>With the above collected data in each run, They created a dataset with Batch size B, Learning rate L and Compute Budget C. By fitting a linear regression model with this dataset, They came up with the following equations to compute the optimal values for both Batch size and learning rate depending upon compute budget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*YfiTLTLPWcJA-nlJD0nzQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*YrJbY2YFarPu5KukQQ_vVg.png" /></figure><h4>Data and Model Allocation strategy</h4><p>The task was to find an exponent “a” and exponent “b” for scaling model and data respectively. The model parameter calculation <strong>C=MD</strong> was done earlier either by,</p><p>N1 -&gt; Non embedding parameters</p><p>N2 -&gt; Complete parameters</p><p>But there is a caveat in both these approached, They didn’t count the attention mechanism overhead. So, In this paper the team found a new way to represent the parameters. They represented it with Flops(per token) rather than the parameters itself. Below are the three equations to calculate the number of parameters,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*3foc_j7_8lKwzGluxCwjLw.png" /><figcaption>6N1 equation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*YK9eJBUiCa00vfnClH9dlw.png" /><figcaption>6N2 equation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*UpctF3mwrwwYIM37RPGFDQ.png" /><figcaption>M equation</figcaption></figure><p>The difference between calculating the parameters with the new “M” formula and the older version of “6N1” and “6N2&quot; were more than 50%. Below is the difference between calculating the parameters of deepseek model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67c37182ffeb476c36a74df91a700d02/href">https://medium.com/media/67c37182ffeb476c36a74df91a700d02/href</a></iframe><p>By doing various experiments with compute scale from the range of <strong>1e17 to 3e20. </strong>After running experiments, they collected a dataset similar to scaling for hyper parameters. Following the same steps by fitting a regression model, They came up with the below equations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*-ElxTkF5d9Ev4OZpQHgQdA.png" /><figcaption>M_opt equation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*U_SRfNWwbpK4E5xhaqRfSw.png" /><figcaption>D_opt equation</figcaption></figure><p>This is the power law relationship to find the optimal data size and model size depending upon the compute budget.</p><p>𝑀base = 0.1715, 𝑎 = 0.5243 and 𝐷base = 5.8316, 𝑏 = 0.4757 are the values found using the fit regression model.</p><p><strong>Example: How to calculate the model architecture like number of layers, embedding dimension when you know the size of the dataset?</strong></p><p>Let’s say that my pretraining dataset has 3 billion tokens. So, from the D_opt equation we know the value for D_opt with which we can calculate it’s corresponding compute budget C.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*64Xa1ryGtuFgUTe3NfIAnQ.png" /><figcaption>Finding compute budget from given dataset size</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*YiTeiXgDZiUWFDnrdzF4Uw.png" /><figcaption>Optimal model size</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*KTuTnDYDich7muD1gfAdNg.png" /><figcaption>optimal model architecture</figcaption></figure><p>So, from the above equations we can find for a dataset of size 3 billion tokens, the optimal model size is 685Million params. The number of layers should be 8 (or) 9 with 4096 seqlen and embedding dimension of 768.</p><h3>Conclusion</h3><p>This paper marks an important milestone for DeepSeek in its journey into large language models. The scaling techniques introduced laid the groundwork for building more efficient and accurate models, culminating in the development of DeepSeek-V3. Notably, DeepSeek-V3 served as the base model for the DeepSeek-R1 reasoning model. In the coming weeks, I will continue exploring subsequent papers in this series, each accompanied by a brief implementation to deepen our understanding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac949831f0ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Novel Decoder-Only LLM architecture for speech synthesis and zero shot TTS]]></title>
            <link>https://medium.com/@gglrthiru/a-novel-decoder-only-llm-architecture-for-speech-synthesis-and-zero-shot-tts-8d502b9c6e9f?source=rss-6c58aa90b315------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d502b9c6e9f</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[text-to-speech]]></category>
            <category><![CDATA[codec]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[speech]]></category>
            <dc:creator><![CDATA[Thirumalai Kumar]]></dc:creator>
            <pubDate>Fri, 14 Mar 2025 07:30:35 GMT</pubDate>
            <atom:updated>2025-03-14T07:30:35.260Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ePLGkYz2HiSZ2a5iycz8vQ.png" /></figure><h3>Introduction</h3><p>Hi guys!, Its me again here explaining the new state-of-the-art speech synthesis model. This blog gives you a detailed summarization of the [Spark-TTS research paper](<a href="https://arxiv.org/pdf/2503.01710">https://arxiv.org/pdf/2503.01710</a>) . There are more technical jargons as well, I haven’t explained those in this article, I will be explaining those in separate titles as they have their own depth and details. All those words that are both <strong>Bold </strong>and <strong><em>Italic </em></strong>are topics that will be covered if separate articles</p><h3>Let’s Dive into it!……</h3><p>Recent advancements in LLM space have led to zero-shot text to speech feasibility. But these <br>approaches are more complex and are of multi-stage which might create multiple codebooks for different settings like (Male voice -1 codebook, Female voice — 1 codebook, etc.;). This is more tedious and more costlier also being time consuming. In this papers, the authors introduce a new approach named as Spark-TTS(Maybe as fast as spark.)</p><p>Spark-TTS brings in a new codec called Bicodec. This bicodec converts speech into 2 types of tokens: Low-bitrate tokens for representing linguistic information whereas High-bitrate fixed length tokens for speaker attributes like pitch, speaker gender, speaking speed, speech rate, etc.;<br>Coupling this fine-grained representation with a powerful multimodal LLM like Qwen-2.5 provides you with both coarse and fine-grained control over the voice generated.</p><p>To develop and test the proposed framework, The author has also published an 100,000 hours of audio dataset with a comprehensive metadata required to develop and evaluate the model.</p><p><strong><em>What does this paper contribute?</em></strong><br>Even though recent advancements have made zero-shot speech to text possible, The LLMs still depend on specialized architectures like VQ(vector quantization), FSQ(finite scale quantization)and LLM-Codecs .<br>Although training these models with large parameters with large datasets achieve near human speech synthesis, There are still caveats. This models either depend on Multi-Stage synthesis approach (or) parallel stream construction that deviates completely from the actual text-based LLMs. They depend on external architectures because the pre-existing codecs could provide rich representations for linguistic information but lacks in providing information for speaker attributes for which again these models depends on complicated architectures like Group VQ .</p><p><strong>This paper contributes 3 major things:</strong><br>1. A novel hybrid tokenization framework called Bicodec.<br>2. Introduces more coarse grained control like gender, speech speed and more fine-grained controls like speech rate, pitch (timbre quantities.). More control to the user.<br>3. A new benchmarking dataset called VoxBox with 100,000 hours of audio with metadata.</p><p><strong>BiCodec — Novel Hybrid Tokenization Framework</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0rjZE8hw8f6Sc70ZQ-xquQ.png" /></figure><p>Bicodec follows a standard VQ like architecture to create tokens. The input audio is provided as an input in two parallel pipelines: One for semantic tokenizer and another one for global tokenizer. The semantic tokenizer gets the input audio and extracts features using a <strong><em>wav2vec2.0 model (XLSR — 53)</em></strong>. The features are extracted from 11, 14 and 16th layers and averaged together to get representations for linguistic information like phonemes, words, etc.; This extracted representation is sent to an encoder which is a fully convolutional network built by ConvNext blocks.</p><p>The global tokenizer converts the audio to melspectrogram and extracts feature from it. The encoder of global tokenizer follows <strong><em>ECAPA TDNN</em></strong> architecture, following the We-speaker implementation till the last pooling layer.</p><p><strong>Quantizations used in the network</strong>: The semantic tokenizer uses a VQ method for quantization, follows the steps of the paper DAC published by (kumar et al). The global tokenizer uses FSQ(Finite Scale Quantization) to mitigate any training collapse problem from VQ.</p><p><strong>Training Methodology for Bicodec</strong></p><p>The bicodec is trained end-to-end in a GAN method trying to optimize a reconstruction loss and a L1 loss for feature matching(for discriminators). <br>L1 loss is also used for reconstruction on multi-scale mel spectrograms. There are 2 discriminators in this architecture to train the decoder in GAN manner. Multi period discriminator and mutli-band multi-scale stft discriminator for waveform discrimination and frequency domain discrimination respectively.</p><p>The VQ codebook incorporates both codebook and commitment loss. L1 loss is used for the embedding collected from the encoder and the quantized results. Both straight-through and stop-gradients methods are used to efficiently train the codebook.</p><p>It also includes several nuances methodologies to train the model very stable (Not gonna mention it here).</p><p><strong>LLM — Decoder only generation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4G3dGB-B1QnDjUSJdaWbw.png" /></figure><p>For speech data, the VQVAE codebook and the FSQ codebook trained on the audio data is used as tokenizers. For the text, a simple BPE tokenizer is used. While generating the audio from the text, the text is first tokenized with BPE tokenizer, The Mel spectrogram extracted from the audio is used as input for global tokenizer which provides discrete tokens that represent the speaker attributes like gender, speech rate and the other timbre qualities. The semantic tokenizer with the Wav2Vec2.0 embeddings provides tokens that represents the linguistic information like phonemes, words, vowels, etc.;</p><p>These three tokens are concatenated together and provided as inputs to the decoder only LLM architecture. The LLM used here is Qwen2.5–0.5B parameter model. The generated tokens are then decoded into audio using the Decoder model from VQVAE training.</p><h3>Conclusion</h3><p>The above model is the new SOTA text-to-speech, not only in accuracy but also in efficiency. As earlier models have more complex architecture which was not only difficult to setup but also not so efficient when taking metrics like tokens/s, throughput, etc.; This novel decoder only LLM architecture also for speech synthesis just like text generation model is a big breakthrough. I have attached their official github link <a href="https://github.com/SparkAudio/Spark-TTS">here</a> . Once the training script is released, I will create a new topic around setting those codebases up, training the model and deploying it efficiently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d502b9c6e9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a LLM from scratch for Indic language using Huggingface]]></title>
            <link>https://medium.com/analytics-vidhya/how-to-build-a-llm-from-scratch-for-indic-language-using-huggingface-0e0ada9bded9?source=rss-6c58aa90b315------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e0ada9bded9</guid>
            <category><![CDATA[llm-pre-training]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Thirumalai Kumar]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 04:21:31 GMT</pubDate>
            <atom:updated>2025-02-28T06:05:31.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZtaLLCFnw4h1VGT6UR36A.jpeg" /></figure><p>Hey there folks, Thiru here. Long time no see :). I was planning to build an LLM for an Indian language from scratch. I aimed to build a 3 or 8B model for my Tamil mother tongue. I just thought sharing my journey would make it interesting. In this blog post, I’m trying to train a GPT-2 model for the Tamil language. Yeah I know what you all think, such an old and smaller model, Yup for now. It is always to try smaller and scale later. This blog post includes the topics below:</p><ol><li>Where did I get the dataset from and how much the size is?</li><li>What are the preprocessing techniques that I used for the dataset?</li><li>Wait! How did I make a tokenizer for an indic language, which tokenizer did I choose and why?</li><li>Also, How did I get hardware to train on?</li><li>And Finally how to setup a simple training pipeline using huggingface?</li></ol><p>tl;dr</p><pre>git clone git@github.com:ThiruRJST/llm_pretrain.git<br>cd llm_pretrain/<br>sudo apt-get install aria2 -y<br>aria2c -x4 https://objectstore.e2enetworks.net/ai4b-public-nlu-nlg/indic-corp-frozen-for-the-paper-oct-2022/ta.txt<br>mkdir dataset<br>mv ta.txt dataset<br>mv dataset/ta.txt dataset/tamil_pretrain.txt<br>python3 main.py --raw_data dataset/tamil_pretrain.txt</pre><h3><strong>The Dataset</strong></h3><p>Luckily, the AI4 Bharat program made it easy for us to get a dataset for pretraining the LLM for indic languages. There is a dataset called <a href="https://github.com/AI4Bharat/IndicBERT/tree/main?tab=readme-ov-file#indiccorp-v2">IndicCorpV2</a>. This is a multi-lingual dataset that contains 23 indic languages. I have attached the link, you can check for yourself if that includes your language of interest. They had a dataset for Tamil separately of 11GB in size. Yup, it is huge but not that huge. This is more than sufficient for pretraining an LLM, But before that, we need to think about whether this dataset is already clean (or) not, if not what techniques can we use to clean it. The next part explains the preprocessing step in detail with code.</p><blockquote>ராமநாதபுரத்தில் பிரதானமாக நெல், சிறு தானியங்கள் பயிறு வகைகள், நிலக்கடலை, பருத்தி, தென்னை, மிளகாய்,கொத்தமல்லி பயிரிடப்படுகிறது. மாவட்டத்தில் சராசரி மழை 827 மி.மீ., ஆக இருந்தும், கடந்த ஆறு ஆண்டுகளாக மழைபொய்த்து போனது. அனைத்து நீர் நிலைகளும் வறண்ட நிலையில் உள்ளது.</blockquote><h3><strong>Preprocessing the dataset</strong></h3><p>The preprocessing steps include two steps: <strong>Filtering</strong> and <strong>Splitting</strong>.</p><p><strong>Filtering: </strong>I use a context length of 512, So I just want to remove those lines that are lower than the context length. Yes, I could hear you saying, we can pad the data right! There are extremely small sentences of length 5, 3. Such sentences would not provide any value for training and filtering anything below the context length helps to reduce the dataset size too. But how can we operate on such a huge 11GB file, We can make use <strong><em>mmap </em></strong>library from python</p><p>So, what is mmap?</p><p>mmap lazily loads the huge data into the physical memory bypassing all the data buffers that are needed in normal read and write operations. This boosts your speed but occupies space. If you wanna learn about mmap in-depth, I suggest you this blog: <a href="https://realpython.com/python-mmap/">https://realpython.com/python-mmap/</a>. Below is the code that I wrote to do the filtering.</p><pre>@ensure_annotations<br>def clean_whitespaces(text: str):<br>    return re.sub(r&quot;\s+&quot;, &quot; &quot;, text).strip()<br><br><br>@ensure_annotations<br>def filter_sentences(file_path, max_len, output_file):<br>    with open(file_path, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br><br>        mmapped_file = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)<br>        with open(output_file, &quot;w&quot;) as out_file:<br>            for line in iter(mmapped_file.readline, b&quot;&quot;):<br>                sentence = line.decode(&quot;utf-8&quot;).strip()<br>                sentence = clean_whitespaces(sentence)<br>                if sentence:<br>                    if len(sentence) &gt;= max_len:<br>                        out_file.write(sentence + &quot;\n&quot;)<br>        mmapped_file.close()</pre><p>I created clean spaces function to remove abnormal whitespaces in between words in a sentence, These whitespaces adds up unwanted sequence length to the data while training and also misleads the model.</p><p>ensure_annotations is just a fancy decorator to make sure no other data format other than the specified is allowed for a function to execute.</p><p><strong>Splitting: </strong>Now we have a filtered dataset but it is one huge file still of size 5GB, we need to split this dataset into train and test splits. I wrote a custom function for that too, But you can make use of train_test_splits from sklearn. Below is the custom code that does that:</p><pre>def filtering_and_data_splitting(data_path: str):<br><br>    #Filtering<br>    if not os.path.exists(Config.filtered_data):<br>        logger.info(&quot;Filtering data&quot;)<br>        filter_sentences(<br>        file_path=data_path,<br>        max_len=Config.context_length,<br>        output_file=Config.filtered_data,<br>    )<br><br>    # data splitting<br>    if not os.path.exists(f&quot;dataset/v2/tamil_train.txt&quot;):<br><br>        # create a new version of the dataset<br>        create_directory(dir_name=&quot;dataset/v2&quot;)<br><br>        split_dict = {<br>            &quot;train&quot;: open(&quot;dataset/v2/tamil_train.txt&quot;, &quot;w&quot;, encoding=&quot;utf-8&quot;),<br>            &quot;test&quot;: open(&quot;dataset/v2/tamil_test.txt&quot;, &quot;w&quot;, encoding=&quot;utf-8&quot;),<br>        }<br><br>        context_length = 512<br><br>        # reading the files as blocks<br>        with open(data_path, &quot;r&quot;, encoding=&quot;utf-8&quot;) as datafile:<br>            with tqdm(<br>                total=os.path.getsize(data_path),<br>                unit=&quot;B&quot;,<br>                unit_scale=True,<br>                desc=&quot;Reading..&quot;,<br>            ) as pbar:<br>                for chunk in chunk_filereader(fp=datafile, block_size=8192000):<br>                        split = split_train_test()<br>                        split_dict[split].write(chunk)<br><br>                    pbar.update(len(chunk.encode(&quot;utf-8&quot;)))<br><br>            # closing the files<br>            for file in split_dict.values():<br>                file.close()<br><br>        logger.info(&quot;Data splitting completed&quot;)<br>    else:<br>        logger.info(&quot;Data already splitted&quot;)</pre><p>Don’t fret by looking at the size of the code, the logic is so simple, and mainly it creates a directory for a new version of the dataset. This is one pipeline that filters the raw data and then splits it into two: train and test splits. I’m just reading as blocks and making use of a Python generator to lazily load the data from the filtered dataset, Loading the huge 6GB file will make my PC go brrr… For each chunk, I’m just tossing the random function to get a value to decide whether it’s a train or test split, 80% of the time it will be train, and only 20% of the time it will be a test which makes sure of 80–20 split. <strong><em>Hey Also, I’m using DVC for dataset version control, It is always a good practice to do so.</em></strong></p><h3><strong>Training a Tokenizer</strong></h3><p>Huggingface has a great blog explaining how to train different types of tokenizers from scratch by building it block by block: <a href="https://huggingface.co/learn/nlp-course/en/chapter6/8">https://huggingface.co/learn/nlp-course/en/chapter6/8</a>, You should definitely give it a read to know what are the functions I use and why.</p><p>I’m training a BPE(Byte Pair Encoding) Tokenizer, The reason to chose this tokenizer is that sub-word tokenization is still the best for the languages with more dense morphologies and agglutination. If you want to learn what are the other tokenization strategies, I ask you to refer to this link:<br><a href="https://medium.com/@cloudpankaj/tokenization-strategies-for-indian-regional-languages-in-nlp-476a3d501305">https://medium.com/@cloudpankaj/tokenization-strategies-for-indian-regional-languages-in-nlp-476a3d501305</a></p><p>I have an opinion that tokenization works well for languages like English which has minimal morphological challenges but it fails to be understood when it comes to languages like: Tamil, Hindi, Korean, and Japanese. To improve the LLM performance in these languages, we must find a workaround to train the LLM directly on byte data rather than tokenized data. <br>The code to train a brand-new tokenizer for your dataset:</p><pre>def train_custom_tokenizer(filtered_datapath: str, vocab_size: int, save_path: str):<br>    tamil_tokenizer = Tokenizer(models.BPE())<br>    tamil_tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)<br><br>    # tamil sample sentence<br>    sample_text = &quot;வணக்கம் உலகம்&quot;<br>    tamil_tokenizer.pre_tokenizer.pre_tokenize_str(sample_text)<br><br>    # train the tokenizer<br>    trainer = trainers.BpeTrainer(<br>        vocab_size=vocab_size, special_tokens=[&quot;&lt;|endoftext|&gt;&quot;]<br>    )<br>    tamil_tokenizer.model = models.BPE()<br>    tamil_tokenizer.train([filtered_datapath], trainer=trainer)<br><br>    # save the tokenizer<br>    tamil_tokenizer.post_processor = processors.ByteLevel(trim_offsets=False)<br>    tamil_tokenizer.decoder = decoders.ByteLevel()<br><br>    decoded_text = tamil_tokenizer.decode(tamil_tokenizer.encode(&quot;வணக்கம் உலகம்&quot;).ids)<br><br>    assert decoded_text == &quot;வணக்கம் உலகம்&quot;, &quot;Tokenizer not trained properly&quot;<br>    tamil_tokenizer.save(save_path)</pre><p>Please look into the above-mentioned huggingface’s blog to understand why I use several functions and what it mean.</p><h3><strong>Hardware to train on</strong></h3><p>I have a RTX 2070Super with 8GB VRAM which is more than enough to train this model. If you want to scale this model, I prefer</p><p>to check for GPU servers at <a href="https://vast.ai/">https://vast.ai/</a>. This website is great as it offers good GPUs for minimal cost. I was able to get 2xRTXA6000 for like $1/hr or something which might cost a fortune if I tried it in AWS or Azure.</p><p>Also If you don’t have any GPUs, Colab is more than enough to train this tutorial, This tutorial just consumes around 4GB of VRAM.</p><h3><strong>Training Pipeline Setup</strong></h3><p>We can make use of huggingface’s trainer API to train the model. The below is the code for training configuration:</p><pre>args = TrainingArguments(<br>        output_dir=&quot;artifacts&quot;,<br>        per_device_train_batch_size=8,<br>        per_device_eval_batch_size=8,<br>        evaluation_strategy=&quot;steps&quot;,<br>        eval_steps=5_000,<br>        logging_steps=5_000,<br>        max_steps=10_000,<br>        gradient_accumulation_steps=8,<br>        num_train_epochs=1,<br>        weight_decay=0.1,<br>        warmup_steps=1_000,<br>        lr_scheduler_type=&quot;cosine&quot;,<br>        learning_rate=5e-4,<br>        save_steps=5_000,<br>        fp16=True,<br>        push_to_hub=True,<br>        gradient_checkpointing=True,<br>        max_grad_norm=1.0,<br>        optim=&quot;adamw_torch&quot;<br>    )<br><br>    trainer = Trainer(<br>        model=model,<br>        tokenizer=tokenizer,<br>        args=args,<br>        data_collator=data_collator,<br>        train_dataset=tokenized_dataset[&quot;train&quot;],<br>        eval_dataset=tokenized_dataset[&quot;test&quot;],<br>    )<br><br>    trainer.train()</pre><p>The batch size is 8 but along with gradient accumulation, The effective training batch size is 8*8=64. Gradient accumulation just accumulates the gradients for the “n” number of runs without upgrading the weights, once the “n” number of runs is over, it updates the weight. This technique can be used to achieve a larger batch size when you don’t have enough VRAM to achieve it. I’m training it for 10000 steps and evaluating the model at each 5000 steps. Cosine annealing lr scheduler is used to smoothly traverse the loss surface. It also trains in mixed precision(FP16) which helps in saving much more VRAM. So, Here we are at the end of the blog, The above codes work in conjunction to achieve what we need.</p><h3><strong>Conclusion</strong></h3><p>I’m planning to implement all of the above from scratch, Like a transformer model from scratch and BPE, This helps me understand the nuances of both techniques and also provides me more customization power to try new things. Well, I Like PROBLEMS in life so I just want to make it harder for me 😂. Stay in touch fam for the next from scratch implementation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e0ada9bded9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/how-to-build-a-llm-from-scratch-for-indic-language-using-huggingface-0e0ada9bded9">How to build a LLM from scratch for Indic language using Huggingface</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SphereFace Loss-Deep Face Recognition]]></title>
            <link>https://medium.com/@gglrthiru/sphereface-loss-deep-face-recognition-50a8821ef6f9?source=rss-6c58aa90b315------2</link>
            <guid isPermaLink="false">https://medium.com/p/50a8821ef6f9</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[loss-function]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[face-recognition]]></category>
            <dc:creator><![CDATA[Thirumalai Kumar]]></dc:creator>
            <pubDate>Tue, 20 Oct 2020 12:51:05 GMT</pubDate>
            <atom:updated>2020-10-20T12:51:05.110Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deep Face Recognition- SphereFace</h3><p>Hello world, As we all know that CNN learns by optimizing a loss function and this loss function also determines the type of feature that a model learns. The traditional softmax loss learns the features that aren’t discriminative enough in an open-set. so, let’s look into some loss functions that make our DCNN models robust in an open-set. But before that, I would like to explain the problem in recognition tasks concerning the dataset and the need for the new loss function.</p><p>I was obsessed with using the traditional softmax loss to train any classifiers. I tried the same with EfficientNetB7 for the google landmark recognition challenge and got no amazing results. I was wondering how could EfficientNetB7 perform poorly with humongous data. The metric used was <a href="https://towardsdatascience.com/multi-class-metrics-made-simple-part-ii-the-f1-score-ebe8b2c2ca1">micro averaged precision.</a></p><p>My score was hardly moving from 0.000 to 0.001. But, there were a lot of 0.000 in LB at the start. Then, I read the paper about the dataset which convinced me that normal softmax loss won’t be effective since the dataset is humongous and data had large intra-class variation and less inter-class variation.</p><p><strong>SphereFace </strong>loss is an angular variant of traditional softmax loss that helps to make the recognition in datasets with open-test set better. Imagine it as a loss function whose projection space is a 4D sphere or Hypersphere.</p><p><strong>So what’s a hypersphere?</strong></p><p>A hypersphere is a four-dimensional sphere that we cannot visualize since we live in a three-dimensional space. But, We can visualize how would a 4D sphere looks in a three-dimensional space of ours. To those who wanna know about it clearly, I recommend this <a href="https://www.youtube.com/watch?v=_4ruHJFsb4g">video</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*tiXmhJGcHmyVAzxQlG2Xbw.gif" /><figcaption>4D Sphere</figcaption></figure><p><strong>Why we need an Angular margin Loss Function?</strong></p><p><strong>Problem with the dataset:</strong></p><ul><li>The dataset has an unequal distribution.</li><li>The dataset is with long-tail which means there are so many classes with a lesser number of images to get trained.</li><li>The variance within a class is so high and the variance between the two classes is so less.</li></ul><p><strong>There are two types of recognition challenges:</strong></p><ol><li>) Open-Set</li><li>) Closed-Set</li></ol><p>Closed-Set contains the same classes that were present in the training set and it’s like a normal classification problem which doesn’t require any special loss functions While Open-Set contains classes that weren’t present in the training set</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*nLw2APio1EuDzT3q3j73Rg.jpeg" /><figcaption>Example of the open-set and closed-set provided in the paper</figcaption></figure><p>So, you can notice that the task for both the types of recognition is extremely different. The classification problem is nothing but traditional problems like cats and dogs. The test set also contains cats and dogs pictures and not out-of-box classes.</p><blockquote><strong>Metric Learning </strong>problems are learning a distance function like euclidean distance and use it to classify out-of-box images. It involves the use of K-Nearest Neighbors to identify the image in the gallery which is similar to the one in the test.</blockquote><p>To increase the accuracy of the K-Nearest Neighbors, The aforementioned problems present in the dataset has to be tackled with some robust techniques. This is where <strong>SphereFace </strong>comes into the play and they were the pioneers of introducing an angular variant of softmax loss.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50a8821ef6f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How did I get my internship?]]></title>
            <link>https://medium.com/@gglrthiru/how-did-i-get-my-internship-90169fa47328?source=rss-6c58aa90b315------2</link>
            <guid isPermaLink="false">https://medium.com/p/90169fa47328</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[community]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[internships]]></category>
            <dc:creator><![CDATA[Thirumalai Kumar]]></dc:creator>
            <pubDate>Tue, 20 Oct 2020 03:57:06 GMT</pubDate>
            <atom:updated>2020-10-20T03:57:06.430Z</atom:updated>
            <content:encoded><![CDATA[<h3>How did I get my Internship offer in computer-vision</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*DnFljrS-0vX-WajpvXBOBA.jpeg" /></figure><p>I would be explaining how did I get my intern in the first part. This would help some people out there who are looking for internships. The second part will be about my project experiences which I got during my intern.</p><p>Applying for interns through online portals is tiresome and you won’t be getting perfect responses. There are some sites which also scam people by saying it’s paid but, won’t pay you money after your intern. Though I had some bad experiences, I was determined to get an intern in computer vision.</p><p>So, I thought of trying it on LinkedIn rather than job websites which I considered useless. I started being active on LinkedIn and emailing HRs and MD of some companies. The truth is I got replies from all of them who I mailed. I even had some interview sessions with them.</p><p>In India, The companies which are doing ML stuff are startups. The company which I got selected canceled the intern since they faced some financial issues and were on the edge of bankrupt. I was really worried about how could I start my career without an intern. But, At this time I was having a very good number of connections on LinkedIn.</p><p>A senior of mine helped me getting an intern at a company in Singapore. The MD himself interviewed by phone. I was the first person to join the company with experiences in computer vision and deep learning. Through these experiences, I got to know that LinkedIn is a perfect and best platform to get interns. Connections and networking are important aspects if you want to get into a company.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90169fa47328" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seizure Detection Using Machine Learning]]></title>
            <link>https://medium.com/analytics-vidhya/seizure-detection-using-machine-learning-35d5d1d0eab0?source=rss-6c58aa90b315------2</link>
            <guid isPermaLink="false">https://medium.com/p/35d5d1d0eab0</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[seizures]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Thirumalai Kumar]]></dc:creator>
            <pubDate>Fri, 24 Apr 2020 17:07:35 GMT</pubDate>
            <atom:updated>2020-04-24T17:07:35.053Z</atom:updated>
            <content:encoded><![CDATA[<h4>Conventional methods to advanced statistical machine learning method.</h4><blockquote>Hi guys!! I’m a computer science student who is so fond of deep learning. AI is revolutionizing the world by making tough conventional tasks into simpler ones. AI is thriving everywhere and of course, the very bio-medics where there are surfeit data that can be used to train a model. AI has done so many remarkable achievements in the medical field such as predicting glaucoma which is a very difficult task for a human and if not predicted at its earliest, it may cause even blindness.</blockquote><blockquote>So, here I am to tell another such tedious task which can be revolutionized by a deep learning approach.</blockquote><h3><strong>Problem</strong></h3><p>A seizure is a sudden, uncontrolled electrical disturbance in the brain. It can cause changes in your behaviour, movements, or feelings, and levels of consciousness. If you have two or more seizures or a tendency to have recurrent seizures, you have epilepsy. Epilepsy is one of the most common conditions affecting the brain. When counting both children and adults in the United States: About 5.1 million people in the United States have a history of epilepsy. About 3.4 million people in the United States have active epilepsy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*fgirf_asq5yiL-Ld1iEYIw.jpeg" /><figcaption>Seizure</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SOG-p2QhpM6KoJuUPC6f-Q.jpeg" /><figcaption>Hot map of Epileptic patients</figcaption></figure><p>The problem here is not merely a huge number of cases but also the methods used to monitor such patients are so tiresome and elusive.</p><h4>How do you assess for seizures?</h4><p>As of said above that these seizures are electrical disturbances in the brain, There are so many methods used to capture a seizure from the brain signals.</p><p>some of them are:</p><ol><li>) Electroencephalogram</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Y2D1ckonUGeKLkiueslYA.jpeg" /><figcaption>Electroencephalography</figcaption></figure><p>2.) Computerized tomography</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*cA7tmGZ3BTqNHryq4Nur3A.jpeg" /><figcaption>CT Scans</figcaption></figure><p>3.) MRI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cabk2zAyTJmWhj3GkE9fUw.jpeg" /><figcaption>MRI scans</figcaption></figure><p>The electroencephalogram is the one that is widely used across the globe. To diagnose these EEG records, the conventional way is the visual perception of these records by neurologists. Just imagine a single man who comprehensively analyzes the records of a single patient may take a day to classify and there are so many cases in the queue. Humans cannot see the statistical pieces of information inside the EEG record which a machine learning model can do.</p><p>This is the problem statement and the purpose of developing automation for seizure detection</p><h3>Introduction to our work:</h3><p>At present, there are so many works related to seizure detection in the deep learning arena and we are working to bring an optimized way of detection using Generative Adversarial Network.</p><p>This article is based on a task given to me during the training phase to fathom out the basic knowledge of the EEG data and concocting them to make it out in our deep learning project.</p><p>Here, In this task we make use of Stockwell transform and a shallow learner like the random forest,naive-Bayes, and decision tree.</p><p>I used Stockwell transform to preprocess the raw EEG data and transform it into a time-frequency matrix and train in the above-mentioned classifiers. With random forest, I got an accuracy near 99.6%.</p><p>The data set used here is <a href="http://epileptologie-bonn.de/cms/front_content.php?idcat=193&amp;lang=3"><strong>Bonn-database</strong></a></p><h3>Bonn-Dataset:</h3><p>This is the smallest dataset on seizures on the internet. The size would be around some Mbs.</p><p>It is divided into 5 sets:</p><ol><li>set A — Normal</li><li>set B — Normal</li><li>set C — Inter-Ictal</li><li>set D — Inter-Ictal</li><li>set E — Ictal</li></ol><p>Each set has 100 features with 4097 samples.</p><p>set A and set B are the EEG records from a healthy person while set C and set D are from seizure affected persons who are on the state between the normal and seizure. This state in between the normal and stroked is the inter-ictal. This is the stage where we can identify that the person is going to get a seizure. Ictal is the state when the seizure has arrived.</p><h3><strong>Stockwell Transform:</strong></h3><p>Before explaining S-Transform. There may be some questions with you like why do we need to transform the signals for analyzing, What do these transformations do to those signals?. Well I am here to answer those questions!.</p><h4>Why do we need to transform the signals?</h4><p>Mainly for convenience and economy. Many things that are difficult in one domain become trivial in another. For instance, a time-domain convolution which is necessary for filtering becomes a simple multiplication after a Fourier Transform. This is at the heart of most current digital communication technologies including LTE, WiFi, etc.</p><p>Another example can be noise removal in audio and video signals or signal compression as performed in codecs like mp3 and mp4. All of these are done by transforming (sometimes non-linearly) the incoming signal into different domains and taking only the important features.</p><p>On a broader level, you can even look at all artificial neural networks as performing non-linear transforms to an input signal before making decisions on the transformed output</p><h3>What do these transformations do to those signals?</h3><p>Transformation is nothing but changing from one domain to another. Like from the time domain to the frequency domain. These transformations change a signal from a time domain to frequency domain and vice-versa.</p><p>Here In our case S-transform is a time-frequency decomposition tool that transforms a signal to a time-frequency distribution. Time-frequency distribution portraits the changes in the frequency pattern concerning time. Using this distribution, time and frequency can be analyzed simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*IjodyJ2Gkkvn7uNJgMAC2Q.png" /></figure><p>t → Time</p><p>f → Frequency</p><p>x(t) is the input signal and the input signals are scaled using the Gaussian window function</p><p>w(t-τ, f) is the <a href="https://www.dsprelated.com/freebooks/sasp/Gaussian_Window_Transform.html">Gaussian window function</a> which is</p><p>given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*-M9KZpOjNuVQuws5TUw89g.png" /><figcaption>The Gaussian window function</figcaption></figure><p><strong>Window functions</strong> operate on a set of rows and return a single value for each row from the underlying query. The term <strong>window</strong> describes the set of rows on which the <strong>function</strong> operates. A <strong>window function</strong> uses values from the rows in a <strong>window</strong> to calculate the returned values.</p><p>Explaining the Gaussian window function may take some more time. I will explain it in my next blog. So, here you just imagine a function that operates over rows of matrices and returns the transformed values.</p><pre>&lt;script src=&quot;<a href="https://gist.github.com/ThiruRJST/e1b8a3850640c2badadf793d38d21955.js">https://gist.github.com/ThiruRJST/e1b8a3850640c2badadf793d38d21955.js</a>&quot;&gt;&lt;/script&gt;</pre><p>Preprocessing step of the raw EEG data to collect features that shallow learner can learn.</p><h3><strong>Machine learning part</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*v-1zMX7yqEf6vwZC8EDmiQ.png" /><figcaption>Subsets of Machine Learning</figcaption></figure><p>The main difference between the shallow learning and deep learning is that shallow learners depend on the features. On the other hand , deep learners extract the information or features from the scratch data and make perfect prediction models.</p><p>You can understand it here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1d82xaFcjoOotDOUiIngPw.jpeg" /><figcaption>Difference between Deep learning and Shallow learning</figcaption></figure><p>Here I have used random forest classifier which is a shallow learner. I used that because this was only a brush-up session to better understand the basics for my paper.Let’s dive into the learning session.</p><p>Random forest classifier is nothing but a voting based classification algorithm which is an ensemble method. A group of decision trees make up a random forest algorithm hence, it is called as ensemble method.</p><p>Let’s take a real-time example to better understand:</p><p>Now, In this pandemic situation we are all locked down inside our home.It’s really boring right.You decide to watch series but don’t know to choose the odd one out.So, you ask your friend <strong>X </strong>to suggest you some series. your friend <strong>X</strong> ask about the genre you like (may be romantic,action or thriller,etc;) →this is the feature that <strong>X </strong>takes to understand your taste.<strong>X </strong>suggests you some series to watch.But, you are now asking all of your friends like <strong>Y,Z,K,M </strong>to suggest some series.Your friends here form a group of decision trees and the information you both share decides the outcome. The method of shaping solution is based on <a href="https://towardsdatascience.com/cross-entropy-from-an-information-theory-point-of-view-456b34fd939d">information theory and cross entropy</a>. Let’s not dive so deep into it.</p><p>This is the basic way of how random forest classifier works.</p><pre>&lt;script src=&quot;<a href="https://gist.github.com/ThiruRJST/a7c9bf3e7b012a71b8e50a8b0a0f5c05.js">https://gist.github.com/ThiruRJST/a7c9bf3e7b012a71b8e50a8b0a0f5c05.js</a>&quot;&gt;&lt;/script&gt;</pre><p>The accuracy that I got using random forest classifier is 99.5%</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*sWZjgPjC-HlcxjirUQAxyg.png" /><figcaption>Accuracy</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35d5d1d0eab0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/seizure-detection-using-machine-learning-35d5d1d0eab0">Seizure Detection Using Machine Learning</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>