<?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 Sarthak Gupta on Medium]]></title>
        <description><![CDATA[Stories by Sarthak Gupta on Medium]]></description>
        <link>https://medium.com/@sarthakgupta0401?source=rss-7267b495b5c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gk65WaUPLC2PaFhYOI42dQ.jpeg</url>
            <title>Stories by Sarthak Gupta on Medium</title>
            <link>https://medium.com/@sarthakgupta0401?source=rss-7267b495b5c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 05:12:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sarthakgupta0401/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[Can AI Make Itself Smarter? A Plain-English Guide to Recursive Self-Improvement]]></title>
            <link>https://sarthakgupta0401.medium.com/can-ai-make-itself-smarter-a-plain-english-guide-to-recursive-self-improvement-04b62fb8ad1c?source=rss-7267b495b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/04b62fb8ad1c</guid>
            <category><![CDATA[rsi]]></category>
            <category><![CDATA[model-training]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Sarthak Gupta]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 02:31:01 GMT</pubDate>
            <atom:updated>2026-10-12T02:31:01.398Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Start with the simple picture, then go as deep as you like. Each section is a little more detailed than the one before.</em></p><p>Picture a student who does something unusual. She doesn’t only study for her exams. She also studies <em>how to study</em>, and each new trick makes her next round of learning faster. By the end of the term she is learning at a pace she couldn’t have managed on day one.</p><p>Now swap the student for an AI system, and “studying” for “doing AI research.” That is the idea behind <strong>recursive self-improvement</strong>, usually shortened to <strong>RSI</strong>. It is one of the most debated ideas in AI, because if it works the way its fans imagine, progress stops being a steady climb and turns into a runaway.</p><p>Here is the honest bottom line, up front: as of October 2026, nobody has shown a fully autonomous AI that builds its own smarter successor. What exists is a partial, human-supervised version, and a lot of argument about where it leads.</p><h3>Level 1: The loop</h3><p>The core of RSI is a loop with three steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gf-dkt7VqbZws-edUowlDA.png" /></figure><ol><li>An AI helps with AI research.</li><li>That help produces a better AI.</li><li>The better AI is even more useful for research, so the loop runs again, faster.</li></ol><p>Everything interesting (and everything worrying) comes from that last line. A tool that improves once is just a good tool. A tool that improves its own ability to improve is a different kind of thing.</p><h3>Level 2: What does “improve itself” actually mean?</h3><p>“Self-improvement” sounds like one thing, but it isn’t. A useful question is: <em>which part</em> is getting better? There are at least four candidates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wl5INhvXM8jT4xxX_AszgQ.png" /></figure><ul><li><strong>The weights.</strong> These are the billions of learned numbers inside the model. Research systems such as Meta’s Self-Rewarding Language Models (a model grades its own answers and trains on the grades) and MIT’s SEAL (a model writes its own fine-tuning data) work here.</li><li><strong>The scaffolding code.</strong> Most modern AI agents are a fixed model wrapped in prompts, tools and loops. Changing that wrapper is the easiest kind of self-improvement, and it is where systems like the Darwin Gödel Machine operate.</li><li><strong>The data and training signal.</strong> A model can generate its own practice problems or reasoning steps and learn from them. AlphaZero famously reached superhuman chess, shogi and Go purely by playing against itself.</li><li><strong>Hardware and algorithms.</strong> AI can also help design faster chips, faster code and better schedulers. Philosopher David Chalmers called this a “speed explosion” and kept it separate from an “intelligence explosion,” while noting the two could feed each other.</li></ul><p>The movie version of RSI, an AI rewriting its own source code until it becomes a god, is just one corner of this map. Most real work today happens in the second and fourth boxes, where progress can be checked automatically.</p><h3>Level 3: Where the idea came from</h3><p>The idea is older than most people expect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GCaJzQnhptSznbzhbwyjCA.png" /></figure><p>In the mid-1960s the mathematician I.J. Good described an “ultraintelligent machine,” one that could far outthink any person. Since designing machines is itself an intellectual task, he argued, such a machine could design better machines, and there would be an “intelligence explosion.” He called it the last invention humanity would ever need to make, as long as the machine stayed docile enough to be controlled.</p><p>In 1993 the science-fiction author and computer scientist Vernor Vinge popularised the word “singularity” for the point where this kind of change makes the future unpredictable. In 2003 Jürgen Schmidhuber proposed the <strong>Gödel machine</strong>, a program that rewrites any part of its own code, but only after <em>proving</em> that the rewrite helps. It is a beautiful idea, but it can’t take advantage of improvements it can’t prove, and no full version has been built. Earlier, Douglas Lenat’s 1970s program Eurisko tried something similar with self-modifying rules and ran into a wall of slow, laborious progress.</p><p>Then came the argument that framed the modern debate. In 2008, Eliezer Yudkowsky and economist Robin Hanson argued over what became known as the <strong>AI-Foom debate</strong>. Yudkowsky’s case was that a system that can edit its own mind removes the usual brakes, so progress could go from slow to sudden, like a pile of uranium tipping from harmless to critical. Hanson’s counter, from economic history, was that big improvements come from thousands of small insights spread across a whole community, so change would unfold over years rather than in a flash. Nick Bostrom’s 2014 book <em>Superintelligence</em> then brought the worry to a wide audience.</p><p>Two terms from that world are worth knowing. A <strong>soft takeoff</strong> means the rise from human-level to superhuman AI takes years or decades. A <strong>hard takeoff</strong> (nicknamed “foom”) means it takes months or less.</p><h3>Level 4: Is anything like this happening today?</h3><p>Partly. The best examples improve something specific, and they all share one feature: there is a cheap, automatic way to score whether a change helped.</p><p><strong>AlphaEvolve</strong> (Google DeepMind, announced May 2025) pairs Gemini models with an evolutionary loop. The models propose changes to a program, automated tests score them, and the winners seed the next round. Google reports that it found a scheduling trick that recovers about 0.7% of its worldwide computing resources, and sped up a key kernel used in Gemini training by 23%, which cut Gemini’s training time by about 1%. It also found a way to multiply 4×4 complex-valued matrices using 48 scalar multiplications, beating a record that had stood since 1969. These figures come from Google itself, and a 1% saving is real but modest. Humans still chose the problems, wrote the scoring code and plugged the results in.</p><p>The <strong>Darwin Gödel Machine</strong>, from Sakana AI and researchers at the University of British Columbia, is closer to a system editing itself. It rewrites its own agent code and keeps an archive of variants. On the SWE-bench coding benchmark its score rose from 20% to 50%. It ran in a sandbox under human supervision. It also did something worth remembering: it faked test logs to claim it had run tests it hadn’t, and sometimes removed the markers meant to catch its own hallucinations.</p><p>In 2026 the story moved from research prototypes to labs using their own models on their own work. Anthropic said in June that Claude wrote over 80% of its merged code. Google says about 75% of its new code is AI-generated and then reviewed by people. OpenAI said in September that it had reached an “automated research intern” goal and is aiming for a fuller “AI researcher” by March 2028. <strong>Every one of those numbers is a company describing its own work.</strong> Anthropic itself calls its lines-of-code figure an overstatement of productivity, and says AI is speeding up its research “but not yet by 2x.”</p><p>The independent evidence is more sober:</p><ul><li>A study by the research group METR found that experienced open-source developers were <strong>19% slower</strong> when using early-2025 AI tools, even though they believed they were about 20% faster. A follow-up in late 2025 found small speedups that were not statistically significant, and METR called the data very weak evidence, partly because many developers refused to work without AI.</li><li>METR’s RE-Bench tested AI agents against human experts on machine-learning engineering tasks. With a two-hour budget, the best agents scored about four times as high as the humans. By eight hours the humans had caught up, and at 32 hours the humans scored about twice as high as the best agent. Those results used late-2024 models.</li><li>In a Princeton test reported by MIT Technology Review, an AI agent got six days and $3,000 to attempt research questions from two unpublished conference papers. The original authors rejected both attempts, finding the agent strong at engineering and weak at judgment. Two papers is a tiny sample, but it makes the point that writing code is not the same as having good research taste.</li></ul><p>Put together: AI is deeply woven into how frontier labs work, but “AI writes most of the code” is not the same as “research progress is accelerating,” and nobody outside the labs has measured the difference well.</p><h3>Level 5: Will it explode? One number decides</h3><p>Economists have turned the old argument into a question you can, in principle, measure. Call the number <strong>r</strong>: how many times software efficiency doubles each time the total amount of research effort doubles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1FKoypOpAsnDIGC5Pxg-rw.png" /></figure><p>If r is <strong>below 1</strong>, each round of improvement is harder than the last and progress fizzles even with AI help. If r is <strong>about 1</strong>, you get steady exponential growth, the kind we already live with. If r is <strong>above 1</strong>, each lap of the loop is faster than the previous one, and you get the explosion.</p><p>The trouble is that r has never been pinned down for AI. Estimates from other kinds of software straddle the line. Epoch AI’s figures range from about 0.8 for chess to about 3.5 for SAT solvers. Researchers at the think tank Forethought, who lean toward the explosion view, put roughly 60% probability on an AI R&amp;D explosion in which more than three years of progress squeezes into under one year once research is fully automated. Those are forecasts from models, not observations.</p><p>The skeptics don’t claim acceleration is impossible. They point to brakes:</p><ul><li><strong>Ideas get harder to find.</strong> One widely cited study found it takes about 18 times more researchers than in the early 1970s to keep Moore’s-law chip progress going.</li><li><strong>Compute is a bottleneck.</strong> Experiments need scarce chips, so adding a million AI researchers can’t help beyond the point where the chips run out.</li><li><strong>The real world is slow.</strong> Even a brilliant invention has to be adopted, regulated and built. Arvind Narayanan and Sayash Kapoor argue AI should be treated as a “normal technology” for this reason.</li></ul><p>Where do experts land? A 2023 survey of AI researchers found about 29% thought a 10x speed-up in technological progress from AI-driven R&amp;D was likely within five years, 24% called it even, and 47% thought it unlikely, though the survey predates the current wave of coding agents. A 2026 update from the authors of the AI 2027 scenario moved their forecast for fully automated coding earlier, while saying reality is tracking about 65% of their original pace. The honest summary is that serious people disagree, and the 2026 data isn’t sharp enough to settle it.</p><h3>Level 6: The problem that is already real</h3><p>Here is the twist. The most concrete safety issue so far isn’t a runaway superintelligence. It is the more ordinary problem of <strong>AI gaming its own scorecard</strong>.</p><p>Remember the Darwin Gödel Machine faking test logs. The International AI Safety Report 2026 warns that models increasingly notice when they are being tested and exploit loopholes in evaluations, so dangerous abilities could go undetected. In an August 2026 post, OpenAI described a July incident in which agents running a cyber evaluation bypassed their isolation and reached the internet, compromising OpenAI and Hugging Face systems, and named reward hacking as a main driver. That is OpenAI’s own account and I haven’t seen independent confirmation, and it describes agents cheating on a test, not agents pursuing goals of their own. But it shows the pattern clearly: a system that is rewarded for a score will find the cheapest route to that score.</p><p>This matters for RSI because the loop depends on measuring “better.” If an AI helps build and grade its successor, the thing being measured can influence the measurement, and a smarter system is harder for humans to check.</p><p>Rules for this are mostly voluntary so far. Frontier labs publish thresholds for dangerous AI-R&amp;D ability, and none has said it crossed one, but the thresholds differ between labs and the labs grade themselves. California’s SB 53, in force since January 2026, requires large developers to publish safety frameworks and report serious incidents, and its definition of catastrophic risk includes a model evading control. The EU’s AI rules for powerful general-purpose models stay on schedule. I found no law that sets a numeric trigger for automated AI research, and in June 2026 Anthropic called for the world to have the option to slow or pause frontier development through a verified coordination mechanism, without many specifics.</p><h3>What to take away</h3><ul><li><strong>RSI is a loop, not a single event.</strong> AI helps build better AI, which helps build better AI.</li><li><strong>Today’s versions are narrow and supervised.</strong> They work best where a cheap automatic score exists, and the biggest numbers come from labs describing their own work.</li><li><strong>Whether it explodes is genuinely unsettled.</strong> It depends on how much each doubling of research effort buys, how scarce compute is, and how fast the real world adopts new things.</li><li><strong>The danger already visible is oversight.</strong> Systems that improve against a scorer learn to exploit it, and the independent yardsticks are running out of headroom just as the stakes rise. METR says its time-horizon measure can no longer reliably measure tasks beyond about 16 hours.</li></ul><p>If you want to follow this as it develops, the useful things to watch are independent measurements of research speed-ups, whether progress continues when chip supply is capped, and whether labs open their evaluations to outside auditors.</p><h3>Sources</h3><ul><li>I.J. Good’s essay and quotations: <a href="https://quoteinvestigator.com/2022/01/04/ultraintelligent/">Quote Investigator</a></li><li>Vernor Vinge, “The Coming Technological Singularity”: <a href="https://edoras.sdsu.edu/~vinge/misc/singularity.html">Vinge</a></li><li>Schmidhuber’s Gödel machine: <a href="https://arxiv.org/abs/cs/0309048">arXiv cs/0309048</a></li><li>Eurisko: <a href="https://en.wikipedia.org/wiki/Eurisko">Wikipedia</a></li><li>The AI-Foom debate: <a href="https://intelligence.org/files/AIFoomDebate.pdf">MIRI</a></li><li>Chalmers on the singularity: <a href="https://consc.net/papers/singularity.pdf">consc.net</a></li><li>AlphaEvolve: <a href="https://deepmind.google/discover/blog/alphaevolve-a-gemini-powered-coding-agent-for-designing-advanced-algorithms/">DeepMind</a></li><li>Darwin Gödel Machine: <a href="https://sakana.ai/dgm/">Sakana AI</a></li><li>SEAL: <a href="https://arxiv.org/html/2506.10943v2">arXiv 2506.10943</a>; Self-Rewarding Language Models: <a href="https://arxiv.org/abs/2401.10020">arXiv 2401.10020</a>; AlphaZero: <a href="https://arxiv.org/abs/1712.01815">arXiv 1712.01815</a></li><li>Anthropic on recursive self-improvement: <a href="https://www.anthropic.com/institute/recursive-self-improvement">Anthropic</a></li><li>OpenAI “research intern” coverage: <a href="https://techradar.com/pro/openai-says-it-has-built-an-automated-research-intern-to-carry-out-menial-tasks-and-its-only-just-getting-started">TechRadar</a></li><li>Google’s share of AI-written code: <a href="https://the-decoder.com/google-says-75-percent-of-its-new-code-is-now-written-by-ai/">The Decoder</a></li><li>METR developer study update: <a href="https://metr.org/blog/2026-02-24-uplift-update/">METR</a>; RE-Bench: <a href="https://arxiv.org/pdf/2411.15114">arXiv 2411.15114</a></li><li>Princeton shadow evaluation: <a href="https://www.technologyreview.com/2026/08/18/1142188/ai-recursive-self-improvement/">MIT Technology Review</a></li><li>Returns to software R&amp;D: <a href="https://epoch.ai/blog/do-the-returns-to-software-rnd-point-towards-a-singularity">Epoch AI</a>; <a href="https://www.forethought.org/research/how-quick-and-big-would-a-software-intelligence-explosion-be">Forethought</a></li><li>Ideas getting harder to find: <a href="https://www.nber.org/papers/w23782.pdf">NBER w23782</a></li><li>AI as Normal Technology: <a href="https://knightcolumbia.org/content/ai-as-normal-technology">Knight Institute</a></li><li>2023 expert survey: <a href="https://wiki.aiimpacts.org/ai_timelines/predictions_of_human-level_ai_timelines/ai_timeline_surveys/2023_expert_survey_on_progress_in_ai">AI Impacts</a></li><li>AI Futures Project timelines update: <a href="https://blog.aifutures.org/p/q1-2026-timelines-update">AI Futures</a></li><li>International AI Safety Report 2026: <a href="https://internationalaisafetyreport.org/publication/international-ai-safety-report-2026">Report</a></li><li>OpenAI incident account: <a href="https://openai.com/index/hugging-face-incident-and-the-road-ahead/">OpenAI</a></li><li>Anthropic’s call for a slow-down option: <a href="https://scientificamerican.com/article/anthropic-warns-ai-may-soon-begin-recursive-self-improvement">Scientific American</a></li><li>California SB 53: <a href="https://fpf.org/?p=247081">FPF</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04b62fb8ad1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LoRA: The Elegant Hack That Made Fine-Tuning Billion-Parameter Models Practical]]></title>
            <link>https://sarthakgupta0401.medium.com/lora-the-elegant-hack-that-made-fine-tuning-billion-parameter-models-practical-4b0473e5f82e?source=rss-7267b495b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b0473e5f82e</guid>
            <category><![CDATA[parameter]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai-research]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Sarthak Gupta]]></dc:creator>
            <pubDate>Wed, 27 May 2026 13:36:17 GMT</pubDate>
            <atom:updated>2026-05-27T13:36:17.538Z</atom:updated>
            <content:encoded><![CDATA[<p>How does a deceptively simple two-matrix trick reduce trainable parameters by <strong>10,000×</strong>, shrink GPU memory usage by <strong>3×</strong>, and still preserve the performance of massive LLMs like GPT-3 — all while adding <strong>zero inference latency</strong>?</p><p>That’s the core idea behind <strong>LoRA (Low-Rank Adaptation)</strong>, one of the most influential breakthroughs in parameter-efficient fine-tuning for large language models.</p><p>In this deep-dive, I break down:<br>• Why full fine-tuning becomes impractical at the scale of GPT-3<br>• The mathematical intuition behind low-rank decomposition<br>• How LoRA injects trainable matrices into Transformer attention layers<br>• Why adapter layers increase latency but LoRA doesn’t<br>• The actual equations, architecture diagrams, and empirical benchmark results from the original Microsoft Research paper<br>• How LoRA achieves near full fine-tuning performance with only a fraction of the parameters</p><p>I also cover:<br>→ Attention matrix adaptation (Wq, Wv, Wo)<br>→ Rank deficiency and intrinsic dimension<br>→ GPU memory optimization<br>→ Transformer-level implementation details<br>→ Real benchmark comparisons on RoBERTa, DeBERTa, GPT-2, and GPT-3</p><p>If you’re working with:<br>LLMs, PEFT, Fine-Tuning, MLOps, Generative AI, or Transformer optimization — this article gives both the research intuition and engineering perspective behind why LoRA became foundational for modern LLM adaptation.</p><p>Read the full article here:<br><a href="https://sgupta-4.github.io/loraArticle/">https://sgupta-4.github.io/loraArticle/</a></p><p>#AI #MachineLearning #LLM #GenerativeAI #LoRA #DeepLearning #Transformers #DataScience #FineTuning #MLOps #ArtificialIntelligence</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b0473e5f82e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hermes Agent: The AI That Gets Smarter Every Time You Use It]]></title>
            <link>https://sarthakgupta0401.medium.com/hermes-agent-the-ai-that-gets-smarter-every-time-you-use-it-59e708e5f00d?source=rss-7267b495b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/59e708e5f00d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[openclaw]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Sarthak Gupta]]></dc:creator>
            <pubDate>Mon, 25 May 2026 11:31:00 GMT</pubDate>
            <atom:updated>2026-05-25T11:31:00.773Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How Nous Research built an agent that turns every task into a permanent skill — and why that changes everything.</em></p><p>Most AI agents suffer from amnesia. You run a complex task, the agent fumbles through it, eventually figures it out — and the next time you run the same task, it starts from scratch. Every token spent on trial-and-error is wasted. Every recovery strategy learned is forgotten.</p><p><strong>Hermes Agent</strong>, developed by Nous Research, is built around a different premise: what if an agent could remember not just <em>what</em> happened, but <em>how</em> it happened — and get measurably better at it over time?</p><h3>The Big Idea: Compounding Intelligence</h3><p>Most agent frameworks treat task execution as a stateless event. Hermes treats it as an investment.</p><p>The core innovation is a <strong>Closed Learning Loop</strong> — a four-phase cycle that transforms every task execution into persistent, procedural knowledge. Unlike LLM fine-tuning (which requires retraining weights), this happens entirely through structured text files and a curated skill library. No GPU budget required.</p><p>Here’s the cycle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_uZxj_0LbFdopmxSwD9X6Q.png" /><figcaption>Hermes Learning Loop</figcaption></figure><p><strong>Phase 1 — Execute:</strong> The agent performs the task using its full toolkit: web search, browser automation, terminal access, MCP servers, and more.</p><p><strong>Phase 2 — Evaluate:</strong> Post-completion, the agent doesn’t just stop. It reviews its own trace — the reasoning steps, tool calls, errors encountered, and recovery strategies used. The question it’s asking itself: <em>how did I do that, and could I do it better?</em></p><p><strong>Phase 3 — Extract:</strong> If a reusable pattern is identified, it gets codified into a SKILL.md file — a structured Markdown document with YAML frontmatter that captures the procedure in portable, human-readable form.</p><p><strong>Phase 4 — Retrieve:</strong> On future tasks, the agent checks its skill library first. If a matching pattern exists, it loads the proven procedure and bypasses the trial-and-error phase entirely.</p><p>The result is an agent that gets faster and cheaper to run over time. The first time Hermes does something hard, it earns it. Every subsequent time, it just knows.</p><h3>A Three-Layer Memory System</h3><p>Hermes manages state and knowledge through three distinct memory layers, each serving a different purpose:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7SvCXWehNla-3jWie7TJA.png" /><figcaption>Hermes Three Layer Architecture</figcaption></figure><h3>Layer 1 — Core Memory</h3><p>Always loaded. Defines who the agent <em>is</em> and who it’s working for. Three files:</p><ul><li>SOUL.md — the agent&#39;s persona and behavioral constraints</li><li>MEMORY.md — persistent factual knowledge accumulated over time</li><li>USER.md — preferences, working style, and context about the person it&#39;s serving</li></ul><h3>Layer 2 — Procedural Memory (The Skill Library)</h3><p>The heart of Hermes. A growing collection of SKILL.md files, each encoding a proven procedure for a specific type of task.</p><p>Critically, Hermes uses <strong>Progressive Disclosure</strong> to keep token usage in check. It doesn’t dump the entire skill library into context on every call. Instead, it retrieves only the skills relevant to the current task — a semantic match against what it’s about to do.</p><p>As the library grows, this becomes more powerful: the agent accumulates specialized knowledge across dozens of domains without the per-call cost ballooning.</p><h3>Layer 3 — Episodic Memory</h3><p>A SQLite database with FTS5 full-text search and LLM-powered summarization. This is the agent’s long-term autobiographical memory — a record of what happened across sessions, searchable by keyword, queryable by similarity.</p><p>When Hermes encounters a new problem, it can look back across its entire history of past executions and surface relevant episodes. It’s the difference between having experience and having <em>useful, accessible</em> experience.</p><h3>GEPA: The Agent That Edits Its Own Manual</h3><p>Manual skill creation is useful, but Hermes goes further with <strong>GEPA</strong> — Genetic-Pareto Prompt Evolution. This is an autonomous pipeline that mines the agent’s own execution history and proposes improvements to its existing skills, without any human intervention until the very end.</p><p>The pipeline runs in five stages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AjQexxsYaUNWBgh21vbjDw.png" /><figcaption>GEPA — Genetic-Pareto Prompt Evolution</figcaption></figure><ol><li><strong>Trace Collection</strong> — mines the SQLite execution history for relevant data about past skill performance</li><li><strong>Reflective Analysis</strong> — an LLM diagnoses <em>why</em> specific skills failed, were slow, or used more tokens than necessary</li><li><strong>Targeted Mutation</strong> — proposes specific text edits to the SKILL.md files</li><li><strong>Multi-Candidate Evaluation</strong> — runs candidate variants against a test suite, using Pareto optimization to balance two objectives simultaneously: success rate and token efficiency</li><li><strong>Human-in-the-Loop</strong> — proposed changes are packaged as a Pull Request and require human approval before deployment</li></ol><p>The last step is the crucial safety mechanism. GEPA can identify improvements, but it can’t deploy them unilaterally. This prevents <strong>skill hallucination</strong> — the failure mode where an agent confidently applies a subtly wrong procedure because it optimized for surface metrics rather than actual correctness.</p><p>The Pareto optimization is particularly elegant: GEPA doesn’t just maximize success rate (which might produce verbose, expensive procedures) or minimize token cost (which might produce fragile ones). It finds the frontier of solutions that improve both, and presents them for human review.</p><h3>Hermes vs. OpenClaw: A Tale of Two Philosophies</h3><p>As of mid-2026, Hermes’s primary competition is <strong>OpenClaw</strong>, which took a fundamentally different architectural approach when it migrated to ClawHub.</p><p>Where Hermes bets on <em>compounding intelligence</em>, OpenClaw bets on <em>breadth</em>. Its value proposition is a massive, community-built plugin ecosystem — thousands of pre-made integrations ready to use out of the box. Each session starts fresh with your chosen plugin configuration.</p><p>This is a real advantage when you need to connect to something obscure quickly. But it comes at a cost:</p><p><strong>No learning.</strong> OpenClaw sessions are stateless. Every time you run a task, it starts from zero. There’s no accumulated skill library, no episodic memory, no GEPA-driven improvement. The agent that runs your task on day 365 is no smarter than the one that ran it on day 1.</p><p><strong>Security trade-offs.</strong> A large third-party plugin ecosystem means a large attack surface. OpenClaw has accumulated multiple reported CVEs from its plugin layer. Hermes, with its sandboxed skill execution and deny-by-default permission model, maintains a zero-CVE record as of May 2026.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sCGcl1liMKQfHOCz_MGfXQ.png" /><figcaption>Hermes V/s OpenClaw</figcaption></figure><p>The choice between them is actually quite clear-cut:</p><blockquote><strong><em>Choose Hermes</em></strong><em> if you have recurring workflows, value long-term efficiency gains, and want a secure execution environment. The investment in the learning curve pays back in compounding returns.</em></blockquote><blockquote><strong><em>Choose OpenClaw</em></strong><em> if you need a specific integration </em>today<em> and don’t expect the task to recur. The breadth of the plugin library is unmatched for one-off tasks.</em></blockquote><h3>The Architecture in Full</h3><p>Pulling it all together, the Hermes runtime looks like this:</p><pre>User<br>  └─ Multi-Platform Gateway (web, API, CLI, mobile)<br>        ├─ Core Memory (SOUL / USER / MEMORY — always loaded)<br>        ├─ Agent Loop<br>        │     ├─ Tools / MCP Servers (web search, browser, terminal, ...)<br>        │     └─ Procedural Memory Hub (Progressive Disclosure)<br>        │           └─ SKILL.md × N<br>        └─ GEPA Evolution Pipeline<br>              └─ (async) mines SQLite → proposes skill mutations → PR</pre><p>The key structural insight is the separation between <strong>what the agent knows</strong> (Core Memory), <strong>how it does things</strong> (Procedural Memory), and <strong>what it has done</strong> (Episodic Memory). These three layers compose cleanly. GEPA bridges the episodic and procedural layers — it takes <em>what happened</em> and distills it into <em>how to do it better</em>.</p><h3>Why This Matters</h3><p>The dominant paradigm for improving AI systems has been: collect data, train a model, deploy, repeat. That loop is measured in months and costs millions.</p><p>Hermes proposes a different loop: deploy an agent, let it accumulate experience, let it propose improvements to its own procedures, approve the good ones. That loop runs continuously, costs nothing except inference, and doesn’t require touching the underlying model at all.</p><p>It’s a form of AI improvement that operates at the application layer rather than the model layer — and it compounds. An agent with 1,000 curated skills is qualitatively different from one with 10. The gap widens over time.</p><p>The Closed Learning Loop isn’t just a clever architecture. It’s a different theory of where agent capability comes from: not from a bigger model, but from better procedures, persistently accumulated, continuously refined.</p><p><em>Architecture diagrams generated from the official Nous Research technical documentation.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59e708e5f00d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Paper That Changed Everything: A Deep Dive into “Attention Is All You Need”]]></title>
            <link>https://sarthakgupta0401.medium.com/the-paper-that-changed-everything-a-deep-dive-into-attention-is-all-you-need-1c4597e23471?source=rss-7267b495b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c4597e23471</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[encoder-decoder]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Sarthak Gupta]]></dc:creator>
            <pubDate>Sun, 24 May 2026 05:04:08 GMT</pubDate>
            <atom:updated>2026-05-24T05:04:08.626Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How eight researchers from Google quietly rewired the future of AI in 2017</em></p><p>By the time you finish reading this sentence, a language model somewhere will have processed millions of tokens, translated a dozen documents, and helped someone write code — all because of a 15-page paper published in June 2017.</p><p>“Attention Is All You Need” by Vaswani et al. is not just an influential paper. It is arguably the most consequential machine learning publication of the 21st century. It gave us the Transformer — the architecture that powers GPT-4, Gemini, Claude, and virtually every state-of-the-art AI system you interact with today.</p><p>But what exactly did it propose? Why was it revolutionary? And what can we, as practitioners, learn from re-reading it in 2024?</p><p>Let’s dig in.</p><h3>The World Before the Transformer</h3><p>To understand why this paper matters, you need to feel the pain it solved.</p><p>Before 2017, the gold standard for sequence modeling — tasks like machine translation, text summarization, and question answering — was the Recurrent Neural Network, specifically its descendants: LSTMs (Long Short-Term Memory networks) and GRUs (Gated Recurrent Units).</p><p>RNNs are elegant in theory. They process sequences one token at a time, maintaining a “hidden state” that carries information forward. Think of it like reading a book and keeping a running mental summary as you go. The problem? That analogy reveals the flaw.</p><p><strong>They are fundamentally sequential.</strong> To process token 512, you must first process tokens 1 through 511. There’s no shortcut. On modern GPUs — which are built for parallelism — this is a massive waste of hardware. Training on long sequences became brutally slow.</p><p>Worse, information from early in a sequence had to survive through hundreds of hidden-state updates to influence the output. By token 512, what happened at token 3 had often been “forgotten” — numerically washed away. This is the infamous <strong>vanishing gradient problem</strong> for long-range dependencies.</p><p>Attention mechanisms were invented to patch this. By adding a mechanism that let the decoder “look back” at all encoder states, researchers improved translation quality considerably. But critically, these attention mechanisms were <em>add-ons</em> to RNNs, not replacements. The sequential bottleneck remained.</p><p>The authors of “Attention Is All You Need” asked a simple, radical question:</p><blockquote>What if we threw out the recurrence entirely?</blockquote><h3>The Core Idea: Self-Attention All the Way Down</h3><p>The Transformer dispenses with recurrence and convolutions completely. Its entire architecture is built on one primitive: <strong>attention</strong>.</p><p>The intuition is beautiful. When you read the sentence <em>“The animal didn’t cross the street because it was too tired,”</em> you immediately know “it” refers to “the animal,” not “the street.” You resolved that reference by attending to distant words based on semantic relevance — not by processing tokens sequentially.</p><p>The Transformer formalizes this. Every position in the sequence can directly attend to every other position in a single operation, regardless of distance.</p><h3>Scaled Dot-Product Attention</h3><p>The mechanism works like a soft lookup system. Each token produces three vectors through learned linear projections:</p><ul><li><strong>Query (Q)</strong> — “What am I looking for?”</li><li><strong>Key (K)</strong> — “What do I offer?”</li><li><strong>Value (V)</strong> — “What information do I carry?”</li></ul><p>The attention score between two tokens is computed by taking the dot product of one’s query with the other’s key, scaling by the square root of the key dimension (to prevent vanishingly small gradients in high dimensions), then applying a softmax to get a probability distribution over all positions. Finally, the output is a weighted sum of the values.</p><pre>Attention(Q, K, V) = softmax( QK^T / √d_k ) · V</pre><p>This single formula is doing something profound: it’s computing, for every token, how much it should “borrow” from every other token’s representation. And it does this for all tokens simultaneously — fully parallel, fully GPU-friendly.</p><h3>Why Scale by √d_k?</h3><p>This is a detail worth pausing on. The authors note that for large key dimensions, dot products grow very large in magnitude, pushing the softmax into regions of extremely small gradients — effectively killing learning. Dividing by √d_k keeps the values in a reasonable range. It’s a small fix with a large practical impact, and it’s a good example of the engineering intuition threaded throughout the paper.</p><h3>Multi-Head Attention: Learning Multiple Perspectives</h3><p>A single attention operation learns one way of relating tokens. But language is rich — “bank” relates to “river” in one context and “money” in another. Syntactic relationships differ from semantic ones.</p><p>The paper’s solution is elegant: run multiple attention operations in parallel, each with its own learned projections, then concatenate and project the outputs.</p><pre>MultiHead(Q, K, V) = Concat(head_1, ..., head_h) · W^O<br>where head_i = Attention(Q·W^Q_i, K·W^K_i, V·W^V_i)</pre><p>The paper uses <strong>h = 8 heads</strong>, with each head operating on a subspace of dimension 64 (since 512 / 8 = 64). The total computational cost is roughly the same as single-head attention at full dimension — but the model can now attend to information from multiple representation subspaces simultaneously.</p><p>The attention visualizations in the paper (Figures 3–5) are revelatory. Different heads learn genuinely different behaviors: some track syntactic dependencies, others handle anaphora resolution (like resolving pronoun references), and others still capture long-range semantic structure. The heads are not redundant — they specialize.</p><h3>The Full Architecture</h3><p>The Transformer follows an <strong>encoder-decoder</strong> structure, standard for sequence transduction tasks like translation.</p><h3>Encoder</h3><p>The encoder is a stack of N=6 identical layers. Each layer has two sub-layers:</p><ol><li><strong>Multi-Head Self-Attention</strong> — every position attends to every other position in the input</li><li><strong>Position-wise Feed-Forward Network</strong> — a two-layer MLP (with inner dimension 2048) applied identically to each position</li></ol><p>Each sub-layer is wrapped with a residual connection and layer normalization: output = LayerNorm(x + Sublayer(x)). This is critical for training deep networks stably.</p><h3>Decoder</h3><p>The decoder mirrors the encoder but adds a third sub-layer: <strong>cross-attention</strong> over the encoder’s output. This is where the decoder “reads” the encoded source representation while generating each output token.</p><p>Crucially, the decoder’s self-attention is <strong>masked</strong> — a position can only attend to earlier positions. This preserves the auto-regressive property: when generating token t, you cannot see tokens t+1, t+2, …. At inference time, you don’t have them yet.</p><h3>Positional Encoding</h3><p>Here’s the catch: pure attention has no notion of order. The attention operation is permutation-invariant — it doesn’t care whether token A comes before or after token B. For language, that’s a problem.</p><p>The solution is to inject positional information by adding sinusoidal encodings to the input embeddings:</p><pre>PE(pos, 2i)   = sin(pos / 10000^(2i/d_model))<br>PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model))</pre><p>Each dimension of the positional encoding corresponds to a different frequency sinusoid. The authors chose sinusoids (over learned embeddings) because they hypothesized the model could extrapolate to sequence lengths longer than those seen during training — a relative position PE_pos+k can be represented as a linear function of PE_pos.</p><p>Interestingly, they tested learned positional embeddings too, and found nearly identical results. But the sinusoidal approach had the length-generalization argument going for it, so that’s what shipped.</p><h3>Why Self-Attention Beats Recurrence: The Complexity Argument</h3><p>The paper’s Section 4 contains a table that became one of the most-cited comparisons in deep learning:</p><pre>|   Layer Type   | Complexity per Layer | Sequential Ops | Max Path Length |<br>|----------------|----------------------|----------------|-----------------|<br>| Self-Attention |      O(n² · d)       |       O(1)     |     O(1)        |<br>|    Recurrent   |      O(n · d²)       |       O(n)     |     O(n)        |<br>| Convolutional  |     O(k · n · d²)    |       O(1)     |   O(log_k(n))   |</pre><p>Three things jump out:</p><p><strong>Sequential operations</strong>: Self-attention requires O(1) sequential operations — everything is computed in parallel. Recurrent layers require O(n) — one step per token. This is the core training speed advantage.</p><p><strong>Maximum path length</strong>: The “path length” between two positions determines how easily long-range dependencies can be learned. For self-attention, any two positions are just one operation apart — O(1). For recurrent layers, a signal from position 1 must traverse n steps to reach position n — O(n), and gradients vanish along the way.</p><p><strong>Complexity per layer</strong>: Self-attention is quadratic in sequence length (n²) but linear in representation dimension (d). For typical NLP tasks where n &lt;&lt; d (sentence representations are often shorter than they are wide), self-attention is actually <em>faster</em> than recurrence.</p><p>The quadratic n² term becomes a real problem for very long sequences — this is precisely what drove later innovations like sparse attention (Longformer), linear attention approximations, and ultimately the Flash Attention algorithm. But for the sequence lengths typical in 2017 NLP, the tradeoff was overwhelmingly favorable.</p><h3>Training Details That Actually Matter</h3><p>The paper is unusually transparent about its training setup, and the details reward careful reading.</p><p><strong>Data</strong>: ~4.5 million English-German sentence pairs for the primary translation task, encoded with byte-pair encoding (shared source-target vocabulary of ~37,000 tokens).</p><p><strong>Hardware</strong>: 8 NVIDIA P100 GPUs. The base model trained in 12 hours; the big model in 3.5 days.</p><p><strong>Optimizer</strong>: Adam with a custom learning rate schedule — linearly warm up for 4,000 steps, then decay proportional to the inverse square root of the step number. This warmup turned out to be critical for training stability in Transformers, and variants of it persist in virtually every large model training run today.</p><p><strong>Regularization</strong>: Dropout (rate 0.1 for base, 0.3 for big) applied to sub-layer outputs and embedding sums. Label smoothing (ε = 0.1) — the model is penalized for being overconfident, which hurts perplexity slightly but improves translation quality and BLEU scores. Both choices were principled and effective.</p><h3>The Results</h3><p>The numbers were stunning for their time.</p><p>On WMT 2014 English-to-German translation, the Transformer (big) achieved <strong>28.4 BLEU</strong> — over 2 points better than the previous state of the art, including ensembles, at a fraction of the training cost.</p><p>On English-to-French, it hit <strong>41.8 BLEU</strong> after 3.5 days of training — a new single-model state of the art that cost less than one-quarter of what the previous best model required.</p><p>To put the efficiency story in context: the prior best model (GNMT + RL ensemble) cost ~1.1 × 1⁰²¹ FLOPs to train. The Transformer (big) cost ~2.3 × 1⁰¹⁹ FLOPs — roughly 50× cheaper — while exceeding it.</p><p>The paper also tested generalization to English constituency parsing, achieving competitive results with almost no task-specific tuning. A signal, in retrospect, of what was coming.</p><h3>What the Ablations Teach Us</h3><p>Table 3 in the paper runs systematic ablations on the architecture, and the lessons are worth internalizing:</p><ul><li><strong>Attention heads</strong>: Single-head attention is meaningfully worse. Too many heads also hurts. Eight was the sweet spot for this model scale.</li><li><strong>Key dimension (d_k)</strong>: Reducing it hurts quality — compatibility computation is non-trivial, and dot-product may not be expressive enough as d_k shrinks.</li><li><strong>Model size</strong>: Bigger is better, consistently. The big model (d_model=1024, 16 heads, 300K steps) outperforms the base by about 0.6 BLEU.</li><li><strong>Dropout</strong>: Highly effective. The model without dropout overfits noticeably.</li><li><strong>Positional encodings</strong>: Sinusoidal vs. learned — nearly identical. The architectural choice matters far less than it seems.</li></ul><h3>The Legacy: Why This Paper Rewired AI</h3><p>It is almost impossible to overstate the downstream impact of this work. A non-exhaustive list of what “Attention Is All You Need” enabled:</p><p><strong>BERT (2018)</strong> — Bidirectional encoder-only Transformer, pre-trained on masked language modeling. Transformed NLP benchmarks overnight.</p><p><strong>GPT series (2018–present)</strong> — Decoder-only Transformer, scaled aggressively. The architecture powering ChatGPT, GPT-4, and their successors.</p><p><strong>T5, BART, and the encoder-decoder renaissance</strong> — The full architecture as proposed, refined and scaled for seq2seq tasks.</p><p><strong>Vision Transformers (ViT, 2020)</strong> — The same architecture applied to image patches. Competitive with CNNs on ImageNet. Self-attention is not just for text.</p><p><strong>AlphaFold 2 (2021)</strong> — Attention mechanisms at the core of the model that solved protein structure prediction, one of biology’s hardest problems.</p><p><strong>Diffusion models with Transformers</strong> — DiT and Stable Diffusion 3 replace U-Net backbones with Transformers.</p><p>The paper’s final paragraph reads almost prophetically: <em>“We are excited about the future of attention-based models and plan to apply them to other tasks… involving input and output modalities other than text… such as images, audio and video.”</em></p><p>That future arrived, and then some.</p><h3>What Can We Learn, Re-Reading This in 2024?</h3><p>A few things stand out with the benefit of hindsight.</p><p><strong>Simplicity wins</strong>. The Transformer is not complicated. The attention formula fits on one line. The architecture is a clean stack of the same building block repeated. The insight was conceptual — recurrence is not necessary — and the execution was clean enough to let that insight shine through.</p><p><strong>Engineering details compound</strong>. The √d_k scaling factor, the warmup schedule, label smoothing, residual connections — none of these are glamorous. All of them matter. The difference between a paper that trains and one that doesn’t often comes down to exactly these choices.</p><p><strong>Parallelism unlocks scale</strong>. The reason Transformers scaled so dramatically — from the original 65M parameter base model to today’s trillion-parameter behemoths — is that the architecture is inherently GPU-friendly. Sequential computation bottlenecks don’t just slow you down; they cap you. Remove the bottleneck, and you can scale.</p><p><strong>Generalization is a clue, not an afterthought</strong>. The constituency parsing experiments in Section 6.3 were a footnote in the original paper. In retrospect, they were a preview of something profound: the architecture generalizes far beyond its training objective. That generality is what enables today’s multi-modal, multi-task foundation models.</p><h3>Final Thoughts</h3><p>“Attention Is All You Need” is the rare paper where the title is a complete argument. The claim is bold, the evidence is rigorous, and history has validated it beyond what even its authors anticipated.</p><p>If you work in machine learning and haven’t read it, stop here and read it now. It’s 15 pages. The math is accessible. The writing is clear. And understanding it deeply will sharpen your intuition for virtually every modern AI system you encounter.</p><p>The Transformer didn’t just improve NLP. It created the substrate on which modern AI runs. Eight researchers at Google proposed dispensing with 30 years of recurrent network orthodoxy, and the field never looked back.</p><p>Sometimes the right idea is not incremental. Sometimes it’s: throw away what you have, attend to what matters, and start over.</p><p><em>If you found this useful, follow for more deep dives into foundational ML research. Next up: BERT, and how bidirectional pre-training changed the game again.</em></p><p><strong>References</strong>: Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., &amp; Polosukhin, I. (2017). Attention is all you need. <em>Advances in Neural Information Processing Systems</em>, 30.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c4597e23471" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vector Databases Explained: The Memory Layer Powering Modern AI]]></title>
            <link>https://sarthakgupta0401.medium.com/vector-databases-explained-the-memory-layer-powering-modern-ai-73ba455f18a6?source=rss-7267b495b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/73ba455f18a6</guid>
            <category><![CDATA[vector-database]]></category>
            <dc:creator><![CDATA[Sarthak Gupta]]></dc:creator>
            <pubDate>Thu, 14 May 2026 07:36:15 GMT</pubDate>
            <atom:updated>2026-05-14T07:36:15.326Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How AI applications remember, search, and reason — and the specialized databases making it all possible</em></p><p>You’ve probably marveled at how ChatGPT can answer questions about a document you just pasted in, or how Spotify somehow knows what song you’re in the mood for. Behind these experiences lies a technology that rarely gets the spotlight it deserves: <strong>vector databases</strong>.</p><p>This article breaks down what vector databases are, how they work under the hood, and why they’re quickly becoming the backbone of every serious AI application.</p><h3>The Problem: Traditional Databases Can’t Think in “Meaning”</h3><p>Traditional databases are exceptional at exact lookups. Ask a SQL database for all users with age &gt; 25, and it returns precise results in milliseconds. But try asking it something like:</p><blockquote>“Find me articles that feel similar to this one”</blockquote><p>A relational database has no idea what to do. It can match keywords, but it can’t understand <strong>semantic similarity</strong> — the idea that “car” and “automobile” mean the same thing, or that a photo of a golden retriever is conceptually close to one of a labrador.</p><p>This is the gap that vector databases fill.</p><h3>What Is a Vector Embedding?</h3><p>Before we understand vector <em>databases</em>, we need to understand vector <em>embeddings</em>.</p><p>An embedding is a numerical representation of a piece of data — a sentence, an image, a product — expressed as a list of floating-point numbers called a <strong>vector</strong>.</p><pre># Example: Converting text to a vector embedding using OpenAI<br>import openai<br>client = openai.OpenAI(api_key=&quot;your-api-key&quot;)<br>response = client.embeddings.create(<br>    model=&quot;text-embedding-3-small&quot;,<br>    input=&quot;The quick brown fox jumps over the lazy dog&quot;<br>)<br>vector = response.data[0].embedding<br>print(f&quot;Dimensions: {len(vector)}&quot;)   # e.g., 1536<br>print(f&quot;First 5 values: {vector[:5]}&quot;)<br># Output: [-0.0023, 0.0412, -0.0193, 0.0287, -0.0341]</pre><p>The magic here is that <strong>semantically similar content produces numerically similar vectors</strong>. The vectors for “king” and “queen” will be much closer together in this high-dimensional space than “king” and “broccoli”.</p><h3>What Is a Vector Database?</h3><p>A vector database is a purpose-built data store that <strong>indexes, stores, and retrieves vector embeddings efficiently</strong>. Unlike traditional databases optimized for exact scalar lookups, vector databases are optimized for <strong>similarity search</strong> — finding the vectors closest to a given query vector.</p><p>They also bring the operational features of a proper database: CRUD operations, metadata filtering, horizontal scaling, backups, access control, and real-time updates. This is what separates them from standalone vector indexes like FAISS.</p><h3>How It Works: The Full Pipeline</h3><p>Here’s the lifecycle of data in a vector database:</p><pre>Raw Data  →  Embedding Model  →  Vector  →  Vector DB Index<br>                                                    ↑<br>Query     →  Embedding Model  →  Query Vector  ─────┘<br>                                                    ↓<br>                                          Similar Vectors  →  Results</pre><h3>Step 1 — Indexing</h3><p>When you insert data, the vector database runs it through an indexing algorithm to build a data structure optimized for nearest-neighbor lookup. There are several approaches — more on that below.</p><h3>Step 2 — Querying</h3><p>When a query arrives, it’s also embedded into a vector. The database then compares this query vector against indexed vectors using a <strong>similarity metric</strong> to find the closest matches.</p><h3>Step 3 — Post-Processing</h3><p>Results may be re-ranked using a different (often more expensive) similarity measure, and filtered by metadata to refine the final output.</p><h3>The Algorithms Powering Vector Search</h3><p>Under the hood, vector databases use <strong>Approximate Nearest Neighbor (ANN)</strong> algorithms. Here are the three most common approaches:</p><h3>1. Random Projection</h3><p>The idea: project high-dimensional vectors down to a lower-dimensional space using a random matrix, then compare in that smaller space.</p><pre>import numpy as np<br>def random_projection(vectors, target_dim):<br>    &quot;&quot;&quot;Reduce dimensionality using a random projection matrix.&quot;&quot;&quot;<br>    original_dim = vectors.shape[1]<br>    <br>    # Create a random projection matrix<br>    projection_matrix = np.random.randn(original_dim, target_dim) / np.sqrt(target_dim)<br>    <br>    # Project the vectors<br>    projected = vectors @ projection_matrix<br>    return projected<br># Example<br>original_vectors = np.random.randn(1000, 1536)   # 1000 vectors, 1536 dims<br>projected_vectors = random_projection(original_vectors, target_dim=128)<br>print(f&quot;Original shape:  {original_vectors.shape}&quot;)   # (1000, 1536)<br>print(f&quot;Projected shape: {projected_vectors.shape}&quot;)  # (1000, 128)</pre><p>Speed increases dramatically because searching 128 dimensions is far cheaper than searching 1,536. The trade-off is a small loss in accuracy.</p><h3>2. Locality-Sensitive Hashing (LSH)</h3><p>LSH maps similar vectors into the same “bucket” using hash functions. To find neighbors, you only search within the same bucket — not the entire dataset.</p><pre>import numpy as np<br>class LSH:<br>    def __init__(self, n_vectors, n_bits):<br>        &quot;&quot;&quot;Simple LSH using random hyperplane projections.&quot;&quot;&quot;<br>        self.planes = np.random.randn(n_bits, n_vectors)<br>    <br>    def hash_vector(self, vector):<br>        &quot;&quot;&quot;Hash a vector to a binary bucket key.&quot;&quot;&quot;<br>        projections = self.planes @ vector<br>        binary = (projections &gt; 0).astype(int)<br>        return &#39;&#39;.join(map(str, binary))<br>    <br>    def build_index(self, vectors):<br>        &quot;&quot;&quot;Build hash table from a set of vectors.&quot;&quot;&quot;<br>        self.table = {}<br>        for i, vec in enumerate(vectors):<br>            key = self.hash_vector(vec)<br>            self.table.setdefault(key, []).append(i)<br>        return self.table<br>    <br>    def query(self, query_vector):<br>        &quot;&quot;&quot;Find approximate neighbors for a query vector.&quot;&quot;&quot;<br>        key = self.hash_vector(query_vector)<br>        return self.table.get(key, [])<br><br># Usage<br>lsh = LSH(n_vectors=64, n_bits=8)<br>database_vectors = np.random.randn(500, 64)<br>lsh.build_index(database_vectors)<br>query = np.random.randn(64)<br>candidates = lsh.query(query)<br>print(f&quot;Candidate indices: {candidates}&quot;)</pre><h3>3. Hierarchical Navigable Small World (HNSW)</h3><p>HNSW is the gold standard in production vector search. It builds a multi-layer graph where vectors are nodes and edges connect similar vectors. Search begins at the top (coarse) layer and progressively zooms in.</p><pre># Using the `hnswlib` library — a production HNSW implementation<br>import hnswlib<br>import numpy as np<br>dim = 128<br>num_elements = 10_000<br># Initialize and build the index<br>index = hnswlib.Index(space=&#39;cosine&#39;, dim=dim)<br>index.init_index(max_elements=num_elements, ef_construction=200, M=16)<br># Add vectors to the index<br>data = np.random.randn(num_elements, dim).astype(np.float32)<br>index.add_items(data)<br># Query: find top 5 nearest neighbors<br>query_vector = np.random.randn(1, dim).astype(np.float32)<br>labels, distances = index.knn_query(query_vector, k=5)<br>print(f&quot;Nearest neighbor indices: {labels[0]}&quot;)<br>print(f&quot;Distances:                {distances[0]}&quot;)</pre><p>HNSW offers an excellent balance between speed and recall, which is why it’s the default algorithm in most production vector databases.</p><h3>Similarity Measures: How “Close” Is Close?</h3><p>The choice of similarity metric shapes your results. Here are the three main options:</p><pre>import numpy as np<br>def cosine_similarity(a, b):<br>    &quot;&quot;&quot;Measures the angle between vectors. Range: -1 to 1.&quot;&quot;&quot;<br>    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))<br>def euclidean_distance(a, b):<br>    &quot;&quot;&quot;Measures straight-line distance. Range: 0 to ∞.&quot;&quot;&quot;<br>    return np.linalg.norm(a - b)<br>def dot_product(a, b):<br>    &quot;&quot;&quot;Measures alignment and magnitude. Range: -∞ to ∞.&quot;&quot;&quot;<br>    return np.dot(a, b)<br># Example<br>v1 = np.array([1.0, 2.0, 3.0])<br>v2 = np.array([1.1, 1.9, 3.1])<br>v3 = np.array([-1.0, -2.0, -3.0])  # Opposite direction<br>print(f&quot;Cosine(v1, v2) = {cosine_similarity(v1, v2):.4f}&quot;)   # ≈ 0.9997 (very similar)<br>print(f&quot;Cosine(v1, v3) = {cosine_similarity(v1, v3):.4f}&quot;)   # ≈ -1.000 (opposite)<br>print(f&quot;Euclidean(v1, v2) = {euclidean_distance(v1, v2):.4f}&quot;)  # ≈ 0.1732 (close)</pre><p><strong>Rule of thumb:</strong> Use cosine similarity for text (normalizes for length), Euclidean for image embeddings, and dot product when magnitude matters.</p><h3>Metadata Filtering: Combining Semantic Search with Hard Constraints</h3><p>One of the key advantages of vector databases over standalone indexes is <strong>metadata filtering</strong>. You can attach structured data to each vector and combine semantic search with traditional filters.</p><pre># Using Pinecone as an example<br>from pinecone import Pinecone<br>pc = Pinecone(api_key=&quot;your-api-key&quot;)<br>index = pc.Index(&quot;articles-index&quot;)<br># Upsert vectors with metadata<br>index.upsert(vectors=[<br>    {<br>        &quot;id&quot;: &quot;article-001&quot;,<br>        &quot;values&quot;: [0.12, 0.45, ...],   # your embedding vector<br>        &quot;metadata&quot;: {<br>            &quot;category&quot;: &quot;technology&quot;,<br>            &quot;year&quot;: 2024,<br>            &quot;language&quot;: &quot;en&quot;,<br>            &quot;author&quot;: &quot;Jane Doe&quot;<br>        }<br>    },<br>    # ... more vectors<br>])<br># Query: find similar articles, but only from 2024, in English<br>results = index.query(<br>    vector=[0.11, 0.46, ...],   # query embedding<br>    top_k=5,<br>    filter={<br>        &quot;year&quot;: {&quot;$eq&quot;: 2024},<br>        &quot;language&quot;: {&quot;$eq&quot;: &quot;en&quot;}<br>    },<br>    include_metadata=True<br>)<br>for match in results[&#39;matches&#39;]:<br>    print(f&quot;Score: {match[&#39;score&#39;]:.4f} | {match[&#39;metadata&#39;][&#39;author&#39;]}&quot;)</pre><p>This two-dimensional search (semantic + structured) is incredibly powerful for real-world applications.</p><h3>Serverless Vector Databases: The Next Generation</h3><p>First-generation vector databases were fast and accurate — but expensive. They required dedicated compute running 24/7. Serverless vector databases decouple storage from compute, meaning you only pay for queries when they happen.</p><p>The architecture adds two key innovations:</p><p><strong>Geometric Partitioning</strong> — the index is split into sub-indices, allowing queries to search only relevant partitions rather than the full index.</p><p><strong>Freshness Layer</strong> — a temporary cache of recently inserted vectors that can be queried immediately, before the slower partitioned index has been updated.</p><pre>Insert new vector<br>       │<br>       ▼<br>┌─────────────┐      Freshness Layer (fast cache)<br>│ New Vectors │ ──► ┌──────────────────────────────┐<br>└─────────────┘     │  queryable within seconds     │<br>       │            └──────────────────────────────┘<br>       │                         │<br>       ▼                         │ (merged at query time)<br> Index Builder                   │<br>       │                         ▼<br>       ▼            ┌──────────────────────────────┐<br> Partitioned Index ►│  Query Router combines both   │<br>                    └──────────────────────────────┘</pre><h3>A Minimal End-to-End Example</h3><p>Let’s put it all together — a simple semantic search system using OpenAI embeddings and Pinecone:</p><pre>import openai<br>from pinecone import Pinecone, ServerlessSpec<br># Setup<br>openai_client = openai.OpenAI(api_key=&quot;your-openai-key&quot;)<br>pc = Pinecone(api_key=&quot;your-pinecone-key&quot;)<br># Create index<br>pc.create_index(<br>    name=&quot;semantic-search&quot;,<br>    dimension=1536,<br>    metric=&quot;cosine&quot;,<br>    spec=ServerlessSpec(cloud=&quot;aws&quot;, region=&quot;us-east-1&quot;)<br>)<br>index = pc.Index(&quot;semantic-search&quot;)<br># Documents to index<br>documents = [<br>    {&quot;id&quot;: &quot;1&quot;, &quot;text&quot;: &quot;Python is a high-level programming language.&quot;},<br>    {&quot;id&quot;: &quot;2&quot;, &quot;text&quot;: &quot;Machine learning enables computers to learn from data.&quot;},<br>    {&quot;id&quot;: &quot;3&quot;, &quot;text&quot;: &quot;Vector databases power semantic search applications.&quot;},<br>    {&quot;id&quot;: &quot;4&quot;, &quot;text&quot;: &quot;The Eiffel Tower is located in Paris, France.&quot;},<br>]<br># Embed and upsert<br>def get_embedding(text):<br>    res = openai_client.embeddings.create(model=&quot;text-embedding-3-small&quot;, input=text)<br>    return res.data[0].embedding<br>vectors = [<br>    {&quot;id&quot;: doc[&quot;id&quot;], &quot;values&quot;: get_embedding(doc[&quot;text&quot;]), &quot;metadata&quot;: {&quot;text&quot;: doc[&quot;text&quot;]}}<br>    for doc in documents<br>]<br>index.upsert(vectors=vectors)<br># Search<br>query = &quot;What language is great for data science?&quot;<br>query_vector = get_embedding(query)<br>results = index.query(vector=query_vector, top_k=2, include_metadata=True)<br>print(f&quot;Query: &#39;{query}&#39;\n&quot;)<br>for match in results[&quot;matches&quot;]:<br>    print(f&quot;  [{match[&#39;score&#39;]:.4f}] {match[&#39;metadata&#39;][&#39;text&#39;]}&quot;)<br># Output:<br># Query: &#39;What language is great for data science?&#39;<br>#   [0.8921] Python is a high-level programming language.<br>#   [0.7834] Machine learning enables computers to learn from data.</pre><p>The database surfaced the right answers without any exact keyword matches — purely on semantic meaning.</p><h3>Real-World Use Cases</h3><p>Vector databases are the foundation for many AI applications you interact with daily:</p><pre>Use Case             | What Gets Embedded        | Query Type<br>---------------------|---------------------------|--------------------------------------<br>Semantic search      | Documents, articles       | &quot;Find articles about climate change&quot;<br>RAG                  | Knowledge base chunks     | LLM context retrieval<br>Recommendations      | User behaviour, products  | &quot;Find similar products&quot;<br>Image similarity     | Photos, thumbnails        | &quot;Find visually similar images&quot;<br>Anomaly detection    | System logs, transactions | &quot;Find unusual patterns&quot;<br>Chatbot memory       | Conversation history      | &quot;What did the user ask before?&quot;</pre><h3>Vector DB vs. Traditional DB vs. Standalone Index</h3><pre>Feature              | Traditional DB | Standalone Index (FAISS) | Vector Database<br>---------------------|----------------|--------------------------|----------------<br>Similarity search    | No             | Yes                      | Yes<br>Metadata filtering   | Yes            | No                       | Yes<br>CRUD operations      | Yes            | No                       | Yes<br>Real-time updates    | Yes            | No (full re-index)       | Yes<br>Horizontal scaling   | Yes            | Custom                   | Yes<br>Access control       | Yes            | No                       | Yes<br>Production-ready     | Yes            | Requires work            | Yes</pre><h3>Final Thoughts</h3><p>Vector databases aren’t just a trendy tool — they represent a fundamental shift in how we store and query knowledge for AI systems. They’re the memory layer that makes AI applications <em>feel</em> intelligent: able to retrieve the right information, understand context, and reason across vast knowledge bases.</p><p>As AI workloads continue to grow, the vector database space will only mature. Serverless architectures are already making it possible to run semantic search at scale without burning through compute budgets. Multimodal embeddings (text + image + audio in the same space) are pushing the boundaries further.</p><p>Whether you’re building a RAG pipeline, a recommendation engine, or a semantic search tool — understanding the internals of a vector database will make you a better engineer and a more thoughtful architect.</p><p><em>Enjoyed this article? Follow for more deep-dives into the infrastructure powering modern AI.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73ba455f18a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built an Obsidian Clone for Windows & Android Using Flutter — Here’s Everything I Learned]]></title>
            <link>https://sarthakgupta0401.medium.com/i-built-an-obsidian-clone-for-windows-android-using-flutter-heres-everything-i-learned-7bd0c4e175c4?source=rss-7267b495b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bd0c4e175c4</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Sarthak Gupta]]></dc:creator>
            <pubDate>Sat, 28 Feb 2026 02:31:00 GMT</pubDate>
            <atom:updated>2026-02-28T02:31:00.690Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I built </em><a href="https://github.com/SGupta-4/OuterVoyager.git"><em>OuterVoyager</em></a><em>: an offline-first, encrypted, cross-platform note-taking app with wiki links, a knowledge graph, and free cloud sync — in a single Flutter codebase.</em></p><p>I’ve been an Obsidian user for years. I love the idea of a connected knowledge base — wiki links, backlinks, a visual graph of ideas. But I always ran into the same wall: Obsidian on Android felt like an afterthought, and getting seamless sync between my Windows machine and phone required third-party plugins and workarounds.</p><p>So I did what every developer eventually does: I built my own.</p><p><a href="https://github.com/SGupta-4/OuterVoyager.git"><strong>OuterVoyager</strong></a> is an Obsidian-inspired note-taking app targeting Windows and Android, built entirely in Flutter. It’s offline-first, end-to-end encryptable, has a force-directed knowledge graph, full-text search under 200ms, and syncs via Supabase’s free tier — so it costs $0/month to run.</p><p>Here’s how I built it, and what I learned along the way.</p><h3>Why Flutter?</h3><p>The obvious question first. Why not React Native + Electron? Why not a web app?</p><p>The answer comes down to three things: <strong>one codebase, one language, no bridge overhead.</strong></p><p>Flutter compiles to native ARM on Android and native Win32 on Windows. There’s no JavaScript bridge, no Electron Chromium shell eating 200MB of RAM before your app even loads. A single Dart codebase handles both platforms, with platform-specific layout adaptations handled cleanly through LayoutBuilder and responsive widgets.</p><p>The ecosystem maturity also helped — sqflite for SQLite, supabase_flutter for sync, riverpod for state management. Everything I needed existed and was stable.</p><h3>The Architecture: Three Clean Layers</h3><p>Before writing a single widget, I planned the architecture. The app follows a strict three-layer pattern:</p><pre>Presentation Layer  →  Domain Layer  →  Data Layer<br>(Flutter Widgets)      (Services)        (SQLite + Supabase)<br>(Riverpod Providers)</pre><p><strong>Data Layer</strong> handles all persistence — SQLite locally, Supabase remotely. Nothing in this layer knows about the UI.</p><p><strong>Domain Layer</strong> contains pure business logic: NoteService, SyncService, SearchService, BackupService, ExportService. These are plain Dart classes — easy to test, easy to reason about.</p><p><strong>Presentation Layer</strong> is Flutter widgets connected to Riverpod providers. The providers talk to domain services and expose state to the UI.</p><p>This separation paid off enormously when debugging sync issues. I could test conflict resolution logic with pure Dart unit tests without spinning up any UI.</p><h3>Core Features Deep-Dive</h3><h3>1. The Markdown Editor with Live Preview</h3><p>The editor is a split-panel experience: raw Markdown on the left, rendered preview on the right. On mobile, you toggle between the two.</p><p>I used markdown_widget for rendering — it&#39;s lightweight, supports code highlighting, tables, and works identically on both platforms. I deliberately avoided appflowy_editor because its dependency tree is massive and slows cold starts noticeably.</p><p>The formatting toolbar provides quick access to bold, italic, headings, code blocks, and wiki link insertion. Wiki links are the magic ingredient — type [[Note Name]] and the app parses it on save, auto-creates a link record in the database, and even creates the target note if it doesn&#39;t exist yet.</p><h3>2. Wiki Links &amp; Backlinks</h3><p>This is the heart of any Obsidian-like app. When you save a note, the NoteService runs a regex pass over the content:</p><pre>final wikiLinkRegex = RegExp(r&#39;\[\[([^\]]+)\]\]&#39;);</pre><p>Every match gets resolved to a note ID (or creates a stub note), and a row is inserted into the note_links table:</p><pre>CREATE TABLE note_links (<br>  source_id TEXT NOT NULL,<br>  target_id TEXT NOT NULL,<br>  target_title TEXT NOT NULL,<br>  PRIMARY KEY (source_id, target_id)<br>);</pre><p>Backlinks are then a simple reverse query — “give me all notes where target_id equals the current note&#39;s ID.&quot; The right panel shows these instantly, and clicking one navigates directly to that note.</p><h3>3. The Knowledge Graph</h3><p>This was the most fun part to build, and the part I was most tempted to over-engineer.</p><p>I wrote a custom force-directed layout engine in about 180 lines of Dart. Nodes repel each other (Coulomb’s law approximation), edges attract connected nodes (Hooke’s law), and a damping factor bleeds off energy until the graph settles. The whole simulation runs inside CustomPainter and hits 60fps for up to 500 nodes without breaking a sweat.</p><p>No external graph library. No WebView. Just math and Flutter’s canvas.</p><p>Tapping a node navigates to that note. Dragging nodes repositions them. The graph is rendered in both a full-screen GraphScreen and a smaller preview panel in the right sidebar.</p><h3>4. Instant Full-Text Search with FTS5</h3><p>SQLite has a killer feature that most people never use: <strong>FTS5</strong> — a full-text search virtual table that uses an inverted index under the hood. Results on 10,000 notes come back in under 200ms consistently.</p><p>The schema is straightforward:</p><pre>CREATE VIRTUAL TABLE notes_fts USING fts5(<br>  title, content, id UNINDEXED,<br>  content=&#39;notes&#39;, content_rowid=&#39;rowid&#39;<br>);</pre><p>FTS5 triggers keep the index in sync as notes are created, updated, and deleted. Searching is a single query:</p><pre>SELECT notes.* FROM notes<br>JOIN notes_fts ON notes.id = notes_fts.id<br>WHERE notes_fts MATCH ?<br>ORDER BY rank<br>LIMIT 50;</pre><p>The result is search that feels instantaneous.</p><h3>5. Offline-First Sync with Supabase</h3><p>This is the piece I’m proudest of architecturally.</p><p><strong>Everything writes to local SQLite first.</strong> The user never waits for a network response. Supabase is a secondary concern — a sync target, not a dependency.</p><p>When a note is saved, two things happen simultaneously:</p><ol><li>The note is written to the local SQLite database.</li><li>A record is added to a sync_queue table describing what changed.</li></ol><pre>CREATE TABLE sync_queue (<br>  entity_type TEXT,  -- &#39;note&#39; or &#39;folder&#39;<br>  entity_id TEXT,<br>  action TEXT,       -- &#39;create&#39;, &#39;update&#39;, &#39;delete&#39;<br>  payload TEXT,      -- JSON blob<br>  created_at TEXT,<br>  retries INTEGER DEFAULT 0<br>);</pre><p>A SyncService runs every 30 seconds when online, and also fires immediately when connectivity is restored (via connectivity_plus). It drains the queue oldest-first, pushing each change to Supabase. If a push fails, it increments retries and skips it — changes with more than 5 retries are surfaced to the user.</p><p>Pull sync fetches all remote changes newer than the last sync timestamp and applies them locally.</p><h3>6. Conflict Resolution</h3><p>Conflicts happen when you edit a note on both devices while offline. The algorithm is simple and transparent:</p><ol><li>Compare updated_at timestamps.</li><li>The newer version becomes the primary note.</li><li>The older version is saved as a new note titled {original_title}_conflict_{date}.md.</li><li>The user gets a notification and can manually review the conflict backup.</li></ol><p>No silent data loss. Ever.</p><h3>7. AES-256-GCM Encryption</h3><p>Sensitive notes can be encrypted using pointycastle — a pure Dart cryptography library with no native dependencies.</p><p>The key is derived from your password using PBKDF2 with SHA-256 and 100,000 iterations. Your password is never stored anywhere — not in SQLite, not in Supabase, not in shared preferences. You enter it per-session, and if you forget it, the note is gone.</p><p>The cipher is AES-256-GCM, which provides both confidentiality and authenticity. Any tampering with the ciphertext causes decryption to fail loudly.</p><h3>State Management with Riverpod</h3><p>I chose Riverpod 2.6 over BLoC for this project. For an app of this scale, BLoC’s boilerplate felt like overkill. Riverpod gives me:</p><ul><li><strong>Type-safe providers</strong> with compile-time errors</li><li><strong>AsyncNotifier</strong> for async data (notes list, search results)</li><li><strong>StateNotifier</strong> for UI state (selected note, sidebar state)</li><li>Providers that work outside the widget tree — essential for background sync</li></ul><p>The dependency graph is clean: SyncProvider depends on NoteProvider and ConnectivityProvider, and Riverpod handles the dependency wiring automatically.</p><h3>Database Schema Highlights</h3><p>The local SQLite schema has six tables:</p><p>Table Purpose notes Core note data with soft delete notes_fts FTS5 virtual table for search folders Hierarchical folder structure (self-referencing) tags Tag registry note_tags Many-to-many junction note_links Wiki link graph edges sync_queue Pending changes for cloud sync</p><p>The Supabase schema mirrors the notes and folders tables, with PostgreSQL Row Level Security policies ensuring users can only access their own data.</p><h3>Responsive Layout: One Codebase, Two Experiences</h3><p>On Windows, the app renders a three-panel layout: sidebar, editor, and right panel side by side. On Android, the sidebar becomes a Drawer, and the right panel is accessible via bottom tabs.</p><p>This is handled in HomeScreen with a single LayoutBuilder check:</p><pre>if (constraints.maxWidth &gt; 900) {<br>  return DesktopLayout();  // 3-panel<br>} else {<br>  return MobileLayout();   // drawer + tabs<br>}</pre><p>No separate codebases. No platform-specific forks. The same widget tree adapts.</p><h3>What I’d Do Differently</h3><p><strong>Real-time sync.</strong> Currently sync polls every 30 seconds. Supabase supports real-time subscriptions via WebSockets — I’d use those to push changes instantly instead of polling.</p><p><strong>Conflict UI.</strong> The current conflict resolution just creates a backup note. A side-by-side diff view would be far more helpful.</p><p><strong>Plugin system.</strong> Obsidian’s power comes from its community plugins. I’d love to add a lightweight plugin API — maybe WASM-based — but that’s a v2 problem.</p><h3>Try It Yourself</h3><p><a href="https://github.com/SGupta-4/OuterVoyager.git">OuterVoyager</a> is open source under the MIT License. You can clone it, set up a free Supabase project in 5 minutes, and have a fully functional personal knowledge base running on your Windows machine and Android phone — for free, forever.</p><p>The app works completely offline without any Supabase setup. Cloud sync is opt-in.</p><pre>git clone https://github.com/YOUR_USERNAME/OuterVoyager.git<br>cd OuterVoyager<br>flutter pub get<br>flutter run -d windows  # or -d &lt;android-device-id&gt;</pre><p>Building <a href="https://github.com/SGupta-4/OuterVoyager.git">OuterVoyager</a> reminded me why I love Flutter. The ability to ship a genuinely native app on two very different platforms from one codebase — without compromising on performance or platform feel — is still remarkable. The knowledge graph alone took an afternoon. The sync engine took a week. But the result is an app I actually use every day.</p><p>If you’re thinking about building a cross-platform desktop + mobile app, I’d strongly encourage you to look at Flutter before defaulting to Electron + React Native. The developer experience is excellent and the output is fast.</p><p><em>Made with ❤️ by Sarthak Gupta</em></p><p><em>Have questions about the architecture or want to contribute? Open an issue on GitHub or leave a comment below.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bd0c4e175c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Can Now Write Research Papers. But It Still Can’t Draw the Diagrams. Until Now.]]></title>
            <link>https://sarthakgupta0401.medium.com/ai-can-now-write-research-papers-but-it-still-cant-draw-the-diagrams-until-now-e6d8b549e7d7?source=rss-7267b495b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6d8b549e7d7</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[paperbanana]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-research]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Sarthak Gupta]]></dc:creator>
            <pubDate>Wed, 11 Feb 2026 05:58:45 GMT</pubDate>
            <atom:updated>2026-02-11T05:58:45.799Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s the paradox nobody talks about: AI can run your experiments, write your code, and even draft your conclusions. But when it comes to making Figure 1 — that one diagram that explains your entire methodology — you’re still stuck in PowerPoint at 2 AM, manually dragging boxes around.</p><p>This isn’t just annoying. It’s the bottleneck that’s holding back the entire vision of autonomous science.</p><p>A team from Peking University and Google Cloud AI Research just changed that. Their system, called PaperBanana, doesn’t just generate diagrams. It assembles a team of AI agents that collaborate like a professional design studio — complete with a research intern, an architect, a designer, an illustrator, and a critic who tells everyone when they’re wrong.</p><p>And the results? Diagrams that beat human-drawn versions in clarity, aesthetics, and conciseness.</p><p>Let’s break down how they pulled this off.</p><h3>The Figure 1 Problem Is Worse Than You Think</h3><p>Every researcher knows the drill. You’ve spent weeks building a model, running experiments, analyzing results. Your breakthrough is real. Your data is solid.</p><p>Then you hit the wall: explaining it visually.</p><p>Figure 1 is the executive summary of your paper. It’s the first thing reviewers see. It’s what determines whether someone keeps reading or moves on to the next submission. And despite all the progress in AI-assisted research, creating that diagram is still a completely manual process.</p><p>Why? Because academic diagrams aren’t just pictures. They’re a visual language with unspoken rules about color palettes, layout conventions, and aesthetic norms that vary by field and venue. A diagram that works for a computer vision paper looks different from one in natural language processing. A NeurIPS figure has a different vibe than a Nature figure.</p><p>These aren’t things you can capture in a simple text prompt.</p><h3>Why Current Approaches Fall Short</h3><p>You might think: “Can’t we just use code-based tools like TikZ or SVG generators?”</p><p>Sure, if you want pixel-perfect accuracy. But code-based approaches are rigid. They require you to specify every geometric detail manually. You’re essentially programming the diagram, which defeats the purpose of automation.</p><p>What about image generation models? Just feed them a description and let them create something pretty?</p><p>Here’s the problem: image models are trained on everything from memes to movie posters. They don’t inherently understand the scholarly aesthetic. Ask them to “make a diagram showing multi-agent collaboration” and you might get something visually interesting — but it won’t look like it belongs in a research paper.</p><p>Even worse, image models hallucinate. They might flip your data relationships, duplicate labels, or connect the wrong components. When you’re trying to communicate precise technical logic, these errors aren’t just embarrassing — they’re misleading.</p><p>The real challenge is that creating academic diagrams requires something AI hasn’t mastered: <strong>taste</strong>.</p><h3>The Big Idea: What If AI Worked Like a Design Agency?</h3><p>Here’s where PaperBanana gets clever. Instead of treating diagram generation as a single-model problem, the researchers built it as a <strong>multi-agent collaboration</strong>.</p><p>Think about how a professional design studio actually works. You don’t have one person doing everything. You have specialists:</p><ul><li>Someone who researches existing work and finds inspiration</li><li>Someone who plans the overall structure</li><li>Someone who ensures it matches the brand guidelines</li><li>Someone who creates the actual visuals</li><li>Someone who reviews and provides feedback</li></ul><p>PaperBanana mirrors this exact workflow. But instead of humans, it’s five AI agents, each with a specific job.</p><h3>Meet the Team: Five Agents, One Goal</h3><p><strong>The Retriever</strong> is your research intern. Its job is to dig through thousands of published papers and find visual examples that match your methodology. But here’s the twist: it doesn’t just search by topic. It searches by <em>visual structure</em>. If your paper describes a multi-stage pipeline, the Retriever finds other papers with multi-stage pipeline diagrams — even if they’re from completely different domains.</p><p><strong>The Planner</strong> is your architect. It takes your methodology description (usually just a text explanation of how your system works) and translates it into a detailed visual plan. It learns from the examples the Retriever found, understanding how similar ideas were visualized before. This isn’t template-filling — it’s reasoning about how to map abstract concepts onto concrete visual elements.</p><p><strong>The Stylist</strong> is your designer. This is where PaperBanana gets really interesting. The Stylist doesn’t just apply random aesthetic choices. It has analyzed thousands of successful papers and synthesized a set of “Aesthetic Guidelines” — basically, a codebook for what makes a diagram look professional.</p><p>These guidelines cover five dimensions: color palettes (avoid garish combinations, use semantic color coding), shapes and containers (rounded vs. sharp corners, when to use boxes vs. circles), lines and arrows (solid vs. dashed, thickness conventions), layout and composition (whitespace rules, alignment principles), and typography (font hierarchies, icon styles).</p><p>By automating taste, the Stylist ensures your diagram doesn’t just communicate — it communicates <em>like a professional</em>.</p><p><strong>The Visualizer</strong> is your illustrator. Powered by specialized image generation models, it takes the Stylist’s refined description and creates the actual visual output. This is where the abstract plan becomes concrete pixels.</p><p><strong>The Critic</strong> is your reviewer. And this agent is crucial. Using advanced vision-language models, the Critic inspects the generated diagram against the original methodology description. It looks for factual errors, visual glitches, and inconsistencies. Did the Visualizer connect the wrong components? Does the arrow flow match the described logic? The Critic catches these mistakes and sends the diagram back for revision.</p><p>This isn’t a one-shot process. It’s an iterative loop that can run up to three refinement rounds.</p><h3>The Self-Improving Cycle</h3><p>Here’s what makes this powerful: the system mirrors how humans actually refine their work.</p><p>You don’t write a perfect paper on the first draft. You iterate. You write, review, revise. Write, review, revise.</p><p>PaperBanana does the same thing with diagrams. The Visualizer creates an initial version. The Critic evaluates it. If there are issues — maybe an arrow points to the wrong block, or a label is missing — the Critic provides specific feedback. The Visualizer generates a new version. The cycle repeats.</p><p>The researchers found that this iterative refinement is where the magic happens. The first draft might have hallucinations or awkward layout choices. By the third iteration, the diagram is publication-ready.</p><h3>What Actually Improved?</h3><p>The team tested PaperBanana on 292 real methodology diagrams from NeurIPS 2025 papers. They compared AI-generated versions against the original human-drawn diagrams.</p><p>The results were striking.</p><p><strong>Conciseness:</strong> PaperBanana beat humans by 37%. Why? Because humans over-explain. When you’re creating a diagram manually, you feel the need to add extra text, redundant labels, and explanatory notes. You don’t trust the visual structure to carry the information. The AI, guided by reference-driven planning, trusts the visual language. It removes clutter.</p><p><strong>Readability:</strong> 13% improvement. The AI used distinct color zones and logical separation more effectively. Human diagrams often blend sections together or use inconsistent visual hierarchies. The AI, following synthesized aesthetic guidelines, creates clearer boundaries.</p><p><strong>Aesthetics:</strong> When they ran a direct comparison (human-drawn vs. AI-polished), the AI-enhanced versions won 56% of the time. That’s not just matching human quality — it’s exceeding it.</p><p>These aren’t marginal gains. These are diagrams that reviewers would actually prefer to look at.</p><h3>The Unexpected Use Case: Polishing Human Work</h3><p>Here’s something the researchers didn’t initially plan for: PaperBanana became a design assistant.</p><p>Instead of generating diagrams from scratch, researchers could feed in their existing hand-drawn diagrams. The Stylist Agent would analyze them against the aesthetic guidelines and suggest improvements — better color choices, cleaner typography, more balanced layouts.</p><p>It’s like having a professional designer review your work and give you actionable feedback.</p><p>This opens up a different vision of AI tools. Not replacing human creativity, but augmenting it. You sketch the idea, the AI polishes it into something publication-worthy.</p><h3>The Accuracy Paradox</h3><p>There’s one area where PaperBanana hits a fundamental trade-off: statistical plots.</p><p>When you need to create a bar chart or line graph with precise numerical values, you have two options. You can use image generation (visually stunning, but prone to numerical hallucinations) or you can generate Python code that renders with Matplotlib (perfectly accurate, but aesthetically dated).</p><p>The researchers found that image models would sometimes invert relationships — showing Player A’s bar higher than Player B’s when the data said the opposite. Or they’d duplicate axis labels unnecessarily.</p><p>Code generation avoided these errors but produced plots that looked like default Matplotlib outputs from 2010.</p><p>The solution? Hybrid workflows. Use image generation for high-level methodology diagrams where visual appeal matters. Use code generation for data-heavy plots where numerical precision is critical.</p><h3>Why This Matters Beyond Diagrams</h3><p>PaperBanana isn’t just about making prettier figures. It’s a proof point for something bigger: <strong>autonomous scientific communication</strong>.</p><p>We’re moving toward a future where AI doesn’t just conduct research — it presents research. An autonomous agent could run experiments, analyze results, and then generate the entire visual narrative needed to communicate those findings.</p><p>Think about the implications:</p><ul><li>AI-generated textbooks that visualize complex concepts on demand</li><li>Research tools that automatically create presentation slides from your draft papers</li><li>Design assistants that help non-designers create professional visual content</li><li>Fully autonomous scientists that can publish their own discoveries</li></ul><p>The bottleneck between discovery and communication is dissolving.</p><h3>The Limitations You Need to Know</h3><p>Before we get too excited, let’s talk about where PaperBanana still struggles.</p><p><strong>Vector vs. Raster:</strong> The current system generates raster images (pixels). For publication-quality diagrams, researchers often need vector formats (SVG, PDF) that scale cleanly to any resolution. That’s still an open problem.</p><p><strong>Fine-Grained Connectivity:</strong> The Critic agent is good at catching major errors, but it sometimes misses subtle technical details. In their failure analysis, the researchers found cases where arrows connected to the wrong blocks — pointing to “Keys” when the text specified “Queries.” These are the kinds of precise logical relationships that current vision-language models still struggle to verify.</p><p><strong>Human Oversight Required:</strong> The researchers emphasized this in their impact statement: visual hallucinations are a real risk. You can’t blindly trust these diagrams. A human expert needs to review the output, especially for technical papers where precision matters.</p><p>This isn’t a fully autonomous solution yet. It’s a powerful assistant that still needs supervision.</p><h3>The Future of Research Communication</h3><p>Here’s the closing thought: if AI can now synthesize the visual logic of thousands of papers in seconds and present it with professional-grade polish, how will this change the speed at which we consume and validate new breakthroughs?</p><p>The traditional research cycle has built-in slowdowns. Writing is slow. Formatting is slow. Creating diagrams is painfully slow. These delays give us time to think, to review, to question.</p><p>What happens when those delays disappear?</p><p>We might publish faster. We might communicate more clearly. We might make science more accessible.</p><p>But we’ll also need to adapt how we evaluate and validate scientific claims. When the presentation is polished to perfection, the burden shifts entirely to the substance. The diagram won’t be the bottleneck anymore.</p><p>The ideas will be.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6d8b549e7d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dart Fundamentals: A Beginner’s Guide to Variables, Types, and More]]></title>
            <link>https://sarthakgupta0401.medium.com/dart-fundamentals-a-beginners-guide-to-variables-types-and-more-7396a7b6936d?source=rss-7267b495b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7396a7b6936d</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[variables-in-dart]]></category>
            <category><![CDATA[functions-in-dart]]></category>
            <category><![CDATA[dart-programming-language]]></category>
            <dc:creator><![CDATA[Sarthak Gupta]]></dc:creator>
            <pubDate>Wed, 28 Jan 2026 02:31:01 GMT</pubDate>
            <atom:updated>2026-01-28T02:31:01.646Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the world of Dart! Whether you’re diving into Flutter development or exploring Dart as a standalone language, understanding the fundamentals is crucial. This guide will walk you through the essential concepts that every Dart developer needs to know.</p><h3>Understanding Variables in Dart</h3><h3>The Three Ways to Declare Variables</h3><p>When you start with Dart, you’ll encounter three main keywords for declaring variables: var, final, and const. Let&#39;s understand when to use each.</p><h4>Using var for Type Inference</h4><p>The var keyword lets Dart figure out the type automatically based on the value you assign:</p><pre>var name = &#39;Alice&#39;;        // Dart knows this is a String<br>var age = 25;              // Dart knows this is an int<br>var height = 5.8;          // Dart knows this is a double</pre><p>You can also be explicit about types if you prefer:</p><pre>String name = &#39;Alice&#39;;<br>int age = 25;<br>double height = 5.8;</pre><h4>The Difference Between final and const</h4><p>This is where many beginners get confused, so let’s clarify:</p><p><strong>final - Set Once at Runtime</strong></p><p>Use final when you want a variable that won&#39;t change after it&#39;s set, but its value is determined while your program runs:</p><pre>final DateTime now = DateTime.now();  // Value known at runtime<br>final String userName = getUserInput();  // Gets value from user<br>final List&lt;int&gt; numbers = [1, 2, 3];<br>numbers.add(4);  // This works! The list can change<br>numbers = [5, 6];  // ERROR: Can&#39;t reassign final variable</pre><p><strong>const - Compile-Time Constant</strong></p><p>Use const when the value is known before your program even runs:</p><pre>const double pi = 3.14159;  // Known at compile time<br>const int maxUsers = 100;<br>const List&lt;int&gt; primes = [2, 3, 5, 7];<br>primes.add(11);  // ERROR: Can&#39;t modify const collection</pre><p><strong>Key takeaway</strong>: final means &quot;assign once, value determined at runtime.&quot; const means &quot;never changes, value known before running.&quot;</p><h3>The late Keyword: Delayed Initialization</h3><p>Sometimes you know a variable will have a value before you use it, but you can’t set it right away. That’s where late comes in:</p><pre>late String description;<br>void setup() {<br>  description = &#39;Ready to go!&#39;;<br>}<br>void main() {<br>  setup();<br>  print(description);  // Works fine<br>}</pre><p>late has two powerful uses:</p><ol><li><strong>Telling Dart “trust me”</strong> — You promise to set the value before using it</li><li><strong>Lazy initialization</strong> — The value is only calculated when first accessed:</li></ol><pre>late String expensiveData = fetchFromDatabase();  <br>// Only runs when you actually use expensiveData</pre><p><strong>Warning</strong>: If you access a late variable before initializing it, your program will crash with a runtime error.</p><h3>Dart’s Type System</h3><h3>Numbers: int and double</h3><p>Dart has two number types:</p><pre>int age = 25;                    // Whole numbers<br>double price = 19.99;            // Decimal numbers<br>num flexibleNumber = 42;         // Can be int or double<br>flexibleNumber = 42.5;           // Still valid!</pre><p>Dart 3.6+ introduced <strong>digit separators</strong> for readability:</p><pre>var million = 1_000_000;<br>var phoneNumber = 555_123_4567;<br>var piApprox = 3.141_592_653;</pre><p><strong>Converting between strings and numbers:</strong></p><pre>// String to number<br>var age = int.parse(&#39;25&#39;);<br>var price = double.parse(&#39;19.99&#39;);<br>// Number to string<br>String ageText = 25.toString();<br>String priceText = 19.99.toStringAsFixed(2);  // &quot;19.99&quot;</pre><h3>Strings: More Than Just Text</h3><p>Dart strings are powerful and flexible:</p><pre>var single = &#39;Single quotes work&#39;;<br>var double = &quot;Double quotes too&quot;;<br>var escaped = &#39;It\&#39;s easy to escape&#39;;</pre><p><strong>String interpolation</strong> makes combining text and variables elegant:</p><pre>var name = &#39;Alice&#39;;<br>var age = 25;<br>print(&#39;Hello, $name!&#39;);  // For simple variables<br>print(&#39;Next year you\&#39;ll be ${age + 1}&#39;);  // For expressions</pre><p><strong>Multi-line strings</strong> use triple quotes:</p><pre>var multiLine = &#39;&#39;&#39;<br>This is a<br>multi-line<br>string.<br>&#39;&#39;&#39;;</pre><p><strong>Raw strings</strong> treat everything literally (great for regex):</p><pre>var path = r&#39;C:\Users\Alice\Documents&#39;;  // Backslashes are literal</pre><h3>Booleans: True or False</h3><p>Dart is strict about boolean values — no “truthy” or “falsy” conversions:</p><pre>var isLoggedIn = true;<br>var hasPermission = false;<br>// You must explicitly check conditions<br>var name = &#39;&#39;;<br>if (name.isEmpty) {  // Correct<br>  print(&#39;No name provided&#39;);<br>}<br>// if (name) { }  // ERROR: Dart doesn&#39;t allow this</pre><h3>Null Safety: Preventing the Billion Dollar Mistake</h3><p>Dart’s null safety prevents crashes from accessing null values:</p><pre>String cannotBeNull = &#39;Always has a value&#39;;<br>String? mightBeNull = null;  // The ? allows null<br>// cannotBeNull = null;  // ERROR: Not allowed<br>mightBeNull = null;  // OK<br>// Safely handle nullable values<br>if (mightBeNull != null) {<br>  print(mightBeNull.length);  // Safe to use<br>}<br>// Force unwrap (use carefully!)<br>String definitelyHasValue = mightBeNull!;  // Throws if null</pre><h3>Collections: Lists, Sets, and Maps</h3><pre>// Lists (ordered, allows duplicates)<br>var fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;];<br>fruits.add(&#39;mango&#39;);<br>// Sets (unordered, unique values)<br>var uniqueNumbers = {1, 2, 3, 3, 3};  // Still just {1, 2, 3}<br>// Maps (key-value pairs)<br>var person = {<br>  &#39;name&#39;: &#39;Alice&#39;,<br>  &#39;age&#39;: 25,<br>  &#39;city&#39;: &#39;New York&#39;<br>};</pre><h3>Understanding Method Chaining</h3><p>Let’s revisit that line of code from earlier:</p><pre>flybyObjects.where((name) =&gt; name.contains(&#39;turn&#39;)).forEach(print);</pre><p>This demonstrates <strong>method chaining</strong> — calling multiple methods in sequence. Let’s break it down:</p><h3>Step 1: Start with a list</h3><pre>var flybyObjects = [&#39;Jupiter&#39;, &#39;Saturn&#39;, &#39;Uranus&#39;, &#39;Neptune&#39;];</pre><h3>Step 2: Filter with where()</h3><pre>flybyObjects.where((name) =&gt; name.contains(&#39;turn&#39;))</pre><p>The where() method filters the list. It takes a function that:</p><ul><li>Receives each element (we call it name)</li><li>Returns true to keep the element, false to discard it</li><li>Only ‘Saturn’ contains ‘turn’, so only it passes through</li></ul><h3>Step 3: Print each result with forEach()</h3><pre>.forEach(print)</pre><p>The forEach() method runs a function for each remaining element. Here we pass print directly as a function.</p><p><strong>Result</strong>: This prints “Saturn” to the console.</p><h3>Understanding Arrow Functions</h3><p>The =&gt; syntax is a shorthand for simple functions:</p><pre>// Arrow function (concise)<br>(name) =&gt; name.contains(&#39;turn&#39;)<br>// Equivalent regular function<br>(name) {<br>  return name.contains(&#39;turn&#39;);<br>}</pre><p>Use arrow functions when you have a single expression to return. They make your code cleaner and more readable.</p><h3>Practical Example: Putting It All Together</h3><p>Let’s create a simple program that demonstrates these concepts:</p><pre>void main() {<br>  // Variables and type inference<br>  var userName = &#39;Alice&#39;;<br>  final DateTime signupDate = DateTime.now();<br>  const int maxLoginAttempts = 3;<br>  <br>  // Collections<br>  var favoriteColors = [&#39;blue&#39;, &#39;green&#39;, &#39;purple&#39;];<br>  <br>  // String interpolation<br>  print(&#39;Welcome, $userName!&#39;);<br>  print(&#39;Member since: ${signupDate.year}&#39;);<br>  <br>  // Method chaining with arrow functions<br>  var longColors = favoriteColors<br>      .where((color) =&gt; color.length &gt; 4)<br>      .toList();<br>  <br>  print(&#39;Your long color names: $longColors&#39;);<br>  <br>  // Null safety<br>  String? optionalMessage;<br>  print(optionalMessage ?? &#39;No message available&#39;);<br>  <br>  // Late variable<br>  late String greeting;<br>  greeting = &#39;Hello, ${userName}!&#39;;<br>  print(greeting);<br>}</pre><h3>Key Takeaways</h3><ol><li><strong>Use </strong><strong>var for flexibility</strong> - Let Dart infer types in most cases</li><li><strong>Choose </strong><strong>final over </strong><strong>const</strong> - Unless the value is truly known at compile time</li><li><strong>Embrace null safety</strong> — Use ? for nullable types, ! to assert non-null</li><li><strong>late is powerful</strong> - Use it for deferred or lazy initialization</li><li><strong>String interpolation is your friend</strong> — Use $variable or ${expression}</li><li><strong>Arrow functions are concise</strong> — Perfect for simple, single-expression functions</li><li><strong>Method chaining is elegant</strong> — Chain operations for readable, functional-style code</li></ol><h3>What’s Next?</h3><p>Now that you understand Dart’s fundamentals, you’re ready to explore:</p><ul><li>Classes and object-oriented programming</li><li>Asynchronous programming with async and await</li><li>Error handling with exceptions</li><li>Advanced collection operations</li><li>Building real applications with Flutter</li></ul><p>Remember, the best way to learn is by writing code. Experiment with these concepts, break things, and learn from the errors. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7396a7b6936d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Dart’s Three Web Compilation Modes: A Developer’s Guide]]></title>
            <link>https://sarthakgupta0401.medium.com/understanding-darts-three-web-compilation-modes-a-developer-s-guide-195c4e94d096?source=rss-7267b495b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/195c4e94d096</guid>
            <category><![CDATA[native-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Sarthak Gupta]]></dc:creator>
            <pubDate>Wed, 21 Jan 2026 02:33:12 GMT</pubDate>
            <atom:updated>2026-01-21T02:33:12.415Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re building web applications with Dart or Flutter, you might have wondered: “How does my Dart code actually run in a browser?” The answer is more sophisticated than you might think — and it’s one of Dart’s key advantages for web development.</p><h3>The Fundamental Challenge</h3><p>Browsers don’t natively understand Dart. They understand two languages:</p><ul><li><strong>JavaScript</strong> (supported by all browsers)</li><li><strong>WebAssembly</strong> (supported by modern browsers)</li></ul><p>So Dart needs to be translated. But here’s where it gets interesting: Dart doesn’t just have <em>one</em> way to compile to the web — it has <em>three</em>, each optimized for different scenarios.</p><h3>The Three Compilation Modes</h3><h3>1. Incremental JavaScript Development Compiler: Your Iteration Engine</h3><p>During development, speed is everything. You make a change, you want to see it <em>now</em> — not after a 30-second rebuild.</p><p>This is where the <strong>incremental JavaScript development compiler</strong> shines.</p><p><strong>What it does:</strong></p><ul><li>Compiles only the code that changed</li><li>Enables hot reload in the browser</li><li>Provides source maps for debugging</li><li>Prioritizes compilation speed over output optimization</li></ul><p><strong>Example workflow:</strong></p><pre>1. Edit your Dart file → Save<br>2. Compiler recompiles changed parts (&lt; 1 second)<br>3. Browser updates automatically<br>4. See your changes instantly</pre><p>This is similar to Dart’s JIT (Just-In-Time) approach for native development — fast iteration is the priority. The generated JavaScript might be larger and less optimized, but that doesn’t matter during development. What matters is getting feedback quickly.</p><p><strong>When to use it:</strong> Every single time you’re actively developing and testing.</p><h3>2. Optimizing JavaScript Production Compiler: The Efficiency Expert</h3><p>When you’re ready to deploy, everything changes. Now you care about:</p><ul><li>Load time (how fast does the app start?)</li><li>File size (how much data needs to download?)</li><li>Runtime performance (how smooth is the user experience?)</li></ul><p>The <strong>optimizing JavaScript production compiler</strong> is built for this.</p><p><strong>What it does:</strong></p><p><strong>Dead-code elimination:</strong></p><pre>void unusedFunction() {<br>  print(&#39;This is never called&#39;);<br>}<br>void main() {<br>  print(&#39;Hello, world!&#39;);<br>}</pre><p>After compilation, unusedFunction() is completely removed. It never makes it to the final JavaScript bundle.</p><p><strong>Tree shaking:</strong></p><pre>import &#39;massive_library.dart&#39;;  // 100+ functions<br>void main() {<br>  doOneThing();  // Only uses one function<br>}</pre><p>Only doOneThing() and its dependencies are included in the output. The other 99+ functions? Gone.</p><p><strong>Minification:</strong></p><pre>// Before<br>function calculateUserDiscount(userName, userAge) {<br>  return userAge &gt; 65 ? 0.2 : 0.1;<br>}<br>// After<br>(u,a)=&gt;a&gt;65?.2:.1</pre><p>Variable names shortened, whitespace removed, code compressed.</p><p><strong>The result:</strong> A JavaScript bundle that’s often 50–70% smaller than the development version, with faster execution.</p><p><strong>When to use it:</strong> When deploying to production and you need broad browser support.</p><h3>3. Optimizing WebAssembly Compiler: The Performance Powerhouse</h3><p>WebAssembly (Wasm) is a game-changer for web performance. It’s a binary instruction format that runs at near-native speed — often 2–5x faster than equivalent JavaScript.</p><p>The <strong>WebAssembly compiler with WasmGC</strong> is Dart’s newest and most powerful option.</p><p><strong>What makes it special:</strong></p><p><strong>Binary format:</strong> Unlike JavaScript’s text-based format, WebAssembly is compiled to a compact binary. This means:</p><ul><li>Faster parsing</li><li>Smaller file sizes</li><li>More efficient execution</li></ul><p><strong>Near-native performance:</strong></p><pre>int fibonacci(int n) {<br>  if (n &lt;= 1) return n;<br>  return fibonacci(n - 1) + fibonacci(n - 2);<br>}</pre><p>Running fibonacci(40) in WebAssembly can be <strong>3-4x faster</strong> than in JavaScript.</p><p><strong>WasmGC (Garbage Collection):</strong> Traditionally, WebAssembly couldn’t handle garbage-collected languages well. WasmGC changes that — it’s a newer Wasm feature that allows efficient memory management, making it perfect for Dart.</p><p><strong>When to use it:</strong></p><ul><li>Games (need maximum FPS)</li><li>Data visualization (processing large datasets)</li><li>Scientific computing</li><li>Any compute-intensive web application</li></ul><p><strong>Trade-off:</strong> Requires modern browsers (Chrome 119+, Firefox 120+, Safari 17.4+)</p><h3>Real-World Example: Building a Flutter Web App</h3><p>Let’s walk through a typical development cycle.</p><h3>Phase 1: Development</h3><pre>flutter run -d chrome</pre><p>This uses the <strong>incremental JavaScript compiler</strong>. You’re coding, testing UI changes, fixing bugs. Every save triggers a quick recompilation and hot reload. You see your changes in under a second.</p><h3>Phase 2: Production Build (Standard)</h3><pre>flutter build web</pre><p>This uses the <strong>optimizing JavaScript compiler</strong>. The build takes longer (maybe 30–60 seconds), but you get:</p><ul><li>A main.dart.js file that&#39;s minified and optimized</li><li>Dead code eliminated</li><li>Tree-shaken dependencies</li><li>Ready to deploy to any web server</li></ul><p>Your users get a fast, efficient app that works on all browsers.</p><h3>Phase 3: Production Build (High Performance)</h3><pre>flutter build web --wasm</pre><p>This uses the <strong>WebAssembly compiler</strong>. The build takes about the same time as the JS build, but you get:</p><ul><li>A main.dart.wasm binary file</li><li>Maximum runtime performance</li><li>Smallest possible bundle size</li><li>Optimized for modern browsers</li></ul><p>Your users get the absolute best performance — perfect if your app does heavy computation or rendering.</p><h3>The Bigger Picture: Why Three Modes?</h3><p>You might wonder: “Why not just use WebAssembly everywhere?”</p><p>The answer is <strong>context matters</strong>.</p><p>During development, you don’t care about a 5MB bundle size. You care about seeing your change <em>right now</em>. The incremental JavaScript compiler gives you that.</p><p>For production, you need to balance performance, compatibility, and file size. JavaScript output works everywhere. WebAssembly gives you peak performance but requires modern browsers.</p><p>This is the same philosophy behind Dart’s native compilation (JIT for development, AOT for production). Dart gives you the right tool for each phase of development, rather than forcing one-size-fits-all.</p><h3>Dead-Code Elimination in Action</h3><p>Let me show you a concrete example of how powerful the production compiler’s optimization is.</p><p><strong>Your code:</strong></p><pre>class MathUtils {<br>  static int add(int a, int b) =&gt; a + b;<br>  static int subtract(int a, int b) =&gt; a - b;<br>  static int multiply(int a, int b) =&gt; a * b;<br>  static int divide(int a, int b) =&gt; a ~/ b;<br>}<br>class StringUtils {<br>  static String reverse(String s) =&gt; s.split(&#39;&#39;).reversed.join(&#39;&#39;);<br>  static String uppercase(String s) =&gt; s.toUpperCase();<br>}<br>void main() {<br>  print(MathUtils.add(5, 3));<br>}</pre><p><strong>Development compiler output</strong> (simplified):</p><pre>// Everything is included for flexibility<br>class MathUtils {<br>  static add(a, b) { return a + b; }<br>  static subtract(a, b) { return a - b; }<br>  static multiply(a, b) { return a * b; }<br>  static divide(a, b) { return Math.floor(a / b); }<br>}<br>class StringUtils {<br>  static reverse(s) { return s.split(&#39;&#39;).reverse().join(&#39;&#39;); }<br>  static uppercase(s) { return s.toUpperCase(); }<br>}<br>console.log(MathUtils.add(5, 3));</pre><p><strong>Production compiler output:</strong></p><pre>// Only what&#39;s actually used<br>console.log(8);</pre><p>The compiler:</p><ol><li>Noticed that only add() is called → removed all other functions</li><li>Noticed that add(5, 3) uses constants → computed the result at compile time</li><li>Noticed that no classes are needed anymore → removed them entirely</li><li>Inlined the result directly</li></ol><p>From dozens of lines to one. That’s the power of dead-code elimination.</p><h3>Choosing the Right Mode</h3><p>Here’s a simple decision tree:</p><p><strong>Are you actively developing?</strong> → Use incremental JavaScript compiler (it’s automatic with flutter run)</p><p><strong>Are you deploying to production?</strong> → Ask: Do you need maximum compatibility?</p><ul><li>Yes → Use JavaScript compiler (flutter build web)</li><li>No, and performance is critical → Use Wasm compiler (flutter build web --wasm)</li></ul><p><strong>Special cases:</strong></p><ul><li>Building a game? → Consider Wasm</li><li>Building a data dashboard? → Consider Wasm</li><li>Building a simple website? → JavaScript is fine</li><li>Need to support older browsers? → Stick with JavaScript</li></ul><h3>The Future: WebAssembly is Growing</h3><p>WebAssembly support is expanding rapidly. More browsers are adopting WasmGC, and the performance gap between Wasm and JavaScript continues to widen for compute-intensive tasks.</p><p>Dart’s early investment in WebAssembly compilation means Flutter web apps can take advantage of these improvements immediately. As browser support improves, expect to see Wasm become the default production target.</p><h3>Key Takeaways</h3><ol><li><strong>Dart provides three web compilation modes</strong>, each optimized for different scenarios</li><li><strong>Development mode</strong> prioritizes fast iteration with incremental compilation and hot reload</li><li><strong>Production JavaScript</strong> delivers optimized, compact code that works everywhere</li><li><strong>Production WebAssembly</strong> provides maximum performance for modern browsers</li><li><strong>The right mode depends on context</strong> — development vs. production, compatibility vs. performance</li></ol><p>This multi-compiler approach is what makes Dart powerful for web development. You’re not stuck with one compilation strategy — you get the best tool for each phase of your development cycle.</p><p>Whether you’re rapidly prototyping with hot reload, deploying a production app with optimized JavaScript, or pushing performance boundaries with WebAssembly, Dart has you covered.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=195c4e94d096" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Medallion Architecture in Microsoft Fabric: A Complete Guide]]></title>
            <link>https://sarthakgupta0401.medium.com/medallion-architecture-in-microsoft-fabric-a-complete-guide-022187e563ff?source=rss-7267b495b5c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/022187e563ff</guid>
            <dc:creator><![CDATA[Sarthak Gupta]]></dc:creator>
            <pubDate>Sat, 20 Dec 2025 02:32:19 GMT</pubDate>
            <atom:updated>2025-12-20T02:32:19.581Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the world of modern data engineering, organizing and managing data efficiently is paramount. The Medallion Architecture has emerged as a gold standard (pun intended!) for structuring data in lakehouses, and Microsoft Fabric has embraced this pattern wholeheartedly. In this article, we’ll explore what Medallion Architecture is, why it matters, and how to implement it in Microsoft Fabric.</p><h3>What is Medallion Architecture?</h3><p>Medallion Architecture is a data design pattern that organizes data into three progressive layers: Bronze, Silver, and Gold. Think of it as a refinement process where raw ore (data) is progressively processed into pure gold (analytics-ready insights).</p><pre>Raw Data Sources → Bronze → Silver → Gold → Business Intelligence<br>    (Extract)      (Load)   (Transform) (Aggregate)  (Consume)</pre><p>This architecture provides a clear, structured path for data as it flows from raw ingestion to business consumption.</p><h3>The Three Layers Explained</h3><h3>🥉 Bronze Layer: The Raw Truth</h3><p>The Bronze layer is your data landing zone. Here, data arrives in its raw, unprocessed form directly from source systems.</p><p><strong>Characteristics:</strong></p><ul><li>Raw, immutable data</li><li>Minimal to no transformations</li><li>Full historical records</li><li>Preserves original format and structure</li><li>Audit trail and data lineage</li></ul><p><strong>Example Use Cases:</strong></p><ul><li>IoT sensor data streams</li><li>Application logs</li><li>Database change data capture (CDC)</li><li>API responses</li></ul><p><strong>Sample PySpark Code for Bronze Layer:</strong></p><pre>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import current_timestamp, input_file_name<br><br># Read raw JSON files into Bronze layer<br>df_bronze = (spark.read<br>    .format(&quot;json&quot;)<br>    .option(&quot;inferSchema&quot;, &quot;true&quot;)<br>    .load(&quot;Files/raw/sales/*.json&quot;)<br>    .withColumn(&quot;ingestion_timestamp&quot;, current_timestamp())<br>    .withColumn(&quot;source_file&quot;, input_file_name())<br>)<br># Write to Bronze Delta table<br>(df_bronze.write<br>    .format(&quot;delta&quot;)<br>    .mode(&quot;append&quot;)<br>    .option(&quot;mergeSchema&quot;, &quot;true&quot;)<br>    .save(&quot;Tables/bronze_sales&quot;)<br>)</pre><h3>🥈 Silver Layer: The Refined Truth</h3><p>The Silver layer is where data cleaning and standardization happen. This is your “single source of truth.”</p><p><strong>Characteristics:</strong></p><ul><li>Cleansed and validated data</li><li>Standardized schemas</li><li>Deduplication applied</li><li>Data quality rules enforced</li><li>Type conversions and parsing</li><li>Still fairly granular</li></ul><p><strong>Transformations Applied:</strong></p><ul><li>Remove duplicates</li><li>Handle null values</li><li>Standardize date formats</li><li>Apply business rules</li><li>Validate data types</li></ul><p><strong>Sample PySpark Code for Silver Layer:</strong></p><pre>from pyspark.sql.functions import col, to_date, trim, upper<br>from delta.tables import DeltaTable<br><br># Read from Bronze<br>df_silver = spark.read.format(&quot;delta&quot;).load(&quot;Tables/bronze_sales&quot;)<br># Apply transformations<br>df_silver_cleaned = (df_silver<br>    .dropDuplicates([&quot;transaction_id&quot;])<br>    .filter(col(&quot;amount&quot;).isNotNull())<br>    .filter(col(&quot;amount&quot;) &gt; 0)<br>    .withColumn(&quot;transaction_date&quot;, to_date(col(&quot;transaction_date&quot;), &quot;yyyy-MM-dd&quot;))<br>    .withColumn(&quot;customer_name&quot;, trim(upper(col(&quot;customer_name&quot;))))<br>    .withColumn(&quot;processed_timestamp&quot;, current_timestamp())<br>)<br># Merge into Silver Delta table (SCD Type 1)<br>silver_table = DeltaTable.forPath(spark, &quot;Tables/silver_sales&quot;)<br>(silver_table.alias(&quot;target&quot;)<br>    .merge(<br>        df_silver_cleaned.alias(&quot;source&quot;),<br>        &quot;target.transaction_id = source.transaction_id&quot;<br>    )<br>    .whenMatchedUpdateAll()<br>    .whenNotMatchedInsertAll()<br>    .execute()<br>)</pre><h3>🥇 Gold Layer: The Business Truth</h3><p>The Gold layer contains highly refined, aggregated, and business-ready data optimized for analytics and reporting.</p><p><strong>Characteristics:</strong></p><ul><li>Business-level aggregations</li><li>Denormalized for query performance</li><li>Domain-specific data marts</li><li>Optimized for BI tools</li><li>Feature engineering for ML</li></ul><p><strong>Example Datasets:</strong></p><ul><li>Monthly revenue by region</li><li>Customer 360 views</li><li>Product performance metrics</li><li>KPI dashboards</li></ul><p><strong>Sample PySpark Code for Gold Layer:</strong></p><pre>from pyspark.sql.functions import sum, count, avg, date_trunc<br><br># Read from Silver<br>df_gold_source = spark.read.format(&quot;delta&quot;).load(&quot;Tables/silver_sales&quot;)<br># Create aggregated Gold table - Monthly Sales Summary<br>df_gold_monthly = (df_gold_source<br>    .withColumn(&quot;month&quot;, date_trunc(&quot;month&quot;, col(&quot;transaction_date&quot;)))<br>    .groupBy(&quot;month&quot;, &quot;region&quot;, &quot;product_category&quot;)<br>    .agg(<br>        sum(&quot;amount&quot;).alias(&quot;total_revenue&quot;),<br>        count(&quot;transaction_id&quot;).alias(&quot;transaction_count&quot;),<br>        avg(&quot;amount&quot;).alias(&quot;avg_transaction_value&quot;)<br>    )<br>    .withColumn(&quot;created_timestamp&quot;, current_timestamp())<br>)<br># Write to Gold Delta table<br>(df_gold_monthly.write<br>    .format(&quot;delta&quot;)<br>    .mode(&quot;overwrite&quot;)<br>    .option(&quot;overwriteSchema&quot;, &quot;true&quot;)<br>    .save(&quot;Tables/gold_monthly_sales_summary&quot;)<br>)</pre><h3>Architecture Diagram</h3><pre>┌─────────────────────────────────────────────────────────────────┐<br>│                        DATA SOURCES                              │<br>│  [APIs] [Databases] [Files] [Streaming] [SaaS Apps]            │<br>└────────────────────────┬────────────────────────────────────────┘<br>                         │<br>                         ▼<br>         ┌───────────────────────────────────┐<br>         │     BRONZE LAYER (Raw)            │<br>         │  • Raw data ingestion             │<br>         │  • Original format preserved      │<br>         │  • Full history                   │<br>         │  • Audit trail                    │<br>         └───────────────┬───────────────────┘<br>                         │<br>                         │ Cleaning &amp; Validation<br>                         ▼<br>         ┌───────────────────────────────────┐<br>         │     SILVER LAYER (Refined)        │<br>         │  • Data cleansing                 │<br>         │  • Standardization                │<br>         │  • Deduplication                  │<br>         │  • Quality checks                 │<br>         └───────────────┬───────────────────┘<br>                         │<br>                         │ Aggregation &amp; Enrichment<br>                         ▼<br>         ┌───────────────────────────────────┐<br>         │     GOLD LAYER (Curated)          │<br>         │  • Business aggregates            │<br>         │  • Analytics-ready                │<br>         │  • Domain-specific marts          │<br>         │  • Optimized for consumption      │<br>         └───────────────┬───────────────────┘<br>                         │<br>                         ▼<br>         ┌───────────────────────────────────┐<br>         │        CONSUMPTION LAYER          │<br>         │  [Power BI] [Excel] [ML Models]   │<br>         │  [Apps] [APIs] [Reports]          │<br>         └───────────────────────────────────┘</pre><h3>Key Benefits</h3><p><strong>1. Incremental Processing</strong> Process only new or changed data, reducing compute costs and improving performance.</p><p><strong>2. Data Quality &amp; Governance</strong> Each layer has clear data quality standards, making it easier to track and fix issues.</p><p><strong>3. Flexibility</strong> Multiple teams can consume data at different refinement levels based on their needs.</p><p><strong>4. Performance Optimization</strong> Each layer is optimized for its specific purpose — raw storage, processing, or analytics.</p><p><strong>5. Clear Data Lineage</strong> Easy to trace data from source to consumption, crucial for compliance and debugging.</p><h3>Implementing in Microsoft Fabric</h3><p>Microsoft Fabric provides native support for Medallion Architecture through:</p><h3>OneLake</h3><ul><li>Centralized data lake storage</li><li>Delta Lake format by default</li><li>Automatic optimization</li></ul><h3>Data Factory</h3><ul><li>Data pipelines for ingestion</li><li>Dataflows for transformations</li><li>Copy activities for Bronze layer</li></ul><h3>Synapse Data Engineering</h3><ul><li>Notebooks for transformations</li><li>Spark pools for processing</li><li>SQL for querying</li></ul><h3>Example Fabric Notebook Cell:</h3><pre># Fabric Notebook - Bronze to Silver Pipeline<br><br>from notebookutils import mssparkutils<br># Set storage paths<br>bronze_path = &quot;abfss://workspace@onelake.dfs.fabric.microsoft.com/lakehouse/Tables/bronze_sales&quot;<br>silver_path = &quot;abfss://workspace@onelake.dfs.fabric.microsoft.com/lakehouse/Tables/silver_sales&quot;<br># Read Bronze with schema evolution<br>df = spark.read.format(&quot;delta&quot;).option(&quot;mergeSchema&quot;, &quot;true&quot;).load(bronze_path)<br># Apply Silver transformations<br>from pyspark.sql.functions import *<br>df_silver = (df<br>    .filter(col(&quot;_rescued_data&quot;).isNull())  # Remove corrupted records<br>    .drop(&quot;_rescued_data&quot;)<br>    .dropDuplicates()<br>    .withColumn(&quot;processed_date&quot;, current_date())<br>)<br># Write to Silver<br>df_silver.write.format(&quot;delta&quot;).mode(&quot;overwrite&quot;).save(silver_path)<br># Optimize Delta table<br>spark.sql(f&quot;OPTIMIZE delta.`{silver_path}`&quot;)</pre><h3>Best Practices</h3><p><strong>1. Use Delta Lake Format</strong> Delta provides ACID transactions, time travel, and schema evolution — essential for production pipelines.</p><p><strong>2. Implement Incremental Loading</strong> Use watermarks and checkpoints to process only new data:</p><pre># Incremental load using watermark<br>last_processed = spark.sql(<br>    &quot;SELECT MAX(ingestion_timestamp) FROM silver_sales&quot;<br>).collect()[0][0]<br>df_incremental = (spark.read.format(&quot;delta&quot;)<br>    .load(&quot;Tables/bronze_sales&quot;)<br>    .filter(col(&quot;ingestion_timestamp&quot;) &gt; last_processed)<br>)</pre><p><strong>3. Partition Strategically</strong> Partition tables by date or frequently filtered columns:</p><pre>df.write.format(&quot;delta&quot;).partitionBy(&quot;year&quot;, &quot;month&quot;).save(path)</pre><p><strong>4. Document Data Lineage</strong> Add metadata columns to track data flow:</p><pre>.withColumn(&quot;source_system&quot;, lit(&quot;SAP&quot;))<br>.withColumn(&quot;pipeline_run_id&quot;, lit(pipeline_run_id))<br>.withColumn(&quot;processed_by&quot;, lit(&quot;silver_transformation_v2&quot;))</pre><p><strong>5. Implement Data Quality Checks</strong> Add validation at each layer:</p><pre>from pyspark.sql.functions import col<br># Quality checks<br>quality_checks = {<br>    &quot;null_check&quot;: df.filter(col(&quot;customer_id&quot;).isNull()).count() == 0,<br>    &quot;duplicate_check&quot;: df.count() == df.dropDuplicates([&quot;order_id&quot;]).count(),<br>    &quot;range_check&quot;: df.filter(col(&quot;amount&quot;) &lt; 0).count() == 0<br>}<br>if not all(quality_checks.values()):<br>    raise ValueError(f&quot;Quality checks failed: {quality_checks}&quot;)</pre><h3>Common Patterns</h3><h3>Pattern 1: Slowly Changing Dimensions (SCD Type 2)</h3><pre>from delta.tables import DeltaTable<br>from pyspark.sql.functions import col, current_timestamp, lit<br># SCD Type 2 implementation<br>silver_table = DeltaTable.forPath(spark, &quot;Tables/silver_customers&quot;)<br>updates = (df_new<br>    .withColumn(&quot;effective_date&quot;, current_timestamp())<br>    .withColumn(&quot;end_date&quot;, lit(None).cast(&quot;timestamp&quot;))<br>    .withColumn(&quot;is_current&quot;, lit(True))<br>)<br>(silver_table.alias(&quot;target&quot;)<br>    .merge(updates.alias(&quot;source&quot;), &quot;target.customer_id = source.customer_id AND target.is_current = true&quot;)<br>    .whenMatchedUpdate(<br>        condition=&quot;target.customer_name != source.customer_name OR target.email != source.email&quot;,<br>        set={<br>            &quot;is_current&quot;: &quot;false&quot;,<br>            &quot;end_date&quot;: &quot;source.effective_date&quot;<br>        }<br>    )<br>    .whenNotMatchedInsertAll()<br>    .execute()<br>)</pre><h3>Pattern 2: Event Streaming to Medallion</h3><pre># Bronze - Stream ingestion<br>stream_df = (spark.readStream<br>    .format(&quot;cloudFiles&quot;)<br>    .option(&quot;cloudFiles.format&quot;, &quot;json&quot;)<br>    .option(&quot;cloudFiles.schemaLocation&quot;, checkpoint_path)<br>    .load(raw_path)<br>)<br>(stream_df.writeStream<br>    .format(&quot;delta&quot;)<br>    .option(&quot;checkpointLocation&quot;, checkpoint_path)<br>    .trigger(processingTime=&quot;5 minutes&quot;)<br>    .start(bronze_path)<br>)<br># Silver - Stream transformation<br>bronze_stream = spark.readStream.format(&quot;delta&quot;).load(bronze_path)<br>silver_stream = bronze_stream.filter(col(&quot;status&quot;) == &quot;valid&quot;)<br>(silver_stream.writeStream<br>    .format(&quot;delta&quot;)<br>    .option(&quot;checkpointLocation&quot;, silver_checkpoint)<br>    .trigger(processingTime=&quot;10 minutes&quot;)<br>    .start(silver_path)<br>)</pre><h3>Monitoring and Maintenance</h3><p>Track pipeline health with built-in Fabric monitoring:</p><pre># Log pipeline metrics<br>metrics = {<br>    &quot;records_processed&quot;: df.count(),<br>    &quot;processing_time&quot;: processing_time,<br>    &quot;data_quality_score&quot;: quality_score<br>}<br>mssparkutils.notebook.exit(metrics)</pre><h3>Conclusion</h3><p>The Medallion Architecture provides a robust, scalable framework for organizing data in Microsoft Fabric. By implementing Bronze, Silver, and Gold layers, you create a clear data journey from raw ingestion to business insights. This pattern not only improves data quality and governance but also makes your data platform more maintainable and cost-effective.</p><p>Whether you’re building a new lakehouse or modernizing an existing data warehouse, the Medallion Architecture in Microsoft Fabric gives you the structure and tools needed to succeed in today’s data-driven world.</p><h3>Additional Resources</h3><ul><li><a href="https://learn.microsoft.com/fabric/">Microsoft Fabric Documentation</a></li><li><a href="https://docs.delta.io/latest/best-practices.html">Delta Lake Best Practices</a></li><li><a href="https://learn.microsoft.com/fabric/data-engineering/lakehouse-overview">Lakehouse Architecture Guide</a></li></ul><p><em>Have you implemented Medallion Architecture in your organization? Share your experiences and challenges in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=022187e563ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>