<?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 Vesa Alexandru on Medium]]></title>
        <description><![CDATA[Stories by Vesa Alexandru on Medium]]></description>
        <link>https://medium.com/@vesaalexandru95?source=rss-a0286b59c498------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8wbCh4p7lKu2Bxk5jgx6lQ.jpeg</url>
            <title>Stories by Vesa Alexandru on Medium</title>
            <link>https://medium.com/@vesaalexandru95?source=rss-a0286b59c498------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:03:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vesaalexandru95/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[Unicorn and Rainbows : The reality of implement AI in corporate]]></title>
            <link>https://medium.com/marvelous-mlops/unicorn-and-rainbows-the-reality-of-implement-ai-in-corporate-022665db18fb?source=rss-a0286b59c498------2</link>
            <guid isPermaLink="false">https://medium.com/p/022665db18fb</guid>
            <category><![CDATA[enterprise]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Vesa Alexandru]]></dc:creator>
            <pubDate>Wed, 05 Feb 2025 13:23:00 GMT</pubDate>
            <atom:updated>2025-02-05T13:23:48.265Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unicorns and Rainbows: The Reality of Implementing AI in a Corporate</h3><h4>The AI Bubble: Hype, herd mentality, and harsh realities</h4><p><strong>Unicorns and Rainbows. </strong>Is it a metaphor? Is it a reality? Maybe both. Think of an unicorn dancing on top of a radiant rainbow. But, in fact, what does it mean?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*QxE9SdX4skAenhvoC-VV-A.jpeg" /><figcaption>Image generated by AI</figcaption></figure><p>Humanity has always been drawn to <strong>utopia</strong> — a perfect, idealized future where all problems are solved. Believing that the world is steadily marching toward this vision is tempting. In the AI landscape, the unicorn (you have noticed the <strong>5th leg</strong>, right?) represents the elevated promises, wild imagination, and relentless hype that paint a picture of transformative, almost magical technology.</p><p>The rainbow, however, represents the real world: entire potential but riddled with imperfections, inconsistencies, and systemic barriers.</p><p>Just like the stock market, AI has its declines and flows. Everything might seem to skyrocket, but a slight shift — technical debt, regulatory burdens, or enterprise realities — can send it crashing back to earth. The question is not whether AI is a transformative force (there is no doubt it is!) but whether we’re being realistic about its trajectory.</p><p>This article will discuss the reality of using AI in the enterprise environment, address technical debt, bridge knowledge gaps, and understand the herd effect that fuels the AI bubble. We aim to offer a realistic roadmap for businesses navigating the complex AI landscape by critically analyzing these factors.</p><h3><strong>1. The AI bubble</strong></h3><p>We have been in Data &amp; AI for over 10 years. The AI bubble has never been so big. We have AI everywhere on our laptops, phones, and websites. The CEOs of Nvidia, Microsoft, Meta, and OpenAI are spreading a lot of news about revolutionary AI technology, how AI agents will replace humans, how we will reach AGI soon, and how we will have AI everywhere. We live in an AI bubble, and even though the technology is accurate, it is nontrivial to apply it to actual use cases and drive business value than advertised.</p><p>The technological advancements in the AI field are significant, and the value AI generates is real. However, there are still many gaps that people who try to build AI products see clearly. Two factors contribute to the AI bubble: knowledge and the herd effect. Somehow, they are tangential but different.</p><h3><strong>2. The Role of Knowledge Gaps</strong></h3><p>The gap between AI insiders and the general public is one of the hinds of the AI bubble. The saying “Knowledge is power” remains valid for AI within its development and implementation context.</p><p>People who are deeply invested in the development of AI are fully aware of the nuances, challenges, and limitations that come with the implementation of AI-based solutions.</p><p>On the other hand, AI outsiders are constantly awe-struck by the marketing terms associated with AI which presents an entirely different world of possibilities. This knowledge gap enables misconceptions to spread at an alarming rate, therefore making the hype of AI take precedence over the reality of what AI systems can offer.</p><h3><strong>3. Herd Effect: Fear of Missing Out (FOMO)</strong></h3><p>Another significant factor driving the AI hype is the herd effect or the Fear of Missing Out (FOMO).</p><p>As more companies invest in AI and tout their successes, others feel compelled to follow suit, fearing they’ll fall behind if they don’t adopt AI technologies. This rush often leads to deploying AI solutions without a thorough understanding of their applicability or potential ROI, further inflating the AI bubble. The result is a market saturated with AI buzzwords and solutions that may not deliver the promised transformative impact.</p><p>AI models (under AI models, we understand foundation models) are used everywhere, where a standard ML model should be used instead. This adds complexity and decreases reliability.</p><h3><strong>4. Back to basics</strong></h3><p>Most companies can not reliably bring standard machine learning models to production and lack monitoring practices.</p><p>Despite what many people think, workflows that include AI models are, on average, more complex to bring into production and monitor — even if you take the simplest scenario without RAG or finetuning involved — just call a 3rd party API.</p><p>In too many cases, we seem to have forgotten the basic principles of machine learning and blindly rely on what that API outputs. This is the danger of AI hype: AI has become accessible to everyone, and many software engineers treat it as just another API call.</p><p>What could go wrong? The data model has not changed, the code has not changed (and neither has the environment where it gets executed), and the version of the API has not changed. But this is the beauty of machine learning: even if everything in your control has not changed, the model can start performing poorly unexpectedly because data distribution has changed.</p><p>This does not just happen with standard machine learning models, it also happens with AI models — we just have less means to impact that behavior, and prompt finetuning becomes an essential part of the process.</p><h3>5. <strong>Real-world, 2025</strong></h3><p>Experts say that 2025 will be the year of AI agents. <strong>But is it really true?</strong></p><p>While the AI hype machine continues to boom, real-world adoption tells a different story. The promise of autonomous AI agents seamlessly operating across enterprises remains largely aspirational. The reality? AI in enterprise is still a work in progress — complex, expensive, and often misaligned with actual business needs.</p><p>Take <strong>BBVA</strong>, the Spanish bank that <a href="https://www.wsj.com/articles/six-months-thousands-of-gpts-and-some-big-unknowns-inside-openais-deal-with-bbva-5d6f1c03?utm_source=chatgpt.com">went all in</a> on OpenAI’s technology. They deployed over 2,900 AI models to enhance productivity, yet integrating them into their existing systems turned out to be a logistical nightmare. AI doesn’t operate in a vacuum; it needs to connect with legacy infrastructure, existing workflows, and strict regulatory requirements. And that’s where reality bites — scaling AI across an enterprise is exponentially harder than rolling out a chatbot.</p><p>The UK government’s attempt to integrate AI into its welfare system <a href="https://www.theguardian.com/technology/2025/jan/27/ai-prototypes-uk-welfare-system-dropped?utm_source=chatgpt.com">faced significant limitations</a>. At least six AI prototypes, designed to enhance staff training, improve job center services, and streamline disability benefit processing, were discontinued due to issues in scalability, reliability, and insufficient testing. Officials acknowledged several “frustrations and false starts,” highlighting the complexities involved in deploying AI within public services.</p><p><a href="https://www.architectureandgovernance.com/artificial-intelligence/new-research-uncovers-top-challenges-in-enterprise-ai-agent-adoption/?utm_source=chatgpt.com">A study </a>highlighted several obstacles in developing and deploying AI agents within enterprises. Security concerns were identified as a top challenge by leadership (53%) and practitioners (62%). Other significant challenges included data governance, performance issues, and integration complexity. These findings underscore the multifaceted difficulties organizations face in implementing AI agents effectively.</p><p>Reflecting on these examples, it’s evident that the widespread adoption of AI agents in enterprise settings faces significant limitations. While 2025 may usher in extensive research, proofs of concept (POCs), and minimum viable products (MVPs), the path to full-scale integration remains complex.</p><h3>6. AI in a corporate environment</h3><p>Big companies operate under strict rules, structured workflows, and a constant focus on ROI. Unlike agile startups that can adapt on the fly, large organizations have to deal with complex approval processes, compliance checks, and risk management. All this makes adopting AI a slower process, and the idea of rapid transformation often feels more like a distant dream than something achievable.</p><p>Chip Huyen references the most common LLM applications in her AI engineering book. Enterprises are risk-averse and prefer to deploy internal-facing applications first. From what we have seen so far, even though there is initial support from the leadership to deploy such applications, not enough funding goes to those projects (and unlikely will) as they do not generate direct business value. We are not saying there is no value — there is, but it is challenging to convince stakeholders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jIaxdz6Nk6vfrREFcdd41A.jpeg" /><figcaption>Image reinterpreted from <strong>Huyen, C.</strong> (2025). <em>AI Engineering: Building Applications with Foundation Models</em>. <a href="https://www.amazon.com/AI-Engineering-Building-Applications-Foundation/dp/1098166302">Available on Amazon</a></figcaption></figure><p>In enterprises, the most common use cases with direct business generation are related to customer service (forwarding customers to the right agents/ processes) and reviewing contracts. These use cases have been there for a while, and have historically been NLP-heavy, and AI models helped to improve these projects.</p><p>Some companies have tried to use LLMs for recommendations and chatbots, and the world has seen enough failures. Here are some examples:</p><p><strong>DPD’s customer-facing</strong> chatbot, “Ruby,” was designed to assist customers with their inquiries. However, due to insufficient safeguards, a user was able to provoke the bot into swearing and composing a poem criticizing the company itself. <a href="https://www.cxtoday.com/conversational-ai/dpds-genai-chatbot-swears-and-writes-a-poem-about-how-awful-it-is/">This incident</a> underscores the importance of implementing strict content moderation protocols and regularly updating AI systems to prevent such occurrences.</p><p>Similarly, Pak’nSave’s AI meal planner app, intended to provide innovative recipe suggestions, <a href="https://www.theguardian.com/world/2023/aug/10/pak-n-save-savey-meal-bot-ai-app-malfunction-recipes?utm_source=chatgpt.com">malfunctioned</a> and recommended a combination of ingredients that would produce chlorine gas, labeling it as an “aromatic water mix.” This highlights the critical need for rigorous testing and validation of AI outputs, especially in applications directly impacting consumer health and safety.</p><p>It feels like not everyone has learned from it, and we regularly see companies launching AI applications without clear business value with poor guardrails, mainly for “marketing purposes”. Let’s hope it will not turn out to be bad marketing, as users will try to make the app do things it is not supposed to do “just for fun”.</p><p>There are exceptions. Some companies created nice LLM-powered recommendations, for example, Zalando. It has well-implemented guardrails and is useful for the customers (it helps to find items that are otherwise hard to find via search). In October 2024, <a href="https://corporate.zalando.com/en/newsroom/en/stories/zalando-expands-ai-powered-shopping-assistant-25-markets">Zalando expanded its AI-powered assistant to all 25 markets</a>, supporting local languages. This expansion aims to provide customers with personalized fashion advice and insights into emerging local trends, thereby enhancing the shopping experience.</p><h3>7. Areas of attention &amp; conclusions</h3><p>There is great potential to leverage AI in a corporate setting. However, to hope for enterprise adoption, we must consider <strong>security gaps, controlled environments, transparency and traceability</strong>, and a way to monitor and evaluate AI systems.</p><p>In enterprise ecosystems, AI systems need large volumes of data, including personal and proprietary information. Their role is to enhance workflows and boost efficiency, but they need access to critical systems, which can be considered a security risk. Organizations must focus on preventing unapproved access to data, breaches, and compliance issues.</p><p>Threat actors can deploy malware that mimics AI behavior to breach networks, skew decisions, or steal secrets. AI agents act autonomously, making them harder to detect and control. This creates a major challenge: real-time oversight of AI systems.</p><p>Monitoring is a persistent issue. Few companies have proper systems in place, and AI’s complexity makes it even harder. Owners must fully understand every decision their AI makes</p><p>AI’s transformative potential is undeniable, but the path from hype to reality is complex and challenging. Rather than chasing unicorns and rainbows, organizations must take a grounded, strategic approach — one that prioritizes real business needs, robust security frameworks, and a deep understanding of AI’s limitations. The road ahead is uncertain, but one thing is clear: the way we answer these questions will determine whether AI becomes a lasting force for good or just another passing bubble.</p><p><strong>What do you think — are we ready?</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=022665db18fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/marvelous-mlops/unicorn-and-rainbows-the-reality-of-implement-ai-in-corporate-022665db18fb">Unicorn and Rainbows : The reality of implement AI in corporate</a> was originally published in <a href="https://medium.com/marvelous-mlops">Marvelous MLOps</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building AI systems is fun.]]></title>
            <link>https://medium.com/ml-vanguards/building-ai-systems-is-fun-c5029518ed0c?source=rss-a0286b59c498------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5029518ed0c</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Vesa Alexandru]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 19:18:39 GMT</pubDate>
            <atom:updated>2024-12-23T19:18:39.917Z</atom:updated>
            <content:encoded><![CDATA[<h4>Running to AI or running from AI</h4><h4><strong>Why do so many AI projects feel like déjà vu?</strong></h4><p>You start with bold ambitions, tackle a proof of concept, and… it stalls. Again.</p><p>At <a href="https://mlvanguards.substack.com/"><strong>ML Vanguards</strong></a>, we know this story all too well. It’s the cycle we’ve broken countless times in our work at <a href="https://www.cube-digital.io/"><strong>Cube Digital</strong></a>.</p><p>The truth? Building production-grade AI isn’t about chasing buzzwords — it’s about combining <strong>engineering knowledge</strong> with <strong>practical AI </strong>to deliver <strong>systems</strong> that actually work, scale, and drive real-world impact.</p><pre>                           [ START ]<br>                               |<br>                               v<br>                   +-----------------------+<br>                   | Surviving in the High-|<br>                   |   Velocity AI Era      |<br>                   +-----------------------+<br>                           |<br>                           v<br>                  ┌────────────────────────┐<br>                  │ 1. Slow Down to Go Fast │<br>                  └────────────────────────┘<br>                           |<br>                           |-- (a) Create “No-Noise” Slots<br>                           |       - What/Why/How<br>                           |<br>                           |-- (b) Plan Your Learning in Sprints<br>                           |       - What/Why/How<br>                           |<br>                           |-- (c) Leverage Structured Breaks<br>                           |       - What/Why/How<br>                           |<br>                           └-- (d) Measure Real Progress<br>                                   - What/Why/How<br>                           |<br>                           v<br>                  ┌────────────────────────┐<br>                  │ 2. Return to Foundations│<br>                  └────────────────────────┘<br>                           |<br>                           |-- (a) Start with Classical ML<br>                           |       - Why it matters / Practical steps<br>                           |<br>                           |-- (b) Explore Early NLP<br>                           |       - Why it matters / Practical steps<br>                           |<br>                           |-- (c) Demystify CNNs for CV<br>                           |       - Why it matters / Practical steps<br>                           |<br>                           |-- (d) Deep Learning Building Blocks<br>                           |       - Why it matters / Practical steps<br>                           |<br>                           |-- (e) Foundations of Generative AI<br>                           |       - Why it matters / Practical steps<br>                           |<br>                           └-- (f) Measure Real Progress<br>                                   - Why / How<br>                           |<br>                           v<br>                  ┌────────────────────────┐<br>                  │ 3. Real AI vs Buzzwords │<br>                  └────────────────────────┘<br>                           |<br>                           |-- (a) Focus on Underlying Mechanisms<br>                           |-- (b) Look for Evidence of Impact<br>                           |-- (c) Cut Through the Noise<br>                           |-- (d) Beware Personal Branding Traps<br>                           └-- (e) Ask the Right Questions<br>                               - (Long-standing bottleneck?)<br>                               - (Significant performance boost?)<br>                               - (Credible voices in community?)<br>                           |<br>                           v<br>                   +-----------------------+<br>                   |   Genuine AI Mastery   |<br>                   |  (Calm, Focused, &amp;     |<br>                   |  Truly Understands     |<br>                   |   the Tech)           |<br>                   +-----------------------+</pre><p>This year has been nothing short of insane.</p><p>The field of artificial intelligence is on hyperdrive, and it often feels like we’re trapped in a relentless sprint to keep pace.</p><p>I’ve tried to follow all the trends, starting with ChatGPT and moving on to Vector Databases, Retrieval-Augmented Generation (RAG), Advanced RAG, Hybrid RAG, Knowledge Graphs, and self-hosted LLMs.</p><p>And these are just the highlights. Every week seems to bring another breakthrough, another “must-learn” tool, or another “game-changer.”</p><p><strong>If you blink, you miss it. Do you feel it?</strong></p><h3>When development speed is too high, discipline alone is not enough.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/0*Hn1zsYAMC-RRPSyH.png" /><figcaption><strong>Godspeed</strong></figcaption></figure><p>In such an environment, <strong>discipline alone is not enough</strong>. I’ve been passionate about AI since I was 18, and over the last 11 years, I’ve accumulated a wealth of research, proof-of-concepts, products, failures, and experiments.</p><p>Yet, today, I constantly question my ability to keep up. I doubt my own skills, my own knowledge base, and even my own motivations. It’s not that I lack dedication or curiosity — I’m more committed to AI than ever — but the sheer velocity of new developments is overwhelming.</p><p><strong>So, what can we do when the AI ecosystem evolves like Flash with Godspeed?</strong></p><h3>1. Slow down to go fast</h3><p>It’s tempting to chase every new model architecture, technique, and research paper.</p><p>But there comes a point when consuming more information makes us less effective. We burn out, get confused, or feel stuck.</p><p><strong>Sometimes, we must slow down to go fast: pick one or two core domains that </strong>resonate with us and dig deep. Mastering a smaller subset deeply is often more impactful than skimming everything superficially.</p><p><strong>Create “No-Noise” Slots</strong></p><ul><li><strong>What:</strong> Set aside dedicated blocks of time (could be an hour or two each day or week) with no distractions — no Slack, no emails, no social media.</li><li><strong>Why:</strong> You’ll be amazed at how much deep work you can accomplish when you’re not constantly interrupted.</li><li><strong>How:</strong> Mute notifications. Put your phone in another room or on “Do Not Disturb.” Clearly communicate to colleagues or family that you’re unavailable during these slots.</li></ul><p><strong>Plan your learning in sprints</strong></p><ul><li><strong>What:</strong> Instead of randomly consuming AI content, organize your learning into small, time-bound “sprints” (e.g., two-week blocks focusing on one topic: ChatGPT, Vector Databases, or RAG).</li><li><strong>Why:</strong> Sprints help you go deeper on one subject, avoid context switching, and reduce the anxiety of feeling behind on every new release.</li><li><strong>How:</strong> Pick a topic, define goals (e.g., “By the end of this sprint, I want to build a proof-of-concept with Vector Databases”), and stick to them. Don’t chase other shiny AI topics during that sprint.</li></ul><p><strong>Leverage structured breaks and downtime</strong></p><ul><li><strong>What:</strong> Build short, regular breaks into your routine — coffee breaks, walks, or any activity that helps your brain rest.</li><li><strong>Why:</strong> Mental downtime allows your subconscious to process your learning, sparking new insights and creativity.</li><li><strong>How:</strong> Use the Pomodoro Technique (25 minutes work + 5 minutes break) or schedule non-negotiable downtime. Pausing when you’re behind might seem counterintuitive, but it will make you more productive in the long run.</li></ul><p><strong>Measure real progress (Not just busywork)</strong></p><ul><li><strong>What:</strong> Define clear metrics for “success” in your AI journey: maybe finishing a mini-project, publishing a blog post, or implementing a particular model in a real-world environment.</li><li><strong>Why:</strong> Feeling like you’re always behind often comes from vague goals. When your targets are specific, you can see real progress — even if it’s incremental.</li><li><strong>How:</strong> Write down your goals in a trackable format (a spreadsheet, a project management tool, or a notebook). Evaluate your progress weekly or monthly rather than daily.</li></ul><p><strong>Books that really helped me with this:</strong></p><ol><li><strong>Deep Work</strong> by Cal Newport</li><li><strong>Atomic Habits</strong> by James Clear</li><li><strong>Getting Things Done</strong> by David Allen</li></ol><p><em>By deliberately slowing down — creating focused “no-noise” slots, planning learning in sprints, and implementing structured breaks — you’ll make more significant strides in AI than if you constantly chase every new update. Instead of constantly feeling outpaced, you’ll see measurable growth and gain a clearer sense of direction.</em></p><h3>2. Return to foundations</h3><p>I come from the era of running backpropagation algorithms in MATLAB and building OpenCV from source because a simple pip install was not yet feasible. I gladly spent my Christmas holidays on Andrew Ng’s original Machine Learning Foundations course and writing prototypes in TensorFlow 1 — where we had to define computational graphs explicitly.</p><p>Being “forced” to understand everything under the hood gave me a deep appreciation for how machine learning pipelines actually work—and this foundation continues to be my anchor even now, when new models and techniques are coming at us at lightning speed.</p><p>At the time, learning how gradient descent works, debugging backpropagation, or training a deep learning algorithm from scratch seemed difficult and absurd.</p><p><strong>But now, all these concepts represent my anchor in this noisy field.</strong></p><p>Below are some <strong>concrete steps</strong> to help you reconnect with (or build up) these same fundamentals so you can better navigate the current wave of AI innovations:</p><h4>Start with classical ML</h4><p><strong>Why it matters. </strong>Classical algorithms like linear regression, logistic regression, SVMs, and decision trees are often dismissed as “old-school,” but they’re the bedrock foundation.</p><p>Understanding how these models optimize parameters, handle data bias/variance, and manage feature spaces lays the groundwork for more complex architectures later.</p><p><strong>Practical steps:</strong></p><ol><li><strong>Re-implement a basic classifier:</strong> Try coding a logistic regression or SVM from scratch (even if you use a library for the math).</li><li><strong>Experiment with real data:</strong> Download a small dataset (e.g., from the UCI Machine Learning Repository) and test your own classifier.</li><li><strong>Focus on interpretability:</strong> Classical methods are more interpretable than deep networks. Understanding <em>why</em> a model predicts what it does helps you think more critically about black-box models later.</li></ol><h4>Explore early NLP</h4><p><strong>Why it matters. </strong>We often jump straight to large language models (LLMs) like GPT-4 or ChatGPT. However, foundational NLP methods — like Bag-of-Words, TF-IDF, and classical sequence models — illustrate the core principles of text representation and language understanding.</p><p><strong>Practical steps:</strong></p><ol><li><strong>Build a simple text classifier:</strong> Use Naive Bayes or logistic regression on a text corpus to see how tokenization and feature extraction matter.</li><li><strong>Play with word embeddings (the older ones):</strong> GloVe and word2vec might feel “dated,” but they remain critical to understanding how neural embeddings represent language.</li><li><strong>Compare before and after:</strong> Train a classical model, then swap in a modern transformer-based approach (e.g., BERT). Observing the differences clarifies how far NLP has come — and <em>why</em>.</li></ol><h4>Demystify CNNs for computer vision</h4><p><strong>Why it matters. </strong>Convolutional Neural Networks revolutionized image recognition, but the underlying principles — convolutions, feature hierarchies, pooling — are not magical. They’re meticulously engineered methods for extracting visual features.</p><p><strong>Practical steps:</strong></p><ol><li><strong>Manual Convolution:</strong> Write a function that performs 2D convolution on an image matrix. Seeing how filters “slide” over pixels cements your grasp of feature extraction.</li><li><strong>Replicate a Classic Network:</strong> Implement or recreate a historical CNN (like LeNet-5) to understand the design choices.</li><li><strong>Visualize Filters:</strong> Tools like TensorBoard or custom scripts can show you what each filter “sees,” deepening your understanding of <em>why</em> CNNs work.</li></ol><h4>Deep Learning building blocks</h4><p><strong>Why it matters. </strong>Most modern AI systems — be it image classification, speech recognition, or text generation — run on deep learning frameworks. But whether you’re dealing with a GPT or a CNN, the building blocks (layers, activations, optimizers, backpropagation) remain constant.</p><p><strong>Practical steps:</strong></p><ol><li><strong>Implement a mini network from scratch:</strong> Use only NumPy or raw tensors. This forces you to handle forward passes, backpropagation, and gradient updates yourself.</li><li><strong>Understand optimization:</strong> Familiarize yourself with gradient descent, SGD, and advanced optimizers like Adam or RMSProp. Know <em>why</em> they converge and what hyperparameters matter.</li><li><strong>Track loss curves and metrics:</strong> Regularly plot your training/validation loss. Observing how models overfit, underfit, or converge too slowly builds intuition for larger projects.</li></ol><h4>Foundations of Generative AI</h4><p><strong>Why it matters. </strong>Generative models — like GANs, VAEs, and large language models — might seem like a giant leap away from classical ML. Yet they, too, revolve around core principles: data distribution modeling, latent spaces, and optimization.</p><p><strong>Practical steps:</strong></p><ol><li><strong>Try a simple GAN:</strong> Implement a tiny GAN on MNIST or CIFAR-10 to see how a generator and discriminator “compete.” Understanding adversarial training is key to mastering generative AI.</li><li><strong>Explore language modeling:</strong> Even a small LSTM trained on text reveals why next-token prediction is the backbone of large language models.</li><li><strong>Experiment with loss functions:</strong> MSE vs. cross-entropy vs. KL divergence. Each has a different interpretation and dramatically affects model behavior.</li></ol><h4>Learn properly from the get-go</h4><p>It’s tempting to chase every new model in a field this dynamic. But do you really <em>understand</em> it if you can’t connect it to foundational principles? Here’s how to stay grounded:</p><ul><li><strong>Set tangible milestones:</strong> Instead of saying, “I’ll learn GPT this week,” define a goal like “Implement a sentiment analysis system using a BERT-like model — and compare it to logistic regression.”</li><li><strong>Keep a learning journal:</strong> Document your experiments, successes, and failures. This log becomes your personal library of insights.</li><li><strong>Validate with side projects:</strong> Before jumping to the next big thing, confirm that you truly understand the current one by solving a small, real-world problem.</li></ul><h4>Why foundations are your superpower</h4><p>From a simple regression to GPT-like language models, the leap is not as giant as it appears when you zoom in on <em>why</em> each piece of the puzzle works.</p><p>That fundamental knowledge is what keeps you agile in a domain that changes faster than most of us can keep up with. Rather than feeling swept away by the endless wave of new AI tools, you’ll have the clarity and confidence to pivot, adapt, and innovate — no matter what comes next.</p><p>You&#39;re not being left behind when you invest in the “boring” details — like how gradients flow or word embeddings capture semantic meaning.</p><p>You’re gearing up with the intellectual toolkit necessary to spot new opportunities, tackle challenges creatively, and build AI solutions that endure beyond the latest hype cycle.</p><h3>3. Real AI vs buzzwords</h3><p>Every week, it feels like there’s a new Large Language Model (LLM) hitting the scene, fresh research on vector databases, or yet another “game-changing” AI agent. Online chatter and social media amplify this buzz, and soon enough, you’re bombarded with hot takes about how this or that technology is the ultimate AI revolution. It’s no wonder we feel overwhelmed.</p><p>But here’s the truth: <strong>If you grasp the core principles behind LLMs (tokenization, attention, training objectives), vector-based retrieval (similarity search, embeddings), or other AI components, each new release is just an incremental update on what you already know.</strong></p><p>Of course, incremental updates can be exciting, but they’re rarely the radical leaps that the hype machine claims.</p><p>Meanwhile, we’re also living in an era of intense <strong><em>personal branding</em>.</strong></p><p>It’s common to see individuals who’ve read a handful of articles spinning entire narratives on the “next big thing” and launching startups that seem indistinguishable from one another.</p><p><strong>This sea of repetition can make it even harder to spot real innovation.</strong></p><h4>Hype vs. Reality: How to stay grounded</h4><p><strong>Focus on the underlying mechanisms.</strong></p><ul><li><strong>Why it matters:</strong> Whether you’re dealing with a new GPT variant or the latest vector database, the fundamentals — like embeddings, attention mechanisms, and approximate nearest neighbor searches — tend to remain the same.</li><li><strong>How to do it:</strong> Ask yourself: “What problem does this new approach claim to solve? What are its architectural differences? Is it genuinely novel, or just a repackaging of existing methods?”</li></ul><p><strong>Look for evidence of actual impact.</strong></p><ul><li><strong>Why it matters:</strong> Genuine AI solutions solve real problems in industry or research. They’re not just blog posts with inflated promises.</li><li><strong>How to do it:</strong> Check if there’s a working demo, open-source code, or reproducible benchmarks. If a “revolutionary” method refuses to show tangible results or publish details, treat the hype with caution.</li></ul><p><strong>Cut through the noise.</strong></p><ul><li><strong>Why it matters:</strong> Many “new” tools are variations on old themes. With so many nearly identical solutions flooding the market, it’s easy to feel every new release is a must-know.</li><li><strong>How to do it:</strong> Rely on your foundations. If you understand how embeddings or generative models work, you can quickly dissect whether a new product or paper truly stands out — or simply rebrands standard techniques.</li></ul><p><strong>Beware of the personal branding traps.</strong></p><ul><li><strong>Why it matters:</strong> Social media thrives on hot takes and surface-level excitement. Self-declared “experts” may amplify trivial improvements to bolster their own brand.</li><li><strong>How to do it:</strong> Diversify your sources. Follow reputable researchers, read peer-reviewed work, and learn from people who are actively building or researching AI — not just marketing it.</li></ul><p><strong>Ask the right questions. </strong>Critical thinking saves you from chasing every buzzword-laden release.</p><p>When confronted with something “new,” ask:</p><ul><li>Does it solve a long-standing bottleneck?</li><li>Is the performance boost significant or marginal?</li><li>Are there credible voices in the community corroborating its value?</li></ul><h3>Conclusion</h3><p>AI can feel like a high-speed train that never stops. But as we’ve seen, the real key to thriving in this environment is focusing on the fundamentals, pacing yourself for deep learning rather than superficial skimming, and cutting through the relentless buzz.</p><p>“Slowing down to go fast” and returning to foundational ML concepts might feel counterintuitive when you’re bombarded with “the next big thing” every week.</p><p>Yet, this steady, grounded approach will ultimately help you build solutions that matter — and stay ahead of those who chase hype but lack depth.</p><p>Have you <strong>enjoyed</strong> this <strong>article</strong>? Then…</p><p>If you’re ready to adopt a more practical, sustainable approach to AI — combining real-world engineering principles with effective AI strategies — subscribe to <a href="https://mlvanguards.substack.com/"><strong>ML Vanguards</strong></a> and join our community.</p><p>We’re dedicated to sharing hands-on guidance, battle-tested workflows, and insights that cut through the noise so you can build AI systems that endure.</p><p>↓↓↓</p><p><a href="https://mlvanguards.substack.com/embed">ML Vanguards | Cube Digital | Substack</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5029518ed0c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ml-vanguards/building-ai-systems-is-fun-c5029518ed0c">Building AI systems is fun.</a> was originally published in <a href="https://medium.com/ml-vanguards">Hyperplane</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Role of Feature Stores in Fine-Tuning LLMs]]></title>
            <link>https://medium.com/@vesaalexandru95/the-role-of-feature-stores-in-fine-tuning-llms-22bd60afd4b9?source=rss-a0286b59c498------2</link>
            <guid isPermaLink="false">https://medium.com/p/22bd60afd4b9</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[feature-store]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai]]></category>
            <dc:creator><![CDATA[Vesa Alexandru]]></dc:creator>
            <pubDate>Sat, 11 May 2024 07:25:34 GMT</pubDate>
            <atom:updated>2024-08-20T11:39:22.158Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://medium.com/decodingml/llm-twin-course/home">LLM TWIN COURSE: BUILDING YOUR PRODUCTION-READY AI REPLICA</a></h4><h4>From raw data to instruction dataset</h4><p><em>→ the 6nd out of 12 lessons of </em><a href="https://medium.com/decodingml/llm-twin-course/home"><strong><em>the LLM Twin</em></strong></a><em> free course</em></p><p><strong>What is your LLM Twin?</strong> It is an AI character that writes like yourself by incorporating your style, personality and voice into an LLM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*CwuA4bMWf9aZYZaJ.png" /><figcaption>Image by DALL-E</figcaption></figure><h3>Why is this course different?</h3><p><em>By finishing the “</em><a href="https://medium.com/decodingml/llm-twin-course/home"><strong><em>LLM Twin: Building Your Production-Ready AI Replica</em></strong></a><strong><em>”</em> </strong><em>free course, you will learn how to design, train, and deploy a production-ready LLM twin of yourself powered by LLMs, vector DBs, and LLMOps good practices</em>.</p><blockquote><strong><em>Why should you care? 🫵</em></strong></blockquote><blockquote><strong>→ No more isolated scripts or Notebooks!</strong> Learn production ML by building and deploying an end-to-end production-grade LLM system.</blockquote><h3>What will you learn to build by the end of this course?</h3><p>You will <strong>learn</strong> how to <strong>architect </strong>and<strong> build a real-world LLM system</strong> from <strong>start</strong> to <strong>finish</strong> — from <strong>data collection</strong> to <strong>deployment</strong>.</p><p>You will also <strong>learn</strong> to <strong>leverage MLOps best practices</strong>, such as experiment trackers, model registries, prompt monitoring, and versioning.</p><p><strong>The end goal?</strong> Build and deploy your own LLM twin.</p><p><strong>What is an LLM Twin?</strong> It is an AI character that learns to write like somebody by incorporating its style and personality into an LLM.</p><p><em>The </em><strong><em>architecture</em></strong><em> of the </em><strong><em>LLM twin</em></strong><em> is split into </em><strong><em>4 Python microservices</em></strong><em>:</em></p><ol><li><strong><em>the data collection pipeline:</em></strong> crawl your digital data from various social media platforms. Clean, normalize and load the data to a NoSQL DB through a series of ETL pipelines. Send database changes to a queue using the CDC pattern. (deployed on AWS)</li><li><strong><em>the feature pipeline:</em></strong> consume messages from a queue through a Bytewax streaming pipeline. Every message will be cleaned, chunked, embedded (using Superlinked), and loaded into a Qdrant vector DB in real-time. (deployed on AWS)</li><li><strong><em>the training pipeline:</em></strong><em> </em>create a custom dataset based on your digital data.<em> </em>Fine-tune an LLM using QLoRA. Use Comet ML’s experiment tracker to monitor the experiments. Evaluate and save the best model to Comet’s model registry. (deployed on Qwak)</li><li><strong><em>the inference pipeline:</em></strong> load and quantize the fine-tuned LLM from Comet’s model registry. Deploy it as a REST API. Enhance the prompts using RAG. Generate content using your LLM twin. Monitor the LLM using Comet’s prompt monitoring dashboard (deployed on Qwak)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RiQfAzK0sh-lJZtebBeuMA.png" /><figcaption>LLM twin system architecture [Image by the Author]</figcaption></figure><p>Along the 4 microservices, you will learn to integrate 3 serverless tools:</p><ul><li><a href="https://www.comet.com/signup/?utm_source=decoding_ml&amp;utm_medium=partner&amp;utm_content=medium">Comet ML </a>as your ML Platform;</li><li><a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">Qdrant</a> as your vector DB;</li><li><a href="https://www.qwak.com/lp/end-to-end-mlops/?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=decodingml">Qwak</a> as your ML infrastructure;</li></ul><h3>Who is this for?</h3><p><strong>Audience:</strong> MLE, DE, DS, or SWE who want to learn to engineer production-ready LLM systems using LLMOps sound principles.</p><p><strong>Level: </strong>intermediate</p><p><strong>Prerequisites:</strong> basic knowledge of Python, ML, and the cloud</p><h3>How will you learn?</h3><p><em>The course</em> contains <strong>10 hands-on written lessons</strong> and the <strong>open-source code</strong> you can <a href="https://github.com/decodingml/llm-twin-course"><em>access on GitHub</em></a>, <em>showing how to build an end-to-end LLM system.</em></p><p>Also, it includes <strong>2 bonus lessons</strong> on how to <strong>improve</strong> the <strong>RAG system</strong>.</p><p>You can read everything at your own pace.</p><p><em>→ To get the most out of this course, we encourage you to clone and run the repository while you cover the lessons.</em></p><h3>Costs?</h3><p>The <strong>articles</strong> and <strong>code</strong> are <strong>completely free</strong>. They will always remain free.</p><p>But if you plan to run the code while reading it, you must know that we use several cloud tools that might generate additional costs.</p><p>The cloud computing platforms (<a href="https://aws.amazon.com/">AWS</a>, <a href="https://www.qwak.com/lp/end-to-end-mlops/?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=decodingml">Qwak</a>) have a pay-as-you-go pricing plan. Qwak offers a few hours of free computing. Thus, we did our best to keep costs to a minimum.</p><p>For the other serverless tools (<a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">Qdrant</a>, <a href="https://www.comet.com/signup/?utm_source=decoding_ml&amp;utm_medium=partner&amp;utm_content=medium">Comet</a>), we will stick to their freemium version, which is free of charge.</p><h3>Meet your teachers!</h3><p>The course is created under the <a href="https://medium.com/decodingml">Decoding ML</a> umbrella by:</p><ul><li><a href="https://www.linkedin.com/in/pauliusztin/">Paul Iusztin</a> | Senior ML &amp; MLOps Engineer</li><li><a href="https://www.linkedin.com/in/vesaalexandru/">Alex Vesa</a> | Senior AI Engineer</li><li><a href="https://www.linkedin.com/in/arazvant/">Alex Razvant</a> | Senior ML &amp; MLOps Engineer</li></ul><blockquote><em>🔗 </em><strong><em>Check out</em></strong><em> </em><a href="https://github.com/decodingml/llm-twin-course"><em>the code on GitHub</em></a><em> [1] and support us with a ⭐️</em></blockquote><h3>Lessons</h3><p>→ <a href="https://medium.com/decodingml/the-llm-twin-free-course-on-production-ready-rag-pipelines-c96472f4e8c8">Quick overview</a> of <strong>each lesson</strong> of the LLM Twin free course.</p><p><em>The course is split into 12 lessons. Every Medium article will be its own lesson:</em></p><ol><li><a href="https://medium.com/decodingml/an-end-to-end-framework-for-production-ready-llm-systems-by-building-your-llm-twin-2cc6bb01141f">An End-to-End Framework for Production-Ready LLM Systems by Building Your LLM Twin</a></li><li><a href="https://medium.com/decodingml/the-importance-of-data-pipelines-in-the-era-of-generative-ai-673e1505a861">The Importance of Data Pipelines in the Era of Generative AI</a></li><li><a href="https://medium.com/decodingml/the-3nd-out-of-11-lessons-of-the-llm-twin-free-course-ba82752dad5a">Change Data Capture: Enabling Event-Driven Architectures</a></li><li><a href="https://medium.com/decodingml/sota-python-streaming-pipelines-for-fine-tuning-llms-and-rag-in-real-time-82eb07795b87">SOTA Python Streaming Pipelines for Fine-tuning LLMs and RAG — in Real-Time!</a></li><li><a href="https://medium.com/decodingml/the-4-advanced-rag-algorithms-you-must-know-to-implement-5d0c7f1199d2">The 4 Advanced RAG Algorithms You Must Know to Implement</a></li><li><strong>The Role of Feature Stores in Fine-Tuning LLMs</strong></li><li><a href="https://medium.com/decodingml/how-to-fine-tune-llms-on-custom-datasets-at-scale-using-qwak-and-cometml-12216a777c34?source=your_stories_page-------------------------------------">How to fine-tune LLMs on custom datasets at Scale using Qwak and CometML</a></li><li><a href="https://medium.com/decodingml/best-practices-when-evaluating-fine-tuned-llms-47f02f5164c2">Best Practices When Evaluating Fine-Tuned LLMs</a></li><li><a href="https://medium.com/decodingml/architect-scalable-and-cost-effective-llm-rag-inference-pipelines-73b94ef82a99">Architect scalable and cost-effective LLM &amp; RAG inference pipelines</a></li><li><a href="https://medium.com/decodingml/how-to-evaluate-your-rag-using-ragas-framework-18d2325453ae">How to evaluate your RAG pipeline using the RAGAs Framework</a></li><li><a href="https://medium.com/decodingml/build-a-scalable-rag-ingestion-pipeline-using-74-3-less-code-ac50095100d6">[Bonus] Build a scalable RAG ingestion pipeline using 74.3% less code</a></li><li><a href="https://medium.com/decodingml/build-multi-index-advanced-rag-apps-bd33d2f0ec5c">[Bonus] Build Multi-Index Advanced RAG Apps</a></li></ol><blockquote><strong>To</strong> <strong>better understand </strong>the <strong>course’s goal, technical details, </strong>and <strong>system design </strong>→ <a href="https://medium.com/decodingml/an-end-to-end-framework-for-production-ready-llm-systems-by-building-your-llm-twin-2cc6bb01141f"><em>Check out Lesson 1</em></a></blockquote><p><strong>Let’s start</strong> with <strong>Lesson 6 </strong>↓↓↓</p><h3>Lesson 6: Prepare Finetuning Dataset</h3><p>Large language models (LLMs) have changed how we interact with machines. These powerful models have a remarkable understanding of human language, enabling them to translate text, write different kinds of creative content formats, and answer your questions in an informative way.</p><p>But how do we take these LLMs and make them even better?</p><p>The answer lies in <strong>fine-tuning.</strong></p><p><strong>Fine-tuning</strong> is the process of taking a pre-trained LLM and adapting it to a specific task or domain.</p><p>One important aspect of fine-tuning is <strong>dataset preparation.</strong></p><p>Remember the quote from 2018: “garbage in, garbage out.”</p><p><strong>The quality of your dataset</strong> directly impacts how well your fine-tuned model will perform.</p><h4>Why Data Matters?</h4><p>Let’s explore why a well-prepared, high-quality dataset is essential for successful LLM fine-tuning:</p><ul><li><strong>Specificity is Key:</strong> LLMs like Mistral are trained on massive amounts of general text data. This gives them a broad understanding of language, but it doesn’t always align with the specific task you want the model to perform. A carefully curated dataset helps the model understand the nuances of your domain, vocabulary, and the types of outputs you expect.</li><li><strong>Contextual Learning:</strong> High-quality datasets offer rich context that the LLM can use to learn patterns and relationships between words within your domain. This context enables the model to generate more relevant and accurate responses for your specific application.</li><li><strong>Avoiding Bias:</strong> Unbalanced or poorly curated datasets can introduce biases into the LLM, impacting its performance and leading to unfair or undesirable results. A well-prepared dataset helps to mitigate these risks.</li></ul><p>Today, we will learn how to generate a custom dataset for our specific task: content generation.</p><h4>Understanding the Data Types</h4><p>Our data consists of two primary types: posts and articles. Each type serves a different purpose and is structured to accommodate specific needs:</p><ul><li><strong>Posts</strong>: Typically shorter and more dynamic, posts are often user-generated content from social platforms or forums. They are characterized by varied formats and informal language, capturing real-time user interactions and opinions.</li><li><strong>Articles</strong>: These are more structured and content-rich, usually sourced from news outlets or blogs. Articles provide in-depth analysis or reporting and are formatted to include headings, subheadings, and multiple paragraphs, offering comprehensive information on specific topics.</li><li><strong>Code</strong>: Sourced from repositories like GitHub, this data type encompasses scripts and programming snippets crucial for LLMs to learn and understand technical language</li></ul><p>Both data types require careful handling during insertion to preserve their integrity and ensure they are stored correctly for further processing and analysis in MongoDB. This includes managing formatting issues and ensuring data consistency across the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gufpoEo92ZtuGQlVx6HVTw.png" /><figcaption>Finetuning Dataset Generation Process [Image by the Author]</figcaption></figure><h3>Table of Contents</h3><ol><li>System Design and Data Flow</li><li>Insert Data into MongoDB</li><li>Qdrant VectorDB — storing cleaned data</li><li>Generate Finetuning Dataset</li><li><a href="https://www.comet.com/signup/?utm_source=decoding_ml&amp;utm_medium=partner&amp;utm_content=medium">CometML</a> — data versioning</li></ol><blockquote>🔗 <strong>Check out</strong> <a href="https://github.com/decodingml/llm-twin-course">the code on GitHub</a> [1] and support us with a ⭐️</blockquote><h3>1. System Design and Data Flow</h3><p>In a real-world application, data is not manually inserted into MongoDB but flows through a well-structured Data Collection Pipeline. This section explains how the data is integrated into the system.</p><p><a href="https://medium.com/decodingml/the-importance-of-data-pipelines-in-the-era-of-generative-ai-673e1505a861">In Lesson 2 of LLM Twin Course we explained the importance of data pipelines in an AI project:</a></p><ul><li><strong>Data Collection</strong>: Initially, data is automatically collected from various sources such as social media platforms, news feeds, and other digital channels. This automated process ensures a continuous stream of fresh data that feeds into the pipeline.</li></ul><p><a href="https://medium.com/decodingml/sota-python-streaming-pipelines-for-fine-tuning-llms-and-rag-in-real-time-82eb07795b87">In Lesson 4 of LLM Twin Course we learnt how to build a real time feature pipeline which:</a></p><ul><li>leverage Change Data Capture (CDC)</li><li>consume data from a RabbitMQ queue</li><li>use a <a href="https://www.linkedin.com/company/bytewax/">Bytewax</a> streaming engine to process data streams used for fine-tuning LLMs &amp; RAG</li><li>load fine-tuning &amp; RAG data to a <a href="https://www.linkedin.com/company/qdrant/">Qdrant</a> vector DB</li></ul><p>We also emphasize the importance of having a feature store like Qdrant, in a production environment:</p><ul><li><strong>Data Cleaning</strong>: Once collected, the data undergoes a cleaning process to remove inconsistencies, correct formatting issues, and prepare it for storage. This step is crucial to ensure that the data stored in MongoDB is of high quality and ready for analysis.</li><li><strong>Role of Qdrant</strong>: In the broader system architecture, <a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">Qdrant</a> acts as a feature store. After the data is stored in MongoDB, it is further processed and the relevant features are extracted and stored in <a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">Qdrant</a>. This makes the data readily accessible for machine learning models and other analytical tasks, enhancing the system’s efficiency.</li></ul><h4>Test this module</h4><ul><li><strong>Manual Insertion for Testing</strong>: For the purposes of this lesson, we manually insert data into MongoDB to simulate how cleaned data is stored. This step helps us understand and test the dataset creation process in a controlled environment.</li><li><strong>Manual Retrieval from Qdrant</strong>: When testing or developing features, data can be manually retrieved from <a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">Qdrant</a>. This step involves querying the feature store to fetch specific feature vectors, which allows you to use them in specific tasks like finetuning.</li></ul><h3>2. Insert Data into MongoDB</h3><p>Before starting any logic on generating a finetuning dataset for our LLM Twin, we need data in MongoDB.</p><p>You can quickly populate your MongoDB by running the following Make commands:</p><pre>make local-test-github<br># OR<br>make local-test-medium</pre><p>You can always change the link inside the <a href="https://github.com/decodingml/llm-twin-course/blob/main/Makefile">Makefile</a> to crawl different links.</p><h3>3. Qdrant VectorDB — storing &amp; retrieving cleaned data</h3><p>To fully understand the data flow, please review the other two lessons that detail our use of the CDC pattern and <a href="https://bytewax.io/?utm_source=medium&amp;utm_medium=decodingml&amp;utm_campaign=2024_q1">Bytewax</a> pipelines:</p><p><a href="https://medium.com/decodingml/the-3nd-out-of-11-lessons-of-the-llm-twin-free-course-ba82752dad5a">Change Data Capture: Enabling Event-Driven Architectures</a></p><p>The output of the Bytewax pipelines is sent to <a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">Qdrant</a> VectorDB:</p><p><a href="https://medium.com/decodingml/sota-python-streaming-pipelines-for-fine-tuning-llms-and-rag-in-real-time-82eb07795b87">SOTA Python Streaming Pipelines for Fine-tuning LLMs and RAG — in Real-Time!</a></p><p><a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">Qdrant</a> can be utilized via its Docker implementation or through its <a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">managed cloud service</a>. This flexibility allows you to choose an environment that best suits your project’s needs.</p><h3>Environment Variables</h3><p>To configure your environment for Qdrant, set the following variables:</p><h3>Docker Variables</h3><ul><li>QDRANT_HOST: The hostname or IP address where your Qdrant server is running.</li><li>QDRANT_PORT: The port on which Qdrant listens, typically 6333 for Docker setups.</li></ul><h3>Qdrant Cloud Variables</h3><ul><li>QDRANT_CLOUD_URL: The URL for accessing Qdrant Cloud services.</li><li>QDRANT_APIKEY: The API key for authenticating with Qdrant Cloud.</li></ul><p><a href="https://qdrant.tech/documentation/cloud/quickstart-cloud/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course"><em>Please check this article to learn how to obtain these variables:</em></a></p><p>Additionally, you can control the connection mode (Cloud or Docker) using a setting in your configuration file. More details can be found in <a href="https://github.com/decodingml/llm-twin-course/blob/main/3-feature-pipeline/db.py">db.py</a><strong> </strong>:</p><pre>USE_QDRANT_CLOUD: True  # Set to False to use Docker setup</pre><p>If the data pipeline succeeded, you should see in Qdrant cloud 3 collections: cleaned_articles, cleaned_posts, cleaned_repositories</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4yXI5o6jI6tKD0jOY6Uw-Q.jpeg" /><figcaption>Qdrant collections screenshot [Image by the author]</figcaption></figure><h4>Retrieve Cleaned Data</h4><p>Once you have a cleaned dataset, the next step is to utilize it effectively. Qdrant serves as a robust feature store, where data specifically prepared for machine learning applications is stored. In our case, this data is used for finetuning tasks.</p><h4>Importance of a Feature Store</h4><p>A feature store plays a critical role in machine learning workflows by:</p><ul><li><strong>Centralizing Data Management</strong>: It centralizes feature data, making it accessible and reusable across multiple machine learning models and projects.</li><li><strong>Ensuring Consistency</strong>: Consistent feature calculation ensures that the same data preprocessing steps are applied in both training and prediction phases, reducing errors.</li><li><strong>Improving Efficiency</strong>: By storing pre-computed features, it significantly speeds up the experimentation process, allowing for rapid testing of different models.</li><li><strong>Scaling with Ease</strong>: As projects grow, a feature store can manage scaling of data operations efficiently, supporting larger datasets and more complex feature engineering tasks.</li></ul><p>By leveraging a feature store like <a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">Qdrant</a>, teams can enhance the reproducibility and scalability of their machine learning projects.</p><p>We will use the client from the <a href="https://github.com/decodingml/llm-twin-course/blob/main/3-feature-pipeline/db.py"><em>db.py</em></a><em> </em>file:</p><pre>from qdrant_client import QdrantClient<br>from qdrant_client.http.exceptions import UnexpectedResponse<br>from qdrant_client.http.models import Batch, Distance, VectorParams<br><br>import logger_utils<br>from settings import settings<br><br>logger = logger_utils.get_logger(__name__)<br><br><br>class QdrantDatabaseConnector:<br>    _instance: QdrantClient = None<br><br>    def __init__(self):<br>        if self._instance is None:<br>            try:<br>                if settings.USE_QDRANT_CLOUD:<br>                    self._instance = QdrantClient(<br>                        url=settings.QDRANT_CLOUD_URL,<br>                        api_key=settings.QDRANT_APIKEY,<br>                    )<br>                else:<br>                    self._instance = QdrantClient(<br>                        host=settings.QDRANT_DATABASE_HOST,<br>                        port=settings.QDRANT_DATABASE_PORT,<br>                    )<br><br>            except UnexpectedResponse:<br>                logger.exception(<br>                    &quot;Couldn&#39;t connect to the database.&quot;,<br>                    host=settings.QDRANT_DATABASE_HOST,<br>                    port=settings.QDRANT_DATABASE_PORT,<br>                )<br><br>                raise<br><br>    def get_collection(self, collection_name: str):<br>        return self._instance.get_collection(collection_name=collection_name)<br><br>    def create_non_vector_collection(self, collection_name: str):<br>        self._instance.create_collection(collection_name=collection_name, vectors_config={})<br><br>    def create_vector_collection(self, collection_name: str):<br>        self._instance.create_collection(<br>            collection_name=collection_name,<br>            vectors_config=VectorParams(size=settings.EMBEDDING_SIZE, distance=Distance.COSINE),<br>        )<br><br>    def write_data(self, collection_name: str, points: Batch):<br>        try:<br>            self._instance.upsert(collection_name=collection_name, points=points)<br>        except Exception:<br>            logger.exception(&quot;An error occurred while inserting data.&quot;)<br><br>            raise<br><br>    def scroll(self, collection_name: str, limit: int):<br>        return self._instance.scroll(collection_name=collection_name, limit=limit)<br><br>    def close(self):<br>        if self._instance:<br>            self._instance.close()<br><br>            logger.info(&quot;Connected to database has been closed.&quot;)<br><br><br>connection = QdrantDatabaseConnector()</pre><p>To easily fetch data from a <a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">Qdrant</a> database, you can utilize the Python function fetch_all_cleaned_content. This function demonstrates how to efficiently retrieve a list of cleaned content from a specified collection:</p><pre>from db.qdrant import connection as client<br>    <br>def fetch_all_cleaned_content(self, collection_name: str) -&gt; list:<br>        all_cleaned_contents = []<br><br>        scroll_response = client.scroll(collection_name=collection_name, limit=10000)<br>        points = scroll_response[0]<br><br>        for point in points:<br>            cleaned_content = point.payload[&quot;cleaned_content&quot;]<br>            if cleaned_content:<br>                all_cleaned_contents.append(cleaned_content)<br><br>        return all_cleaned_contents</pre><ol><li><strong>Initialize the Scroll</strong>: Start by scrolling through the database using the scroll method, which can fetch large amounts of data. Specify the collection name and set a limit to manage data volume effectively.</li><li><strong>Access Points</strong>: Retrieve points from the initial scroll response. Each point contains payloads where the actual data is stored.</li><li><strong>Extract Data</strong>: Loop through the points to extract the cleaned_content from each payload. This content is checked for existence before being added to the results list.</li><li><strong>Return Results</strong>: The function returns a list containing all the cleaned content extracted from the database, making the process straightforward and manageable.</li></ol><h3><strong>4. </strong>Generate Finetuning Dataset</h3><ul><li><strong>The Challenge:</strong> Manually creating a dataset for fine-tuning a language model like Mistral-7B can be time-consuming and prone to errors.</li><li><strong>The Solution: Instruction Datasets</strong> Instruction datasets offer an efficient way to guide a language model toward a specific task like news classification.</li><li><strong>Methods:</strong> While instruction datasets can be built manually or derived from existing sources, we’ll leverage a powerful LLM like OpenAI’s GPT 3.5-turbo due to our time and budget constraints.</li></ul><h4><strong>Using Qdrant Data to Craft Instructions</strong></h4><p>Let’s analyze the sample data point from Qdrant to demonstrate how we can derive instructions for generating our instruction dataset:</p><p>Data Point:</p><pre>{<br>  &quot;author_id&quot;: &quot;2&quot;,<br>  &quot;cleaned_content&quot;: &quot;Do you want to learn to build hands-on LLM systems using good LLMOps practices? A new Medium series is coming up for the Hands-on LLMs course\n.\nBy finishing the Hands-On LLMs free course, you will learn how to use the 3-pipeline architecture &amp; LLMOps good practices to design, build, and deploy a real-time financial advisor powered by LLMs &amp; vector DBs.\nWe will primarily focus on the engineering &amp; MLOps aspects.\nThus, by the end of this series, you will know how to build &amp; deploy a real ML system, not some isolated code in Notebooks.\nThere are 3 components you will learn to build during the course:\n- a real-time streaming pipeline\n- a fine-tuning pipeline\n- an inference pipeline\n.\nWe have already released the code and video lessons of the Hands-on LLM course.\nBut we are excited to announce an 8-lesson Medium series that will dive deep into the code and explain everything step-by-step.\nWe have already released the first lesson of the series  \nThe LLMs kit: Build a production-ready real-time financial advisor system using streaming pipelines, RAG, and LLMOps:  \n[URL]\n  In Lesson 1, you will learn how to design a financial assistant using the 3-pipeline architecture (also known as the FTI architecture), powered by:\n- LLMs\n- vector DBs\n- a streaming engine\n- LLMOps\n.\n  The rest of the articles will be released by the end of January 2024.\nFollow us on Medium&#39;s Decoding ML publication to get notified when we publish the other lessons:  \n[URL]\nhashtag\n#\nmachinelearning\nhashtag\n#\nmlops\nhashtag\n#\ndatascience&quot;,<br>  &quot;platform&quot;: &quot;linkedin&quot;,<br>  &quot;type&quot;: &quot;posts&quot;<br>},<br>{<br>  &quot;author_id&quot;: &quot;2&quot;,<br>  &quot;cleaned_content&quot;: &quot;RAG systems are far from perfect   This free course teaches you how to improve your RAG system.\nI recently finished the Advanced Retrieval for AI with Chroma free course from\nDeepLearning.AI\nIf you are into RAG, I find it among the most valuable learning sources.\nThe course already assumes you know what RAG is.\nIts primary focus is to show you all the current issues of RAG and why it is far from perfect.\nAfterward, it shows you the latest SoTA techniques to improve your RAG system, such as:\n- query expansion\n- cross-encoder re-ranking\n- embedding adaptors\nI am not affiliated with\nDeepLearning.AI\n(I wouldn&#39;t mind though).\nThis is a great course you should take if you are into RAG systems.\nThe good news is that it is free and takes only 1 hour.\nCheck it out  \n  Advanced Retrieval for AI with Chroma:\n[URL]\nhashtag\n#\nmachinelearning\nhashtag\n#\nmlops\nhashtag\n#\ndatascience\n.\n  Follow me for daily lessons about ML engineering and MLOps.[URL]&quot;,<br>  &quot;image&quot;: null,<br>  &quot;platform&quot;: &quot;linkedin&quot;,<br>  &quot;type&quot;: &quot;posts&quot;<br>}</pre><h4>Process:</h4><p><strong>Deriving Instructions:</strong> We can use these insights to craft instructions for GPT 3.5-turbo:</p><ul><li><strong>Instruction 1:</strong> “Write a LinkedIn post promoting a new educational course on building LLM systems with a focus on LLMOps. Use relevant hashtags and a tone that is both informative and engaging.”</li><li><strong>Instruction 2:</strong> “Write a LinkedIn post explaining the benefits of using LLMs and vector databases in real-time financial advising applications. Highlight the importance of LLMOps for successful deployment.”</li></ul><h4><strong>Generating the Dataset with GPT 3.5-turbo</strong></h4><ul><li><strong>Feeding Instructions:</strong> We would input the <strong>content</strong> derived from our Qdrant data points, along with others similarly created, into GPT 3.5-turbo.</li><li><strong>LLM Outputs:</strong> GPT 3.5-turbo would then generate instruction for every LinkedIn-style text content.</li></ul><p><strong>Result:</strong> This process would yield a dataset of instruction-output pairs designed to fine-tune Mistral-7B for content generation.</p><h4>Practical Example</h4><p>In this section, we will demonstrate a practical application of the methods discussed above using a batch of content derived from various posts.</p><p>The example will simulate the process of creating a training dataset for an LLM, using the format we’ve outlined.</p><p>Imagine that we want to go from this ↓</p><pre>{<br>  &quot;author_id&quot;: &quot;2&quot;,<br>  &quot;cleaned_content&quot;: &quot;Do you want to learn to build hands-on LLM systems using good LLMOps practices? A new Medium series is coming up for the Hands-on LLMs course\n.\nBy finishing the Hands-On LLMs free course, you will learn how to use the 3-pipeline architecture &amp; LLMOps good practices to design, build, and deploy a real-time financial advisor powered by LLMs &amp; vector DBs.\nWe will primarily focus on the engineering &amp; MLOps aspects.\nThus, by the end of this series, you will know how to build &amp; deploy a real ML system, not some isolated code in Notebooks.\nThere are 3 components you will learn to build during the course:\n- a real-time streaming pipeline\n- a fine-tuning pipeline\n- an inference pipeline\n.\nWe have already released the code and video lessons of the Hands-on LLM course.\nBut we are excited to announce an 8-lesson Medium series that will dive deep into the code and explain everything step-by-step.\nWe have already released the first lesson of the series  \nThe LLMs kit: Build a production-ready real-time financial advisor system using streaming pipelines, RAG, and LLMOps:  \n[URL]\n  In Lesson 1, you will learn how to design a financial assistant using the 3-pipeline architecture (also known as the FTI architecture), powered by:\n- LLMs\n- vector DBs\n- a streaming engine\n- LLMOps\n.\n  The rest of the articles will be released by the end of January 2024.\nFollow us on Medium&#39;s Decoding ML publication to get notified when we publish the other lessons:  \n[URL]\nhashtag\n#\nmachinelearning\nhashtag\n#\nmlops\nhashtag\n#\ndatascience&quot;,<br>},<br>{<br>  &quot;author_id&quot;: &quot;2&quot;,<br>  &quot;cleaned_content&quot;: &quot;RAG systems are far from perfect   This free course teaches you how to improve your RAG system.\nI recently finished the Advanced Retrieval for AI with Chroma free course from\nDeepLearning.AI\nIf you are into RAG, I find it among the most valuable learning sources.\nThe course already assumes you know what RAG is.\nIts primary focus is to show you all the current issues of RAG and why it is far from perfect.\nAfterward, it shows you the latest SoTA techniques to improve your RAG system, such as:\n- query expansion\n- cross-encoder re-ranking\n- embedding adaptors\nI am not affiliated with\nDeepLearning.AI\n(I wouldn&#39;t mind though).\nThis is a great course you should take if you are into RAG systems.\nThe good news is that it is free and takes only 1 hour.\nCheck it out  \n  Advanced Retrieval for AI with Chroma:\n[URL]\nhashtag\n#\nmachinelearning\nhashtag\n#\nmlops\nhashtag\n#\ndatascience\n.\n  Follow me for daily lessons about ML engineering and MLOps.[URL]&quot;,<br>}</pre><p>to this ↓</p><pre>[<br>  {<br>    &quot;instruction&quot;: &quot;Share the announcement of the upcoming Medium series on building hands-on LLM systems using good LLMOps practices, focusing on the 3-pipeline architecture and real-time financial advisor development. Follow the Decoding ML publication on Medium for notifications on future lessons.&quot;,<br>    &quot;content&quot;: &quot;Do you want to learn to build hands-on LLM systems using good LLMOps practices? A new Medium series is coming up for the Hands-on LLMs course\n.\nBy finishing the Hands-On LLMs free course, you will learn how to use the 3-pipeline architecture &amp; LLMOps good practices to design, build, and deploy a real-time financial advisor powered by LLMs &amp; vector DBs.\nWe will primarily focus on the engineering &amp; MLOps aspects.\nThus, by the end of this series, you will know how to build &amp; deploy a real ML system, not some isolated code in Notebooks.\nThere are 3 components you will learn to build during the course:\n- a real-time streaming pipeline\n- a fine-tuning pipeline\n- an inference pipeline\n.\nWe have already released the code and video lessons of the Hands-on LLM course.\nBut we are excited to announce an 8-lesson Medium series that will dive deep into the code and explain everything step-by-step.\nWe have already released the first lesson of the series  \nThe LLMs kit: Build a production-ready real-time financial advisor system using streaming pipelines, RAG, and LLMOps:  \n[URL]\n  In Lesson 1, you will learn how to design a financial assistant using the 3-pipeline architecture (also known as the FTI architecture), powered by:\n- LLMs\n- vector DBs\n- a streaming engine\n- LLMOps\n.\n  The rest of the articles will be released by the end of January 2024.\nFollow us on Medium&#39;s Decoding ML publication to get notified when we publish the other lessons:  \n[URL]\nhashtag\n#\nmachinelearning\nhashtag\n#\nmlops\nhashtag\n#\ndatascience&quot;<br>  },<br>  {<br>    &quot;instruction&quot;: &quot;Promote the free course &#39;Advanced Retrieval for AI with Chroma&#39; from DeepLearning.AI that aims to improve RAG systems and takes only 1 hour to complete. Share the course link and encourage followers to check it out for the latest techniques in query expansion, cross-encoder re-ranking, and embedding adaptors.&quot;,<br>    &quot;content&quot;: &quot;RAG systems are far from perfect   This free course teaches you how to improve your RAG system.\nI recently finished the Advanced Retrieval for AI with Chroma free course from\nDeepLearning.AI\nIf you are into RAG, I find it among the most valuable learning sources.\nThe course already assumes you know what RAG is.\nIts primary focus is to show you all the current issues of RAG and why it is far from perfect.\nAfterward, it shows you the latest SoTA techniques to improve your RAG system, such as:\n- query expansion\n- cross-encoder re-ranking\n- embedding adaptors\nI am not affiliated with\nDeepLearning.AI\n(I wouldn&#39;t mind though).\nThis is a great course you should take if you are into RAG systems.\nThe good news is that it is free and takes only 1 hour.\nCheck it out  \n  Advanced Retrieval for AI with Chroma:\n[URL]\nhashtag\n#\nmachinelearning\nhashtag\n#\nmlops\nhashtag\n#\ndatascience\n.\n  Follow me for daily lessons about ML engineering and MLOps.[URL]&quot;<br>  },</pre><p>We are enhancing the LLM’s capability to generate specific instructions for each data point, aiming to impregnate the model with specialized knowledge in content creation.</p><h4>Step 1: Set Up Data Points</h4><p>First, let’s define a sample set of data points. These represent different content pieces from which we want to generate LinkedIn post instructions.</p><pre>{<br>  &quot;author_id&quot;: &quot;2&quot;,<br>  &quot;cleaned_content&quot;: &quot;Do you want to learn to build hands-on LLM systems using good LLMOps practices? A new Medium series is coming up for the Hands-on LLMs course\n.\nBy finishing the Hands-On LLMs free course, you will learn how to use the 3-pipeline architecture &amp; LLMOps good practices to design, build, and deploy a real-time financial advisor powered by LLMs &amp; vector DBs.\nWe will primarily focus on the engineering &amp; MLOps aspects.\nThus, by the end of this series, you will know how to build &amp; deploy a real ML system, not some isolated code in Notebooks.\nThere are 3 components you will learn to build during the course:\n- a real-time streaming pipeline\n- a fine-tuning pipeline\n- an inference pipeline\n.\nWe have already released the code and video lessons of the Hands-on LLM course.\nBut we are excited to announce an 8-lesson Medium series that will dive deep into the code and explain everything step-by-step.\nWe have already released the first lesson of the series  \nThe LLMs kit: Build a production-ready real-time financial advisor system using streaming pipelines, RAG, and LLMOps:  \n[URL]\n  In Lesson 1, you will learn how to design a financial assistant using the 3-pipeline architecture (also known as the FTI architecture), powered by:\n- LLMs\n- vector DBs\n- a streaming engine\n- LLMOps\n.\n  The rest of the articles will be released by the end of January 2024.\nFollow us on Medium&#39;s Decoding ML publication to get notified when we publish the other lessons:  \n[URL]\nhashtag\n#\nmachinelearning\nhashtag\n#\nmlops\nhashtag\n#\ndatascience&quot;,<br>  &quot;platform&quot;: &quot;linkedin&quot;,<br>  &quot;type&quot;: &quot;posts&quot;<br>},<br>{<br>  &quot;author_id&quot;: &quot;2&quot;,<br>  &quot;cleaned_content&quot;: &quot;RAG systems are far from perfect   This free course teaches you how to improve your RAG system.\nI recently finished the Advanced Retrieval for AI with Chroma free course from\nDeepLearning.AI\nIf you are into RAG, I find it among the most valuable learning sources.\nThe course already assumes you know what RAG is.\nIts primary focus is to show you all the current issues of RAG and why it is far from perfect.\nAfterward, it shows you the latest SoTA techniques to improve your RAG system, such as:\n- query expansion\n- cross-encoder re-ranking\n- embedding adaptors\nI am not affiliated with\nDeepLearning.AI\n(I wouldn&#39;t mind though).\nThis is a great course you should take if you are into RAG systems.\nThe good news is that it is free and takes only 1 hour.\nCheck it out  \n  Advanced Retrieval for AI with Chroma:\n[URL]\nhashtag\n#\nmachinelearning\nhashtag\n#\nmlops\nhashtag\n#\ndatascience\n.\n  Follow me for daily lessons about ML engineering and MLOps.[URL]&quot;,<br>  &quot;image&quot;: null,<br>  &quot;platform&quot;: &quot;linkedin&quot;,<br>  &quot;type&quot;: &quot;posts&quot;<br>}</pre><h4>Step 2: Utilize the DataFormatter Class</h4><p>We’ll use the DataFormatter class to format these data points into a structured prompt for the LLM. Here’s how you would use the class to prepare the content:</p><pre>data_type = &quot;posts&quot;<br>USER_PROMPT = (<br>    f&quot;I will give you batches of contents of {data_type}. Please generate me exactly 1 instruction for each of them. The {data_type} text &quot;<br>    f&quot;for which you have to generate the instructions is under Content number x lines. Please structure the answer in json format,&quot;<br>    f&quot;ready to be loaded by json.loads(), a list of objects only with fields called instruction and content. For the content field, copy the number of the content only!.&quot;<br>    f&quot;Please do not add any extra characters and make sure it is a list with objects in valid json format!\n&quot;<br>)<br><br><br>class DataFormatter:<br>    @classmethod<br>    def format_data(cls, data_points: list, is_example: bool, start_index: int) -&gt; str:<br>        text = &quot;&quot;<br>        for index, data_point in enumerate(data_points):<br>            if not is_example:<br>                text += f&quot;Content number {start_index + index }\n&quot;<br>            text += str(data_point) + &quot;\n&quot;<br>        return text<br><br>    @classmethod<br>    def format_batch(cls, context_msg: str, data_points: list, start_index: int) -&gt; str:<br>        delimiter_msg = context_msg<br>        delimiter_msg += cls.format_data(data_points, False, start_index)<br>        return delimiter_msg<br><br>    @classmethod<br>    def format_prompt(cls, inference_posts: list, start_index: int):<br>        initial_prompt = USER_PROMPT<br>        initial_prompt += f&quot;You must generate exactly a list of {len(inference_posts)} json objects, using the contents provided under CONTENTS FOR GENERATION\n&quot;<br>        initial_prompt += cls.format_batch(<br>            &quot;\nCONTENTS FOR GENERATION: \n&quot;, inference_posts, start_index<br>        )<br>        return initial_prompt</pre><p>Output of the <strong><em>format_prompt</em></strong> function:</p><pre>I will give you batches of contents of posts. Please generate me exactly 1 instruction for each of them. The posts text for which you have to generate the instructions is under Content number x lines. Please structure the answer in json format,ready to be loaded by json.loads(), a list of objects only with fields called instruction and content. For the content field, copy the number of the content only!.Please do not add any extra characters and make sure it is a list with objects in valid json format!<br>You must generate exactly a list of 1 json objects, using the contents provided under CONTENTS FOR GENERATION<br><br>CONTENTS FOR GENERATION: <br>Content number 0<br>Do you want to learn to build hands-on LLM systems using good LLMOps practices? A new Medium series is coming up for the Hands-on LLMs course<br>.<br>By finishing the Hands-On LLMs free course, you will learn how to use the 3-pipeline architecture &amp; LLMOps good practices to design, build, and deploy a real-time financial advisor powered by LLMs &amp; vector DBs.<br>We will primarily focus on the engineering &amp; MLOps aspects.<br>Thus, by the end of this series, you will know how to build &amp; deploy a real ML system, not some isolated code in Notebooks.<br>There are 3 components you will learn to build during the course:<br>- a real-time streaming pipeline<br>- a fine-tuning pipeline<br>- an inference pipeline</pre><h4>Step 3: Automate finetuning data generation using the DatasetGenerator Class</h4><p>To automate the generation of finetuning data, we desgined the DatasetGenerator class. This class is designed to streamline the process from fetching data to logging the training data into Comet ML.</p><p>The DatasetGenerator class is initialized with three components: a file handler for managing file I/O, an API communicator for interacting with the LLM, and a data formatter for preparing data:</p><pre>class DatasetGenerator:<br>    def __init__(self, file_handler, api_communicator, data_formatter):<br>        self.file_handler = file_handler<br>        self.api_communicator = api_communicator<br>        self.data_formatter = data_formatter</pre><p><strong>Generating Finetuning Data</strong></p><p>The generate_training_data method from <strong>DatasetGenerator class</strong> handles the full lifecycle of data generation:</p><pre>def generate_training_data(self, collection_name: str, batch_size: int = 1):<br>    all_contents = self.fetch_all_cleaned_content(collection_name)<br>    response = []<br>    for i in range(0, len(all_contents), batch_size):<br>        batch = all_contents[i : i + batch_size]<br>        initial_prompt = self.data_formatter.format_prompt(batch, i)<br>        response += self.api_communicator.send_prompt(initial_prompt)<br>        for j in range(i, i + batch_size):<br>            response[j][&quot;content&quot;] = all_contents[j]<br><br>    self.push_to_comet(response, collection_name)</pre><p><strong>Fetch Content</strong></p><p>The fetch_all_cleaned_content method retrieves all relevant content from a specified collection and prepares it for processing:</p><pre>def fetch_all_cleaned_content(self, collection_name: str) -&gt; list:<br>    all_cleaned_contents = []<br>    scroll_response = client.scroll(collection_name=collection_name, limit=10000)<br>    points = scroll_response[0]<br>    for point in points:<br>        cleaned_content = point.payload[&quot;cleaned_content&quot;]<br>        if cleaned_content:<br>            all_cleaned_contents.append(cleaned_content)<br>    return all_cleaned_contents</pre><h3>4. CometML — data versioning</h3><p>In this section, we focus on a critical aspect of Machine Learning Operations (MLOps) — data versioning.</p><p>We’ll specifically look at how to implement this using <a href="https://www.comet.com/signup/?utm_source=decoding_ml&amp;utm_medium=partner&amp;utm_content=medium">Comet ML</a>, a platform that facilitates experiment management and reproducibility in machine learning projects.</p><p><a href="https://www.comet.com/signup/?utm_source=decoding_ml&amp;utm_medium=partner&amp;utm_content=medium">CometML</a> is a cloud-based platform that provides tools for tracking, comparing, explaining, and optimizing experiments and models in machine learning. CometML helps data scientists and teams to better manage and collaborate on machine learning experiments.</p><h3>Why Use CometML?</h3><ul><li><strong>Artifacts</strong>: Leverages <a href="https://www.comet.com/docs/v2/guides/artifacts/using-artifacts/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">artifact management</a> to capture, version, and manage data snapshots and models, which helps maintain data integrity and trace experiment lineage effectively.</li><li><strong>Experiment Tracking</strong>: <a href="https://www.comet.com/signup/?utm_source=decoding_ml&amp;utm_medium=partner&amp;utm_content=medium">CometML</a> automatically tracks your code, experiments, and results, allowing you to compare different runs and configurations visually.</li><li><strong>Model Optimization</strong>: It offers tools to compare different models side by side, analyze hyperparameters, and track model performance across various metrics.</li><li><strong>Collaboration and Sharing</strong>: Share findings and models with colleagues or the ML community, enhancing team collaboration and knowledge transfer.</li><li><strong>Reproducibility</strong>: By logging every detail of the experiment setup, CometML ensures experiments are reproducible, making it easier to debug and iterate.</li></ul><p>Maybe you’re asking why not to choose <strong>MLFlow</strong> for example [<a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">2</a>]:</p><ul><li><a href="https://www.comet.com/signup/?utm_source=decoding_ml&amp;utm_medium=partner&amp;utm_content=medium"><strong>CometML</strong></a> excels in user interface design, providing a clean, intuitive experience for tracking experiments and models.</li><li>It offers robust collaboration tools, making it easier for teams to work together on machine learning projects.</li><li><a href="https://www.comet.com/signup/?utm_source=decoding_ml&amp;utm_medium=partner&amp;utm_content=medium"><strong>CometML</strong></a> provides comprehensive security features that help protect data and models, an important consideration for enterprises.</li><li>It has superior scalability, supporting larger datasets and more complex model training scenarios.</li><li>The platform allows for more detailed tracking and analysis of experiments compared to MLflow.</li></ul><h3>CometML Variables</h3><p>When integrating CometML into your projects, you’ll need to set up several environment variables to manage the authentication and configuration:</p><ul><li>COMET_API_KEY: Your unique API key that authenticates your interactions with the CometML API.</li><li>COMET_PROJECT: The project name under which your experiments will be logged.</li><li>COMET_WORKSPACE: The workspace name that organizes various projects and experiments.</li></ul><h3>Obtaining CometML Variables</h3><p>To access and set up the necessary CometML variables for your project, follow these steps:</p><ol><li><strong>Create an Account or Log In</strong>:</li></ol><ul><li>Visit <a href="https://www.comet.com/signup/?utm_source=decoding_ml&amp;utm_medium=partner&amp;utm_content=medium">CometML’s website</a> and log in if you already have an account, or sign up if you’re a new user.</li></ul><p><strong>2. Create a New Project</strong>:</p><ul><li>Once logged in, navigate to your dashboard. Here, you can create a new project by clicking on “New Project” and entering the relevant details for your project.</li></ul><p><strong>3. Access API Key</strong>:</p><ul><li>After creating your project, you will need to obtain your API key. Navigate to your account settings by clicking on your profile at the top right corner. Select ‘API Keys’ from the menu, and you’ll see an option to generate or copy your existing API key.</li></ul><p><strong>4. Set Environment Variables</strong>:</p><ul><li>Add the obtained COMET_API_KEY to your environment variables, along with the COMET_PROJECT and COMET_WORKSPACE names you have set up.</li></ul><h4>The Importance of Data Versioning in MLOps</h4><p><strong>Data versioning</strong> is the practice of keeping a record of multiple versions of datasets used in training machine learning models. This practice is essential for several reasons:</p><ol><li><strong>Reproducibility</strong>: It ensures that experiments can be reproduced using the exact same data, which is crucial for validating and comparing machine learning models.</li><li><strong>Model Diagnostics and Auditing</strong>: If a model’s performance changes unexpectedly, data versioning allows teams to revert to previous data states to identify issues.</li><li><strong>Collaboration and Experimentation</strong>: Teams can experiment with different data versions to see how changes affect model performance without losing the original data setups.</li><li><strong>Regulatory Compliance</strong>: In many industries, keeping track of data modifications and training environments is required for compliance with regulations.</li></ol><h4>Comet ML’s Artifacts</h4><ul><li><strong>Version Control</strong>: Artifacts in Comet ML are versioned, allowing you to track changes and iterate on datasets and models efficiently.</li><li><strong>Immutability</strong>: Once created, artifacts are immutable, ensuring that data integrity is maintained throughout the lifecycle of your projects.</li><li><strong>Metadata and Tagging</strong>: You can enhance artifacts with metadata and tags, making them easier to search and organize within Comet ML.</li><li><strong>Alias Management</strong>: Artifacts can be assigned aliases to simplify references to versions, streamlining workflow and reference.</li><li><strong>External Storage</strong>: Supports integration with external storage solutions like Amazon S3, enabling scalable and secure data management.</li></ul><p>The provided push_to_comet function is a key part of this process.</p><pre>def push_to_comet(self, data: list, collection_name: str):<br>        try:<br>            logging.info(f&quot;Starting to push data to Comet: {collection_name}&quot;)<br><br>            # Assuming the settings module has been properly configured with the required attributes<br>            experiment = Experiment(<br>                api_key=settings.COMET_API_KEY,<br>                project_name=settings.COMET_PROJECT,<br>                workspace=settings.COMET_WORKSPACE,<br>            )<br><br>            file_name = f&quot;{collection_name}.json&quot;<br>            logging.info(f&quot;Writing data to file: {file_name}&quot;)<br><br>            with open(file_name, &quot;w&quot;) as f:<br>                json.dump(data, f)<br><br>            logging.info(&quot;Data written to file successfully&quot;)<br><br>            artifact = Artifact(collection_name)<br>            artifact.add(file_name)<br>            logging.info(f&quot;Artifact created and file added: {file_name}&quot;)<br><br>            experiment.log_artifact(artifact)<br>            experiment.end()<br>            logging.info(&quot;Data pushed to Comet successfully and experiment ended&quot;)<br><br>        except Exception as e:<br>            logging.error(f&quot;Failed to push data to Comet: {e}&quot;, exc_info=True)</pre><p>Breakdown of Function Components</p><ul><li><strong>Experiment Initialization</strong>: An experiment is created using the project settings. This ties all actions, like logging artifacts, to a specific experimental run.</li><li><strong>Data Saving</strong>: Data is saved locally as a JSON file. This file format is versatile and widely used, making it a good choice for data interchange.</li><li><strong>Artifact Creation and Logging</strong>: An artifact is a versioned object in Comet ML that can be associated with an experiment. By logging artifacts, you keep a record of all data versions used throughout the project lifecycle.</li></ul><p>After running the script that invokes the push_to_comet function, Comet ML will update with new data artifacts, each representing a different dataset version. This is a crucial step in ensuring that all your data versions are logged and traceable within your MLOps environment.</p><h4>What to Expect in Comet ML</h4><p>Here is what you should see in Comet ML after successfully executing the script:</p><ol><li><strong>Artifacts Section</strong>: Navigate to the “Artifacts” tab in your Comet ML dashboard.</li><li><strong>List of Artifacts</strong>: You will see entries for each type of data you’ve processed and saved. For example, if you have cleaned and versioned articles and posts, they will appear as separate artifacts.</li><li><strong>Artifact Versions</strong>: Each artifact can have multiple versions. Each time you run the script with a new or updated dataset, a new version of the respective artifact is created.</li></ol><p>For example, in the screenshot below there are two artifacts listed:</p><ul><li><strong>cleaned_articles</strong>: This artifact has 10 versions, indicating it has been updated or modified 10 times.</li><li><strong>cleaned_posts</strong>: This artifact shows 3 versions, showing fewer updates compared to the articles.</li></ul><p>Each version is timestamped and stored with a unique ID, allowing you to track changes over time or revert to previous versions if necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oiHyiouxyu-MBSVOWDJQFA.jpeg" /><figcaption>Comet ML data artifacts [Image by the author]</figcaption></figure><p>A final version of your dataset, such as cleaned_articles.json, will be ready for the fine-tuning task.</p><p>This JSON file will include pairs of instructions and contents.</p><p>The instructions are generated by the LLM, guiding the model to perform specific tasks or understand particular contexts, while the content comprises data crawled and processed through your pipeline.</p><p>This format ensures each dataset version is not only tracked but also structured to enhance machine learning model performance through targeted finetuning.</p><p>Here’s an example of what the final version of cleaned_articles.json might look like, ready for the fine-tuning task:</p><pre>[<br>  {<br>    &quot;instruction&quot;: &quot;Design and build a production-ready feature pipeline using Bytewax as a stream engine, RabbitMQ queue, and Qdrant vector DB. Include steps for processing raw data, data snapshots, Pydantic models, and loading cleaned features to the vector DB. Deploy the pipeline to AWS and integrate with previous components.&quot;,<br>    &quot;content&quot;: &quot;SOTA Python Streaming Pipelines for Fine-tuning LLMs and RAG \\u2014 in Real-Time!Use a Python streaming engine to populate a feature store from 4+ data sourcesStreaming Pipelines for LLMs and RAG | Decoding MLOpen in appSign upSign inWriteSign upSign inMastodonLLM TWIN COURSE: BUILDING YOUR PRODUCTION-READY AI REPLICASOTA Python Streaming Pipelines for Fine-tuning LLMs and RAG  in Real-Time!Use a Python streaming engine to populate a feature store from 4+ data sourcesPaul IusztinFollowPublished inDecoding ML18 min read6 days ago698ListenShare  the 4th out of 11 lessons of the LLM Twin free courseWhat is your LLM Twin? It is an AI character that writes like yourself by incorporating your style, personality and voice into an LLM.Image by DALL-EWhy is this course different?By finishing the LLM Twin: Building Your Production-Ready AI Replica free course, you will learn how to design, train, and deploy a production-ready LLM twin of yourself powered by LLMs, vector DBs, and LLMOps good practices.Why should you care? \\U0001faf5  No more isolated scripts or Notebooks! Learn production ML by building and deploying an end-to-end production-grade LLM system.What will you learn to build by the end of this course?You will learn how to architect and build a real-world LLM system from start to finish  from data collection to deployment.You will also learn to leverage MLOps best practices, such as experiment trackers, model registries, prompt monitoring, and versioning.The end goal? Build and deploy your own LLM twin.The architecture of the LLM twin is split into 4 Python microservices:the data collection pipeline: crawl your digital data from various social media platforms. Clean, normalize and load the data to a NoSQL DB through a series of ETL pipelines. Send database changes to a queue using the CDC pattern. (deployed on AWS)the feature pipeline: consume messages from a queue through a Bytewax streaming pipeline. Every message will be cleaned, chunked, embedded (using Superlinked), and loaded into a Qdrant vector DB in real-time. (deployed on AWS)the training pipeline: create a custom dataset based on your digital data. Fine-tune an LLM using QLoRA. Use Comet MLs experiment tracker to monitor the experiments. Evaluate and save the best model to Comets model registry. (deployed on Qwak)the inference pipeline: load and quantize the fine-tuned LLM from Comets model registry. Deploy it as a REST API. Enhance the prompts using RAG. Generate content using your LLM twin. Monitor the LLM using Comets prompt monitoring dashboard. (deployed on Qwak)LLM twin system architecture [Image by the Author]Along the 4 microservices, you will learn to integrate 3 serverless tools:Comet ML as your ML Platform;Qdrant as your vector DB;Qwak as your ML infrastructure;Who is this for?Audience: MLE, DE, DS, or SWE who want to learn to engineer production-ready LLM systems using LLMOps good principles.Level: intermediatePrerequisites: basic knowledge of Python, ML, and the cloudHow will you learn?The course contains 11 hands-on written lessons and the open-source code you can access on GitHub.You can read everything at your own pace.  To get the most out of this course, we encourage you to clone and run the repository while you cover the lessons.Costs?The articles and code are completely free. They will always remain free.But if you plan to run the code while reading it, you have to know that we use several cloud tools that might generate additional costs.The cloud computing platforms (AWS, Qwak) have a pay-as-you-go pricing plan. Qwak offers a few hours of free computing. Thus, we did our best to keep costs to a minimum.For the other serverless tools (Qdrant, Comet), we will stick to their freemium version, which is free of charge.Meet your teachers!The course is created under the Decoding ML umbrella by:Paul Iusztin | Senior ML &amp; MLOps EngineerAlex Vesa | Senior AI EngineerAlex Razvant | Senior ML &amp; MLOps EngineerLessonsThe course is split into 11 lessons. Every Medium article will be its own lesson.An End-to-End Framework for Production-Ready LLM Systems by Building Your LLM TwinThe Importance of Data Pipelines in the Era of Generative AIChange Data Capture: Enabling Event-Driven ArchitecturesSOTA Python Streaming Pipelines for Fine-tuning LLMs and RAG  in Real-Time!Vector DB retrieval clients [Module 2] WIPTraining data preparation [Module 3] WIPFine-tuning LLM [Module 3] WIPLLM evaluation [Module 4] WIPQuantization [Module 5] WIPBuild the digital twin inference pipeline [Module 6] WIPDeploy the digital twin as a REST API [Module 6] WIP  Check out the code on GitHub [1] and support us with a Lets start with Lesson 4  Lesson 4: Python Streaming Pipelines for Fine-tuning LLMs and RAG  in Real-Time!In the 4th lesson, we will focus on the feature pipeline.The feature pipeline is the first pipeline presented in the 3 pipeline architecture: feature, training and inference pipelines.A feature pipeline is responsible for taking raw data as input, processing it into features, and storing it in a feature store, from which the training &amp; inference pipelines will use it.The component is completely isolated from the training and inference code. All the communication is done through the feature store.To avoid repeating myself, if you are unfamiliar with the 3 pipeline architecture, check out Lesson 1 for a refresher.By the end of this article, you will learn to design and build a production-ready feature pipeline that:uses Bytewax as a stream engine to process data in real-time;ingests data from a RabbitMQ queue;uses SWE practices to process multiple data types: posts, articles, code;cleans, chunks, and embeds data for LLM fine-tuning and RAG;loads the features to a Qdrant vector DB.Note: In our use case, the feature pipeline is also a streaming pipeline, as we use a Bytewax streaming engine. Thus, we will use these words interchangeably.We will wrap up Lesson 4 by showing you how to deploy the feature pipeline to AWS and integrate it with the components from previous lessons: data collection pipeline, MongoDB, and CDC.In the 5th lesson, we will go through the vector DB retrieval client, where we will teach you how to query the vector DB and improve the accuracy of the results using advanced retrieval techniques.Excited? Lets get started!The architecture of the feature/streaming pipeline.Table of ContentsWhy are we doing this?System design of the feature pipelineThe Bytewax streaming flowPydantic data modelsLoad data to QdrantThe dispatcher layerPreprocessing steps: Clean, chunk, embedThe AWS infrastructureRun the code locallyDeploy the code to AWS &amp; Run it from the cloudConclusion  Check out the code on GitHub [1] and support us with a 1. Why are we doing this?A quick reminder from previous lessonsTo give you some context, in Lesson 2, we crawl data from LinkedIn, Medium, and GitHub, normalize it, and load it to MongoDB.In Lesson 3, we are using CDC to listen to changes to the MongoDB database and emit events in a RabbitMQ queue based on any CRUD operation done on MongoDB.and here we are in Lesson 4, where we are building the feature pipeline that listens 24/7 to the RabbitMQ queue for new events to process and load them to a Qdrant vector DB.The problem we are solvingIn our LLM Twin use case, the feature pipeline constantly syncs the MongoDB warehouse with the Qdrant vector DB while processing the raw data into features.Important: In our use case, the Qdrant vector DB will be our feature store.Why we are solving itThe feature store will be the central point of access for all the features used within the training and inference pipelines.For consistency and simplicity, we will refer to different formats of our text data as features.  The training pipeline will use the feature store to create fine-tuning datasets for your LLM twin.  The inference pipeline will use the feature store for RAG.For reliable results (especially for RAG), the data from the vector DB must always be in sync with the data from the data warehouse.The question is, what is the best way to sync these 2?Other potential solutionsThe most common solution is probably to use a batch pipeline that constantly polls from the warehouse, computes a difference between the 2 databases, and updates the target database.The issue with this technique is that computing the difference between the 2 databases is extremely slow and costly.Another solution is to use a push technique using a webhook. Thus, on any CRUD change in the warehouse, you also update the source DB.The biggest issue here is that if the webhook fails, you have to implement complex recovery logic.Lesson 3 on CDC covers more of this.2. System design of the feature pipeline: our solutionOur solution is based on CDC, a queue, a streaming engine, and a vector DB:  CDC adds any change made to the Mongo DB to the queue (read more in Lesson 3).  the RabbitMQ queue stores all the events until they are processed.  The Bytewax streaming engine cleans, chunks, and embeds the data.  A streaming engine works naturally with a queue-based system.  The data is uploaded to a Qdrant vector DB on the flyWhy is this powerful?Here are 4 core reasons:The data is processed in real-time.Out-of-the-box recovery system: If the streaming pipeline fails to process a message will be added back to the queueLightweight: No need for any diffs between databases or batching too many recordsNo I/O bottlenecks on the source database  It solves all our problems!The architecture of the feature/streaming pipeline.How is the data stored?We store 2 snapshots of our data in the feature store. Here is why  Remember that we said that the training and inference pipeline will access the features only from the feature store, which, in our case, is the Qdrant vector DB?Well, if we had stored only the chunked &amp; embedded version of the data, that would have been useful only for RAG but not for fine-tuning.Thus, we make an additional snapshot of the cleaned data, which will be used by the training pipeline.Afterward, we pass it down the streaming flow for chunking &amp; embedding.How do we process multiple data types?How do you process multiple types of data in a single streaming pipeline without writing spaghetti code?Yes, that is for you, data scientists! Jokingam I?We have 3 data types: posts, articles, and code.Each data type (and its state) will be modeled using Pydantic models.To process them we will write a dispatcher layer, which will use a creational factory pattern [9] to instantiate a handler implemented for that specific data type (post, article, code) and operation (cleaning, chunking, embedding).The handler follows the strategy behavioral pattern [10].Intuitively, you can see the combination between the factory and strategy patterns as follows:Initially, we know we want to clean the data, but as we dont know the data type, we cant know how to do so.What we can do, is write the whole code around the cleaning code and abstract away the login under a Handler() interface (aka the strategy).When we get a data point, the factory class creates the right cleaning handler based on its type.Ultimately the handler is injected into the rest of the system and executed.By doing so, we can easily isolate the logic for a given data type &amp; operation while leveraging polymorphism to avoid filling up the code with 1000x if else statements.We will dig into the implementation in future sections.Streaming over batchYou may ask why we need a streaming engine instead of implementing a batch job that polls the messages at a given frequency.That is a valid question.The thing is thatNowadays, using tools such as Bytewax makes implementing streaming pipelines a lot more frictionless than using their JVM alternatives.The key aspect of choosing a streaming vs. a batch design is real-time synchronization between your source and destination DBs.In our particular case, we will process social media data, which changes fast and irregularly.Also, for our digital twin, it is important to do RAG on up-to-date data. We dont want to have any delay between what happens in the real world and what your LLM twin sees.That being said choosing a streaming architecture seemed natural in our use case.3. The Bytewax streaming flowThe Bytewax flow is the central point of the streaming pipeline. It defines all the required steps, following the next simplified pattern: input -&gt; processing -&gt; output.As I come from the AI world, I like to see it as the graph of the streaming pipeline, where you use the input(), map(), and output() Bytewax functions to define your graph, which in the Bytewax world is called a flow.As you can see in the code snippet below, we ingest posts, articles or code messages from a RabbitMQ queue. After we clean, chunk and embed them. Ultimately, we load the cleaned and embedded data to a Qdrant vector DB, which in our LLM twin use case will represent the feature store of our system.To structure and validate the data, between each Bytewax step, we map and pass a different Pydantic model based on its current state: raw, cleaned, chunked, or embedded.Bytewax flow   GitHub Code We have a single streaming pipeline that processes everything.As we ingest multiple data types (posts, articles, or code snapshots), we have to process them differently.To do this the right way, we implemented a dispatcher layer that knows how to apply data-specific operations based on the type of message.More on this in the next sections  Why Bytewax?Bytewax is an open-source streaming processing framework that:- is built in Rust  for performance- has Python   bindings for leveraging its powerful ML ecosystem so, for all the Python fanatics out there, no more JVM headaches for you.Jokes aside, here is why Bytewax is so powerful  - Bytewax local setup is plug-and-play- can quickly be integrated into any Python project (you can go wild  even use it in Notebooks)- can easily be integrated with other Python packages (NumPy, PyTorch, HuggingFace, OpenCV, SkLearn, you name it)- out-of-the-box connectors for Kafka and local files, or you can quickly implement your ownWe used Bytewax to build the streaming pipeline for the LLM Twin course and loved it.To learn more about Bytewax, go and check them out. They are open source, so no strings attached   Bytewax [2] 4. Pydantic data modelsLets take a look at what our Pydantic models look like.First, we defined a set of base abstract models for using the same parent class across all our components.Pydantic base model structure   GitHub Code Afterward, we defined a hierarchy of Pydantic models for:all our data types: posts, articles, or codeall our states: raw, cleaned, chunked, and embeddedThis is how the set of classes for the posts will look like  Pydantic posts model structure   GitHub Code We repeated the same process for the articles and code model hierarchy.Check out the other data classes on our GitHub.Why is keeping our data in Pydantic models so powerful?There are 4 main criteria:every field has an enforced type: you are ensured the data types are going to be correctthe fields are automatically validated based on their type: for example, if the field is a string and you pass an int, it will through an errorthe data structure is clear and verbose: no more clandestine dicts that you never know what is in themyou make your data the first-class citizen of your program5. Load data to QdrantThe first step is to implement our custom Bytewax DynamicSink class  Qdrant DynamicSink   GitHub Code Next, for every type of operation we need (output cleaned or embedded data ) we have to subclass the StatelessSinkPartition Bytewax class (they also provide a stateful option   more in their docs)An instance of the class will run on every partition defined within the Bytewax deployment.In the course, we are using a single partition per worker. But, by adding more partitions (and workers), you can quickly scale your Bytewax pipeline horizontally.Qdrant worker partitions   GitHub Code Note that we used Qdrants Batch method to upload all the available points at once. By doing so, we reduce the latency on the network I/O side: more on that here [8] The RabbitMQ streaming input follows a similar pattern. Check it out here 6. The dispatcher layerNow that we have the Bytewax flow and all our data models.How do we map a raw data model to a cleaned data model?  All our domain logic is modeled by a set of Handler() classes.For example, this is how the handler used to map a PostsRawModel to a PostCleanedModel looks like  Handler hierarchy of classes   GitHub Code Check out the other handlers on our GitHub:  ChunkingDataHandler and EmbeddingDataHandlerIn the next sections, we will explore the exact cleaning, chunking and embedding logic.Now, to build our dispatcher, we need 2 last components:a factory class: instantiates the right handler based on the type of the eventa dispatcher class: the glue code that calls the factory class and handlerHere is what the cleaning dispatcher and factory look like  The dispatcher and factory classes   GitHub Code Check out the other dispatchers on our GitHub.By repeating the same logic, we will end up with the following set of dispatchers:RawDispatcher (no factory class required as the data is not processed)CleaningDispatcher (with a ChunkingHandlerFactory class)ChunkingDispatcher (with a ChunkingHandlerFactory class)EmbeddingDispatcher (with an EmbeddingHandlerFactory class)7. Preprocessing steps: Clean, chunk, embedHere we will focus on the concrete logic used to clean, chunk, and embed a data point.Note that this logic is wrapped by our handler to be integrated into our dispatcher layer using the Strategy behavioral pattern [10].We already described that in the previous section. Thus, we will directly jump into the actual logic here, which can be found in the utils module of our GitHub repository.Note: These steps are experimental. Thus, what we present here is just the first iteration of the system. In a real-world scenario, you would experiment with different cleaning, chunking or model versions to improve it on your data.CleaningThis is the main utility function used to clean the text for our posts, articles, and code.Out of simplicity, we used the same logic for all the data types, but after more investigation, you would probably need to adapt it to your specific needs.For example, your posts might start containing some weird characters, and you dont want to run the unbold_text() or unitalic_text() functions on your code data point as is completely redundant.Cleaning logic   GitHub Code Most of the functions above are from the unstructured [3] Python package. It is a great tool for quickly finding utilities to clean text data.  More examples of unstructured here [3] One key thing to notice is that at the cleaning step, we just want to remove all the weird, non-interpretable characters from the text.Also, we want to remove redundant data, such as extra whitespace or URLs, as they do not provide much value.These steps are critical for our tokenizer to understand and efficiently transform our string input into numbers that will be fed into the transformer models.Note that when using bigger models (transformers) + modern tokenization techniques, you dont need to standardize your dataset too much.For example, it is redundant to apply lemmatization or stemming, as the tokenizer knows how to split your input into a commonly used sequence of characters efficiently, and the transformers can pick up the nuances of the words.  What is important at the cleaning step is to throw out the noise.ChunkingWe are using Langchain to chunk our text.We use a 2 step strategy using Langchains RecursiveCharacterTextSplitter [4] and SentenceTransformersTokenTextSplitter [5]. As seen below  Chunking logic   GitHub Code Overlapping your chunks is a common pre-indexing RAG technique, which helps to cluster chunks from the same document semantically.Again, we are using the same chunking logic for all of our data types, but to get the most out of it, we would probably need to tweak the separators, chunk_size, and chunk_overlap parameters for our different use cases.But our dispatcher + handler architecture would easily allow us to configure the chunking step in future iterations.EmbeddingThe data preprocessing, aka the hard part is done.Now we just have to call an embedding model to create our vectors.Embedding logic   GitHub Code We used the all-MiniLm-L6-v2 [6] from the sentence-transformers library to embed our articles and posts: a lightweight embedding model that can easily run in real-time on a 2 vCPU machine.As the code data points contain more complex relationships and specific jargon to embed, we used a more powerful embedding model: hkunlp/instructor-xl [7].This embedding model is unique as it can be customized on the fly with instructions based on your particular data. This allows the embedding model to specialize on your data without fine-tuning, which is handy for embedding pieces of code.8. The AWS infrastructureIn Lesson 2, we covered how to deploy the data collection pipeline that is triggered by a link to Medium, Substack, LinkedIn or GitHub   crawls the given link   saves the crawled information to a MongoDB.In Lesson 3, we explained how to deploy the CDC components that emit events to a RabbitMQ queue based on any CRUD operation done to MongoDB.What is left is to deploy the Bytewax streaming pipeline and Qdrant vector DB.We will use Qdrants self-hosted option, which is easy to set up and scale.To test things out, they offer a Free Tier plan for up to a 1GB cluster, which is more than enough for our course.  We explained in our GitHub repository how to configure Qdrant.AWS infrastructure of the feature/streaming pipeline.The last piece of the puzzle is the Bytewax streaming pipeline.As we dont require a GPU and the streaming pipeline needs to run 24/7, we will deploy it to AWS Fargate, a cost-effective serverless solution from AWS.As a serverless solution, Fargate allows us to deploy our code quickly and scale it fast in case of high traffic.How do we deploy the streaming pipeline code to Fargate?Using GitHub Actions, we wrote a CD pipeline that builds a Docker image on every new commit made on the main branch.After, the Docker image is pushed to AWS ECR. Ultimately, Fargate pulls the latest version of the Docker image.This is a common CD pipeline to deploy your code to AWS services.Why not use lambda functions, as we did for the data pipeline?An AWS lambda function executes a function once and then closes down.This worked perfectly for the crawling logic, but it won&#39;t work for our streaming pipeline, which has to run 24/7.9. Run the code locallyTo quickly test things up, we wrote a docker-compose.yaml file to spin up the MongoDB, RabbitMQ queue and Qdrant vector db.You can spin up the Docker containers using our Makefile by running the following:make local-start-infraTo fully test the Bytewax streaming pipeline, you have to start the CDC component by running:make local-start-cdcUltimately, you start the streaming pipeline:make local-bytewaxTo simulate the data collection pipeline, mock it as follows:make local-insert-data-mongoThe README of our GitHub repository provides more details on how to run and set up everything.10. Deploy the code to AWS &amp; Run it from the cloudThis article is already too long, so I wont go into the details of how to deploy the AWS infrastructure described above and test it out here.But to give you some insights, we have used Pulumi as our infrastructure as a code (IaC) tool, which will allow you to spin it quickly with a few commands.Also, I wont let you hang on to this one. We made a promise and  We prepared step-by-step instructions in the README of our GitHub repository on how to use Pulumni to spin up the infrastructure and test it out.ConclusionNow you know how to write streaming pipelines like a PRO!In Lesson 4, you learned how to:design a feature pipeline using the 3-pipeline architecturewrite a streaming pipeline using Bytewax as a streaming engineuse a dispatcher layer to write a modular and flexible application to process multiple types of data (posts, articles, code)load the cleaned and embedded data to Qdrantdeploy the streaming pipeline to AWS  This is only the ingestion part used for fine-tuning LLMs and RAG.In Lesson 5, you will learn how to write a retrieval client for the 3 data types using good SWE practices and improve the retrieval accuracy using advanced retrieval &amp; post-retrieval techniques. See you there!  Check out the code on GitHub [1] and support us with a Enjoyed This Article?Join the Decoding ML Newsletter for battle-tested content on designing, coding, and deploying production-grade ML &amp; MLOps systems. Every week. For FREE  Decoding ML Newsletter | Paul Iusztin | SubstackJoin for battle-tested content on designing, coding, and deploying production-grade ML &amp; MLOps systems. Every week. Fordecodingml.substack.comReferencesLiterature[1] Your LLM Twin Course  GitHub Repository (2024), Decoding ML GitHub Organization[2] Bytewax, Bytewax Landing Page[3] Unstructured Cleaning Examples, Unstructured Documentation[4] Recursively split by character, LangChains Documentation[5] Split by tokens, LangChains Documentation[6] sentence-transformers/all-MiniLM-L6-v2, HuggingFace[7] hkunlp/instructor-xl, HuggingFace[8] Qdrant, Qdrant Documentation[9] Abstract Factory Pattern, Refactoring Guru[10] Strategy Pattern, Refactoring GuruImagesIf not otherwise stated, all images are created by the author.Sign up to discover human stories that deepen your understanding of the world.FreeDistraction-free reading. No ads.Organize your knowledge with lists and highlights.Tell your story. Find your audience.Sign up for freeMembershipAccess the best member-only stories.Support independent authors.Listen to audio narrations.Read offline.Join the Partner Program and earn for your writing.Try for $5/monthMl System DesignMachine LearningArtificial IntelligenceData ScienceSoftware Engineering698698FollowWritten by Paul Iusztin2.4K FollowersEditor for Decoding ML Senior ML Engineer | Helping machine learning engineers design and productionize ML systems. | Decoding ML Newsletter: [URL] from Paul Iusztin and Decoding MLPaul IusztininDecoding MLAn End-to-End Framework for Production-Ready LLM Systems by Building Your LLM TwinFrom data gathering to productionizing LLMs using LLMOps good practices.16 min readMar 16, 20241.5K10Razvant AlexandruinDecoding MLHow to build a Real-Time News Search Engine using Serverless Upstash Kafka and Vector DBA hands-on guide to implementing a live news aggregating streaming pipeline with Apache Kafka, Bytewax, and Upstash Vector Database.19 min readApr 13, 20246873Paul IusztininDecoding MLThe LLMs kit: Build a production-ready real-time financial advisor system using streamingLesson 1: LLM architecture system design using the 3-pipeline pattern12 min readJan 5, 2024383Paul IusztininDecoding MLA Real-time Retrieval System for RAG on Social Media DataUse a streaming engine to populate a vector DB in real-time. Improve RAG accuracy using rerank &amp; UMAP.12 min readMar 30, 2024305See all from Paul IusztinSee all from Decoding MLRecommended from MediumVipra SinghBuilding LLM Applications: Serving LLMs (Part 9)Learn Large Language Models ( LLM ) through the lens of a Retrieval Augmented Generation ( RAG ) Application.49 min readApr 18, 20243741A B Vijay KumarMulti-Agent System\\u200a\\u200aCrew.AIMulti-Agent systems are LLM applications that are changing the automation landscape with intelligent bots.7 min readApr 18, 20241574ListsPredictive Modeling w/ Python20 stories1126 savesNatural Language Processing1402 stories899 savesPractical Guides to Machine Learning10 stories1352 savesdata science and AI40 stories137 savesFabio MatricardiinGenerative AILlama3 is out and you can run it on your Computer!After only 1 day from the release, here is how you can run even on your Laptop with CPU only the latest Meta-AI model.8 min read6 days ago1.2K13Gavin LiinAI AdvancesRun the strongest open-source LLM model: Llama3 70B with just a single 4GB GPU!The strongest open source LLM model Llama3 has been released, Here is how you can run Llama3 70B locally with just 4GB GPU, even on Macbook4 min read4 days ago7982Plaban NayakinThe AI ForumSemantic Chunking for RAGWhat is Chunking\\xa0?17 min read4 days ago1651Damian GilinTowards Data ScienceAdvanced Retriever Techniques to Improve Your RAGsMaster Advanced Information Retrieval: Cutting-edge Techniques to Optimize the Selection of Relevant Documents with Langchain to Create18 min readApr 17, 20245393See more recommendationsHelpStatusAboutCareersBlogPrivacyTermsText to speechTeams\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nTo make Medium work, we log user data. By using Medium, you agree to our Privacy Policy, including cookie policy.&quot;<br>  },<br>  {<br>    &quot;instruction&quot;: &quot;Focus on creating battle-tested content on building production-grade ML systems using good SWE and MLOps practices.&quot;,<br>    &quot;content&quot;: &quot;About Decoding MLThe hub for continuous learning on ML system design, ML engineering, MLOps, LLMs and computer vision.About Decoding ML. The hub for continuous learning on ML | by Paul Iusztin | Decoding ML | MediumOpen in appSign upSign inWriteSign upSign inMastodonAbout Decoding MLThe hub for continuous learning on ML system design, ML engineering, MLOps, LLMs and computer vision.Paul IusztinFollowPublished inDecoding ML2 min readFeb 19, 202491ListenShareDecoding ML is a publication that creates battle-tested content on building production-grade ML systems leveraging good SWE and MLOps practices.Our motto is More engineering, less F1 scores.Following Decoding ML, you will learn about the entire lifecycle of an ML system, from system design to deploying and monitoring.Decoding ML is the hub for continuous learning on:ML system designML engineeringMLOpsLarge language modelsComputer visionWe are all about end-to-end ML use cases that can directly be applied in the real world  no stories  just hands-on content.The minds behind Decoding ML  Alex Vesa (left), Paul Iusztin (middle) and Alexandru Razvant (right)The minds behind Decoding ML are Vesa Alexandru, Paul Iusztin and Razvant Alexandru.Our passion for constantly learning and engineering production-ready ML systems inevitably turned into Decoding ML.With our 10+ years of hands-on experience in the industry in:Data ScienceDeep LearningComputer VisionGenerative AIML InfrastructureMLOpsSoftware Engineeringwe decided it is about time to share it with the world!Why follow?Join Decoding ML for battle-tested content on designing, coding, and deploying production-grade ML &amp; MLOps systems. Every week. For FREE.No more bedtime stories in Jupyter Notebooks.  DML is all about hands-on advice from our 10+ years of experience in AI.We are also on: Newsletter  GitHubSign up to discover human stories that deepen your understanding of the world.FreeDistraction-free reading. No ads.Organize your knowledge with lists and highlights.Tell your story. Find your audience.Sign up for freeMembershipAccess the best member-only stories.Support independent authors.Listen to audio narrations.Read offline.Join the Partner Program and earn for your writing.Try for $5/monthAbout9191FollowWritten by Paul Iusztin2.4K FollowersEditor for Decoding ML Senior ML Engineer | Helping machine learning engineers design and productionize ML systems. | Decoding ML Newsletter: [URL] from Paul Iusztin and Decoding MLPaul IusztininDecoding MLAn End-to-End Framework for Production-Ready LLM Systems by Building Your LLM TwinFrom data gathering to productionizing LLMs using LLMOps good practices.16 min readMar 16, 20241.5K10Razvant AlexandruinDecoding MLHow to build a Real-Time News Search Engine using Serverless Upstash Kafka and Vector DBA hands-on guide to implementing a live news aggregating streaming pipeline with Apache Kafka, Bytewax, and Upstash Vector Database.19 min readApr 13, 20246873Paul IusztininDecoding MLThe LLMs kit: Build a production-ready real-time financial advisor system using streamingLesson 1: LLM architecture system design using the 3-pipeline pattern12 min readJan 5, 2024383Paul IusztininDecoding MLA Real-time Retrieval System for RAG on Social Media DataUse a streaming engine to populate a vector DB in real-time. Improve RAG accuracy using rerank &amp; UMAP.12 min readMar 30, 2024305See all from Paul IusztinSee all from Decoding MLRecommended from MediumQwakHow to Build an End-to-End ML Pipeline in 2024Learn to build an end-to-end ML pipeline and streamline your ML workflows in 2024, from data ingestion to model deployment and performance24 min readApr 7, 20242071Paul IusztininDecoding MLThe LLMs kit: Build a production-ready real-time financial advisor system using streamingLesson 1: LLM architecture system design using the 3-pipeline pattern12 min readJan 5, 2024383ListsMedium&#39;s Huge List of Publications Accepting Submissions285 stories2516 savesYesmine RouisinTheFork Engineering BlogA Guide to MLOps with Airflow and MLflowIntroduction11 min readNov 6, 2023319ManralaiMastering MLOps for FreeYour Go-To GitHub Repositories Collection4 min readJan 28, 20246463Vipra SinghBuilding LLM Applications: Evaluation (Part 8)Learn Large Language Models ( LLM ) through the lens of a Retrieval Augmented Generation ( RAG ) Application.47 min readApr 8, 20241891Ramazan OlmezEnd-to-End Machine Learning Project: Churn PredictionThe main objective of this article is to develop an end-to-end machine learning project. For a model to be truly useful, it needs to be18 min readFeb 22, 202487See more recommendationsHelpStatusAboutCareersBlogPrivacyTermsText to speechTeams\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nTo make Medium work, we log user data. By using Medium, you agree to our Privacy Policy, including cookie policy.&quot;<br>  },<br>  {<br>    &quot;instruction&quot;: &quot;Design and build a production-ready feature pipeline using Bytewax as a stream engine to process data in real-time, ingest data from a RabbitMQ queue, implement SWE practices to process multiple data types, clean, chunk, and embed data for LLM fine-tuning and RAG, and load features to a Qdrant vector DB.&quot;,<br>    &quot;content&quot;: &quot;SOTA Python Streaming Pipelines for Fine-tuning LLMs and RAG \\u2014 in Real-Time!Use a Python streaming engine to populate a feature store from 4+ data sourcesStreaming Pipelines for LLMs and RAG | Decoding MLOpen in appSign upSign inWriteSign upSign inMastodonLLM TWIN COURSE: BUILDING YOUR PRODUCTION-READY AI REPLICASOTA Python Streaming Pipelines for Fine-tuning LLMs and RAG  in Real-Time!Use a Python streaming engine to populate a feature store from 4+ data sourcesPaul IusztinFollowPublished inDecoding ML18 min read6 days ago698ListenShare  the 4th out of 11 lessons of the LLM Twin free courseWhat is your LLM Twin? It is an AI character that writes like yourself by incorporating your style, personality and voice into an LLM.Image by DALL-EWhy is this course different?By finishing the LLM Twin: Building Your Production-Ready AI Replica free course, you will learn how to design, train, and deploy a production-ready LLM twin of yourself powered by LLMs, vector DBs, and LLMOps good practices.Why should you care? \\U0001faf5  No more isolated scripts or Notebooks! Learn production ML by building and deploying an end-to-end production-grade LLM system.What will you learn to build by the end of this course?You will learn how to architect and build a real-world LLM system from start to finish  from data collection to deployment.You will also learn to leverage MLOps best practices, such as experiment trackers, model registries, prompt monitoring, and versioning.The end goal? Build and deploy your own LLM twin.The architecture of the LLM twin is split into 4 Python microservices:the data collection pipeline: crawl your digital data from various social media platforms. Clean, normalize and load the data to a NoSQL DB through a series of ETL pipelines. Send database changes to a queue using the CDC pattern. (deployed on AWS)the feature pipeline: consume messages from a queue through a Bytewax streaming pipeline. Every message will be cleaned, chunked, embedded (using Superlinked), and loaded into a Qdrant vector DB in real-time. (deployed on AWS)the training pipeline: create a custom dataset based on your digital data. Fine-tune an LLM using QLoRA. Use Comet MLs experiment tracker to monitor the experiments. Evaluate and save the best model to Comets model registry. (deployed on Qwak)the inference pipeline: load and quantize the fine-tuned LLM from Comets model registry. Deploy it as a REST API. Enhance the prompts using RAG. Generate content using your LLM twin. Monitor the LLM using Comets prompt monitoring dashboard. (deployed on Qwak)LLM twin system architecture [Image by the Author]Along the 4 microservices, you will learn to integrate 3 serverless tools:Comet ML as your ML Platform;Qdrant as your vector DB;Qwak as your ML infrastructure;Who is this for?Audience: MLE, DE, DS, or SWE who want to learn to engineer production-ready LLM systems using LLMOps good principles.Level: intermediatePrerequisites: basic knowledge of Python, ML, and the cloudHow will you learn?The course contains 11 hands-on written lessons and the open-source code you can access on GitHub.You can read everything at your own pace.  To get the most out of this course, we encourage you to clone and run the repository while you cover the lessons.Costs?The articles and code are completely free. They will always remain free.But if you plan to run the code while reading it, you have to know that we use several cloud tools that might generate additional costs.The cloud computing platforms (AWS, Qwak) have a pay-as-you-go pricing plan. Qwak offers a few hours of free computing. Thus, we did our best to keep costs to a minimum.For the other serverless tools (Qdrant, Comet), we will stick to their freemium version, which is free of charge.Meet your teachers!The course is created under the Decoding ML umbrella by:Paul Iusztin | Senior ML &amp; MLOps EngineerAlex Vesa | Senior AI EngineerAlex Razvant | Senior ML &amp; MLOps EngineerLessonsThe course is split into 11 lessons. Every Medium article will be its own lesson.An End-to-End Framework for Production-Ready LLM Systems by Building Your LLM TwinThe Importance of Data Pipelines in the Era of Generative AIChange Data Capture: Enabling Event-Driven ArchitecturesSOTA Python Streaming Pipelines for Fine-tuning LLMs and RAG  in Real-Time!Vector DB retrieval clients [Module 2] WIPTraining data preparation [Module 3] WIPFine-tuning LLM [Module 3] WIPLLM evaluation [Module 4] WIPQuantization [Module 5] WIPBuild the digital twin inference pipeline [Module 6] WIPDeploy the digital twin as a REST API [Module 6] WIP  Check out the code on GitHub [1] and support us with a Lets start with Lesson 4  Lesson 4: Python Streaming Pipelines for Fine-tuning LLMs and RAG  in Real-Time!In the 4th lesson, we will focus on the feature pipeline.The feature pipeline is the first pipeline presented in the 3 pipeline architecture: feature, training and inference pipelines.A feature pipeline is responsible for taking raw data as input, processing it into features, and storing it in a feature store, from which the training &amp; inference pipelines will use it.The component is completely isolated from the training and inference code. All the communication is done through the feature store.To avoid repeating myself, if you are unfamiliar with the 3 pipeline architecture, check out Lesson 1 for a refresher.By the end of this article, you will learn to design and build a production-ready feature pipeline that:uses Bytewax as a stream engine to process data in real-time;ingests data from a RabbitMQ queue;uses SWE practices to process multiple data types: posts, articles, code;cleans, chunks, and embeds data for LLM fine-tuning and RAG;loads the features to a Qdrant vector DB.Note: In our use case, the feature pipeline is also a streaming pipeline, as we use a Bytewax streaming engine. Thus, we will use these words interchangeably.We will wrap up Lesson 4 by showing you how to deploy the feature pipeline to AWS and integrate it with the components from previous lessons: data collection pipeline, MongoDB, and CDC.In the 5th lesson, we will go through the vector DB retrieval client, where we will teach you how to query the vector DB and improve the accuracy of the results using advanced retrieval techniques.Excited? Lets get started!The architecture of the feature/streaming pipeline.Table of ContentsWhy are we doing this?System design of the feature pipelineThe Bytewax streaming flowPydantic data modelsLoad data to QdrantThe dispatcher layerPreprocessing steps: Clean, chunk, embedThe AWS infrastructureRun the code locallyDeploy the code to AWS &amp; Run it from the cloudConclusion  Check out the code on GitHub [1] and support us with a 1. Why are we doing this?A quick reminder from previous lessonsTo give you some context, in Lesson 2, we crawl data from LinkedIn, Medium, and GitHub, normalize it, and load it to MongoDB.In Lesson 3, we are using CDC to listen to changes to the MongoDB database and emit events in a RabbitMQ queue based on any CRUD operation done on MongoDB.and here we are in Lesson 4, where we are building the feature pipeline that listens 24/7 to the RabbitMQ queue for new events to process and load them to a Qdrant vector DB.The problem we are solvingIn our LLM Twin use case, the feature pipeline constantly syncs the MongoDB warehouse with the Qdrant vector DB while processing the raw data into features.Important: In our use case, the Qdrant vector DB will be our feature store.Why we are solving itThe feature store will be the central point of access for all the features used within the training and inference pipelines.For consistency and simplicity, we will refer to different formats of our text data as features.  The training pipeline will use the feature store to create fine-tuning datasets for your LLM twin.  The inference pipeline will use the feature store for RAG.For reliable results (especially for RAG), the data from the vector DB must always be in sync with the data from the data warehouse.The question is, what is the best way to sync these 2?Other potential solutionsThe most common solution is probably to use a batch pipeline that constantly polls from the warehouse, computes a difference between the 2 databases, and updates the target database.The issue with this technique is that computing the difference between the 2 databases is extremely slow and costly.Another solution is to use a push technique using a webhook. Thus, on any CRUD change in the warehouse, you also update the source DB.The biggest issue here is that if the webhook fails, you have to implement complex recovery logic.Lesson 3 on CDC covers more of this.2. System design of the feature pipeline: our solutionOur solution is based on CDC, a queue, a streaming engine, and a vector DB:  CDC adds any change made to the Mongo DB to the queue (read more in Lesson 3).  the RabbitMQ queue stores all the events until they are processed.  The Bytewax streaming engine cleans, chunks, and embeds the data.  A streaming engine works naturally with a queue-based system.  The data is uploaded to a Qdrant vector DB on the flyWhy is this powerful?Here are 4 core reasons:The data is processed in real-time.Out-of-the-box recovery system: If the streaming pipeline fails to process a message will be added back to the queueLightweight: No need for any diffs between databases or batching too many recordsNo I/O bottlenecks on the source database  It solves all our problems!The architecture of the feature/streaming pipeline.How is the data stored?We store 2 snapshots of our data in the feature store. Here is why  Remember that we said that the training and inference pipeline will access the features only from the feature store, which, in our case, is the Qdrant vector DB?Well, if we had stored only the chunked &amp; embedded version of the data, that would have been useful only for RAG but not for fine-tuning.Thus, we make an additional snapshot of the cleaned data, which will be used by the training pipeline.Afterward, we pass it down the streaming flow for chunking &amp; embedding.How do we process multiple data types?How do you process multiple types of data in a single streaming pipeline without writing spaghetti code?Yes, that is for you, data scientists! Jokingam I?We have 3 data types: posts, articles, and code.Each data type (and its state) will be modeled using Pydantic models.To process them we will write a dispatcher layer, which will use a creational factory pattern [9] to instantiate a handler implemented for that specific data type (post, article, code) and operation (cleaning, chunking, embedding).The handler follows the strategy behavioral pattern [10].Intuitively, you can see the combination between the factory and strategy patterns as follows:Initially, we know we want to clean the data, but as we dont know the data type, we cant know how to do so.What we can do, is write the whole code around the cleaning code and abstract away the login under a Handler() interface (aka the strategy).When we get a data point, the factory class creates the right cleaning handler based on its type.Ultimately the handler is injected into the rest of the system and executed.By doing so, we can easily isolate the logic for a given data type &amp; operation while leveraging polymorphism to avoid filling up the code with 1000x if else statements.We will dig into the implementation in future sections.Streaming over batchYou may ask why we need a streaming engine instead of implementing a batch job that polls the messages at a given frequency.That is a valid question.The thing is thatNowadays, using tools such as Bytewax makes implementing streaming pipelines a lot more frictionless than using their JVM alternatives.The key aspect of choosing a streaming vs. a batch design is real-time synchronization between your source and destination DBs.In our particular case, we will process social media data, which changes fast and irregularly.Also, for our digital twin, it is important to do RAG on up-to-date data. We dont want to have any delay between what happens in the real world and what your LLM twin sees.That being said choosing a streaming architecture seemed natural in our use case.3. The Bytewax streaming flowThe Bytewax flow is the central point of the streaming pipeline. It defines all the required steps, following the next simplified pattern: input -&gt; processing -&gt; output.As I come from the AI world, I like to see it as the graph of the streaming pipeline, where you use the input(), map(), and output() Bytewax functions to define your graph, which in the Bytewax world is called a flow.As you can see in the code snippet below, we ingest posts, articles or code messages from a RabbitMQ queue. After we clean, chunk and embed them. Ultimately, we load the cleaned and embedded data to a Qdrant vector DB, which in our LLM twin use case will represent the feature store of our system.To structure and validate the data, between each Bytewax step, we map and pass a different Pydantic model based on its current state: raw, cleaned, chunked, or embedded.Bytewax flow   GitHub Code We have a single streaming pipeline that processes everything.As we ingest multiple data types (posts, articles, or code snapshots), we have to process them differently.To do this the right way, we implemented a dispatcher layer that knows how to apply data-specific operations based on the type of message.More on this in the next sections  Why Bytewax?Bytewax is an open-source streaming processing framework that:- is built in Rust  for performance- has Python   bindings for leveraging its powerful ML ecosystem so, for all the Python fanatics out there, no more JVM headaches for you.Jokes aside, here is why Bytewax is so powerful  - Bytewax local setup is plug-and-play- can quickly be integrated into any Python project (you can go wild  even use it in Notebooks)- can easily be integrated with other Python packages (NumPy, PyTorch, HuggingFace, OpenCV, SkLearn, you name it)- out-of-the-box connectors for Kafka and local files, or you can quickly implement your ownWe used Bytewax to build the streaming pipeline for the LLM Twin course and loved it.To learn more about Bytewax, go and check them out. They are open source, so no strings attached   Bytewax [2] 4. Pydantic data modelsLets take a look at what our Pydantic models look like.First, we defined a set of base abstract models for using the same parent class across all our components.Pydantic base model structure   GitHub Code Afterward, we defined a hierarchy of Pydantic models for:all our data types: posts, articles, or codeall our states: raw, cleaned, chunked, and embeddedThis is how the set of classes for the posts will look like  Pydantic posts model structure   GitHub Code We repeated the same process for the articles and code model hierarchy.Check out the other data classes on our GitHub.Why is keeping our data in Pydantic models so powerful?There are 4 main criteria:every field has an enforced type: you are ensured the data types are going to be correctthe fields are automatically validated based on their type: for example, if the field is a string and you pass an int, it will through an errorthe data structure is clear and verbose: no more clandestine dicts that you never know what is in themyou make your data the first-class citizen of your program5. Load data to QdrantThe first step is to implement our custom Bytewax DynamicSink class  Qdrant DynamicSink   GitHub Code Next, for every type of operation we need (output cleaned or embedded data ) we have to subclass the StatelessSinkPartition Bytewax class (they also provide a stateful option   more in their docs)An instance of the class will run on every partition defined within the Bytewax deployment.In the course, we are using a single partition per worker. But, by adding more partitions (and workers), you can quickly scale your Bytewax pipeline horizontally.Qdrant worker partitions   GitHub Code Note that we used Qdrants Batch method to upload all the available points at once. By doing so, we reduce the latency on the network I/O side: more on that here [8] The RabbitMQ streaming input follows a similar pattern. Check it out here 6. The dispatcher layerNow that we have the Bytewax flow and all our data models.How do we map a raw data model to a cleaned data model?  All our domain logic is modeled by a set of Handler() classes.For example, this is how the handler used to map a PostsRawModel to a PostCleanedModel looks like  Handler hierarchy of classes   GitHub Code Check out the other handlers on our GitHub:  ChunkingDataHandler and EmbeddingDataHandlerIn the next sections, we will explore the exact cleaning, chunking and embedding logic.Now, to build our dispatcher, we need 2 last components:a factory class: instantiates the right handler based on the type of the eventa dispatcher class: the glue code that calls the factory class and handlerHere is what the cleaning dispatcher and factory look like  The dispatcher and factory classes   GitHub Code Check out the other dispatchers on our GitHub.By repeating the same logic, we will end up with the following set of dispatchers:RawDispatcher (no factory class required as the data is not processed)CleaningDispatcher (with a ChunkingHandlerFactory class)ChunkingDispatcher (with a ChunkingHandlerFactory class)EmbeddingDispatcher (with an EmbeddingHandlerFactory class)7. Preprocessing steps: Clean, chunk, embedHere we will focus on the concrete logic used to clean, chunk, and embed a data point.Note that this logic is wrapped by our handler to be integrated into our dispatcher layer using the Strategy behavioral pattern [10].We already described that in the previous section. Thus, we will directly jump into the actual logic here, which can be found in the utils module of our GitHub repository.Note: These steps are experimental. Thus, what we present here is just the first iteration of the system. In a real-world scenario, you would experiment with different cleaning, chunking or model versions to improve it on your data.CleaningThis is the main utility function used to clean the text for our posts, articles, and code.Out of simplicity, we used the same logic for all the data types, but after more investigation, you would probably need to adapt it to your specific needs.For example, your posts might start containing some weird characters, and you dont want to run the unbold_text() or unitalic_text() functions on your code data point as is completely redundant.Cleaning logic   GitHub Code Most of the functions above are from the unstructured [3] Python package. It is a great tool for quickly finding utilities to clean text data.  More examples of unstructured here [3] One key thing to notice is that at the cleaning step, we just want to remove all the weird, non-interpretable characters from the text.Also, we want to remove redundant data, such as extra whitespace or URLs, as they do not provide much value.These steps are critical for our tokenizer to understand and efficiently transform our string input into numbers that will be fed into the transformer models.Note that when using bigger models (transformers) + modern tokenization techniques, you dont need to standardize your dataset too much.For example, it is redundant to apply lemmatization or stemming, as the tokenizer knows how to split your input into a commonly used sequence of characters efficiently, and the transformers can pick up the nuances of the words.  What is important at the cleaning step is to throw out the noise.ChunkingWe are using Langchain to chunk our text.We use a 2 step strategy using Langchains RecursiveCharacterTextSplitter [4] and SentenceTransformersTokenTextSplitter [5]. As seen below  Chunking logic   GitHub Code Overlapping your chunks is a common pre-indexing RAG technique, which helps to cluster chunks from the same document semantically.Again, we are using the same chunking logic for all of our data types, but to get the most out of it, we would probably need to tweak the separators, chunk_size, and chunk_overlap parameters for our different use cases.But our dispatcher + handler architecture would easily allow us to configure the chunking step in future iterations.EmbeddingThe data preprocessing, aka the hard part is done.Now we just have to call an embedding model to create our vectors.Embedding logic   GitHub Code We used the all-MiniLm-L6-v2 [6] from the sentence-transformers library to embed our articles and posts: a lightweight embedding model that can easily run in real-time on a 2 vCPU machine.As the code data points contain more complex relationships and specific jargon to embed, we used a more powerful embedding model: hkunlp/instructor-xl [7].This embedding model is unique as it can be customized on the fly with instructions based on your particular data. This allows the embedding model to specialize on your data without fine-tuning, which is handy for embedding pieces of code.8. The AWS infrastructureIn Lesson 2, we covered how to deploy the data collection pipeline that is triggered by a link to Medium, Substack, LinkedIn or GitHub   crawls the given link   saves the crawled information to a MongoDB.In Lesson 3, we explained how to deploy the CDC components that emit events to a RabbitMQ queue based on any CRUD operation done to MongoDB.What is left is to deploy the Bytewax streaming pipeline and Qdrant vector DB.We will use Qdrants self-hosted option, which is easy to set up and scale.To test things out, they offer a Free Tier plan for up to a 1GB cluster, which is more than enough for our course.  We explained in our GitHub repository how to configure Qdrant.AWS infrastructure of the feature/streaming pipeline.The last piece of the puzzle is the Bytewax streaming pipeline.As we dont require a GPU and the streaming pipeline needs to run 24/7, we will deploy it to AWS Fargate, a cost-effective serverless solution from AWS.As a serverless solution, Fargate allows us to deploy our code quickly and scale it fast in case of high traffic.How do we deploy the streaming pipeline code to Fargate?Using GitHub Actions, we wrote a CD pipeline that builds a Docker image on every new commit made on the main branch.After, the Docker image is pushed to AWS ECR. Ultimately, Fargate pulls the latest version of the Docker image.This is a common CD pipeline to deploy your code to AWS services.Why not use lambda functions, as we did for the data pipeline?An AWS lambda function executes a function once and then closes down.This worked perfectly for the crawling logic, but it won&#39;t work for our streaming pipeline, which has to run 24/7.9. Run the code locallyTo quickly test things up, we wrote a docker-compose.yaml file to spin up the MongoDB, RabbitMQ queue and Qdrant vector db.You can spin up the Docker containers using our Makefile by running the following:make local-start-infraTo fully test the Bytewax streaming pipeline, you have to start the CDC component by running:make local-start-cdcUltimately, you start the streaming pipeline:make local-bytewaxTo simulate the data collection pipeline, mock it as follows:make local-insert-data-mongoThe README of our GitHub repository provides more details on how to run and set up everything.10. Deploy the code to AWS &amp; Run it from the cloudThis article is already too long, so I wont go into the details of how to deploy the AWS infrastructure described above and test it out here.But to give you some insights, we have used Pulumi as our infrastructure as a code (IaC) tool, which will allow you to spin it quickly with a few commands.Also, I wont let you hang on to this one. We made a promise and  We prepared step-by-step instructions in the README of our GitHub repository on how to use Pulumni to spin up the infrastructure and test it out.ConclusionNow you know how to write streaming pipelines like a PRO!In Lesson 4, you learned how to:design a feature pipeline using the 3-pipeline architecturewrite a streaming pipeline using Bytewax as a streaming engineuse a dispatcher layer to write a modular and flexible application to process multiple types of data (posts, articles, code)load the cleaned and embedded data to Qdrantdeploy the streaming pipeline to AWS  This is only the ingestion part used for fine-tuning LLMs and RAG.In Lesson 5, you will learn how to write a retrieval client for the 3 data types using good SWE practices and improve the retrieval accuracy using advanced retrieval &amp; post-retrieval techniques. See you there!  Check out the code on GitHub [1] and support us with a Enjoyed This Article?Join the Decoding ML Newsletter for battle-tested content on designing, coding, and deploying production-grade ML &amp; MLOps systems. Every week. For FREE  Decoding ML Newsletter | Paul Iusztin | SubstackJoin for battle-tested content on designing, coding, and deploying production-grade ML &amp; MLOps systems. Every week. Fordecodingml.substack.comReferencesLiterature[1] Your LLM Twin Course  GitHub Repository (2024), Decoding ML GitHub Organization[2] Bytewax, Bytewax Landing Page[3] Unstructured Cleaning Examples, Unstructured Documentation[4] Recursively split by character, LangChains Documentation[5] Split by tokens, LangChains Documentation[6] sentence-transformers/all-MiniLM-L6-v2, HuggingFace[7] hkunlp/instructor-xl, HuggingFace[8] Qdrant, Qdrant Documentation[9] Abstract Factory Pattern, Refactoring Guru[10] Strategy Pattern, Refactoring GuruImagesIf not otherwise stated, all images are created by the author.Sign up to discover human stories that deepen your understanding of the world.FreeDistraction-free reading. No ads.Organize your knowledge with lists and highlights.Tell your story. Find your audience.Sign up for freeMembershipAccess the best member-only stories.Support independent authors.Listen to audio narrations.Read offline.Join the Partner Program and earn for your writing.Try for $5/monthMl System DesignMachine LearningArtificial IntelligenceData ScienceSoftware Engineering698698FollowWritten by Paul Iusztin2.4K FollowersEditor for Decoding ML Senior ML Engineer | Helping machine learning engineers design and productionize ML systems. | Decoding ML Newsletter: [URL] from Paul Iusztin and Decoding MLPaul IusztininDecoding MLAn End-to-End Framework for Production-Ready LLM Systems by Building Your LLM TwinFrom data gathering to productionizing LLMs using LLMOps good practices.16 min readMar 16, 20241.5K10Razvant AlexandruinDecoding MLHow to build a Real-Time News Search Engine using Serverless Upstash Kafka and Vector DBA hands-on guide to implementing a live news aggregating streaming pipeline with Apache Kafka, Bytewax, and Upstash Vector Database.19 min readApr 13, 20246873Paul IusztininDecoding MLThe LLMs kit: Build a production-ready real-time financial advisor system using streamingLesson 1: LLM architecture system design using the 3-pipeline pattern12 min readJan 5, 2024383Paul IusztininDecoding MLA Real-time Retrieval System for RAG on Social Media DataUse a streaming engine to populate a vector DB in real-time. Improve RAG accuracy using rerank &amp; UMAP.12 min readMar 30, 2024305See all from Paul IusztinSee all from Decoding MLRecommended from MediumVipra SinghBuilding LLM Applications: Serving LLMs (Part 9)Learn Large Language Models ( LLM ) through the lens of a Retrieval Augmented Generation ( RAG ) Application.49 min readApr 18, 20243741A B Vijay KumarMulti-Agent System\\u200a\\u200aCrew.AIMulti-Agent systems are LLM applications that are changing the automation landscape with intelligent bots.7 min readApr 18, 20241574ListsPredictive Modeling w/ Python20 stories1126 savesNatural Language Processing1402 stories899 savesPractical Guides to Machine Learning10 stories1352 savesdata science and AI40 stories137 savesFabio MatricardiinGenerative AILlama3 is out and you can run it on your Computer!After only 1 day from the release, here is how you can run even on your Laptop with CPU only the latest Meta-AI model.8 min read6 days ago1.2K13Gavin LiinAI AdvancesRun the strongest open-source LLM model: Llama3 70B with just a single 4GB GPU!The strongest open source LLM model Llama3 has been released, Here is how you can run Llama3 70B locally with just 4GB GPU, even on Macbook4 min read4 days ago7982Plaban NayakinThe AI ForumSemantic Chunking for RAGWhat is Chunking\\xa0?17 min read4 days ago1651Damian GilinTowards Data ScienceAdvanced Retriever Techniques to Improve Your RAGsMaster Advanced Information Retrieval: Cutting-edge Techniques to Optimize the Selection of Relevant Documents with Langchain to Create18 min readApr 17, 20245393See more recommendationsHelpStatusAboutCareersBlogPrivacyTermsText to speechTeams\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nTo make Medium work, we log user data. By using Medium, you agree to our Privacy Policy, including cookie policy.&quot;<br>  },<br>  {<br>    &quot;instruction&quot;: &quot;Generate a publication that offers battle-tested content on building production-grade ML systems leveraging good SWE and MLOps practices. Follow for learning about the entire lifecycle of an ML system.&quot;,<br>    &quot;content&quot;: &quot;About Decoding MLThe hub for continuous learning on ML system design, ML engineering, MLOps, LLMs and computer vision.About Decoding ML. The hub for continuous learning on ML | by Paul Iusztin | Decoding ML | MediumOpen in appSign upSign inWriteSign upSign inMastodonAbout Decoding MLThe hub for continuous learning on ML system design, ML engineering, MLOps, LLMs and computer vision.Paul IusztinFollowPublished inDecoding ML2 min readFeb 19, 202491ListenShareDecoding ML is a publication that creates battle-tested content on building production-grade ML systems leveraging good SWE and MLOps practices.Our motto is More engineering, less F1 scores.Following Decoding ML, you will learn about the entire lifecycle of an ML system, from system design to deploying and monitoring.Decoding ML is the hub for continuous learning on:ML system designML engineeringMLOpsLarge language modelsComputer visionWe are all about end-to-end ML use cases that can directly be applied in the real world  no stories  just hands-on content.The minds behind Decoding ML  Alex Vesa (left), Paul Iusztin (middle) and Alexandru Razvant (right)The minds behind Decoding ML are Vesa Alexandru, Paul Iusztin and Razvant Alexandru.Our passion for constantly learning and engineering production-ready ML systems inevitably turned into Decoding ML.With our 10+ years of hands-on experience in the industry in:Data ScienceDeep LearningComputer VisionGenerative AIML InfrastructureMLOpsSoftware Engineeringwe decided it is about time to share it with the world!Why follow?Join Decoding ML for battle-tested content on designing, coding, and deploying production-grade ML &amp; MLOps systems. Every week. For FREE.No more bedtime stories in Jupyter Notebooks.  DML is all about hands-on advice from our 10+ years of experience in AI.We are also on: Newsletter  GitHubSign up to discover human stories that deepen your understanding of the world.FreeDistraction-free reading. No ads.Organize your knowledge with lists and highlights.Tell your story. Find your audience.Sign up for freeMembershipAccess the best member-only stories.Support independent authors.Listen to audio narrations.Read offline.Join the Partner Program and earn for your writing.Try for $5/monthAbout9191FollowWritten by Paul Iusztin2.4K FollowersEditor for Decoding ML Senior ML Engineer | Helping machine learning engineers design and productionize ML systems. | Decoding ML Newsletter: [URL] from Paul Iusztin and Decoding MLPaul IusztininDecoding MLAn End-to-End Framework for Production-Ready LLM Systems by Building Your LLM TwinFrom data gathering to productionizing LLMs using LLMOps good practices.16 min readMar 16, 20241.5K10Razvant AlexandruinDecoding MLHow to build a Real-Time News Search Engine using Serverless Upstash Kafka and Vector DBA hands-on guide to implementing a live news aggregating streaming pipeline with Apache Kafka, Bytewax, and Upstash Vector Database.19 min readApr 13, 20246873Paul IusztininDecoding MLThe LLMs kit: Build a production-ready real-time financial advisor system using streamingLesson 1: LLM architecture system design using the 3-pipeline pattern12 min readJan 5, 2024383Paul IusztininDecoding MLA Real-time Retrieval System for RAG on Social Media DataUse a streaming engine to populate a vector DB in real-time. Improve RAG accuracy using rerank &amp; UMAP.12 min readMar 30, 2024305See all from Paul IusztinSee all from Decoding MLRecommended from MediumQwakHow to Build an End-to-End ML Pipeline in 2024Learn to build an end-to-end ML pipeline and streamline your ML workflows in 2024, from data ingestion to model deployment and performance24 min readApr 7, 20242071Paul IusztininDecoding MLThe LLMs kit: Build a production-ready real-time financial advisor system using streamingLesson 1: LLM architecture system design using the 3-pipeline pattern12 min readJan 5, 2024383ListsMedium&#39;s Huge List of Publications Accepting Submissions285 stories2516 savesYesmine RouisinTheFork Engineering BlogA Guide to MLOps with Airflow and MLflowIntroduction11 min readNov 6, 2023319ManralaiMastering MLOps for FreeYour Go-To GitHub Repositories Collection4 min readJan 28, 20246463Vipra SinghBuilding LLM Applications: Evaluation (Part 8)Learn Large Language Models ( LLM ) through the lens of a Retrieval Augmented Generation ( RAG ) Application.47 min readApr 8, 20241891Ramazan OlmezEnd-to-End Machine Learning Project: Churn PredictionThe main objective of this article is to develop an end-to-end machine learning project. For a model to be truly useful, it needs to be18 min readFeb 22, 202487See more recommendationsHelpStatusAboutCareersBlogPrivacyTermsText to speechTeams\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nTo make Medium work, we log user data. By using Medium, you agree to our Privacy Policy, including cookie policy.&quot;<br>  }<br>]</pre><h3>Conclusion</h3><p>In <strong>Lesson 6</strong>, you <strong>learned how</strong> to:</p><ul><li><strong>understanding fine-tuning importance</strong></li><li><strong>use an LLM to generate instructions for crawled data</strong></li><li><strong>load the cleaned and embedded data to</strong> <a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">Qdrant</a></li><li><strong>dataset quality is crucial</strong></li><li><strong>data versioning with </strong><a href="https://www.comet.com/signup/?utm_source=decoding_ml&amp;utm_medium=partner&amp;utm_content=medium"><strong>CometML</strong></a>: Implementing data versioning using CometML ensures reproducibility of experiments, aids in model diagnostics, and supports regulatory compliance. This is crucial for maintaining a robust and traceable MLOps workflow.</li></ul><p>In <a href="https://medium.com/decodingml/how-to-fine-tune-llms-on-custom-datasets-at-scale-using-qwak-and-cometml-12216a777c34"><strong>Lesson</strong> 7</a>, you will learn how <em>to use the generated dataset to finetune a Mistral-7b for content generation </em>building and deploying the training pipeline to <a href="https://mlengineering.medium.com/"><strong><em>Qwak</em></strong></a><em> </em>an AI serverless platform<em>.</em></p><p>🔗 <strong>Check out</strong> <a href="https://github.com/decodingml/llm-twin-course">the code on GitHub</a> [1] and support us with a ⭐️</p><h3>Enjoyed This Article?</h3><p><em>Join the </em><a href="https://decodingml.substack.com/"><strong><em>Decoding ML Newsletter</em></strong></a><em> for </em><strong><em>battle-tested content</em></strong><em> on designing, coding, and deploying </em><strong><em>production-grade ML &amp; MLOps systems</em></strong><em>. Every week. For FREE </em>↓</p><p><a href="https://decodingml.substack.com/">Decoding ML | Paul Iusztin | Substack</a></p><h3>References</h3><h4>Literature</h4><p>[1] <a href="https://github.com/decodingml/llm-twin-course">Your LLM Twin Course — GitHub Repository</a> (2024), Decoding ML GitHub Organization<br>[2] <a href="https://neptune.ai/blog/best-mlflow-alternatives">MLFlow Alternatives</a>, Neptune.ai</p><h3>Images</h3><p>If not otherwise stated, all images are created by the author.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22bd60afd4b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Change Data Capture: Enabling Event-Driven Architectures]]></title>
            <link>https://medium.com/@vesaalexandru95/the-3nd-out-of-11-lessons-of-the-llm-twin-free-course-ba82752dad5a?source=rss-a0286b59c498------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba82752dad5a</guid>
            <category><![CDATA[ml-system-design]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Vesa Alexandru]]></dc:creator>
            <pubDate>Sat, 06 Apr 2024 06:42:26 GMT</pubDate>
            <atom:updated>2024-08-20T11:38:28.440Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://medium.com/decodingml/llm-twin-course/home">LLM TWIN COURSE: BUILDING YOUR PRODUCTION-READY AI REPLICA</a></h4><h4>Transforming Data Streams: The Core of Event-Driven Architectures</h4><p><em>→ the 3rd out of 12 lessons of </em><a href="https://medium.com/decodingml/llm-twin-course/home"><strong><em>the LLM Twin</em></strong></a><em> free course</em></p><p><strong>What is your LLM Twin?</strong> It is an AI character that writes like yourself by incorporating your style, personality and voice into an LLM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*FLQSWJLO_dwYZBbg.png" /><figcaption>Image by DALL-E</figcaption></figure><h3>Why is this course different?</h3><p><em>By finishing the “</em><a href="https://medium.com/decodingml/llm-twin-course/home"><strong><em>LLM Twin: Building Your Production-Ready AI Replica</em></strong></a><strong><em>”</em> </strong><em>free course, you will learn how to design, train, and deploy a production-ready LLM twin of yourself powered by LLMs, vector DBs, and LLMOps good practices</em>.</p><blockquote><strong>Why should you care? 🫵</strong></blockquote><blockquote><strong><em>→ No more isolated scripts or Notebooks!</em></strong><em> Learn production ML by building and deploying an end-to-end production-grade LLM system.</em></blockquote><h3>What will you learn to build by the end of this course?</h3><p>You will <strong>learn</strong> how to <strong>architect </strong>and<strong> build a real-world LLM system</strong> from <strong>start</strong> to <strong>finish</strong> — from <strong>data collection</strong> to <strong>deployment</strong>.</p><p>You will also <strong>learn</strong> to <strong>leverage MLOps best practices</strong>, such as experiment trackers, model registries, prompt monitoring, and versioning.</p><p><strong>The end goal?</strong> Build and deploy your own LLM twin.</p><p><strong>What is an LLM Twin?</strong> It is an AI character that learns to write like somebody by incorporating its style and personality into an LLM.</p><p><em>The </em><strong><em>architecture</em></strong><em> of the </em><strong><em>LLM twin</em></strong><em> is split into </em><strong><em>4 Python microservices</em></strong><em>:</em></p><ol><li><strong><em>the data collection pipeline:</em></strong> crawl your digital data from various social media platforms. Clean, normalize and load the data to a NoSQL DB through a series of ETL pipelines. Send database changes to a queue using the CDC pattern. (deployed on AWS)</li><li><strong><em>the feature pipeline:</em></strong> consume messages from a queue through a Bytewax streaming pipeline. Every message will be cleaned, chunked, embedded (using Superlinked), and loaded into a Qdrant vector DB in real-time. (deployed on AWS)</li><li><strong><em>the training pipeline:</em></strong><em> </em>create a custom dataset based on your digital data.<em> </em>Fine-tune an LLM using QLoRA. Use Comet ML’s experiment tracker to monitor the experiments. Evaluate and save the best model to Comet’s model registry. (deployed on Qwak)</li><li><strong><em>the inference pipeline:</em></strong> load and quantize the fine-tuned LLM from Comet’s model registry. Deploy it as a REST API. Enhance the prompts using RAG. Generate content using your LLM twin. Monitor the LLM using Comet’s prompt monitoring dashboard (deployed on Qwak)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*CcZotQi-PxtOLjuy.png" /><figcaption>LLM twin system architecture [Image by the Author]</figcaption></figure><p>Along the 4 microservices, you will learn to integrate 3 serverless tools:</p><ul><li><a href="https://www.comet.com/signup/?utm_source=decoding_ml&amp;utm_medium=partner&amp;utm_content=medium">Comet ML </a>as your ML Platform;</li><li><a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">Qdrant</a> as your vector DB;</li><li><a href="https://www.qwak.com/lp/end-to-end-mlops/?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=decodingml">Qwak</a> as your ML infrastructure;</li></ul><h3>Who is this for?</h3><p><strong>Audience:</strong> MLE, DE, DS, or SWE who want to learn to engineer production-ready LLM systems using LLMOps sound principles.</p><p><strong>Level: </strong>intermediate</p><p><strong>Prerequisites:</strong> basic knowledge of Python, ML, and the cloud</p><h3>How will you learn?</h3><p><em>The course</em> contains <strong>10 hands-on written lessons</strong> and the <strong>open-source code</strong> you can <a href="https://github.com/decodingml/llm-twin-course"><em>access on GitHub</em></a>, <em>showing how to build an end-to-end LLM system.</em></p><p>Also, it includes <strong>2 bonus lessons</strong> on how to <strong>improve</strong> the <strong>RAG system</strong>.</p><p>You can read everything at your own pace.</p><p><em>→ To get the most out of this course, we encourage you to clone and run the repository while you cover the lessons.</em></p><h3>Costs?</h3><p>The <strong>articles</strong> and <strong>code</strong> are <strong>completely free</strong>. They will always remain free.</p><p>But if you plan to run the code while reading it, you must know that we use several cloud tools that might generate additional costs.</p><p>The cloud computing platforms (<a href="https://aws.amazon.com/">AWS</a>, <a href="https://www.qwak.com/lp/end-to-end-mlops/?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=decodingml">Qwak</a>) have a pay-as-you-go pricing plan. Qwak offers a few hours of free computing. Thus, we did our best to keep costs to a minimum.</p><p>For the other serverless tools (<a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">Qdrant</a>, <a href="https://www.comet.com/signup/?utm_source=decoding_ml&amp;utm_medium=partner&amp;utm_content=medium">Comet</a>), we will stick to their freemium version, which is free of charge.</p><h3>Meet your teachers!</h3><p>The course is created under the <a href="https://medium.com/decodingml">Decoding ML</a> umbrella by:</p><ul><li><a href="https://www.linkedin.com/in/pauliusztin/">Paul Iusztin</a> | Senior ML &amp; MLOps Engineer</li><li><a href="https://www.linkedin.com/in/vesaalexandru/">Alex Vesa</a> | Senior AI Engineer</li><li><a href="https://www.linkedin.com/in/arazvant/">Alex Razvant</a> | Senior ML &amp; MLOps Engineer</li></ul><blockquote><em>🔗 </em><strong><em>Check out</em></strong><em> </em><a href="https://github.com/decodingml/llm-twin-course"><em>the code on GitHub</em></a><em> [1] and support us with a ⭐️</em></blockquote><h3>Lessons</h3><p>→ <a href="https://medium.com/decodingml/the-llm-twin-free-course-on-production-ready-rag-pipelines-c96472f4e8c8">Quick overview</a> of <strong>each lesson</strong> of the LLM Twin free course.</p><p><em>The course is split into 12 lessons. Every Medium article will be its own lesson:</em></p><ol><li><a href="https://medium.com/decodingml/an-end-to-end-framework-for-production-ready-llm-systems-by-building-your-llm-twin-2cc6bb01141f">An End-to-End Framework for Production-Ready LLM Systems by Building Your LLM Twin</a></li><li><a href="https://medium.com/decodingml/the-importance-of-data-pipelines-in-the-era-of-generative-ai-673e1505a861">The Importance of Data Pipelines in the Era of Generative AI</a></li><li><strong>Change Data Capture: Enabling Event-Driven Architectures</strong></li><li><a href="https://medium.com/decodingml/sota-python-streaming-pipelines-for-fine-tuning-llms-and-rag-in-real-time-82eb07795b87">SOTA Python Streaming Pipelines for Fine-tuning LLMs and RAG — in Real-Time!</a></li><li><a href="https://medium.com/decodingml/the-4-advanced-rag-algorithms-you-must-know-to-implement-5d0c7f1199d2">The 4 Advanced RAG Algorithms You Must Know to Implement</a></li><li><a href="https://medium.com/decodingml/the-role-of-feature-stores-in-fine-tuning-llms-22bd60afd4b9">The Role of Feature Stores in Fine-Tuning LLMs</a></li><li><a href="https://medium.com/decodingml/how-to-fine-tune-llms-on-custom-datasets-at-scale-using-qwak-and-cometml-12216a777c34?source=your_stories_page-------------------------------------">How to fine-tune LLMs on custom datasets at Scale using Qwak and CometML</a></li><li><a href="https://medium.com/decodingml/best-practices-when-evaluating-fine-tuned-llms-47f02f5164c2">Best Practices When Evaluating Fine-Tuned LLMs</a></li><li><a href="https://medium.com/decodingml/architect-scalable-and-cost-effective-llm-rag-inference-pipelines-73b94ef82a99">Architect scalable and cost-effective LLM &amp; RAG inference pipelines</a></li><li><a href="https://medium.com/decodingml/how-to-evaluate-your-rag-using-ragas-framework-18d2325453ae">How to evaluate your RAG pipeline using the RAGAs Framework</a></li><li><a href="https://medium.com/decodingml/build-a-scalable-rag-ingestion-pipeline-using-74-3-less-code-ac50095100d6">[Bonus] Build a scalable RAG ingestion pipeline using 74.3% less code</a></li><li><a href="https://medium.com/decodingml/build-multi-index-advanced-rag-apps-bd33d2f0ec5c">[Bonus] Build Multi-Index Advanced RAG Apps</a></li></ol><blockquote><strong>To</strong> <strong>better understand </strong>the <strong>course’s goal, technical details, </strong>and <strong>system design </strong>→ <a href="https://medium.com/decodingml/an-end-to-end-framework-for-production-ready-llm-systems-by-building-your-llm-twin-2cc6bb01141f"><em>Check out Lesson 1</em></a></blockquote><p><strong>Let’s start</strong> with <strong>Lesson 3 </strong>↓↓↓</p><h3>Lesson 3: <strong>Change Data Capture: Enabling Event-Driven Architectures</strong></h3><p>We have changes everywhere. Linkedin, Medium and Github can be updated every day.</p><p>To be able to have or Digital Twin up to date we need <strong>synchronized</strong> data.</p><p>What is synchronized data?</p><p><strong>Synchronized data</strong> is data that is consistent and up-to-date across all systems and platforms it resides on or interacts with. It is the result of making sure that any change made in one dataset is immediately reflected in all other datasets that need to share that information.</p><p><strong>CDC’s primary purpose </strong>is to identify and capture changes made to database data, such as insertions, updates, and deletions.</p><p>It then logs these events and sends them to a message queue, like RabbitMQ. This allows other system parts to react to the data changes in real-time by reading from the queue, ensuring that all application parts are up-to-date.</p><p>Today, we will learn how to syncronize a data pipeline and a feature pipeline by using CDC pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aEVdvBaPKhd-V0A6Mt_hUQ.png" /><figcaption>Integrating CDC for Enhanced Data Consistency in LLM System Architecture [Image by the Author]</figcaption></figure><h3>Table of Contents</h3><ol><li>CDC pattern — Overview</li><li>CDC pattern —Digital Twin Architecture Use Case</li><li>CDC with MongoDB</li><li>RabbitMQ Message Broker</li><li>Hands-on CDC: Mongo+RabbitMQ</li><li>Test the system -&gt; on local environment</li><li>Test the system -&gt; cloud environment</li><li>Conclusion</li></ol><blockquote><em>🔗 </em><strong><em>Check out</em></strong><em> </em><a href="https://github.com/decodingml/llm-twin-course"><em>the code on GitHub</em></a><em> [1] and support us with a ⭐️</em></blockquote><h3>1. CDC pattern-Overview</h3><p><strong>Change Data Capture</strong>, commonly known as CDC, is an efficient way to track changes in a database.</p><p>The purpose of CDC is to capture insertions, updates, and deletions applied to a database and to make this change data available in a format easily consumable by downstream applications.</p><h4><strong>Why do we need CDC pattern?</strong></h4><ul><li><strong>Real-time Data Syncing</strong>: CDC facilitates near-real-time data integration and syncing.</li><li><strong>Efficient Data Pipelines</strong>: It allows incremental data loading, which is more efficient than bulk load operations.</li><li><strong>Minimized System Impact</strong>: CDC minimizes the impact on the source system by reducing the need for performance-intensive queries.</li><li><strong>Event-Driven Architectures</strong>: It enables event-driven architectures by streaming database events.</li></ul><h4><strong>What problem does CDC solve?</strong></h4><p>Change Data Capture (CDC) is particularly adept at solving consistency issues in distributed systems.</p><p>Consider a common scenario where an application is required to perform a sequence of actions in response to a trigger — such as a REST call or an event receipt.</p><p>These actions usually involve making a change to the database and sending a message through a messaging service like Kafka.</p><p>However, there’s an inherent risk: if the application encounters a failure or loses its connection to the messaging service after the database transaction but before the message dispatch, the database will reflect the change, but the corresponding message will never be sent. This discrepancy leads to an inconsistent state within the system.</p><p>CDC solve this challenge by decoupling the database update from the messaging.</p><p>It works by treating the database as a reliable source of events. Any committed change in the database is automatically captured by the CDC mechanism, which then ensures the corresponding message is sent to the messaging queue.</p><p>This <strong>separation of concerns</strong> provided by CDC means that the database update and the message dispatch are no longer directly dependent on the application’s stability or network reliability.</p><p>By employing CDC, we can maintain consistency across distributed components of a system, even in the face of application failures or network issues, thereby solving a critical problem in maintaining the integrity of distributed systems.</p><p>Another advantage of using change streams is that they read from this <strong>Oplog</strong>, not directly from the database.</p><p>This method significantly reduces the load on the database, avoiding the common pitfall of throttling database performance with frequent direct queries.</p><p>By tapping into the Oplog, CDC can efficiently identify and capture change events (such as insertions, updates, or deletions) without adding undue stress on the database itself. You can learn more about it here <a href="https://www.mongodb.com/docs/manual/changeStreams/">[2]</a>, <a href="https://shantanubansal.medium.com/demystifying-mongodb-oplog-a-comprehensive-guide-with-oplog-entry-examples-3bd716789f78">[3]</a> and <a href="https://www.mongodb.com/basics/change-streams">[4]</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YycR_jRhh-tDbCdAGZGqUw.png" /><figcaption>The problem that CDC solves in distributed systems [Generated by ChatGpt]</figcaption></figure><h4>Summary of diagram:</h4><ol><li><strong>Application Triggered</strong>: The diagram begins with an application that is triggered by a REST call or an event.</li><li><strong>Update Database</strong>: The application first updates the database. This is shown as a communication from the ‘Application’ to the ‘Database’.</li><li><strong>Database Acknowledges</strong>: The database acknowledges the update back to the application.</li><li><strong>Send Message Attempt</strong>: Next, the application tries to send a message through the messaging service (like Kafka). This is where the risk of failure is highlighted — if the application fails after updating the database but before successfully sending the message, it results in inconsistency.</li><li><strong>CDC Mechanism</strong>: To resolve this, the CDC mechanism comes into play. It decouples the database update from the messaging.</li><li><strong>Database Commit Triggering CDC</strong>: Any committed change in the database is automatically captured by the CDC mechanism.</li><li><strong>CDC Dispatches Message</strong>: Finally, the CDC mechanism ensures that the corresponding message is sent to the messaging service. This maintains consistency across the system, even if the application encounters issues after updating the database.</li></ol><h3>2. CDC pattern — Digital Twin Architecture Use Case</h3><p>The Digital Twin Architecture is respecting ‘the 3-pipeline architecture’ pattern:</p><ol><li>the feature pipeline</li><li>the training pipeline</li><li>the inference pipeline</li></ol><p>But one of the most important component in our architecture is the <strong>entrypoint</strong> of the system: the data pipeline</p><p>To ensure our <strong>feature store</strong> stays up-to-date with the<strong> data pipeline</strong>, we need a mechanism that detects changes at the pipeline’s entry point. This way, we can avoid discrepancies like having 100 entries deleted from our RAW Database while the Vector Database lags behind without these updates.</p><p>In the <strong>Data Collection Pipeline,</strong> data from various digital platforms like Medium, Substack, LinkedIn, and GitHub is extracted, transformed, and loaded (ETL) into a NoSQL database. Once this raw data is stored,<strong> the CDC pattern comes into play.</strong></p><p>The CDC pattern comes into action after data storage, meticulously monitoring and capturing any changes — insertions, updates, or deletions within the NoSQL database.</p><p>These changes then trigger events that the CDC system captures and pushes onto a queue, managed by <strong>RabbitMQ </strong>(message broker).</p><p>On the other side of the CDC pattern is the <strong>Feature Pipeline</strong>, where the data continue to flow.</p><p>Here, a streaming ingestion pipeline (<a href="https://bytewax.io/?utm_source=medium&amp;utm_medium=decodingml&amp;utm_campaign=2024_q1">Bytewax</a> and <a href="https://superlinked.com/?utm_source=community&amp;utm_medium=blog&amp;utm_campaign=oscourse">Superlinked</a>) takes the queue’s data and processes it in real-time. The processed data includes articles, posts, and code which are then transformed into features — actionable insights or inputs for machine learning models.</p><p>The processed data is then loaded into a Vector DB (<a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">Qdrant</a>), where it’s organized and indexed for efficient retrieval.</p><p>The Vector DB Retrieval Clients serve as the access points for querying and extracting these processed data features, now ready to be used in various applications, including training machine learning models or powering search algorithms.</p><h3>3. CDC with MongoDB</h3><p>In the world of data-driven applications, timing is everything.</p><p>The swifter a system can respond to data changes, the more agile and user-friendly it becomes. Let’s dive into this concept, especially in the context of <strong>MongoDB’s change streams</strong>, a feature that fundamentally transforms how applications interact with data.</p><h4>Immediate Response to Data Changes</h4><p>Consider a scenario where LinkedIn posts are regularly updated in our MongoDB database. Each post might undergo changes — perhaps an edit to the content, a new comment, or an update in user engagement metrics.</p><p>In a traditional setup, reflecting these updates into our feature store, specifically <a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">Qdrant</a>, could involve significant delays and manual intervention.</p><p>However, with <strong>MongoDB’s change streams</strong>, we implement a observer within our database. This feature is detecting changes in real-time. When a LinkedIn post is edited, MongoDB instantly captures this event and relays it to our data pipeline.</p><p>Our <strong>data pipeline</strong>, upon receiving a notification of the change, springs into action. The updated LinkedIn post is then processed — perhaps analyzed for new keywords, sentiments, or user interactions — and updated in Qdrant.</p><p>The sweet spot of MongoDB’s change streams is in their ability to streamline this process. They provide a direct line from the occurrence of a change in MongoDB to its reflection in Qdrant, ensuring our feature store is always in sync with the latest data.</p><p>This capability is crucial for maintaining an up-to-date and accurate data landscape, which in turn, powers more relevant and dynamic analytics for the LLM twin.</p><p>Before <strong>change streams</strong>, applications that needed to know about the addition of new data in real-time had to continuously poll data or rely on other update mechanisms.</p><p>One common, if complex, technique for monitoring changes was tailing <strong>MongoDB’s Operation Log (Oplog).</strong> The Oplog is part of the replication system of MongoDB and as such already tracks modifications to the database but is not easy to use for business logic.</p><p>Change streams are built on top of the Oplog but they provide a native API that improves efficiency and usability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zrEEJGaL0SoS-3Mu-MwEmw.png" /><figcaption>Example of Change Streams flow [Image by the Author]</figcaption></figure><p><strong>Note that you cannot open a change stream against a collection in a standalone MongoDB server because the feature relies on the Oplog which is only used on replica sets.</strong></p><p>When registering a change stream you need to specify <strong>the collection</strong> and what <strong>types of changes</strong> you want to listen to. You can do this by using the $match and a few other aggregation pipeline stages which limit the amount of data you will receive.</p><h3>4. RabbitMQ Message Broker</h3><p><a href="https://www.rabbitmq.com/">RabbitMQ</a> is a reliable and mature messaging and streaming broker, which is easy to deploy on cloud environments, on-premises, and on your local machine. It is currently used by millions worldwide.</p><h4><strong>Why do we need a message broker?</strong></h4><ul><li><strong>Reliability</strong>: RabbitMQ guarantees reliable message delivery, ensuring that change events are conveyed to the Feature Pipeline, even in the face of temporary outages.</li><li><strong>Decoupling</strong>: This enables loose coupling between services, promoting autonomous operation and mitigating the propagation of failures across the system.</li><li><strong>Load Management</strong>: It evenly distributes the data load across multiple consumers, enhancing system efficiency.</li><li><strong>Asynchronous Processing</strong>: The system benefits from asynchronous processing, with RabbitMQ queuing change events for processing without delay.</li><li><strong>Scalability</strong>: RabbitMQ’s scalability features accommodate growing data volumes by facilitating easy addition of consumers and horizontal scaling.</li><li><strong>Data Integrity</strong>: It ensures messages are processed in the order they’re received, which is critical for data integrity.</li><li><strong>Recovery Mechanisms</strong>: RabbitMQ offers message acknowledgment and redelivery features, vital for recovery from failures without data loss.</li></ul><h3>5. Hands-on — CDC: Mongo+RabbitMQ</h3><h4>5.1 Hands-on CDC: Mongo+RabbitMQ</h4><p>We are building the RabbitMQConnection class, a singleton structure, for establishing and managing connections to the RabbitMQ server. This class is robustly designed to handle connection parameters like username, password, queue name, host, port, and virtual_host, which can be customized or defaulted from settings.</p><p>Utilizing the pika Python library, RabbitMQConnection provides methods to connect, check connection status, retrieve channels, and close the connection. This improved approach encapsulates connection management within a singleton instance, ensuring efficient handling of RabbitMQ connections throughout the system lifecycle, from initialization to closure.</p><pre>class RabbitMQConnection:<br>    &quot;&quot;&quot;Singleton class to manage RabbitMQ connection.&quot;&quot;&quot;<br><br>    _instance = None<br><br>    def __new__(<br>        cls, host: str = None, port: int = None, username: str = None, password: str = None, virtual_host: str = &quot;/&quot;<br>    ):<br>        if not cls._instance:<br>            cls._instance = super().__new__(cls)<br>        return cls._instance<br><br>    def __init__(<br>        self,<br>        host: str = None,<br>        port: int = None,<br>        username: str = None,<br>        password: str = None,<br>        virtual_host: str = &quot;/&quot;,<br>        fail_silently: bool = False,<br>        **kwargs,<br>    ):<br>        self.host = host or settings.RABBITMQ_HOST<br>        self.port = port or settings.RABBITMQ_PORT<br>        self.username = username or settings.RABBITMQ_DEFAULT_USERNAME<br>        self.password = password or settings.RABBITMQ_DEFAULT_PASSWORD<br>        self.virtual_host = virtual_host<br>        self.fail_silently = fail_silently<br>        self._connection = None<br><br>    def __enter__(self):<br>        self.connect()<br>        return self<br><br>    def __exit__(self, exc_type, exc_val, exc_tb):<br>        self.close()<br><br>    def connect(self):<br>        try:<br>            credentials = pika.PlainCredentials(self.username, self.password)<br>            self._connection = pika.BlockingConnection(<br>                pika.ConnectionParameters(<br>                    host=self.host, port=self.port, virtual_host=self.virtual_host, credentials=credentials<br>                )<br>            )<br>        except pika.exceptions.AMQPConnectionError as e:<br>            print(&quot;Failed to connect to RabbitMQ:&quot;, e)<br>            if not self.fail_silently:<br>                raise e<br><br>    def is_connected(self) -&gt; bool:<br>        return self._connection is not None and self._connection.is_open<br><br>    def get_channel(self):<br>        if self.is_connected():<br>            return self._connection.channel()<br><br>    def close(self):<br>        if self.is_connected():<br>            self._connection.close()<br>            self._connection = None<br>            print(&quot;Closed RabbitMQ connection&quot;)</pre><p><strong>Publishing to RabbitMQ</strong>: The publish_to_rabbitmq function is where the magic happens. It connects to RabbitMQ , ensures that the message delivery is confirmed for reliability, and then publishes the data. The data variable, which is expected to be a JSON string, represents the changes captured by MongoDB&#39;s CDC mechanism.</p><pre>def publish_to_rabbitmq(queue_name: str, data: str):<br>    &quot;&quot;&quot;Publish data to a RabbitMQ queue.&quot;&quot;&quot;<br>    try:<br>        # Create an instance of RabbitMQConnection<br>        rabbitmq_conn = RabbitMQConnection()<br><br>        # Establish connection<br>        with rabbitmq_conn:<br>            channel = rabbitmq_conn.get_channel()<br><br>            # Ensure the queue exists<br>            channel.queue_declare(queue=queue_name, durable=True)<br><br>            # Delivery confirmation<br>            channel.confirm_delivery()<br><br>            # Send data to the queue<br>            channel.basic_publish(<br>                exchange=&quot;&quot;,<br>                routing_key=queue_name,<br>                body=data,<br>                properties=pika.BasicProperties(<br>                    delivery_mode=2,  # make message persistent<br>                ),<br>            )<br>            print(&quot;Sent data to RabbitMQ:&quot;, data)<br>    except pika.exceptions.UnroutableError:<br>        print(&quot;Message could not be routed&quot;)<br>    except Exception as e:<br>        print(f&quot;Error publishing to RabbitMQ: {e}&quot;)</pre><p>→🔗 <a href="https://github.com/decodingml/llm-twin-course/blob/main/2-data-ingestion/mq.py">Full RabbitMQ code</a></p><h4>5.2 CDC Pattern in MongoDB</h4><p><strong>Setting Up MongoDB Connection</strong>: The script begins by establishing a connection to a MongoDB database using MongoDatabaseConnectorclass. This connection targets a specific database named scrabble.</p><pre>mongo.py<br><br>from pymongo import MongoClient<br>from pymongo.errors import ConnectionFailure<br><br>from rag.settings import settings<br><br><br>class MongoDatabaseConnector:<br><br>    _instance: MongoClient = None<br><br>    def __new__(cls, *args, **kwargs):<br>        if cls._instance is None:<br>            try:<br>                cls._instance = MongoClient(settings.MONGO_DATABASE_HOST)<br>            except ConnectionFailure as e:<br>                print(f&quot;Couldn&#39;t connect to the database: {str(e)}&quot;)<br>                raise<br><br>        print(f&quot;Connection to database with uri: {settings.MONGO_DATABASE_HOST} successful&quot;)<br>        return cls._instance<br><br>    def get_database(self):<br>        return self._instance[settings.MONGO_DATABASE_NAME]<br><br>    def close(self):<br>        if self._instance:<br>            self._instance.close()<br>            print(&quot;Connected to database has been closed.&quot;)<br><br><br>connection = MongoDatabaseConnector()<br></pre><p><strong>Monitoring Changes with </strong><strong>watch</strong>: The core of the CDC pattern in MongoDB is realized through the watch method. Here, the script sets up a change stream to monitor for specific types of changes in the database. In this case, it&#39;s configured to listen for insert operations in any collection within the scrabble database.</p><pre>changes = db.watch([{&#39;$match&#39;: {&#39;operationType&#39;: {&#39;$in&#39;: [&#39;insert&#39;]}}}])</pre><p><strong>Processing Each Change</strong>: As changes occur in the database, the script iterates through each change event. For each event, the script extracts important metadata like the data type (collection name) and the entry ID. It also reformats the document by removing the MongoDB-specific _id and appending the data type and entry ID. This formatting makes the data more usable for downstream processes.</p><pre>    for change in changes:<br>        data_type = change[&#39;ns&#39;][&#39;coll&#39;]<br>        entry_id = change[&#39;fullDocument&#39;][&#39;_id&#39;]<br>        change[&#39;fullDocument&#39;].pop(&#39;_id&#39;)<br>        change[&#39;fullDocument&#39;][&#39;type&#39;] = data_type<br>        change[&#39;fullDocument&#39;][&#39;entry_id&#39;] = entry_id</pre><p><strong>Conversion to JSON and Publishing to RabbitMQ</strong>: The transformed document is then converted to a JSON string. This serialized data is ready to be sent to a messaging system, RabbitMQ, in this instance. This is where publish_to_rabbitmq comes into play, sending the JSON data to a specified RabbitMQ queue.</p><pre>data = json.dumps(change[&#39;fullDocument&#39;])<br>publish_to_rabbitmq(data=data)</pre><p>→🔗 <a href="https://github.com/decodingml/llm-twin-course/blob/main/2-data-ingestion/cdc.py">Full CDC code</a></p><h4>5.3 The full system docker-compose</h4><p>This docker-compose configuration outlines the setup for a system comprising a MongoDB database and a RabbitMQ message broker. The setup is designed to facilitate a development or testing environment using Docker containers. Let’s walk through the key components of this configuration:</p><p>This docker-compose configuration outlines the setup for a system comprising a MongoDB database and a RabbitMQ message broker. The setup is designed to facilitate a development or testing environment using Docker containers.</p><blockquote>In section 6 we will show you how to start this docker-compose and test the system.</blockquote><p>Let’s walk through the key components of this configuration:</p><p><strong>MongoDB Service Setup</strong></p><ol><li><strong>Image</strong>: Each MongoDB instance uses the mongo:5 image, which is the official MongoDB image at version 5.</li></ol><p><strong>2. Container Names</strong>: Individually named (mongo1, mongo2, mongo3) for easy identification.</p><p><strong>3. Commands</strong>: Each instance is started with specific commands:</p><ul><li>--replSet &quot;my-replica-set&quot; to set up a replica set named &#39;my-replica-set&#39;.</li><li>--bind_ip_all to bind MongoDB to all IP addresses.</li><li>--port 3000X (where X is 1, 2, or 3) to define distinct ports for each instance.</li></ul><p>Using<strong> three replicas in a MongoDB replica set</strong> is a common practice primarily for achieving high availability, data redundancy, and fault tolerance. Here’s why having three replicas is beneficial:</p><ol><li><strong>High Availability</strong>: In a replica set, one node is the primary node that handles all write operations, while the others are secondary nodes that replicate the data from the primary. If the primary node fails, one of the secondary nodes is automatically elected as the new primary. With three nodes, you ensure that there’s always a secondary node available to take over if the primary fails, minimizing downtime.</li><li><strong>Data Redundancy</strong>: Multiple copies of the data are maintained across different nodes. This redundancy safeguards against data loss in case of a hardware failure or corruption on one of the nodes.</li></ol><p><strong>4.Volumes</strong>: Maps a local directory (e.g., ./data/mongo-1) to the container&#39;s data directory (/data/db). This ensures data persistence across container restarts.</p><p><strong>5. Ports</strong>: Exposes each MongoDB instance on a unique port on the host machine (30001, 30002, 30003).</p><p><strong>6. Healthcheck (only for </strong><strong>mongo1)</strong>: Regularly checks the health of the first MongoDB instance, ensuring the replica set is correctly initiated and operational.</p><p><strong>RabbitMQ Service Setup</strong></p><ol><li><strong>Image and Container</strong>: Uses RabbitMQ 3 with management plugin based on Alpine Linux. The container is named scrabble_mq.</li><li><strong>Ports</strong>: Exposes RabbitMQ on port 5673 for message queue communication and 15673 for management console access.</li><li><strong>Volumes</strong>: Maps local directories for RabbitMQ data and log storage, ensuring persistence and easy access to logs.</li><li><strong>Restart Policy</strong>: Like MongoDB, it’s configured to always restart if it stops.</li></ol><pre>version: &#39;3.8&#39;<br><br>services:<br>  mongo1:<br>    image: mongo:5<br>    container_name: mongo1<br>    command: [&quot;--replSet&quot;, &quot;my-replica-set&quot;, &quot;--bind_ip_all&quot;, &quot;--port&quot;, &quot;30001&quot;]<br>    volumes:<br>      - ./data/mongo-1:/data/db<br>    ports:<br>      - 30001:30001<br>    healthcheck:<br>      test: test $$(echo &quot;rs.initiate({_id:&#39;my-replica-set&#39;,members:[{_id:0,host:\&quot;mongo1:30001\&quot;},{_id:1,host:\&quot;mongo2:30002\&quot;},{_id:2,host:\&quot;mongo3:30003\&quot;}]}).ok || rs.status().ok&quot; | mongo --port 30001 --quiet) -eq 1<br>      interval: 10s<br>      start_period: 30s<br><br>  mongo2:<br>    image: mongo:5<br>    container_name: mongo2<br>    command: [&quot;--replSet&quot;, &quot;my-replica-set&quot;, &quot;--bind_ip_all&quot;, &quot;--port&quot;, &quot;30002&quot;]<br>    volumes:<br>      - ./data/mongo-2:/data/db<br>    ports:<br>      - 30002:30002<br><br>  mongo3:<br>    image: mongo:5<br>    container_name: mongo3<br>    command: [&quot;--replSet&quot;, &quot;my-replica-set&quot;, &quot;--bind_ip_all&quot;, &quot;--port&quot;, &quot;30003&quot;]<br>    volumes:<br>      - ./data/mongo-3:/data/db<br>    ports:<br>      - 30003:30003<br><br>  mq:<br>    image: rabbitmq:3-management-alpine<br>    container_name: scrabble_mq<br>    ports:<br>      - &quot;5673:5672&quot;<br>      - &quot;15673:15672&quot;<br>    volumes:<br>      - ~/rabbitmq/data/:/var/lib/rabbitmq/<br>      - ~/rabbitmq/log/:/var/log/rabbitmq<br>    restart: always</pre><p>→🔗 <a href="https://github.com/decodingml/llm-twin-course/blob/main/docker-compose.yml">Full docker-compose.yml file</a></p><h3>6. Test the system -&gt; on local environment</h3><p>In order to test the entire system on your local environment we created a .Makefile where 3 steps are defined:</p><pre>help:<br> @grep -E &#39;^[a-zA-Z0-9 -]+:.*#&#39;  Makefile | sort | while read -r l; do printf &quot;\033[1;32m$$(echo $$l | cut -f 1 -d&#39;:&#39;)\033[00m:$$(echo $$l | cut -f 2- -d&#39;#&#39;)\n&quot;; done<br><br>local-start: # Buil and start mongodb and mq.<br> docker-compose -f docker-compose.yml up --build -d<br><br>local-start-cdc: # Start CDC system<br> python cdc.py<br><br>local-test-cdc: #Test CDC system by inserting data to mongodb<br> python test_cdc.py<br><br></pre><p>1. Build and run docker-compose</p><ul><li><strong>Command</strong>: make local-start</li><li><strong>Purpose</strong>: This step involves building and starting the MongoDB and RabbitMQ services using Docker Compose.</li></ul><p>If everything went well, type <em>docker ps</em> and see if services are up and running:</p><pre> docker ps<br>CONTAINER ID   IMAGE                          COMMAND                  CREATED         STATUS                   PORTS                                                                                                         NAMES<br>8193d0af74b6   mongo:5                        &quot;docker-entrypoint.s…&quot;   6 minutes ago   Up 6 minutes (healthy)   27017/tcp, 0.0.0.0:30001-&gt;30001/tcp                                                                           mongo1<br>2d82263e5780   mongo:5                        &quot;docker-entrypoint.s…&quot;   6 minutes ago   Up 6 minutes             27017/tcp, 0.0.0.0:30003-&gt;30003/tcp                                                                           mongo3<br>d1cb8d96dba0   rabbitmq:3-management-alpine   &quot;docker-entrypoint.s…&quot;   6 minutes ago   Up 6 minutes             4369/tcp, 5671/tcp, 15671/tcp, 15691-15692/tcp, 25672/tcp, 0.0.0.0:5673-&gt;5672/tcp, 0.0.0.0:15673-&gt;15672/tcp   scrabble_mq<br>7a213f0a22a6   mongo:5                        &quot;docker-entrypoint.s…&quot;   6 minutes ago   Up 6 minutes             27017/tcp, 0.0.0.0:30002-&gt;30002/tcp                                                                           mongo2</pre><p>2. Start the CDC ‘watcher’</p><ul><li><strong>Command</strong>: make local-start-cdc</li><li><strong>Purpose</strong>: This step starts the Change Data Capture (CDC) system, which monitors and captures changes in the MongoDB database.</li><li><strong>Action</strong>: Execute make local-start-cdc in your terminal. It triggers the python cdc.py script, activating the CDC watcher. This watcher will monitor for changes in the database and send them to the message queue.</li></ul><p>After you run this command you must see the following logs:</p><pre>Connection to database with uri: mongodb://localhost:30001,localhost:30002,localhost:30003/?replicaSet=my-replica-set successful<br>Connection to database with uri: mongodb://localhost:30001,localhost:30002,localhost:30003/?replicaSet=my-replica-set successful<br>2024-04-05 04:43:34,661 - INFO - Connected to MongoDB.</pre><p>3. Insert dummy data into MongoDB</p><ul><li><strong>Command</strong>: make local-test-cdc</li><li><strong>Purpose</strong>: To test if the CDC system is functioning correctly, you need to insert test data into MongoDB.</li><li><strong>Action</strong>: Use make local-test-cdc to run the command python test_cdc.py. This script inserts dummy data into MongoDB, which should trigger the CDC system. Watch for the CDC system to capture these changes and relay them to RabbitMQ, verifying the whole setup is working correctly.</li></ul><p>After you run this command, you must observe in the logs that CDC observed that a <strong>change</strong> was made, and published it to the RabbitMQ .</p><pre>024-04-05 04:43:51,510 - INFO - Change detected and serialized: {&quot;name&quot;: &quot;LLM TWIN&quot;, &quot;type&quot;: &quot;test&quot;, &quot;entry_id&quot;: &quot;660f5757b3153bbb219fd901&quot;}<br>2024-04-05 04:43:51,513 - INFO - Pika version 1.3.2 connecting to (&#39;127.0.0.1&#39;, 5673)<br>2024-04-05 04:43:51,513 - INFO - Socket connected: &lt;socket.socket fd=15, family=2, type=1, proto=6, laddr=(&#39;127.0.0.1&#39;, 63697), raddr=(&#39;127.0.0.1&#39;, 5673)&gt;<br>2024-04-05 04:43:51,514 - INFO - Streaming transport linked up: (&lt;pika.adapters.utils.io_services_utils._AsyncPlaintextTransport object at 0x105c05b80&gt;, _StreamingProtocolShim: &lt;SelectConnection PROTOCOL transport=&lt;pika.adapters.utils.io_services_utils._AsyncPlaintextTransport object at 0x105c05b80&gt; params=&lt;ConnectionParameters host=localhost port=5673 virtual_host=/ ssl=False&gt;&gt;).<br>2024-04-05 04:43:51,521 - INFO - AMQPConnector - reporting success: &lt;SelectConnection OPEN transport=&lt;pika.adapters.utils.io_services_utils._AsyncPlaintextTransport object at 0x105c05b80&gt; params=&lt;ConnectionParameters host=localhost port=5673 virtual_host=/ ssl=False&gt;&gt;<br>2024-04-05 04:43:51,521 - INFO - AMQPConnectionWorkflow - reporting success: &lt;SelectConnection OPEN transport=&lt;pika.adapters.utils.io_services_utils._AsyncPlaintextTransport object at 0x105c05b80&gt; params=&lt;ConnectionParameters host=localhost port=5673 virtual_host=/ ssl=False&gt;&gt;<br>2024-04-05 04:43:51,521 - INFO - Connection workflow succeeded: &lt;SelectConnection OPEN transport=&lt;pika.adapters.utils.io_services_utils._AsyncPlaintextTransport object at 0x105c05b80&gt; params=&lt;ConnectionParameters host=localhost port=5673 virtual_host=/ ssl=False&gt;&gt;<br>2024-04-05 04:43:51,522 - INFO - Created channel=1<br>Sent data to RabbitMQ: {&quot;name&quot;: &quot;LLM TWIN&quot;, &quot;type&quot;: &quot;test&quot;, &quot;entry_id&quot;: &quot;660f5757b3153bbb219fd901&quot;}<br>2024-04-05 04:43:51,534 - INFO - Closing connection (200): Normal shutdown<br>2024-04-05 04:43:51,534 - INFO - Closing channel (200): &#39;Normal shutdown&#39; on &lt;Channel number=1 OPEN conn=&lt;SelectConnection OPEN transport=&lt;pika.adapters.utils.io_services_utils._AsyncPlaintextTransport object at 0x105c05b80&gt; params=&lt;ConnectionParameters host=localhost port=5673 virtual_host=/ ssl=False&gt;&gt;&gt;<br>2024-04-05 04:43:51,535 - INFO - Received &lt;Channel.CloseOk&gt; on &lt;Channel number=1 CLOSING conn=&lt;SelectConnection OPEN transport=&lt;pika.adapters.utils.io_services_utils._AsyncPlaintextTransport object at 0x105c05b80&gt; params=&lt;ConnectionParameters host=localhost port=5673 virtual_host=/ ssl=False&gt;&gt;&gt;<br>2024-04-05 04:43:51,535 - INFO - Closing connection (200): &#39;Normal shutdown&#39;<br>2024-04-05 04:43:51,536 - INFO - Aborting transport connection: state=1; &lt;socket.socket fd=15, family=2, type=1, proto=6, laddr=(&#39;127.0.0.1&#39;, 63697), raddr=(&#39;127.0.0.1&#39;, 5673)&gt;<br>2024-04-05 04:43:51,536 - INFO - _AsyncTransportBase._initate_abort(): Initiating abrupt asynchronous transport shutdown: state=1; error=None; &lt;socket.socket fd=15, family=2, type=1, proto=6, laddr=(&#39;127.0.0.1&#39;, 63697), raddr=(&#39;127.0.0.1&#39;, 5673)&gt;<br>2024-04-05 04:43:51,536 - INFO - Deactivating transport: state=1; &lt;socket.socket fd=15, family=2, type=1, proto=6, laddr=(&#39;127.0.0.1&#39;, 63697), raddr=(&#39;127.0.0.1&#39;, 5673)&gt;<br>2024-04-05 04:43:51,536 - INFO - AMQP stack terminated, failed to connect, or aborted: opened=True, error-arg=None; pending-error=ConnectionClosedByClient: (200) &#39;Normal shutdown&#39;<br>2024-04-05 04:43:51,536 - INFO - Stack terminated due to ConnectionClosedByClient: (200) &#39;Normal shutdown&#39;<br>2024-04-05 04:43:51,536 - INFO - Closing transport socket and unlinking: state=3; &lt;socket.socket fd=15, family=2, type=1, proto=6, laddr=(&#39;127.0.0.1&#39;, 63697), raddr=(&#39;127.0.0.1&#39;, 5673)&gt;<br>2024-04-05 04:43:51,536 - INFO - User-initiated close: result=BlockingConnection__OnClosedArgs(connection=&lt;SelectConnection CLOSED transport=None params=&lt;ConnectionParameters host=localhost port=5673 virtual_host=/ ssl=False&gt;&gt;, error=ConnectionClosedByClient: (200) &#39;Normal shutdown&#39;)<br>Closed RabbitMQ connection<br>2024-04-05 04:43:51,536 - INFO - Data published to RabbitMQ.</pre><h3>7. Test the system -&gt; cloud environment.</h3><p>The flow suggests a system where content from various platforms is crawled, processed, and stored in MongoDB. A CDC system running on Fargate captures any changes in the database and publishes messages about these changes to RabbitMQ.</p><h4>Architecture Overview</h4><ol><li><strong>Medium/Substack/Linkedin/Github URL Link</strong>: These are the sources of content. The system starts with URLs from these platforms.</li><li><strong>Lambda Handler</strong>: This includes a Python Dispatcher and a Lambda Crawler which contains all types of crawlers. The Python Dispatcher is a component that decides which crawler to invoke based on the URL, while the Lambda Crawler is responsible for extracting the content from the provided URLs.</li><li><strong>MongoDB</strong>: A NoSQL database used to store the crawled content.</li><li><strong>CDC Fargate</strong>: This is a Change Data Capture (CDC) process running on AWS Fargate, which is a serverless compute engine for containers. CDC is used to capture and monitor changes in the database (like new articles added, or existing articles updated or deleted).</li><li><strong>RabbitMQ</strong>: This is a message-broker software that receives messages about the changes from the CDC process and likely forwards these messages to other components in the system for further processing or notifying subscribers of the changes.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wanGDB4GkdYt6DvNoGytVw.png" /><figcaption>AWS Infrastructure for MongoDB CDC [Image by the Author]</figcaption></figure><h4>Cloud Deployment with GitHub Actions and AWS</h4><p>In this final phase, we’ve established a streamlined deployment process using GitHub Actions. This setup automates the build and deployment of our entire system into AWS.</p><p>It’s a hands-off, efficient approach ensuring that every push to our .github folder triggers the necessary actions to maintain your system in the cloud.</p><p>In our <a href="https://github.com/decodingml/llm-twin-course">GitHub repository</a> it will be a README file in which we will explain everything you need to setup your credentials and run everything.</p><p>You can delve into the specifics of our infrastructure-as-code (IaC) practices, particularly our use of Pulumi, in the <a href="https://github.com/decodingml/llm-twin-course/tree/main/ops">ops</a> folder within our <a href="https://github.com/decodingml/llm-twin-course">GitHub repository.</a></p><p>This is a real-world example of modern DevOps practices, offering a peek into industry-standard methods for deploying and managing cloud infrastructure.</p><h3>Conclusion</h3><p>This is the 3rd article of the<strong> <em>LLM Twin: Building Your Production-Ready AI Replica</em> </strong>free<strong> </strong>course.</p><p>In this lesson, we presented Change Data Capture (CDC) as a key component for synchronizing data across various platforms, crucial for maintaining real-time data consistency in event-driven systems:</p><ul><li><strong>Integration with MongoDB and RabbitMQ</strong>: The lesson demonstrates how CDC, combined with MongoDB for data management and RabbitMQ for message brokering, creates a robust framework for real-time data processing.</li><li><strong>Role of CDC in LLM Twin Architecture</strong>: It emphasizes CDC’s importance in the construction of an LLM Twin, ensuring data remains synchronized across the system, from data collection to feature extraction.</li><li><strong>Practical Application and Implementation</strong>: Detailed instructions are provided on setting up and testing CDC in both local and cloud environments, offering hands-on experience in implementing these technologies.</li></ul><p>In <a href="https://medium.com/decodingml/sota-python-streaming-pipelines-for-fine-tuning-llms-and-rag-in-real-time-82eb07795b87"><strong>Lesson 4</strong></a>, we will dive deeper into the<strong> Streaming ingestion pipeline </strong>and explain why it’s a crucial component in any machine learning project, where data is involved.</p><blockquote><em>🔗 </em><strong><em>Check out</em></strong><em> </em><a href="https://github.com/decodingml/llm-twin-course"><em>the code on GitHub</em></a><em> [1] and support us with a </em>⭐️</blockquote><p>Have you <strong>enjoyed</strong> this <strong>article</strong>? Then…</p><p>↓↓↓</p><p>Join other engineers in the 𝗗𝗲𝗰𝗼𝗱𝗶𝗻𝗴 𝗠𝗟 𝗡𝗲𝘄𝘀𝗹𝗲𝘁𝘁𝗲𝗿 for battle-tested content on production-grade ML. 𝗘𝘃𝗲𝗿𝘆 𝘄𝗲𝗲𝗸:</p><p><a href="https://rebrand.ly/decodingml-newsletter">Decoding ML Newsletter | Paul Iusztin | Substack</a></p><h3>References</h3><p>[1] <a href="https://github.com/decodingml/llm-twin-course">Your LLM Twin Course — GitHub Repository</a> (2024), Decoding ML GitHub Organization<br>[2] <a href="https://www.mongodb.com/docs/manual/changeStreams/">Change Streams</a>, MongoDB Documentation<br>[3]Shantanu Bansal, <a href="https://shantanubansal.medium.com/demystifying-mongodb-oplog-a-comprehensive-guide-with-oplog-entry-examples-3bd716789f78">Demystifying MongoDB Oplog: A Comprehensive Guide with Oplog Entry Examples</a>, 2023, Medium<br>[4] <a href="https://www.mongodb.com/basics/change-streams">How Do Change Streams Work in MongoDB?</a>, MongoDB Documentation</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba82752dad5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Importance of Data Pipelines in the Era of Generative AI]]></title>
            <link>https://medium.com/@vesaalexandru95/the-importance-of-data-pipelines-in-the-era-of-generative-ai-673e1505a861?source=rss-a0286b59c498------2</link>
            <guid isPermaLink="false">https://medium.com/p/673e1505a861</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[cloud-infrastructure]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vesa Alexandru]]></dc:creator>
            <pubDate>Sat, 23 Mar 2024 06:02:24 GMT</pubDate>
            <atom:updated>2024-08-20T11:37:30.824Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://medium.com/decodingml/llm-twin-course/home">LLM TWIN COURSE: BUILDING YOUR PRODUCTION-READY AI REPLICA</a></h4><h4>From unstructured data crawling to structured valuable data</h4><p><em>→ the 2nd out of 12 lessons of </em><a href="https://medium.com/decodingml/llm-twin-course/home"><strong><em>the LLM Twin</em></strong></a><em> free course</em></p><p><strong>What is your LLM Twin?</strong> It is an AI character that writes like yourself by incorporating your style, personality and voice into an LLM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*akIomhnrM8pTEqNj.png" /><figcaption>Image by DALL-E</figcaption></figure><h4>Why is this course different?</h4><p><em>By finishing the “</em><a href="https://medium.com/decodingml/llm-twin-course/home"><strong><em>LLM Twin: Building Your Production-Ready AI Replica</em></strong></a><strong><em>”</em> </strong><em>free course, you will learn how to design, train, and deploy a production-ready LLM twin of yourself powered by LLMs, vector DBs, and LLMOps good practices</em>.</p><blockquote><strong><em>Why should you care? 🫵</em></strong></blockquote><blockquote><strong>→ No more isolated scripts or Notebooks!</strong> Learn production ML by building and deploying an end-to-end production-grade LLM system.</blockquote><h4>What will you learn to build by the end of this course?</h4><p>You will <strong>learn</strong> how to <strong>architect </strong>and<strong> build a real-world LLM system</strong> from <strong>start</strong> to <strong>finish</strong> — from <strong>data collection</strong> to <strong>deployment</strong>.</p><p>You will also <strong>learn</strong> to <strong>leverage MLOps best practices</strong>, such as experiment trackers, model registries, prompt monitoring, and versioning.</p><p><strong>The end goal?</strong> Build and deploy your own LLM twin.</p><p><strong>What is an LLM Twin?</strong> It is an AI character that learns to write like somebody by incorporating its style and personality into an LLM.</p><p><em>The </em><strong><em>architecture</em></strong><em> of the </em><strong><em>LLM twin</em></strong><em> is split into </em><strong><em>4 Python microservices</em></strong><em>:</em></p><ol><li><strong><em>the data collection pipeline:</em></strong> crawl your digital data from various social media platforms. Clean, normalize and load the data to a NoSQL DB through a series of ETL pipelines. Send database changes to a queue using the CDC pattern. (deployed on AWS)</li><li><strong><em>the feature pipeline:</em></strong> consume messages from a queue through a Bytewax streaming pipeline. Every message will be cleaned, chunked, embedded (using Superlinked), and loaded into a Qdrant vector DB in real-time. (deployed on AWS)</li><li><strong><em>the training pipeline:</em></strong><em> </em>create a custom dataset based on your digital data.<em> </em>Fine-tune an LLM using QLoRA. Use Comet ML’s experiment tracker to monitor the experiments. Evaluate and save the best model to Comet’s model registry. (deployed on Qwak)</li><li><strong><em>the inference pipeline:</em></strong> load and quantize the fine-tuned LLM from Comet’s model registry. Deploy it as a REST API. Enhance the prompts using RAG. Generate content using your LLM twin. Monitor the LLM using Comet’s prompt monitoring dashboard (deployed on Qwak)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-P4iUaDaWvbZFfeF.png" /><figcaption>LLM twin system architecture [Image by the Author]</figcaption></figure><p>Along the 4 microservices, you will learn to integrate 3 serverless tools:</p><ul><li><a href="https://www.comet.com/signup/?utm_source=decoding_ml&amp;utm_medium=partner&amp;utm_content=medium">Comet ML </a>as your ML Platform;</li><li><a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">Qdrant</a> as your vector DB;</li><li><a href="https://www.qwak.com/lp/end-to-end-mlops/?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=decodingml">Qwak</a> as your ML infrastructure;</li></ul><h4>Who is this for?</h4><p><strong>Audience:</strong> MLE, DE, DS, or SWE who want to learn to engineer production-ready LLM systems using LLMOps sound principles.</p><p><strong>Level: </strong>intermediate</p><p><strong>Prerequisites:</strong> basic knowledge of Python, ML, and the cloud</p><h4>How will you learn?</h4><p><em>The course</em> contains <strong>10 hands-on written lessons</strong> and the <strong>open-source code</strong> you can <a href="https://github.com/decodingml/llm-twin-course"><em>access on GitHub</em></a>, <em>showing how to build an end-to-end LLM system.</em></p><p>Also, it includes <strong>2 bonus lessons</strong> on how to <strong>improve</strong> the <strong>RAG system</strong>.</p><p>You can read everything at your own pace.</p><p><em>→ To get the most out of this course, we encourage you to clone and run the repository while you cover the lessons.</em></p><h4>Costs?</h4><p>The <strong>articles</strong> and <strong>code</strong> are <strong>completely free</strong>. They will always remain free.</p><p>But if you plan to run the code while reading it, you must know that we use several cloud tools that might generate additional costs.</p><p>The cloud computing platforms (<a href="https://aws.amazon.com/">AWS</a>, <a href="https://www.qwak.com/lp/end-to-end-mlops/?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=decodingml">Qwak</a>) have a pay-as-you-go pricing plan. Qwak offers a few hours of free computing. Thus, we did our best to keep costs to a minimum.</p><p>For the other serverless tools (<a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">Qdrant</a>, <a href="https://www.comet.com/signup/?utm_source=decoding_ml&amp;utm_medium=partner&amp;utm_content=medium">Comet</a>), we will stick to their freemium version, which is free of charge.</p><h4>Meet your teachers!</h4><p>The course is created under the <a href="https://medium.com/decodingml">Decoding ML</a> umbrella by:</p><ul><li><a href="https://www.linkedin.com/in/pauliusztin/">Paul Iusztin</a> | Senior ML &amp; MLOps Engineer</li><li><a href="https://www.linkedin.com/in/vesaalexandru/">Alex Vesa</a> | Senior AI Engineer</li><li><a href="https://www.linkedin.com/in/arazvant/">Alex Razvant</a> | Senior ML &amp; MLOps Engineer</li></ul><blockquote>🔗 <strong>Check out</strong> <a href="https://github.com/decodingml/llm-twin-course">the code on GitHub</a> [1] and support us with a <em>⭐️</em></blockquote><h3>Lessons</h3><p>→ <a href="https://medium.com/decodingml/the-llm-twin-free-course-on-production-ready-rag-pipelines-c96472f4e8c8">Quick overview</a> of <strong>each lesson</strong> of the LLM Twin free course.</p><p><em>The course is split into 12 lessons. Every Medium article will be its own lesson:</em></p><ol><li><a href="https://medium.com/decodingml/an-end-to-end-framework-for-production-ready-llm-systems-by-building-your-llm-twin-2cc6bb01141f">An End-to-End Framework for Production-Ready LLM Systems by Building Your LLM Twin</a></li><li><strong>The importance of Data Pipelines in the era of Generative AI</strong></li><li><a href="https://medium.com/decodingml/the-3nd-out-of-11-lessons-of-the-llm-twin-free-course-ba82752dad5a">Change Data Capture: Enabling Event-Driven Architectures</a></li><li><a href="https://medium.com/decodingml/sota-python-streaming-pipelines-for-fine-tuning-llms-and-rag-in-real-time-82eb07795b87">SOTA Python Streaming Pipelines for Fine-tuning LLMs and RAG — in Real-Time!</a></li><li><a href="https://medium.com/decodingml/the-4-advanced-rag-algorithms-you-must-know-to-implement-5d0c7f1199d2">The 4 Advanced RAG Algorithms You Must Know to Implement</a></li><li><a href="https://medium.com/decodingml/the-role-of-feature-stores-in-fine-tuning-llms-22bd60afd4b9">The Role of Feature Stores in Fine-Tuning LLMs</a></li><li><a href="https://medium.com/decodingml/how-to-fine-tune-llms-on-custom-datasets-at-scale-using-qwak-and-cometml-12216a777c34?source=your_stories_page-------------------------------------">How to fine-tune LLMs on custom datasets at Scale using Qwak and CometML</a></li><li><a href="https://medium.com/decodingml/best-practices-when-evaluating-fine-tuned-llms-47f02f5164c2">Best Practices When Evaluating Fine-Tuned LLMs</a></li><li><a href="https://medium.com/decodingml/architect-scalable-and-cost-effective-llm-rag-inference-pipelines-73b94ef82a99">Architect scalable and cost-effective LLM &amp; RAG inference pipelines</a></li><li><a href="https://medium.com/decodingml/how-to-evaluate-your-rag-using-ragas-framework-18d2325453ae">How to evaluate your RAG pipeline using the RAGAs Framework</a></li><li><a href="https://medium.com/decodingml/build-a-scalable-rag-ingestion-pipeline-using-74-3-less-code-ac50095100d6">[Bonus] Build a scalable RAG ingestion pipeline using 74.3% less code</a></li><li><a href="https://medium.com/decodingml/build-multi-index-advanced-rag-apps-bd33d2f0ec5c">[Bonus] Build Multi-Index Advanced RAG Apps</a></li></ol><blockquote><strong>To</strong> <strong>better understand </strong>the <strong>course’s goal, technical details, </strong>and <strong>system design </strong>→ <a href="https://medium.com/decodingml/an-end-to-end-framework-for-production-ready-llm-systems-by-building-your-llm-twin-2cc6bb01141f"><em>Check out Lesson 1</em></a></blockquote><p><strong>Let’s start</strong> with <strong>Lesson 2 </strong>↓↓↓</p><h3>Lesson 2: The Importance of Data Pipelines in the Era of Generative AI</h3><p>We have data everywhere. Linkedin, Medium, Github, Substack, and many other platforms.</p><p>To be able to build your Digital Twin, you need <strong>data</strong>.</p><p>Not all types of data, but <strong>organized</strong>, <strong>clean</strong>, and <strong>normalized</strong> data.</p><p>In <strong>Lesson 2, </strong>we will learn how to think and build a <strong>data pipeline </strong>by aggregating data from:</p><ul><li>Medium</li><li>Linkedin</li><li>Github</li><li>Substack</li></ul><p>We will <strong>present</strong> all our <strong>architectural decisions</strong> regarding the design of the data collection pipeline for social media data and why separating raw data and feature data is essential.</p><p>In<strong> Lesson 3, we will present the CDC (change data capture) pattern, a database architecture, and a design for data management systems</strong>.</p><p>CDC&#39;s primary purpose is to identify and capture changes made to database data, such as insertions, updates, and deletions.</p><p>It then logs these events and sends them to a message queue, like RabbitMQ. This allows other system parts to react to the data changes in real-time by reading from the queue, ensuring that all application parts are up-to-date.</p><p>We will go into detail in Lesson 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5lTAPWYWnVEvytRrRff9qQ.png" /><figcaption>Data Pipeline System Architecture [Image by the Author]</figcaption></figure><h3>Table of Contents</h3><ol><li>What is a data pipeline? The critical point in any AI project.</li><li>Data crawling. How to collect your data?</li><li>How do you store your data?</li><li>Raw data vs. Features data</li><li>Cloud Infrastructure</li><li>Wrap-up — Run everything</li></ol><blockquote>🔗 <strong>Check out</strong> <a href="https://github.com/decodingml/llm-twin-course">the code on GitHub</a> [1] and support us with a ⭐️</blockquote><h3>1. What is a data pipeline? The critical point in any AI project.</h3><p>Data is the lifeblood of any successful AI project, and a well-engineered data pipeline is the key to harnessing its power.</p><p>This automated system acts as the engine, seamlessly moving data through various stages and transforming it from raw form into actionable insights.</p><p>But what exactly is a data pipeline, and why is it so critical?</p><p><strong>A data pipeline is a series of automated steps that guide data on a purpose.</strong></p><p>It starts with <strong>data collection, gathering information from diverse sources, such as LinkedIn</strong>, Medium, Substack, Github, etc.</p><p>The pipeline then tackles the raw data, performing <strong>cleaning and transformation</strong>.</p><p>This step removes inconsistencies and irrelevant information and transforms the data into a format suitable for analysis and ML models.</p><p><strong>But why are data pipelines so crucial in AI projects?</strong> Here are some key reasons:</p><ul><li><strong>Efficiency and Automation:</strong> Manual data handling is slow and prone to errors. Pipelines automate the process, ensuring speed and accuracy, especially when dealing with massive data volumes.</li><li><strong>Scalability:</strong> AI projects often grow in size and complexity. A well-designed pipeline can scale seamlessly, accommodating this growth without compromising performance.</li><li><strong>Quality and Consistency:</strong> Pipelines standardize data handling, ensuring consistent and high-quality data throughout the project lifecycle, leading to more reliable AI models.</li><li><strong>Flexibility and Adaptability:</strong> The AI landscape is constantly evolving. A robust data pipeline can adapt to changing requirements without a complete rebuild, ensuring long-term value.</li></ul><p><strong>Data is the engine of any ML model. If we don’t give it enough importance, the model’s output</strong> will be very unexpected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wkjJQaVVlpyvStPK.jpg" /><figcaption>Importance of Data [Image by the Author]</figcaption></figure><p>But how can we transform the raw data into <strong>actionable insights?</strong></p><h3>2. Data crawling. How to collect your data?</h3><p>The first step in building a database of relevant data is choosing our data sources. In this lesson, we will focus on four sources:</p><ul><li>Linkedin</li><li>Medium</li><li>Github</li><li>Substack</li></ul><p>Why do we choose 4 data sources? We need <strong>complexity</strong> and<strong> diversity</strong> in our data to build a powerful LLM twin. To obtain these characteristics, we will focus on building three collections of data:</p><ul><li>Articles</li><li>Social Media Posts</li><li>Code</li></ul><p>For the data crawling module, we will focus on <strong>two libraries</strong>:</p><ol><li><strong>BeautifulSoup</strong>: A Python library for parsing HTML and XML documents. It creates parse trees that help us extract the data quickly, but BeautifulSoup needs to fetch the web page for us. That’s why we need to use it alongside libraries like requests or Selenium which can fetch the page for us.</li><li><strong>Selenium</strong>: A tool for automating web browsers. It’s used here to interact with web pages programmatically (like logging into LinkedIn, navigating through profiles, etc.). Selenium can work with various browsers, but this code configures it to work with Chrome. We created a base crawler class to respect the best software engineering practices.</li></ol><p>The BaseAbstractCrawler class in a web crawling context is essential for several key reasons:</p><ol><li><strong>Code Reusability and Efficiency</strong>: It contains standard methods and properties used by different scrapers, reducing code duplication and promoting efficient development.</li><li><strong>Simplification and Structure</strong>: This base class abstracts complex or repetitive code, allowing derived scraper classes to focus on specific tasks. It enforces a consistent structure across different scrapers.</li><li><strong>Ease of Extension</strong>: New types of scrapers can easily extend this base class, making the system adaptable and scalable for future requirements.</li><li><strong>Maintenance and Testing</strong>: Updates or fixes to standard functionalities must be made only once in the base class, simplifying maintenance and testing.</li></ol><p>The class can be found here <a href="https://github.com/decodingml/llm-twin-course/blob/main/1-data-crawling/crawlers/base.py">base.py</a></p><pre>import time<br><br>from selenium import webdriver<br>from selenium.webdriver.chrome.options import Options<br>from selenium.webdriver.chrome.service import Service<br>from webdriver_manager.chrome import ChromeDriverManager<br><br>from collector.documents import BaseDocument<br><br><br>class BaseCrawler:<br><br>    model: BaseDocument<br><br>    def extract(self, link: str, **kwargs):<br>        raise NotImplemented(&quot;Needs implementation in subclass.&quot;)<br><br><br>class BaseAbstractCrawler(BaseCrawler):<br><br>    def __init__(self, scroll_limit: int = 5):<br>        options = self.set_driver_options()<br><br>        self.scroll_limit = scroll_limit<br>        self.driver = webdriver.Chrome(<br>            service=Service(ChromeDriverManager().install()), options=options<br>        )<br><br>    def set_driver_options(self) -&gt; Options:<br>        return Options()<br><br>    def login(self):<br>        pass<br><br>    def scroll_page(self):<br>        &quot;&quot;&quot;Scroll through the LinkedIn page based on the scroll limit.&quot;&quot;&quot;<br>        current_scroll = 0<br>        last_height = self.driver.execute_script(&quot;return document.body.scrollHeight&quot;)<br>        while True:<br>            self.driver.execute_script(<br>                &quot;window.scrollTo(0, document.body.scrollHeight);&quot;<br>            )<br>            time.sleep(5)<br>            new_height = self.driver.execute_script(&quot;return document.body.scrollHeight&quot;)<br>            if new_height == last_height or (<br>                self.scroll_limit and current_scroll &gt;= self.scroll_limit<br>            ):<br>                break<br>            last_height = new_height<br>            current_scroll += 1python</pre><p>We created separate crawlers for each collection (posts, articles, and repositories): <a href="https://github.com/decodingml/llm-twin-course/blob/main/1-data-crawling/crawlers/github.py">github.py</a>, <a href="https://github.com/decodingml/llm-twin-course/blob/main/1-data-crawling/crawlers/medium.py">medium.py</a>, substack.py and <a href="https://github.com/decodingml/llm-twin-course/blob/main/1-data-crawling/crawlers/linkedin.py">linkedin.py</a>.</p><p>Every crawler extends the <strong>BaseCrawler</strong> or <strong>BaseAbstractCrawler</strong> class, depending on the purpose.</p><p>The <em>MediumCrawler</em>, <em>SubstackCrawler</em> and <em>LinkedinCrawler</em> extend the BaseAbstractCrawler (as they depend on the login and scrolling functionality).</p><p>Here is what the <em>LinkedInCrawler</em> looks like ↓</p><pre>import os<br>import time<br>from typing import Dict, List<br><br>from bs4 import BeautifulSoup<br>from bs4.element import Tag<br>from selenium.webdriver.chrome.options import Options<br>from selenium.webdriver.common.by import By<br><br>from config import settings<br>from crawlers.base import BaseAbstractCrawler<br>from documents import PostDocument<br>from errors import ImproperlyConfigured<br><br><br>class LinkedInCrawler(BaseAbstractCrawler):<br><br>    model = PostDocument<br><br>    def set_driver_options(self) -&gt; Options:<br>        options = Options()<br>        options.add_experimental_option(&quot;detach&quot;, True)<br>        return options<br><br>    def extract(self, link: str, **kwargs):<br>        print(f&quot;Starting to scrape data for profile: {link}&quot;)<br><br>    def _scrape_section(self, soup: BeautifulSoup, *args, **kwargs):<br>        &quot;&quot;&quot;Scrape a specific section of the LinkedIn profile.&quot;&quot;&quot;<br>        # Example: Scrape the &#39;About&#39; section<br>        parent_div = soup.find(*args, **kwargs)<br>        return parent_div.get_text(strip=True) if parent_div else &quot;&quot;<br><br>    def _extract_image_urls(self, buttons: List[Tag]) -&gt; Dict[str, str]:<br>        &quot;&quot;&quot;<br>        Extracts image URLs from button elements.<br><br>        Args:<br>            buttons (List[Tag]): A list of BeautifulSoup Tag objects representing buttons.<br><br>        Returns:<br>            Dict[str, str]: A dictionary mapping post indexes to image URLs.<br>        &quot;&quot;&quot;<br><br>    def _get_page_content(self, url: str) -&gt; BeautifulSoup:<br>        &quot;&quot;&quot;Retrieve the page content of a given URL.&quot;&quot;&quot;<br><br>    def _extract_posts(<br>        self, post_elements: List[Tag], post_images: Dict[str, str]<br>    ) -&gt; Dict[str, Dict[str, str]]:<br>        &quot;&quot;&quot;<br>        Extracts post texts and combines them with their respective images.<br><br>        Args:<br>            post_elements (List[Tag]): A list of BeautifulSoup Tag objects representing post elements.<br>            post_images (Dict[str, str]): A dictionary containing image URLs mapped by post index.<br><br>        Returns:<br>            Dict[str, Dict[str, str]]: A dictionary containing post data with text and optional image URL.<br>        &quot;&quot;&quot;<br><br>    def _scrape_experience(self, profile_url: str):<br>        &quot;&quot;&quot;Scrapes the Experience section of the LinkedIn profile.&quot;&quot;&quot;<br>        self.driver.get(profile_url + &quot;/details/experience/&quot;)<br><br>    def _scrape_education(self, profile_url: str) -&gt; str:<br>        self.driver.get(profile_url + &quot;/details/education/&quot;)<br><br>    def login(self):<br>        &quot;&quot;&quot;Log in to LinkedIn.&quot;&quot;&quot;</pre><p>For example, the GitHub crawler is a static crawler that doesn’t need a login function, <em>scroll_page</em> function, or driver. It uses only git commands.</p><p>The <em>GithubCrawler</em> extends the <em>BaseCrawler</em> class and uses the extract method to retrieve the desired repository.</p><pre>import os<br>import shutil<br>import subprocess<br>import tempfile<br><br>from crawlers.base import BaseCrawler<br>from documents import RepositoryDocument<br><br><br>class GithubCrawler(BaseCrawler):<br><br>    model = RepositoryDocument<br><br>    def __init__(self, ignore=(&quot;.git&quot;, &quot;.toml&quot;, &quot;.lock&quot;, &quot;.png&quot;)):<br>        super().__init__()<br>        self._ignore = ignore<br><br>    def extract(self, link: str, **kwargs):<br>        repo_name = link.rstrip(&quot;/&quot;).split(&quot;/&quot;)[-1]<br><br>        local_temp = tempfile.mkdtemp()<br><br>        try:<br>            os.chdir(local_temp)<br>            subprocess.run([&quot;git&quot;, &quot;clone&quot;, link])<br><br>            repo_path = os.path.join(local_temp, os.listdir(local_temp)[0])<br><br>            tree = {}<br>            for root, dirs, files in os.walk(repo_path):<br>                dir = root.replace(repo_path, &quot;&quot;).lstrip(&quot;/&quot;)<br>                if dir.startswith(self._ignore):<br>                    continue<br><br>                for file in files:<br>                    if file.endswith(self._ignore):<br>                        continue<br>                    file_path = os.path.join(dir, file)<br>                    with open(os.path.join(root, file), &quot;r&quot;, errors=&quot;ignore&quot;) as f:<br>                        tree[file_path] = f.read().replace(&quot; &quot;, &quot;&quot;)<br><br>            instance = self.model(<br>                name=repo_name, link=link, content=tree, owner_id=kwargs.get(&quot;user&quot;)<br>            )<br>            instance.save()<br><br>        except Exception:<br>            raise<br>        finally:<br>            shutil.rmtree(local_temp)</pre><h3>3. How do you store your data? An ODM approach</h3><p>Object Document Mapping (ODM) is a technique that maps between an object model in an application and a document database.</p><p>By abstracting database interactions through model classes, it simplifies the process of storing and managing data in a document-oriented database like MongoDB. This approach is particularly beneficial in applications where data structures align well with object-oriented programming paradigms.</p><p>The <a href="https://github.com/decodingml/llm-twin-course/blob/main/1-data-crawling/db/documents.py">documents.py</a> module serves as a foundational framework for interacting with MongoDB.</p><p>Our data modeling centers on creating specific document classes — <strong>UserDocument</strong>, <strong>RepositoryDocument</strong>, <strong>PostDocument</strong>, and <strong>ArticleDocument</strong> — that mirror the structure of our MongoDB collections.</p><p>These classes define the schema for each data type we store, such as users’ details, repository metadata, post content, and article information.</p><p>By using these classes, we can ensure that the data inserted into our database is consistent, valid, and easily retrievable for further operations.</p><pre>class BaseDocument(BaseModel):<br>    id: UUID4 = Field(default_factory=uuid.uuid4)<br><br>    model_config = ConfigDict(from_attributes=True, populate_by_name=True)<br><br>    @classmethod<br>    def from_mongo(cls, data: dict):<br>        &quot;&quot;&quot;Convert &quot;_id&quot; (str object) into &quot;id&quot; (UUID object).&quot;&quot;&quot;<br><br><br>    def to_mongo(self, **kwargs) -&gt; dict:<br>        &quot;&quot;&quot;Convert &quot;id&quot; (UUID object) into &quot;_id&quot; (str object).&quot;&quot;&quot;<br><br><br>    def save(self, **kwargs):<br>        collection = _database[self._get_collection_name()]<br><br>    @classmethod<br>    def get_or_create(cls, **filter_options) -&gt; Optional[str]:<br>        collection = _database[cls._get_collection_name()]<br><br><br>    @classmethod<br>    def bulk_insert(cls, documents: List, **kwargs) -&gt; Optional[List[str]]:<br>        collection = _database[cls._get_collection_name()]<br><br><br>    @classmethod<br>    def _get_collection_name(cls):<br>        if not hasattr(cls, &quot;Settings&quot;) or not hasattr(cls.Settings, &quot;name&quot;):<br>            raise ImproperlyConfigured(<br>                &quot;Document should define an Settings configuration class with the name of the collection.&quot;<br>            )<br><br>        return cls.Settings.name<br><br><br>class UserDocument(BaseDocument):<br><br>    first_name: str<br>    last_name: str<br><br>    class Settings:<br>        name = &quot;users&quot;<br><br><br>class RepositoryDocument(BaseDocument):<br><br>    name: str<br>    link: str<br>    content: dict<br>    owner_id: str = Field(alias=&quot;owner_id&quot;)<br><br>    class Settings:<br>        name = &quot;repositories&quot;<br><br><br>class PostDocument(BaseDocument):<br><br>    platform: str<br>    content: dict<br>    author_id: str = Field(alias=&quot;author_id&quot;)<br><br>    class Settings:<br>        name = &quot;posts&quot;<br><br><br>class ArticleDocument(BaseDocument):<br><br>    platform: str<br>    link: str<br>    content: dict<br>    author_id: str = Field(alias=&quot;author_id&quot;)<br><br>    class Settings:<br>        name = &quot;articles&quot;</pre><p>In our ODM approach for MongoDB, key CRUD operations are integrated:</p><ol><li><strong>Conversion</strong>: The to_mongo method transforms model instances into MongoDB-friendly formats.</li><li><strong>Inserting</strong>: The save method uses PyMongo&#39;s insert_one for adding documents, returning MongoDB&#39;s acknowledgment as the inserted ID.</li><li><strong>Bulk Operations</strong>: bulk_insert employs insert_many for adding multiple documents and returning their IDs.</li><li><strong>Upserting</strong>: get_or_create either fetches an existing document or creates a new one, ensuring seamless data updates.</li><li><strong>Validation and Transformation</strong>: Using Pydantic models, each class ensures data is correctly structured and validated before database entry.</li></ol><h3>4. Raw data vs features</h3><p>Now that we understand the critical role of data pipelines in preparing raw data let’s explore how we can transform this data into a usable format for our LLM twin. This is where the concept of features comes into play.</p><p><strong>Features </strong>are the processed building blocks used to fine-tune your LLM twin.</p><blockquote>Imagine you’re teaching someone your writing style. You wouldn’t just hand them all your social media posts! Instead, you might point out your frequent use of specific keywords, the types of topics you write about, or the overall sentiment you convey. Features work similarly for your LLM twin.</blockquote><p><strong>Raw data</strong>, on the other hand, is the unrefined information collected from various sources. Social media posts might contain emojis, irrelevant links, or even typos. This raw data needs cleaning and transformation before it can be used effectively.</p><p>In our <strong>data flow</strong>, raw data is initially captured and stored in MongoDB, which remains unprocessed.</p><p>Then, we process this data to create features — key details we use to teach our LLM twin — and keep these in <a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course"><strong>Qdrant</strong></a>. We do this to keep our raw data intact in case we need it again, while <a href="https://qdrant.tech/?utm_source=decodingml&amp;utm_medium=referral&amp;utm_campaign=llm-course">Qdrant</a> holds the ready-to-use features for efficient machine learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fF7OSGURGnjV_C4AeeT2Qw.jpeg" /><figcaption>Raw Data vs Features [Image by the Author]</figcaption></figure><h3>5. Cloud Infrastructure</h3><p>In this section, we will focus on how to constantly update our database with the most recent data from the 3 data sources.</p><p>Before diving into how to build the infrastructure of our data pipeline, I would like to show you how to “think” through the whole process before stepping into the details of AWS.</p><p>The first step in doing an infrastructure is to draw a high-level overview of my components.</p><p>So, the components of our data pipeline are:</p><ul><li>Linkedin crawler</li><li>Medium crawler</li><li>Github crawler</li><li>Substack crawler</li><li>MongoDB (Data Collector)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*48hc90bpvgBqIeuCfDE3sg.png" /><figcaption>High-Level AWS Infrastructure [Image by the Author]</figcaption></figure><p>Every <strong>crawler</strong> is a .py file. Since this data pipeline must be constantly updated, we will design a system based on lambda functions, where every <strong>lambda function </strong>represents a crawler.</p><p>What is a <strong>lambda function</strong> in the <strong>AWS Environment?</strong></p><p><strong>AWS Lambda</strong> is a serverless computing service that allows you to run code without provisioning or managing servers. It executes your code only when needed and scales automatically, from a few daily requests to thousands per second.</p><p>Here’s how Lambda fits within the AWS environment and what makes it particularly powerful:</p><ul><li><strong>Event-Driven:</strong> AWS Lambda is designed to use events as triggers. These events could be changes to data in an Amazon S3 bucket, updates to a DynamoDB table, HTTP requests via Amazon API Gateway, or direct invocation via SDKs from other applications. In the diagram I provided, the events would likely be new or updated content on LinkedIn, Medium, or GitHub.</li><li><strong>Scalable:</strong> AWS Lambda can run as many instances of the function as needed to respond to the rate of incoming events. This could mean running dozens or even hundreds of cases of your function in parallel.</li><li><strong>Managed Execution Environment:</strong> AWS handles all the administration of the underlying infrastructure, including server and operating system maintenance, capacity provisioning and automatic scaling, code monitoring, and logging. This allows you to focus on your code.</li></ul><p>How can we put the medium crawler on an AWS Lambda function?</p><p>We need a <strong>handler</strong>.</p><p>The handler function is the entry point for the AWS Lambda function. In AWS Lambda, the handler function is invoked when an event triggers the Lambda function.</p><p>→🔗 <a href="https://github.com/decodingml/llm-twin-course/blob/main/1-data-crawling/main.py">Code</a></p><p>In the next section, I will show how this handler will be used to deploy this function on AWS Lambda.</p><pre>from aws_lambda_powertools import Logger<br>from aws_lambda_powertools.utilities.typing import LambdaContext<br><br>from crawlers import MediumCrawler, LinkedInCrawler, GithubCrawler<br>from dispatcher import CrawlerDispatcher<br>from documents import UserDocument<br><br>logger = Logger(service=&quot;decodingml/crawler&quot;)<br><br>_dispatcher = CrawlerDispatcher()<br>_dispatcher.register(&quot;medium&quot;, MediumCrawler)<br>_dispatcher.register(&quot;linkedin&quot;, LinkedInCrawler)<br>_dispatcher.register(&quot;github&quot;, GithubCrawler)<br><br><br>def handler(event, context: LambdaContext):<br><br>    first_name, last_name = event.get(&#39;user&#39;).split(&quot; &quot;)<br>    user = UserDocument.get_or_create(first_name=first_name, last_name=last_name)<br><br>    link = event.get(&#39;link&#39;)<br>    crawler = _dispatcher.get_crawler(link)<br><br>    try:<br>        crawler.extract(link=link, user=user)<br><br>        return {&quot;statusCode&quot;: 200, &quot;body&quot;: &quot;Articles processed successfully&quot;}<br>    except Exception as e:<br>        return {&quot;statusCode&quot;: 500, &quot;body&quot;: f&quot;An error occurred: {str(e)}&quot;</pre><p>After you define what it means to transform your Python script into a valid AWS Lambda function, the next phase is to draw the diagram to understand the data flow and how the system will be triggered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lsdtZ_KBvjdAGrqYhwk8qA.png" /><figcaption>AWS High Level Architecture — Overview [Image by the Author]</figcaption></figure><p>Each crawler function is tailored to its data source: fetching posts from <strong>LinkedIn</strong>, articles from <strong>Medium</strong>, and repository data from <strong>GitHub</strong>.</p><p>In order to trigger the lambda function, we have created a <strong>python dispatcher </strong>which is responsible to manage the crawlers for specific domains.</p><p>You can register crawlers for different domains and then use the get_crawler method to get the appropriate crawler for a given URL.</p><pre>import re<br><br>from crawlers.base import BaseCrawler<br><br><br>class CrawlerDispatcher:<br><br>    def __init__(self):<br>        self._crawlers = {}<br><br>    def register(self, domain: str, crawler: BaseCrawler):<br>        self._crawlers[r&quot;https://(www\.)?{}.com/*&quot;.format(re.escape(domain))] = crawler<br><br>    def get_crawler(self, url: str) -&gt; BaseCrawler:<br>        for pattern, crawler in self._crawlers.items():<br>            if re.match(pattern, url):<br>                return crawler()<br>        else:<br>            raise ValueError(&quot;No crawler found for the provided link&quot;)</pre><p>The lambda function can be triggered by invoking the function with a link payload.</p><pre>aws lambda invoke \<br>  --function-name crawler \<br>  --cli-binary-format raw-in-base64-out \<br>  --payload &#39;{&quot;user&quot;: &quot;Paul Iuztin&quot;, &quot;link&quot;: &quot;https://github.com/iusztinpaul/hands-on-llms&quot;}&#39; \<br>  response.json</pre><p>The responsible crawler process its respective data and then pass it to the central <strong>Data Collector MongoDB</strong>.</p><p>The MongoDB component acts as a unified data store, collecting and managing the data harvested by the lambda functions.</p><p>This <strong>infrastructure</strong> is designed for efficient and scalable data extraction, transformation, and loading (ETL) from diverse sources into a single database.</p><h3>6. Wrap-up — Run everything</h3><h4>Cloud Deployment with GitHub Actions and AWS</h4><p>In this final phase, we’ve established a streamlined deployment process using GitHub Actions. This setup automates the build and deployment of our entire system into AWS.</p><p>It’s a hands-off, efficient approach ensuring that every push to our .github folder triggers the necessary actions to maintain your system in the cloud.</p><p>You can delve into the specifics of our infrastructure-as-code (IaC) practices, particularly our use of Pulumi, in the <a href="https://github.com/decodingml/llm-twin-course/tree/main/ops">ops</a> folder within our GitHub repository.</p><p>This is a real-world example of modern DevOps practices, offering a peek into industry-standard methods for deploying and managing cloud infrastructure.</p><h4>Local Testing and Running Options</h4><p>For those preferring a more hands-on approach or wishing to avoid cloud costs, we provide another alternative.</p><p>A detailed <a href="https://github.com/decodingml/llm-twin-course/blob/main/Makefile">Makefile</a> is included in our course materials, allowing you to effortlessly configure and run the entire data pipeline locally.</p><p>It’s especially useful for testing changes in a controlled environment or for those just starting with cloud services.</p><p>For an in-depth explanation and step-by-step instructions, please refer to the <a href="https://github.com/decodingml/llm-twin-course/tree/main"><strong>README</strong></a> in the GitHub repository.</p><h3>Conclusion</h3><p>This is the 2nd article of the<strong> <em>LLM Twin: Building Your Production-Ready AI Replica</em> </strong>free<strong> </strong>course.</p><p>In this lesson, we presented <strong>how to build</strong> a <strong>data pipeline</strong> and why it’s so important in an ML project:</p><p>🔻 <strong>Data collection process</strong> -&gt; Medium, Github, Substack &amp; Linkedin crawlers</p><p>🔻 <strong>ETL pipelines </strong>-&gt; data is cleaned and normalized</p><p>🔻 <strong>ODM</strong> (Object Document Mapping ) -&gt; a technique that maps between an object model in an application and a document database</p><p>🔻<strong> NoSQL Database</strong> (<a href="https://www.linkedin.com/company/mongodbinc/">MongoDB</a>) &amp; <strong>CDC</strong> (Change Data Capture) pattern</p><ul><li>Tracks data changes, logs them, and queues messages for real-time system updates</li><li>The clean data is stored in a NoSQL database</li></ul><p><strong>🔻 Feature Pipeline</strong></p><ul><li>A streaming ingestion pipeline is part of the feature pipeline that processes Articles, Posts, and Code.</li><li>Tools like <a href="https://bytewax.io/?utm_source=medium&amp;utm_medium=decodingml&amp;utm_campaign=2024_q1">Bytewax</a> and <a href="https://superlinked.com/?utm_source=community&amp;utm_medium=blog&amp;utm_campaign=oscourse">Superlinked</a> are used, likely for further data processing and transformation.</li><li>This processed data is then queued in <a href="https://www.linkedin.com/company/rabbitmq/">RabbitMQ</a>, a message broker that helps in asynchronous processing and communication between different services.</li></ul><p>After we went into the details of how to build <strong>data crawlers</strong> for different collections like: user articles, github repositories and user social media posts.</p><p>Ultimately, we went through the process of how to think and prepare your code for AWS by deploying it on lambda functions.</p><p>In <a href="https://medium.com/decodingml/the-3nd-out-of-11-lessons-of-the-llm-twin-free-course-ba82752dad5a"><strong>Lesson 3</strong></a>, we will dive deeper into the <strong>CDC(change data capture) pattern </strong>and explain why it’s a crucial component in any machine learning project, where data is involved.</p><blockquote>🔗 <strong>Check out</strong> <a href="https://github.com/decodingml/llm-twin-course">the code on GitHub</a> [1] and support us with a <em>⭐️</em></blockquote><p>Have you <strong>enjoyed</strong> this <strong>article</strong>? Then…</p><p>↓↓↓</p><p>Join 5k+ engineers in the 𝗗𝗲𝗰𝗼𝗱𝗶𝗻𝗴 𝗠𝗟 𝗡𝗲𝘄𝘀𝗹𝗲𝘁𝘁𝗲𝗿 for battle-tested content on production-grade ML. 𝗘𝘃𝗲𝗿𝘆 𝘄𝗲𝗲𝗸:</p><p><a href="https://decodingml.substack.com/">Decoding ML | Paul Iusztin | Substack</a></p><h3>References</h3><p>[1] <a href="https://github.com/decodingml/llm-twin-course">Your LLM Twin Course — GitHub Repository</a> (2024), Decoding ML GitHub Organization</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=673e1505a861" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>