<?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:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:googleplay="http://www.google.com/schemas/play-podcasts/1.0"><channel><title><![CDATA[Nexus Notes: The Art of Multi-Agent Design]]></title><description><![CDATA[Your playbook for building with multi-agent AI. We dissect complex AI application designs, architectural patterns, training strategies, and deployment guides for technical stakeholders. Learn to build robust, intelligent, and autonomous systems.]]></description><link>https://www.nexusnotes.co</link><image><url>https://substackcdn.com/image/fetch/$s_!g7ea!,w_256,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5c1d6a0e-8acf-4086-8dd0-e09018927183_684x684.png</url><title>Nexus Notes: The Art of Multi-Agent Design</title><link>https://www.nexusnotes.co</link></image><generator>Substack</generator><lastBuildDate>Wed, 06 May 2026 11:48:30 GMT</lastBuildDate><atom:link href="https://www.nexusnotes.co/feed" rel="self" type="application/rss+xml"/><copyright><![CDATA[Alfeo Sabay]]></copyright><language><![CDATA[en]]></language><webMaster><![CDATA[alfeo@substack.com]]></webMaster><itunes:owner><itunes:email><![CDATA[alfeo@substack.com]]></itunes:email><itunes:name><![CDATA[Alfeo Sabay]]></itunes:name></itunes:owner><itunes:author><![CDATA[Alfeo Sabay]]></itunes:author><googleplay:owner><![CDATA[alfeo@substack.com]]></googleplay:owner><googleplay:email><![CDATA[alfeo@substack.com]]></googleplay:email><googleplay:author><![CDATA[Alfeo Sabay]]></googleplay:author><itunes:block><![CDATA[Yes]]></itunes:block><item><title><![CDATA[A Technical Guide to Multi-Agent AI]]></title><description><![CDATA[Building the Sentient Supply Chain]]></description><link>https://www.nexusnotes.co/p/a-technical-guide-to-multi-agent</link><guid isPermaLink="false">https://www.nexusnotes.co/p/a-technical-guide-to-multi-agent</guid><dc:creator><![CDATA[Alfeo Sabay]]></dc:creator><pubDate>Sat, 02 Aug 2025 19:00:37 GMT</pubDate><enclosure url="https://substack-post-media.s3.amazonaws.com/public/images/d23473a9-bcbc-4546-a51f-00fe7b8f3550_2048x2048.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The world of supply chain management is undergoing a seismic shift. I&#8217;ve seen the &#8216;before&#8217; picture firsthand; years ago, I led an engineering team building a B2B Demand Planning Engine. While powerful for its time, it was a world of static, sequential processes that are simply no match for today's market volatility. The future now belongs to a new paradigm: a sentient, self-optimizing supply chain powered by a collaborative crew of AI agents. This isn't science fiction; it's the next evolution in enterprise automation, transforming the supply chain from a rigid set of operations into a responsive, digital nervous system.</p><p>For technical stakeholders, the question isn't <em>why</em> but <em>how</em>. This guide provides a condensed technical blueprint for designing, training, and deploying a sophisticated multi-agent system for autonomous supply chain management.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.nexusnotes.co/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Thanks for reading Nexus Notes: Where AI and ML Meet Innovation! Subscribe for free to receive new posts and support my work.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h3><strong>The Architectural Blueprint: A Hierarchy of Specialists</strong></h3><p>At its core, a multi-agent system tackles complexity by breaking down a massive problem into manageable tasks assigned to specialized agents. For a mission-critical process like supply chain management, a <strong>hierarchical architecture</strong> provides the necessary control, auditability, and alignment with business goals.</p><p>We use <strong>LangGraph</strong>, a framework for building stateful, agentic workflows, to orchestrate this hierarchy. A master SupplyChainSupervisor agent sits at the top, managing the global plan and delegating tasks to a crew of worker agents.</p><p>The workflow operates as a continuous, self-optimizing loop:</p><ol><li><p><strong>Demand Forecasting:</strong> The DemandForecastingAgent analyzes historical data and real-time market signals to predict future demand.</p></li><li><p><strong>Inventory &amp; Risk Analysis:</strong> The forecast is passed to the InventoryManagementAgent to check against current stock levels, while a RiskComplianceAgent scans for potential disruptions.</p></li><li><p><strong>Procurement &amp; Logistics:</strong> Based on this analysis, a nested team of agents manages supplier selection (SupplierLiaisonAgent) and plans optimal shipping routes (LogisticsOptimizationAgent).</p></li><li><p><strong>Quality Assurance &amp; Execution:</strong> A QualityAssuranceAgent reviews the final plan against a predefined rubric before the Supervisor executes the plan by interacting with external systems.</p></li><li><p><strong>Continuous Monitoring:</strong> The system constantly monitors for new events, ready to trigger a re-planning cycle at a moment's notice.</p></li></ol><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!jQ7b!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9e4639e1-31a3-4a79-9ad5-555f07d0b089_789x652.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!jQ7b!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9e4639e1-31a3-4a79-9ad5-555f07d0b089_789x652.png 424w, https://substackcdn.com/image/fetch/$s_!jQ7b!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9e4639e1-31a3-4a79-9ad5-555f07d0b089_789x652.png 848w, https://substackcdn.com/image/fetch/$s_!jQ7b!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9e4639e1-31a3-4a79-9ad5-555f07d0b089_789x652.png 1272w, https://substackcdn.com/image/fetch/$s_!jQ7b!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9e4639e1-31a3-4a79-9ad5-555f07d0b089_789x652.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!jQ7b!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9e4639e1-31a3-4a79-9ad5-555f07d0b089_789x652.png" width="789" height="652" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/9e4639e1-31a3-4a79-9ad5-555f07d0b089_789x652.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:652,&quot;width&quot;:789,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:107173,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.nexusnotes.co/i/169936527?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9e4639e1-31a3-4a79-9ad5-555f07d0b089_789x652.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!jQ7b!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9e4639e1-31a3-4a79-9ad5-555f07d0b089_789x652.png 424w, https://substackcdn.com/image/fetch/$s_!jQ7b!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9e4639e1-31a3-4a79-9ad5-555f07d0b089_789x652.png 848w, https://substackcdn.com/image/fetch/$s_!jQ7b!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9e4639e1-31a3-4a79-9ad5-555f07d0b089_789x652.png 1272w, https://substackcdn.com/image/fetch/$s_!jQ7b!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9e4639e1-31a3-4a79-9ad5-555f07d0b089_789x652.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p></p><h3><strong>Engineering the Agent Crew: Beyond Basic Prompting</strong></h3><p>The intelligence of this system comes from a crew of specialized agents, each strategically engineered for its role. We employ a mix of powerful frontier models, smaller fine-tuned models, and sophisticated training techniques.</p><h4><strong>1. The SupplyChainSupervisor (Orchestrator)</strong></h4><ul><li><p><strong>Role:</strong> The master controller of the LangGraph workflow.</p></li><li><p><strong>Training Strategy:</strong> This agent is <strong>not fine-tuned</strong>. Its intelligence is procedural, defined by meticulously engineered prompts and the coded logic of the LangGraph state machine.</p></li><li><p><strong>Model:</strong> A fast, capable model with excellent tool-use, like <strong>Llama 3 8B-Instruct</strong> or <strong>Gemini 1.5 Flash</strong>, is ideal for low-latency delegation.</p></li></ul><h4><strong>2. The DemandForecastingAgent (The Analyst)</strong></h4><ul><li><p><strong>Role:</strong> Predict future demand by synthesizing historical data and market trends.</p></li><li><p><strong>Training Strategy:</strong> A hybrid approach is used for maximum accuracy:</p></li></ul><ul><li><p><strong>Fine-Tuning:</strong> A model like <strong>Claude 3.5 Sonnet</strong> or a fine-tuned <strong>Mistral 7B</strong> is trained on a dataset of historical sales data paired with ground-truth outcomes. This teaches the model the fundamental demand patterns of the business.</p></li><li><p><strong>Retrieval-Augmented Generation (RAG):</strong> The agent is equipped with a RAG tool connected to a vector database containing market research reports, economic indicators, and news feeds. Before generating a forecast, it retrieves relevant, up-to-the-minute context, dramatically improving its accuracy and relevance.</p></li></ul><h4><strong>3. The InventoryManagementAgent (The Decision-Maker)</strong></h4><ul><li><p><strong>Role:</strong> Monitor stock levels and decide when and how much to reorder.</p></li><li><p><strong>Training Strategy:</strong> This agent is fine-tuned to be a specialized decision engine.</p></li></ul><ul><li><p><strong>Fine-Tuning:</strong> A smaller model like <strong>Llama 3 8B</strong> is trained on a dataset of inventory scenarios. Each data point consists of inputs (current stock, demand forecast, lead times) and the optimal output action (e.g., { "action": "CREATE_PURCHASE_ORDER", "quantity": 5000 }), derived from established inventory formulas like Economic Order Quantity (EOQ). This transforms the LLM into a reliable, cost-effective tool for a specific, repetitive task.</p></li></ul><h4><strong>4. The QualityAssuranceAgent &amp; The Human-in-the-Loop (The Guardian)</strong></h4><ul><li><p><strong>Role:</strong> The critical junction for ensuring trust and accuracy. This agent reviews the system's proposed plans and flags anomalies for human review.</p></li><li><p><strong>Training Strategy:</strong> The focus here is on the process, not the model.</p></li></ul><ul><li><p><strong>LLM-as-Judge:</strong> A powerful frontier model like <strong>GPT-4o</strong> is given a detailed, expert-defined <strong>rubric</strong>. It is prompted to evaluate the final plan against this rubric, providing scores and justifications. If any criterion fails, the plan is automatically flagged.</p></li><li><p><strong>Human-in-the-Loop (HITL):</strong> Flagged plans are sent to a human expert via a dedicated UI. The expert's role is twofold: 1) to make the final decision and correct the plan, and 2) to provide structured feedback on <em>why</em> the plan was flawed.</p></li><li><p><strong>The Feedback Loop:</strong> This expert feedback is invaluable. Each correction becomes a high-quality data point that is fed back into the fine-tuning datasets for the other agents. This creates a virtuous cycle where the system learns directly from expert oversight, continuously improving its accuracy and reliability over time.</p></li></ul><h3><strong>Production Deployment on AWS</strong></h3><p>An enterprise-grade agentic system requires a scalable and resilient infrastructure. Our blueprint leverages a container-based approach orchestrated with Kubernetes.</p><ul><li><p><strong>Containerization:</strong> Each agent is packaged as a microservice using <strong>Docker</strong> and stored in <strong>Amazon Elastic Container Registry (ECR)</strong>. This isolates dependencies and allows for independent scaling.</p></li><li><p><strong>Orchestration:</strong> <strong>Amazon Elastic Kubernetes Service (EKS)</strong> manages the container lifecycle. We use a multi-node group strategy:</p></li></ul><ul><li><p><strong>CPU Node Group:</strong> For standard services like the API gateway and message brokers.</p></li><li><p><strong>GPU Node Group:</strong> For the agent services that require GPU acceleration (e.g., DemandForecastingAgent), using instances from the P3 or G5 families.</p></li></ul><ul><li><p><strong>Autoscaling:</strong> We use <strong>Karpenter</strong>, an AWS-built cluster autoscaler, to provision right-sized EC2 instances (including GPUs) on-demand, optimizing both performance and cost.</p></li><li><p><strong>Communication:</strong> A hybrid model is used. Low-latency internal requests between agents use <strong>gRPC</strong>, load-balanced by an <strong>Application Load Balancer (ALB)</strong>. Asynchronous handoffs to external systems use a managed message broker like <strong>Amazon MQ for RabbitMQ</strong> for resilience.</p></li></ul><h3><strong>The Path Forward</strong></h3><p>Building a multi-agent system is a journey from automation to autonomy. By combining hierarchical control, specialized agent training, and a robust human-in-the-loop validation process, we can construct a supply chain that doesn't just execute commands but senses, reasons, and adapts. This is the foundation for creating a truly sentient supply chain&#8212;one that is not only more efficient and resilient but also a powerful competitive advantage in an increasingly unpredictable world.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.nexusnotes.co/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Thanks for reading Nexus Notes: Where AI and ML Meet Innovation! Subscribe for free to receive new posts and support my work.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item><item><title><![CDATA[Architecting HIPAA-Compliant Cloud-Native AI/LLM Services on AWS]]></title><description><![CDATA[A Comprehensive Guide]]></description><link>https://www.nexusnotes.co/p/architecting-hipaa-compliant-cloud</link><guid isPermaLink="false">https://www.nexusnotes.co/p/architecting-hipaa-compliant-cloud</guid><dc:creator><![CDATA[Alfeo Sabay]]></dc:creator><pubDate>Sat, 11 Nov 2023 03:48:07 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!6tJH!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9585538-0542-47e5-adb9-ddb708429ea8_1000x348.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3>Introduction</h3><p>In the ever-evolving landscape of healthcare technology, the fusion of Cloud-Native architecture with Artificial Intelligence (AI) and Large Language Models (LLM) is redefining patient care. As organizations harness the power of cloud platforms, such as AWS, to develop sophisticated AI/LLM solutions, ensuring compliance with the Health Insurance Portability and Accountability Act (HIPAA) becomes paramount. This comprehensive exploration dives into the intricacies of designing HIPAA-compliant Cloud-Native AI/LLM services on AWS, with each technical facet tailored to the unique challenges of healthcare AI.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!6tJH!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9585538-0542-47e5-adb9-ddb708429ea8_1000x348.jpeg" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!6tJH!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9585538-0542-47e5-adb9-ddb708429ea8_1000x348.jpeg 424w, https://substackcdn.com/image/fetch/$s_!6tJH!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9585538-0542-47e5-adb9-ddb708429ea8_1000x348.jpeg 848w, https://substackcdn.com/image/fetch/$s_!6tJH!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9585538-0542-47e5-adb9-ddb708429ea8_1000x348.jpeg 1272w, https://substackcdn.com/image/fetch/$s_!6tJH!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9585538-0542-47e5-adb9-ddb708429ea8_1000x348.jpeg 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!6tJH!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9585538-0542-47e5-adb9-ddb708429ea8_1000x348.jpeg" width="1000" height="348" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/c9585538-0542-47e5-adb9-ddb708429ea8_1000x348.jpeg&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:348,&quot;width&quot;:1000,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:211270,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/jpeg&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!6tJH!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9585538-0542-47e5-adb9-ddb708429ea8_1000x348.jpeg 424w, https://substackcdn.com/image/fetch/$s_!6tJH!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9585538-0542-47e5-adb9-ddb708429ea8_1000x348.jpeg 848w, https://substackcdn.com/image/fetch/$s_!6tJH!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9585538-0542-47e5-adb9-ddb708429ea8_1000x348.jpeg 1272w, https://substackcdn.com/image/fetch/$s_!6tJH!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9585538-0542-47e5-adb9-ddb708429ea8_1000x348.jpeg 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h4>LLM Inference Design Considerations</h4><p>In the realm of designing HIPAA-compliant Cloud-Native AI/LLM services on AWS, the choice of Large Language Models (LLM) is a crucial consideration. Organizations often opt for well-established LLM frameworks like OpenAI's GPT-3 or BERT for their natural language processing capabilities in healthcare applications. The careful selection of an LLM depends on the specific requirements of the AI/LLM service, such as the complexity of language understanding, context retention, and data leak prevention. Moreover, privacy concerns in healthcare underscore the importance of leveraging private LLM inferences. AWS facilitates this by offering services like Amazon SageMaker for deploying models within a Virtual Private Cloud (VPC), ensuring that LLM inferences are performed in a secure and isolated environment. This approach aligns with HIPAA compliance, as it adds an additional layer of protection to patient data processed through language models, assuring confidentiality and meeting the stringent privacy requirements of healthcare regulations.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.nexusnotes.co/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Thanks for reading Nexus Notes: Where AI and ML Meet Innovation! Subscribe for free to receive new posts and support my work.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!z70z!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e5a52c0-9382-47fa-860b-e80c3a805c3e_2290x1376.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!z70z!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e5a52c0-9382-47fa-860b-e80c3a805c3e_2290x1376.png 424w, https://substackcdn.com/image/fetch/$s_!z70z!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e5a52c0-9382-47fa-860b-e80c3a805c3e_2290x1376.png 848w, https://substackcdn.com/image/fetch/$s_!z70z!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e5a52c0-9382-47fa-860b-e80c3a805c3e_2290x1376.png 1272w, https://substackcdn.com/image/fetch/$s_!z70z!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e5a52c0-9382-47fa-860b-e80c3a805c3e_2290x1376.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!z70z!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e5a52c0-9382-47fa-860b-e80c3a805c3e_2290x1376.png" width="723" height="434.4951923076923" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/1e5a52c0-9382-47fa-860b-e80c3a805c3e_2290x1376.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:875,&quot;width&quot;:1456,&quot;resizeWidth&quot;:723,&quot;bytes&quot;:772133,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!z70z!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e5a52c0-9382-47fa-860b-e80c3a805c3e_2290x1376.png 424w, https://substackcdn.com/image/fetch/$s_!z70z!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e5a52c0-9382-47fa-860b-e80c3a805c3e_2290x1376.png 848w, https://substackcdn.com/image/fetch/$s_!z70z!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e5a52c0-9382-47fa-860b-e80c3a805c3e_2290x1376.png 1272w, https://substackcdn.com/image/fetch/$s_!z70z!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e5a52c0-9382-47fa-860b-e80c3a805c3e_2290x1376.png 1456w" sizes="100vw"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Image Credit: AWS HIPAA Reference Architecture</p><h3><strong>Foundational Security: Integrating Security by Design into AI/LLM</strong></h3><p>The foundation of a Cloud-Native AI/LLM service lies in the principle of Security by Design. AWS Identity and Access Management (IAM) plays a pivotal role in managing access to AI/LLM models and datasets. Encryption, facilitated by AWS Key Management Service (KMS), is strategically embedded into the architecture, securing both at-rest and in-transit data. This design ensures that sensitive patient information processed by AI/LLM algorithms is shielded, aligning seamlessly with HIPAA's stringent security requirements.</p><h3><strong>Decoupled Architecture: Enhancing Scalability and Privacy in AI/LLM</strong></h3><p>AI/LLM services should adopt a decoupled architecture, leveraging AWS-native Kubernetes service and microservices. This design not only enhances the scalability of AI/LLM models but also aligns with the privacy requirements stipulated by HIPAA. Each microservice operates independently, allowing for isolated updates and reducing the potential attack surface which are critical considerations when dealing with sensitive patient data.</p><h3><strong>Data Encryption: Safeguarding Patient Data in AI/LLM Processing</strong></h3><p>In the context of AI/LLM services, data encryption is a critical component in maintaining HIPAA compliance. Utilizing AWS KMS, our Cloud-Native AI/LLM service ensures that patient data is encrypted before, during, and after processing. This robust encryption strategy not only adheres to HIPAA standards but also fortifies the AI/LLM service against potential security threats.</p><h3><strong>Access Controls and Identity Management: Ensuring Authorized Usage</strong></h3><p>AI/LLM services often involve multiple stakeholders accessing and interacting with models and datasets. AWS IAM, in this scenario, plays a pivotal role in defining granular access controls. By adhering to the principle of least privilege, access to AI/LLM resources is restricted, ensuring that only authorized personnel can utilize and modify the models. This aligns seamlessly with HIPAA's access control mandates, crucial in safeguarding patient data processed by AI/LLM algorithms.</p><h3><strong>Audit Trails : Tracking AI/LLM Model Interactions for Compliance</strong></h3><p>HIPAA compliance demands detailed audit trails, a requirement met by AWS CloudTrail in a Cloud-Native AI/LLM service. Every interaction with AI/LLM models, including data inputs and outputs can be meticulously logged. These logs not only satisfy regulatory compliance but also provide a comprehensive view of how AI/LLM models are utilized, aiding in both auditing and improving the overall AI/LLM service.</p><h3><strong>Secure APIs: Enabling Interoperability in AI/LLM Solutions</strong></h3><p>Interoperability is a key consideration in healthcare AI/LLM solutions. Secure APIs, facilitated by AWS API Gateway and following the OAuth standard, enable seamless integration with other healthcare systems while adhering to HIPAA's encryption and access control requirements. This ensures that data exchanged between AI/LLM services and external systems complies with privacy and security standards.</p><h3><strong>Disaster Recovery and Data Resilience: Ensuring Continuity in AI/LLM Operations</strong></h3><p>For AI/LLM services, data resilience and disaster recovery are paramount. AWS-native services like Amazon S3 for data storage and Amazon Aurora for databases contribute to the robustness of our Cloud-Native AI/LLM service. Automated backup mechanisms and geo-redundancy ensure that patient data remains accessible, even in the face of unforeseen disruptions, aligning with HIPAA's requirements for data availability and integrity.</p><h3><strong>Compliance as Code: Automating Governance and Compliance in AI/LLM</strong></h3><p>In the world of AI/LLM, automation becomes a powerful ally. Compliance as Code principles, implemented through AWS CloudFormation, define and deploy the entire infrastructure of our Cloud-Native AI/LLM service. AWS Config continuously monitors compliance, automatically remediating any deviations. This approach not only streamlines the governance of AI/LLM systems but also ensures ongoing HIPAA compliance.</p><h3><strong>Ongoing Compliance Monitoring : Adapting to Evolving AI/LLM Regulations</strong></h3><p>AI/LLM systems are subject to evolving regulatory landscapes. Regular vulnerability scans, facilitated by AWS-native services like Amazon Inspector, ensure that the AI/LLM service remains resilient to emerging threats. Continuous compliance monitoring, with tools like AWS Security Hub, empowers the AI/LLM service to adapt proactively to evolving HIPAA regulations.</p><h3><strong>Conclusion: Navigating the Future of Healthcare with AI/LLM Designs</strong></h3><p>In conclusion, the design of HIPAA-compliant Cloud-Native AI/LLM services on AWS exemplifies the delicate balance between innovation and regulatory adherence. By intertwining the capabilities of AWS cloud infrastructure with the intricacies of AI and LLM, healthcare organizations can pioneer the future of patient-centric, data-driven care. This approach not only meets current HIPAA standards but also positions healthcare AI/LLM systems to navigate the evolving landscape of regulatory requirements, ensuring a future where cutting-edge technology aligns seamlessly with the principles of privacy, security, and patient well-being. The amalgamation of AWS's robust cloud services with AI/LLM solutions sets the stage for a healthcare revolution where innovation and compliance coexist harmoniously.</p><p><strong>References:</strong></p><p>US Department of Health and Human Services: https://www.hhs.gov/hipaa/index.html</p><p>Architecting for HIPAA Security and Compliance on Amazon Web Services: https://docs.aws.amazon.com/whitepapers/latest/architecting-hipaa-security-and-compliance-on-aws/architecting-hipaa-security-and-compliance-on-aws.html</p><p>HIPAA Reference Architecture on AWS: https://aws.amazon.com/solutions/implementations/compliance-hipaa/</p><p>Health Insurance Portability and Accountability Act (HIPAA) Security Rule 2003: https://docs.aws.amazon.com/audit-manager/latest/userguide/HIPAA.html</p><p></p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.nexusnotes.co/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Thanks for reading Nexus Notes: Where AI and ML Meet Innovation! Subscribe for free to receive new posts and support my work.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item><item><title><![CDATA[🚀 🔥 AI Medical Assistant Part 2: LLM and Chatbot Deployment]]></title><description><![CDATA[AI augmentation is set to reshape medical clinicians' roles, boosting efficiency and healthcare quality. - Contact info@mlpipes.xyz for more info]]></description><link>https://www.nexusnotes.co/p/ai-medical-assistant-part-2-llm-and</link><guid isPermaLink="false">https://www.nexusnotes.co/p/ai-medical-assistant-part-2-llm-and</guid><dc:creator><![CDATA[Alfeo Sabay]]></dc:creator><pubDate>Wed, 20 Sep 2023 20:29:47 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!lozG!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fae27c2c6-6a15-4c7e-baf3-c8c04839e6a5_721x682.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Introduction:</strong></p><p>Let's revisit the key highlights from <a href="https://www.nexusnotes.blog/p/building-an-ai-medical-assistant">Part 1</a> of our journey. In our pursuit of optimizing training costs while aligning with smaller GPU instances, we meticulously configured a PEFT/LoRA model, implementing 4-bit quantization (QLoRA) through BitsAndBytesConfig. This strategic setup, executed prior to its utilization in the training script, effectively mitigated memory consumption during the training phase.</p><p>With the publicly available <a href="https://arxiv.org/abs/2004.03329">MedDialog</a> dataset, the comprehensive fine-tuning endeavor demanded a total of 97 hours, spanning across 2 epochs, culminating in the convergence of the learning rate at 4.55e-8 and the training loss stabilizing at 1.71. The utilization of AWS SageMaker spot instances significantly reduced expenditure, albeit extending the training period due to intermittent interruptions, ultimately amounting to a remarkable 60% cost reduction, from an estimated $687.73 to $287.92. Notably, these insights underscore the intricate balance between time and expenditure.</p><p>Throughout this process, we harnessed the power of the <a href="https://wandb.ai">W &amp; B platform</a>, seamlessly integrated with the wandb API within our training script, enabling us to diligently monitor our progress.</p><p>The overarching lesson derived from this phase is the pivotal trade-off between time efficiency and cost-effectiveness, particularly on larger GPU instances. It is noteworthy that our customized md-assistant model is readily accessible through <a href="https://huggingface.co/mlpipes-asabay/md-assistant">MLPipes on the Hugging Face model hub</a>, adhering to llama2 license terms.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!lozG!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fae27c2c6-6a15-4c7e-baf3-c8c04839e6a5_721x682.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!lozG!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fae27c2c6-6a15-4c7e-baf3-c8c04839e6a5_721x682.png 424w, https://substackcdn.com/image/fetch/$s_!lozG!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fae27c2c6-6a15-4c7e-baf3-c8c04839e6a5_721x682.png 848w, https://substackcdn.com/image/fetch/$s_!lozG!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fae27c2c6-6a15-4c7e-baf3-c8c04839e6a5_721x682.png 1272w, https://substackcdn.com/image/fetch/$s_!lozG!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fae27c2c6-6a15-4c7e-baf3-c8c04839e6a5_721x682.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!lozG!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fae27c2c6-6a15-4c7e-baf3-c8c04839e6a5_721x682.png" width="721" height="682" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/ae27c2c6-6a15-4c7e-baf3-c8c04839e6a5_721x682.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:682,&quot;width&quot;:721,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:113349,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!lozG!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fae27c2c6-6a15-4c7e-baf3-c8c04839e6a5_721x682.png 424w, https://substackcdn.com/image/fetch/$s_!lozG!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fae27c2c6-6a15-4c7e-baf3-c8c04839e6a5_721x682.png 848w, https://substackcdn.com/image/fetch/$s_!lozG!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fae27c2c6-6a15-4c7e-baf3-c8c04839e6a5_721x682.png 1272w, https://substackcdn.com/image/fetch/$s_!lozG!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fae27c2c6-6a15-4c7e-baf3-c8c04839e6a5_721x682.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Now, as we move forward armed with our finely-tuned model, we embark on the exciting journey of deploying it onto a production-grade AWS inference point and constructing a Streamlit Chatbot, serving as a Minimum Viable Product (MVP) User Interface. Furthermore, with the Chatbot in place, we gain the ability to rigorously assess the accuracy and relevance of our model's outputs. The next phase beckons with anticipation&#8212;let's proceed! &#128640;</p><p></p><p><strong>Deployment on AWS SageMaker:</strong></p><p>The deployment process for our md-assistant model on AWS SageMaker exemplifies simplicity and efficiency. Leveraging the SageMaker platform, we establish an inference point with precision. This entails the creation of model and endpoint configurations, followed by the seamless deployment of our model into a Docker Container. Notably, we opted for Hugging Face DLC Containers, a strategic choice that aligns harmoniously with our model's architecture and encapsulates the essence of our project's versatility and extensibility. As in the fine-tuning stage, we use a 4 GPU instance (ml.g5.12xlarge) to host the inference point. Below, you will find an illustrative snippet that sheds light on the elegance and efficacy of this deployment process, a testament to the seamless fusion of cutting-edge AI technologies with SageMaker's robust infrastructure. </p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!gMDx!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa012aa2f-d2d4-499f-80a7-8a3ebcb10534_888x739.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!gMDx!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa012aa2f-d2d4-499f-80a7-8a3ebcb10534_888x739.png 424w, https://substackcdn.com/image/fetch/$s_!gMDx!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa012aa2f-d2d4-499f-80a7-8a3ebcb10534_888x739.png 848w, https://substackcdn.com/image/fetch/$s_!gMDx!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa012aa2f-d2d4-499f-80a7-8a3ebcb10534_888x739.png 1272w, https://substackcdn.com/image/fetch/$s_!gMDx!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa012aa2f-d2d4-499f-80a7-8a3ebcb10534_888x739.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!gMDx!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa012aa2f-d2d4-499f-80a7-8a3ebcb10534_888x739.png" width="888" height="739" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/a012aa2f-d2d4-499f-80a7-8a3ebcb10534_888x739.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:739,&quot;width&quot;:888,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:170007,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!gMDx!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa012aa2f-d2d4-499f-80a7-8a3ebcb10534_888x739.png 424w, https://substackcdn.com/image/fetch/$s_!gMDx!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa012aa2f-d2d4-499f-80a7-8a3ebcb10534_888x739.png 848w, https://substackcdn.com/image/fetch/$s_!gMDx!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa012aa2f-d2d4-499f-80a7-8a3ebcb10534_888x739.png 1272w, https://substackcdn.com/image/fetch/$s_!gMDx!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa012aa2f-d2d4-499f-80a7-8a3ebcb10534_888x739.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>By returning the huggingface_model object in addition to the predictor object, we are able to delete and clean up these resources at a later time to avoid unnecessary inference hosting charges.</p><p><strong>Configuring endpoints for real-time interaction</strong></p><p>In the realm of a comprehensive production deployment, it is customary to establish a RESTful API endpoint, traditionally crafted using the Flask framework. This well-established practice is fortified with robust authentication and security measures, safeguarding the integrity of the system. However, within the context of our specific project, where the test client, embodied as the Streamlit Chatbot, operates from an AWS CLI-enabled local machine, we have chosen a streamlined approach. We have strategically implemented the Langchain LLM endpoint object, meticulously designed for SageMaker, and ingeniously integrated it within a ConversationChain object enriched with memory. This astute decision is a testament to our commitment to alignment with precise requirements and optimization for efficiency. While delving into the intricacies of Langchain implementation is beyond the scope of this discussion, a forthcoming blog may offer a comprehensive exploration of its integration within a Chatbot QA use-case. Below, you will find a code snippet that vividly exemplifies the elegance and efficiency inherent in our deployment strategy, highlighting its adaptability and versatility.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!7iMu!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F02826ad5-034f-43aa-a048-76a8e148a7ec_572x684.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!7iMu!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F02826ad5-034f-43aa-a048-76a8e148a7ec_572x684.png 424w, https://substackcdn.com/image/fetch/$s_!7iMu!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F02826ad5-034f-43aa-a048-76a8e148a7ec_572x684.png 848w, https://substackcdn.com/image/fetch/$s_!7iMu!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F02826ad5-034f-43aa-a048-76a8e148a7ec_572x684.png 1272w, https://substackcdn.com/image/fetch/$s_!7iMu!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F02826ad5-034f-43aa-a048-76a8e148a7ec_572x684.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!7iMu!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F02826ad5-034f-43aa-a048-76a8e148a7ec_572x684.png" width="572" height="684" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/02826ad5-034f-43aa-a048-76a8e148a7ec_572x684.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:684,&quot;width&quot;:572,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:120662,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!7iMu!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F02826ad5-034f-43aa-a048-76a8e148a7ec_572x684.png 424w, https://substackcdn.com/image/fetch/$s_!7iMu!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F02826ad5-034f-43aa-a048-76a8e148a7ec_572x684.png 848w, https://substackcdn.com/image/fetch/$s_!7iMu!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F02826ad5-034f-43aa-a048-76a8e148a7ec_572x684.png 1272w, https://substackcdn.com/image/fetch/$s_!7iMu!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F02826ad5-034f-43aa-a048-76a8e148a7ec_572x684.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong>The Streamlit Chatbot</strong></p><p>And within chat-md.py we access the endpoint through the ConversationChain&#8230;</p><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!YIUz!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2644159-8ae7-400a-a8ce-926f29b579e4_766x166.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!YIUz!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2644159-8ae7-400a-a8ce-926f29b579e4_766x166.png 424w, https://substackcdn.com/image/fetch/$s_!YIUz!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2644159-8ae7-400a-a8ce-926f29b579e4_766x166.png 848w, https://substackcdn.com/image/fetch/$s_!YIUz!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2644159-8ae7-400a-a8ce-926f29b579e4_766x166.png 1272w, https://substackcdn.com/image/fetch/$s_!YIUz!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2644159-8ae7-400a-a8ce-926f29b579e4_766x166.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!YIUz!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2644159-8ae7-400a-a8ce-926f29b579e4_766x166.png" width="727" height="157.54830287206266" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/f2644159-8ae7-400a-a8ce-926f29b579e4_766x166.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:166,&quot;width&quot;:766,&quot;resizeWidth&quot;:727,&quot;bytes&quot;:25768,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!YIUz!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2644159-8ae7-400a-a8ce-926f29b579e4_766x166.png 424w, https://substackcdn.com/image/fetch/$s_!YIUz!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2644159-8ae7-400a-a8ce-926f29b579e4_766x166.png 848w, https://substackcdn.com/image/fetch/$s_!YIUz!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2644159-8ae7-400a-a8ce-926f29b579e4_766x166.png 1272w, https://substackcdn.com/image/fetch/$s_!YIUz!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2644159-8ae7-400a-a8ce-926f29b579e4_766x166.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!T3ba!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd2b452d2-0709-4029-8e18-69c398359ff5_703x358.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!T3ba!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd2b452d2-0709-4029-8e18-69c398359ff5_703x358.png 424w, https://substackcdn.com/image/fetch/$s_!T3ba!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd2b452d2-0709-4029-8e18-69c398359ff5_703x358.png 848w, https://substackcdn.com/image/fetch/$s_!T3ba!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd2b452d2-0709-4029-8e18-69c398359ff5_703x358.png 1272w, https://substackcdn.com/image/fetch/$s_!T3ba!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd2b452d2-0709-4029-8e18-69c398359ff5_703x358.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!T3ba!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd2b452d2-0709-4029-8e18-69c398359ff5_703x358.png" width="727" height="370.22190611664297" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/d2b452d2-0709-4029-8e18-69c398359ff5_703x358.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:358,&quot;width&quot;:703,&quot;resizeWidth&quot;:727,&quot;bytes&quot;:56467,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!T3ba!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd2b452d2-0709-4029-8e18-69c398359ff5_703x358.png 424w, https://substackcdn.com/image/fetch/$s_!T3ba!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd2b452d2-0709-4029-8e18-69c398359ff5_703x358.png 848w, https://substackcdn.com/image/fetch/$s_!T3ba!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd2b452d2-0709-4029-8e18-69c398359ff5_703x358.png 1272w, https://substackcdn.com/image/fetch/$s_!T3ba!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd2b452d2-0709-4029-8e18-69c398359ff5_703x358.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Upon user input into the chatbot, a pivotal event unfolds&#8212;the invocation of the on_click_callback() function. Within this function lies the core of our implementation, where we execute the ConversationChain object. This masterful orchestration involves processing the input text and summoning the deployed md-assistant to procure a precise and context-aware reply.</p><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!T7mx!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83c54d91-2f45-4fb8-b30c-347496409960_662x281.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!T7mx!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83c54d91-2f45-4fb8-b30c-347496409960_662x281.png 424w, https://substackcdn.com/image/fetch/$s_!T7mx!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83c54d91-2f45-4fb8-b30c-347496409960_662x281.png 848w, https://substackcdn.com/image/fetch/$s_!T7mx!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83c54d91-2f45-4fb8-b30c-347496409960_662x281.png 1272w, https://substackcdn.com/image/fetch/$s_!T7mx!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83c54d91-2f45-4fb8-b30c-347496409960_662x281.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!T7mx!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83c54d91-2f45-4fb8-b30c-347496409960_662x281.png" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/83c54d91-2f45-4fb8-b30c-347496409960_662x281.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:48265,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!T7mx!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83c54d91-2f45-4fb8-b30c-347496409960_662x281.png 424w, https://substackcdn.com/image/fetch/$s_!T7mx!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83c54d91-2f45-4fb8-b30c-347496409960_662x281.png 848w, https://substackcdn.com/image/fetch/$s_!T7mx!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83c54d91-2f45-4fb8-b30c-347496409960_662x281.png 1272w, https://substackcdn.com/image/fetch/$s_!T7mx!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83c54d91-2f45-4fb8-b30c-347496409960_662x281.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><p>The default appearance of Streamlit's seemingly straightforward components left me yearning for more, prompting me to delve into the world of CSS customization to create a more aesthetically pleasing user interface. For an in-depth exploration of this customization process, I recommend perusing Fanilo Andrianasolo's GitHub repository, which offers valuable insights into this artful endeavor. Additionally, you can find the chatbot's code within the Chatbot folder on my GitHub repository dedicated to this project, providing a comprehensive resource for those seeking further details and inspiration.</p><p>Here&#8217;s a screen recording of the md-assistant chatbot in operation &#129299;</p><div class="native-video-embed" data-component-name="VideoPlaceholder" data-attrs="{&quot;mediaUploadId&quot;:&quot;b1f7369d-a5be-42e3-961b-8f0ef3270365&quot;,&quot;duration&quot;:null}"></div><p><strong>Model Performance Evaluation:</strong></p><p>Given the fine-tuned nature of the md-assistant model to cater specifically to clinician-to-patient dialogues, our testing protocol entails the rigorous examination of simulated user inputs that have never previously crossed paths with the md-assistant model. This meticulous approach is indispensable for assessing accuracy and contextual relevance. In my comprehensive testing endeavor, I subjected the model to 100 out-of-bag questions, and the results unequivocally showcased responses that remained impeccably contextual and entirely pertinent to the addressed topics. Moreover, the model's versatility was evident as it responded to the same questions with slight variations, preserving context, thanks to the 'repetition_penalty' setting of 1.03 and a 'temperature' value of 0.7. However, it is essential to emphasize that the true accuracy of the llm response can only be comprehensively evaluated by licensed medical clinicians&#8212;a step we have yet to undertake.</p><p>In a real-world, commercially deployed application of the md-assistant llm model, a critical phase would encompass Subject Matter Expert (SME) evaluation, instrumental for model testing and validation. Furthermore, standard operating procedure for deploying a fine-tuned chat model like this involves an exhaustive scrutiny of dialog and meticulous data anonymization, ensuring compliance with the stringent requirements of HIPAA. In such scenarios, the model can be further fine-tuned to align precisely with a specific clinician's advisory history, a departure from the MedDialog public dataset, which encompasses a vast array of over 250,000 utterances, spanning 51 medical categories and 96 specialties, from diverse patients and medical professionals.</p><p><strong>Conclusion and Key Takeaways</strong></p><p>Our journey, spanning both fine-tuning and deployment stages, has uncovered several key insights and achievements:</p><p>1. <strong>Optimized Training:</strong> We diligently tailored our PEFT/LoRA model, implementing 4-bit quantization (QLoRA) through BitsAndBytesConfig, successfully mitigating memory consumption during training&#8212;a crucial step towards cost-effective GPU utilization.</p><p>2. <strong>Efficiency vs. Cost:</strong> Balancing time efficiency and cost-effectiveness in GPU instance selection was paramount. Utilizing AWS SageMaker spot instances achieved a remarkable 60% cost reduction, albeit with extended training periods.</p><p>3. <strong>Monitoring with W &amp; B:</strong> Our integration of the W &amp; B platform and wandb API provided invaluable progress monitoring, ensuring fine-tuning precision.</p><p>4. <strong>Deployment Excellence:</strong> Deploying on AWS SageMaker was a seamless process, with Docker Container utilization, highlighting our strategic choice of Hugging Face DLC Containers for compatibility and adaptability.</p><p>5. <strong>Real-time Interaction:</strong> Implementing Langchain LLM endpoints within a ConversationChain object, a deviation from traditional RESTful API approaches, showcased our commitment to tailored efficiency.</p><p>6. <strong>UI Customization:</strong> We delved into CSS customization to enhance the Streamlit Chatbot's user interface, offering an improved user experience.</p><p>7. <strong>Model Testing:</strong>  Rigorous testing of the fine-tuned model with simulated user inputs revealed contextually precise responses. Repetition_penalty settings allowed for nuanced variations, emphasizing adaptability.</p><p>8. <strong>SME Evaluation: </strong>In a real-world, commercial deployment, Subject Matter Expert (SME) evaluation and HIPAA-compliant data anonymization would be pivotal, showcasing the model's flexibility in adapting to specific clinician advisory histories.</p><p>In essence, our journey underscores the fusion of cutting-edge AI technologies with efficient deployment strategies and meticulous model testing. While we've made significant strides, the path ahead holds exciting possibilities as we continue to refine and adapt our md-assistant LLM model to the dynamic field of clinician-patient interactions. </p><p><strong>Project Demo:</strong></p><p>If you're eager to witness a live demonstration of our end-to-end Chatbot application in action, don't hesitate to reach out to me directly at <a href="mailto:info@mlpipes.xyz">MLPipes</a>. I'd be delighted to schedule a convenient time to showcase the demo. While we're unable to maintain a live deployment of the model due to GPU hosting costs, you can alternatively engage with me via the <a href="https://www.mlpipes.xyz">MLPipes Chatbot</a>.</p><p>Should you have a specific LLM Customization project in mind and seek to explore possibilities, I encourage you to initiate contact with me at <a href="mailto:info@mlpipes.xyz">MLPipes</a>. I'm more than willing to engage in a productive discussion about your project needs. At <a href="https://mlpipes.xyz">MLPipes</a>, our expertise lies in Machine Learning Engineering and LLM Customization, and we're eager to collaborate on your next endeavor. &#128640;</p><p>For those who found value in this blog, we extend an invitation to seize the opportunity for a complimentary subscription below.</p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.nexusnotes.co/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.nexusnotes.co/subscribe?"><span>Subscribe now</span></a></p><p><strong>References:</strong></p><p><a href="https://ai.meta.com/llama/">Meta Llama 2</a></p><p><a href="https://github.com/huggingface/notebooks/blob/main/sagemaker/27_deploy_large_language_models/sagemaker-notebook.ipynb">Philip Schmid: How to deploy Large Language Models (LLMs) to Amazon SageMaker using new Hugging Face LLM DLC</a></p><p><a href="https://github.com/samrawal/llama2_chat_templater/tree/main">Sam Rawal: Llama2 Chat Templater</a></p><p><a href="https://api.python.langchain.com/en/latest/api_reference.html">Langchain API</a></p><p><a href="https://github.com/andfanilo/social-media-tutorials">Fanilo Andrianasolo: Social Media Tutorials Github</a> - Fantastic examples on how to add css to Streamlit!!</p><p><a href="https://github.com/alsabay/ai_md_assistant/blob/main/README.md">Alfeo Sabay: MD Assistant Github</a></p><p><a href="https://huggingface.co/mlpipes-asabay/md-assistant">Alfeo Sabay: MLPipes Hugging Face Model Hub </a> - Where you can access this fantastic model!! &#128170;&#128640;&#128513;</p><p></p>]]></content:encoded></item><item><title><![CDATA["Building an AI Medical Assistant Part 1: LLama2 Fine-Tuning with Hugging Face Containers, QLoRA and PEFT With WANDB in AWS Sagemaker Spot Instances to cut LLM customization costs.”]]></title><description><![CDATA[&#128640; Boost your LLama2 fine-tuning projects to new heights with the power of Hugging Face Transformers and AWS Spot Instances! &#128176; Save up to 90% on your fine-tuning customization costs.]]></description><link>https://www.nexusnotes.co/p/building-an-ai-medical-assistant</link><guid isPermaLink="false">https://www.nexusnotes.co/p/building-an-ai-medical-assistant</guid><dc:creator><![CDATA[Alfeo Sabay]]></dc:creator><pubDate>Fri, 01 Sep 2023 13:00:29 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!kz_i!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F42c5d08e-7734-480c-9121-3495b49944d6_1024x1024.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3>I. <strong>Introduction</strong></h3><p>Generative AI is currently gaining a lot of momentum. Modern Large Language Models have the ability to generate relevant responses to human queries. This has motivated many new AI startups to apply this capability to everyday business tasks, automate workflows and processes, and improve work products.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!kz_i!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F42c5d08e-7734-480c-9121-3495b49944d6_1024x1024.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!kz_i!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F42c5d08e-7734-480c-9121-3495b49944d6_1024x1024.png 424w, https://substackcdn.com/image/fetch/$s_!kz_i!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F42c5d08e-7734-480c-9121-3495b49944d6_1024x1024.png 848w, https://substackcdn.com/image/fetch/$s_!kz_i!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F42c5d08e-7734-480c-9121-3495b49944d6_1024x1024.png 1272w, https://substackcdn.com/image/fetch/$s_!kz_i!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F42c5d08e-7734-480c-9121-3495b49944d6_1024x1024.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!kz_i!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F42c5d08e-7734-480c-9121-3495b49944d6_1024x1024.png" width="372" height="372" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/42c5d08e-7734-480c-9121-3495b49944d6_1024x1024.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1024,&quot;width&quot;:1024,&quot;resizeWidth&quot;:372,&quot;bytes&quot;:1609043,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!kz_i!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F42c5d08e-7734-480c-9121-3495b49944d6_1024x1024.png 424w, https://substackcdn.com/image/fetch/$s_!kz_i!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F42c5d08e-7734-480c-9121-3495b49944d6_1024x1024.png 848w, https://substackcdn.com/image/fetch/$s_!kz_i!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F42c5d08e-7734-480c-9121-3495b49944d6_1024x1024.png 1272w, https://substackcdn.com/image/fetch/$s_!kz_i!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F42c5d08e-7734-480c-9121-3495b49944d6_1024x1024.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>One potential workflow that comes to mind is a clinical conversation between a clinician and a patient. Clinics and medical care providers have existing documentation on these clinical scenarios. Large Language Models are particularly good at this. With anonymized patient conversation data, can we train a Large Language Model to respond to patient questions? How effective will this be? What benefits can modern clinical practice gain from modern Large Language Models?</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.nexusnotes.co/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Thanks for reading Nexus Notes: Where AI and ML Meet Innovation! Subscribe for free to receive new posts and support my work.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><ul><li><p>In part 1 of this newsletter, we cover the data pre-processing and model fine-tuning using QLoRA and Hugging Face PEFT on AWS Sagemaker spot instances and see the resulting cost savings! </p></li><li><p>In part 2, we will be deploying the fine-tuned llama-2-13b-chat-hf (md-assistant model) to an inference container in AWS Sagemaker and we will build a simple chat user interface to avail the services provided by the new chat model.</p></li></ul><p><strong>Amazon SageMaker Spot Instances, Hugging Face DLC containers, and Weights and Biases API</strong></p><p>In this two-part newsletter, we will dive into the use of Amazon SageMaker spot instances, Hugging Face DLC containers, and the Weights and Biases API to fine-tune the LLaMA2-13B-chat-hf model on a patient-clinician conversation dataset. This workflow has potential applications in clinical practice, where Large Language Models can be trained to respond to patient questions as a tool for the clinician. We will discuss the benefits of using SageMaker spot instances, including cost savings and scalability, as well as the advantages of using Hugging Face DLC containers for model deployment. Additionally, we will explore the role of the Weights and Biases API in monitoring and optimizing machine learning experiments.</p><h3><strong>II. Background</strong> </h3><p><strong>Overview of the chosen model architecture: LLaMA-2-13B-chat-hf</strong></p><p>LLaMA2 is a family of pre-trained language models developed by Meta AI, which have gained popularity among researchers and practitioners in natural language processing (NLP) due to their impressive performance across various benchmarks. Additionally, Among the many available variants, we selected the LLaMA2-13B-chat-hf model for our fine-tuning experiment. But why did we choose this particular model?</p><p>One of the main reasons behind my choice was the fact that the LLaMA2-13B-chat-hf model has been pre-trained on a diverse range of text data, including conversational datasets like Cornell Movie Dialog Corpus and OpenSubtitles. This pre-training objective allows the model to learn patterns and structures commonly found in human dialogues, making it well-suited for generating coherent and contextually appropriate responses in chatbot scenarios. In other words, the "chat" in the model name reflects its chat question and answer pre-training, which aligns with our goal of developing a conversational AI system for healthcare professionals.</p><p>Another important factor was the balance between model size and computational requirements. Compared to smaller models like LLaMA2-7B, the LLaMA2-13B-chat-hf model offers better performance and more capacity to handle complex conversations. However, larger models like LLaMA2-70B come with increased computational demands and longer training times, which could limit our ability to experiment with different hyperparameter configurations within a reasonable time frame. By selecting the mid-sized LLaMA2-13B-chat-hf model, we were able to strike a good balance between these competing factors.</p><p><strong>Major factors in choosing LLama 2 models pertaining to licensing.</strong></p><ul><li><p>LLama2 is an open-source implementation of the language model, LLaMA.</p></li><li><p>The project is released under the Apache License 2.0, which allows for free use, modification, and distribution of the software.</p></li><li><p>The Apache License 2.0 is a permissive open-source license that allows for free use, modification, and distribution of software.</p></li><li><p>The license provides a perpetual, world-wide, non-exclusive, no-charge, royalty-free license to use, reproduce, modify, and distribute the software.</p></li><li><p>LLama2 uses other open-source libraries and frameworks that are released under their own licenses, such as PyTorch (MIT License) and transformers (Apache License 2.0).</p></li><li><p>The open-source licensing of LLama2 allows for maximum flexibility and freedom for users to use, modify, and distribute the software as they see fit.</p></li><li><p>The licensing aligns with the goals of the open-source community, which emphasizes collaboration, transparency, and freely available software.</p></li></ul><p><strong>Fine-tuning the model is like doing the fit and finish of the raw material which is the pre-trained model</strong></p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!SaSq!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f6bc81b-1095-4d9c-a2c9-21efaab651c9_1784x1272.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!SaSq!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f6bc81b-1095-4d9c-a2c9-21efaab651c9_1784x1272.png 424w, https://substackcdn.com/image/fetch/$s_!SaSq!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f6bc81b-1095-4d9c-a2c9-21efaab651c9_1784x1272.png 848w, https://substackcdn.com/image/fetch/$s_!SaSq!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f6bc81b-1095-4d9c-a2c9-21efaab651c9_1784x1272.png 1272w, https://substackcdn.com/image/fetch/$s_!SaSq!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f6bc81b-1095-4d9c-a2c9-21efaab651c9_1784x1272.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!SaSq!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f6bc81b-1095-4d9c-a2c9-21efaab651c9_1784x1272.png" width="1456" height="1038" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/3f6bc81b-1095-4d9c-a2c9-21efaab651c9_1784x1272.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1038,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:250825,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!SaSq!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f6bc81b-1095-4d9c-a2c9-21efaab651c9_1784x1272.png 424w, https://substackcdn.com/image/fetch/$s_!SaSq!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f6bc81b-1095-4d9c-a2c9-21efaab651c9_1784x1272.png 848w, https://substackcdn.com/image/fetch/$s_!SaSq!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f6bc81b-1095-4d9c-a2c9-21efaab651c9_1784x1272.png 1272w, https://substackcdn.com/image/fetch/$s_!SaSq!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f6bc81b-1095-4d9c-a2c9-21efaab651c9_1784x1272.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Fine-tuning pre-trained language models for specific domains is crucial for achieving optimal performance in various applications, especially in scenarios where the model needs to understand domain-specific terminology, concepts, and nuances. In the context of patient-clinician conversations, fine-tuning a pre-trained language model can significantly improve its ability to comprehend medical jargon, diagnose diseases, and provide relevant treatment recommendations. In essence, the pre-trained model is the raw material and fine-tuning the model is the process of carving and shaping the raw material into a beautiful piece of sculpture!</p><p>Here are some reasons why fine-tuning pre-trained language models is important for specific domains like patient-clinician conversations:</p><ul><li><p>Domain-specific vocabulary: Medical conversations often involve specialized terminology that may not be present in general language datasets. By fine-tuning a pre-trained model on a dataset containing medical terms and phrases commonly used in patient-clinician interactions, the model becomes more adept at understanding the unique vocabulary associated with this domain.</p></li><li><p>Concept drift: The underlying distribution of data in different domains can differ significantly, leading to a phenomenon known as concept drift. Fine-tuning a pre-trained model helps adapt it to the new domain, ensuring that it can capture subtle variations in language usage, sentiment, and topics that are specific to patient-clinician conversations.</p></li><li><p>Contextual understanding: Patient-clinician conversations often involve complex dialogues that require an understanding of the context, including the patient's medical history, symptoms, and treatment plans. Fine-tuning a pre-trained model enables it to better grasp the relationships between these elements and provide more accurate responses.</p></li><li><p>Personalization: Every patient's situation is unique, and clinicians must consider individual factors when making decisions about diagnosis and treatment. By fine-tuning a language model on a dataset that reflects the diversity of patients and clinicians, the model can learn to recognize patterns and tailor its responses to suit each person's needs. Think about the correlations that the LLM can point out in a particular patient&#8217;s history.</p></li><li><p>Ethical considerations: Healthcare is a sensitive domain, and there are ethical concerns surrounding the use of AI in patient care. Fine-tuning a pre-trained model on a dataset that adheres to privacy regulations and respects patient autonomy helps ensure that the model's responses align with ethical principles and standards.</p></li><li><p>Improved accuracy: Fine-tuning a pre-trained model typically leads to improved accuracy compared to using a generic, pre-trained model. This is because the model has learned to recognize patterns and relationships specific to the target domain, resulting in fewer errors and more effective communication.</p></li><li><p>Efficient use of resources: Fine-tuning a pre-trained model requires less data and computational resources than training a model from scratch. By leveraging the knowledge captured by the pre-trained model, we can adapt it to the target domain more efficiently and effectively.</p></li><li><p>Faster adaptation to new tasks: Once a pre-trained model has been fine-tuned for a specific domain, it can quickly adapt to new tasks within that domain. This is particularly useful in healthcare, where new treatments, technologies, and regulations emerge regularly, and the model needs to be able to respond accordingly.</p></li><li><p>Enhanced interpretability: Fine-tuning a pre-trained model can help make its internal workings more transparent and interpretable. By analyzing the model's weights and activations, we can gain insights into how it processes domain-specific language and which features it deems most important.</p></li><li><p>Better handling of out-of-distribution inputs: Fine-tuning a pre-trained model improves its ability to handle unexpected or out-of-distribution inputs that may arise in real-world applications. This is critical in healthcare, where unusual cases or unforeseen situations can have significant consequences.</p></li></ul><p>So, fine-tuning pre-trained language models for specific domains like patient-clinician conversations is essential for achieving high accuracy, efficiency, and ethical considerations. By adapting these models to the unique characteristics of the target domain, we can develop more effective and reliable AI language models that support clinicians in providing better patient care.</p><h3><strong>III. System Design</strong></h3><p><strong>Pre-requisites</strong> <em>(Disclaimer: I am not sponsored by any of these companies. I am a paid subscriber to AWS, Weights &amp; Biases and Hugging Face)</em></p><ol><li><p><strong>AWS Account:</strong></p></li></ol><p><a href="https://aws.amazon.com/">Cloud Computing Services - Amazon Web Services (AWS)</a></p><ol start="2"><li><p><strong>HuggingFace Account: Free signup</strong></p></li></ol><p><a href="https://huggingface.co/pricing">Hugging Face &#8211; Pricing</a></p><ol start="3"><li><p><strong>Weights &amp; Biases Account: Free signup</strong></p></li></ol><p><a href="https://docs.wandb.ai/">W&amp;B Docs | Weights &amp; Biases Documentation</a></p><ol start="4"><li><p><strong>Meta LLama-2 approval for access:</strong></p></li></ol><p><a href="https://ai.meta.com/resources/models-and-libraries/llama-downloads/">Llama access request form - Meta AI</a></p><p><strong>Amazon SageMaker and its benefits for machine learning and AI development</strong></p><p>With AWS SageMaker, the process of fine-tuning a pre-trained language model (LLM) becomes significantly simpler and more efficient for machine learning engineers. By leveraging the cloud infrastructure provided by SageMaker, engineers can focus solely on the fine-tuning task without worrying about the underlying infrastructure.</p><p>Here are some ways in which SageMaker streamlines the LLM fine-tuning process:</p><ul><li><p>No Infrastructure Setup: SageMaker eliminates the need for engineers to perform low level set up and manage infrastructure, such as spinning up containers, managing data storage, and configuring network security. This saves time and effort, allowing engineers to focus on the core task of fine-tuning the LLM.</p></li><li><p>Easy Access to Data: SageMaker provides integrated data management capabilities, making it easy for engineers to access and manipulate data for fine-tuning. This includes data loading, preprocessing, and feature engineering, all of which can be performed within the SageMaker framework.</p></li><li><p>Automated Hyperparameter Tuning: SageMaker automates the hyperparameter tuning process, allowing engineers to focus on other aspects of the fine-tuning task. This feature saves time and reduces the risk of overfitting or underfitting the model.</p></li><li><p>Support for Various Frameworks: SageMaker supports a variety of machine learning frameworks, including TensorFlow, PyTorch, and Scikit-learn. This means that engineers can use their preferred framework for LLM fine-tuning, further simplifying the process.</p></li><li><p>Flexible Deployment Options: Once the fine-tuning process is complete, SageMaker provides flexible deployment options, including hosting the model in a SageMaker endpoint, deploying it to AWS Lambda, or exporting it to a containerized application. This enables engineers to easily integrate the fine-tuned LLM into their desired environment.</p></li><li><p>Time Savings: By leveraging SageMaker's automated infrastructure provisioning, data management, and hyperparameter tuning capabilities, engineers can save a significant amount of time compared to setting up and managing the infrastructure themselves. This allows them to focus on the fine-tuning task at hand and deliver high-quality LLM models more rapidly.</p></li><li><p>Improved Productivity: With SageMaker, engineers can work more efficiently and avoid tedious, repetitive tasks. They can focus on developing and refining their LLM models, leading to improved productivity and better model performance.</p></li><li><p>Better Collaboration: SageMaker facilitates collaboration among team members, enabling them to work together more effectively. Features like version control, reproducibility, and shared notebooks simplify the collaborative fine-tuning process, ensuring that everyone is on the same page.</p></li><li><p>Cost Optimization: SageMaker provides optimized computing resources that adjust to meet changing demand. This means that engineers can minimize costs associated with LLM fine-tuning while still achieving optimal results.</p></li><li><p>Security and Compliance: SageMaker adheres to strict security and compliance standards, giving engineers peace of mind regarding data privacy and protection. This allows them to focus on the fine-tuning task without worrying about potential security breaches or non-compliance issues.</p></li></ul><p>By using AWS SageMaker for LLM fine-tuning, machine learning engineers can offload the burden of managing infrastructure and focus exclusively on optimizing their models. This leads to increased productivity, simplified collaboration, reduced costs, and improved model performance, ultimately resulting in better outcomes for their organization.</p><p><strong>Introduction to Hugging Face DLC containers and their integration with SageMaker</strong></p><p>HuggingFace DLC (Deep Learning Container) is a containerization technology specifically designed for deep learning models. It provides a simple and efficient way to package and distribute deep learning models and their dependencies, allowing developers to focus on building models instead of managing infrastructure.</p><p>DLCs are built on top of Docker and provide a standardized way to package models, datasets, and other dependencies required for training and inference. They support a wide range of deep learning frameworks, including TensorFlow, PyTorch, and Keras.</p><p>SageMaker, on the other hand, is a fully managed service provided by Amazon Web Services (AWS) that makes it easy to build, train, and deploy machine learning models at scale. It provides a variety of features, including automatic model tuning, hyperparameter optimization, and deployment of models to production environments.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!c6JS!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2bd7bae-c8fb-4de0-8ec0-24c66ae226b5_798x620.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!c6JS!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2bd7bae-c8fb-4de0-8ec0-24c66ae226b5_798x620.png 424w, https://substackcdn.com/image/fetch/$s_!c6JS!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2bd7bae-c8fb-4de0-8ec0-24c66ae226b5_798x620.png 848w, https://substackcdn.com/image/fetch/$s_!c6JS!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2bd7bae-c8fb-4de0-8ec0-24c66ae226b5_798x620.png 1272w, https://substackcdn.com/image/fetch/$s_!c6JS!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2bd7bae-c8fb-4de0-8ec0-24c66ae226b5_798x620.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!c6JS!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2bd7bae-c8fb-4de0-8ec0-24c66ae226b5_798x620.png" width="798" height="620" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/f2bd7bae-c8fb-4de0-8ec0-24c66ae226b5_798x620.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:620,&quot;width&quot;:798,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!c6JS!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2bd7bae-c8fb-4de0-8ec0-24c66ae226b5_798x620.png 424w, https://substackcdn.com/image/fetch/$s_!c6JS!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2bd7bae-c8fb-4de0-8ec0-24c66ae226b5_798x620.png 848w, https://substackcdn.com/image/fetch/$s_!c6JS!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2bd7bae-c8fb-4de0-8ec0-24c66ae226b5_798x620.png 1272w, https://substackcdn.com/image/fetch/$s_!c6JS!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff2bd7bae-c8fb-4de0-8ec0-24c66ae226b5_798x620.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong>Advantages of integrating Hugging Face DLCs with SageMaker</strong></p><ul><li><p><strong>Simplified model packaging</strong>: Hugging Face DLCs provide a standardized way to package models and their dependencies, making it easy to manage and distribute models across different environments.</p></li><li><p><strong>Faster model deployment</strong>: By using DLCs, you can quickly deploy models to SageMaker, reducing the time and effort required to set up and configure environments.</p></li><li><p><strong>Improved reproducibility</strong>: DLCs ensure that models are trained and deployed consistently across different environments, which improves reproducibility and reduces the risk of errors caused by inconsistent environments.</p></li><li><p><strong>Easier collaboration</strong>: DLCs make it easier for data scientists to collaborate on projects by providing a standardized way to exchange models and reproduce experiments.</p></li><li><p><strong>Better resource utilization</strong>: SageMaker's integration with DLCs allows you to take advantage of spot instances and other cost-effective compute resources, reducing the cost of training and deploying models.</p></li></ul><p><strong>Fine-tuning Set-up:</strong></p><p>When leveraging the MedDialog dataset to fine-tune a pre-trained LLaMA-2-13B-chat-hf model, there are several key considerations to keep in mind to ensure optimal performance and efficiency.</p><p>First and foremost, it is crucial to select an appropriate batch size for training. In this case, a batch size of 2 per device is recommended to strike a balance between resource utilization and training speed. By doing so, the model can be trained efficiently without sacrificing too much time or computational resources.</p><p>Next, the number of epochs must be carefully chosen. In this scenario, running the experiment for 3 epochs should suffice for the model to converge properly and achieve satisfactory results. Selecting the right number of epochs is critical, as it impacts both the accuracy of the model and the time required for training.</p><p>AdamW optimization is also vital for achieving optimal model performance. AdamW is a well-known algorithm that adapts the learning rate for each parameter individually, based on the magnitude of the gradient. This helps to prevent overshooting or undershooting the optimal learning rate, resulting in faster convergence and better model accuracy.</p><p>Another important aspect to consider is the choice of instance type. For this particular use case, an ml.g5.4xlarge SageMaker spot instance is recommended. Not only does this instance type offer powerful GPU acceleration, but it also comes with a discounted pricing model thanks to Amazon Elastic Compute Cloud (EC2) Spot Instances. By leveraging EC2 Spot Instances, SageMaker can automatically handle bid management and instance selection, streamlining the process and minimizing costs.</p><p>Monitoring the fine-tuning progress is equally important. From the smart folks at Weights &amp; Biases ( https://wand.ai), the wandb API provides comprehensive monitoring capabilities for SageMaker/HuggingFace experiments, including essential metrics like loss, accuracy, and validation accuracy. Real-time monitoring enables engineers to identify potential issues early on and make informed decisions throughout the experiment. Additionally, it lets you version and iterate on datasets, evaluate model performance, reproduce models, visualize results and spot regressions, and share findings with colleagues.</p><p>In the fine-tuning process (run_clm.py), I simply imported wandb and using my api key, logged-in to the <a href="http://wandb.ai">wandb.ai</a> platform within my training script. By adding the following to the python script, this was made possible. Pretty simple and you can view the real-time progress as shown below. The different colors represent different traces post spot instance interruption. Yes it remembers the last trace and depicts the newer trace in a different color! </p><pre><code># making
import wandb
.
.
.
.
# login to wandb instrumentation platform
    if args.wandb_api_key:
        print(f'logging in to wandb.....')
        wandb.login(anonymous='never', key=args.wandb_api_key)
