<?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 Ritik Nandwal on Medium]]></title>
        <description><![CDATA[Stories by Ritik Nandwal on Medium]]></description>
        <link>https://medium.com/@nandwalritik?source=rss-3d8aed4265e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gZCbQ_VlxkPeZ-urLDUGJg.jpeg</url>
            <title>Stories by Ritik Nandwal on Medium</title>
            <link>https://medium.com/@nandwalritik?source=rss-3d8aed4265e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:09:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nandwalritik/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[Getting Started with Open Source: A Beginner’s Guide]]></title>
            <link>https://medium.com/@nandwalritik/getting-started-with-open-source-a-beginners-guide-57a69b178a2c?source=rss-3d8aed4265e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/57a69b178a2c</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[contribution]]></category>
            <dc:creator><![CDATA[Ritik Nandwal]]></dc:creator>
            <pubDate>Wed, 07 May 2025 07:15:40 GMT</pubDate>
            <atom:updated>2025-05-07T07:25:17.355Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>When I first heard about open source, I imagined it was something only experienced developers contributed to.</p><p>Like many beginners, I hesitated at first. I didn’t know where to start, what project to choose.</p><p>This guide is what I wish I had when I started out. It’s a beginner-friendly walk through of how to get started with open source, how to pick the right projects, how to make meaningful contributions, and how to grow through the process. Whether you’re a student, a self-taught developer, or just curious about giving back, this article will help you take your first step into the world of open source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*UzsiRpQi-hQ1agCGqLXr_w.png" /><figcaption>Open Source</figcaption></figure><h3>Choosing Language and Filtering Projects</h3><p>One of the first challenges I faced was choosing the right programming language and finding a project that matched my skill level. With thousands of open source repositories out there, it’s easy to feel overwhelmed. But here’s what helped me simplify the process.</p><h4>Start with What You Know (or Want to Learn)</h4><p>I began by listing the languages I was comfortable with ,Python in my case and looking for projects that used them. If you’re still learning a language, that’s perfectly fine. Open source is a great way to learn by doing. Some contributors even pick projects in a language they want to learn and improve through real-world practice.</p><h4>Filter by Relevance and Interest</h4><p>Your motivation will stay stronger if you work on something that genuinely interests you. For example, I love working on python and machine learning, so I filtered projects related to those domains. GitHub lets you search by topic tags (like machine-learning, web-dev, data-viz, etc.), which makes it easier to find relevant projects.</p><h4>Look for Beginner-Friendly Projects</h4><p>Some projects are better for newcomers than others. I looked for repositories that had</p><ul><li>A welcoming README and clear contributing guidelines</li><li>Issues labeled good first issue or help wanted</li><li>Active maintainers who responded to pull requests or discussions</li></ul><h4>Check Project Activity</h4><p>An important lesson I learned early on was to check if the project is actively maintained. Look at how recent the last commits or pull requests are. If a repo hasn’t been touched in over a year, your contributions might go unnoticed.</p><h3>Steps to Contribute</h3><p>After you have selected a project of your choice, there are certain common steps for every project.</p><ol><li>Read the README.md, explore the documentation, check open issues, and browse through the codebase a little. This helps you get a sense of how things are organized. Almost every project which promotes open source contribution has a CONTRIBUTING.md it has all the steps to contribute to that specific project.</li><li>First fork that project and set it up on your local, you can easily find setup instructions in the repository guidelines or even documentations.</li><li>Now Search for beginner friendly issues, they are usually tagged with good-first-issue or similar tags. . If you’re unsure about what to do, don’t hesitate to comment and ask for clarification.</li><li>After you have identified the issue you want to work on, create a new branch with a self-descriptive name, and now you can make your changes, make sure you follow the contribution guidelines while making changes.</li><li>Once changes are done push your changes to your branch and raise a PR.</li></ol><h3>Benefits of Contributing</h3><p>Contributing to open source can have lots of benefits like :</p><ol><li>Improves your coding, collaboration, and problem-solving skills.</li><li>Real-world contributions look great on resumes and GitHub profiles.</li><li>Helps to Connect with developers, mentors, and communities worldwide.</li><li>Its kind of giving back to the community by improving tools and libraries you already use.</li><li>It Boosts career opportunities many hiring managers value open source experience.</li></ol><h3>Conclusion</h3><p>Contributing to open source might seem intimidating at first, but it’s one of the most rewarding ways to learn, grow, and connect with a global community. You don’t need to be an expert to start ,you just need curiosity, patience, and a willingness to learn. Whether you’re fixing a bug, improving documentation, or just opening your first issue, every contribution matters.</p><p>Start small, stay consistent, and over time, you’ll not only improve your skills but also become part of something much bigger.</p><p>At the end I have shared some open source projects which I personally explored/contributed to along with the resources that might be useful while contributing, please check them out.</p><h3>Resources</h3><ul><li><a href="https://github.com/huggingface/transformers/">https://github.com/huggingface/transformers/</a></li><li><a href="https://github.com/huggingface/datasets/">https://github.com/huggingface/datasets/</a></li><li><a href="https://github.com/apache/superset">https://github.com/apache/superset</a></li><li><a href="https://github.com/Lightning-AI/pytorch-lightning">https://github.com/Lightning-AI/pytorch-lightning</a></li><li><a href="https://education.github.com/git-cheat-sheet-education.pdf">https://education.github.com/git-cheat-sheet-education.pdf</a></li><li><a href="https://www.atlassian.com/git/tutorials/rewriting-history/git-rebase">https://www.atlassian.com/git/tutorials/rewriting-history/git-rebase</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57a69b178a2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Concurrency in Go]]></title>
            <link>https://medium.com/@nandwalritik/mastering-concurrency-in-go-65780d45bc9f?source=rss-3d8aed4265e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/65780d45bc9f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Ritik Nandwal]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 13:33:12 GMT</pubDate>
            <atom:updated>2025-04-14T13:33:12.259Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Scalable distributed system have performance as one of the most important metric. Applications are expected to be fast, responsive and capable of handling multiple tasks simultaneously, whether its processing user request, handling file I/O or managing network calls. This is where concurrency comes into play.</p><p><strong>Golang </strong>developed by google,was designed with concurrency as one of its prime objective. In this article we will walk through the basic concepts of concurrency in Go, and how to implement them. So lets get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*kCPHTH0IUFJDDdKnVCHeZg.png" /></figure><h3>What are Goroutines?</h3><p>If you have ever heard about concurrency in golang, you must have came across this most commonly used term goroutine.</p><p>A goroutine is a lightweight thread of execution managed by Go runtime.</p><p>If we want to understand it in simple terms a goroutine is any function in golang which is preceded by keyword <strong>go</strong>.</p><h4>But what makes goroutines special?</h4><p>They are extremely lightweight, starts with a very small stack and grows/shrinks dynamically as needed. Goroutines are scheduled and managed by the Go runtime.</p><p>When a goroutine is created, it runs independently of the main function’s execution. However, if the main function finishes before the goroutines completes their tasks, those goroutines will be terminated abruptly they don’t get a chance to finish.</p><p>To ensure that all goroutines complete their execution, Go provides two common approaches:</p><ul><li>Using <strong>Channels</strong></li><li>Using <strong>WaitGroups</strong></li></ul><p>We’ll dive deeper into both of these in the upcoming sections.<br>But before that, let’s build a strong foundation by understanding the difference between concurrency and parallelism.</p><h3>Concurrency vs Parallelism in Go</h3><p>When we start exploring goroutines, one common confusion often arises: whether its concurrent or parallel. Lets break it down.</p><h4><strong>Concurrency</strong></h4><p>It is about dealing with a lot of things at once, even if they are not happening at same time. Let’s understand it with below example.</p><p>Think of it like a single chef who is cooking multiple dishes, switching between them based on priority or when something is idle.</p><p>Similarly Go uses goroutines to switch between tasks efficiently even if our machine has a single core.</p><h4>Parallelism</h4><p>It is when our program literally performs multiple tasks at the same time(using multiple CPU cores). Understand it with the same example, we took above.</p><p>Imagine multiple chefs in the kitchen, each working on a different dish at the same time.</p><p>Go can achieve this when you run goroutines on a multi-core system, with Go’s runtime scheduler automatically distributing work across available cores.</p><blockquote>Go gives you <strong>concurrency by default</strong> with goroutines and channels.<br> It can also <strong>scale to parallelism</strong> when needed using runtime.GOMAXPROCS to control how many OS threads (and CPU cores) are used.</blockquote><blockquote>We write the same code, Go handles the rest under the hood.</blockquote><h3>Understanding Channels</h3><p>In Go, channels can be thought of as communication links between goroutines or between a goroutine and the main function, that can be used to safely transfer data between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*JlP_Pa3dMYPTSZ6ak7dInA.png" /><figcaption>Channels In Go</figcaption></figure><p>In the Code snippet below:</p><ul><li>A <strong>channel</strong> is created using make(chan datatype).</li><li>The sayHi goroutine <strong>sends data</strong> into the channel using ch &lt;- &quot;Hi from Goroutine!&quot;.</li><li>The main function <strong>receives data</strong> from the channel using msg := &lt;-ch</li></ul><p>This allows communication between the goroutine and the main function in a safe and synchronized manner.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func sayHi(ch chan string) {<br>    ch &lt;- &quot;Hi from Goroutine!&quot;<br>}<br><br>func main() {<br>    ch := make(chan string)      // Creating a channel<br>    go sayHi(ch)                 // Starting a goroutine<br>    msg := &lt;-ch                  // Receiving data from channel<br>    fmt.Println(msg)<br>}<br></pre><blockquote>Note: The main function will wait until it receives a value from the goroutine, preventing the program from exiting early.</blockquote><h4>Types of Channels</h4><p><strong>Unbuffered Channels</strong> → Unbuffered channel is a channel that can be used for both sending and receiving but doesn’t have a buffer to store data. This means that when a goroutine sends data to an unbuffered channel, the data is not stored in a buffer, but is instead immediately passed to the goroutine that is trying to receive data from the channel. Similarly, when a goroutine receives data from an unbuffered channel, it blocks until data is available to be received.</p><pre>package main<br>import &quot;fmt&quot;<br><br>func sayHi(ch chan string){<br> ch &lt;- &quot;Hi from Goroutine!&quot; <br>}<br><br>func main(){<br> ch := make(chan string)<br> go sayHi(ch)<br> msg := &lt;-ch<br> fmt.Println(msg)<br>}</pre><blockquote>Note if we remove the receiver(the msg :=&lt;-ch) the program will hang, because the sender will be waiting for someone to receive it.</blockquote><p><strong>Buffered Channels → </strong>It lets the sender to push the data into the channel <strong><em>even if no receiver is ready</em></strong>, as long as there is space in the buffer.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br>)<br><br>func main() {<br> ch := make(chan string, 2) // buffer size 2<br><br> ch &lt;- &quot;Hello&quot;<br> ch &lt;- &quot;Gopher&quot;<br> <br> // h &lt;- &quot;Overflow&quot; // uncommenting this will block here (deadlock)<br><br> fmt.Println(&lt;-ch)<br> fmt.Println(&lt;-ch)<br>}</pre><p><strong>Send-Only and Receive-Only Channels → </strong>There can be certain cases in which we just want to only send or only receive data in channels, for them we can use send-only or receive-only channels.</p><pre>func sendData(ch chan&lt;- int) {<br>    ch &lt;- 10<br>}<br><br>func receiveData(ch &lt;-chan int) {<br>    fmt.Println(&lt;-ch)<br>}</pre><h3>WaitGroups: Synchronizing Goroutines</h3><p>In Go, a WaitGroup is used to wait for multiple goroutines to finish executing. It is provided by the sync package.</p><p>It ensures that our program waits for a collection of goroutines to finish executing, preventing premature exits or progression while goroutines are still running.</p><p>We can implement it using sync.WaitGroup from the sync package. It includes Add(), Done() and Wait methods.</p><ol><li><strong>Add → </strong>It maintains a counter for the number of goroutines.</li><li><strong>Done → </strong>It decrements the counter by 1. This method is called by a goroutine when it finishes its task.</li><li><strong>Wait</strong> → The wait method blocks execution in main until all added goroutines have called Done.</li></ol><p>Let us understand it with the help of following example.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br>)<br><br>func worker(id int, wg *sync.WaitGroup) {<br> defer wg.Done() // mark this goroutine as done when it finishes<br> fmt.Printf(&quot;Worker %d starting\n&quot;, id)<br> // simulate some work<br> fmt.Printf(&quot;Worker %d done\n&quot;, id)<br>}<br><br>func main() {<br> var wg sync.WaitGroup<br><br> for i := 1; i &lt;= 3; i++ {<br>  wg.Add(1) // register one goroutine<br>  go worker(i, &amp;wg)<br> }<br><br> wg.Wait() // block until all registered goroutines call Done()<br> fmt.Println(&quot;All workers finished&quot;)<br>}</pre><blockquote>Note: Always use defer wg.Done() at the <strong>start of the goroutine</strong> to ensure it runs <strong>even if the goroutine panics or returns early</strong>.</blockquote><h3>Channels vs WaitGroups: When to Use What?</h3><p>Both channels and WaitGroups help us to coordinate goroutines. We can use channels when we want to exchange data between goroutines whereas WaitGroups can be used when we want to wait for a group of goroutines to complete without sharing data between them.</p><p>We can even <strong>combine both</strong> when needed, for example, using <strong>WaitGroups to synchronize completion</strong> and <strong>channels to collect results</strong> from multiple concurrent tasks.</p><h3>Advanced Concepts in Go Concurrency</h3><p>Once you are comfortable with goroutines, channels and WaitGroups, Go offers some advanced concepts. We will try to cover them in short</p><h4><strong>Select Statement</strong></h4><p>Go’s select statement lets a goroutine <strong>wait on multiple channel operations</strong>. It’s like a switch, but for channels. It executes <strong>the first case that’s ready</strong>. Example</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br><br>func sendData(ch chan string, message string, delay time.Duration) {<br> time.Sleep(delay)<br> ch &lt;- message<br>}<br><br>func main() {<br> ch1 := make(chan string)<br> ch2 := make(chan string)<br><br> // Start two goroutines<br> go sendData(ch1, &quot;Message from ch1&quot;, 2*time.Second)<br> go sendData(ch2, &quot;Message from ch2&quot;, 1*time.Second)<br><br> select {<br> case msg1 := &lt;-ch1:<br>  fmt.Println(&quot;Received:&quot;, msg1)<br> case msg2 := &lt;-ch2:<br>  fmt.Println(&quot;Received:&quot;, msg2)<br> }<br>}</pre><p>This is especially useful when working with <strong>timeouts</strong>, <strong>fan-in/fan-out patterns</strong>, or when <strong>multiple sources</strong> may produce data.</p><h4><strong>sync.Once</strong></h4><p>It ensures that a block of code runs <strong>exactly once, </strong>even if its called by <strong>multiple goroutines.</strong></p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br> &quot;time&quot;<br>)<br><br>var once sync.Once<br><br>func initialize() {<br> fmt.Println(&quot;Initialized&quot;)<br>}<br><br>func main() {<br> for i := 0; i &lt; 5; i++ {<br>  go func() {<br>   once.Do(initialize)<br>  }()<br> }<br><br> time.Sleep(time.Second) // wait for goroutines<br>}</pre><h4><strong>sync.Mutex</strong></h4><p>When multiple goroutines access and modify shared memory (e.g., a counter or a map), it can lead to <strong>race conditions</strong>. Go provides the sync.Mutex to safely lock and unlock critical sections of code.</p><pre>package main<br><br>import (<br> &quot;sync&quot;<br>)<br><br>func main() {<br> var mu sync.Mutex<br> counter := 0<br><br> go func() {<br>  mu.Lock()<br>  counter++<br>  mu.Unlock()<br> }()<br>}</pre><h3>Conclusion</h3><p>In this article, we explored the building blocks of Go’s concurrency model: goroutines, channels, and WaitGroups, and went deeper into tools like select, sync.Once, and sync.Mutex. I would highly recommend to try it on your own and try to use the above concepts which you have learned.</p><p>I have shared some resources at the end, I hope that will help.</p><h3>Resources</h3><ol><li><a href="https://go.dev/doc/">https://go.dev/doc/</a></li><li><a href="https://youtu.be/8uiZC0l4Ajw?si=L6TZ5wVrxk_29hXs">https://youtu.be/8uiZC0l4Ajw?si=L6TZ5wVrxk_29hXs</a></li><li><a href="https://www.scalent.io/golang/waitgroups-in-golang-in-detail/">https://www.scalent.io/golang/waitgroups-in-golang-in-detail/</a></li><li><a href="https://medium.com/goturkiye/concurrency-in-go-channels-and-waitgroups-25dd43064d1">https://medium.com/goturkiye/concurrency-in-go-channels-and-waitgroups-25dd43064d1</a></li><li><a href="https://bwoff.medium.com/the-comprehensive-guide-to-concurrency-in-golang-aaa99f8bccf6">https://bwoff.medium.com/the-comprehensive-guide-to-concurrency-in-golang-aaa99f8bccf6</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65780d45bc9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Kafka : The Backbone of Modern Distributed Systems]]></title>
            <link>https://medium.com/@nandwalritik/apache-kafka-the-backbone-of-modern-distributed-systems-175d80dd20f4?source=rss-3d8aed4265e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/175d80dd20f4</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Ritik Nandwal]]></dc:creator>
            <pubDate>Mon, 07 Apr 2025 17:05:03 GMT</pubDate>
            <atom:updated>2025-04-07T17:05:03.781Z</atom:updated>
            <content:encoded><![CDATA[<h3>Apache Kafka : The Backbone of Modern Distributed Systems</h3><h3>Introduction</h3><p>If you’re in a senior engineering role or even just starting your software journey, you’ve probably come across system design discussions.<br>Whether its a data pipeline at netflix or a messaging system at uber there is this one common thing which is used almost in every architecture: <strong>Apache Kafka.</strong></p><p>But what exactly is Kafka? Why does it show up in so many system architectures? And how does it even manage to scale so effortlessly across huge workloads?</p><p>In this post, we will follow a top-down approach to learn kafka’s working. Instead of jumping straight into brokers, partitions, or storage internals we’ll start by following the actual flow of data i.e from producer, into the Kafka cluster, and finally to the consumer group. Then we’ll slowly peel back the layers to understand the core components that make Kafka reliable, scalable, and fault-tolerant.</p><h3>Kafka Architecture</h3><p>Let us begin with the simplest question: What happens when we want to send some data through kafka.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*1oE-jU-OG0ldGk-PIvQ-aw.png" /><figcaption>Message Flow</figcaption></figure><p>It involves three main components:</p><ul><li><strong>Producer </strong>→ publishes the data to the kafka.</li><li><strong>Kafka Cluster</strong> → Stores and distributes the data.</li><li><strong>Consumer Group</strong> → Reads and processes the data.</li></ul><h4><strong>Kafka Cluster</strong></h4><p>Kafka cluster is the core of the system, it receives the messages from producers, stores them and makes them available to consumers.</p><p>It consists of<strong> multiple brokers</strong>, each broker in a cluster is identified by a unique id . Each broker <strong>manages a set of topics </strong>and each topic is further divided into partitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*sSXhW7Lo1FtyEV5Mrj7gjg.png" /><figcaption>Kafka Cluster</figcaption></figure><p>Let’s break down each of these components (as shown in the diagram above):</p><p><strong>Broker → </strong>It is a single kafka server, which receives data from producer, stores it on disk and serves it to consumers. A Kafka cluster typically runs multiple brokers working together to ensure <strong>scalability and fault tolerance</strong>.</p><blockquote>When we say “Kafka Cluster stores data”, what we really mean is:</blockquote><blockquote>Each broker stores the data on disk (not just in memory), inside a log file per partition.</blockquote><blockquote>These logs are persisted and replicated (based on replication factor) to ensure durability and fault tolerance.</blockquote><blockquote>Kafka keeps this data for a configurable amount of time (e.g., 7 days) or until a size limit is reached this is not tied to whether the data has been consumed or not.</blockquote><p><strong>Topic </strong>→ It is a <strong>named stream</strong> of data. Producers publish messages to topic and consumers subscribe to them to read data.</p><p><strong>Partition </strong>→ Each topic is split into one or more partitions. A partition is an ordered, immutable log of messages. Each message in a partition has a unique <strong>offset</strong> that acts like a message ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*lvuAc4bT4QELmi9yid0w4A.png" /><figcaption>Partition Leader — <a href="https://www.educba.com/kafka-replication/">https://www.educba.com/kafka-replication/</a></figcaption></figure><p><strong>Leader and Replicas →</strong> Each partition has one <strong>leader</strong> and zero or more <strong>replicas</strong>. The leader handles <strong>all reads and writes</strong> for that partition. Other brokers may hold replicas (followers) of the same partition to ensure <strong>high availability</strong>. If a leader broker goes down, Kafka automatically performs <strong>leader election</strong> to promote one of the in-sync replicas as the new leader — ensuring seamless recovery.</p><p>At high level, <strong>kafka</strong> acts like a distributed commit log. It <strong>doesn’t push data to consumers</strong>. It <strong>hold onto it and waits for consumers to pull messages</strong> at their own pace.</p><h4><strong>Producer</strong></h4><p>A producer is any application or service that sends data(messages or events) to kafka topics. Messages are stored in the form of <strong>key-value</strong> in the partitions of a topic.</p><p>When sending a message the producer needs to choose a partition, it can be done in two ways:</p><ul><li><strong>If a key is provided </strong>→ Kafka <strong>uses a hash of the key</strong> to pick a partition. This ensures ordering for messages with same key.</li><li><strong>If no key is provided </strong>→ Kafka simply <strong>uses a round-robin</strong> strategy to balance messages across the partitions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*BE99wnm6rwPaCyuECkvDZw.png" /><figcaption>Receiving Data Acknowledgement</figcaption></figure><p>Kafka allows producers to specify <strong>how many acknowledgements</strong> they require from the broker before considering a message successfully sent. This is controlled using the acks setting</p><ul><li>acks=0 → The producer doesn’t wait for any acknowledgment. Fastest, but least reliable.</li><li>acks=1 → The producer waits for a response from the leader broker only. A good balance between performance and reliability.</li><li>acks=all (or -1) → The producer waits for the message to be replicated to all in-sync replicas (ISRs). Most reliable, but also the slowest.</li></ul><p>Additionally, Kafka producers handle <strong>automatic load balancing </strong>distributing messages across partitions based on keys or strategies and can retry sending messages in case of transient errors.</p><h4><strong>Consumer Group and Consumers</strong></h4><p>While producers write data into kafka, <strong>consumers </strong>are the component that read it. But kafka doesn’t just serve consumers individually , it introduces a powerful concept: consumer groups.</p><p>A <strong>consumer group</strong> is a set of consumers that work together to read data from a Kafka topic. The group ensures that:</p><ul><li>Each partition is read by only one consumer in the group.</li><li>Multiple consumers can process data in parallel by splitting partitions.</li><li>Kafka tracks the progress of each group via <strong>offsets(</strong><em>An </em><strong><em>offset</em></strong><em> is a unique ID that Kafka assigns to every message within a partition. It acts like a bookmark keeping track of which messages a consumer has already read</em><strong>)</strong></li></ul><p>This way we can ensure parallel processing of records from a topic and be sure that your consumers won’t be stepping on each other toes.</p><p>Each topic consists of one or more partitions. When a new consumer is started it will join a consumer group (this happens under the hood) and Kafka will then ensure that each partition is consumed by only one consumer from that group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*jCsKpaFKa701bjSqsUyzJg.png" /><figcaption>Single Consumer in Consumer Group - <a href="https://codingharbour.com/apache-kafka/what-is-a-consumer-group-in-kafka/">https://codingharbour.com/apache-kafka/what-is-a-consumer-group-in-kafka/</a></figcaption></figure><p>After another consumer joins the same group, each consumer would continue consuming only one partition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*3jPJ7oUtQuqdgVBIUQ50OA.png" /><figcaption>Multiple Consumers in One Consumer Group - <a href="https://codingharbour.com/apache-kafka/what-is-a-consumer-group-in-kafka/">https://codingharbour.com/apache-kafka/what-is-a-consumer-group-in-kafka/</a></figcaption></figure><p>If the number of consumers in a group is more than the number of partitions, extra consumers will sit idle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*oORrbmd9-BW42h0Ut0OWtw.png" /><figcaption>Additional Consumer Sits Idly - <a href="https://codingharbour.com/apache-kafka/what-is-a-consumer-group-in-kafka/">https://codingharbour.com/apache-kafka/what-is-a-consumer-group-in-kafka/</a></figcaption></figure><p><strong>What if I want multiple consumers to read the same data?</strong></p><p>If we want multiple consumers to independently consume the same records from a topic, just make sure each one belongs to a <strong>different consumer group</strong> (i.e., they have different group IDs). Kafka will treat them as separate subscribers and deliver all messages to each group individually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*-KGr1DJiyIg6zLybFjSfUg.png" /><figcaption>Multiple Consumers Reading Same Record From the Topic - <a href="https://codingharbour.com/apache-kafka/what-is-a-consumer-group-in-kafka/">https://codingharbour.com/apache-kafka/what-is-a-consumer-group-in-kafka/</a></figcaption></figure><p>This entire orchestration how partitions are assigned, how consumers coordinate, how leadership is managed is all part of what makes Kafka a distributed system that’s both fast and reliable. But this coordination doesn’t happen magically. Behind the scenes, Kafka traditionally relied on <strong>Apache ZooKeeper</strong>(uptil version 2.8) to handle critical tasks like broker metadata, leader election, and health monitoring.</p><p>Starting with <strong>Kafka 2.8</strong>, support for running Kafka <strong>without ZooKeeper</strong> was introduced in <strong>early access</strong>, and as of <strong>Kafka 3.3+</strong>, the <strong>KRaft mode (Kafka Raft)</strong> is considered <strong>production-ready</strong>, aiming to completely eliminate the need for ZooKeeper in the near future.</p><p>I hope by now if you have reached till here, you might have gained some basic working of kafka, at the end I have attached some of the resources which can help to dive even deeper.</p><h3>Resources</h3><ol><li><a href="https://www.confluent.io/blog/apache-kafka-intro-how-kafka-works/">https://www.confluent.io/blog/apache-kafka-intro-how-kafka-works/</a></li><li><a href="https://youtube.com/playlist?list=PLa7VYi0yPIH0KbnJQcMv5N9iW8HkZHztH&amp;si=Y34zj71WelnrUnw9">https://youtube.com/playlist?list=PLa7VYi0yPIH0KbnJQcMv5N9iW8HkZHztH&amp;si=Y34zj71WelnrUnw9</a></li><li><a href="https://medium.com/swlh/apache-kafka-what-is-and-how-it-works-e176ab31fcd5">https://medium.com/swlh/apache-kafka-what-is-and-how-it-works-e176ab31fcd5</a></li><li><a href="https://medium.com/@cobch7/kafka-producer-and-consumer-f1f6390994fc">https://medium.com/@cobch7/kafka-producer-and-consumer-f1f6390994fc</a></li><li><a href="https://codingharbour.com/apache-kafka/what-is-a-consumer-group-in-kafka/">https://codingharbour.com/apache-kafka/what-is-a-consumer-group-in-kafka/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=175d80dd20f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG From Scratch]]></title>
            <link>https://medium.com/@nandwalritik/rag-from-scratch-d01458bc641a?source=rss-3d8aed4265e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d01458bc641a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[vector-database]]></category>
            <dc:creator><![CDATA[Ritik Nandwal]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 09:11:12 GMT</pubDate>
            <atom:updated>2024-11-12T09:11:12.585Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>LLM’s have limited knowledge on the data, for which it was trained on. If we want to query some information, on which LLM was not trained on, it won’t be able to answer the queries.</p><p>RAG(Retrieval Augmented Generation) is a methodology which helps in providing the knowledge base access to an LLM, which can further enhance an LLM’s capability.</p><p>RAG as a simple pipeline consisting of three major steps <a href="#8bd1"><strong>Indexing</strong></a>, <a href="#6a89"><strong>Retrieval and Generation</strong></a>. We will go through each part in detail in the upcoming section of the article.</p><h3>Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*W-1v9D1xHC-ZiVCosYES0A.png" /><figcaption>RAG Architecture</figcaption></figure><p>The RAG pipeline consists of three steps Indexing(used to load the document in vector DB), Retrieval(fetch the relevant docs as per the user query) and Generation(uses the fetched documents as context for passing the user query to an LLM).</p><h4>Indexing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YfQ7OR1lUALunoNy.png" /><figcaption>Indexing</figcaption></figure><p>Indexing consists of :-</p><ul><li><strong>Load the documents</strong> → Documents could be of different type like pdf, doc, txt or even an html page. We can load them using different document loaders available in langchain.</li><li><strong>Split them into chunks</strong> → Large documents might not fit into the input size of current LLM’s. Splitting them into chunks improve the retrieval accuracy by allowing a model to focus on specific part of the text.</li><li><strong>Generate Embeddings</strong>(for each chunk) → An embedding is a vector representation of text captures its semantic meaning. These embedding are important because vector db uses them to search and retrieve relevant documents.</li><li><strong>Store them to a vector DB </strong>→ It involves dumping the embeddings along with their metadata to a vector DB (chromaDB,qdrant etc).</li></ul><pre>#### INDEXING ####<br># 1.) Loading the documents<br>import bs4<br>from langchain_community.document_loaders import WebBaseLoader<br>loader = WebBaseLoader(<br>    web_paths=(&quot;https://lilianweng.github.io/posts/2023-06-23-agent/&quot;,),<br>    bs_kwargs=dict(<br>        parse_only=bs4.SoupStrainer(<br>            class_=(&quot;post-content&quot;, &quot;post-title&quot;, &quot;post-header&quot;)<br>        )<br>    ),<br>)<br>blog_docs = loader.load()<br># 2.) Splitting<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>text_splitter = RecursiveCharacterTextSplitter(<br>    # Set a really small chunk size, just to show.<br>    chunk_size=100,<br>    chunk_overlap=20<br>)<br>splits = text_splitter.split_documents(blog_docs)<br># 3.) Intialize Embeddings<br>from langchain_huggingface import HuggingFaceEmbeddings<br>model_name = &quot;sentence-transformers/all-mpnet-base-v2&quot;<br>model_kwargs = {&#39;device&#39;: &#39;cpu&#39;}<br>encode_kwargs = {&#39;normalize_embeddings&#39;: False}<br>embeddings = HuggingFaceEmbeddings(<br>    model_name=model_name,<br>    model_kwargs=model_kwargs,<br>    encode_kwargs=encode_kwargs<br>)<br># 4.) Initialize Vector Store<br>from langchain_chroma import Chroma<br>vector_store = Chroma(<br>    collection_name=&quot;rag_scratch_web&quot;,<br>    embedding_function=embeddings,<br>    persist_directory=&quot;./chroma_langchain_db&quot;<br>)<br># 5.) Storing Them To Vector DB<br>from tqdm import tqdm<br>print(&quot;Indexing documents...&quot;)<br>for doc in tqdm(splits, desc=&quot;Indexing&quot;, unit=&quot;doc&quot;):<br>    vector_store.add_documents([doc])</pre><h4>Retrieval and Generation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q-M73pMFu4wNNCwe.png" /><figcaption>Retrieval Relevant Doc and Generate Output</figcaption></figure><p><strong>Retrieval</strong></p><p>Retrieval is the process of fetching the top-k most semantically relevant documents from a vector store based on the user query. This is achieved using embeddings that represent both the documents and query in a shared semantic space for similarity-based search. The retriever object is initialized from the vector store, and the number of documents to fetch (k) is configurable via search_kwargs.</p><pre>retriever = vector_store.as_retriever(search_kwargs={&quot;k&quot;:1})<br>query = &quot;What is task decomposition&quot;<br>results = retriever.get_relevant_documents(query)<br>print(results)</pre><p><strong>Generation</strong></p><p>Generation refers to prompting a Large Language Model (LLM) with a template that includes placeholders for the retrieved context and the user query. The LLM uses this context along with its pre-trained knowledge to generate a detailed response. In this implementation, we use &quot;llama3.2:1b&quot; for the generation step.</p><pre># 1.) Initializing LLM<br>from langchain_ollama import ChatOllama<br>local_llm = &quot;llama3.2:1b&quot;<br>llm = ChatOllama(model=local_llm,temperature=0)<br><br># 2.) Initializing Prompt<br>from langchain.prompts import ChatPromptTemplate<br>template = &quot;&quot;&quot;Answer the question based only on the following context:<br>{context}<br>Question: {question}<br>&quot;&quot;&quot;<br>prompt = ChatPromptTemplate.from_template(template)</pre><h3>RAG Chain</h3><p>The Retrieval-Augmented Generation (RAG) chain integrates the retrieval and generation steps into a unified pipeline. The retriever fetches relevant documents, which are then used as context in the prompt passed to the LLM. This approach allows for generating responses grounded in external knowledge (retrieved documents) while leveraging the generative capabilities of the LLM.</p><pre># 3.) Creating A RAG Chain<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import RunnablePassthrough<br><br>rag_chain = (<br>    {&quot;context&quot;:retriever,&quot;question&quot;:RunnablePassthrough()}<br>    | prompt<br>    | llm<br>    | StrOutputParser()<br>)<br># 4.) Generating Response For Query<br>query = &quot;What is task decomposition, please explain in detail in points&quot;<br>rag_chain.invoke(query)</pre><h3>References</h3><ul><li><a href="https://www.langchain.com/">Langchain Documentation</a></li><li><a href="https://github.com/langchain-ai/rag-from-scratch/blob/main/rag_from_scratch_1_to_4.ipynb">RAG from scratch</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d01458bc641a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformer From Scratch In Pytorch]]></title>
            <link>https://medium.com/@nandwalritik/transformer-from-scratch-in-pytorch-8939d2b5b696?source=rss-3d8aed4265e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8939d2b5b696</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Ritik Nandwal]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 06:28:03 GMT</pubDate>
            <atom:updated>2024-09-05T06:28:03.996Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Implementing transformer architecture from scratch is as important as understanding it theoretically, In my previous article I have covered the theoretical explanation on transformer and its working. In this article we will be implementing a transformer from scratch in pytorch and then train it on a very small dataset for Neural Machine Translation task.</p><p>If you have not read my previous article please give it a read.</p><p><a href="https://medium.com/@nandwalritik/attention-is-all-you-need-understanding-transformers-8acc3aa93de7">Attention Is All You Need: Understanding transformers</a></p><p>To keep the flow easily understandable, first we will code each component and in the end we can combine them together.</p><h3>Components</h3><p>Let’s code the components in the order of their usage.</p><p>A transformer block consists of an Encoder and a Decoder , both of them rely on <a href="#ab9f"><strong>Attention mechanism</strong></a> and a <a href="#78dd"><strong>Feed Forward layer</strong></a>.</p><p>The <a href="#ce8e"><strong>Encoder</strong></a><strong> </strong>and <a href="http://425a/"><strong>Decoder</strong></a><strong> </strong>can be finally used to form a <a href="#327d"><strong>Transformer</strong> </a>Block.</p><h4>Attention</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*YpzaRidefJqINRuJgsRv3g.png" /><figcaption>1. Scaled Dot Product Attention | 2. Multi-Attention</figcaption></figure><p>It takes Q, K, V vectors as input which are passed through linear layers before applying the scaled dot product attention. The output is then concatenated and then passed through a linear layer.</p><blockquote>Note: In the original paper the dimension of W_Q_i, W_K_i and W_V_i was (d_model,d_k), where the value of i is from 0 to num_of_heads . So finally stacking up the vectors W_Q_i’s it will result into a vector of dimension (d_model,d_model).</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63e11d1eb51abb0a0f53ffaf3c1797b8/href">https://medium.com/media/63e11d1eb51abb0a0f53ffaf3c1797b8/href</a></iframe><h4>Position Wise Feed Forward</h4><p>The output of multihead attention layer is passed through a feed forward layer, in both encoder and decoder blocks. It consists of two linear transformations with a ReLU activation in between.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55a8f9a61a3934b37c1ac42be7468886/href">https://medium.com/media/55a8f9a61a3934b37c1ac42be7468886/href</a></iframe><p>Now let’s code the encoder layer and decoder layer which will further be used to form the encoder and decoder blocks.</p><h4>Encoder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*dFYAQ8FTTeIgB2iJ9oEkhA.png" /><figcaption>Encoder Layer</figcaption></figure><p>The input tokens are used to find the input embedding, and since they don’t carry any information regarding their positions, we need to add positional encoding to them, which can be calculated using below formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*_Qxf89lfShN5hzwTyJ8t4w.png" /><figcaption>Positional Encoding</figcaption></figure><p>You can find the code for calculating PE, inside the encoder and decoder blocks which uses the input tensor x to generate the PE’s.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e12e487db432ccfbbddb09b980549778/href">https://medium.com/media/e12e487db432ccfbbddb09b980549778/href</a></iframe><p>Above is a simple encoder layer, in which input is passed through multiple such layers(6 as mentioned in original paper) which combinedly forms the encoder block, as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e129190aae1495902234db5b4f9ea299/href">https://medium.com/media/e129190aae1495902234db5b4f9ea299/href</a></iframe><h4>Decoder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*XNfJMLLWUZ5qk1K2WJ8oIg.png" /><figcaption>Decoder Layer</figcaption></figure><p>The output embedding is generated using the output tokens to which their PE is added and passed as input to self attention block of decoder.</p><p>The decoder differs from the encoder by having a cross-attention block, that uses the encoder’s output as the Query and Key, while the Value comes from its self-attention block.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/471287325219697b5c4a12b4f5e6bba3/href">https://medium.com/media/471287325219697b5c4a12b4f5e6bba3/href</a></iframe><p>The decoder block consists of multiple decoder layers(6 as mentioned in original paper) which takes output embedding and encoder blocks output as input, which is then finally passed through a linear layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/574f90c8c472c7dba488c62cbc617bcc/href">https://medium.com/media/574f90c8c472c7dba488c62cbc617bcc/href</a></iframe><h4>Transformer Block</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*GveDFoo7p_ifOp6ULGI5sg.png" /><figcaption>Transformer Architecture</figcaption></figure><p>Now let’s combine it all together, stacking up the encoder and decoder blocks forms a transformer. The input to the transformer is source and target vectors, which are used to form the src_mask and trg_mask .</p><p>Source masks in the encoder prevents attention to padding tokens, while target masks in the decoder blocks future tokens (look-ahead masking) to ensure autoregressive generation.</p><p>The source vector and source mask are passed as input to encoder block, to obtain the encoder’s output, which is passed along with target vector, source mask and target mask to decoder, which gives the final output.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74dcb8b6ff5782089752b86b4838740e/href">https://medium.com/media/74dcb8b6ff5782089752b86b4838740e/href</a></iframe><h3>Training on NMT Task</h3><h4>Introduction</h4><p>We will be training the transformer which we implemented for language translation task(English to Hindi). I have taken a very small dataset and vocabulary so that we can overfit the model on these sample translation sentences and check its performance if its working for the examples which we trained on.</p><h4>Dataset Preparation</h4><p>The dataset class takes index as input, for that particular index it converts the sentences into its token using the source and target vocabularies. In case if a word is not present it replaces it with &lt;unk&gt; token. The tokens are finally padded as per the max_len .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d07379e7b834cb9747ddec287d06d987/href">https://medium.com/media/d07379e7b834cb9747ddec287d06d987/href</a></iframe><h4>Training code</h4><p>Now let’s train the model on our sample dataset. Note that we are trying to overfit the model, just to check its working.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2056327a493d5f9bd00ca7a8f92483e/href">https://medium.com/media/a2056327a493d5f9bd00ca7a8f92483e/href</a></iframe><h4>Inference</h4><p>We can now test the trained model on some sample sentences.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e383e0286fd75247290ee7ea1a7d54fa/href">https://medium.com/media/e383e0286fd75247290ee7ea1a7d54fa/href</a></iframe><h3>Conclusion</h3><p>So finally we have learned how a transformer works and we have a working implementation from scratch. I hope this helps to have a deeper understanding of transformers.</p><h3>References</h3><ul><li><a href="https://arxiv.org/abs/1706.03762">Research Paper</a></li><li><a href="https://github.com/tensorflow/tensor2tensor">Tensor2Tensor Repository</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8939d2b5b696" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Attention Is All You Need: Understanding Transformers]]></title>
            <link>https://medium.com/@nandwalritik/attention-is-all-you-need-understanding-transformers-8acc3aa93de7?source=rss-3d8aed4265e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8acc3aa93de7</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Ritik Nandwal]]></dc:creator>
            <pubDate>Tue, 03 Sep 2024 12:41:57 GMT</pubDate>
            <atom:updated>2024-09-05T06:31:57.318Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Before 2017, models like RNNs and LSTMs handled sequences of data but often struggled with long-range dependencies and were slow to train. The “Attention is All You Need” paper introduced the Transformer model, which relies entirely on attention mechanisms, eliminating the need for recurrence. This innovation not only addressed the limitations of earlier models but also transformed NLP, enabling powerful models like GPT and BERT.</p><p>In this article I will walk through the summary and easy explanation for the research paper, which introduced attention mechanism.</p><h3>The Transformer Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*EV2BdvxKSUDN1Ii1Pbv3pg.png" /><figcaption>Transformer Architecture</figcaption></figure><h4>Component Breakdown</h4><p>A transformer block consists of</p><ul><li><a href="#9a35"><strong>Encoder</strong></a></li><li><a href="#0001"><strong>Decoder</strong></a></li><li><a href="#dd7f"><strong>Attention</strong></a></li><li><a href="#98ec"><strong>Feed Forward Network</strong></a></li><li><a href="#4167"><strong>Layer Normalization</strong></a></li><li><a href="#2098"><strong>Positional Encoding</strong></a></li></ul><h3>Encoder</h3><p>It is composed of 6 identical layers , each layer has two sublayers.<br>|- <strong><em>subLayer1 </em></strong>→ Multi-Head Self Attention followed by Add &amp; norm<br>|- <strong><em>subLayer2 </em></strong>→ Feed Forward followed by Add &amp; norm</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*POJydGquzET8fewpn4ga4w.png" /><figcaption>Encoder Block</figcaption></figure><h3>Decoder</h3><p>It is composed of 6 identical layers , each layer has two sublayers.<br>|- <strong><em>sublayer1 </em></strong>→ Multi-Head Self Attention followed by Add &amp; Norm<br>|- <strong><em>sublayer2 </em></strong>→ Multi-Head Self Attention Over Encoder’s Output followed by Add &amp; Norm<br>|- <strong><em>sublayer3 </em></strong>→ Feed Forward followed by Add &amp; Norm</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*9NkeRJSL_aSFqAiKCPibRA.png" /><figcaption>Decoder Block</figcaption></figure><h3>Attention</h3><h4>Multihead Attention</h4><p>The heart of transformer lies in Attention Mechanism, which is a scaled dot product of three vectors (Query,Key,Values).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*OfpOuFX0tZxHhDiCYWDUGA.png" /><figcaption>Scaled Dot Product Attention</figcaption></figure><ul><li>Query → It is a vector representing current word, for which we want to calculate the attention weights.</li><li>Key → It is a vector which acts as an identifier, that helps to determine if a part of the sequence is relevant to what the query is looking for.</li><li>Value → It is a vector which carry the actual information that will be used to build the next layer’s representation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*0V3LTqIoyMRrOTSYcDYhNg.png" /><figcaption>Scaled Dot Product Attention</figcaption></figure><p>A multihead attention consists of <strong>h </strong>blocks of attention stacked up in parallel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*UJLEnQp5n4ZlP1O1QKHf3w.png" /><figcaption>Multi-Head Attention</figcaption></figure><h4>What Does a Self Attention Represent ?</h4><p>Self-attention, often called intra-attention, allows each word in a sequence to focus on different words in the same sequence, helping the model understand relationships and dependencies between words.</p><p>For example, consider the sentence: “The animal didn’t cross the street because it was too tired.” Here’s how self-attention works:</p><ol><li>Identify Relationships: The word “it” could refer to different entities in the sentence. Self-attention helps in identifying that “it” refers to “the animal” by evaluating the context provided by all other words in the sentence.</li><li>Contextual Relevance: Self-attention calculates how much focus each word should give to every other word. In the case of “it”, the model uses self-attention to assign higher weights to the word “animal” compared to other words, making the relationship clear.</li></ol><h3>Position Wise Feed Forward Network</h3><p>The attention sublayer in encoder and decoder is followed by a fully connected feed-forward layer, which is applied to each position separately and identically, it consists of two linear transformation with a ReLU activation in between.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*CrczcuhuB5e6FsXk2ImP3Q.png" /></figure><h3>Layer Normalization</h3><p>The multihead attention layer and Feed forward layer is followed by a add and normalization layer in both encoder and decoder.</p><p>The add operation is for residual connection(carries the previous information), which adds the input to the output of multihead attention, which is then normalized.</p><h3>Positional Embedding</h3><p><em>Transformers treat input sequence as set rather than a ordered sequence.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*YPjytiGYOl_0vzT3v6REqg.png" /><figcaption><strong>Adding PE to Input Embedding</strong></figcaption></figure><p>Positional embedding is added to the input embedding to give the model, information about the position of token in Sequence.</p><blockquote><strong>Note : This is not a model parameter.</strong></blockquote><p>We can calculate the PE for a given pos and dimension i using:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*LrNbgUa9ctbieiHk9eJfBg.png" /><figcaption>Sine and Cosine Function for calculating PE</figcaption></figure><p>Let’s understand this with an example</p><blockquote><strong>Sentence 1:</strong> “She wore a beautiful red dress.”</blockquote><blockquote><strong>Sentence 2:</strong> “She has a red Ferrari.”</blockquote><p>In both sentences, the word “red” appears. Using only word embeddings (without positional embeddings), the embedding for “red” would be similar in both sentences, as it reflects the semantic meaning of the word itself. However, the context in which “red” appears is different, to make sense of these different contexts, we need to consider the position of “red” in each sentence</p><h3>Conclusion</h3><p>I tried to keep the article short and explanatory, I would highly recommend to read the original research paper to get a deeper insights. In the next part we will be implementing transformer from scratch and train it on NMT task. Do give it a read to have a deeper understanding of its implementations.</p><p><a href="https://medium.com/@nandwalritik/transformer-from-scratch-in-pytorch-8939d2b5b696">Transformer From Scratch In Pytorch</a>.</p><h3>References</h3><ul><li>Research Paper [<a href="https://arxiv.org/abs/1706.03762">Attention Is All You Need</a>]</li><li><a href="https://jalammar.github.io/illustrated-transformer/">Jay Alammar’s Blog</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8acc3aa93de7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embed Superset Dashboard: React]]></title>
            <link>https://medium.com/@nandwalritik/embed-superset-dashboard-react-843b0a60a31f?source=rss-3d8aed4265e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/843b0a60a31f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[superset]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Ritik Nandwal]]></dc:creator>
            <pubDate>Sat, 25 May 2024 07:02:44 GMT</pubDate>
            <atom:updated>2024-05-25T07:02:44.769Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Superset can be a great tool for data visualization, but everytime we can’t directly use superset, instead we can embed its dashboard into our web application.</p><p>There are two possible ways for integrating apache superset dashboards in web apps, one is using iframe and second one is using its embedded sdk.</p><p>In this article I will guide you to integrate superset dashboard using embedded sdk in React application.</p><h3>Enable Embedded Option and Get Dashboard Id.</h3><p>We need to first enable embedded option in superset from superset_config.py , for that make EMBEDDED_SUPERSET:True inside the <strong>FEATURE_FLAGS </strong>dictionary.</p><pre>FEATURE_FLAGS = {<br>    # Paste this along with other feature flag options<br>    &quot;EMBEDDED_SUPERSET&quot;: True,<br>}</pre><p>After this you will be able to see embed dashboard option from the three dots near Edit Dashboard button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*T-zfQLugt7_H4WuXIKLQdw.png" /><figcaption>Embed Dashboard Option</figcaption></figure><p>Click on Embed dashboard option</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*UFp3mRh9qxuqO0fOxF3GfA.png" /><figcaption>Embed Dashboard Pop Up</figcaption></figure><p>Click on Enable Embedding and copy the dashboard id generated</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*SjXW1uYL1eeV9LMeXS194g.png" /><figcaption>Dashboard ID</figcaption></figure><p><strong>Note</strong> : If you want to restrict only specific domains to be able to access this dashboard using its id, add it to list of allowed domains, if you leave it blank any domain can access the dashboard using its ID.</p><h3>Creating Role For Embedded View</h3><p>When we embed the dashboard in web app, the end user must have restricted access to view the dashboards, for this we need a create role and assign that role to GUEST_ROLE_NAME property in superset_config.py .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KlciMo2GwcBEPpVfHGPVpw.png" /><figcaption>Role For Embedded Dashboard</figcaption></figure><p>Add following changes in superset_config.py</p><pre>GUEST_ROLE_NAME= &#39;embed_dashboard&#39;<br>GUEST_TOKEN_JWT_SECRET = &quot;test-guest-secret-change-me&quot;<br>GUEST_TOKEN_JWT_EXP_SECONDS = 3600  # 1 hour</pre><h3>Integrating in React Application</h3><p><strong><em>Note</em></strong> : If you are running the react server and superset server both on local you need to enable cors setting in superset, add the following in superset_config.py .</p><pre>CORS_OPTIONS = {<br>    &quot;supports_credentials&quot;: True,<br>    &quot;allow_headers&quot;: [&quot;*&quot;],<br>    &quot;resources&quot;: [&quot;*&quot;],<br>    &quot;origins&quot;: [&quot;http://localhost:3000&quot;], # replace the port-number <br>                                          # as per your application.<br>}</pre><p>Integrating dashboard in react we need to install embedded sdk using npm.</p><pre>npm install --save @superset-ui/embedded-sdk</pre><p>Import the required dependencies. We need to fetch the guest token to embed dashboard using its ID generated using embed dashboard option, for that we will use superset api’s.</p><pre>import axios from &#39;axios&#39;;<br>import { embedDashboard } from &quot;@superset-ui/embedded-sdk&quot;;<br><br>const supersetUrl = &#39;http://localhost:8088&#39;<br>const supersetApiUrl = supersetUrl + &#39;/api/v1/security&#39;<br>const dashboardId = &quot;abc&quot; // replace with your dashboard id</pre><p>Fetching the guest_token requires the token obtained from login endpoint, we will use admin creds to fetch this token.</p><p>After fetching the guest_token we will use embedDashboard function of superset sdk to embed the dashboard in react app.</p><p>Set the width and height of the iframe, to render the superset dashboard.</p><pre>async function getToken() {<br>  // This uses admin creds to fetch the token<br>  const login_body = {<br>    &quot;password&quot;: &quot;admin&quot;,<br>    &quot;provider&quot;: &quot;db&quot;,<br>    &quot;refresh&quot;: true,<br>    &quot;username&quot;: &quot;admin&quot;<br>  };<br>  const login_headers = {<br>    &quot;headers&quot;: {<br>      &quot;Content-Type&quot;: &quot;application/json&quot;<br>    }<br>  }<br><br>  const { data } = await axios.post(supersetApiUrl + &#39;/login&#39;, login_body, login_headers)<br>  const access_token = data[&#39;access_token&#39;]<br>  console.log(access_token)<br><br><br>  // Calling guest token<br>  const guest_token_body = JSON.stringify({<br>    &quot;resources&quot;: [<br>      {<br>        &quot;type&quot;: &quot;dashboard&quot;,<br>        &quot;id&quot;: dashboardId,<br>      }<br>    ],<br>    &quot;rls&quot;: [],<br>    &quot;user&quot;: {<br>      &quot;username&quot;: &quot;&quot;,<br>      &quot;first_name&quot;: &quot;&quot;,<br>      &quot;last_name&quot;: &quot;&quot;,<br>    }<br>  });<br><br>  const guest_token_headers = {<br>    &quot;headers&quot;: {<br>      &quot;Content-Type&quot;: &quot;application/json&quot;,<br>      &quot;Authorization&quot;: &#39;Bearer &#39; + access_token<br>    }<br>  }<br><br><br>  // Calling guest token endpoint to get the guest_token<br>  await axios.post(supersetApiUrl + &#39;/guest_token/&#39;, guest_token_body, guest_token_headers).then(dt =&gt; {<br>    console.log(dt.data[&#39;token&#39;])<br>    embedDashboard({<br>      id: dashboardId,  // Use the id obtained from enabling embedding dashboard option<br>      supersetDomain: supersetUrl,<br>      mountPoint: document.getElementById(&quot;superset-container&quot;), // html element in which iframe will be mounted to show the dashboard<br>      fetchGuestToken: () =&gt; dt.data[&#39;token&#39;],<br>      dashboardUiConfig: { <br>        // hideTitle: true,<br>        // hideTab:true<br>        filters:{<br>          expanded:true<br>        },<br>        urlParams:{<br>          standalone:3 // here you can add the url_params and there values<br>        }<br>      }<br>    });<br>  })<br><br>  var iframe = document.querySelector(&quot;iframe&quot;)<br>  if (iframe) {<br>    iframe.style.width = &#39;100%&#39;; // Set the width of the iframe<br>    iframe.style.minHeight = &#39;100vw&#39;; // Set the height of the iframe<br>  }<br><br>}</pre><p>Inside the main function call the getToken function and don’t forget to give the same id to div tag, which we mentioned in mountPoint option in embedDashboard function.</p><pre>function App() {<br>  getToken()<br><br>    return (<br>        &lt;div className=&quot;App&quot;&gt;<br>        &lt;div id=&#39;superset-container&#39;&gt;&lt;/div&gt;<br>        &lt;/div&gt;<br>    );<br>}</pre><p>Using above approach we can easily integrate superset dashboard in our react application.</p><h4>References</h4><ul><li>Embedded SDK Documentation [<a href="https://github.com/apache/superset/tree/master/superset-embedded-sdk">link</a>]</li><li>Youtube Tutorial [<a href="https://youtu.be/rlv7Rtrtyjw?si=CCwv-oh8hYPooSIu">link</a>]</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=843b0a60a31f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Superset Local Installation]]></title>
            <link>https://medium.com/@nandwalritik/apache-superset-local-installation-7958cbf7c5f4?source=rss-3d8aed4265e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7958cbf7c5f4</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[superset]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Ritik Nandwal]]></dc:creator>
            <pubDate>Mon, 13 May 2024 13:57:04 GMT</pubDate>
            <atom:updated>2024-05-25T06:06:59.539Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>Apache Superset stands as a powerful tool in the realm of data visualization and exploration, offering a robust platform for data analysts and developers to craft insightful dashboards and delve deep into datasets.</p><p>In this guide, I will walk through the process of setting up Apache Superset in a local development environment. By installing Superset in dev mode, developers gain the flexibility to experiment, customize, and contribute to its codebase with ease.</p><p>Apache superset installation consists of two parts, setting up the frontend and backend.</p><p>For Setting up frontend we need to install NodeJS(preferably version 16). You can use <a href="https://github.com/nvm-sh/nvm">NVM</a> to switch between different versions of NodeJS.</p><p>For Setting up backend we need to create a virtual environment in python( for this you can use <a href="https://docs.python.org/3/library/venv.html">venv</a> or <a href="https://docs.conda.io/projects/conda/en/latest/user-guide/install/">conda</a>)</p><p>Clone the Apache Superset Repository</p><pre>git clone https://github.com/apache/superset/<br>cd superset</pre><h3>Front-End Setup</h3><pre>cd superset-frontend<br>npm ci<br>npm run build</pre><p>This will be build the front assets necessary to run the UI for superset.</p><p><strong>NOTE : </strong>If you are making any changes to frontend codebase and want to see the changes in hot-reload mode, run it using following command and open superset on localhost:9000.</p><pre>npm run dev-server</pre><h3><strong>Backend Setup</strong></h3><p>Create a virtual environment with following command</p><pre>python3 -m venv supersetDev<br>source ./supersetDev/bin/activate</pre><p>Install the external dependencies and install superset in development mode</p><pre>pip install -r requirements/testing.txt<br>pip install -e .</pre><p>After above installation we need to</p><ul><li>Initialize the database.</li></ul><pre>superset db upgrade</pre><ul><li>Create superset Admin User. Note down the credentials you will input after below command, because that will be the login credentials for Superset Admin User.</li></ul><pre>superset fab create-admin</pre><ul><li>Creating default roles and permissions</li></ul><pre>superset init</pre><ul><li>Load some sample data to play with</li></ul><pre>superset load-examples</pre><ul><li>Starting Superset Server</li></ul><pre>superset run -p 8080 --with-threads --reload</pre><p>Now you can open superset in browser on localhost:8080 and login with the admin credentials that we create with superset fab create-admin command.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7958cbf7c5f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3D Face and Body Reconstruction]]></title>
            <link>https://medium.com/offnote-labs/3d-face-and-body-reconstruction-95f59ada1040?source=rss-3d8aed4265e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/95f59ada1040</guid>
            <category><![CDATA[smpl]]></category>
            <category><![CDATA[skinning]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[3d-reconstruction]]></category>
            <category><![CDATA[flame]]></category>
            <dc:creator><![CDATA[Ritik Nandwal]]></dc:creator>
            <pubDate>Mon, 20 Sep 2021 10:22:40 GMT</pubDate>
            <atom:updated>2021-09-20T10:22:40.642Z</atom:updated>
            <content:encoded><![CDATA[<p>3D face/body reconstruction is the task of reconstructing face/body into its 3d form (mesh) given one or more 2d images as input. A large number of models and techniques have been proposed to address the 3D reconstruction problem.</p><p>In this article, we will discuss some of the prominent models used for the problem: 3DMM, FLAME, SMPL, SMPL-X.</p><p><strong>3D Face Reconstruction</strong></p><p>So, how do we reconstruct the 3d object of the face from a given 2d image as input. It is an important task in the field of computer vision and 3d graphics and animation. There are two main methods.</p><p>Firstly, we can directly regress the 3d voxels (<em>pixels in 3d are equivalent to voxels</em>) using CNN. This is a generalized method for 3d reconstruction. In this method input are 2D images and 3D facial scans of human heads, CNN predicts the 3D voxels, weights are learned by minimizing the loss function (difference between ground truth and predicted 3d parameters).</p><p>Regressing 3d voxels usually takes a longer time, as the CNN has to learn a large number of parameters (more than 20,000). So research has come to build models specific to the human face, hands, and body and regress them from monocular 2d images. We will discuss some of the prominent ones here.</p><p><strong>3DMM</strong>: It stands for 3D morphable face model, where the face can be represented as a linear combination of shape and texture (<em>variation in color across different points in 3d</em>). The model needs to predict both <em>identity</em> and <em>expression</em> parameters <em>(the two components of the 3DMM model)</em>. Input is 2d image and ground truth 3dmm parameters and output is predicted values of 3dmm parameters. Parameters are learned by minimizing the value of the loss function. The 3DMM parameters can be regressed using any model like <em>resnet</em> or <em>mobilenet. </em>The number of parameters when compared to the parameters obtained in directly regressing 3D voxels is very less, hence it is faster and can be used for real-time applications where speed is an important factor.</p><p><strong>3DMM (3D morphable face model)</strong></p><p>Face can be represented as a linear combination of shape and texture(<em>variation in color across different points in 3d</em>). It is a statistical model which transforms the shape and texture of the faces into a vector space representation. Shape vector consists of (x,y,z) coordinates of face, and Texture vector consists of (r,g,b) values of corresponding shape vector coordinates.</p><p>The <em>neutral</em> face is the basis of every face, i.e face without any expressions which can be represented as a linear combination of shape and texture vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*XyuNzEv-nRoTS3VBUEjmRg.png" /><figcaption>Shape Model Equation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*75361x2KrBEF4071_cFH5g.png" /><figcaption>Texture Model Equation</figcaption></figure><ul><li>S_bar and T_bar denote mean shape and mean texture vectors.</li><li>m → Number of eigenvectors of shape and texture covariance matrices</li><li>s_i and t_i → ith eigenvectors of shape and texture covariance matrices</li><li>alpha and beta →shape and texture parameters of S_model and T_model</li></ul><p>To add expressions, we add expression variation term to the equation of neutral face.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*MxD-_0vIa0WEtixb7LhH_A.png" /><figcaption>Face Model with expression variation</figcaption></figure><ul><li>alpha_j → expression parameter and s_j → eigenvectors for expressions</li></ul><p>3DMM parameters consist of <em>[f, pitch, yaw, roll,t2d,alpha_id,alpha_exp]</em> terms where f → constant value that is used as a scale factor in the equation | pitch, yaw, and roll → rotations around three perpendicular axis | t2d → translation vector | alpha_id and alpha_exp → shape and expression parameters respectively.</p><p><strong>Flame Model</strong></p><p>FLAME is a different lightweight and expressive generic head model, learned from over 33,000 accurately aligned 3D scans. To understand this model, we first need to understand the SMPL model, so we will discuss it in the latter part of the article.</p><p>Most methods to 3D-reconstruct human body use <em>SMPL</em> and <em>SMPL-X</em> models. Before going into them, we need to understand a few key concepts: <em>skinning</em>, <em>blendshapes, </em>and<em> template meshes.</em></p><p><strong>Skinning</strong></p><p>To reconstruct 3d body, we detect its skeletal <em>pose</em> and then construct 3d mesh on it to capture the <em>surface</em>/shape of the body. Skinning is a method used to <em>attach</em> the mesh to the skeletal structure. The position of a vertex in a mesh depends on multiple bones. Each bone has a deformation of the space around it, we can’t attach the vertex to just a single bone because in this case, its position during movement will be rigid, rather it depends on the position where the vertex lies. For example, at a joint skin is deformed due to two or more bones, therefore it must be a weighted sum of those bones. Whereas a point lying in the middle of the limb will almost depend only on one single bone and its movement will be almost rigid. Read more in [<a href="http://www.cs.cmu.edu/~yaser/Lecture-9-Skinning%20and%20Body%20Representations.pdf">1</a>].</p><p>There are different types of skinning:</p><ul><li>Linear: It has one disadvantage, at joints, it deforms unusually.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qgHnsuPsniF4TtDeGJyhVw.png" /><figcaption>Collapse and Candy Wrapper Effects in Linear Blend Skinning</figcaption></figure><ul><li>Dual-Quaternion: Almost has natural deformation at joints.</li></ul><p><strong>Blendshapes</strong></p><p>It is a set of vertex offsets that can be linearly interpolated to generate expressions. It can be considered as a collection of different node points connected to each other, when one node is displaced, all other nodes connected to it get displaced.</p><p><strong>Template Mesh/Mean Template Shape(T)</strong></p><p>It is a T-shaped, neutral pose, 3d mesh representative of the human body shape, which can be used as a base for reconstructing differently shaped human bodies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*zvMWyAjlMJeL_x4QCMln4A.png" /><figcaption>Mean Template Shape</figcaption></figure><p><strong>Blend Weights</strong></p><p>Weights are used to control the movement of different regions in blend shapes. The different colors in the above template mesh represent different blend weights.</p><p><strong>Pose Dependent Blend Shape</strong></p><p>The surface of the body deforms according to the pose of the person. To capture this, a function is learned to add required changes to the Template shape, keeping the identity of the person as a constant attribute.</p><p><strong>Identity Dependent blend Shape</strong></p><p>Blend shape function learned to add shape changes to the template shape, which are specific to the identity of the person, keeping pose as a constant attribute.</p><p>Now, we discuss two popular 3d human models: SMPL and SMPL-X.</p><p><strong>SMPL</strong></p><p>It is a skinned vertex-based model <em>(meaning it construct surface on top of the skeleton)</em> that accurately represents different varieties of human bodies in natural human poses. The parameters of the model are <em>learned from data</em> including the rest pose template, blend weights, pose-dependent blend shapes, identity-dependent blend shapes.</p><p>Recall how the 3DMM model decomposes the representation of the face into identity and expressions/texture. Similarly, SMPL decomposes the body shape representation into the <em>identity</em> shape and <em>pose-dependent</em> shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*QX09R7i-iOL0HxOPnNlHPg.png" /><figcaption>B_Shape+Pose = B_p(theta)+B_s(beta) , where B is blend shape function</figcaption></figure><p>identity shape → It means varying the pose, such that identity remains constant.</p><p>pose-dependent-shape → In this the pose is always the same, but identity is varied.</p><p>Once these objectives are achieved, we can add both the blend shape functions linearly, to represent any body shape and pose.</p><p>Let us now see how these different components come together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ABbHV_Wr3WPchxk3nXkeUA.png" /><figcaption><strong>SMPL</strong> <strong>Model</strong></figcaption></figure><p>SMPL model breaks down body shape into identity and non-rigid pose dependent shape. SMPL already has neutral template mesh <strong><em>(a)</em></strong>, which is learned from thousands of 3d body scans. A blend shape function B_S takes a vector of shape parameters <em>beta</em> as input and outputs blend shapes (deviations from template mesh) for the input image, which are then added to template mesh to produce <strong><em>(b)</em></strong>. Similarly pose blendshape (deformation due to pose of person) are calculated using the<em> B_p</em> function and added to above result to obtain the result in <strong><em>(c). </em></strong>Finally, a standard blend skinning function W (·) (linear or dual-quaternion) is applied to rotate the vertices around the estimated joint centers with smoothing (meaning the surface must be continuous without any breaks) defined by the blend weights to produce result in <strong><em>(d).</em></strong></p><p>Now since we have understood the working of the SMPL model, we can have a look at the FLAME model for faces which uses SMPL’s method as the base and reconstructs 3d face from 2d image as input.</p><p><strong>FLAME</strong></p><p>FLAME model consists of Template mesh <strong>T</strong> for face in neutral pose. The shape blendshape function <strong><em>S()</em></strong> handles identity-related shape variation on top of the template mesh. The pose blendshape function <strong><em>P()</em></strong> corrects the pose deformation of the head. These above functions were derived from SMPL , Additionally, an expression blendshape function E is added, to capture the facial expression.</p><p>The skinning function is applied to template mesh linearly combined with shape, pose and expression blendshape functions to generate the final output.</p><p><strong><em>T + S() + P() + E()</em></strong> passed as input to skinning function, <strong><em>W(T,S,P,E)</em></strong> which generates 3d face. The skinning function also rotates the vertices of the face around joints J linearly smoothed (meaning there are no gaps in 3d reconstructed output) by blend-weights <strong><em>W</em></strong><em>. </em>This finally results in 3d reconstructed face with expressions.</p><p><strong>SMPL-X</strong></p><p>SMPL-X is an extended version of SMPl, specialized for capturing hands and facial expressions, and reconstructs 3d body specific to gender.</p><p>The SMPL-X uses a similar decomposition as SMPL, where additionally the pose parameter <em>theta</em> is broken down into pose parameters for jaw, finger and remaining body joints. This, in turn, helps in specializing for capturing facial expressions and hand poses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*aNFrj0o3JZlTnIsTC6k8qg.png" /><figcaption>Left 3d body is the output of SMPL, Right 3d body is of SMPL-X</figcaption></figure><p>It uses a better pose prior by applying collision penalty to impossible poses, by detecting a list of colliding triangles in the mesh.</p><p>One key difference when compared to SMPL is that SMPL-X breaks down the pose<em>(theta)</em> into 3 parts <em>(theta_f → for jaw joint, theta_h → for finger joints, theta_b → for remaining body joints)</em>, these are then again combined back using weighted sum loss function.</p><p>Additionally, SMPL-X has got some important features. It has got a separate function for penalizing impossible poses. SMPL used an approximation of negative log of gaussian mixture model trained on MoCap dataset, but it’s not that efficient and fails in many cases because it makes symmetrical changes in the body. Consider a case when a person is just moving his right hand and left hand is still, but deformations will be seen in the left hand, this is a drawback of SMPL.</p><p>SMPL-X uses a Variational Autoencoder which learns a latent representation of human pose and regularizes the distribution of the latent code to be a normal distribution.</p><p>SMPL-X uses pose space and pose corrective blendshape parameters of MANO hand model and expression space parameters from FLAME model because full-body scans had limited resolution for hands and face. MANO and FLAME were specialized for 3d hand reconstruction and facial expressions respectively. So a better option is to use their trained parameters rather than training from scratch for hands and expressions. It handles body folds by using separate functions for penalizing self-collisions and penetrations of different body parts that are physically impossible. For gender classification, they used a gender classifier that takes input images containing full body and openpose joints and assigns gender labels to detected persons.</p><p>We now discuss some methods for 3D reconstruction <strong><em>DECA</em></strong> and <strong><em>Pixie</em></strong>., which employ one or more of above models.</p><p><strong>DECA</strong></p><p>It is a combination of the FLAME model with UV displacement maps.</p><p><em>UV-Displacement Maps</em>: They are helpful in capturing wrinkle-level deformations on a surface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*8xsysUzAzDwPSsqagc6p0w.png" /><figcaption>UV-Map of Face</figcaption></figure><p>They are also known as height maps/bump maps used to capture heightened displacement in 3d, the parts which are at lower height are black in color whereas points at higher height are white in color. This black and white variation can be captured using an encoder like resnet which can generate latent code for a given input image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6hQKS7UKMpAYnjUVc9nQ1w.png" /><figcaption>DECA Model</figcaption></figure><p>DECA mainly consists of two parts: coarse reconstruction and detailed reconstruction. In the coarse reconstruction part, the 3d face is reconstructed using the FLAME model, which is not that good at capturing wrinkle-level deformations of the face. Detailed reconstruction aims at combining the coarse reconstructed part with a detailed UV displacement map <em>(UV map captures expressions using low dimensional latent representation obtained from the encoder)</em> for facial expressions.</p><p>Encoder E_d is trained to encode input image to 128-dimensional latent code delta that represents subject-specific details.</p><p>A decoder F_d is trained that combines FLAME’s expression and jaw pose parameters with latent code delta and outputs the final 3d reconstructed face with expressions.</p><p><strong>Pixie</strong></p><p>It is a combination of FLAME face model and decomposition of the SMPL-X model. It uses an SMPL-X body model that captures whole body pose and shape, including facial expressions, and produces a 3D mesh. In order to improve 3d body reconstruction, they use a set of expert sub-networks for the body, face/head, hands and then combine these sub networks into a bigger network architecture for 3d body reconstruction of each part separately and then combine them using a weighted sum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*47PXVNUN7Ph_JUp0gjvVtg.png" /><figcaption>Pixie Architecture</figcaption></figure><p>Pixie uses different encoders for feature extraction of hands, body, and face. They treated {body, head} and {body, hand} as complimentary features and learned separate <em>moderators</em> for them. A moderator is basically an MLP that takes body (F_b) and part (F_f or F_h) as input features and fuses them with a weighted sum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*hr44rq9JFHA8xD0zrPwS6A.png" /><figcaption>Moderator Equation</figcaption></figure><ul><li>M_p(M_f/M_h) → part moderator</li><li>w_p(w_f/w_h) → expert’s confidence</li><li>F_b_p → body feature obtained by transforming the output of encoder using linear layer L_p</li><li>t → learned temperature weight parameter</li></ul><p>Different regressors are used to obtain values for different parameters (camera, body rotation, pose, albedo, lightning, expressions, head pose, jaw pose, and body shapes). For capturing details, first they calculate 3D displacements on top of FLAME’s surface. Then convert the displacements from FLAME’s to SMPL-X’s UV map and apply them to PIXIE’s calculated head shape. They do this only when the face image is not too noisy, to identify that face is noisy or not using a moderator.</p><p><strong>Examples and Applications</strong></p><p>The methods which we discussed above have been used in many papers like Direct Volumetric Regression [<a href="https://arxiv.org/abs/1703.07834">Github</a>][<a href="https://github.com/AaronJackson/vrn">Paper</a>] where they regressed 3d voxels using CNN’s, 3DDFA_v2 [<a href="https://arxiv.org/abs/2009.09960">Paper</a>][<a href="https://github.com/cleardusk/3DDFA_V2">Github</a>] used 3dmm parameters with fast optimization techniques for loss functions.</p><p>There are also GAN based approaches for 3d face reconstruction, for reference you can read a recent paper Fast-GANFIT [<a href="https://github.com/barisgecer/ganfit">Github</a>][<a href="https://arxiv.org/abs/2105.07474">Paper</a>].</p><p>For exploring more recent work in 3d face reconstruction, you could try reading <em>To fit or not to fit</em>[<a href="https://github.com/unibas-gravis/Occlusion-Robust-MoFA">Github</a>][<a href="https://arxiv.org/pdf/2106.09614v1.pdf">Paper</a>], <em>SADRNet</em>[<a href="https://github.com/MCG-NJU/SADRNet">Github</a>][<a href="https://arxiv.org/pdf/2106.03021v1.pdf">paper</a>].</p><p>In this article, we discussed different techniques of 3D face reconstruction and different models that are being used for 3d body reconstruction and how these models can be used in pipelines of different reconstruction techniques to get desired output with more specialized improvements.</p><p><strong>OffNote Internship Experience</strong></p><p>My research internship experience was smooth under the guidance of <a href="https://www.linkedin.com/in/nishant-sinha-a610311/"><strong>Dr. Nishant Sinha Sir</strong></a><strong>,</strong> It was the first time I read so many research papers to understand different methods to perform the same task. At first, I found it a little bit difficult as I was not able to understand research papers in one go, but after few iterations and careful studies, and making proper notes, my brain took over and started understanding things on its own. Not only I understood the theory part but also went through their codebases, logged the values of input/output of different layers and functions which helped me to understand their working.</p><p>My writing skills also improved as I started writing this article. When writing an article, we have to think from the reader&#39;s perspective. We have to order and organize the content in such a way that the reader understands it in one go. This was a thing I got to learn after writing this article. All thanks to Nishant Sir for his constant guidance.</p><p>You can view my other projects at my <a href="https://github.com/nandwalritik">github</a> and in case if you have got any questions, you can approach me on <a href="https://www.linkedin.com/in/nandwalritik/">linkedin</a>.</p><p><strong>References</strong></p><ul><li>Landmark Weighting for 3DMM Shape Fitting [<a href="https://arxiv.org/abs/1808.05399">Paper</a>]</li><li>SMPL: A Skinned Multi-Person Linear Model [<a href="https://files.is.tue.mpg.de/black/papers/SMPL2015.pdf">Paper</a>] [<a href="https://www.youtube.com/watch?v=rzpiSYTrRU0&amp;t=1932s">Video</a>]</li><li>SMPL-X [<a href="https://ps.is.tuebingen.mpg.de/uploads_file/attachment/attachment/497/SMPL-X.pdf">Paper</a>]</li><li>FLAME [<a href="https://www.is.mpg.de/uploads_file/attachment/attachment/400/paper.pdf">Paper</a>]</li><li>Skinning [<a href="http://www.cs.cmu.edu/~yaser/Lecture-9-Skinning%20and%20Body%20Representations.pdf">1</a>] [<a href="https://skinning.org/direct-methods-slides.pdf">2</a>]</li><li>DECA: Detailed Expression Capture and Animation [<a href="https://arxiv.org/abs/2012.04012">Paper</a>] [<a href="https://github.com/yadiraF/DECA/">Code</a>]</li><li>Pixie: Collaborative Regression of Expressive Bodies using Moderation [<a href="https://arxiv.org/abs/2105.05301">Paper</a>]</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95f59ada1040" width="1" height="1" alt=""><hr><p><a href="https://medium.com/offnote-labs/3d-face-and-body-reconstruction-95f59ada1040">3D Face and Body Reconstruction</a> was originally published in <a href="https://medium.com/offnote-labs">OffNote Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>