<?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 Dinesh on Medium]]></title>
        <description><![CDATA[Stories by Dinesh on Medium]]></description>
        <link>https://medium.com/@humble_bee?source=rss-43c33ea8bc34------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*zawGpWxpVxYB7Ryb-PLbkQ.gif</url>
            <title>Stories by Dinesh on Medium</title>
            <link>https://medium.com/@humble_bee?source=rss-43c33ea8bc34------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 02:30:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@humble_bee/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[The Two-Faced CPU: The Hybrid Harvard & Von Neumann Soul of Your Processor]]></title>
            <link>https://medium.com/@humble_bee/the-two-faced-cpu-the-hybrid-harvard-von-neumann-soul-of-your-processor-0397912b97f0?source=rss-43c33ea8bc34------2</link>
            <guid isPermaLink="false">https://medium.com/p/0397912b97f0</guid>
            <category><![CDATA[computer-architecture]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[compilers]]></category>
            <dc:creator><![CDATA[Dinesh]]></dc:creator>
            <pubDate>Fri, 03 Oct 2025 01:05:03 GMT</pubDate>
            <atom:updated>2025-10-03T07:47:00.161Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever wonder why your code runs fast (or slow)? The answer lies in a decades-old architectural debate that lives inside every modern chip. Let’s decode the secrets of the CPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5mXJcMRn2QzF3Je10eMEQ.png" /><figcaption>Code &amp; Data: Two Ways to Feast</figcaption></figure><h4>The Bottleneck That Started It All</h4><p>If you’ve spent any time in performance-critical fields like AI or high-performance computing, you may have heard of the infamous <strong>“Von Neumann bottleneck”.</strong> <br>It’s the simple idea that a processor<em> can’t fetch instructions and data at the same time</em> because they have to travel down the same path. For tasks like the massive <em>matrix multiplications</em> in AI, this <a href="https://research.ibm.com/blog/why-von-neumann-architecture-is-impeding-the-power-of-ai-computing"><em>sequential traffic jam</em></a> is a disaster, leaving precious computing power waiting on the sidelines.</p><p>This single problem has dictated decades of computer design. But if this bottleneck is so bad, why is the architecture that causes it still at the heart of the processor you’re using right now?</p><p>The answer is that modern CPUs are not what they seem. They are clever, two-faced hybrids, combining the best of two warring architectural philosophies. In this post, we’ll try to peel back the layers of a modern CPU to understand its split personality.</p><h3>The Two Original Blueprints</h3><p>To understand the modern hybrid, we first need to meet the two original, competing designs for a computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MJEbPTaPxelK6OSglqfzPA.png" /><figcaption>Von Neumann vs Harvard Architecture</figcaption></figure><blockquote><strong>TL;DR:</strong> Modern CPUs are <strong>Harvard at L1 for speed</strong> and <strong>von Neumann below for flexibility</strong>. Coherence keeps it all consistent across cores.</blockquote><h3>The Von Neumann Architecture: The Flexible Librarian</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DIDHL8VX0zy1vpfM8LOHDg.png" /><figcaption>Von Neumann Architecture</figcaption></figure><p>The <strong>Von Neumann architecture</strong> is the classic blueprint for almost every computer you’ve ever used. The easiest way to picture it is as a library where the instruction manuals on “how to do things” (the code) and the books containing the actual information (the data) are all stored on the same shelves. Everything is accessed by a single, hardworking librarian who runs back and forth on one path.</p><p>At its heart, this architecture is defined by one crucial design choice: a single, unified memory space for both program instructions and the data those instructions operate on. A central processing unit (CPU) fetches an instruction from memory, decodes it, and then fetches the data it needs from that same memory to execute the instruction. This cycle repeats, instruction by instruction. The key idea is this shared memory and the sequential fetching of instructions and data through a common pathway.</p><p>Here’s how it works step-by-step:</p><ol><li><strong>Fetch:</strong> The CPU’s Control Unit asks for the next instruction from memory, using an address from the Program Counter. The instruction travels from Main Memory to the CPU across a shared pathway called a <strong>bus</strong>.</li><li><strong>Decode:</strong> The CPU figures out what the instruction means.</li><li><strong>Execute:</strong> The instruction is carried out. If the instruction needs data (for example, “add 5 to the number stored at memory location X”), the CPU must go <strong>back to the same memory, using the same bus</strong>, to fetch that data.</li></ol><p>This sequential, two-step trip — first for the instruction, then again for the data, all over the same single-lane road — is the source of the infamous <strong>Von Neumann bottleneck</strong>. The CPU, which can perform calculations at incredible speeds, often spends most of its time idle, simply waiting for the “librarian” to come back with either the next instruction or the piece of data it needs.</p><p>Let’s summarize:</p><ul><li><strong>Design:</strong> A single, unified memory for both code and data, accessed via a shared bus.</li><li><strong>Advantage: Flexibility.</strong> This unified design is incredibly flexible. It allows code to be treated as data, a principle that enables powerful modern technologies like Just-in-Time (JIT) compilers, which can write new machine code into memory on the fly and then execute it.</li><li><strong>Disadvantage: The Bottleneck.</strong> The shared bus creates a sequential traffic jam, preventing the simultaneous fetching of instructions and data. This severely limits <strong>throughput</strong> (the total amount of work done over time), especially for data-hungry tasks like the ones found in AI.</li></ul><p>This classic blueprint, with its trade-off between flexibility and performance, remains the fundamental starting point for understanding modern processors. In fact, the CPU in your computer today is still based on this Von Neumann model, but as we’ll see, it employs some incredible tricks to overcome the very bottleneck it created.</p><h3>The Harvard Architecture: The Two-Conveyor Factory</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQo7y9by8QqAG7wSXIywrg.png" /><figcaption>Harvard Architecture</figcaption></figure><p>To solve the traffic jam created by the Von Neumann bottleneck, another blueprint was developed: the Harvard architecture. Its philosophy is simple: if one road is too slow, build a second one.</p><p>This is the <strong>Two-Conveyor Factory</strong>. Imagine two completely separate warehouses: one for assembly instructions (code) and another for raw materials (data). Crucially, two dedicated, independent conveyor belts run from these warehouses to the factory floor (the CPU), allowing for a constant, parallel flow of both.</p><p>This physical separation is the defining feature. By having distinct memories and buses for instructions and data, the CPU can perform two actions at the exact same time. As the control unit is fetching the <em>next</em> instruction from the instruction memory, the ALU can be simultaneously reading or writing data from the data memory for the <em>current</em> instruction. There is no need to wait; the two operations don’t compete for the same pathway.</p><p>This parallel access dramatically increases <strong>throughput</strong>, making the entire system far more efficient for high-performance tasks.</p><p>Let’s summarize:</p><ul><li><strong>Design:</strong> Physically separate memory systems and dedicated buses for both program instructions and data.</li><li><strong>Advantage: Performance.</strong> This is the architecture’s main selling point. The ability to fetch instructions and access data simultaneously eliminates the Von Neumann bottleneck, leading to significantly faster and more efficient operation.</li><li><strong>Disadvantage: Architectural Rigidity and Cost.</strong> This high performance comes at a price. The primary drawback of a <em>pure Harvard design</em> is its strict and inflexible separation of code and data, which creates several significant challenges. <strong>For modern software,</strong> this rigid division is a major limitation because it makes it fundamentally difficult to treat code as data, breaking powerful technologies like Just-in-Time (JIT) compilers that are essential for languages like Java and JavaScript. <strong>On a practical level,</strong> this separation can create headaches for programmers on systems that more closely follow this model, often requiring special instructions just to access constants stored in code memory. <strong>Finally, from a hardware perspective,</strong> building two separate memory systems adds cost and complexity and can lead to inefficient memory use. This combination of rigidity and cost is why pure Harvard isn’t used for general-purpose CPUs.</li></ul><h3>The Modern Compromise — A “Modified Harvard” Hybrid Architecture</h3><p>So, which design won? Neither. We took the best parts of both.</p><p>You might hear the seemingly contradictory statement that <em>‘All modern processors adhere to the von Neumann architecture model’</em>. From a broad system perspective, that’s true. Your operating system and the programs you write see a single, unified block of <strong>RAM</strong>, giving them the flexibility to treat instructions and data as interchangeable, making memory management simpler and more adaptable for software. That’s the core power of Von Neumann.</p><p>However, for raw performance, the devil is in the details, specifically at the heart of the CPU itself. As the insightful article ‘<a href="http://ithare.com/modified-harvard-architecture-clarifying-confusion/">Modified Harvard Architecture: Clarifying Confusion</a>’ elaborates, a modern CPU is a hybrid that is <strong>Harvard-like at its core</strong> and <strong>Von Neumann-like for the rest of the system.</strong> This design is what the we refer to as <strong>‘Almost von-Neumann’.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bK-Dz_xRr5S-EG4o9OIItw.png" /><figcaption>Modern Processor Design</figcaption></figure><p>The magic happens in the <strong>Level 1 (L1) cache</strong> — the memory physically closest to the CPU’s processing units. This cache is split:</p><ul><li><strong>L1 Instruction Cache (I-Cache):</strong> A dedicated cache just for code.</li><li><strong>L1 Data Cache (D-Cache):</strong> A dedicated cache just for data.</li></ul><p>By splitting the L1 cache, the CPU gets the key performance benefit of a Harvard machine: it can fetch the next instruction from the I-Cache and load or store data from the D-Cache <strong>at the exact same time</strong>. This simultaneous access is critical for maximizing <strong>throughput</strong> — the amount of work the processor can get done — by ensuring its execution units are never left waiting for their next task or the data they need. It is a direct, localized solution to the Von Neumann bottleneck.</p><p>However, further down the memory hierarchy, the <strong>L2 cache, L3 cache, and the main RAM are all unified</strong>. They hold both code and data in the same space. This is a deliberate choice to preserve the flexibility of the Von Neumann model for the overall system. A single, large memory pool is far easier for the operating system to manage and for programs to use, allowing for the dynamic memory allocation and software capabilities we rely on today. This layered approach provides a masterful compromise, giving us the raw speed of a Harvard design right where it matters most, while maintaining the crucial flexibility of a Von Neumann system for everything else.</p><h3>The Price of Speed: Keeping the Hybrid Modern CPU in Sync</h3><p>In the last section, we celebrated the brilliant hybrid design of a modern CPU — a design that gives us the raw speed of a Harvard machine and the flexibility of a Von Neumann system. But this powerful compromise comes with a profound new challenge: <strong>the problem of consistency</strong>.</p><p>Splitting the caches creates a new, complex problem: how do you make sure these two “faces” of the CPU agree on what the truth is? When you have multiple, independent copies of data — in the L1 D-Cache, the L1 I-Cache, and the private caches of several other cores — how do you ensure they all agree on what the “truth” is? If one core updates a value, how do you prevent another core from accidentally using the old, stale version?</p><p>This is where the magic happens. The solution is a sophisticated set of rules and hardware known as <strong>cache coherence</strong>. It’s the constant, high-speed communication that acts as the CPU’s secret dance, allowing all its different parts to work in perfect harmony. This dance happens in two main arenas.</p><h4>Level 1: Keeping a Single Core Honest (Intra-Core Coherence)</h4><p>The first challenge occurs <em>inside</em> a single core itself. Because the I-Cache and D-Cache are separate at L1, a core could theoretically lie to itself.</p><ul><li><strong>The Problem:</strong> Imagine a Just-in-Time (JIT) compiler is running. It generates new, optimized machine code. This code is created as <em>data</em>, so the write operation goes through the <strong>D-Cache</strong>. A moment later, the CPU tries to <em>execute</em> this new code, meaning it needs to fetch it as an instruction via the <strong>I-Cache</strong>. But without coherence, the I-Cache would still hold the last old, stale data from that memory location, and the program would crash by running the wrong code.</li><li><strong>The Solution:</strong> The <strong>Load/Store Unit (LSU)</strong>, the CPU’s vigilant gatekeeper for all memory operations, is the hero here. While the exact hardware method can vary between different processor families, the principle is the same. The LSU and the CPU’s internal coherence logic work together to <strong>guarantee</strong> that a write to the D-Cache triggers an invalidation of any matching entry in the I-Cache. This tightly-coupled action ensures a core never disagrees with itself and can always execute the freshest, most recently written instructions.</li></ul><h4>Level 2: Keeping All Cores in Sync (Inter-Core Coherence)</h4><p>This challenge explodes on a multi-core processor, where each core has its own private L1 and L2 caches. How do you keep them all consistent?</p><ul><li><strong>The Problem:</strong> If Core A updates a variable X in its private L1 cache, how do Core B and Core C, which may have their own copies of X, know that their versions are now wrong?</li><li><strong>The Solution:</strong> This is solved by two key pieces of hardware working together: the <a href="https://www.arteris.com/blog/the-soc-interconnect-fabric-a-brief-history/"><strong>Interconnect Fabric</strong></a> (the smart on-chip highway) and the shared <strong>L3 Cache Controller</strong> (the central traffic authority).</li></ul><ol><li>When Core A writes to X, its cache controller sends a &quot;write&quot; message out onto the <strong>Interconnect</strong>.</li><li>The shared <strong>L3 Controller</strong> sees this message. It has a master <strong>directory</strong> that tracks which cores have a copy of X. It sees that Core B and Core C also have copies.</li><li>The L3 Controller then becomes the new messenger, sending targeted “Invalidate” messages back out onto the Interconnect, addressed to Core B and Core C.</li><li>The Interconnect delivers these messages. When Core B and Core C receive the “Invalidate” command, they immediately purge their stale copies of X. The next time they need X, they will have to fetch the new, correct version.</li></ol><blockquote>This communication follows specific protocols, most commonly <strong>MESI </strong>(Modified, Exclusive, Shared, Invalid) or its variants. Each cache line is tagged with a state, and the protocol defines exactly what messages must be sent when that state changes. It’s a distributed algorithm running in hardware at nanosecond speeds, ensuring consistency across the entire chip.</blockquote><p>This constant, high-speed chatter of requests and invalidations is the “secret dance” that allows multiple cores to work together on shared data without chaos. It’s the price of performance, paid for by some of the most complex and elegant engineering in modern technology.</p><h4>Conclusion: The Two-Faced Marvel</h4><p>The next time you wonder why your code runs the way it does, remember the processor it’s running on. It’s a pragmatic, two-faced marvel of engineering. It wears a <strong>Harvard mask</strong> at its core to feed the insatiable demand for instructions and data in parallel. Yet, its <strong>Von Neumann soul</strong> provides the unified memory space that offers the flexibility modern software demands.</p><p>This beautiful, complex hybrid is the true foundation of modern computing, constantly performing a high-speed balancing act to keep the digital world running. Understanding this is the first step to truly understanding performance. But what happens when even this brilliant balancing act isn’t enough?</p><p>For the AI revolution, a clever compromise wasn’t the answer. A completely different approach was needed — and it was found hiding in plain sight inside nearly every computer.</p><p><strong>Stay tuned for the next post in our series, where we’ll dive into the architecture of the accidental AI powerhouse: the Graphics Processing Unit (GPU).</strong></p><p>Further Reading / References:</p><ul><li><a href="https://hardwarelottery.github.io/"><strong>The Hardware Lottery:</strong> <em>Why chance and compatibility drive the success of computing ideas.</em></a></li><li><a href="http://ithare.com/modified-harvard-architecture-clarifying-confusion/"><strong>Modified Harvard Architecture: Clarifying Confusion:</strong> <em>An in-depth look at the hybrid nature of modern CPUs (Must Read)</em></a></li><li><a href="https://research.ibm.com/blog/why-von-neumann-architecture-is-impeding-the-power-of-ai-computing"><strong>IBM Research — How the von Neumann bottleneck is impeding AI computing</strong></a></li><li><a href="https://diveintosystems.org/book/C5-Arch/index.html"><strong>Dive Into Systems (Computer Architecture)</strong></a></li><li><a href="https://www.arteris.com/blog/the-soc-interconnect-fabric-a-brief-history/"><strong>Cache Coherence &amp; Interconnect Fabric</strong></a></li><li><a href="https://en.wikipedia.org/wiki/Cache_inclusion_policy"><strong>Cache inclusion policy</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0397912b97f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond CAP: Why PACELC Deserves More Attention in Distributed Systems]]></title>
            <link>https://medium.com/@humble_bee/beyond-cap-why-pacelc-deserves-more-attention-in-distributed-systems-ec1a798ffa47?source=rss-43c33ea8bc34------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec1a798ffa47</guid>
            <category><![CDATA[distributed-computing]]></category>
            <category><![CDATA[pacelc]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[pacelc-theorem]]></category>
            <category><![CDATA[cap-theorem]]></category>
            <dc:creator><![CDATA[Dinesh]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 08:16:58 GMT</pubDate>
            <atom:updated>2024-12-18T15:59:23.669Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2iksVMs953KhGmxg.jpeg" /></figure><p>If you’ve been exploring distributed systems, you’ve probably (nope, surely) heard of CAP Theorem everywhere. It’s often thrown around in blogs, tutorials, and YouTube videos to explain the trade-offs between <strong>Consistency</strong>, <strong>Availability</strong>, and <strong>Partition Tolerance</strong>.</p><p>But what if I told you CAP only tells half the story? It focuses exclusively on what happens when your network splits — when there’s a <strong>partition</strong>. But distributed systems don’t fail all the time (hopefully!), and when the system is running <strong>normally</strong>, CAP stays silent.</p><p>Enter <strong>PACELC</strong> — a model that explains ..</p><blockquote>“What happens when there’s <strong>no partition</strong>?” 👀</blockquote><p><strong>because systems don’t fail <em>all the time</em>, right?.</strong> Yet for some reason, surprisingly, PACELC isn’t talked about much, even though it’s far more <strong>practical</strong> for real-world systems. Let’s break it down and understand why PACELC deserves more love.</p><h4>Quick Recap: What Is CAP Theorem?</h4><p>The <strong>CAP Theorem</strong> (introduced by Eric Brewer in 2000) says:</p><p>A distributed system must be either <strong>CP (Consistency and Partition Tolerant)</strong> or <strong>AP (Availability and Partition Tolerant)</strong> during network partitions.</p><ul><li><strong>C</strong>: Consistency (every node sees the same, up-to-date data).</li><li><strong>A</strong>: Availability (every request gets a response).</li><li><strong>P</strong>: Partition Tolerance (system continues to work despite network failures)</li></ul><p><strong>Trade-off</strong>: During a <strong>network partition</strong> (P), you must choose between:</p><ol><li><strong>Consistency</strong> → Reject responses that are stale.</li><li><strong>Availability</strong> → Allow stale or incomplete responses but ensure a reply is sent.</li></ol><p><strong>Example</strong>: Imagine you’re using an online bank. If there’s a network failure:</p><ul><li>A <strong>CP system</strong> (Consistency + Partition Tolerance) will reject transactions temporarily to avoid inconsistent data.</li><li>An <strong>AP system</strong> (Availability + Partition Tolerance) will let transactions through but might show a slightly stale balance for a few seconds.</li></ul><p>As we can see from above example that in <br> → In a <strong>perfect CP system</strong>, a transaction is only completed after updates are replicated to all nodes. While this ensures consistency, it sacrifices performance and availability. If even one node fails or becomes slow, the transaction cannot proceed. Latency also increases as the number of nodes grows.<br> → In a <strong>perfect AP system</strong>, all nodes must respond under any circumstances. Even if the network is partitioned and consistency is broken, availability is guaranteed by ensuring responses from isolated nodes, which might lead to incorrect/old data.</p><p>However, <strong>perfect CP and perfect AP systems are impractical</strong> in the real world. A <strong>perfect CP system</strong> becomes too slow and fragile, while a <strong>perfect AP system</strong> sacrifices critical data consistency. Instead of choosing one extreme, systems need to find a balance that suits their specific requirements.</p><p>CAP is simple, clean, and easy to remember — which is why everyone loves it. But here’s the kicker:</p><p><strong>What happens when the network is fine? </strong>🤔</p><p>CAP doesn’t tell us how to balance <strong>latency</strong> (how fast responses are) with <strong>consistency</strong> during normal operations. Enter <strong>PACELC</strong>.</p><h3>PACELC: The Complete Story</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/0*AJmD7DRmhlO6daPT.png" /></figure><p>Introduced by <a href="https://www.cs.umd.edu/~abadi/papers/abadi-pacelc.pdf">Daniel Abadi</a> in 2010, <strong>PACELC (</strong>“pass-elk”) extends CAP by adding an <strong>ELSE</strong> condition:</p><blockquote><strong><em>→ If there is a partition (P):</em></strong><em> Trade-off between Availability (A) and Consistency ( C ). [CAP]<br></em><strong><em>ELSE (E), <br> → when the system is running normally:</em></strong><em> Trade-off between </em><strong><em>Latency (L)</em></strong><em> and </em><strong><em>Consistency ( C )</em></strong><em>.</em></blockquote><h4>Breaking It Down</h4><ol><li><strong>P</strong> (During Partition):<br> → Just like CAP: you choose between <strong>Availability </strong>and <strong>Consistency</strong></li><li><strong>E L C</strong> (Else, when no Partition):<br> → You decide between <strong>Low Latency </strong>and <strong>Consistency.</strong></li></ol><h3>Why Does PACELC Matter?</h3><p>If network partitioning occurs, it means that there is a trade-off between<strong> availability </strong>and<strong> consistency</strong> as suggested by CAP theory , and if not, there is a trade-off between <strong>time delay </strong>and <strong>consistency</strong>.</p><p>PACELC is more relevant for <strong>practitioners</strong> and system architects who:</p><ul><li>Build or evaluate real-world distributed systems.</li><li>Care about fine-grained trade-offs beyond partition failures.</li></ul><p>Each system’s design aligns with specific business goals:</p><ul><li><strong>Fast, available systems</strong> like DynamoDB and Cassandra suit real-time, fault-tolerant use cases.</li><li><strong>Consistent, robust systems</strong> like Spanner and HBase suit critical workloads requiring correctness.</li></ul><p>Let’s step into the real world for a moment. Imagine two scenarios:</p><h4>Scenario 1: Amazon DynamoDB (Low Latency Focus)</h4><p>Let’s say you’re shopping on Amazon. You add an item to your cart, but the update hasn’t yet reached a secondary server due to delays. Does Amazon stop you from adding to the cart? Of course not!</p><ul><li>Amazon prioritizes <strong>Availability (A)</strong> during a failure (CAP).</li><li>During normal operations (PACELC), it prioritizes <strong>Latency (L)</strong> over strong consistency to provide a <strong>snappy user experience</strong>.</li></ul><p>The data might be slightly inconsistent for a short time, but the system remains highly responsive and available.</p><h4>Scenario 2: Google Spanner (Strong Consistency Focus)</h4><p>Now imagine you’re transferring money between two bank accounts. You wouldn’t want one server to show “$0” while another shows “$10,000”, right?</p><p>Google Spanner prioritizes <strong>strong consistency ( C ) </strong>at the cost of higher latency, both during network partitions and during normal operation.</p><p>This ensures that you <strong>always see the correct data</strong>, no matter the trade-offs.</p><p>So, we can see that —</p><ol><li><strong>DynamoDB and Cassandra</strong>:</li></ol><ul><li>Prioritize Availability and Low Latency → Eventual consistency.</li><li><strong>PACELC</strong>: Availability during partitions (A), Low Latency during normal operation (L).</li></ul><p><strong>2. Google Spanner</strong>:</p><ul><li>Prioritizes strong consistency → higher latency.</li><li><strong>PACELC</strong>: Consistency during partitions ( C ), Consistency during normal operation ( C )</li></ul><blockquote><em>“PACELC gives us a </em><strong><em>more complete model</em></strong><em> for designing systems. Real-world systems balance trade-offs between Consistency, Availability, and Latency every day.”</em></blockquote><h3>How PACELC Applies to Real Systems</h3><p>Here’s how modern distributed systems fit into <strong>PACELC</strong> and the reasoning behind their trade-offs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*xjdeSBuiz_Xw8YrKNIGkhA.png" /></figure><h3>Detailed Insights</h3><ol><li><strong>Amazon DynamoDB</strong>:</li></ol><ul><li>DynamoDB is optimized for applications requiring high availability and fast responses, such as real-time gaming or e-commerce. During partitions, it sacrifices strong consistency to ensure every node remains available.</li><li>Under normal conditions, it trades strict consistency for low latency, providing <strong>eventual consistency</strong>.</li></ul><p><strong>2. Google Spanner</strong>:</p><ul><li>Spanner is designed for applications that demand global correctness, like financial transactions. It prioritizes <strong>strong consistency</strong> by synchronizing data across regions using atomic clocks and GPS.</li><li>Both during partitions and normal operations, it sacrifices latency for correctness.</li></ul><p><strong>3. Cassandra</strong>:</p><ul><li>Cassandra’s design is optimized for write-heavy and scalable systems like IoT or logs. It uses a tunable consistency model (e.g., quorum reads/writes) and prioritizes <strong>availability</strong> during failures.</li><li>Under normal conditions, it provides low-latency reads/writes by allowing minor inconsistencies.</li></ul><p><strong>4. HBase</strong>:</p><ul><li>HBase focuses on strong consistency by using a master-slave architecture and write-ahead logs. It’s ideal for workloads requiring ordered, consistent writes, such as time-series databases.</li><li>Both during partitions and normal conditions, HBase sacrifices availability for data correctness.</li></ul><p>These systems demonstrate that PACELC trade-offs are <strong>everywhere</strong>, even if we don’t name them.</p><h3>Takeaway: Why You Should Care About PACELC</h3><p>If you’re building or evaluating distributed systems, CAP isn’t enough. You need PACELC to:</p><ol><li>Understand how systems behave <strong>during network failures</strong> (P).</li><li>Design for <strong>low latency vs. strong consistency</strong> under normal operation (ELC).</li></ol><h4>Real-World Insight</h4><ul><li>Choose <strong>AP systems</strong> (like DynamoDB) for low-latency, high-availability use cases where eventual consistency is acceptable.</li><li>Choose <strong>CP systems</strong> (like Spanner) when strong consistency is critical, even at the cost of latency.</li></ul><h3>Conclusion</h3><p>So, next time someone says “CAP Theorem,” politely ask them:</p><blockquote><em>“But what about PACELC? What happens when there’s no partition?”</em></blockquote><p>You’ll likely get a blank stare, and that’s your cue to drop some knowledge. PACELC fills the gap CAP left behind, and it’s time we give it the attention it deserves. I feel the reason it’s not talked about much because its I<strong>mplicit in System Design. </strong>Many engineers already design systems that inherently follow PACELC principles, even if they don’t explicitly call it out.</p><p>So, next time you design or evaluate a distributed system, don’t stop at CAP. Think about PACELC — and choose the trade-offs that fit your goals.</p><p>Distributed systems are all about trade-offs. PACELC helps us make <strong>better decisions</strong> for real-world systems.</p><p>References:</p><ul><li>Paper: <a href="https://www.cs.umd.edu/~abadi/papers/abadi-pacelc.pdf">https://www.cs.umd.edu/~abadi/papers/abadi-pacelc.pdf</a></li><li><a href="https://www.scylladb.com/glossary/pacelc-theorem/">https://www.scylladb.com/glossary/pacelc-theorem/</a></li><li><a href="https://www.linkedin.com/pulse/consistency-vs-latency-globally-distributed-databases-kanagala-t1qwe/">https://www.linkedin.com/pulse/consistency-vs-latency-globally-distributed-databases-kanagala-t1qwe/</a></li><li><a href="https://docs.yugabyte.com/preview/architecture/design-goals/">https://docs.yugabyte.com/preview/architecture/design-goals/</a></li><li><a href="https://eitca.org/cloud-computing/eitc-cl-gcp-google-cloud-platform/gcp-labs/scalable-database-service-with-cloud-spanner/examination-review-scalable-database-service-with-cloud-spanner/how-does-cloud-spanner-achieve-both-strong-transactional-consistency-and-horizontal-scalability/#:~:text=Cloud%20Spanner%20achieves%20strong%20consistency,across%20all%20Cloud%20Spanner%20nodes">https://eitca.org/cloud-computing/eitc-cl-gcp-google-cloud-platform/gcp-labs/scalable-database-service-with-cloud-spanner/examination-review-scalable-database-service-with-cloud-spanner/how-does-cloud-spanner-achieve-both-strong-transactional-consistency-and-horizontal-scalability/</a></li><li><a href="https://cloud.google.com/spanner/docs/transactions">https://cloud.google.com/spanner/docs/transactions</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec1a798ffa47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why is Memory Safety Without GC a Big Deal in RUST?]]></title>
            <link>https://medium.com/@humble_bee/why-is-memory-safety-without-gc-a-big-deal-in-rust-41f6bdd5902f?source=rss-43c33ea8bc34------2</link>
            <guid isPermaLink="false">https://medium.com/p/41f6bdd5902f</guid>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <dc:creator><![CDATA[Dinesh]]></dc:creator>
            <pubDate>Mon, 16 Dec 2024 23:37:13 GMT</pubDate>
            <atom:updated>2024-12-22T18:27:43.072Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Un4zxhADSU-RhZhS3ZLlEw.png" /></figure><p>Memory safety is one of the most crucial aspects of modern programming, ensuring that your programs don’t crash, leak memory, or behave unpredictably. For decades, languages have struggled to strike a balance between <strong>performance</strong>, <strong>safety</strong>, and <strong>developer control</strong>. On one side, languages like <strong>C++</strong> offer full control but require manual memory management, leaving developers prone to bugs like dangling pointers and memory leaks. On the other side, languages like <strong>Java</strong> use <strong>Garbage Collection (GC)</strong> to automate cleanup, but at the cost of unpredictable pauses, runtime overhead, and increased resource usage.</p><p>Then came <strong>Rust</strong>, a language that flipped the script. Rust guarantees <strong>memory safety without a Garbage Collector</strong>, achieving performance on par with C++ while eliminating an entire class of bugs <strong>at compile time</strong>. This is why Rust’s approach to memory safety is not just “nice” — revolutionary!</p><p>But why is this such a big deal? After all, C++ doesn’t use GC either, and Java ensures safety with GC. Why does Rust’s memory model get so much praise? The answer lies in how Rust solves the problem: it combines the <strong>performance of C++</strong>, the <strong>safety of GC-based languages</strong>, and a developer-friendly <strong>ownership system</strong> that makes memory management automatic, efficient, and deterministic.</p><p>In this blog, we’ll explore <strong>why memory safety without GC is a game-changer</strong>, how Rust achieves it, and why it’s being praised as the future of safe, fast, and reliable programming.</p><h3>1. What’s the Problem with Garbage Collection?</h3><p>Languages like Java and Python use Garbage Collection to automatically reclaim unused memory. While GC simplifies a developer’s life by automating cleanup, it has significant downsides:</p><h4>Latency</h4><p>Garbage collectors pause program execution to clean up unused memory. These “stop-the-world” events cause <strong>unpredictable pauses</strong>, which can ruin real-time systems, games, or applications with tight latency requirements.</p><h4>Performance Overhead</h4><p>Tracking unused memory and running cleanup consumes CPU cycles, increasing runtime overhead. This extra cost can be unacceptable in performance-critical domains.</p><h4>Resource Usage</h4><p>Garbage Collection requires additional memory to manage the heap efficiently. This is not ideal for <strong>embedded systems</strong> or resource-constrained environments.</p><h4>Loss of Control</h4><p>With GC, developers cannot predict <strong>when</strong> memory will be reclaimed. This lack of fine-grained control complicates optimizations and resource management.</p><p>While GC-based languages guarantee <strong>safety</strong>, they trade off control and predictable performance.</p><h3>2. How Does Rust Achieve Memory Safety Without GC?</h3><p>Rust avoids the pitfalls of garbage collection through its <strong>Ownership System</strong>, enforced at compile time. The core components of this system are <strong>ownership</strong>, <strong>borrowing</strong>, and <strong>lifetimes</strong>.</p><h4>Ownership</h4><ul><li>Each value in Rust has a single <strong>owner</strong>.</li><li>When the owner goes out of scope, the memory is automatically deallocated.</li><li>This is <strong>deterministic</strong> and requires no runtime tracking.</li></ul><pre>fn main() {<br>    let s = String::from(&quot;hello&quot;);<br>    println!(&quot;{}&quot;, s);<br>} // `s` is dropped here; memory is freed automatically.</pre><h4>Borrowing</h4><p>Instead of transferring ownership, Rust allows <strong>references</strong> to data:</p><ul><li><strong>Immutable References (</strong><strong>&amp;T)</strong>: Allow shared, read-only access.</li><li><strong>Mutable References (</strong><strong>&amp;mut T)</strong>: Allow exclusive, write access.</li></ul><p>Rust’s <strong>borrow checker</strong> ensures:</p><ul><li>No two mutable references coexist.</li><li>No data is accessed after it’s freed.</li></ul><pre>fn main() {<br>    let mut x = 5;<br>    let y = &amp;x; // Immutable borrow<br>    println!(&quot;{}&quot;, y);<br>    <br>    let z = &amp;mut x; // Mutable borrow; safe because `y` is no longer used.<br>    *z += 1;<br>    println!(&quot;{}&quot;, x);<br>}</pre><h4>Lifetimes</h4><p>Lifetimes ensure references remain valid only for as long as they’re needed, preventing dangling pointers.</p><p><strong>Result</strong>: Rust <strong>statically guarantees</strong> memory safety at <strong>compile time</strong>, avoiding runtime GC overhead entirely.</p><h3>3. Rust vs C++: The No-GC Battle</h3><p>C++ also avoids garbage collection, relying on <strong>manual memory management</strong>:</p><p>Developers use new/delete or smart pointers (std::unique_ptr, std::shared_ptr).</p><p>While powerful, but manual management is error-prone and can lead to:</p><ul><li><strong>Memory Leaks</strong>: Forgetting to free memory.</li><li><strong>Dangling Pointers</strong>: Accessing freed memory.</li><li><strong>Double Frees</strong>: Deallocating memory twice.</li><li><strong>Data Races</strong>: Unsafe access in multithreaded programs.</li></ul><h4>How Rust Wins Over C++</h4><ol><li><strong>Safety</strong>: Rust prevents all memory issues (leaks, dangling pointers, double frees) <strong>by design</strong>.</li><li><strong>Concurrency</strong>: Rust’s borrow checker guarantees <strong>thread safety</strong>, eliminating data races.</li><li><strong>Ergonomics</strong>: Rust’s memory safety is automatic and enforced by the compiler, whereas C++ requires careful manual checks.</li></ol><p>Rust delivers the same performance as C++ but with fewer bugs and less developer effort.</p><h3>4. Rust vs Java: Why Rust Doesn’t Need GC</h3><p>Java uses Garbage Collection to ensure memory safety, but this comes at a cost:</p><h4>GC-Induced Latency</h4><p>Garbage Collection introduces unpredictable pauses:</p><ul><li><strong>Real-Time Systems</strong>: GC is unacceptable in applications requiring low latency (e.g., games, audio processing).</li><li><strong>Rust</strong>: Memory is freed deterministically when it goes out of scope — no pauses, no surprises.</li></ul><h4>Performance Overhead</h4><ul><li><strong>Java</strong>: GC adds runtime costs for memory tracking and cleanup.</li><li><strong>Rust</strong>: Ownership eliminates the need for GC, with zero runtime overhead.</li></ul><h4>Resource Usage</h4><ul><li><strong>Java</strong>: GC requires additional heap space and CPU cycles.</li><li><strong>Rust</strong>: Efficient memory usage makes it ideal for resource-constrained environments like <strong>embedded systems</strong> and IoT devices.</li></ul><h4>Control</h4><p>Java abstracts away memory management, reducing control over performance. Rust gives you fine-grained control while maintaining safety guarantees.</p><h3>5. Why Memory Safety Without GC Is a Game-Changer</h3><h4>Real-Time Performance</h4><p>In systems programming, <strong>predictable performance</strong> is non-negotiable. Rust’s deterministic memory management makes it ideal for:</p><ul><li>Operating systems</li><li>Game engines</li><li>Network services</li><li>High-frequency trading systems</li></ul><h4>Safety with Zero Overhead</h4><p>Rust eliminates memory bugs <strong>at compile time</strong>, providing:</p><ul><li><strong>No dangling pointers</strong></li><li><strong>No double frees</strong></li><li><strong>No memory leaks</strong></li></ul><p>All of this comes with <strong>zero runtime cost</strong> — something GC-based languages can’t offer.</p><h4>Embedded Systems and Resource-Constrained Environments</h4><p>Rust’s lightweight memory model works seamlessly in low-memory environments like embedded systems, where GC overhead is unacceptable.</p><h3>Beyond Systems Programming: Where Rust Excels?</h3><p>Rust’s lack of GC isn’t just for operating systems — it’s making waves in other domains too:</p><ul><li><strong>Web Development</strong>: Frameworks like <strong>Actix</strong> and <strong>Axum</strong> offer high-performance backends without GC pauses.</li><li><strong>Game Development</strong>: Engines like <strong>Bevy</strong> ensure smooth performance with zero GC stutters.</li><li><strong>Blockchain</strong>: Rust’s safety and performance are ideal for writing smart contracts and cryptographic libraries.</li><li><strong>Embedded Systems</strong>: Rust’s zero-cost abstractions make it perfect for IoT and real-time systems.</li></ul><h3>Digging Deeper: How Does Rust’s Safety Work? The Case of Bounds Checking 🛡️</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dhOgF-WGeQGmxSefse7nZA.png" /></figure><p>Earlier, we discussed how Rust avoids <strong>manual memory management pitfalls</strong> seen in C++ while offering similar performance. But a natural question arises:</p><blockquote><strong><em>If C++ also avoids GC and allows same (manual) optimizations (by developers), what makes Rust’s safety and speed stand out?</em></strong></blockquote><p>Let’s explore a key mechanism: <strong>bounds checking</strong>, its impact on performance, and where Rust’s design shines.</p><h4>1. Bounds Checking: Built-In Safety by Default</h4><p>Whenever you access an array or vector in Rust, the compiler ensures that the index is within valid bounds. If it isn’t, Rust <strong>panics</strong> at runtime to prevent undefined behavior like accessing invalid memory or corrupting data.</p><ul><li>In <strong>Rust</strong>, bounds checking happens <strong>automatically</strong> for each array access:</li></ul><pre>let array = vec![1, 2, 3];<br>println!(&quot;{}&quot;, array[3]); // Panics at runtime: Out of bounds!</pre><p>Rust checks index &lt; array.len() behind the scenes and prevents <strong>out-of-bounds access</strong>.</p><ul><li>In C++, bounds checking is not automatic, the same needs be done <strong>manually:</strong></li></ul><pre>std::vector&lt;int&gt; array = {1, 2, 3};<br>if (index &lt; array.size()) {    // Manual bounds check<br>    std::cout &lt;&lt; array[index] &lt;&lt; std::endl;<br>}</pre><p>Here, the developer must explicitly write the bounds check. If you don’t, accessing out-of-bounds memory may result in crashes, corrupted data, or silent bugs.</p><h4>2. Doesn’t Bounds Checking Add Overhead?</h4><p>Yes, bounds checking adds a small performance overhead cost, especially for <strong>large arrays</strong> or tight loops. <strong>Whether in C++ (manually written) or Rust (automatically added), this overhead exists.</strong> So, the natural question is:</p><blockquote><strong><em>“If both Rust and C++ perform bounds checking, isn’t their performance the same?”</em></strong></blockquote><p>This is where Rust’s design makes a difference:</p><ul><li>Rust’s <strong>compiler optimizations</strong> ensure that bounds checks are minimized or eliminated when possible. For example, in a loop iterating over a range (for i in 0..array.len()), Rust often removes redundant checks because the safety of the access is provable at compile time.</li><li>C++ relies on the developer to write checks, and while compilers like Clang or GCC can optimize manual checks, it requires more effort and care from the developer.</li></ul><h4>3. Iterators: Rust’s Elegant Solution</h4><p>In Rust, <strong>iterators</strong> provide a safe, efficient, and idiomatic way to access elements in a collection. Unlike manual loops, iterators inherently avoid bounds checking overhead because they only traverse valid indices.</p><pre>let array = vec![1, 2, 3];<br>for item in array.iter() {<br>    println!(&quot;{}&quot;, item); // No bounds checks needed<br>}</pre><ul><li>Iterators ensure that every element accessed is valid, making them both safe and efficient.</li><li>The compiler optimizes iterators into raw loops, achieving performance equivalent to — or sometimes better than — manual indexing.</li></ul><p>In C++, while iterators also exist (std::vector::iterator), they don’t inherently guarantee safety. Rust’s iterators combine safety and performance in a way that’s hard to match.</p><h3>What’s the Bigger Picture?</h3><p>While raw performance may sometimes favor C++, Rust’s memory safety model eliminates an entire class of bugs without relying on garbage collection. Consider:</p><ol><li><strong>Memory Safety Without Trade-Offs</strong>:</li></ol><ul><li>Rust guarantees no dangling pointers, no double frees, and no memory leaks — without the need for a runtime GC.</li><li>C++ leaves these issues to the developer, increasing the risk of runtime errors.</li></ul><p><strong>2. Iterators and Zero-Cost Abstractions</strong>:</p><ul><li>Rust’s iterators are a prime example of how safety can coexist with performance. They abstract away common pitfalls while compiling down to highly efficient machine code.</li><li>In C++, achieving similar safety and performance often requires careful manual coding and testing.</li></ul><p><strong>3. Predictable Performance</strong>:</p><ul><li>In Rust, memory safety and bounds checking are deterministic, with no unpredictable pauses like those caused by garbage collection.</li><li>This makes Rust ideal for real-time systems, embedded programming, and high-performance applications.</li></ul><p>In short, Rust doesn’t just offer performance — it offers <strong>reliable performance</strong>, allowing developers to focus on building robust systems without worrying about memory safety bugs.</p><h3>Conclusion</h3><p>Rust proves that you don’t need a Garbage Collector to guarantee memory safety. By leveraging the <strong>ownership system</strong>, Rust achieves:</p><ul><li><strong>Memory safety</strong> without runtime overhead.</li><li><strong>Deterministic performance</strong> with no GC pauses.</li><li><strong>Control and efficiency</strong> without sacrificing developer productivity.</li></ul><p>Compared to C++, Rust eliminates memory bugs and concurrency issues at <strong>compile time</strong>. Compared to Java, Rust delivers predictable performance and low resource usage, making it ideal for real-time and high-performance systems.</p><p>Rust isn’t just another systems programming language — it’s redefining how we think about memory management.</p><p>REFERENCES:<br>- <a href="https://nested.substack.com/p/safety">https://nested.substack.com/p/safety</a><br>- <a href="https://users.rust-lang.org/t/we-all-know-iter-is-faster-than-loop-but-why/51486/4">https://users.rust-lang.org/t/we-all-know-iter-is-faster-than-loop-but-why/51486/4</a><br>- <a href="https://www.reddit.com/r/rust/comments/11f00kc/huge_performance_gap_in_simple_loop_explanations/">https://www.reddit.com/r/rust/comments/11f00kc/huge_performance_gap_in_simple_loop_explanations/</a><br>- <a href="https://users.rust-lang.org/t/we-all-know-iter-is-faster-than-loop-but-why/51486/15">https://users.rust-lang.org/t/we-all-know-iter-is-faster-than-loop-but-why/51486/15</a><br>- <a href="https://steveklabnik.com/writing/borrow-checking-escape-analysis-and-the-generational-hypothesis">https://steveklabnik.com/writing/borrow-checking-escape-analysis-and-the-generational-hypothesis</a></p><blockquote>UNDER DEVELOPMENT … Detailed performance comparison pending! (You might not see the performance gains in simple loops in Rust, as it requires specific compiler optimizations, careful use of iterators, and understanding of safety trade-offs compared to C++.)</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41f6bdd5902f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Embeddings, Vectors, and Vector Databases]]></title>
            <link>https://medium.com/@humble_bee/demystifying-embeddings-vectors-and-vector-databases-3e5187db4ea7?source=rss-43c33ea8bc34------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e5187db4ea7</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[embedding]]></category>
            <dc:creator><![CDATA[Dinesh]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 19:11:38 GMT</pubDate>
            <atom:updated>2024-01-30T19:11:38.537Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SKno-yhS-HzahbaUASdQhg.jpeg" /></figure><p>Ever wondered how artificial intelligence effortlessly understands the meaning behind words, images, or even entire documents?</p><p>Join us on a journey as we unravel the mysteries of embeddings, vectors, and vector databases — the unsung heroes shaping the intelligence of modern machines. Ready to delve into the heart of data transformation?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*znJO0qS602NxFg-FwV-FmQ.png" /><figcaption>Source: pinecone.io</figcaption></figure><p>Rerences:</p><ul><li><a href="https://cloud.google.com/blog/topics/developers-practitioners/find-anything-blazingly-fast-googles-vector-search-technology">https://cloud.google.com/blog/topics/developers-practitioners/find-anything-blazingly-fast-googles-vector-search-technology</a></li><li><a href="https://www.youtube.com/watch?v=ySus5ZS0b94">OpenAI Embeddings and Vector Databases Crash Course — YouTube</a></li><li><a href="https://stablecog.com/blog/the-best-vector-database-for-stablecogs-semantic-search">https://stablecog.com/blog/the-best-vector-database-for-stablecogs-semantic-search</a></li><li><a href="https://www.manning.com/books/build-a-large-language-model-from-scratch?a_aid=raschka&amp;a_bid=4c2437a0&amp;chan=mm_linkedin">https://www.manning.com/books/build-a-large-language-model-from-scratch</a></li><li><a href="https://www.engati.com/blog/vector-search">An introduction to Vector Search &amp; the search algorithms | Engati</a></li><li><a href="https://www.pinecone.io/learn/vector-search-basics/">Introduction to Vector Search for Developers | Pinecone</a></li><li><a href="https://www.linkedin.com/pulse/demystifying-embeddings-beginners-guide-krish-thukral-t8egc/">Demystifying Embeddings: A Beginner’s Guide | LinkedIn</a></li><li><a href="https://www.youtube.com/watch?v=nQkmgCtVz5k">Milvus vector database in 150 Seconds (youtube.com)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e5187db4ea7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Attention Before Prediction Please!]]></title>
            <link>https://medium.com/@humble_bee/attention-before-prediction-please-75fc74cfb87f?source=rss-43c33ea8bc34------2</link>
            <guid isPermaLink="false">https://medium.com/p/75fc74cfb87f</guid>
            <dc:creator><![CDATA[Dinesh]]></dc:creator>
            <pubDate>Sat, 17 Apr 2021 10:18:56 GMT</pubDate>
            <atom:updated>2021-04-17T10:18:56.160Z</atom:updated>
            <content:encoded><![CDATA[<p>At a high-level, an attention mechanism enables your neural network to focus on relevant parts of your input more than the irrelevant parts when doing a prediction task.</p><p>Attention aims to capture something we do as humans. E.g. if you are manually translating a long sentence from one language to another, at any given point you will be focusing more on the specific word or phrase that you are translating, no matter where it lies in the input sentence. Attention recreates this mechanism for neural networks.</p><p>The attention mechanism is most often used in sequence-to-sequence models. Without an attention mechanism, your model has to capture the essence of the entire input sequence in a single hidden state (represented by S in the diagram below), the encoder encodes the input sequence into a fixed-length context vector. This vector is an internal representation of the text. This context vector is then decoded into the output sequence by the decoder. This is very hard to do in practice, and this problem gets worse the longer your input sequence is because the neural network compresses all the information of an input source sentence into a fixed-length vector. It has been shown that this leads to a decline in performance when dealing with long sentences. The attention mechanism was introduced by Bahdanau in “<a href="https://arxiv.org/abs/1409.0473">Neural Machine Translation by Jointly Learning to Align and Translate</a><strong>” </strong>to alleviate this problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*KvrqE7tCNegmoxXzztCpnQ.png" /><figcaption>Basic Encoder-Decoder architecture (without Attention)</figcaption></figure><p>The Attention mechanism enhances this model by enabling you to “glance back” at the input sentence at each step of your decoder stage. Each decoder output now depends not just on the last decoder state, but on a weighted combination of all the input states.</p><blockquote>The basic idea: each time the model predicts an output word, it only uses parts of an input where the most relevant information is concentrated instead of an entire sentence. In other words, it only pays attention to some input words.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*o8hzODWjLdslhu6UEhXXlA.png" /><figcaption>Encoder-Decoder architecture with Attention</figcaption></figure><p>Given that all that the attention mechanism adds is additional structure to your network, it is learned as part of the standard model training via backpropagation. You don’t need to do anything special for it.</p><p>####</p><p>After obtaining all of our encoder outputs, we can start using the decoder to produce outputs. <br><em>At each time step of the decoder, we have to calculate the alignment score of each encoder output with respect to the decoder input and hidden state at that time step.</em></p><blockquote>The alignment score is the essence of the Attention mechanism, as it quantifies the amount of “Attention” the decoder will place on each of the encoder outputs when producing the next output.</blockquote><p>##<br> More broadly, attentional interfaces can be used whenever one wants to interface with a neural network that has a repeating structure in its output.</p><p># References:<br> <a href="http://www.abigailsee.com/2017/04/16/taming-rnns-for-better-summarization.html">http://www.abigailsee.com/2017/04/16/taming-rnns-for-better-summarization.html</a></p><p><a href="https://blog.floydhub.com/attention-mechanism/">https://blog.floydhub.com/attention-mechanism/</a></p><p>Under development ….</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75fc74cfb87f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OS Fundamentals (Programmer’s Perspective)]]></title>
            <link>https://medium.com/@humble_bee/os-fundamentals-programmers-perspective-97e5bde086d6?source=rss-43c33ea8bc34------2</link>
            <guid isPermaLink="false">https://medium.com/p/97e5bde086d6</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[os-fundamentos]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Dinesh]]></dc:creator>
            <pubDate>Wed, 19 Feb 2020 05:01:23 GMT</pubDate>
            <atom:updated>2020-02-19T05:01:23.327Z</atom:updated>
            <content:encoded><![CDATA[<h3>Comparison (Stack vs Heap)</h3><p># <strong>Stack</strong></p><p>In C++ stack memory is a place where local variables are stored upon declaration. The stack is also used for storage of parameters passed to function. The stack is a LIFO( <strong>L</strong>ast <strong>I</strong>n <strong>F</strong>irst <strong>O</strong>ut) data structure that is organized and controlled by the CPU. Every time that an action inside of a function triggers the declaration of a new variable, it is pushed onto the stack by that parent function. After that when function exits, and resolves its work, all of the data from variables, which are pushed into the stack are freed and that part of memory becomes available for other data. The advantage of using the stack region of memory for variable storage is that memory is managed by the CPU, freeing you from any concerns. Another advantage of this approach is that the CPU is in charge and in control during this process. With that in mind, you get an optimized and efficient process.</p><p>Generally speaking stack is a limited resource and it shouldn’t be used for anything large in memory size. Problems like out of memory stack is stack buffer overflow. It’s a serious problem to solve and it can be encountered in small, primitive systems, such as micro-controllers found in embedded systems.</p><pre>int stackFunction(int x){<br>    // integer y is stored into stack<br>    int y = 5;<br>    x+=y;<br>    // in the moment when this function exits, or returns a value, <br>    // stack removes space occupied by y &amp; shrinks the stack itself<br>    return x;<br>}</pre><p># <strong>Heap</strong></p><p>The heap is a part (region) of a computer’s memory that is free for use by a user and isn’t managed by CPU or any onboard mechanism. It can be observed as a free-floating region of memory and is typically substantially larger in memory size than the stack.</p><p>Accessing the heap from C++ is done using typical memory management tools like pointers and the whole concept behind them. Heap memory is <em>allocated</em> , and because you don’t have any backup tool which will clean and tidy your actions you are left with a responsibility of freeing used memory upon completion of your program. Plainly put, heap memory is memory that gets left over after the program loads and the stack memory gets allocated. Running out of heap memory can (and probably will) result in thrown error of type std:: bad_alloc. This can be encountered typically in a recursive functions and implementations.</p><pre>// we are allocating char of value &#39;C&#39; to the heap<br>char *ptr = <strong>new</strong> char(&#39;C&#39;);<br><br>// preventing memory leakage<br>// by freeing used memory<br><strong>delete</strong> ptr;</pre><h3>The Stack</h3><ol><li>only local variables</li><li>resizing of variables cannot be done (Static/Fixed size)</li><li>efficiently managed space by CPU, memory does not become fragmented</li><li>very quick access</li><li>there is a limit on stack size (OS-dependent)</li><li>explicit de-allocation of variables is not mandatory</li></ol><h3>The Heap</h3><ol><li>memory must be managed (explicit deallocation is needed).<br> It isn’t managed by CPU or any onboard mechanism.</li><li>memory size is not limited (very large size)</li><li>access is relatively slower (because data is not stored sequentially like in stack and is randomly anywhere in heap and hence first needed to be found before reading, plus data gets fragmented also. This makes it inefficient and increasingly slower if not managed properly.)</li><li>realloc() is used for the resizing of variables (dynamic)</li><li>variables can be accessed globally</li><li>efficient use of space is not guaranteed, memory can become fragmented over time when blocks of memory are allocated, then freed.</li></ol><h3><strong>Memory Management</strong></h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fp9yZNLeOj4s%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dp9yZNLeOj4s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fp9yZNLeOj4s%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f944b3c3c464957717776e6ed2c69c2/href">https://medium.com/media/1f944b3c3c464957717776e6ed2c69c2/href</a></iframe><p>Things to understand: Segmentation,Paged Memory,Virtual Memory, (Difference between Logical,Physical &amp; Virtual Memory),Segmentation, Fragmentation, Disk Thrashing, Overflow.</p><p>There are three related concepts here:</p><ol><li><strong>Physical</strong> — An actual device</li><li><strong>Logical</strong> — A translation to a physical device</li><li><strong>Virtual </strong>— A simulation of a physical device</li></ol><p>Note: The term “logical memory” is rarely used nowadays because we normally use the term “virtual memory” to cover both the virtual and logical translations of memory.</p><ul><li><strong>Physical memory</strong> is RAM, actually belongs to main memory.It is what the CPU addresses on its address bus. It’s the lowest level software can get to. Physical memory is organized as a sequence of 8-bit bytes, each with a physical address. This is the memory that is actually present and every process needs space here to execute their code.</li><li><strong>Logical address</strong> is the<em> address generated by CPU.<br></em> In paging,logical address is mapped into physical address with the help of page tables. Logical address contains page number and an offset address.</li><li>Virtual memory (“Paging”).</li></ul><p>Page tables are swapped in and out on the fly by the kernel when different programs are run. This allows for optimization and security in process/memory management.</p><p><strong>F</strong>irst of all you should understand <strong>Address Binding.</strong></p><p>Usually a program resides on a disk as a binary executable file. The program must be brought into memory and placed within a process for it to be executed. The collection of processes on the disk that is waiting to be brought into memory for execution forms the <strong>input queue.</strong></p><p>THE normal procedure is to select one process form the input queue and load it into memory. As a process is executed, it accesses instructions and data from memory. Eventually the process terminates and its memory space is reclaimed. Now lets understand the basic memory addresses.</p><p>As normally used, “logical” memory is the address actually used inside your program.</p><p>An address generated by the <strong>CPU</strong> is commonly know as<strong> logical address</strong> whereas an address seen by the<strong> memory unit</strong> — that is the one loaded into the <strong>memory-address registers </strong>of the memory is commonly referred to as <strong>physical address.</strong></p><p>Physical memory is the actual read/write memory hardware on your device. It normally is RAM, but modern systems can make use of other read/write devices on a computer, such as hard drives, Solid-state drives, etc as swap space by treating these using virtual memory methods (see below) as extensions of the possible memory pool available to applications. (Physical memory can also include Read-only memory (ROM).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*7S-UHd-n048jcO_c2arcWQ.png" /></figure><p><strong>Virtual memory </strong>is how most larger-device operating systems actually work. The OS gives you what <em>appears to be a contiguous sequence of memory addresses</em> that map to physical memory, which may be stored in RAM or possibly on disk if there isn’t enough RAM available for all running processes. (If you access an address that is on disk at the moment in your program, it’ll be loaded to RAM by the OS/MMU <strong>(memory-management unit)</strong>, and some other memory will be “paged out”)</p><p>Naturally, paging is extremely slow, which is why once you’ve exceeded your available RAM and “swap space” on disk/SSD is being used, your computer runs visibly more slowly.</p><blockquote>Under Development..</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97e5bde086d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Basics for a Beginner]]></title>
            <link>https://medium.com/@humble_bee/django-basics-for-a-beginner-5d864e6aa084?source=rss-43c33ea8bc34------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d864e6aa084</guid>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[website-design]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Dinesh]]></dc:creator>
            <pubDate>Fri, 31 Jan 2020 17:46:50 GMT</pubDate>
            <atom:updated>2024-09-13T01:20:28.050Z</atom:updated>
            <content:encoded><![CDATA[<h3>Django Essentials: A Beginner’s Introduction</h3><p>Here I’ll mention some basic things to understand for a beginner before starting any web app development in django. This blog will give you the head start for django with proper understanding of basic things.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*7Y-o8gTDAczXDGu8NMAtyg.png" /><figcaption>Django Flow Structure</figcaption></figure><p>Before understanding Django, let’s first understand why do we need a web framework? A web framework is a server-side application framework which is designed to support the development of dynamic websites. With the help of a framework, you don’t have to handle the hassles of web development and its various components. Therefore, it makes the life of a web application developer much easier as they don’t have to code from scratch. There are various web development frameworks available in the market. Some of them are listed below:</p><ul><li>React JS, Angular, Ruby on Rails, Express etc</li></ul><p>One of the highlights of Django is that it is built on python. It follows the principle of “Don’t Repeat Yourself”. As the name says, this principal is all about keeping the code simple and non repeating.</p><ul><li>It takes care of user authentication, content administration, site maps and many more.</li><li>Django<em> </em>is highly secure. It helps the developers to avoid many common security mistakes, such as SQL injection, cross-site scripting, csrf/ xsrf (cross-site request forgery) and click-jacking. Its user authentication system provides a secure way to manage user accounts and passwords.</li><li>It’s pretty scalable. (<a href="https://djangosites.org/">Example</a>: Instagram, Disqus).<br>Django uses a “shared-nothing” architecture, which means you can add hardware at any level — database servers, caching servers or Web/application servers.</li><li>The framework cleanly separates components such as its database layer and application layer. And it ships with a simple-yet-powerful <a href="https://docs.djangoproject.com/en/dev/topics/cache/">cache framework</a>.</li><li>Django is used to build all sort of things (very versatile)— from content management systems to social networks to scientific computing platforms.</li><li>It has various other advantages as it has an automatic administration interface, Object-relational mapper (ORM), RSS feeds and many more.</li><li>Django is also a high level, MVT architecture based.</li></ul><p>##############################</p><ul><li>Dynamically builds web applications.</li><li>Grands ease to build multi-protocol networks.</li><li>Provides quick processing.</li><li>Extremely fast &amp; SEO Optimized.</li></ul><p>So let’s understand the architecture or internal working of Django.</p><h3>Django Architecture</h3><p>Django follows the MVT or <a href="https://pythonistaplanet.com/difference-between-mvc-and-mvt/">Model View Template architecture</a> which is based on the MVC or Model View Controller architecture. The main difference between these two is that Django itself takes care of the controller part.</p><p>MVC stands for <em>Model View Controller</em>. It is used for developing the web applications, where we break the code into various segments. Here we have 3 segments — model, view and a controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*_korbq8yByjtES8-PH54fw.png" /></figure><p><strong>Model</strong> — Model is used for storing and maintaining your data. It is the backend where your database is defined.</p><p><strong>Views</strong> — In Django templates, views are in html. View is all about the presentation and it is not at all aware of the backend. Whatever the user is seeing, it is referred to a view.</p><p><strong>Controller</strong> — Controller is a business logic which will interact with the model and the view.</p><p>Now that we have understood MVC, lets learn about<strong><em> Django MVT pattern</em></strong>.</p><p>MVT stands for <em>Model View Template</em>. In MVT, there is a predefined template for user interface. Let’s take an example, say you want to write several static html forms like hello user1, hello user2 and so on. With template, you will be having only one file that prints hello along with the variable name. Now this variable will be substituted in that particular template using some jinja logic. That’s the magic of template, you don’t need to rewrite the code again n again!</p><p>Now you might be wondering where is the controller?</p><p>In the case of MVT, Django itself takes care of the controller part, it’s inbuilt.<br>That is, it’s probably the framework itself: the machinery that sends a request to the appropriate view, according to the Django URL configuration.</p><p>So, in the case of Django, this is what each component is doing:</p><ul><li>The <strong>MODEL</strong> helps to handle database. It is a data access layer, which contains the required fields and behaviors of the data you’re storing. There’s hardly an application without a database. A model is a Python class, and it does not know anything about other Django layers. Models help developers to create, read, update, and delete objects (CRUD operations) in the original database. Also, they hold business logic, custom methods, properties, and other things related to data manipulation.</li><li>The <strong>VIEW</strong> is used to execute the business logic and interact with a model to carry data and renders a template. The view fetches data from a model. Then, it either gives each template access to specific data to be displayed, or it processes data beforehand. It accepts HTTP requests, applies business logic provided by Python classes and methods, and provides HTTP responses to the client requests.</li><li>The <strong>TEMPLATE</strong> is a presentation layer that handles the User Interface part completely. These are files with HTML code, which is used to render data. The contents of these files can be static or dynamic. A template is used only to present data since there’s no business logic in it.</li></ul><blockquote>A “view” is the Python callback function for a particular URL, because that callback function describes which data is presented.</blockquote><blockquote>Furthermore, it’s sensible to separate content from presentation — which is where templates come in. In Django, a “view” describes which data is presented, but a view normally delegates to a template, which describes <em>how</em> the data is presented.</blockquote><blockquote>The ‘controller’ here is Django itself which sends the request to the appropriate view in accordance with the specified URL. This is why Django is referred to as MTV rather than MVC architecture.</blockquote><p>The developer provides the model, the view, and the template, then maps it to a URL, and Django does the magic, to serve it to the user.</p><p>In short, a web application has data, layout, and logic. The model will work with the data, the view will work with the logic, and the template will work with the layout.</p><p>Moving ahead in Django tutorial, let’s understand how things work internally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nTL9xRiU9H9am0XF.png" /><figcaption>Simple Overview of Django MVT Architecture</figcaption></figure><p>In the image, template is your front end which will interact with the view and the model will be used as a backend. Then view will access both the model and the templates and maps it to a url. After that, Django plays the role of controller and serves it to the user.</p><p><strong>Let’s Understand the Project &amp; Web Application Directory/File Structure</strong></p><p>For creating a web application, first let’s create a project. To create a project, just enter into a directory where you would like to share your code, then run the following command:</p><p>&gt;&gt; django<strong>-</strong>admin startproject <strong><em>myproject</em></strong></p><p>Once your project has been created, you will find a list of files inside the <strong>project directory.</strong> Let’s discuss each one of them.</p><p><strong>manage.py</strong> — It is a command-line utility that lets you interact with this Django project in various ways.</p><p><strong>myproject/</strong> — It is the actual Python package for your project. It is used to import anything, say — myproject.urls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/0*gB0cK22Re3lsQD_P.png" /></figure><p><strong>init.py</strong> — Init just tells the python that this is to be treated like a python package.</p><p><strong>settings.py</strong> — This file manages all the settings &amp; configuration of your project.</p><p><strong>urls.py</strong> — This is the main controller which maps it to your website.</p><p><strong>wsgi.py</strong> — This is an entry-point for the web servers to serve the project you have created. It serves as an entry point for WSGI (Web Server Gateway Interface) compatible web servers. The Web Server Gateway Interface is a simple calling convention for web servers to forward requests to web applications or frameworks written in the Python programming language. It describes how a web server communicates with web applications, and how web applications can be chained together to process one request.</p><p>It is used to forward requests from a web server (such as Apache or <a href="https://www.liquidweb.com/blog/wordpress-multisite/">NGINX</a>) to a backend Python web application or framework. From there, responses are then passed back to the webserver to reply to the requestor.<br> Requests are sent from the client’s browser to the server. WSGI forwards the request to the webserver python app, which then returns the completed request back to the webserver and on to the browser</p><p>As well as WSGI, Django now also supports deploying on <a href="https://asgi.readthedocs.io/en/latest/">ASGI</a>, the emerging Python standard for asynchronous web servers and applications.</p><p>Note that to create your application, make sure you are in the same directory as manage.py and then type the below command:</p><p>python manage.py startapp webapp</p><p>Now if we look at the ‘webapp’ directory, we have some extra things from the original myproject. It includes model, test which are related to your backend databases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*vOcr1d6rafRmSy-bIjrhHQ.png" /><figcaption>Importing our webapp application manually</figcaption></figure><p>Next in Django tutorial, you need to import your application manually inside your project settings. For that, open your myproject/settings.py and add your app manually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*m6JxBRpwCLwEjI5_6uUKiQ.png" /><figcaption>Creating a View</figcaption></figure><p>Once you have installed your app, let’s create a view now. Open your webapp/views.py and put the given code in it:</p><p>In the above code, I have created a view which returns httpResponse. Now we need to map this view to a URL. We need a URLconf in our application. So let’s create a new python file “urls.py” inside our webapp. In webapp/urls.py include the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*YkH3c7ZUocp6onmw07pEpw.png" /><figcaption>Url Mapping (our webapp url to Controller’s main URL)</figcaption></figure><p>In the above code, I have referenced a view which will return index (defined in views.py file). The url pattern is in regular expression format where ^ stands for beginning of the string and $ stands for the end.</p><p>The next step is to point the root URLconf at the webapp.urls module. Open your myproject/urls.py file and write the below code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*NhqyZti5CA_UJM2TVoiKBA.png" /></figure><p>In the above code, I have added my <em>webapp</em> and included the webapp.urls. Now don’t forget to import django.conf.urls.include and insert an include() in the <strong>urlpatterns</strong> list. The include() function allows <em>referencing other</em> <strong>URLconfs</strong>.</p><p>Note that the regular expression doesn’t have a ‘$’ but rather a trailing slash, this means whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to include URLconf for further processing.</p><p>We are now done with the coding part! Let’s now start the server and see what happens. To start the server, type the below command:</p><p>python manage.py runserver</p><p>After running the server, go to <a href="http://localhost:8000/webapp/"><strong>http://localhost:8000/webapp/</strong></a> in your browser, and you should see the text “<em>HEY! Welcome to Edureka!</em>”, which you defined in the index view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/0*iQ7WqY8dij79MsUp.png" /></figure><p><em>Hurray</em>! We have successfully created a basic “hello world” Web App.</p><p>STEPS:</p><ol><li>[Optional] Create a virtual environment<br>&amp; Activate your virtual environment.<br>&gt; <strong>VirtualPythonDirectory\Scripts\activate</strong></li><li>Install Django (in your virtual env) <br>&gt; <strong>pip install django</strong><em><br></em>Check Version:<em> &gt; </em><strong>python -m django — version<br></strong>Note:By default,it’ll install other required dependencies also along with it.</li><li>To check which django commands are available (for creating project, running server and for other things) [READ IN BOTTOM]<em><br>&gt; </em><strong>django-admin</strong></li><li>CREATE/START A PROJECT<br>&gt; <strong>django-admin startproject <em>PROJECT_NAME<br></em></strong>Note: After creating/ starting the Project, django will create some basic files in the newly created project directory which are basically used to handle/manage the whole project (for creating apps inside, to <em>manage</em> , <em>webserver</em>, project <em>settings</em>,<em>urls</em> file, <em>database</em>, etc).</li><li>Now, move to Project Directory<br>&gt; <strong>cd</strong> <strong><em>PROJECT_NAME</em></strong></li><li>[Optional: To Check] Now You can run the server with the default django homepage (which you can replace with yours after making).<br>&gt; <strong>python manage.py runserver<br></strong>Close the server using ‘Ctr+C’ or ‘Ctr+break’ in terminal.<br>Note: <strong>manage.py </strong>file allows us to run command line commands.</li><li>Now You Can Start Creating your web <strong>APPS </strong>in the current directory(<em>PROJECT_NAME). </em>You can create any number of app(s) here and integrate each of them with the whole web project.<br>You can create an app using this command:<br>&gt; <strong>python manage.py startapp <em>APP_NAME</em></strong></li><li>After creating the app, django automatically creates some of the basic necessary files and codes in new APP_NAME directory.<br>Now all you have to do is to create your website specific codes in this APP_NAME directory and add the required files for your page along with modifying the given default files as per your needs.</li></ol><p>NOTE: You might be wondering what additional Files or folders to create and where and what to modify in the default files to add our files/webpage.<br>Well, there could be lots of as per your website design needs. But let’s just look at the essential ones you need.<br>* First, You need to create a ‘<strong><em>templates</em></strong>’ folder inside the APP_NAME directory and inside the ‘templates’ directory, create one more directory with the same name (django convention) as APP_NAME &lt;— this will keep all html/css/static files, etc files for your webpage.<br>Example: Our App Name: ‘ProductPage’, so create directory as follows-<br>(App) ProductPage → templates → ProductPage → (files like page.html)</p><ul><li>After that, You’ll need to modify the ‘<strong>views.py</strong>’ file (present in your App directory) where you’ll have to define the View functions which will be called using a specific URL and this function will return the response to the server (basically it’ll return the rendered webpage).</li><li>Now that you have created an App response page (in your app) and associated it also with a url response function(view) through the function defined in views.py (i.e basically you have created a View for a specific request). <br>But the problem is that that this view (you created in your app) is not linked/mapped to the URL list of the Project (<strong>urls.py </strong>in <strong><em>PROJECT_NAME </em></strong><em>directory).<br>i.e. You need to route different URLs to your different applications/logics through urls.py in project folder.<br>OR in simple words: setting app-routes</em></li><li><em>So, now you have to create a similar ‘</em><strong><em>urls.py</em></strong><em>’ in your APP_NAME directory also which will be almost same as the urls.py file in the project directory, but this APP_NAME urls.py file will only keep the list of all the urls in this specific app(APP_NAME) only. And then we have to link this urls.py(of APP_NAME) to the urls.py(PROJECT_NAME) by simply adding a reference of app’s url file in the Project’s url file (i.e. Add the path of the App’s urls.py file int he Project’s urls.py file list). <br><br>urlpatterns[…] -&gt; this is basically the url mapping of certain urls to where we send the user by mentioning in the urlpatterns list in urls.py file.</em></li></ul><p><em>This is how we’ll map the urls of every app created in the project with the main project’s urls.py file.</em></p><p><em>JUST CHILL, I know it seems quite confusing now, but just wait and do this (as shown in the references anywhere) and Re-Read this, then all will be cleared and then you can related things easily.</em></p><p>####################</p><p>Now, if you have created the web pages (pages.html) &amp; other files in the templates directory, so you have to add a path to them in the view functions which will render these files.</p><p><strong>NOTE:</strong> To make these templates files work &amp; also the database associated with each app, you need to add the APP in the main project’s <strong>settings.py </strong>file manually in the list of <strong>INSTALLED_APPS=[ ], </strong>so that, by doing this, now django will know to look at the <em>templates directory for files.</em></p><p>To add your app in the INSTALLED_APPS list, you need to add the App Configuration of your app (class name inside the apps.py file inside your app) in the INSTALLED_APPS list in the project’s settings.py file.<br>Example: <strong>apps.py</strong> file inside the ‘pages’ app</p><blockquote><em>from django.apps import AppConfig<br>class </em><strong><em>PagesConfig</em></strong><em> (AppConfig):<br> name = ‘pages’</em></blockquote><blockquote>NOTE: Your app class is inheriting features from the main django app configurations.</blockquote><p>Here the app configuration name of your app is the name of the class. Here it is “<strong>PagesConfig” </strong>in the above example.</p><p>So, Copy this class name from the apps.py file of your app, and add it inside the INSTALLED_APPS list in the settings.py file inside the main project directory.<br>Here you need to add the Path to the app configuration of your app in this way:</p><pre>INSTALLED_APPS = [<br>    &#39;pages.apps.<strong>PagesConfig&#39;,  ## Here You have to add for all apps<br>    &#39;&lt;APP_NAME&gt;.apps.&lt;ClassName&gt;&#39;,<br>  </strong>  &#39;django.contrib.admin&#39;,<br>    .. <br>]</pre><p>Refer this video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FqDwdMDQ8oX4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DqDwdMDQ8oX4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqDwdMDQ8oX4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c383d17d2327d5f04444e9cc01bef54/href">https://medium.com/media/3c383d17d2327d5f04444e9cc01bef54/href</a></iframe><p>I hope you understood now, how to do this. After adding your app configuration in the main projects app list, it’ll automatically render the templates files and the database of each app. Now all you have to do is to design your webpage and all that stuff. For more advanced stuff like dynamic pages, getting response from the user and all those things, refer other tutorials. This was just a stepping stone for you in django.</p><p>ALL THE BEST</p><p>References:</p><p><a href="https://docs.djangoproject.com/">Django</a></p><p><a href="http://www.edureka.co/">www.edureka.co/</a> Videos: <a href="https://www.youtube.com/watch?v=HRLIEgwYSHc">https://www.youtube.com/watch?v=HRLIEgwYSHc</a></p><p>Interview Questions: <a href="https://www.edureka.co/blog/interview-questions/django-interview-questions/">https://www.edureka.co/blog/interview-questions/django-interview-questions/</a></p><p><a href="https://vsupalov.com/quick-django-refresher-crash-course/">https://vsupalov.com/quick-django-refresher-crash-course/</a></p><p><a href="https://www.youtube.com/playlist?list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p">Watch this awesome Django Tutorial Playlist by Corey Schafer</a></p><p>#### APPENDIX ####</p><p><strong>WHAT does APPs means here?</strong></p><p>Apps are basically different pages of a website(web project).<br>For Example: You have created a e-commerce website which will have these pages:<br>App1: Login Page<br>App2: Profile Page<br>App3: Product Page<br>App4: Blogs Page<br>App5: Careers Page<br>It could be anything, even a web app. So here the advantage is that since all of them are an independent entity in its own, therefore we can directly use any app of this project into another web project.<br>This is Python-Django!! — <strong>“Don’t Repeat Yourself”</strong></p><h3>django-admin</h3><p><em>‘django-admin’</em> is the command-line utility of Django for administrative tasks. Using the django-admin you can perform a number of tasks some of which are listed out in the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9F8pXo_B5fsdMCrZpVyYg.png" /><figcaption>django-admin commands</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*XPYV-i-uldfrjZ3hEmuFsQ.png" /><figcaption>django flow</figcaption></figure><p>If you liked the content and would like to connect on LinkedIn: <a href="https://www.linkedin.com/in/dineshyd/">https://www.linkedin.com/in/dineshyd</a></p><blockquote>UNDER DEVELOPMENT…</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d864e6aa084" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginner’s Guide to RNN & LSTMs]]></title>
            <link>https://medium.com/@humble_bee/rnn-recurrent-neural-networks-lstm-842ba7205bbf?source=rss-43c33ea8bc34------2</link>
            <guid isPermaLink="false">https://medium.com/p/842ba7205bbf</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[recurrent-neural-network]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[rnn]]></category>
            <dc:creator><![CDATA[Dinesh]]></dc:creator>
            <pubDate>Thu, 05 Dec 2019 18:16:56 GMT</pubDate>
            <atom:updated>2019-12-31T17:46:56.022Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0iYioJCuefCPma0q.png" /><figcaption>A recurrent neuron, where the output data is multiplied by a weight and fed back into the input</figcaption></figure><p><strong>What is RNN?</strong></p><p><strong>R</strong>ecurrent <strong>N</strong>eural <strong>N</strong>etwork is basically a generalization of feed-forward neural network <em>that has an internal memory</em>. RNNs are a special kind of neural networks that are designed to effectively deal with <strong>sequential data</strong>. This kind of data includes <strong>time series</strong> (a list of values of some parameters over a certain period of time) <strong>text documents</strong>, which can be seen as a sequence of words, or <strong>audio, </strong>which can be seen as a sequence of sound frequencies over time.<br>RNN is recurrent in nature as it performs the same function for every input of data while the output of the current input depends on the past one computation. For making a decision, it considers the current input and the output that it has learned from the previous input.</p><blockquote>Cells that are a function of inputs from previous time steps are also known as <strong><em>memory cells</em></strong>.</blockquote><p>Unlike feed-forward neural networks, RNNs can use their internal state (memory) to process sequences of inputs. In other neural networks, all the inputs are independent of each other. But in RNN, all the inputs are related to each other.</p><p><strong>Why RNN?</strong></p><p>The basic challenge of classic feed-forward neural network is that it has no memory, that is, each training example given as input to the model is treated independent of each other. In order to work with sequential data with such models — you need to show them the entire sequence in one go as one training example. This is problematic because number of words in a sentence could vary and more importantly this is not how we tend to process a sentence in our head.</p><p>When we read a sentence, we read it word by word, keep the prior words / context in memory and then update our understanding based on the new words which we incrementally read to understand the whole sentence. This is the basic idea behind the RNNs — they iterate through the elements of input sequence while maintaining a internal “state”, which encodes everything which it has seen so far. The “state” of the RNN is reset when processing two different and independent sequences.</p><blockquote>Recurrent neural networks are a special type of neural network where the outputs from previous time steps are fed as input to the current time step.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*svWmOxHbfu0e6Mc7u4wk4Q.jpeg" /><figcaption>Basic Recurrent neural network with three input nodes</figcaption></figure><p>The way RNNs do this, is by taking the output of each neuron (input nodes are fed into a hidden layer with sigmoid or tanh activations), and <em>feeding it back</em> to it as an input. By doing this, it does not only receive new pieces of information in every time step, but it also adds to these new pieces of information <em>a w̲e̲i̲g̲h̲t̲e̲d̲ ̲v̲e̲r̲s̲i̲o̲n̲</em> <em>of the </em><strong><em>previous output</em></strong><em>. </em>As you can see the hidden layer outputs are passed through a conceptual <em>delay </em>block to allow the input of <strong>h</strong> ᵗ⁻¹<strong> </strong>into the hidden layer. What is the point of this? Simply, the point is that we can now model <em>time </em>or sequence-dependent data.<br>This makes these neurons have a kind of <strong><em>“memory</em>”</strong> of the previous inputs it has had, as they are somehow quantified by the output being fed back to the neuron.</p><p>A particularly good example of this is in predicting text sequences. Consider the following text string: “A girl walked into a bar, and she said ‘Can I have a drink please?’. The bartender said ‘Certainly <strong>{ }</strong>”. There are many options for what could fill in the <strong>{ }</strong> symbol in the above string, for instance, “miss”, “ma’am” and so on. However, other words could also fit, such as “sir”, “Mister” etc. In order to get the correct gender of the noun, <em>the neural network needs to </em><strong><em>“recall”</em> </strong>that two previous words designating the likely gender (i.e. “girl” and “she”) were used. <br>A recurrent neural network can be <em>thought of</em> as multiple copies of the same network, each passing a message to a successor. This type of <em>flow of information through time (or sequence)</em> in a recurrent neural network is shown in the diagram below, which <em>unrolls </em>the sequence (loop unrolled):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*s1EGNG54_4j93SCQF-NvKA.png" /><figcaption>Unrolled recurrent neural network</figcaption></figure><p>This unrolled network shows how we can supply a stream of data (intimately related to sequences, lists and time-series data) to the recurrent neural network. For instance, first we supply the word vector for “A” to the network <em>F</em> — the output of the nodes in <em>F </em>are fed into the “next” network and also act as a stand-alone output ( <strong>h₀ </strong>). The next network (though it’s the same network) <em>F</em> at time <em>t=1</em> takes the next word vector for “girl” and the previous output <strong>h₀</strong> into its hidden nodes, producing the next output <strong>h₁</strong> and so on.</p><p>NOTE: Although shown for easy explanation in Diagram, but the words themselves i.e. “A”, “girl” etc. aren’t inputted directly into the neural network. Neither are their one-hot vector type representations — rather, an <em>embedding word vector </em>(read <a href="https://arxiv.org/abs/1301.3781">Word2Vec</a>) is used for each word.</p><p>One last thing to note — the weights of the connections between time steps are <em>shared</em> i.e. there isn’t a different set of weights for each time step (it’s the same for all time steps BECAUSE we have the same single RNN cell looped to itself)</p><h4>Different types of RNN’s</h4><p>The core reason that recurrent nets are more exciting is that they allow us to operate over <em>sequences</em> of vectors: Sequences in the input, the output, or in the most general case both. A few examples may make this more concrete:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hyjRrIcBHnv8gNgND86XQ.png" /><figcaption>RNN Implementation types</figcaption></figure><p>The problem with RNNs is that as time passes by and they get fed more and more new data, <strong>they start to “<em>forget</em>”</strong> about the previous data they have seen <em>(vanishing gradient problem)</em>, as it gets <strong>diluted</strong> between the new data, the transformation from activation function, and the weight multiplication. This means they have a <strong>good <em>short term memory</em></strong>, but a slight problem when trying to remember things that have happened a while ago (data they have seen many time steps in the past).<br>The more time steps we have, the more chance we have of back-propagation gradients either accumulating and exploding or vanishing down to nothing.<br>Consider the following representation of a recurrent neural network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*cL2HAU5Q9qcwD-LKjgPdWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*pTQkhzc6_jnfiE-Lkco9sw.png" /></figure><p>Here, <strong>ht </strong>is the new state (<em>current time stamp)</em>, <strong>ht</strong>₋₁is the previous state (<em>previous time stamp) </em>while <strong>xₜ </strong>is the current input.<br>Where <strong><em>U </em></strong>and <strong><em>V</em></strong><em> </em>are the weight matrices connecting the inputs and the recurrent outputs respectively. We then often will perform a softmax of all <strong>hₜ </strong>the outputs. Notice, however, that if we go back three time steps in our recurrent neural network, we have the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*qt7iz4AT7ESBLZmZxuQPXA.png" /></figure><p>From the above you can see, as we work our way back in time, we are essentially adding deeper and deeper layers to our network. This causes a problem — consider the gradient of the error with respect to the weight matrix <strong><em>U</em></strong> during back-propagation through time, it looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*ZpwvKJ14XhK9oUxV7e1NLg.png" /></figure><p>The equation above is only a rough approximation of what is going on during <em>back-propagation through time.</em> Each of these gradients will involve calculating the gradient of the sigmoid function. The problem with the sigmoid function occurs when the input values are such that the output is close to either 0 or 1 — at this point, the gradient is very small (saturating).</p><p><strong>For ex</strong>:- Lets say the value decreased like 0.863 →0.532 →0.356 →0.192 →0.117 →0.086 →0.023 →0.019.. <br>you can see that there is no much change in last 3 iterations.</p><p>It means that when you multiply many sigmoid gradients together you are multiplying many values which are potentially much less than zero — this leads to a vanishing gradient problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Sokn0XW8Z6GD4A6bg-CaCg.gif" /><figcaption>Gradients shrink as it back-propagates through time</figcaption></figure><p>The gradient values will exponentially shrink as it propagates through each time step. Because the gradient will become basically zero when dealing with many prior time steps, the weights won’t adjust to take into account these values, and therefore the network won’t learn any relationships separated by a long significant periods of time. So, Vanishing gradient problem results in long-term dependencies being ignored during training.</p><p>You Can <strong>Visualize</strong> this Vanishing gradient problem at real time <a href="https://distill.pub/2019/memorization-in-rnns/"><strong>here</strong></a><strong>.</strong></p><p>Hence, the RNN doesn’t learn the long-range dependencies across time steps. This makes them not much useful.</p><p>We need some sort of<strong> Long term memory</strong>, which is just what LSTMs provide.</p><h3>Enhancing our memory — Long Short Term Memory Networks (LSTM)</h3><p>Long-Short Term Memory networks or<strong> LSTMs</strong> are a variant of RNN that solve the Long term memory problem of the former.</p><p>They have a more <strong>complex cell structure</strong> than a normal recurrent neuron, that allows them to better regulate how to <strong><em>learn</em> or <em>forget </em></strong>efficiently<strong><em> </em></strong>from the different input sources.</p><p>The key to LSTMs is the <strong>cell state </strong>(cell memory), the horizontal line running through the top of the diagram, through which the information flows along and the internal mechanism called <strong>gates </strong>that can<em> regulate the flow of information.</em><br>The cell state is kind of like a conveyor belt. It runs straight down the entire chain, with only<em> some minor linear interactions.</em></p><blockquote>Cell State <em>basically e</em>ncodes the information of the inputs (relevant info.) that have been observed up to that step (at every step).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XuM8aRzh17kdjeOgrjFE6A.png" /><figcaption>Representation of an LSTM cell</figcaption></figure><p><strong>Cell state</strong> is a memory of the LSTM cell and <strong>hidden state </strong><em>(cell output) </em>is an output of this cell.</p><blockquote>Cells do have internal cell state, often abbreviated as “c”, and cells output is what is called a “hidden state”, abbreviated as “h”. <br>Regular RNNs have just the hidden state and no cell state. Therefore, RNNs have difficulty of accessing information from a long time ago.</blockquote><p>Note: Hidden state is an output of the LSTM cell, used for Prediction. It contains the information of previous inputs (from cell state/memory) along with current input (decided according which context is important).</p><blockquote><strong>Hidden state (hₜ ₋ ₁) and cell input (xₜ) data is used to control what to do with memory (cell state) cₜ : to forget or to write new information.</strong></blockquote><p>We decide what to do with memory knowing about previous cell output (hidden state) and current input and we do this using gates.</p><p><strong>Gates</strong> are a way to optionally let information through. They are composed out of a sigmoid neural net layer and a point-wise multiplication operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*a6FEUZOlcx4peSLv3eZVnw.png" /><figcaption>LSTM Gate</figcaption></figure><p>The sigmoid layer outputs numbers between zero and one, <em>describing how much of each component should be let through</em>. <br>A value of zero means “let nothing through,” while a value of one means “let everything through!”</p><blockquote>An LSTM has three of these gates, to protect and control the cell state.</blockquote><p>These gates can learn which data in a sequence is important to keep or throw away. By doing that, it can pass relevant information down the long chain of sequences to make predictions.</p><p>An LSTM neuron can do this learning by incorporating a<strong> </strong><em>cell state</em> and three different <em>gates</em>: the <em>input gate</em>, the <em>forget gate</em> and the <em>output gate.</em> In each time step, the cell can decide what to do with the state vector:<em> read from it</em>, <em>write to it</em>, or <em>delete it</em>, thanks to an explicit gating mechanism. <br>With the <strong>input gate</strong>, the cell can decide whether to update the cell state or not. With the <strong>forget gate</strong> the cell can erase its memory, and with the <strong>output gate</strong> the cell can decide whether to make the output information available or not.</p><p>LSTMs also mitigate the problems of <strong>exploding and vanishing gradients.</strong></p><p>To reduce the vanishing (and exploding) gradient problem, and therefore allow deeper networks and recurrent neural networks to perform well in practical settings, there needs to be a way to reduce the multiplication of gradients which are less than zero.</p><p>The LSTM cell is a specifically designed unit of logic that will help reduce the vanishing gradient problem sufficiently to make recurrent neural networks more useful for long-term memory tasks i.e. text sequence predictions. <br>The way it does so is by creating an internal memory state which<em> </em>is simply <em>added</em> to the processed input, which greatly <em>reduces the multiplicative effect of small gradients</em>. The time dependence and effects of previous inputs are controlled by an interesting concept called a <em>forget gate</em>, which determines which states are remembered or forgotten. Two other gates, the <em>input gate</em> and <em>output gate</em>, are also featured in LSTM cells.</p><p>Here’s a brief summary of all the internal formulation and working of different gates,cell state,hidden state and current input, explained through mathematical formulas, referenced from a research paper <a href="https://arxiv.org/abs/1603.03827">https://arxiv.org/abs/1603.03827</a> (~LSTM for text classification):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJXjFnwov9eYFBmERD1AaQ.png" /><figcaption>LSTM summarized</figcaption></figure><p>Let’s first have a look at LSTM cell more carefully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*sBWGqAJtqm2iV0DYapT2rg.png" /><figcaption>LSTM cell another view</figcaption></figure><p>The data flow is from left-to-right in the diagram above, with the current input <strong>xₜ </strong>and the previous cell output <strong>hₜ</strong>₋₁<strong> </strong>concatenated together and entering the top “data rail”. The <strong>long-term memory</strong> is usually called the <strong>cell state Ct</strong>. The looping arrows indicate recursive nature of the cell. This allows information from previous intervals to be stored within the LSTM cell. Here’s where things get interesting.</p><p><strong>Input Gate:</strong></p><p>The <em>input gate </em>is also called the <strong>save vector.<br></strong> These gates determine which information should enter the cell state / long-term memory OR which information should be saved to the cell state or should be forgotten.</p><p>First, the (combined) input is squashed between -1 and 1 using a <em>tanh</em> activation function.<br>This squashed input (from tanh) is then multiplied element-wise by the output of the <em>input gate</em>. The input gate is basically a hidden layer of sigmoid activated nodes, with weighted <strong>xₜ </strong>and input values <strong>hₜ </strong>₋ ₁, which outputs values of between 0 and 1 and when multiplied element-wise by the input determines which inputs are switched on and off (actually, the values aren’t binary, they are a continuous values between 0 &amp; 1). In other words, it is a kind of input filter or gate (it tells what to learn and add to the memory from current input and the context its given and also how much {sigmoid gives values between 0&amp;1} of what to learn).</p><blockquote>Simplistic (could be wrong) view: Tanh gives the Standardized (between -1 &amp; 1) value of the actual unscaled (combined) input vector and the sigmoid layer is the controller of what percentage (values between 0 &amp; 1 or 0 to 100%) of what inputs should be passed on of the scaled (from tanh) values to be added to the memory considering the current and previous context.</blockquote><p>But Why <em>tanh activation?</em></p><p>Because the equation of the cell state is a <em>summation</em> between the previous cell state, sigmoid function alone will only add memory and not be able to remove/forget memory. If you can only add a float number between [0,1], that number will never be zero / turned-off / forget. This is why the input modulation gate has an <strong>tanh</strong> activation function. Tanh has a range of [-1, 1] and allows the cell state to forget certain memories.</p><p><strong>Forget Gate:</strong></p><p>The forget gate<strong> </strong>is also called the <strong>remember vector</strong>. The output of the forget gate tells the cell state which information to forget by multiplying 0 to a position in the matrix. If the output of the forget gate is 1, the information is kept in the cell state.</p><p>Although initially it is randomly initialized, but it basically LEARNS What exactly to FORGET (when the current input and previous <em>Context is given) from the memory (cell state).</em></p><p><strong>Output Gate:</strong></p><p>The <em>output gate </em>is also called the <strong>focus vector.<br></strong>It basically highlights, out of all the possible values from the matrix(long memory), which information should be moving forward to the next hidden state.</p><p>Note: The <strong>working memory</strong> is usually called the <strong>hidden state</strong>(<strong>ht</strong>).<strong> <br></strong>It is basically → ht (LSTM OUTPUT) → What part of the existing memory (Ct) should be fed as context for the next round. This is analogous to the hidden state in RNN and HMM.</p><p>Gates Summarized:<br><em>Input</em> gate determines the extent to which the current timestamp input should be used , the <em>Forget</em> gate determines the extent to which output of the previous timestamp state should be used, and the <em>Output</em> gate determines the output of the current timestamp.</p><p>Still Unclear? Doubts? Then I’ll highly recommend you to watch this amazing video by Brandon Rohrer on RNN &amp; LSTM (A Must Watch):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWCUNPb-5EYI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWCUNPb-5EYI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWCUNPb-5EYI%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/25d32679abdbd99675b55ab5d38c272c/href">https://medium.com/media/25d32679abdbd99675b55ab5d38c272c/href</a></iframe><blockquote>Conclusion</blockquote><p>The idea is how the learning process is based on context (memory). <br>You forget, you learn and you extract a part of it for the next round, but in next round you again repeat the same process.</p><p>Basically, we are trying to mimic how human brain tries to learn things through LSTM internal gate mechanism (&amp; this may not be necessarily true, we’re just trying different approaches)</p><p><strong>GRU — Gated Recurrent Unit</strong></p><p>The GRU introduced in 2014 by Kyunghyun Cho et al was a simplified version of LSTM with just two gates instead of 3 and with a far fewer parameters vs LSTM.</p><p>GRU have been shown to have better performance on certain tasks and smaller datasets, but LSTM tend to outperform GRU in general.</p><p>There were some additional variants like bidirectional LSTM which don’t just process text left to right, but also do it right to left to give additional performance boost.</p><p>References:<br>1) RNN: <a href="https://www.analyticsvidhya.com/blog/2017/12/introduction-to-recurrent-neural-networks/">https://www.analyticsvidhya.com/blog/2017/12/introduction-to-recurrent-neural-networks/</a></p><p>2) <a href="https://hackernoon.com/rnn-or-recurrent-neural-network-for-noobs-a9afbb00e860">https://hackernoon.com/rnn-or-recurrent-neural-network-for-noobs-a9afbb00e860</a></p><p>3) <a href="https://medium.com/explore-artificial-intelligence/an-introduction-to-recurrent-neural-networks-72c97bf0912">https://medium.com/explore-artificial-intelligence/an-introduction-to-recurrent-neural-networks-72c97bf0912</a></p><p>4) <a href="http://colah.github.io/posts/2015-08-Understanding-LSTMs/">http://colah.github.io/posts/2015-08-Understanding-LSTMs/</a></p><p>5) <a href="https://towardsdatascience.com/illustrated-guide-to-recurrent-neural-networks-79e5eb8049c9">https://towardsdatascience.com/illustrated-guide-to-recurrent-neural-networks-79e5eb8049c9</a><br>&amp; many more …</p><p>WHAT DOES THE <strong>CONTEXT</strong> CONTAIN:</p><ul><li>We extract only a part of our memory that is relevant at any point.</li><li>We combine it with current surroundings.</li><li>We then forget parts of this total that is not required or might confuse.</li><li>We learn new stuff from this total (current and our past) and update our memory.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=842ba7205bbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CNN vs MLP for Image Classification]]></title>
            <link>https://medium.com/analytics-vidhya/cnn-convolutional-neural-network-8d0a292b4498?source=rss-43c33ea8bc34------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d0a292b4498</guid>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[convolutional-neural-net]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <dc:creator><![CDATA[Dinesh]]></dc:creator>
            <pubDate>Wed, 06 Nov 2019 14:34:17 GMT</pubDate>
            <atom:updated>2019-11-28T07:54:50.108Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*AO-IxW91_GmKOZ-faQULlQ.png" /><figcaption>A Typical Architecture of CNN</figcaption></figure><p><strong><em>Why CNN is preferred over MLP (ANN) for image classification?</em></strong></p><p>MLPs (<a href="https://en.wikipedia.org/wiki/Multilayer_perceptron">Multilayer Perceptron</a>) use one perceptron for each input (e.g. pixel in an image) and the amount of weights rapidly becomes unmanageable for large images. It includes too many parameters because it is fully connected. Each node is connected to every other node in next and the previous layer, forming a very dense web — resulting in redundancy and inefficiency. As a result, difficulties arise whilst training and <em>overfitting</em> can occur which makes it lose the ability to generalize.</p><p>Another common problem is that MLPs react differently to an input (images) and its shifted version — they are not translation invariant. For example, if a picture of a cat appears in the top left of the image in one picture and the bottom right of another picture, the MLP will try to correct itself and assume that a cat will always appear in this section of the image.</p><p>Hence, MLPs are not the best idea to use for image processing. One of the main problems is that spatial information is lost when the image is flattened(matrix to vector) into an MLP.</p><p>We thus need a way to leverage the spatial correlation of the image features (pixels) in such a way that we can see the cat in our picture no matter where it may appear. Solution? — <strong>CNN</strong> !</p><p><a href="https://en.wikipedia.org/wiki/Convolutional_neural_network"><strong>Convolutional Neural Network</strong></a><strong> (CNN)</strong>: More generally, CNNs work well with data that has a spatial relationship. Therefore CNNs are go-to method for any type of prediction problem involving image data as an input. <br>The benefit of using CNNs is their ability to develop an internal representation of a two-dimensional image. This allows the model to learn position and scale in variant structures in the data, which is important when working with images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*Ff6mG3aPdWFkjb6hZPy3Xw.gif" /><figcaption>Convolution Operation</figcaption></figure><p>It can account for <em>local connectivity </em>(each filter is panned around the entire image [Convolution] according to certain size and stride(no. of pixels/blocks to shift around after every convolution step), allows the filter to find and match patterns no matter where the pattern is located in a given image). The weights are smaller and shared — less wasteful, easier to train than MLP and more effective too. They can also go deeper. Layers are sparsely connected rather than fully connected. <br>It takes matrices as well as vectors as inputs. <br>The layers are <em>sparsely connected </em>or partially connected rather than <em>fully connected</em>. <em>Every node does not connect to every other node.</em></p><p>CNN’s leverage the fact that nearby pixels are more strongly related than distant ones.<br>We analyze the influence of nearby pixels by using something called a <strong>filter /Kernel </strong>and we move this across the image from top left to bottom right. For each point on the image, a value is calculated based on the filter using a convolution operation.<br>A filter could be related to anything, for pictures of humans, one filter could be associated with seeing noses, and our nose filter would give us an indication of how strongly a nose seems to appear in our image, and how many times and in what locations they occur. This reduces the number of weights that the neural network must learn compared to an MLP, and also means that when the location of these features changes it does not throw the neural network off.</p><p>The panning of filters (you can set the stride and filter size) in CNN <em>essentially allows parameter sharing</em>, <em>weight sharing </em>so that the filter looks for a specific pattern, and is <em>location invariant </em>— can find the pattern anywhere in an image. This is very useful for object detection. Patterns can be discovered in more than one part of the image. <br>Additionally, it can also find the similar pattern even if the object is somewhat rotated/tilted using a concept called Pooling, which makes CNN more robust to changes in the position of the feature in the image, referred to by the technical phrase “<em>local translation invariance</em>.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jfe-3pG2sJ8P0GJKWIkhCQ.png" /></figure><p>After the filters have passed over the image, a <strong>feature map</strong> is generated for each filter. These are then taken through an activation function, which decides whether a certain feature is present at a given location in the image. We can then do a lot of things, such as adding more filtering layers and creating more feature maps, which become more and more abstract as we create a deeper CNN. We can also use pooling layers in order to select the largest values on the feature maps and use these as inputs to subsequent layers. In theory, any type of operation can be done in pooling layers, but in practice, only max pooling is used because we want to find the outliers — these are when our network sees the feature!</p><p>In Pooling, it basically takes a filter and a stride of the same length. It then applies it to the input volume and outputs the maximum number in every sub-region that the filter convolves around. The intuitive reasoning behind this <em>Pooling</em> layer is that once we know that a specific feature is in the original input volume (there will be a high activation value), its exact location is not as important as its relative location to the other features. As you can imagine, this layer drastically reduces the spatial dimension (the length and the width change but not the depth) of the input volume.</p><p>The neural network (in MLP) will learn different interpretations for something that is possibly the same. But in CNN, the number of weights is dependent on the kernel size <em>(see Weight sharing)</em> instead of the input size which is really important for images. So, by forcing the shared weights among spatial dimensions which drastically reduces the number of parameters, the convolution kernel acts as a learning framework.<br>That’s how convolutional layers reduce memory usage and compute faster.</p><p><strong>Note 1: </strong>Spatial Information refers to information having location-based relation with other information. Space represents the 2D plane(x-y) in images.<br>Earlier layers of CNN are convolutional layers, which take into account the image as a 2D (spatial) information. Whereas, the deeper layers flatten that (convoluted) information in first conv layer, it extracts spatial information like edges, corners etc. and in other conv layer it extracts spatial information like eyes, nose etc.<br>This is spatial information in images. CNN’s don’t maintain spatial relationship among features. Advanced capsnet addresses this problem.</p><p><a href="https://towardsdatascience.com/capsule-neural-networks-are-here-to-finally-recognize-spatial-relationships-693b7c99b12">Capsule Neural Networks: The Next Neural Networks? Part 1: CNNs and their problems.</a></p><p><strong>Note 2:</strong> CNNs are designed to be <em>spatially invariant</em>, that is — they are not sensitive to the position of, for example, object in the picture. The deeper you go into layers, the originally not so (pixel wise) similar objects (or usually parts of objects) are becoming more similar (and <em>this is achieved via convolution</em>). At the deepest layers we have extracted features with no information on where they were positioned on the original image. We even lose the information on pixel-size of original objects because of another process in CNN called pooling.<br>Convolution is the key for why CNNs perform better than any other model in such “human-like” tasks like recognizing specific objects in the picture, words in a recorded speech and other tasks.</p><p><a href="https://www.peculiar-coding-endeavours.com/2018/mlp_vs_cnn/">Image classification: MLP vs CNN</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d0a292b4498" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/cnn-convolutional-neural-network-8d0a292b4498">CNN vs MLP for Image Classification</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>