.
.
.
# add report_to='wandb'parameter
# Define training args
    output_dir = args.output_dir
    training_args = TrainingArguments(
        output_dir=output_dir,
        resume_from_checkpoint=True,
        overwrite_output_dir=True,
        per_device_train_batch_size=args.per_device_train_batch_size,
        bf16=args.bf16,  # Use BF16 if available
        learning_rate=args.lr,
        num_train_epochs=args.epochs,
        gradient_checkpointing=args.gradient_checkpointing,
        # logging strategies
        logging_dir=f"{output_dir}/logs",
        logging_strategy="steps",
        logging_steps=10,
        #warmup_steps=100,
        save_steps=50,
        save_strategy="steps",
        report_to="wandb",
        run_name=f'md-asistant-{time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())}'
    )</code></pre><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!rh9r!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6eb9c521-161c-4c9c-8816-d83d773c16e9_888x640.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!rh9r!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6eb9c521-161c-4c9c-8816-d83d773c16e9_888x640.png 424w, https://substackcdn.com/image/fetch/$s_!rh9r!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6eb9c521-161c-4c9c-8816-d83d773c16e9_888x640.png 848w, https://substackcdn.com/image/fetch/$s_!rh9r!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6eb9c521-161c-4c9c-8816-d83d773c16e9_888x640.png 1272w, https://substackcdn.com/image/fetch/$s_!rh9r!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6eb9c521-161c-4c9c-8816-d83d773c16e9_888x640.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!rh9r!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6eb9c521-161c-4c9c-8816-d83d773c16e9_888x640.png" width="888" height="640" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/6eb9c521-161c-4c9c-8816-d83d773c16e9_888x640.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:640,&quot;width&quot;:888,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:104739,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!rh9r!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6eb9c521-161c-4c9c-8816-d83d773c16e9_888x640.png 424w, https://substackcdn.com/image/fetch/$s_!rh9r!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6eb9c521-161c-4c9c-8816-d83d773c16e9_888x640.png 848w, https://substackcdn.com/image/fetch/$s_!rh9r!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6eb9c521-161c-4c9c-8816-d83d773c16e9_888x640.png 1272w, https://substackcdn.com/image/fetch/$s_!rh9r!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6eb9c521-161c-4c9c-8816-d83d773c16e9_888x640.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p></p><p>Finally, it's worth noting that using spot instances has its advantages over on-demand instances. Besides being significantly cheaper, spot instances grant access to a larger pool of available instances, making it easier to launch experiments promptly. Additionally, spot instances allow for greater flexibility in scaling resources up or down according to changing demands. Of course, there are some risks associated with spot instances, such as potential instance termination due to fluctuations in EC2 spot instance supply and demand. Nevertheless, SageMaker's integration with EC2 Spot Instances mitigates these risks while maximizing the benefits.</p><p>By taking these factors into account when fine-tuning the LLaMA-2-13B-chat-hf model on the MedDialog dataset, experienced ML engineers can create a robust and cost-efficient chatbot solution that delivers high-quality user experiences while optimizing resource utilization.</p><p><strong>Dataset: description of the patient-clinician conversation dataset used for fine-tuning</strong></p><p>First introduced in a 2004 paper by Xuehai He et al., MedDialog consists of two large-scale medical dialogue datasets that capture conversations between patients and doctors across various medical domains.</p><p>What makes MedDialog particularly interesting for business applications is its scope and diversity. The dataset contains over 250,000 utterances from both patients and doctors, spanning 51 different medical categories and 96 specialties. This wealth of information provides a unique opportunity for machine learning models to learn patterns and relationships within medical dialogues, which can ultimately enhance decision-making processes in healthcare settings.</p><p>Developing conversational AI systems that can facilitate patient-doctor interactions using clinic or provider specific dialog datasets is a valid use case. By analyzing the language used in medical consultations, these systems can better understand patient concerns and provide personalized recommendations for treatment options. This not only improves patient satisfaction but also streamlines the consultation process for doctors, allowing them to focus on more complex cases.</p><p><strong>MedDialog Dataset Preprocessing</strong></p><p>The code provided (modified from <a href="https://github.com/philschmid/sagemaker-huggingface-llama-2-samples">https://github.com/philschmid/sagemaker-huggingface-llama-2-samples</a>) is responsible for formatting medical dialog data into a suitable format for training a language model. Here's an overview of the steps involved in this process:</p><ol><li><p>Loading the Data: The first step is to load the medical dialog data from a dataset file. This is done using the&nbsp;<code>load_dataset</code>&nbsp;function, which returns a pandas dataframe containing the data.</p></li><li><p>Removing Unwanted Columns: The next step is to remove any unwanted columns from the dataframe. In this case, we only need the "text" column, so we remove all other columns using the&nbsp;<code>remove_columns</code>&nbsp;parameter of the&nbsp;<code>df.map()</code>&nbsp;method.</p></li><li><p>Formatting Samples: We then apply a custom function called&nbsp;<code>template_dataset</code>&nbsp;to each row of the dataframe. This function takes a sample and formats it according to the required format for our language model. Specifically, it adds a system prompt and user prompt to each sample, separated by a newline character.</p></li><li><p>Chunking and Tokenizing: After formatting the samples, we use another custom function called&nbsp;<code>chunk</code>&nbsp;to split the text into smaller chunks. Each chunk has a maximum length of 2048 tokens. Any remaining tokens are saved as a global variable called&nbsp;<code>remainder</code>&nbsp;to be used in the next batch. Within each chunk, we also tokenize the text using the&nbsp;<code>tokenizer</code>&nbsp;function.</p></li><li><p>Preparing Labels: Once we have our chunks of text, we create labels for them. The labels are simply copies of the input IDs.</p></li><li><p>Saving the Data: Finally, we save the processed data to disk using the&nbsp;<code>save_to_disk</code>&nbsp;method. The output path is specified using the&nbsp;<code>training_input_path</code>&nbsp;variable which is an s3 bucket.</p></li></ol><p>The code loads medical dialog data, removes unnecessary columns, formats each sample with system and user prompts, chunks and tokenizes the text, prepares labels, and saves the processed data to disk. These steps are necessary to prepare the data for training a language model capable of generating appropriate responses to medical queries.</p><pre><code><code>######################################################
# Pre-processing of medical_dialog dataset from hf hub.
# Stores formatted, tokenized, chunked 
# training data to s3 bucket.
# Derived from @philschmid hugginface-llama-2-samples
# on a different hf dataset
######################################################

import sagemaker
import boto3
from random import randint
from itertools import chain
from functools import partial
from datasets import load_dataset
from random import randrange
import json
import pandas as pd
from transformers import AutoTokenizer

#sagemaker_session_bucket='mlpipes-sm'                                # us-west-2
sagemaker_session_bucket='mlpipes-03-29-2023-asabay'                  # us-east-1
role_name = 'Sagemaker-mle'
dataset_name = 'medical_dialog'
dataset_lang = 'en'
model_id = 'meta-llama/Llama-2-13b-chat-hf'
# empty list to save remainder from batches to use in next batch
remainder = {"input_ids": [], "attention_mask": [], "token_type_ids": []}
# sess = sagemaker.Session()

# fetch tokenizer pad_token
def fetch_tokenizer(model_id):
    tokenizer = AutoTokenizer.from_pretrained(model_id)
    tokenizer.pad_token = tokenizer.eos_token
    return tokenizer

tokenizer = fetch_tokenizer(model_id)

# sagemaker session bucket -&gt; used for uploading data, models and logs
# sagemaker will automatically create this bucket if it not exists
def init_sagemaker(role, session_bucket):
    if session_bucket is None and sess is not None:
        # set to default bucket if a bucket name is not given
        session_bucket = sess.default_bucket()
    try:
        role = sagemaker.get_execution_role()
    except ValueError:
        iam = boto3.client('iam')
        role = iam.get_role(RoleName=role_name)['Role']['Arn']

    sess = sagemaker.Session(default_bucket=sagemaker_session_bucket)
    return (sess, role)

# load dataset and remove un-used fields
def load_and_extract(dataset_name, dataset_lang):
    dataset = load_dataset(dataset_name, dataset_lang)
    dataset = dataset['train'].remove_columns(['file_name', 'dialogue_id', 'dialogue_url'])
    return dataset

# function to format samples to llama-2-chat-hf format
# which is:
# &lt;s&gt;[INST] &lt;&lt;SYS&gt;&gt;
# System prompt
# &lt;&lt;/SYS&gt;&gt;
# User prompt [/INST] Model answer &lt;/s&gt;
def format_dialogue(sample):
    instruction = f"[INST]{sample['dialogue_turns']['utterance'][0]}[/INST]"
    response = f"{sample['dialogue_turns']['utterance'][1]}"
    # join all the parts together
    prompt = "\\n".join([i for i in [instruction, response] if i is not None])
    return '&lt;s&gt;' + prompt + '&lt;/s&gt;'

# template dataset to add prompt to each sample
def template_dataset(sample):
    sample["text"] = f"{format_dialogue(sample)}{tokenizer.eos_token}"
    return sample

# chunk and tokenize
def chunk(sample, chunk_length=2048):
    # define global remainder variable to save remainder from batches to use in next batch
    global remainder
    # Concatenate all texts and add remainder from previous batch
    concatenated_examples = {k: list(chain(*sample[k])) for k in sample.keys()}
    concatenated_examples = {k: remainder[k] + concatenated_examples[k] for k in concatenated_examples.keys()}
    # get total number of tokens for batch
    batch_total_length = len(concatenated_examples[list(sample.keys())[0]])

    # get max number of chunks for batch
    if batch_total_length &gt;= chunk_length:
        batch_chunk_length = (batch_total_length // chunk_length) * chunk_length

    # Split by chunks of max_len.
    result = {
        k: [t[i : i + chunk_length] for i in range(0, batch_chunk_length, chunk_length)]
        for k, t in concatenated_examples.items()
    }
    # add remainder to global variable for next batch
    remainder = {k: concatenated_examples[k][batch_chunk_length:] for k in concatenated_examples.keys()}
    # prepare labels
    result["labels"] = result["input_ids"].copy()
    return result

def process_data():
    sm_session, _ = init_sagemaker(role_name, sagemaker_session_bucket)
    ds = load_and_extract(dataset_name, dataset_lang)
    ds = ds.map(template_dataset)
    print(ds[randint(0, len(ds))]["text"])  # print random sample
    lm_dataset = ds.map(
        lambda sample: tokenizer(sample["text"]), batched=True, remove_columns=list(ds.features)
            ).map(partial(chunk, chunk_length=2048),
            batched=True,
        )
    print(f"Total number of samples: {len(lm_dataset)}")
    # save train_dataset to s3
    training_input_path = f's3://{sm_session.default_bucket()}/processed/llama/md_dialouge/train'
    lm_dataset.save_to_disk(training_input_path)
    print("uploaded data to:")
    print(f"training dataset to: {training_input_path}")

if __name__ == '__main__':
    process_data()
</code></code></pre><p><strong>Fine-Tuning with QLora and PEFT for Cost Savings</strong></p><p>As a way to reduce training costs on AWS Sagemaker, the QLoRA method was used. This would allow the use of smaller GPU instances which in this case is a single GPU ml.g5.4xlarge sagemaker spot training instance (16 cvpu, 64G mem, 1 gpu, 24G total gpu mem, A10G). The on-demand cost in aws us-east-1 region is $2.03 per hour, discounted by up to 90% if using spot instances. In this project, the discount is around 65% using this setup.</p><p>QLoRA (Quantized LORA) is a novel method for efficient finetuning of quantized large language models (LLMs) proposed by Tim Dettmers, Artidoro Pagnoni, Ari Holtzman, and Luke Zettlemoyer in their research paper titled "QLORA: Efficient Finetuning of Quantized LLMs." The authors present a systematic approach to fine-tune quantized LLMs for downstream natural language processing tasks while maintaining competitive performance and reducing computational requirements.</p><p>The authors address the challenge of finetuning large language models that have been quantized, which results in loss of precision and degraded performance. They propose QLoRA, which leverages the strengths of two existing techniques: LORA (Latent Optimization Regularization Algorithm) and quantization. QLoRA introduces a regularization term that encourages the model to learn discrete representations that are close to the original continuous representations. This term is combined with the standard cross-entropy loss, resulting in a hybrid objective function that enables efficient finetuning of quantized LLMs.</p><p>The authors evaluate QLoRA on several benchmark datasets and compare its performance to full-precision and quantized baselines. Their results show that QLoRA achieves competitive performance with the full-precision baseline while providing significant computational savings. Specifically, they report that QLoRA achieves 97% of the full-precision performance on the GLUE benchmark while being 3.8x more computationally efficient.</p><p>The authors also investigate the effectiveness of QLoRA across different levels of quantization and observe that it consistently outperforms the quantized baseline across all levels. Furthermore, they demonstrate that QLoRA can be used for few-shot learning, adapting the model to new tasks with only a handful of labeled examples.</p><p>In the training script, the llama2 model is instantiated with quantization_config parameter passed in as a BitsAndBytesConfig object that specifies:</p><pre><code><code># from &lt;https://github.com/philschmid/sagemaker-huggingface-llama-2-samples&gt;, run_clm.py
bnb_config = BitsAndBytesConfig(
        load_in_4bit=True,
        bnb_4bit_use_double_quant=True,
        bnb_4bit_quant_type="nf4",
        bnb_4bit_compute_dtype=torch.bfloat16,
    )
model = AutoModelForCausalLM.from_pretrained(
        args.model_id,
        use_cache=False
        if args.gradient_checkpointing
        else True,  # this is needed for gradient checkpointing
        device_map="auto",
        quantization_config=bnb_config,
    )
</code></code></pre><p>Further, PEFT is implemented to strike a middle ground between full-fine tuning which is resource intensive, and feature engineering. Parameter-Efficient Fine-Tuning (PEFT) is a novel approach to adapting pre-trained language models (PLMs) to various downstream tasks without fine-tuning all model parameters. PEFT selectively updates a small number of extra parameters, striking a balance between performance and efficiency. Recent advancements in PEFT techniques have achieved performance comparable to full fine-tuning while significantly reducing computational and storage costs. PEFT offers a promising solution for scaling up NLP models while minimizing resource requirements, making it a valuable tool in shaping the future of natural language processing, particularly in resource-constrained scenarios.</p><p>The PEFT setup is done below:</p><pre><code><code># from &lt;https://github.com/philschmid/sagemaker-huggingface-llama-2-samples&gt;, run_clm.py
def create_peft_model(model, gradient_checkpointing=True, bf16=True):
    from peft import (
        get_peft_model,
        LoraConfig,
        TaskType,
        prepare_model_for_kbit_training,
    )
    from peft.tuners.lora import LoraLayer

    # prepare int-4 model for training
    model = prepare_model_for_kbit_training(
        model, use_gradient_checkpointing=gradient_checkpointing
    )
    if gradient_checkpointing:
        model.gradient_checkpointing_enable()

    # get lora target modules
    modules = find_all_linear_names(model)
    print(f"Found {len(modules)} modules to quantize: {modules}")

    peft_config = LoraConfig(
        r=64,
        lora_alpha=16,
        target_modules=modules,
        lora_dropout=0.1,
        bias="none",
        task_type=TaskType.CAUSAL_LM,
    )

    model = get_peft_model(model, peft_config)
</code></code></pre><p>Finally, the entire training_function prepares a llama-2-13b-chat-hf model with QLora and PEFT set-up parameters for fine-tuning as shown before trainer.train() is called. By the way, you will also see how this training script checks if it is recovering from a spot instance or a user stop interruption by checking for the last_checkpoint. In the TrainingArguments object instantiation prior to the Trainer object instantiation, you can see the parameters required for spot instance training. Checkpointing is enabled by setting save_strategy as &#8220;steps&#8221; and save_steps=10 sets a checkpoint every 10 steps to the s:3// checkpoint location. This is how training recovery is made possible. See code below:</p><pre><code><code># modified from &lt;https://github.com/philschmid/sagemaker-huggingface-llama-2-samples&gt;
def training_function(args):
    # set seed
    set_seed(args.seed)

    dataset = load_from_disk(args.dataset_path)

    # load model from the hub with a bnb config
    bnb_config = BitsAndBytesConfig(
        load_in_4bit=True,
        bnb_4bit_use_double_quant=True,
        bnb_4bit_quant_type="nf4",
        bnb_4bit_compute_dtype=torch.bfloat16,
    )

    model = AutoModelForCausalLM.from_pretrained(
        args.model_id,
        use_cache=False
        if args.gradient_checkpointing
        else True,  # this is needed for gradient checkpointing
        device_map="auto",
        quantization_config=bnb_config,
    )

    # create peft config
    model = create_peft_model(
        model, gradient_checkpointing=args.gradient_checkpointing, bf16=args.bf16
    )

    # Define training args
    output_dir = args.output_dir
    training_args = TrainingArguments(
        output_dir=output_dir,
        resume_from_checkpoint=True,
        overwrite_output_dir=True,
        per_device_train_batch_size=args.per_device_train_batch_size,
        bf16=args.bf16,  # Use BF16 if available
        learning_rate=args.lr,
        num_train_epochs=args.epochs,
        gradient_checkpointing=args.gradient_checkpointing,
        # logging strategies
        logging_dir=f"{output_dir}/logs",
        logging_strategy="steps",
        logging_steps=10,
        #warmup_steps=100,
        save_steps=50,
        save_strategy="steps",
        report_to="wandb",
        run_name=f'md-asistant-{time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())}'
    )

    # Create Trainer instance
    trainer = Trainer(
        model=model,
        args=training_args,
        train_dataset=dataset,
        data_collator=default_data_collator,
    )

    # check if checkpoint exists. if so continue training from where we left off, 
    # this is only for spot instances
    if get_last_checkpoint(args.output_dir) is not None:
        logger.info("***** continue training *****")
        last_checkpoint = get_last_checkpoint(args.output_dir)
        print(f'**********got last checkpoint = {last_checkpoint}**********************')
        trainer.train(resume_from_checkpoint=last_checkpoint)
    else:
        print('!!!!!!!!!!!!!!INITIAL TRAINING RUN!!!!!!!!!!!!!!!!!!!!')
        trainer.train() # no checkpoints found

    sagemaker_save_dir="/opt/ml/model/" # local container directory
    if args.merge_weights:
        # merge adapter weights with base model and save
        # save int 4 model
        trainer.model.save_pretrained(output_dir, safe_serialization=False)
        # clear memory
        del model
        del trainer
        torch.cuda.empty_cache()

        # load PEFT model in fp16
        model = AutoPeftModelForCausalLM.from_pretrained(
            output_dir,
            low_cpu_mem_usage=True,
            torch_dtype=torch.float16,
        )  
        # Merge LoRA and base model and save
        model = model.merge_and_unload()        
        model.save_pretrained(
            sagemaker_save_dir, safe_serialization=True, max_shard_size="2GB"
        )
    else:
        trainer.model.save_pretrained(
            sagemaker_save_dir, safe_serialization=True
        )

    # save tokenizer for easy inference
    tokenizer = AutoTokenizer.from_pretrained(args.model_id)
    tokenizer.save_pretrained(sagemaker_save_dir)
</code></code></pre><p><strong>IV. Results</strong></p><p><strong>Fine-tuning traces on Weights &amp; Biases platform. </strong></p><p>http://wandb.ai</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!pj71!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e02371b-409d-4a9d-aad7-d817851cf59e_880x552.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!pj71!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e02371b-409d-4a9d-aad7-d817851cf59e_880x552.png 424w, https://substackcdn.com/image/fetch/$s_!pj71!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e02371b-409d-4a9d-aad7-d817851cf59e_880x552.png 848w, https://substackcdn.com/image/fetch/$s_!pj71!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e02371b-409d-4a9d-aad7-d817851cf59e_880x552.png 1272w, https://substackcdn.com/image/fetch/$s_!pj71!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e02371b-409d-4a9d-aad7-d817851cf59e_880x552.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!pj71!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e02371b-409d-4a9d-aad7-d817851cf59e_880x552.png" width="880" height="552" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/3e02371b-409d-4a9d-aad7-d817851cf59e_880x552.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:552,&quot;width&quot;:880,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:50306,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!pj71!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e02371b-409d-4a9d-aad7-d817851cf59e_880x552.png 424w, https://substackcdn.com/image/fetch/$s_!pj71!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e02371b-409d-4a9d-aad7-d817851cf59e_880x552.png 848w, https://substackcdn.com/image/fetch/$s_!pj71!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e02371b-409d-4a9d-aad7-d817851cf59e_880x552.png 1272w, https://substackcdn.com/image/fetch/$s_!pj71!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e02371b-409d-4a9d-aad7-d817851cf59e_880x552.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>M<strong>odel cost performance: How much did I save?</strong></p><p><strong>Table 1: On-demand versus Spot Instance cost on ml.g5.4xlarge</strong></p><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!Fgwy!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8204c15-efa0-4ace-ba34-bf6b5c66252a_822x92.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!Fgwy!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8204c15-efa0-4ace-ba34-bf6b5c66252a_822x92.png 424w, https://substackcdn.com/image/fetch/$s_!Fgwy!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8204c15-efa0-4ace-ba34-bf6b5c66252a_822x92.png 848w, https://substackcdn.com/image/fetch/$s_!Fgwy!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8204c15-efa0-4ace-ba34-bf6b5c66252a_822x92.png 1272w, https://substackcdn.com/image/fetch/$s_!Fgwy!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8204c15-efa0-4ace-ba34-bf6b5c66252a_822x92.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!Fgwy!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8204c15-efa0-4ace-ba34-bf6b5c66252a_822x92.png" width="822" height="92" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/c8204c15-efa0-4ace-ba34-bf6b5c66252a_822x92.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:92,&quot;width&quot;:822,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:27925,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!Fgwy!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8204c15-efa0-4ace-ba34-bf6b5c66252a_822x92.png 424w, https://substackcdn.com/image/fetch/$s_!Fgwy!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8204c15-efa0-4ace-ba34-bf6b5c66252a_822x92.png 848w, https://substackcdn.com/image/fetch/$s_!Fgwy!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8204c15-efa0-4ace-ba34-bf6b5c66252a_822x92.png 1272w, https://substackcdn.com/image/fetch/$s_!Fgwy!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8204c15-efa0-4ace-ba34-bf6b5c66252a_822x92.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><p>As can be seen in Table 1, using a small single GPU instance will take longer (147hrs in 3 epochs) to train with a spot instance discounted cost of $104.44.  The total cost of using an on-demand instance would be $298.41 versus $104.44 for the entire fine-tuning cycle. This is a modest dataset size that without using QLoRA, PEFT, and Spot Instances could have fine-tuning costs exceeding a thousand dollars. Depending on the resources and time available, we have to balance cost time, and accuracy to deliver the best product possible. In part 2 I plan to make trial runs with larger aws sagemaker instances to compare cost and time and perhaps identify a sweet spot for cost efficiency. In the meantime, we can see very significant fine-tuning cost savings by using QLoRA, PEFT, and AWS Spot Instances.</p><p>I encourage you to explore and try different LLM fine-tuning setups using this newsletter article and find what works for you and share your experiences as we learn from each other.</p><p>In part 2 of this newsletter article, we will analyze and test the tuned model, deploy it to an inference instance, and build a chat UI for you to try&#128512;</p><p><strong>VI. References</strong></p><p><a href="https://github.com/alsabay/ai_md_assistant/tree/main">All code in this project can be found here</a>.</p><p><a href="https://aws.amazon.com/sagemaker/">AWS Sagemaker Platform</a></p><p><a href="https://github.com/huggingface/peft">Hugging Face PEFT</a></p><p><a href="https://arxiv.org/abs/2305.14314">QLoRA: Efficient Finetuning of Quantized LLMs</a></p><p><a href="https://arxiv.org/abs/2004.03329">MedDialog: Two Large-scale Medical Dialogue Datasets</a></p><p><a href="https://www.philschmid.de/sagemaker-spot-instance">Philschmid Blog on Spot Instances and Hugging Face Transformers</a></p><p><a href="https://github.com/philschmid/sagemaker-huggingface-llama-2-samples">Philschmid Github on Sagemaker-HuggingFace llama-2 fine-tuning and deployment</a></p><p><a href="https://docs.wandb.ai/guides">Weights &amp; Biases platform documentation</a></p><p></p><p></p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.nexusnotes.co/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Thanks for reading Nexus Notes: Where AI and ML Meet Innovation! Subscribe for free to receive new posts and support my work.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item><item><title><![CDATA[Unraveling the Hidden Magic of Vector Databases 🔍✨]]></title><description><![CDATA[A simple example of how Vector Databases work behind the scenes]]></description><link>https://www.nexusnotes.co/p/unraveling-the-hidden-magic-of-vector</link><guid isPermaLink="false">https://www.nexusnotes.co/p/unraveling-the-hidden-magic-of-vector</guid><dc:creator><![CDATA[Alfeo Sabay]]></dc:creator><pubDate>Sat, 22 Jul 2023 11:43:55 GMT</pubDate><enclosure url="https://substack-post-media.s3.amazonaws.com/public/images/4535f86e-b55e-4a89-91ea-5bb25cb987f2_1024x1024.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3>Introduction:</h3><p>Today, I'm thrilled to share the transformative potential of vector databases in the realm of data-driven decision making. Over the years, I've witnessed how businesses have harnessed the full potential of analytics, and vector databases have emerged as a game-changer, revolutionizing AI and ML architectures. Today, I'm excited to take you on a journey to explore how this cutting-edge technology can be applied in a real-world scenario: a Movie Recommender system, similar to what powers personalized recommendations on platforms like Netflix or Prime Video.</p><h4>How Vector Databases Drive Personalized Movie Recommendations:</h4><p>In our Python code example, I'll showcase the seamless integration of Faiss, a powerful vector database from Meta, to create a sophisticated Movie Recommender. By leveraging Faiss alongside Word2Vec embeddings, I'll demonstrate how this technology powers accurate and efficient similarity searches based on movie preferences. This innovative approach enables streaming platforms to offer users a highly personalized and engaging movie-watching experience.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.nexusnotes.co/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Thanks for reading Nexus Notes: Where AI and ML Meet Innovation! Subscribe for free to receive new posts and support my work.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h4>Unlocking the Secrets of Faiss in Movie Recommendations:</h4><p>Through the code example, I'll reveal how Faiss efficiently organizes and indexes movie vectors, ensuring rapid retrieval of the most relevant movie recommendations for each user. By combining the power of vector databases with state-of-the-art AI algorithms, this system elevates the movie discovery process, enticing users to explore new genres and undiscovered gems.</p><p>Join me as we dive into the Python code, where you'll witness firsthand the incredible capabilities of vector databases in action. Let's embark on this exciting journey together to unravel the power of vector databases and their potential to revolutionize your data-driven endeavors, just like the Movie Recommender we're about to unveil. </p><h3>How the Recommendation System Works</h3><p>Let me walk you through the technology behind our movie recommendation system. At the core of this system are Word2Vec ( <em>here I&#8217;m using the <a href="https://github.com/RaRe-Technologies/gensim/tree/develop">gensim</a> python library, it&#8217;s super fast</em> ) embeddings, a powerful technique that represents movie titles as dense vectors in a high-dimensional space. This enables the system to capture semantic relationships between movies, facilitating efficient comparison and similarity calculations.</p><p>Word2Vec uses a neural network to learn word embeddings from vast amounts of textual data, such as movie titles in our case. Each word is mapped to a dense vector, where similar words are placed closer together in the vector space. This linguistic context allows us to establish connections between movie titles, even those that may not share identical words but are conceptually related.</p><p>To show how these similarity searches work, let&#8217;s use Faiss, a remarkable vector database from Meta ( <em>though there are many to choose from such as Pinecone, Milvus, Weaviate etc </em>). Faiss optimizes the organization and indexing of movie vectors, enabling us to find similar movies rapidly based on user input. By employing Faiss alongside Word2Vec embeddings, we achieve lightning-fast response times, providing users with an exceptional movie discovery experience.</p><p>Now that we understand the technology behind our recommendation system, let's dive into it!</p><h3>Building the Recommendation System</h3><p>I ran this example python code on AWS Sagemaker with a <strong>ml.g4dn.2xlarge </strong>single GPU notebook instance with 32 GiB of memory, but you should be able to run this on a local machine preferably with a GPU. I opted to use the Kaggle <strong><a href="https://www.kaggle.com/datasets/singole/tmdb-1000-movie-dataset-2023-new-updated?select=Movies_dataset.csv">TMDB 3000+ Movie Dataset-2023</a> . </strong></p><p><strong>Loading Word2Vec Model and Dataset</strong>: We start by importing necessary libraries, capturing messages (output), and loading a pre-trained Word2Vec model from the <em><a href="https://github.com/RaRe-Technologies/gensim/tree/develop">gensim</a></em> library. </p><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!Wy02!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F66a35646-764b-4448-a88d-3fab7ced2c8a_1754x386.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!Wy02!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F66a35646-764b-4448-a88d-3fab7ced2c8a_1754x386.png 424w, https://substackcdn.com/image/fetch/$s_!Wy02!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F66a35646-764b-4448-a88d-3fab7ced2c8a_1754x386.png 848w, https://substackcdn.com/image/fetch/$s_!Wy02!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F66a35646-764b-4448-a88d-3fab7ced2c8a_1754x386.png 1272w, https://substackcdn.com/image/fetch/$s_!Wy02!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F66a35646-764b-4448-a88d-3fab7ced2c8a_1754x386.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!Wy02!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F66a35646-764b-4448-a88d-3fab7ced2c8a_1754x386.png" width="1456" height="320" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/66a35646-764b-4448-a88d-3fab7ced2c8a_1754x386.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:320,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:89032,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!Wy02!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F66a35646-764b-4448-a88d-3fab7ced2c8a_1754x386.png 424w, https://substackcdn.com/image/fetch/$s_!Wy02!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F66a35646-764b-4448-a88d-3fab7ced2c8a_1754x386.png 848w, https://substackcdn.com/image/fetch/$s_!Wy02!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F66a35646-764b-4448-a88d-3fab7ced2c8a_1754x386.png 1272w, https://substackcdn.com/image/fetch/$s_!Wy02!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F66a35646-764b-4448-a88d-3fab7ced2c8a_1754x386.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><p><strong>Preprocessing Text Data</strong>: The 'Movie_Name' column in the dataset contains movie titles that need to be preprocessed before using them as input to the Word2Vec model. The function <code>preprocess_text</code> is removes non-alphanumeric characters and convert the text to lowercase. The cleaned movie titles are then stored in a new column called 'title_cleaned' as shown here.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!NYJq!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff65aa9a3-af19-4a91-a181-50fa344b37b1_1756x568.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!NYJq!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff65aa9a3-af19-4a91-a181-50fa344b37b1_1756x568.png 424w, https://substackcdn.com/image/fetch/$s_!NYJq!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff65aa9a3-af19-4a91-a181-50fa344b37b1_1756x568.png 848w, https://substackcdn.com/image/fetch/$s_!NYJq!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff65aa9a3-af19-4a91-a181-50fa344b37b1_1756x568.png 1272w, https://substackcdn.com/image/fetch/$s_!NYJq!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff65aa9a3-af19-4a91-a181-50fa344b37b1_1756x568.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!NYJq!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff65aa9a3-af19-4a91-a181-50fa344b37b1_1756x568.png" width="1456" height="471" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/f65aa9a3-af19-4a91-a181-50fa344b37b1_1756x568.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:471,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:160176,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!NYJq!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff65aa9a3-af19-4a91-a181-50fa344b37b1_1756x568.png 424w, https://substackcdn.com/image/fetch/$s_!NYJq!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff65aa9a3-af19-4a91-a181-50fa344b37b1_1756x568.png 848w, https://substackcdn.com/image/fetch/$s_!NYJq!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff65aa9a3-af19-4a91-a181-50fa344b37b1_1756x568.png 1272w, https://substackcdn.com/image/fetch/$s_!NYJq!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff65aa9a3-af19-4a91-a181-50fa344b37b1_1756x568.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong>Creating Item Vectors</strong>: The function <code>item_name_to_vector</code> converts movie titles to their vector representations using the Word2Vec model. For each movie in the dataset, a dictionary 'item_vectors' is created, where the key is the movie title, and the value is its corresponding vector. Movie titles not found in the Word2Vec vocabulary are excluded from the 'item_vectors' dictionary.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!qSob!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2187c354-4fd7-4638-b6ba-d4acf2754a7c_1756x556.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!qSob!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2187c354-4fd7-4638-b6ba-d4acf2754a7c_1756x556.png 424w, https://substackcdn.com/image/fetch/$s_!qSob!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2187c354-4fd7-4638-b6ba-d4acf2754a7c_1756x556.png 848w, https://substackcdn.com/image/fetch/$s_!qSob!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2187c354-4fd7-4638-b6ba-d4acf2754a7c_1756x556.png 1272w, https://substackcdn.com/image/fetch/$s_!qSob!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2187c354-4fd7-4638-b6ba-d4acf2754a7c_1756x556.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!qSob!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2187c354-4fd7-4638-b6ba-d4acf2754a7c_1756x556.png" width="1456" height="461" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/2187c354-4fd7-4638-b6ba-d4acf2754a7c_1756x556.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:461,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:163383,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!qSob!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2187c354-4fd7-4638-b6ba-d4acf2754a7c_1756x556.png 424w, https://substackcdn.com/image/fetch/$s_!qSob!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2187c354-4fd7-4638-b6ba-d4acf2754a7c_1756x556.png 848w, https://substackcdn.com/image/fetch/$s_!qSob!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2187c354-4fd7-4638-b6ba-d4acf2754a7c_1756x556.png 1272w, https://substackcdn.com/image/fetch/$s_!qSob!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2187c354-4fd7-4638-b6ba-d4acf2754a7c_1756x556.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong>Setting up Faiss Index</strong>: The 'item_vectors' are then converted to a NumPy array, which is used to initialize a Faiss index with L2 (Euclidean) distance metric. The item vectors are added to the Faiss index, and the index is saved to a file for future use.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!poU6!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7c12207c-f2dc-421b-b414-4f104ffccb3a_1752x766.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!poU6!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7c12207c-f2dc-421b-b414-4f104ffccb3a_1752x766.png 424w, https://substackcdn.com/image/fetch/$s_!poU6!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7c12207c-f2dc-421b-b414-4f104ffccb3a_1752x766.png 848w, https://substackcdn.com/image/fetch/$s_!poU6!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7c12207c-f2dc-421b-b414-4f104ffccb3a_1752x766.png 1272w, https://substackcdn.com/image/fetch/$s_!poU6!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7c12207c-f2dc-421b-b414-4f104ffccb3a_1752x766.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!poU6!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7c12207c-f2dc-421b-b414-4f104ffccb3a_1752x766.png" width="1456" height="637" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/7c12207c-f2dc-421b-b414-4f104ffccb3a_1752x766.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:637,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:179392,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!poU6!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7c12207c-f2dc-421b-b414-4f104ffccb3a_1752x766.png 424w, https://substackcdn.com/image/fetch/$s_!poU6!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7c12207c-f2dc-421b-b414-4f104ffccb3a_1752x766.png 848w, https://substackcdn.com/image/fetch/$s_!poU6!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7c12207c-f2dc-421b-b414-4f104ffccb3a_1752x766.png 1272w, https://substackcdn.com/image/fetch/$s_!poU6!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7c12207c-f2dc-421b-b414-4f104ffccb3a_1752x766.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Shown below is a partial output of the print statement above showing the curated vector items.  We will use some of these vector &#8220;items&#8221; later to represent user preference data collected from user interaction.</p><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!AGyf!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8f1291f7-76be-4f37-9272-092c2fcdbee0_1772x334.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!AGyf!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8f1291f7-76be-4f37-9272-092c2fcdbee0_1772x334.png 424w, https://substackcdn.com/image/fetch/$s_!AGyf!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8f1291f7-76be-4f37-9272-092c2fcdbee0_1772x334.png 848w, https://substackcdn.com/image/fetch/$s_!AGyf!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8f1291f7-76be-4f37-9272-092c2fcdbee0_1772x334.png 1272w, https://substackcdn.com/image/fetch/$s_!AGyf!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8f1291f7-76be-4f37-9272-092c2fcdbee0_1772x334.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!AGyf!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8f1291f7-76be-4f37-9272-092c2fcdbee0_1772x334.png" width="1456" height="274" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/8f1291f7-76be-4f37-9272-092c2fcdbee0_1772x334.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:274,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:155692,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!AGyf!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8f1291f7-76be-4f37-9272-092c2fcdbee0_1772x334.png 424w, https://substackcdn.com/image/fetch/$s_!AGyf!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8f1291f7-76be-4f37-9272-092c2fcdbee0_1772x334.png 848w, https://substackcdn.com/image/fetch/$s_!AGyf!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8f1291f7-76be-4f37-9272-092c2fcdbee0_1772x334.png 1272w, https://substackcdn.com/image/fetch/$s_!AGyf!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8f1291f7-76be-4f37-9272-092c2fcdbee0_1772x334.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><p><strong>Getting Similar Movie Recommendations</strong>: A function called <code>find_similar_items</code> is defined to get similar movie recommendations based on user input. Users can input their preferences or interests, and the function uses Faiss to find similar movies to the user's input. The similarity is based on the Word2Vec vectors of the movie titles. The function then displays the top-k similar movie recommendations.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!8JF9!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0ad79708-227f-47e3-9564-c7349a48a891_1754x916.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!8JF9!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0ad79708-227f-47e3-9564-c7349a48a891_1754x916.png 424w, https://substackcdn.com/image/fetch/$s_!8JF9!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0ad79708-227f-47e3-9564-c7349a48a891_1754x916.png 848w, https://substackcdn.com/image/fetch/$s_!8JF9!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0ad79708-227f-47e3-9564-c7349a48a891_1754x916.png 1272w, https://substackcdn.com/image/fetch/$s_!8JF9!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0ad79708-227f-47e3-9564-c7349a48a891_1754x916.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!8JF9!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0ad79708-227f-47e3-9564-c7349a48a891_1754x916.png" width="1456" height="760" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/0ad79708-227f-47e3-9564-c7349a48a891_1754x916.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:760,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:268550,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!8JF9!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0ad79708-227f-47e3-9564-c7349a48a891_1754x916.png 424w, https://substackcdn.com/image/fetch/$s_!8JF9!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0ad79708-227f-47e3-9564-c7349a48a891_1754x916.png 848w, https://substackcdn.com/image/fetch/$s_!8JF9!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0ad79708-227f-47e3-9564-c7349a48a891_1754x916.png 1272w, https://substackcdn.com/image/fetch/$s_!8JF9!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0ad79708-227f-47e3-9564-c7349a48a891_1754x916.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong>Sample Usage</strong>: The notebook provides sample usage examples to demonstrate how to use the recommendation system. It shows how to get recommendations for a general movie preference (using <code>find_similar_items</code>) and how to get personalized recommendations for a user (using <code>get_user_recommendations</code>) based on their liked movies.</p><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!I6k7!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F973f96dd-f416-4856-86e7-f0fa230d31a4_1782x404.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!I6k7!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F973f96dd-f416-4856-86e7-f0fa230d31a4_1782x404.png 424w, https://substackcdn.com/image/fetch/$s_!I6k7!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F973f96dd-f416-4856-86e7-f0fa230d31a4_1782x404.png 848w, https://substackcdn.com/image/fetch/$s_!I6k7!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F973f96dd-f416-4856-86e7-f0fa230d31a4_1782x404.png 1272w, https://substackcdn.com/image/fetch/$s_!I6k7!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F973f96dd-f416-4856-86e7-f0fa230d31a4_1782x404.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!I6k7!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F973f96dd-f416-4856-86e7-f0fa230d31a4_1782x404.png" width="1456" height="330" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/973f96dd-f416-4856-86e7-f0fa230d31a4_1782x404.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:330,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:63414,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!I6k7!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F973f96dd-f416-4856-86e7-f0fa230d31a4_1782x404.png 424w, https://substackcdn.com/image/fetch/$s_!I6k7!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F973f96dd-f416-4856-86e7-f0fa230d31a4_1782x404.png 848w, https://substackcdn.com/image/fetch/$s_!I6k7!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F973f96dd-f416-4856-86e7-f0fa230d31a4_1782x404.png 1272w, https://substackcdn.com/image/fetch/$s_!I6k7!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F973f96dd-f416-4856-86e7-f0fa230d31a4_1782x404.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!S3eJ!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fafdbe90d-4b34-4591-b855-8120ef9bb7c3_1762x510.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!S3eJ!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fafdbe90d-4b34-4591-b855-8120ef9bb7c3_1762x510.png 424w, https://substackcdn.com/image/fetch/$s_!S3eJ!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fafdbe90d-4b34-4591-b855-8120ef9bb7c3_1762x510.png 848w, https://substackcdn.com/image/fetch/$s_!S3eJ!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fafdbe90d-4b34-4591-b855-8120ef9bb7c3_1762x510.png 1272w, https://substackcdn.com/image/fetch/$s_!S3eJ!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fafdbe90d-4b34-4591-b855-8120ef9bb7c3_1762x510.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!S3eJ!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fafdbe90d-4b34-4591-b855-8120ef9bb7c3_1762x510.png" width="1456" height="421" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/afdbe90d-4b34-4591-b855-8120ef9bb7c3_1762x510.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:421,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:121781,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!S3eJ!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fafdbe90d-4b34-4591-b855-8120ef9bb7c3_1762x510.png 424w, https://substackcdn.com/image/fetch/$s_!S3eJ!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fafdbe90d-4b34-4591-b855-8120ef9bb7c3_1762x510.png 848w, https://substackcdn.com/image/fetch/$s_!S3eJ!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fafdbe90d-4b34-4591-b855-8120ef9bb7c3_1762x510.png 1272w, https://substackcdn.com/image/fetch/$s_!S3eJ!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fafdbe90d-4b34-4591-b855-8120ef9bb7c3_1762x510.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Here&#8217;s the output for User 3:</p><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!WVR8!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa1745da8-7c62-43f6-b94b-86ce20fcaf03_1774x234.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!WVR8!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa1745da8-7c62-43f6-b94b-86ce20fcaf03_1774x234.png 424w, https://substackcdn.com/image/fetch/$s_!WVR8!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa1745da8-7c62-43f6-b94b-86ce20fcaf03_1774x234.png 848w, https://substackcdn.com/image/fetch/$s_!WVR8!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa1745da8-7c62-43f6-b94b-86ce20fcaf03_1774x234.png 1272w, https://substackcdn.com/image/fetch/$s_!WVR8!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa1745da8-7c62-43f6-b94b-86ce20fcaf03_1774x234.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!WVR8!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa1745da8-7c62-43f6-b94b-86ce20fcaf03_1774x234.png" width="1456" height="192" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/a1745da8-7c62-43f6-b94b-86ce20fcaf03_1774x234.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:192,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:33167,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!WVR8!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa1745da8-7c62-43f6-b94b-86ce20fcaf03_1774x234.png 424w, https://substackcdn.com/image/fetch/$s_!WVR8!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa1745da8-7c62-43f6-b94b-86ce20fcaf03_1774x234.png 848w, https://substackcdn.com/image/fetch/$s_!WVR8!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa1745da8-7c62-43f6-b94b-86ce20fcaf03_1774x234.png 1272w, https://substackcdn.com/image/fetch/$s_!WVR8!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa1745da8-7c62-43f6-b94b-86ce20fcaf03_1774x234.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><h3>Conclusion</h3><p>In conclusion, vector databases have revolutionized data-driven decision making, as exemplified by our movie recommendation system. Leveraging Word2Vec embeddings and Faiss, we provided users with highly personalized movie suggestions. Across industries, vector databases drive revenue by delivering personalized experiences, detecting fraud, and optimizing decision-making. With their speed and accuracy, these databases unlock untapped potential in recommendation systems and data analysis. Embrace the vector database revolution for smarter decisions and unparalleled user experiences, propelling us towards a data-powered future. Let's continue pushing the boundaries of AI and ML together.</p><p>If you would like to kick the tires and take this sample code for a spin for a deeper look, you can clone the code in this blog from my <a href="https://github.com/alsabay/vector_db_recommender/tree/main">Github repository</a>.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.nexusnotes.co/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Thanks for reading Nexus Notes: Where AI and ML Meet Innovation! Subscribe for free to receive new posts and support my work.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item></channel></rss>