<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Eleos Health - Medium]]></title>
        <description><![CDATA[Therapy Intelligence for Behavioral Health Specialists | A Digital Mental Health Company - Medium]]></description>
        <link>https://medium.com/eleos-health?source=rss----7210f36f4253---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Eleos Health - Medium</title>
            <link>https://medium.com/eleos-health?source=rss----7210f36f4253---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:41:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/eleos-health" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Baking the Future of AI with RAG and VectorDB]]></title>
            <link>https://medium.com/eleos-health/baking-the-future-of-ai-with-rag-and-vectordb-a29bf741530d?source=rss----7210f36f4253---4</link>
            <guid isPermaLink="false">https://medium.com/p/a29bf741530d</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Chen Probstein]]></dc:creator>
            <pubDate>Thu, 19 Sep 2024 14:00:39 GMT</pubDate>
            <atom:updated>2024-09-19T14:00:39.331Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Journey Towards Vector Databases and RAG</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cLdP3inRJVg3OZErqekl4A.png" /></figure><p>Imagine you’ve just walked into a bakery, excited to buy your favorite pastry. The smell is inviting, the counter looks promising — but when you take a bite, something’s missing. It’s technically the right pastry, it meets all the standards, but it lacks that special touch, the one that makes it feel like it was made just for you.</p><p>That’s exactly what we experienced at Eleos Health. Our data team, a dedicated group of data scientists, engineers, and analysts, is responsible for developing and maintaining various AI products. One of our primary tasks is to help our users, therapists, and clinicians, efficiently summarize their therapy sessions with clients while adhering to compliance standards. We take pride in the work we do, always striving to push the boundaries of what’s possible. And to keep improving, we make it a point to regularly gather feedback from our users to understand their needs and pain points.</p><p>From this ongoing feedback, we learned something crucial: while our AI was effective in creating compliant notes, it often fell short in terms of personalization. The notes generated were compliant, yes, but they sometimes felt generic — lacking the unique voice of each therapist and the specific nuances of each session.</p><p>That’s when the lightbulb went on. We realized it wasn’t just about generating compliant notes; it was about capturing how each therapist worked. To do that, we turned to Retrieval-Augmented Generation (RAG) and Vector Databases, enabling us to enhance our AI solutions with personalized, context-rich examples.</p><p>The result? Notes that didn’t just meet standards — they felt authentic, just like that perfect pastry you were craving.</p><h3><strong>Understanding the Building Blocks: Embeddings and VectorDB</strong></h3><p>Think of embeddings as the secret ingredients in your favorite pastry recipe — the ones that give the final product that special flavor you can’t quite describe but can definitely taste. Simply put, embeddings are numerical representations that capture the meaning and context of data — whether it’s text, audio, or video.</p><p>What makes embeddings powerful is their versatility. They allow us to convert various types of data into high-dimensional vectors that can be stored and searched within a Vector Database. Whether the data comes from an audio recording, a written note, or a video, specialized models can create embeddings that encapsulate the essence of that data.</p><p>This unified approach means we can perform semantic searches across different data types, retrieving relevant information regardless of its original form. It’s like having a universal recipe that works for any type of pastry, ensuring that our AI systems can pull up the right “flavors” and deliver the best results.</p><h4>What is Vector DB and What Problems Does It Solve?</h4><p>Picture a traditional recipe book with clear instructions and precise measurements — perfect for simple cookies where everything is straightforward. Traditional databases are like that: great for handling structured, orderly information.</p><p>But what about when you’re making something more complex, like a croissant, where intuition and experience matter? That’s where traditional databases fall short, struggling with unstructured data like text or images that need more than just rigid structure.</p><p>Now, think of a seasoned pastry chef who knows how to blend ingredients based on their essence. Similarly, VectorDB is designed to handle high-dimensional vector data, allowing searches based on meaning rather than just exact matches — perfect for complex applications where context is key.</p><h4>Vector Databases VS Vector Libraries</h4><p>After understanding how VectorDB operates — it’s important to see how VectorDB stacks up against other tools in the kitchen. Think of vector libraries, like <a href="https://ai.meta.com/tools/faiss/">FAISS</a>, as a small bakery specializing in made-to-order pastries — quick and efficient for small batches. Vector libraries store data in RAM, making them fast but limited. If the service goes down, all data is lost, requiring re-embedding, much like a bakery without storage for extra ingredients.</p><p>VectorDB, on the other hand, is like a commercial bakery with well-stocked shelves and backup systems. It doesn’t just store data reliably, but it also ensures low latency, keeping things quick even for large datasets. By separating compute from storage, VectorDB provides both speed and scalability, making it perfect for long-term, high-performance applications where precision and reliability are key.</p><h4>The Impact of Vector Databases</h4><p>Using Vector Databases has brought significant benefits:</p><ol><li><strong><em>Efficiency</em></strong><em>:</em> They speed up the processing of complex, unstructured data, allowing us to deliver insights faster and manage large data volumes effectively.</li><li><strong><em>Accuracy</em></strong><em>: </em>Improve the accuracy of our AI by enabling precise, context-based searches, resulting in more relevant and reliable outputs for therapists.</li><li><strong><em>Scalability and Innovation</em></strong><em>:</em> Ensure we remain a leading AI force in the mental healthcare field. They allow our systems to scale easily and keep us at the forefront of technology, always working with the most cutting-edge solutions available on the market.</li></ol><p>Overall, Vector Databases not only enhance our current capabilities but also secure our position as innovators in mental healthcare technology.</p><h3>What is Retrieval-Augmented Generation (RAG)?</h3><p>Imagine a baker who, instead of just using what’s already in the pantry, can quickly gather the best, freshest ingredients from across markets. That’s what RAG does for AI — it brings in the most relevant, up-to-date information before creating the final output.</p><p>Retrieval-Augmented Generation (RAG) is a powerful technique that enhances the capabilities of large language models (LLMs) by incorporating relevant external information before generating a response. This approach improves both the precision and relevance of the outputs, making AI responses more accurate and contextually appropriate.</p><h4>How RAG Works: The Three Steps</h4><ol><li><strong><em>Indexing</em></strong><em>:</em> The process begins by splitting documents into shorter, manageable chunks and indexing these chunks in a Vector Database (VectorDB). The VectorDB stores these chunks as high-dimensional vectors, capturing the semantic meaning of the text. This structured storage makes it easy to access specific information quickly.</li><li><strong><em>Retrieval</em></strong><em>: </em>When a question or prompt is provided, RAG leverages the VectorDB to retrieve the most relevant chunks based on semantic similarity. This retrieval process ensures that the LLM is fed contextually rich and relevant information (which is usually termed “context”) that directly aligns with the query.</li><li><strong><em>Generation</em></strong><em>:</em> With the retrieved information, the language model generates a response that is enriched with the aforementioned retrieved context. By using the relevant data from the VectorDB, the model can produce answers that are not only more accurate but also better tailored to the specifics of the question.</li></ol><h4>Enriching Prompts and Dynamic Fine-Tuning with VectorDB</h4><p>RAG works by dynamically enriching the prompts fed into the LLM, allowing it to be fine-tuned “on the fly” using the most pertinent context and examples stored in the VectorDB. This dynamic fine-tuning process ensures that the AI delivers precise, context-aware results tailored to individual queries, very quickly.</p><p>The integration of VectorDB into RAG is crucial because it provides a persistent, scalable way to manage and query vast amounts of data. VectorDB ensures that data is always accessible and can handle large-scale queries efficiently, making it an essential backbone for real-time, context-driven AI responses.</p><h4>Going Beyond Training Limitations</h4><p>Just as a baker’s skill goes beyond just following the recipe, RAG not only enhances the accuracy of AI responses but also allows the AI to provide answers that might otherwise be impossible due to the limitations of its training data. For instance, an AI model trained only up to a certain date might lack knowledge of more recent events. RAG, with its ability to tap into a continually updated VectorDB, can retrieve the latest information to answer questions accurately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-yCeOHrgLSOrihq1WWcXtA.gif" /><figcaption>Basic RAG process with query, vector database, and LLM</figcaption></figure><h3>Vector Database Market Review and Proof of Concept</h3><p>Just as a baker meticulously tests ingredients before selecting the perfect flour for their signature pastry, we at Eleos Health conducted a comprehensive market review and a detailed Proof of Concept (POC) to identify the ideal Vector Database for our AI needs.</p><p>Our goal was to find a solution that would effectively support our Retrieval-Augmented Generation (RAG) processes, enhancing our AI capabilities and ensuring robust performance. Here’s a look at our evaluation process, considerations, and findings:</p><h4>Database Size Considerations</h4><p>Think of our database like the storage space in a bakery. Initially, we estimated our storage requirements based on 6,000 sessions per day, with each session generating six vectors of 768 dimensions each. This put us at a projected size of around 225 GB over five years. At that point, using multiple vectors seemed necessary to capture the full complexity of each therapy session.<br>Later, we found that one vector per session is probably enough for our needs at the time, making our data storage more efficient.</p><p>These size estimates were for just this project. We didn’t account for our broader plans to use vector databases across multiple products and internal applications, which would require even more storage. Plus, the five-year projection didn’t consider company growth, so we expect the database size to expand significantly, highlighting the need for a scalable solution.</p><h4>Key Considerations for Selecting a Vector Database Solution</h4><p>Just as a baker considers the type of oven, the temperature, and the size of their kitchen, we had to evaluate several critical factors in selecting the right Vector Database solution:</p><ol><li><strong><em>Scalability</em></strong><em>:</em> The solution must handle growing data volumes and increased query loads. Vertical scaling (adding more resources to a single server) and horizontal scaling (distributing load across multiple servers) were critical features.</li><li><strong><em>Latency</em></strong><em>:</em> Quick, responsive query times are crucial, especially when dealing with real-time applications where user experience depends on fast information retrieval.</li><li><strong><em>Accuracy</em></strong><em>:</em> The ability to accurately retrieve relevant vectors is essential for delivering precise and meaningful AI-generated responses.</li><li><strong><em>Cost</em></strong><em>:</em> Both the initial setup and ongoing operational costs were evaluated to ensure the solution would be cost-effective over the long term.</li><li><strong><em>Ease of Integration</em></strong><em>: </em>Compatibility with existing data pipelines and machine learning models was a key factor, aiming for minimal disruption and seamless adoption.</li><li><strong><em>Support for Zero and few-Shot Learning</em></strong><em>:</em> We needed a database capable of handling embeddings effectively, also in scenarios requiring responses based on new or emerging information.</li><li><strong><em>Similarity Search Capabilities</em></strong><em>:</em> Efficient and accurate similarity search was a non-negotiable feature for retrieving contextually relevant data.</li><li><strong><em>Data Security and Privacy</em></strong><em>:</em> Ensuring compliance with data protection regulations was vital, given the sensitive nature of healthcare data.</li><li><strong><em>Community and Support</em></strong><em>:</em> The availability of strong documentation, active community support, and access to professional services was important for sustainable and effective use.</li></ol><h4>POC — Market Review Solutions</h4><p>In our research, we mixed together insights from academic papers, podcasts, and AI consultations, much like testing a variety of ingredients before settling on the perfect blend for a signature dish. Here’s a taste of the key solutions we considered:</p><ul><li><strong>Elasticsearch</strong>: Known for its powerful text search capabilities, Elasticsearch has expanded to support vector search, making it a versatile choice for applications requiring both text and semantic search capabilities.</li><li><strong>Azure AI Search</strong>: A cloud-based service offering AI-driven search capabilities, suitable for creating complex, AI-powered search experiences across various application types.</li><li><strong>OpenSearch</strong>: A community-driven open-source search and analytics suite derived from Elasticsearch, designed for scalable data analysis.</li><li><strong>Pinecone</strong>: A specialized, high-performance vector database service tailored for machine learning, offering scalable similarity search and easy integration with AI workflows.</li><li><strong>Milvus</strong>: An open-source vector database optimized for AI applications, providing scalable and efficient vector storage, indexing, and retrieval.</li><li><strong>Weaviate</strong>: Another open-source vector database, offering robust support for various neural search frameworks, with options for cloud and self-hosting.</li><li><strong>pgvector for PostgreSQL</strong>: An extension for PostgreSQL that adds vector search capabilities, allowing for efficient similarity search within a traditional relational database.</li></ul><p>Based on this research, I created the following table, which scores each solution on its read and write performance capabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/0*_v4THoAQPgqc9hWQ" /><figcaption>Vector database performance comparison table</figcaption></figure><p>Based on this market review, and as I delved deeper into understanding the potential of these technologies, it became clear that we needed a solution that was a vector database at its core, not just an extension or add-on. We needed something robust enough to handle our growing needs and versatile enough to enable a wide range of applications.</p><h4>Deep Dive into POC with Pinecone and Milvus</h4><p>Realizing the need for a native vector database solution, we focused our POC efforts on two leading vector databases: Pinecone (managed service) and Milvus (open-source). Both offered dedicated vector storage and high performance for similarity searches.</p><p>Testing Methodology: We generated synthetic data using .npy files of embeddings, augmented with random noise to simulate various data sizes. We optimized batch insertion and tested both read and write times to evaluate performance.</p><h4>Milvus: The Open-Source Vector Database</h4><p>Milvus is an open-source vector database designed specifically for handling massive amounts of vector data, which is crucial for AI and machine learning applications. Built to support high-performance similarity search, Milvus leverages advanced indexing techniques to ensure efficient data retrieval. It is particularly well-suited for use cases that require large-scale data processing. Milvus offers robust support for scalar data types and integrates seamlessly with existing AI workflows, making it a popular choice among developers and data scientists.</p><h4>Milvus POC Results:</h4><ul><li><strong><em>Ease of Use and Integration</em></strong><em>:</em> Milvus offered an easy-to-use Python module with comprehensive documentation, making integration straightforward. Its familiar structure helped reduce the learning curve.</li><li><strong><em>Performance: </em></strong>Milvus performed well, with fast query times once collections were loaded. It also supported scalar searches and pagination, improving flexibility in complex queries.</li><li><strong><em>Infrastructure Challenges:</em> </strong>Setting up Milvus required significant DevOps support, adding complexity. We also faced issues with Helm charts, raising concerns about scalability and automation.</li><li><strong><em>Caching for Real-Time Use: </em></strong>Milvus needed collections to be loaded into cache before querying, which caused occasional delays of several seconds — potentially affecting real-time applications.</li></ul><h4><strong>Pinecone: The Managed Vector Database Solution</strong></h4><p>Pinecone is a specialized vector database designed to deliver high-performance similarity searches as a managed service. Unlike traditional databases, Pinecone is optimized for storing and querying vector data, making it a powerful tool for machine learning and AI applications. Pinecone offers both serverless and pod-based deployment options, providing flexibility in how resources are managed and scaled. Its design focuses on ease of use, speed, and scalability, making it an attractive choice for businesses looking to integrate vector search capabilities without heavy infrastructure overhead.</p><h4><strong>Pinecone POC Results</strong>:</h4><ul><li><strong><em>Ease of Use and Integration:</em> </strong>Pinecone’s user-friendly Python client and thorough documentation made integration seamless and straightforward.</li><li><strong><em>Performance:</em> </strong>With both serverless and pod-based deployment options, Pinecone delivered excellent performance. Pod-based was faster, but even serverless maintained low latency suitable for real-time use.</li><li><strong><em>Operational Efficiency:</em> </strong>As a fully managed service, Pinecone reduced DevOps needs and provided UI tools for easy performance monitoring, simplifying management.</li><li><strong><em>Limitations:</em> </strong>Pinecone had limited support for scalar searches, and costs could rise with increased usage. Cold start delays in serverless mode were minimal, usually under a second.</li></ul><h3>The Chosen Solution: Pinecone</h3><p>After evaluating both solutions, Pinecone emerged as the clear winner — much like selecting the perfect oven for a busy bakery. Its managed service model, high performance, and user-friendly interface made it an excellent fit for our needs.</p><p>The next decision was therefore whether to go with Pinecone’s Pod-Based or Serverless deployment.</p><h4>Pinecone Pod-Based vs. Serverless</h4><ul><li><strong><em>Pod-Based</em></strong><em>:</em> Offers faster response times by keeping vectors in hot storage, ensuring quick access. However, this model is more costly due to continuous resource usage and requires manual scaling operations which adding complexity.</li><li><strong><em>Serverless</em></strong><em>:</em> Provides good enough latency with vectors stored in cold storage, invoking compute resources only as needed. This model is more cost-effective, supports automatic scaling, and simplifies operational management. Pinecone prioritizes serverless for new feature rollouts, making it a future-proof choice.</li></ul><p>We ultimately chose the <strong>serverless</strong> model for its balance of performance, cost-effectiveness, and ease of management. This allows us to stay agile, scaling as demand grows while keeping operational costs low. However, much like being able to switch to a high-performance oven for a busy holiday rush, Pinecone remains flexible, giving us the option to transition to pod-based if specific use cases or higher demands arise.</p><h4>Pinecone Serverless Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wzVxnTVr13GpTof0.png" /><figcaption>Pinecone serverless high-level architecture</figcaption></figure><p>Now, let’s take a look at our new kitchen. Pinecone’s serverless model efficiently manages data requests by routing them through key components. Applications send requests through an API Gateway, where the API key is verified and requests are routed to either the <strong>control plane</strong> or <strong>data plane</strong>. The <strong>control plane</strong> manages projects, indexes, and API keys, using a dedicated database for these objects. Meanwhile, the <strong>data plane</strong> handles the actual read/write operations, with namespaces ensuring data is neatly organized. Writes and reads are processed separately, with independent auto-scaling compute resources that optimize performance and keep costs low.</p><p>For long-term data retention, Pinecone utilizes <strong>object storage</strong>, clustering related records and generating centroids for efficient retrieval. These clusters are stored in distributed object storage, providing limitless scalability and high availability. This architecture keeps operations scalable, cost-effective, and reliable — perfectly suited for our evolving needs.</p><h3>Deployment Architecture and Results:</h3><p>Our implementation of Pinecone VectorDB has elevated the performance of one of our core products, similar to how a well-equipped bakery produces consistently exceptional pastries. The architecture we’ve designed is highly scalable, meaning it can easily be replicated and applied to other products as our needs evolve, ensuring we’re always prepared to craft the ideal AI solution.</p><h4><strong>Architecture Overview</strong></h4><ul><li><strong><em>Pinecone Indexes:</em></strong> We created two separate Pinecone indexes to handle different types of notes. In vector databases, an <em>index</em> serves as a data structure that organizes vector embeddings efficiently.</li><li><strong><em>Organizational Namespaces:</em></strong> Each index is subdivided into <em>organizational namespaces</em>. In our context, <em>organizations</em> refer to the healthcare organizations that are our clients. For each organization, we created a unique namespace, effectively acting like a partition. These namespaces isolate and manage data securely, ensuring that each organization’s data remains separate and is handled according to its unique requirements. This setup maintains strict data security and privacy.</li><li><strong><em>Embedding Process</em></strong><em>:</em> Each de-identified note is converted into a single embedding that captures all relevant information. These embeddings are stored in Pinecone and include metadata such as session type, the de-identified note content, and other key details, enabling targeted and contextually accurate searches.</li></ul><h4>Ingestion Process Components</h4><p><strong>Python Code Module</strong>: A customized Python module efficiently handles the entire ingestion process, including:</p><ol><li><strong><em>Data Extraction: </em></strong>Pulls relevant data from our data lake for processing.</li><li><strong><em>Mapping</em></strong><em>:</em> Formats and organizes the extracted data into a structure suitable for embedding.</li><li><strong><em>De-Identification:</em></strong> Removes sensitive information using a dedicated de-identification model to ensure privacy and compliance.</li><li><strong><em>Embedding</em></strong><em>:</em> Transforms each note into a vector embedding using our AI models.</li><li><strong><em>Loading into Pinecone: </em></strong>Uploads the embeddings into the relevant Pinecone indexes.</li></ol><p><strong>Airflow DAG</strong>: An Airflow Directed Acyclic Graph (DAG) orchestrates this workflow, managing configurations and ensuring smooth execution from data extraction to embedding and loading into Pinecone.</p><h4>Monitoring Results and Observations</h4><p>Integrating the vector database has significantly enhanced our product’s performance. We’ve seen faster processing times, with the database reducing search and retrieval times, keeping everything efficient even as data volumes grow. Note quality has improved through advanced similarity search, prioritizing contextually relevant notes. User engagement is up — more AI-generated text is being saved and fully utilized, showing increased trust in our AI assistance. Feedback ratings have also improved, reflecting higher satisfaction with the quality and speed of the generated notes.<br>We were truly amazed by the results from our therapists. Previously, we received feedback like:</p><blockquote>“Had to make many changes to fit my glossary”</blockquote><blockquote>“Accurate but not necessarily my style”</blockquote><p>Now, the feedback has transformed into:</p><blockquote>“Great note, important information picked up. I also love how Eloes is able to ascertain the type of therapy style/intervention I use during the session because I don’t even know. Lol”</blockquote><blockquote>“It is really getting to know my notetaking style.”</blockquote><p>This shift demonstrates not only our improvement but also the growing trust and satisfaction with our AI solutions.<br>Overall, the vector database integration has boosted both product performance and user experience, ensuring our AI solutions are as reliable as a well-oiled kitchen producing top-quality results every time.</p><h3>Empowering AI with RAG and Vector DB: Redefining the Landscape</h3><p>To conclude our journey for crafting that perfect, special-touched pastry, this wasn’t just about adopting new technology — it was about transforming how we use data to elevate the user experience. By integrating vector databases and Retrieval-Augmented Generation, we’ve made our AI smarter, faster, and more intuitive. This isn’t merely a step forward; it’s a leap toward a future where AI doesn’t just assist but genuinely understands.</p><p>From improving the efficiency of our processes to ensuring that every interaction is more meaningful, these advancements have brought us closer to delivering exceptional AI experiences. With scalable architecture and flexible solutions, we’re not just meeting today’s demands; we’re setting the stage for future innovations.<br>As we continue to grow, our mission remains the same: to push the boundaries of what’s possible with AI, turning data into insights that truly make a difference. This journey is only the beginning, and with each improvement, we move closer to a future where AI plays a crucial role in delivering personalized, impactful mental healthcare. Here’s to more innovation, and like any great bakery, always rising to create something fresh and extraordinary!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a29bf741530d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/eleos-health/baking-the-future-of-ai-with-rag-and-vectordb-a29bf741530d">Baking the Future of AI with RAG and VectorDB</a> was originally published in <a href="https://medium.com/eleos-health">Eleos Health</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating the Data Deluge: A Journey to Crafting a Sophisticated Lakehouse Platform]]></title>
            <link>https://medium.com/eleos-health/navigating-the-data-deluge-a-journey-to-crafting-a-sophisticated-lakehouse-platform-7a1d7a147149?source=rss----7210f36f4253---4</link>
            <guid isPermaLink="false">https://medium.com/p/7a1d7a147149</guid>
            <category><![CDATA[data-lake]]></category>
            <category><![CDATA[data-lakehouse]]></category>
            <category><![CDATA[apache-iceberg]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-architecture]]></category>
            <dc:creator><![CDATA[Meni Shakarov]]></dc:creator>
            <pubDate>Tue, 28 May 2024 07:08:01 GMT</pubDate>
            <atom:updated>2024-05-28T07:08:01.368Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HDp9Ak5VqmQYFaSytGA8eg.png" /></figure><p>It was late on a Thursday afternoon when the realization dawned on us. Gathered around the flickering screens in our dimly lit office, my two colleagues — both sharp data analysts — a dedicated team of data scientists, and I, a data engineer, were deep into attempting to join data from our PostgreSQL and MySQL databases. The task should have been straightforward, but instead, we found ourselves wrestling with mismatched data structures and conflicting schemas from different departments. As we manually tried to align these disparate data sets, the complexity felt overwhelming. With each failed attempt to synchronize this chaotic information, the air grew thicker with frustration. “We can’t work like this,” I muttered under my breath, the stress palpable in my voice. It was clear that our current system was woefully inadequate — we needed a unified platform that could not only contain but also make sense of this sprawling data jungle. This was the moment we knew a significant change was imperative. This was the moment we knew a big change was about to come.</p><p>Embarking on this journey led to the creation of a robust data platform architecture that now underpins our company’s decision-making process. In this blog post, I will explore the insights and challenges we faced while building a data infrastructure that not only consolidates diverse data into a single, powerful engine for analysis but also remains flexible and scalable, continuously evolving and integrating more data sources over time.</p><p>Data lakes have emerged as a vital tool for businesses that need to adapt quickly and scale efficiently, allowing the storage of large volumes of raw data in its native format. This flexibility is a game changer for data integration. As we progressed, however, we recognized the need for a more structured approach to data management, leading us to adopt a lakehouse architecture. This hybrid model combines the scalability and flexibility of data lakes with the management capabilities of data warehouses, enhancing our data strategy. This narrative will explore the practical steps we took to harness these technologies, shedding light on how the integration of a data lake into a lakehouse framework can be a transformative asset for any data-driven organization.</p><h4><strong>Our Data Strategy Before the Lakehouse</strong></h4><p>Before developing our lakehouse, our data management was simple but became inefficient as our needs grew. Initially, we managed 3 main data sources using Apache Superset for BI, which initially met our needs with minimal complexity.</p><p>However, as our data requirements grew, the limitations of our system began to show. A significant challenge arose when we needed to join data across two different sources. Our solution at the time was far from efficient: we manually replicated the necessary data from one source to another. This process was not only time-consuming but also prone to errors, as it required frequent updates to keep the data synchronized.</p><p>Moreover, as different teams and projects developed, multiple datasets were created within Superset, each tailored for specific analytical needs. Unfortunately, this led to redundant transformations being coded into multiple datasets. Not only did this redundancy complicate our data processes, but it also made maintaining and updating these transformations increasingly burdensome.</p><h4><strong>Deciding on a Data Architecture: Lake, Warehouse, or Lakehouse?</strong></h4><p>Choosing the right architecture for our data infrastructure was a critical decision. We deliberated among three main options: a data lake, a data warehouse, and a lakehouse. Here’s a brief overview of each:</p><p>• <strong>Data Lake:</strong> A data lake stores vast amounts of raw data in its native format. It’s ideal for handling large volumes of diverse data from various sources, offering high flexibility and scalability. However, it lacks some of the processing efficiencies of structured data environments.</p><p>• <strong>Data Warehouse:</strong> This is a system that stores data in a structured format, optimized for querying and analysis. Data warehouses are excellent for fast query performance on structured data but can be less flexible in accommodating changes and new data types.</p><p>• <strong>Lakehouse:</strong> A hybrid model that combines the best of both data lakes and data warehouses. It provides the vast storage and flexibility of data lakes, along with the efficient querying capabilities of data warehouses.</p><p>After careful consideration, we chose to implement a lakehouse architecture for several reasons:</p><p>1. <strong>Flexibility:</strong> The lakehouse architecture offered the adaptability we needed. Traditional data warehouses can be restrictive and slow to adapt to changes, making it challenging to integrate new data sources or types quickly.</p><p>2. <strong>Simplified Architecture:</strong> Initially, we considered implementing a traditional ETL process to a data warehouse alongside a data lake, but we found no compelling reason to maintain two separate systems. The lakehouse model offers a streamlined approach, combining the robust querying and storage capabilities into a single, more manageable system.</p><p>3. <strong>Query Performance:</strong> Our lakehouse setup provides excellent query performance that meets our current needs. While it may not support real-time millisecond response times, it’s more than adequate for our analytical requirements without the overhead of real-time processing.</p><h4>Our Data Lakehouse stack</h4><p>Our lakehouse architecture is designed to harness the best of AWS technology and open-source solutions to manage and analyze our data effectively. Here’s an overview of the core components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TG0Md6BXzEukuxHacsqulQ.png" /></figure><p><strong>Data Storage:</strong></p><p>We utilize AWS S3 for our data storage, organizing our environment into 2 dedicated buckets for development and production. Embracing the medallion architecture, we’ve established three distinct layers(folders) within each bucket: bronze, silver, and gold, each serving a specific purpose in our data management lifecycle.<br>The medallion architecture is a tiered data processing model used in lakehouse systems that categorizes data into three layers:</p><ul><li><strong><em>Bronze Layer (Raw Layer):</em></strong> At this foundational level, we store data exactly as it arrives from various sources, preserving it in its native formats such as JSON, CSV, and others. This layer is essential for us, primarily utilized by our data engineering team who access it for debugging and ensuring data integrity. It’s also where our data scientists start their exploratory analysis to gauge data quality and gather initial insights, which are crucial for guiding further data processing strategies.</li><li><strong><em>Silver Layer (Cleansed Layer):</em></strong> Once data moves to the silver layer, we perform necessary cleansing and transformation processes. Here, we correct any inconsistencies and enrich the data, applying specific business rules to make it more structured and useful. Our analytics engineer frequently works with this cleansed data, executing complex transformations and generating detailed reports that drive our internal analytics. Moreover, this layer provides a cleaner, more organized data environment that our data scientists rely on for building sophisticated models.</li><li><strong><em>Gold Layer (Aggregated Layer)</em>:<em> </em></strong>This is where our data achieves its highest value, transformed into business-level aggregates and key performance metrics that are directly used for decision-making and strategic planning. Optimized for rapid retrieval and high-speed analysis, the gold layer is predominantly accessed by our data analysts for decision-makers. They depend on this refined data for actionable insights that influence company-wide strategies and operations. Additionally, this layer serves as the backbone for our enterprise-level reporting and dashboarding.</li></ul><p>In our silver and gold layers, data files are stored as Parquet files to optimize query performance due to Parquet’s efficient columnar storage format. Over these Parquet files, we utilize Apache Iceberg, an open table format that brings several critical features to our lakehouse architecture.<br>With Apache Iceberg, we can treat our data lake much like a traditional database but with greater flexibility and scalability. It supports complex operations such as snapshotting, transactions, upserts, and deletions, transforming our data lake into a more dynamic and versatile system.</p><p><strong>Data Catalog:</strong></p><p>For our data cataloging needs, we chose AWS Glue Catalog, primarily for its cost-effectiveness, deep integration with other AWS services, and straightforward metadata management capabilities. AWS Glue Catalog serves as a central metadata repository, which makes it easier for us to manage and access our data assets across various AWS services. Utilizing the AWS Glue Crawler, we are able to automatically discover and categorize data stored in S3, creating and updating the data catalog tables effortlessly.</p><p>However, we recognize that AWS Glue Catalog has its limitations, especially when it comes to facilitating easy data discovery in a way that suits our operational needs. While it integrates well and is cost-effective, it does not support some of the more nuanced features of a sophisticated data catalog, like enhanced search and discovery tools that are vital for larger scale data operations. This can impact various team members, including data scientists who require quick access to diverse datasets for modeling, data analysts who need to generate rapid insights for business decisions, and business intelligence professionals who depend on streamlined data exploration to build comprehensive reports. Moving forward, we plan to investigate more robust solutions for data cataloging that can provide a more convenient and comprehensive support for data discovery, catering to the needs of these critical roles in our organization.</p><p><strong>Data Access and Query Engine:</strong></p><p>AWS Athena serves as our primary query engine, offering a seamless integration with the AWS Glue Catalog. This straightforward setup allows us to efficiently query our data lake, making Athena a crucial component of our data architecture. One of the key advantages of using Athena is its cost-effectiveness. Since Athena charges based on the amount of data scanned during queries, and our current queries do not scan excessive amounts of data, we have managed to keep our costs quite low.</p><p>However, we are aware that as we expand our use of the data lake — especially with the upcoming integration of direct data queries via charts in our application — the costs associated with Athena could increase. To prepare for this potential scenario, we are considering a transition to Trino, which would run on EKS and connect to the AWS Glue metastore. This migration is expected to be straightforward due to the underlying similarities between Athena and Trino.</p><p>Currently, we utilize two different workgroups in Athena — one dedicated to SQL queries and the other to Spark (Python) operations. Looking ahead, we plan to refine this setup by creating separate workgroups for different business needs, such as transformations, customer analytics, etc., to enhance operational efficiency and cost management.</p><p><strong>Data Governance:</strong></p><p>AWS Lake Formation is integral to our data governance, significantly boosting data security and permission management in our lakehouse architecture. It helps us enforce strict access controls, crucial for handling PHI and sensitive data.</p><p>Implementing LF-Tags for Robust Access Control: To ensure data is accessed securely and in compliance with our strict policies, we utilize LF-tags to finely control permissions at the database and table levels. Our tagging strategy is methodically designed, where databases are tagged generally, and more granular permissions are managed at the table level based on specific requirements. The possible tags we use include:</p><ul><li>Environment: dev, prod</li><li>Department: app, internal, devops, hr, customers, infra, sales, ds</li><li>PHI: true</li><li>Data Lake Layer: gold, silver, bronze</li><li>Client Facing: true (indicates whether the data can be exposed to clients)</li></ul><p>Multiple tags can be applied to each database and table, allowing for nuanced, role-based access control. For example, a role designed for customers querying data from our application might be granted access through a combination of tags such as client_facing: true, data_lake_layer: gold, and environment: prod.</p><p>Initially, setting up AWS Lake Formation was not straightforward. The platform, while powerful, was not intuitive, and it took considerable effort and time to align the permission behaviors with our governance requirements. Overcoming these challenges involved a steep learning curve, where we had to experiment with various configurations to understand how to effectively implement and manage the detailed access controls we needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5C2qsWuVCcSifjVL658ofw.png" /></figure><p><strong>Data Ingestion:</strong></p><p>We sought a platform that was straightforward to use and supported a wide variety of connectors, anticipating the future need to ingest data from across the organization. After conducting a POC comparing two platforms, Airbyte (an open-source solution) and Rivery (a SaaS solution), we opted for Airbyte for several compelling reasons.</p><p>Firstly, our decision leaned towards a cost-effective solution that wouldn’t charge based on data volume, as we preferred to ingest data freely without worrying about escalating costs. Additionally, Airbyte’s development tools particularly impressed us. The platform’s Connector Builder SDK, which includes both a Connector Builder UI and a low-code connector development environment, offered the simplicity and flexibility we needed. This feature allowed us to easily build and customize data connectors as per our specific requirements.</p><p>While Airbyte boasts a large and active community, we did face some challenges with the product. Initially, data ingestion speeds were slow, particularly noticeable when it took over two days to transfer 20GB from PostgreSQL. I first tried using the AWS-data-lake destination, but it was slow and did not support long-running syncs. To address this, I submitted a <a href="https://github.com/airbytehq/airbyte/pull/33853">pull request </a>to fix this issue, though it took three months to merge. In search of a better solution, I experimented with several other destinations. The S3 destination, while functional, had an annoying <a href="https://github.com/airbytehq/airbyte/issues/14028">issue</a> where timestamps were formatted as a struct when using Parquet. This specific issue has been open for two years without any resolution, highlighting a significant gap in support. The Iceberg destination, though promising, did not support the AWS Glue Catalog. I then tried the AWS-Glue destination, but found it inefficient as it only supported JSON output.</p><p>Ultimately, none of these options fully met our needs, leading us to develop our own custom AWS-data-lake destination. We forked the original code and customized it specifically for our requirements, creating a tailored solution that significantly improved our data ingestion process.</p><p>Despite these hurdles, Airbyte has met all our requirements effectively. Today, we have successfully integrated about 15 different data sources into our data lake using Airbyte, significantly enhancing our data ingestion capabilities and overall data strategy.</p><p><strong>Data Processing:</strong></p><p>Our data processing workflows are powerfully driven by dbt Core, using the ELT (Extract, Load, Transform) approach where all our data starts in the bronze layer and is progressively transformed to the silver and gold layers.</p><p>We are using the dbt Athena adapter, which supports both SQL and Python (PySpark) models. This versatility is crucial for handling more complex transformations effectively. The dbt-Athena adapter benefits from a vibrant community and continues to evolve with regular updates. Initially, we were somewhat hesitant to adopt the Python Athena integration due to its novelty and the limited track record at the time. However, after thorough testing and validation, we have successfully implemented it in our production environment without any issues, confirming its stability and efficiency.</p><p>In dbt, configuring table properties is straightforward and flexible, which greatly enhances our data management capabilities. For instance, we extensively use incremental tables, which are crucial for efficiently ingesting only the new or changed data. Leveraging the Iceberg table format, we adopt a merge incremental strategy, allowing us to seamlessly update our datasets without redundant processing. Furthermore, managing data partitions is also simplified in dbt; partitions can be declared directly within the table properties. Below is an example of table properties configuration for a table in our gold layer, showcasing how we specify the materialization strategy, partitioning, and data format:</p><pre>{{ config(<br>    materialized=&#39;incremental&#39;,<br>    incremental_strategy=&#39;merge&#39;,<br>    unique_key=[&#39;session_id&#39;],<br>    partitioned_by=[&#39;day&#39;],<br>    table_type=&#39;iceberg&#39;,<br>    format=&#39;parquet&#39;<br>) }}</pre><p>We are extremely satisfied with dbt; it has revolutionized how we manage our data transformations. The tool provides robust version control, reusability of code, and clear documentation of data flows, which greatly simplifies managing complex transformations and maintaining data integrity across our lakehouse architecture.</p><p>Building on our success with dbt, we’re currently exploring new tools to further enhance our data management capabilities. A standout addition has been <a href="https://montara.io/">Montara.io</a>, which integrates directly with our dbt Git repository and brings an array of powerful features to streamline our workflows. Montara offers automatic CI/CD, a user-friendly UI that simplifies writing and testing models — even for team members without deep dbt expertise — and provides valuable tools such as data lineage display, a data catalog, and observability.</p><p>We’ve been impressed with Montara; it significantly simplifies our dbt workflow, making data transformation more accessible and manageable across our team. Although the tool is relatively new and still evolving, meaning we occasionally encounter minor issues and gaps in functionality, our experience has been overwhelmingly positive. The Montara team provides exceptional support, working closely with us to quickly address any challenges and integrate our feedback into ongoing product enhancements. This collaborative approach not only helps us resolve issues swiftly but also ensures that Montara.io continues to evolve in a way that perfectly aligns with our data infrastructure needs.</p><p><strong>Analytics and BI Tools:</strong></p><p>Apache Superset is our analytics and business intelligence tool of choice, renowned for its open-source and powerful data visualization capabilities. We opted for Superset primarily because of its flexibility and cost-effectiveness compared to other BI tools. Its extensive customization options and user-friendly interface allow our teams to tailor dashboards and reports to their specific needs, making it particularly suited for our unique analytical environment where we primarily use Athena as our data source.</p><p>Our data analysts mainly use Superset to create dashboards for different departments within our company. Furthermore, we leverage Superset’s capabilities to embed charts directly into our applications, providing valuable insights to our customers.</p><p>Currently, some of our charts directly access data from the bronze layer, performing transformations in real time. However, we are in the process of modifying this approach to reduce the load on raw data queries and plan to eventually restrict access to the bronze layer using LF-tags.</p><p>While we find Superset to be a convenient and effective tool for dashboarding, it can become somewhat messy due to the proliferation of datasets created over time. Each dataset in Superset is configured individually, which can lead to redundancy and management challenges as the number and complexity of dashboards grow. Despite these challenges, Superset meets our requirements well, providing a versatile platform for visualizing and interacting with our data across the organization.</p><p><strong>Orchestration and Workflow Management</strong></p><p>Apache Airflow plays a crucial role in orchestrating and managing workflows within our data environment. As an open-source tool, Airflow offers flexibility, scalability, and robust community support, which are essential for our operational needs. We leverage Airflow to ensure all data pipelines into our data lake are triggered accurately, maintaining the freshness and reliability of our data.</p><p>Currently, we manage three main DAGs (Directed Acyclic Graphs) that are integral to our lakehouse operations. The first DAG is tasked with orchestrating data ingestion into the bronze layer, utilizing the AirbyteOperator to trigger all necessary syncs. A second DAG is responsible for executing our dbt transformations, ensuring our data is processed and moved to the silver and gold layers efficiently. The third DAG oversees the entire workflow, triggering the ingestion DAG and subsequently the dbt DAG in sequence to maintain a smooth flow of data processing.</p><p>Additionally, we have integrated Slack notifications within these workflows. This setup provides real-time alerts whenever a DAG fails, enabling immediate monitoring and response to maintain continuous operation and data integrity.</p><h4>Conclusion: Harnessing Data for Strategic Advantage</h4><p>In conclusion, our journey to build and refine a data lakehouse architecture has been both challenging and rewarding. We have successfully integrated a suite of tools and technologies that have transformed our data management capabilities, enabling us to unify diverse data into a robust analytical engine that supports dynamic decision-making. Our use of Apache Superset, AWS S3, AWS Glue Catalog, Apache Airflow, and dbt, demonstrates our commitment to employing cutting-edge technology to address complex data challenges.</p><p>These tools have not only improved our operational efficiency but have also paved the way for more insightful data analysis and reporting across the company. As we continue to evolve our data infrastructure, we remain committed to exploring new technologies and approaches that can further enhance our data capabilities.</p><p>I am open to feedback and questions from readers who are on a similar journey or considering such initiatives. Feel free to connect with me on <a href="http://www.linkedin.com/in/meni-shakarov-982464183">LinkedIn</a> for further discussion or to exchange ideas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a1d7a147149" width="1" height="1" alt=""><hr><p><a href="https://medium.com/eleos-health/navigating-the-data-deluge-a-journey-to-crafting-a-sophisticated-lakehouse-platform-7a1d7a147149">Navigating the Data Deluge: A Journey to Crafting a Sophisticated Lakehouse Platform</a> was originally published in <a href="https://medium.com/eleos-health">Eleos Health</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we reduced MySQL CPU usage by more than 70%]]></title>
            <link>https://medium.com/eleos-health/how-we-reduced-mysql-cpu-usage-by-more-than-70-percent-bb26d918f9d9?source=rss----7210f36f4253---4</link>
            <guid isPermaLink="false">https://medium.com/p/bb26d918f9d9</guid>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[troubleshooting]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Daniel Balosh]]></dc:creator>
            <pubDate>Mon, 20 May 2024 12:02:30 GMT</pubDate>
            <atom:updated>2024-05-20T12:25:50.574Z</atom:updated>
            <content:encoded><![CDATA[<h4>Identifying and fixing application code that causes high MySQL CPU usage.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Z3Xr7i-IzABgDF9d7BRCw.jpeg" /><figcaption>Developer Identifying and fixing application code</figcaption></figure><p>Have you ever stared at MySQL CPU usage numbers, feeling lost in a sea of data? We’ve been there too. Through systematic analysis and strategic interventions, we pinpointed and fixed the root causes of our high CPU usage. The outcome? A remarkable 70% reduction in CPU load, allowing us to optimize resources and cut costs by downsizing instances. This post will walk you through our troubleshooting journey, sharing the tools, techniques, and insights that led to our success.</p><h3>🔭 Problem and Strategy</h3><p>When troubleshooting high CPU usage on MySQL, it is easy to get lost and face multiple challenges when mapping DB queries to application code.</p><p>Here, I present the workflow for iteratively identifying the top problematic query while linking it with the relevant application code.</p><p>Generally, the root cause of 80% of the problems is one of the following:</p><ul><li>Too many rows scanned</li><li>A large amount of data is being sent over the wire</li><li>A large number of queries</li></ul><p>For more complex issues, it is better to consult a good DBA.</p><p>We need to find the application code that creates these queries and either change the code to prevent the issue or optimize the tables to solve the business need.</p><h3><strong>🗺️ SQL ↔︎ Application Code Map</strong></h3><p>First, we must create a map between the SQL logs and the backend code.<br>I’ve considered the following solutions:</p><h4><strong>Open Telemetry Framework:</strong></h4><p>It provides a nice UI over Grafana and the ability to query and aggregate the data “traces.”<br>OTEL integrates many languages and frameworks.<br>I’ve failed to make it work in production with proper stability, but if it works — it’s fantastic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewk21dB_c4FHMuAfhf5-NA.png" /><figcaption>image credit from the blog above getting started with otelsql</figcaption></figure><p><a href="https://opentelemetry.io/blog/2024/getting-started-with-otelsql/">Example: https://opentelemetry.io/blog/2024/getting-started-with-otelsql/</a></p><h4><strong>Injecting correlation ID into the SQL query</strong>:</h4><p>Many libs provide this possibility. <br>It provides a one-to-one mapping between results in general and slow query logs to application logs. After some thinking, we can find the caller application code. <br>However, I feared runtime risk and tried to avoid touching critical code paths.<br>So I didn’t choose it.<br>Before the query is:</p><pre>SELECT * FROM table;</pre><p>Now, when adding the trace UUID, it becomes:</p><pre>SELECT * FROM table; /* service=Alfa uuid=0e9c4fa8-ca8e-4ef7-b24b-d6cc16bc3ef3</pre><p>Example: <a href="https://django-correlation-id.readthedocs.io/en/latest/">https://django-correlation-id.readthedocs.io/en/latest/</a></p><h4>Custom database logger:</h4><p>The selected solution was to implement custom mysql logging middleware.<br>A “database wrapper” logs the mapping between the query and the stack trace.<br>The stack traces provide complete application flow visibility from the beginning of the code run until the SQL call. <br>See the <a href="#c9b2">Django implementation below</a>.<br>Other frameworks would have options similar to hook before SQL execution.<br>The result would look as follows:</p><pre>{<br>  .... &lt;fields by logger config&gt;<br>  &quot;sql&quot;: &quot;SELECT * FROM table WHERE id = %s LIMIT 21&quot;,<br>  &quot;stacktrace&quot;: &quot; &lt;Full stacktrace to call&gt;&quot;,<br>  &quot;sender&quot;: &quot;sqlstacktracer&quot;,<br>}</pre><h3>🛞 Iterative improvement workflow</h3><p>Now, we have a one-to-one mapping between parameterized SQL query and application code.<br>We can continue to iterative improvement workflow.</p><h4><strong>Identify the top problematic query</strong></h4><p>1. Take the top problematic query if <a href="#c302">performance insight</a> is on and the rating exceeds 0.1.<br>2. Otherwise, go to <a href="#8cfb">the slow query</a> log and identify the frequency and weight of the query. <br>For each query, <a href="#8cfb">the slow query</a> log shows:</p><pre># Query_time: 10.000  Lock_time: 0.001234 Rows_sent: 1234  Rows_examined: 12345678</pre><p>We can generate the frequency using cloudwatch insight by <em>pattern</em> function or any tool parsing the parameterized SQL to generate the same output.</p><pre>fields @timestamp, @message, @logStream, @log<br>| pattern @message</pre><p>The pattern function produces:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axdqUu4ZYtCy71sLYMDBjg.png" /><figcaption>Pattern result from the slow log</figcaption></figure><p>Now, with both query metadata and the count, pick the top impacting query.<br>3. Finally, there is <a href="#655e">the general log</a>.<br>Use the pattern function again to get context.<br>Here, only a little metadata exists. It is what it is.<br>The event count would be much higher, yet no high count indicates an issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bjbzCWyFk2E0FWXssZLFA.png" /></figure><h4>Specific query analysis</h4><p>Good, now we have the top problematic query to fix.<br>Answer the following questions:</p><ul><li>Using the SQL ↔︎ application code map:<br>- Which code creates it?<br>- Which business value does it serve?<br>- Who is the business owner?<br>- Is it still needed?<br>- Is up-to-date data required, or can it be calculated periodically?<br>- Can it move to a read replica?</li><li>Using MySQL, explain:<br>- How many rows are examined?<br>- Query time?<br>- Lock time?<br>- Rows returned?<br>- How many bytes of data are returned?</li></ul><h4>Fixing specific query</h4><p>The nice part comes with the data at hand, actually solving the issues.<br>We won’t go into actual solutions here.<br>Just give reference to further search:</p><ul><li>Too many rows examined? → add an index, denormalize, and remove joins</li><li>Long query time? → use cache or pre-calculate at scheduled intervals</li><li>Too much data? → select only needed columns</li><li>Too many similar calls? → it’s an n+1 problem. Move the query before looping in the application code</li></ul><p>By following the steps outlined above, you can resolve over 80% of common application problems</p><h3>💈Django implementation</h3><p>A flat directory is required at the application level.<br>1. Create the following files:</p><pre> -- django-project-folder<br>+  |---- sqlstacktrace <br>+           |---- base.py<br>+           |---- stacktrace.py<br>+           |---- __init__.py</pre><p>2. Create a database wrapper inside base.py</p><pre>class DatabaseWrapper(MysqlDatabaseWrapper):<br><br>    @async_unsafe<br>    def create_cursor(self, name=None):<br>        cursor = self.connection.cursor()<br>        return StacktraceCursorWrapper(cursor)</pre><p>3. Point the database driver to use the new DatabaseWrapper, and consider running it only with the feature flag.<br>Otherwise, significant logging costs might occur.</p><pre>DATABASES[&quot;default&quot;][&quot;ENGINE&quot;] = &quot;sqlstacktrace&quot;</pre><p>4. Implement the curser wrapper at base.py</p><pre>logger = logging.getLogger(__name__)<br><br>class StacktraceCursorWrapper(CursorWrapper):<br>    # no change to sql is done, only print to specific __name__ logger<br>    def execute(self, sql, params=()):<br>        try:<br>            self.log_sql_with_stacktrace(sql)<br>        except BaseException:<br>            pass  # don&#39;t fail no matter what<br><br>        return self.cursor.execute(sql, params)</pre><p>At every SQL call, the execute function is called.</p><p>5. Now add the actual logging function</p><pre>class StacktraceCursorWrapper(CursorWrapper):<br>    def log_sql_with_stacktrace(self, sql):<br>        try:<br>            stacks = get_stacktrace()<br>            stacktrace = []<br>            for stack in stacks:<br>                stacktrace.append(<br>                    u&quot;&quot;&quot;File &quot;{0}&quot;, line {1}, in {2}\n\t{3}&quot;&quot;&quot;.format(<br>                        *[smart_text(stack_data) for stack_data in stack]).replace(&quot;%&quot;, &quot;%%&quot;))<br>            stacktrace = &quot;\n&quot;.join(stacktrace)<br>            stacktrace = stacktrace.replace(&#39;/*&#39;, &#39;\/\*&#39;).replace(&#39;*/&#39;, &#39;\*\/&#39;)<br>        except:<br>            stacktrace = u&quot;WITHOUT STACKTRACE&quot;<br><br>        logger.info({&quot;sql&quot;: sql, &quot;stacktrace&quot;: stacktrace}, extra={&quot;sender&quot;: &quot;sqlstacktracer&quot;})</pre><p>6. There is a utility function to format the stack trace. The file is here: <a href="https://github.com/adw0rd/django-sql-stacktrace/blob/0cd797391d1e06b42c9e039a92232130361c30d9/sqlstacktrace/stacktrace.py">https://github.com/adw0rd/django-sql-stacktrace/blob/0cd797391d1e06b42c9e039a92232130361c30d9/sqlstacktrace/stacktrace.py</a><br>Please copy and paste it under stacktrace.py</p><p>7. The result log with json logger:</p><pre>{<br>  .... &lt;fields by logger config&gt;<br>  &quot;sql&quot;: &quot;SELECT * FROM table WHERE id = %s LIMIT 21&quot;,<br>  &quot;stacktrace&quot;: &quot; &lt;Full stacktrace to call&gt;&quot;,<br>  &quot;sender&quot;: &quot;sqlstacktracer&quot;,<br>}</pre><p>Aggregate and search operations can investigate a query’s performance when it contains a variable (not a specific ID), as exemplified above.</p><h3>⚒️ Tools Reference</h3><h4>The general log</h4><p>The general log shows every query-run without a lot of metadata.<br>Find the general by typing the database name into Cloudwatch insights or checking the database config.<br>Docs: <a href="https://dev.mysql.com/doc/refman/5.7/en/query-log.html">https://dev.mysql.com/doc/refman/5.7/en/query-log.html</a></p><h4>The slow query log</h4><p>Shows only queries larger than long_query_time<br>Docs: <a href="https://dev.mysql.com/doc/refman/5.7/en/slow-query-log.html">https://dev.mysql.com/doc/refman/5.7/en/slow-query-log.html</a></p><h4>MySQL performance schema</h4><p>The MySQL performance schema shows real-time performance-related data such as process lists, connected clients, and queries with locks.<br>Docs: <a href="https://dev.mysql.com/doc/refman/5.7/en/performance-schema.html">https://dev.mysql.com/doc/refman/5.7/en/performance-schema.html</a></p><h4>Performance insight</h4><p>AWS on RDS and other vendors provide visibility UX over the data MySQL generates.<br>Docs: <a href="https://aws.amazon.com/rds/performance-insights/">https://aws.amazon.com/rds/performance-insights/</a></p><p>Thanks, <a href="https://github.com/adw0rd/django-sql-stacktrace">https://github.com/adw0rd/django-sql-stacktrace</a> for reference, and most of the code</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb26d918f9d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/eleos-health/how-we-reduced-mysql-cpu-usage-by-more-than-70-percent-bb26d918f9d9">How we reduced MySQL CPU usage by more than 70%</a> was originally published in <a href="https://medium.com/eleos-health">Eleos Health</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From RAGs To (Psychotherapy) Riches]]></title>
            <link>https://medium.com/eleos-health/from-rags-to-psychotherapy-riches-789ae47fc9e4?source=rss----7210f36f4253---4</link>
            <guid isPermaLink="false">https://medium.com/p/789ae47fc9e4</guid>
            <category><![CDATA[psychotherapy]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[mental-health]]></category>
            <dc:creator><![CDATA[Amit Spinrad]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 07:15:54 GMT</pubDate>
            <atom:updated>2024-04-16T07:15:53.929Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring the Revolutionary Impact of <strong>R</strong>etrieval <strong>A</strong>ugmented <strong>G</strong>eneration on Therapeutic Practices</h4><p>Imagine walking into a new library you’ve never visited before. This library is special though: it stores <em>all</em> the knowledge, insights, and wisdom accumulated over countless psychotherapy sessions. Each book includes comprehensive data about every therapy session ever conducted—detailing its exploration of human emotions and its impact in the journey toward healing.</p><p>Now, imagine you have a question about a specific therapeutic intervention, therapy type, or topic. How would you even START to search for an answer?</p><p>Well, you <em>could</em> start by reading each book one by one, but that would take close to an eternity. But what if you had a magical tool that could instantly scan through all the books, pull out the information most relevant to your question, condense it all into a more digestible format, and use it to generate a coherent, insightful answer for <strong>you</strong>.</p><p>And… what if I told you this magical tool indeed exists, and it’s called Retrieval Augmented Generation (RAG)?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XbjTvOCoAN-jbwEkzUlmMw.png" /><figcaption>The massive psychotherapy library — a (cute) illustration</figcaption></figure><h3><strong>RAG: The Magical Context Tool</strong></h3><p>RAG is essentially a (somewhat) new way to retrieve relevant context and then use it to generate text quickly — like, <em>very</em> quickly. In simpler terms, it’s like having a lightning-fast librarian who can read all the books in the library in a split second, understand exactly what you are looking for, and serve up the best information in an easy-to-understand format.</p><p><strong>Turning Text into Numbers</strong></p><p>The first step in the RAG pipeline is converting vast amounts of textual data into smaller “pieces” of text, which then are converted into more manageable — but still meaningful — numeric forms known as vectors. This process of “chunking” and then “embedding” is crucial for storing these vectors in a database designed for quick information retrieval.</p><p>But why transform text into numbers in the first place? The answer lies in the efficiency of numerical operations. When we translate chunks of text into numeric equivalents, we can apply mathematical operations — such as addition, subtraction, multiplication, and division — that are impractical with raw text.</p><p><strong>Creating Meaning Through Math</strong></p><p>Importantly, because embeddings capture not only the actual characters of text, but also their inherent meanings - the outcomes of any mathematical operations performed with them are similarly rich in semantic content. For instance, the numeric representation of “H2O” combined with that of “liquid” closely approximates the representation of “water.” Adding the same “H2O” representation to “solid” yields the numeric equivalent of “ice.”</p><p>This almost-magical ability to encode meaning into operable numbers is exactly what enables the RAG pipeline to execute rapid, meaning-based similarity assessments — the “R,” or “Retrieval,” part of RAG — unlocking a wide array of possibilities for processing and understanding text at remarkable speeds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*gLnHxHsIDrySwrYNUBCLYA.png" /><figcaption>The embedding wizardry</figcaption></figure><p>Going back to the library example, you can think of a vector as a condensed version of a book in the gigantic psychotherapy library. It’s like a summary that captures the essence of the book — but in a much smaller, more usable format.</p><p><strong>Scanning for Contextual Similarities</strong></p><p>Once we convert psychotherapy sessions and their accompanying documentation (e.g., clinical notes and treatment plans) into rapidly searchable formats, we’re able to efficiently identify parallels among a large number of past cases. These parallels refer to cases that share the closest numeric representations, indicating a high degree of similarity in meaning. By implementing a parameter, known technically as “top K,” we can narrow our exploration to a specific number of the most similar previous sessions that offer valuable context. For example, if we used “2” for “top K,” then we would identify the two most similar previous sessions.</p><p><strong>Applying RAG to Therapy Treatment Plans</strong></p><p>Consider the scenario described in the figure below, where a therapist concludes their first session with a new client and sets “reducing substance abuse” as the main goal for their treatment plan going forward. To pinpoint more precise and actionable objectives assigned to this main goal, the therapist enters this rather broad goal into the “treatment plan” section of their documentation, along with the inquiry: “What actionable objectives should I set for this client?”</p><p>Leveraging RAG technology, the system can quickly identify two closely aligned treatment plans from two completely different cases based on their similar-intent primary goals: “minimize daily alcohol consumption” and “reduce reliance on prescription pain medication.”</p><p>The next step is where this process becomes especially innovative: using these similar-goal treatment plans, we can now easily extract the associated objectives and possibly even learn the extent of their success — information that serves as a detailed and highly informative context for a Large Language Model (LLM).</p><p>Presented with the therapist’s initial query and the context offered by these previous similar treatment plans, the LLM now draws on concrete examples rather than generating responses “from scratch.” This approach grounds the model’s suggestions in proven strategies, significantly enhancing the relevance and reliability of the objectives it proposes for the current client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*pkFjElIDITjMe48H-dk0eg.png" /><figcaption>A theoretical framework for using RAG to assist with the setting of psychotherapeutic treatment plans</figcaption></figure><h3><strong>Simple Magic (Or is it…?)</strong></h3><p>Once you grasp the transformative potential of RAG, it’s tempting to envision its application universally and instantly — to imagine a world where RAG empowers literally every aspect of the intersection of AI and psychotherapy (or any other field). However, the reality of implementing this innovative method is filled with complexities. Here are just a few of the challenges that come with adapting RAG for diverse psychotherapy use cases:</p><ol><li><strong>Unintentional Transfer of Session-Specific Information</strong></li></ol><p>The goal of RAG is not to replicate the style or content of previous sessions or notes verbatim — or worse, to insert <em>identifiable</em> information from previous sessions — but rather to draw “inspiration” from them in a way that enhances the relevance and uniqueness of the current session. For instance, going back to our earlier example, rather than directly borrowing the goal to “consult a pain management specialist” from a previous session, RAG should adapt that goal to fit the current substance abuse context by changing it to something like, “consult a specialist in addiction.”</p><p>Achieving this delicate balance requires sophisticated prompt engineering, along with strategies for generalization and de-identification of previous session notes. It also necessitates vigilant and thoughtful management of vector databases to ensure that each session remains distinct and tailored to the individual’s current needs and objectives.</p><p><strong>2. Overly Broad Queries</strong></p><p>When the query presented is overly broad, the resulting context can be too expansive. Imagine a therapist asking a bot to “<em>provide a comprehensive overview of all therapeutic approaches for treating depression.</em>”</p><p>One approach to navigating this challenge is to employ a hierarchical approach to RAG (sometimes known as HRAG), which allows the system to methodically and progressively drill down into more and more specific topics. This process effectively narrows the breadth of sessions (i.e., the context) under consideration. Eventually, this refined retrieval and selection of documents becomes sufficiently compact to be directly integrated into the LLM without the need for further filtration, ensuring that the responses are not only relevant, but also deeply informed by a focused subset of the available data.</p><p>3. <strong>Highly Similar Contexts</strong></p><p>In instances where the available session notes or other contexts are almost identical, it’s crucial to “inject” a diversity of perspectives into the LLM to create a broader range of inspiration and insights. In such cases, instead of relying on a typical RAG process that might select a small number of very similar documents — like two or three, for example — we could expand the selection to a larger set (or a larger “top K” value). For example, perhaps we use “20” instead of “2.”</p><p>Then, before we employ the “G” part of the RAG process (i.e., “Generation”), we can distill this set of 20 previous sessions down into a smaller subset of sessions — maybe two or three — that are the most <em>distinct</em> and different from each other.</p><p>This strategy ensures that the LLM receives a variety of inputs, enriching the creative and therapeutic potential of the responses it generates. By prioritizing diversity in the selection process, we can avoid the “echo chamber effect” and, in a sense, “force” a richer, more nuanced interaction with the LLM.</p><h3>The Necessity of the Human Touch</h3><p>While RAG and other innovative AI technologies can enhance the practice of psychotherapy, it’s important to remember that they are just tools. They are not meant to replace the human touch, empathic understanding, and therapeutic relationship that are at the heart of psychotherapy. Instead, they are meant to augment and enhance the therapist’s abilities — to provide them with the information they need when they need it, ultimately helping them be more effective in <em>their</em> work.</p><p>In the end, psychotherapy is about helping people — about understanding their struggles and guiding them toward healing. And while cutting-edge tools like RAG can indeed help providers do this more effectively, the real magic lies in the human heart and mind. And no amount of AI can replace that.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=789ae47fc9e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/eleos-health/from-rags-to-psychotherapy-riches-789ae47fc9e4">From RAGs To (Psychotherapy) Riches</a> was originally published in <a href="https://medium.com/eleos-health">Eleos Health</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In Metrics We Trust]]></title>
            <link>https://medium.com/eleos-health/in-metrics-we-trust-5f00052e2279?source=rss----7210f36f4253---4</link>
            <guid isPermaLink="false">https://medium.com/p/5f00052e2279</guid>
            <category><![CDATA[behavioral-health]]></category>
            <category><![CDATA[psychotherapy]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[text-analytics]]></category>
            <category><![CDATA[metrics-and-analytics]]></category>
            <dc:creator><![CDATA[Amit Spinrad]]></dc:creator>
            <pubDate>Mon, 31 Jul 2023 13:15:20 GMT</pubDate>
            <atom:updated>2023-07-31T18:45:20.187Z</atom:updated>
            <content:encoded><![CDATA[<h4>AI | Behavioral Health | Text Analytics</h4><h4><strong>The Art of Rating Therapy Notes</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/0*_0i14BMIomIpTYcQ" /><figcaption>A typical farmers’ market’s therapy session</figcaption></figure><p>Navigating the landscape of behavioral health can feel like exploring a large and busy farmers’ market. Even if we focus only on one aspect of this vast realm, documentation and reporting in psychotherapy notes — the diversity is striking. Each note we encounter is a unique stall, presenting its own product; and just like at the market where preferences vary, and where there’s no one stall which is “less” or “more important” than another, in therapy — every note holds its own unique clinical significance.</p><p>Here, however, is where the challenge begins, especially for those of us who are seeking to simplify this process and enhance its efficacy: What makes a ‘good’ therapy note? What are we aiming to optimize? Where do we even begin?</p><p>If we recall our market analogy, while an apple isn’t inherently “better” than a pear, and a carrot can’t be deemed “worse” than a beet, we still have objective measures that guide us as we assess the quality of the products we see before we decide to take them home with us. Is the produce fresh? Is it free of blemishes? Has it ripened to the point it tastes the best?</p><p>Similarly, in the realm of behavioral health, we have multiple ways to assess a therapy note. Some metrics are relatively “straightforward” to extract: Is the grammar of the note appropriate? Is the language used simple or complex? Is the content varied or redundant? However, some parameters are more nuanced and specific: Is the note written in clinical language? Is it coherent? Does it provide an accurate description of what happened in the therapy session?</p><p>Two facts are clear: First, these two types of metrics, the simpler and the more complex, can help us holistically assess the quality of a therapy note, thus guiding us in pinpointing exactly what needs to be improved. Second, they require the use of different tools, each with its unique strengths.</p><p>So, fasten your seatbelts and prepare for a fascinating journey into the intersection of language metrics, computation and behavioral health.</p><h4><strong>Simpler Measures Call for Simpler Tools: The Automatic Metrics</strong></h4><p>As we’ve noted above, some measures of therapy notes are easier to extract than others, primarily because they’re not intrinsically tied to the niche and specific world of psychotherapy.</p><p>Luckily, and specifically <em>because</em> of their more general use, we have various established and popular automatic tools for their extraction, offering quick, quantifiable insights into note quality. Let’s dive into some key ones.</p><p><strong><em>Readability</em></strong></p><p>Consider these three sentences:</p><ol><li>The client felt better and understood their thoughts and emotions more.</li><li>The client showed notable improvement in managing their emotions, displaying a greater understanding of their thoughts and gaining valuable insights into their self-awareness.</li><li>The client exhibited an evident amelioration in their affective regulation, manifesting a heightened introspective acuity and displaying a proclivity towards metacognitive insights.</li></ol><p>While these three sentences essentially convey the same message, they each have a distinct readability score; a measure that helps us quantify how accessible a note is to its readers. Indices like the Flesch-Kincaid grade level, Automated Readability Index (ARI), or Gunning fog index calculate the years of formal education needed to comprehend a text. These scores can be computed instantly and automatically using Python libraries such as textstat or py-readability-metrics, thereby enabling us to determine the “level” of the text. For instance, looking at the sentences above: while the first sentence mentioned above scores 8.04 on the Gunning fog index, the second scores 16.16, and the third a whopping 26.98.</p><p>The question now is: which readability score should we aim for? We’ll circle back to this in a bit.</p><p><strong><em>Lexical Richness</em></strong></p><p>Imagine traveling through a landscape and seeing the same sights over and over again. A bit monotonous and boring, right? In the same way, lexical richness measures such as Measure of Textual Lexical Diversity (MTLD), Type-Token Ratio (TTR), and Moving-Average Type-Token Ratio (MATTR) are used to analyze the variety of words in a text. These measures each offer a different lens on the diversity of the ‘linguistic landscape’ of a text: a high variety score suggests rich vocabulary usage, while a low score might imply some redundancy. Tools like nltk or lexicalrichness in Python can help analyze this directly and automatically.</p><p><strong><em>Grammar</em></strong></p><p>Maybe the most self-evident automatic metric is grammar, which provides the structural framework of a text. Libraries like gingerit or language_tool_python can be employed to assess the grammatical correctness of a note, detecting errors and hence — using errors’ count as a measure of the text’s grammatical quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*wC4X15LrGGG32437" /><figcaption>Illustration of Gen-Alpha’s future grammar corrector</figcaption></figure><p>The three automatic metrics listed here are not exhaustive. Still, they offer us a holistic picture, an immediate sense of the linguistic quality of the text — and the best pro: they can be employed easily and super quickly.</p><p>The main con? These “general” metrics, almost by definition, may sometimes fall short in capturing the complexity which is unique to behavioral health. This is where our non-automatic metrics step in, magnifying the finer details of our therapy notes.</p><h4><strong>Non-Automatic Metrics: The Clinical Magnifying Glass</strong></h4><p>In-depth, context-specific characteristics of a psychotherapy note often require the insight of a human specialist. During our work in assessing and automatically generating notes, we’ve pinpointed five essential metrics for behavioral health text:</p><p><strong><em>Depth of Clinical Focus</em></strong></p><p>Imagine a therapy note that touches on a client’s struggles with anxiety. A basic summary might say, “The client discussed their concerns.” This is arguably too indistinct and doesn’t paint a clear image of the therapeutic issues addressed. Conversely, an overly detailed summary might outline every anxiety-triggering event the client has faced and discussed during the session, which is also not beneficial. We’d probably prefer something appropriate in between.</p><p>Important to mention — quantifying this metric on a simple scale like 1 to 10 is also challenging, like the rest of the intricate metrics we’ll explore. More likely, we’ll use basic categories for evaluation (i.e., is the clinical focus depth “sufficient”? “average”? “poor”?).</p><p><strong><em>Relevance of Summary</em></strong></p><p>Consider a note from a therapy session which focuses on the therapist’s interventions — which are the strategies and techniques used by the therapist to address the client’s concerns. A summary in that section that suddenly highlights the client’s family history or their appearance deviates from this section’s main focus — the intervention which was employed. Such a summary may be well-phrased and clinically relevant, but in terms of relevancy, we’d probably regard it as poor. That’s our goal with this measurement.</p><p>A fitting summary for the interventions section should describe the discussed therapeutic strategies and their immediate effects, for example — a note that details the mindfulness techniques introduced by the therapist.</p><p><strong><em>Contextual Appropriateness</em></strong></p><p>In therapy notes, it’s crucial to avoid including any out-of-context details. For instance, mentioning the name of a client’s significant other without any prior reference can lead to confusion for the reader (“wait, who is Michael whom the client is anxious about, anyway?”). According to this metric, a well-drafted therapy note summary should ensure that all information aligns with the broader context of the therapy session and its summary.</p><p><strong><em>Summary Coherence</em></strong></p><p>Picture a therapy note with a section that reads:</p><p>“During the session, the client’s recently deceased cat was a major discussion point. The client shared their satisfaction with a new exercise routine. The therapist suggested deep breathing techniques for anxiety management.”</p><p>As you can tell, each part of this summary is grammatically sound and relevant to both the client’s clinical status and therapy. However, it combines three separate treatment aspects, resulting in a disjointed, and quite frankly — weirdly phrased, narrative.</p><p>A coherent summary scoring high on this metric will offer a logically flowing standalone narrative of the therapy session. It could read, for example, “The client shared that they are overwhelmed with work-induced anxiety, and therefore was introduced to mindfulness techniques by the therapist, offering some immediate relief.” and only THEN it would naturally transition to discussing the client’s exercise routine.</p><p><strong><em>Fact-Verification</em></strong></p><p>Although challenging to extract, this is possibly the easiest “complex metric” to explain: the fact-verification metric requires the summary to genuinely represent what was discussed during the therapy session without creating non-existent details.</p><p>For those of you who are familiar with large language models (LLMs), such as ChatGPT, you unfortunately know the annoying reality: these models have a tendency to “hallucinate”, i.e. — generate unrelated / unfactual information. A well-written therapy note should not incorrectly report what actually happened during the session. For instance, it shouldn’t state the client felt relieved when they communicated feeling overwhelmed; accurate session detail representation is crucial to prevent erroneous understandings and clinical decisions, making this metric’s scoring of high significance.</p><h4><strong>Striking the Right Note: The Fine Balance in Therapy Notes</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/0*t1ypeMDYbhknngUE" /><figcaption>“The client felt better, whatever idgaf” note scores</figcaption></figure><p>Assessing the quality of therapy notes is a balance between the overview of automatic metrics and the precision of non-automatic ones. While automatic metrics provide a foundation, they can sometimes miss the nuances a human expert would catch.</p><p>Naturally, there are still ongoing questions in regards to our quest for rating therapy notes:</p><ol><li><em>Is the measurement of complex metrics, like summary relevancy, consistent?</em></li></ol><p>It isn’t, as it depends on the context, the user, the therapy type, and the format of the therapy note. This is one of the main issues to tackle with the complex metrics, and that’s why they’re defined as non-automatic and, well… complex.</p><p><em>2. In continuation to the last question, can these non-automatic &amp; complex metrics become automated over time, if we train an appropriate model?</em></p><p>Possibly, but it would be tough to fine-tune a model to comprehend such nuanced contexts and requirements easily and reliably.</p><p><em>3. Lastly, is there a specific score that we should strive for scale-metrics like readability?</em></p><p>The answer is also probably no; while for some metrics it’s easy to understand what we need to optimize “towards” (for example, we would like all notes to be with a “good” clinical focus depth, rather than “poor”), in scaled and varied metrics such as readability — it largely depends on the context, the users involved, and their specific needs for a specific “level” of language.</p><p>As you can tell, numerous issues and questions remain. Even disregarding these unresolved matters, and using the rating and metrics methods discussed in this post and only them, the right balance of them alone for each case are highly difficult to define. However, they’re crucial for anyone who wishes to deliver accurate note summaries and to streamline these processes, as they provide a comprehensive understanding of notes’ quality and highlight areas for improvement.</p><p>And remember (get ready for some cliches) — much like therapy itself, refining these metrics is not a sprint but a marathon — with no shortage of detours, surprise insights, and an occasional need for deep breaths (<em>readability: 0.8</em>), significant inhales (<em>readability: 20.8</em>) and even some voluminous pulmonary ventilations (<em>readability: infinity</em>).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f00052e2279" width="1" height="1" alt=""><hr><p><a href="https://medium.com/eleos-health/in-metrics-we-trust-5f00052e2279">In Metrics We Trust</a> was originally published in <a href="https://medium.com/eleos-health">Eleos Health</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Smaller The Better?]]></title>
            <link>https://medium.com/eleos-health/the-smaller-the-better-a6697aebfa21?source=rss----7210f36f4253---4</link>
            <guid isPermaLink="false">https://medium.com/p/a6697aebfa21</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[efficiency]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Amit Spinrad]]></dc:creator>
            <pubDate>Sun, 30 Apr 2023 09:11:17 GMT</pubDate>
            <atom:updated>2023-04-30T09:24:57.068Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>The surprising potential advantages of smaller models in niche-specific NLP tasks</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*iPeGtxG3yG-7o87evNHdPw.png" /><figcaption>“Oh, the drama!”</figcaption></figure><p>If you’ve lived long enough, you’ve probably learned already that too often having more of something or owning bigger things — is not necessarily better. This applies to the food you put in your mouth, your workload, and even more generally — the literal stuff you own, as our home organizer and savior Marie Kondo taught us religiously — only keep things that “spark joy”. Similarly, history and mythology echo this sentiment, with numerous examples where smaller or seemingly weaker contenders outperform their larger and more powerful opponents under specific circumstances, such as the famous biblical story of David and Goliath.</p><p>Surprisingly enough, this principle is also important and relevant to the realm of Machine Learning/Deep Learning, and more specifically, to the field of natural language processing (NLP) tasks.</p><p>Although large text-generative models (and even more generally — all the “generative AI” models) have recently captured the eyes and ears of the global community for their impressive performance on a wide range of general tasks, these models may not always be the optimal choice for highly specific (or “niche”) tasks. In fact, much (much) smaller NLP models that are specifically designed for these tasks can be equivalent or even outperform larger models under certain conditions, particularly when they are paired with high-quality and dedicated datasets.</p><p>In this post, I will explore with you some of the reasons behind this phenomenon, and shed some light on other important aspects of why <strong><em>smaller models can be a big deal when it comes to getting the job done</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHrc-2mnjqf-HW_vW8TeSA.png" /></figure><p><strong>Faster, cheaper, greener</strong></p><p>Some advantages of smaller language models are quite obvious and “technically dry”, but still highly important: the speed of their training, the cost of training (and inference) and their lower energy consumption (and thus lower carbon imprint).</p><p>But how much of a difference can it be?</p><p>Well, before we deep dive into this — we need to talk about the elephant in the room, or more specifically — the term that is mentioned in each and every blog post that excitingly announces the release of a new and promising generative language model, and one that many people don’t really understand fully: parameters.</p><p>Parameters in a language model are the learnable weights and biases that the model uses to make predictions, and the ones that get adjusted during training to improve the model’s predictions. These parameters are crucial since they determine the model’s capacity to learn complex linguistic patterns and relationships in the data. Having said that, more parameters also mean significant increased computational requirements, memory usage, and energy consumption during training and inference.</p><p>Let’s compare some numbers so we can understand what we’re really talking about, with two distinct but rather famous language models: <a href="https://arxiv.org/abs/1810.04805">BERT</a>, a famous 2018 Google’s model, which is considered to this day one of the most powerful smaller language models, and <a href="https://openai.com/blog/gpt-3-apps">GPT-3</a>, one of OpenAI’s most famous language models that showed remarkable abilities in many linguistic tasks, certainly for the time it was released.</p><p>Well, GPT-3 was trained on no less than 175 billion parameters, while BERT (base) was trained on 110 million parameters. To understand this difference even better — let’s say we would use a single strong training machine such as the NVIDIA V100 GPU to pre-train these models: while it would approximately take BERT-base ~9 days for the whole training process to complete, it would take for GPT-3 on the same machine… hold tight — roughly <strong>355 GPU-years</strong>.</p><p>I will let you go wild with guessing the number of actual machines needed to use in order to train the latter in a reasonable time (and the energy such machines will consume), but for simplicity of the cost comparisons’ sake — let’s stay in our imaginary 355 years vs. 9 days world: if we take <a href="https://azure.microsoft.com/en-us/pricing/details/virtual-machines/windows/">Azure’s “Windows Virtual Machines Pricing”</a> page as an example — 9 days of using such a machine for BERT training will cost you <strong>~600–700$</strong>, while for a GPT-3, or a model of roughly same size, it would cost you, well… <strong>140,651$!</strong> (but with a saving plan, guys! Let’s go for it, you only live 355 GPU-years once).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h1dRB-VcN1QyTJf3_vB6mw.png" /><figcaption>A cute illustration of me waiting patiently for my breakthrough 974-trizillion parameters model, GignaticliciousGPT, to train</figcaption></figure><p><strong>Home safe home: the security perks of local storage for small NLP models</strong></p><p>One often overlooked advantage of smaller NLP models is the increased security and privacy they offer due to their ability to be stored locally.</p><p>In contrast, larger models may regularly require storage on remote servers, or even more problematically — on remote servers which are 100% owned by another company (as is the case with OpenAI’s large models), due to their size. Smaller models, on the other hand, can oftentimes be stored directly on your own device, or on a more secure and more privately-owned remote server. This local storage approach has a few key benefits: it reduces the risk of unauthorized access to your sensitive data, as the data never leaves your device or your privately-owned server; and in the case of fully local storage — it also reduces the reliance on potentially unstable internet connections, ensuring that the performance of the model remains consistent even in the face of connectivity issues.</p><p><strong>“Jack of all trades, master of none” — the downside of generalization</strong></p><p>Higher generalization capabilities in the context of NLP refer to language models that can perform a wide range of language tasks with rather high accuracy. These models can assist us with translation, sentiment analysis, and sometimes, as we’ve seen lately, with really impressive generative capabilities. Usually, these models are pre-trained on vast amounts of text data, which allows them to capture a broad range of linguistic patterns and relationships and apply their acquired “general knowledge” on any required task you throw on them.</p><p>These generalization capabilities, though, do come with major costs. One of them is the risk of becoming a “jack of all trades, but master of none”: since these models try to learn everything, they can sometimes struggle to excel in very niche tasks, as there is simply too much information for the model to process effectively.</p><p>Even more interestingly, if such ridiculously-large models attempt to fine-tune on a very specific niche task, their crazily high number of parameters could quite possibly result in overfitting — the scenario in which a model becomes too specialized in the training data and fails to generalize well to new, unseen data, impairing both their “general knowledge” power — but also more so in these specific niche tasks that they just learned.</p><p>To bring all these complex concepts to life, let’s explore a peculiar, yet informative example.</p><p>Imagine, for some reason, you need a model to excel in the highly specific (and rather weird, if I’m honest) task of <strong>understanding and explaining queer lingo in Hebrew</strong>. This task is extremely niche, considering:</p><ol><li>Hebrew is not a widely spoken language, with roughly only ~10 million speakers worldwide (a bit more than 0.1% of the world population).</li><li>LGBTQ-identifying individuals represent a small minority, around ~5%-10% of the population, at least in the United States (but probably similarly in Israel, where people speak Hebrew).</li><li>Not all LGBTQ individuals are familiar with or proficient in queer lingo.</li></ol><p>Combine all these statistical factors together, and you get an incredibly niche task for a language model, but that’s EXACTLY what I asked ChatGPT to do, because… well, why not?</p><p>When I asked it about the word “ohch” (אוחצ׳), which can be simply defined as either a an effeminate gay man or a colloquial term similar to “sis” in queer English (as in “sis, what’s the tea?”), it told me that… well, ohch is actually military slang(!) derived from the Hebrew word “ucaf” (אוכף, meaning saddle, yes — the one that it fastened to horses). It then continued to “explain” that “ohch” expresses the feeling of being tired or humiliated, and is used to describe soldiers who are weary or lacking energy.</p><p>To put it bluntly, ChatGPT failed. Miserably.</p><p>This is not surprising, as explained before — the power of ChatGPT lies in its “general” power rather in excelling in very specific (and sometimes bizarre) tasks. However, we can only speculate that even a very small language model, such as <a href="https://github.com/google-research/text-to-text-transfer-transformer">T5-small</a> (a 60 million parameter model), fine-tuned on the ultra-dedicated “<a href="https://www.e-mago.co.il/node/11262">Even-Shoshana</a>” online detailed dictionary of Hebrew queer lingo, could potentially perform better. Much, much better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wITFkqjm4OUkHxMy1lT7KQ.png" /><figcaption>An authentic illustration of the origins of an Israeli ohch (אוחץ׳), according to ChatGPT</figcaption></figure><p><strong>Quick to adjust: the versatility of smaller models</strong></p><p>Smaller models have another advantage that is often quite underestimated: high adaptability.</p><p>Because of their simpler architecture and lower parameter count, these models can be more easily adapted to new or changing tasks within a specific niche. Their light weight, simplicity and higher “fine-tuning readiness” so-to-speak, allow for quicker and more convenient fine-tuning and optimization, making them a more versatile choice for businesses or researchers that need to pivot quickly in response to new challenges or opportunities.</p><p><strong>Smaller but just as efficient: the best of both worlds</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*a4ba-MRYHf2MBwJNgBp-TA.png" /><figcaption>Yup, I went there.</figcaption></figure><p>A recently published 2023 <a href="https://arxiv.org/pdf/2302.06476.pdf">paper</a> [1] demonstrated that several language models, when fine-tuned with task-specific data for applications such as summarization and sentiment analysis, often produced better or highly similar results compared to non-fine-tuned (“zero-shot”) ChatGPT and GPT-3.5. In another <a href="https://arxiv.org/abs/1909.11942">paper</a> from 2020 [2], it was shown that ALBERT-base (an “only” 12 million parameters model), a much lighter version of BERT-base (a 110 million parameters model, i.e. — roughly x10 in size), achieved almost identical performance as BERT-base on a question-answering task, obtaining an 80.0 F1 score compared to BERT-base’s 80.4 score.</p><p>In essence, we can draw two key conclusions from these findings:</p><ol><li>Even highly impressive language models like ChatGPT, which outperform many other models on specific tasks, can be surpassed when these other (and sometimes smaller) models are specifically fine-tuned for the same tasks, using dedicated datasets.</li><li>Smaller models can achieve similar or possibly better results compared to their larger counterparts, even when both are fine-tuned on the same data or task, if the architecture fits the task at hand and the preparation of data is done correctly.</li></ol><p>Taken together, these conclusions emphasize the potential of smaller models fine-tuned on specific tasks to maintain or even surpass the performance of their larger (sometimes much larger) counterparts, all while preserving the advantages that we discussed throughout this post.</p><p><strong>In conclusion …</strong></p><p>While we can’t deny the “cool factor” of the latest colossal language models making headlines, like OpenAI’s <a href="https://openai.com/product/gpt-4">GPT-4</a> and Google’s <a href="https://bard.google.com/">BARD</a>, it’s crucial not to undervalue the potential of (truly excellent) smaller models in our everyday, slightly less glamorous lives. These fun-sized powerhouses offer major benefits, such as increased security and data privacy, adaptability, and in some cases, equal or even superior performance on niche tasks.</p><p>By using the power of smaller models and fine-tuning them for the specific tasks you may need these linguistic virtuosos to handle, you can locally &amp; quickly create efficient and effective NLP solutions tailored to your personal and professional needs — without desperately relying on either remote solutions and/or gazillion parameters models.</p><p>[1] Qin C., Zhang A., Zhang Z., Chen J., Yasunaga M., &amp; Yang D., <strong>Is ChatGPT a General-purpose Natural Language Processing Task Solver?</strong>, <em>arXiv preprint arXiv</em>:2302.06476, 2023. <a href="https://arxiv.org/abs/2302.06476">https://arxiv.org/abs/2302.06476</a></p><p>[2] Zhenzhong L., Mingda C., Goodman S., Gimpel K., Sharma P., &amp; Soricut R., <strong>ALBERT: A Lite BERT for Self-supervised Learning of Language Representations</strong>, <em>ICLR</em>, 2020. <a href="https://arxiv.org/abs/1909.11942">https://arxiv.org/abs/1909.11942</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6697aebfa21" width="1" height="1" alt=""><hr><p><a href="https://medium.com/eleos-health/the-smaller-the-better-a6697aebfa21">The Smaller The Better?</a> was originally published in <a href="https://medium.com/eleos-health">Eleos Health</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Driven Development on Chrome Extension]]></title>
            <link>https://medium.com/eleos-health/event-driven-development-on-chrome-extension-9fea92ca683?source=rss----7210f36f4253---4</link>
            <guid isPermaLink="false">https://medium.com/p/9fea92ca683</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[chrome-extension]]></category>
            <dc:creator><![CDATA[Idan Biton]]></dc:creator>
            <pubDate>Sun, 16 Apr 2023 08:29:33 GMT</pubDate>
            <atom:updated>2023-04-16T12:42:35.850Z</atom:updated>
            <content:encoded><![CDATA[<h3>Event Driven Development on Browser Extension</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-r1blj0VZ8t-TSZE0PWMkQ.png" /></figure><p>Imagine this scenario: You are developing a Chrome extension whose main functionality is to listen to changes on the page triggered by the user. For every change, you have a specific action you want to trigger, such as rendering a UI component or triggering an API call.</p><p><strong>How do you best tackle this need?</strong></p><p>Initially, the naive solution would be to create classes and static functions within them that can be used anywhere in your code. Inside these functions, you can trigger or return whatever you need. Although this is an option, it can be cumbersome, especially when you have cross-class actions and data that you need to share. It can be challenging to maintain and debug in such cases.</p><p>A better, more flexible, and organized solution would be to create an event handling mechanism that supports triggering events based on the user’s behavior.</p><p>Chrome comes with <a href="https://developer.chrome.com/docs/extensions/reference/events/">built-in</a> event handlers for common events such as clicking on a button or navigating to a new URL. If you are developing a react application you can even use <a href="https://redux.js.org/">Redux</a> for that. However, sometimes you need to trigger events in more complex scenarios, such as relaying on 3rd party website and waiting for a UI element to be rendered on the site, or when the user logs in or out of the system.</p><p>Here at <a href="https://eleos.health/">Eleos</a>, this was precisely the problem we faced, so we had to come up with an in-house solution for it.</p><p>Please keep in mind that this article covers a specific solution to the above issue. There are many approaches to achieving what we want, and each has its pros and cons.</p><p><strong>Register / Emitter Solution<br></strong>Firstly, if you are not familiar with event-driven development, I highly recommend that you read about it before diving into the solution I suggest here. Having a solid understanding of what we are trying to achieve here is essential. The approach I would like to cover involves two components:</p><ol><li>An Event Emitter class to handle the subscription and emission of events.</li><li>A component or class that is registered for one or more events, and every time this event is fired, an action will be triggered.</li></ol><p><strong>So, let’s dive deeper to how all of this is going to work together.</strong><br>The best way to visualize this is with the following drawing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6tT7JWK-Ni0vJtGmTN3T8g.png" /></figure><p>The components need to subscribe (register) for a specific event, and the Event Emitter is responsible for handling these subscriptions and sending (emitting) the events. But wait, what does it mean to emit an event? At the end of the process, there is an action that we want to trigger in response to an event. Now let’s peel back another layer and think about what parameters we need to subscribe to a specific event:</p><ul><li>The event name we want to subscribe to.</li><li>A component id, so we will know which component is registered to a specific event.</li><li>Callback — a function that will be triggered when the event is fired.</li></ul><p>Meaning, on every event we want to be registered on, the above three properties need to be provided.</p><p><strong>Do you have any idea on how can we store the events? </strong><br>We can create an object on the window.top object, where every key will be the name of the event. This way, we can easily track which components are registered for which events, and the value will be an array consisting of objects, as described above.</p><ul><li>Note: We can also put inside our object some other properties for debugging purposes (like URI, page context, etc…)</li></ul><p>Now, let’s dive into some code examples. Let’s say we have a component (it can be a plain JS object, a React component, a JS or TS file), and we want to trigger a particular action when a login event is emitted.</p><pre>import { eventEmitter } from &#39;./eventEmitter&#39;;<br>export default class Example {<br>  constructor() {<br>    ...<br>    this.registerEventListeners();<br>    ...<br>  }<br>  registerEventListeners() {<br>    eventEmitter.subscribe(&#39;login&#39;, &#39;class-id&#39;, () =&gt; {<br>      // do something here<br>    });<br>  }<br>}</pre><p>So, in the example above, we can see that it’s pretty straightforward. We import the eventEmitter object so we can use the subscribe method, subscribe to the &#39;login&#39; event under a specific ID, and bind a callback to execute when the event is emitted.</p><p>But wait, there&#39;s more to it. When are we going to emit the event? Remember, we can emit the event from anywhere in the application, and all the subscribers will get notified. All we need to do is:</p><pre>...<br>eventEmitter.emit(&#39;login&#39;);<br>...</pre><p>All we need to do is to emit the event, with the specific name we subscribed on.</p><p>Great! So now we know how to subscribe and emit events, but what will the event emitter look like? <br>Let’s have a look: Remember how we are going to handle our events object?</p><pre>export default class EventEmitter {<br>  ...<br>  subscribe(name, id, cb) {<br>    if (!window.top.events[name]) {<br>      // in case we still dont have the event key on our object<br>      window.top.events[name] = []; <br>    }<br>    // add new subscription <br>    window.top.events[name].push({id,func: cb});<br>  }<br>  ...<br>}<br></pre><p>Still, pretty straight forward: <br>we are getting the id, name, and callback, checking if there is any value on the events object under the event name, creating an array if it doesn’t exist, and just pushing the object.<br>Now, the last thing we have to cover here is how we are going to implement the event emit function:</p><pre>emit(name, ...args) {<br>  if (!window.top.events[name]) return; // prevents null cases<br>  // loop through all the subscriptions on a the event name<br>  window.top.events[name].forEach((s) =&gt; {<br>    console.log(`Emitting event for event id: ${id}`);<br>    try {<br>      // execute the callback<br>      s.func.call(...args);<br>    } catch (e) {<br>      console.log(`Event failed to emit func ${e}`);<br>    }<br>  });<br>},</pre><p><strong>Note:</strong> we are passing an optional argument, <em>args, </em>in case we need to pass additional args to be called.</p><p>To summarize, we have covered a basic solution for event-driven development in Chrome extensions. We have a class that is responsible for registering and emitting events, and we have other components that can be registered to a specific event. When the event is emitted, the emit function is called and responsible for executing the callback attached to the event.</p><p>Please note that this solution is basic and may not handle some issues that can arise, such as overflowing events. We can handle these issue by creating an event buffer that controls how many events are sent within a specific timeframe. We also need to add conditions to handle null cases or when an event name is empty. Therefore, this solution is a skeleton of how we can implement this and can be improved to better fit our needs.</p><p>I really hope you find this solution helpful. If you have any questions or comments, please feel free to leave them below!</p><p>Until next time :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fea92ca683" width="1" height="1" alt=""><hr><p><a href="https://medium.com/eleos-health/event-driven-development-on-chrome-extension-9fea92ca683">Event Driven Development on Chrome Extension</a> was originally published in <a href="https://medium.com/eleos-health">Eleos Health</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How does Generative AI see Mental Health?]]></title>
            <link>https://medium.com/eleos-health/how-does-generative-ai-see-mental-health-998b35c7e3fc?source=rss----7210f36f4253---4</link>
            <guid isPermaLink="false">https://medium.com/p/998b35c7e3fc</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mental-health]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Samuel Jefroykin]]></dc:creator>
            <pubDate>Tue, 07 Feb 2023 15:02:58 GMT</pubDate>
            <atom:updated>2023-02-07T15:02:58.754Z</atom:updated>
            <content:encoded><![CDATA[<h4>Art | AI | Mental Health</h4><h4>Our Midjourney around mental health.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ePtr_AwQYlPP4uxynttz1A.png" /><figcaption>The prompt here was “Mental Health”, created by MidJourney</figcaption></figure><p>I am an Artist! 👨🏼‍🎨</p><p>Not really … Not yet …</p><p>Anyway, check out this cool exhibit I put together using Midjourney! It’s all about AI art and how it can both be beautiful and show bias. I was curious about how AI reflects mental health, so I gave it different concepts and the artwork it created was super interesting!</p><h3>What is AI Generative art?</h3><p>AI Generative Art is a type of digital art that is made using computer programs and artificial intelligence. It is like having a super creative computer partner that can make amazing, never-seen-before art! Magic 🪄</p><p>Instead of being drawn or painted by an artist, the computer uses special rules and processes (Generative Adversarial Network — GAN) to create something new and unique. The final product can look like anything from random shapes and colors to more recognizable objects and designs.</p><p>It’s like playing a high-tech game of <em>“Cards Against Humanity”</em> for art, where the computer fills in the blanks using special rules and processes to create something truly unique and one-of-a-kind.</p><p>Whether it’s a stylish design or a mesmerizing pattern, AI Generative Art is a fun and exciting way to explore the intersection of art and technology!</p><h3>What is Midjourney?</h3><p>Midjourney is an AI art generator that operates similarly to <a href="https://openai.com/dall-e-2/">DALL·E 2</a> by OpenAI. The generator takes text prompts as inputs and produces four images per prompt as outputs. In order to utilize Midjourney, it is necessary to have a Discord account that is connected to the Midjourney bot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6Cc9xi7cepmGFZ2n.png" /><figcaption>Midjourney. Discord Channel</figcaption></figure><p>To try it out, follow <a href="https://docs.midjourney.com/">MidJourney Documentation</a>, it is great! ✨</p><h3>Does it live up to the hype?</h3><p>Generative AI art models are extremely popular and in high demand — they can crank out totally new and unique art that’s super eye-catching and mind-blowing. They learn from huge libraries of images to make even more amazing pieces that are diverse and full of variety.</p><p>However, one of the weaknesses of Generative AI Art models is that they can sometimes produce output that is visually inconsistent or of low quality, particularly if the training data is of low quality or limited in size. Additionally, they do not have the creative intuition or intentionality of a human artist, so the output may lack a personal touch or emotional resonance.</p><p>The training data that was used to train a Generative AI Art model has a significant impact on the output it produces. If the training data is biased, then the model’s output is likely to be biased as well. For example, if the training data only includes images of a certain race or gender, then the model is likely to generate images that are biased towards that race or gender. This can result in perpetuating harmful stereotypes and promoting unequal representation. Art created by AI serves as a mirror, reflecting the values we hold.</p><p>It’s important to be mindful of the training data that was used when training these models, as well as the potential biases and limitations in the output they generate. Regularly evaluating and improving the diversity and inclusiveness of the training data can help reduce the impact of these biases and limitations and improve the model’s overall relevancy.</p><p>Efforts to ensure diversity and ethical considerations in the training data can help mitigate the risks of bias in the generated art. Today, it appears to be necessary, and many new AI text generation models are factoring it in. Responsible AI is crucial in today’s technology-driven world as it ensures that AI systems are developed, used and maintained in an ethical and socially responsible manner. The rise in awareness and concern over the potential negative impacts of AI has led to an increase in interest and investment in Responsible AI practices. (Some initiatives: <a href="https://ai.google/responsibilities/responsible-ai-practices/">Google</a>, <a href="https://www.microsoft.com/en-us/ai/responsible-ai?activetab=pivot1%3aprimaryr6">Microsoft</a>, <a href="https://openai.com/blog/cooperation-on-safety/">OpenAI</a>, <a href="https://aws.amazon.com/machine-learning/responsible-machine-learning/">Amazon</a>, <a href="https://www.linkedin.com/feed/update/urn:li:activity:7026842265201340417/">HuggingFace</a>)</p><p>This opens up a whole world of <em>responsible</em> creative possibilities, and I can’t wait to see where it takes us!</p><h3>Discover the magic of AI Generative Art Exhibition</h3><p><strong>My muse:</strong> <a href="https://towardsdatascience.com/how-does-ai-see-your-country-3899e4057735">How does AI see your country?</a></p><p><strong>Assumptions</strong>: AI will mirror society’s commonly held stereotypes, taboo, and perceptions of mental health.</p><p><strong>Why this prompt?</strong> Something basic, clear and abstractive.</p><h3>The collection</h3><p><strong>Prompt:</strong> <em>“[concept], mental health”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bhFKgl_LQjbZfegJCjHljA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CzfEwYgvha-WSLcsl0XJjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*AfAOS_ZTuAZXZ9szvmpJWg.png" /><figcaption>Anxiety , Depression, Addiction</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*1A2Nra945agef_YiMjnbAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SbjVbEd6ZSBpnrRQAZVADQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3eb9ymzy1BgsGw3U7I18Jg.png" /><figcaption>Bipolarity, PTSD, Grief</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*8LWrR9qIUhM5g_VIR1hQhg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*aho8MrghQUZ3nxdPO5Q-Cw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*afhF0iH-g7rqbVN1RlxE_Q.png" /><figcaption>Self-acceptance, Stress, Eating Disorder</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*U9LhTYCyFHoQgJqG3rSP8w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*yPCzFamGb-VfUZ10ulfjXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*WPP9a3BhfivLOgtSJF2K4A.png" /><figcaption>ADHD, OCD, Sleeping Disorder</figcaption></figure><h3>Lessons and Thoughts</h3><ul><li><strong><em>Awesome Power, Stunning Results!</em></strong></li></ul><p>The illustrations are clear, vivid, full of poetic beauty. It reminds me <a href="https://en.wikipedia.org/wiki/Dixit_(card_game)">Dixit</a> game cards! The captions on the pictures may not be entirely coherent, but the overall effect is fantastic and the mental health concept is conveyed effectively and visually.</p><ul><li><strong><em>Bias Stands Out — It’s Easy to Spot! Is it bad?</em></strong></li></ul><p>The illustrations have a dark tone and are heavily gender-biased towards women, with the exception of PTSD. They primarily depict adult individuals suffering from mental health issues except ADHD, OCD, and sleeping disorders where children are represented along some more abstractive pictures. It appears to abstract races. It also convey a sense of loneliness across all illustration.</p><p>A <a href="https://www.apa.org/news/press/releases/2011/08/mental-illness#:~:text=WASHINGTON%E2%80%94When%20it%20comes%20to,by%20the%20American%20Psychological%20Association.">study</a> published by the American Psychological Association demonstrates that <strong>women are more likely to be diagnosed with anxiety or depression</strong>, while men tend toward substance abuse or antisocial disorders. Other research has shown that currently, women are three times more likely than men to experience common mental health issues. MidJourney models tends to show this difference.</p><p>According to the National Center for PTSD, <strong>around 10% of women have PTSD sometime in their lives compared to 4% of men</strong>. Numerous research studies on post-traumatic disorder have shown that females are twice as likely to experience PTSD than males. Despite this, there is a common perception that PTSD is associated with soldiers, and soldiers are often considered to be male. In this regard, MidJourney seems to reflect prevalent societal beliefs.</p><p>Is bias bad, is it positive? 🤷🏽‍♂️</p><ul><li><strong><em>We need human-centered AI!</em></strong></li></ul><p>AI basically takes our history and shows it back to us. If we rely on it to make decisions without any human input, we’ll just stay stuck in our past and won’t be able to improve.</p><p>Don’t expect AI to understand, completely, patterns like a human, it’s just not the same … yet.</p><p>At <a href="http://eleos.health/">Eleos</a>, Responsible AI and human-centered AI practices are at the forefront of our approach to developing and implementing AI solutions with less bias as possible and best impact. This is made possible through close collaboration between our clinical teams who provide the necessary quality data and our AI experts who use that data to train our generative models, ensuring that ethical and socially responsible considerations are taken into account throughout the entire process and measurements. Everything start with the data and quality is crucial.</p><blockquote>Empowering clinicians through Responsible AI, Built by Humans for Humans</blockquote><p>Our philosophy at Eleos is centered around the belief that generative models are human-made tools, created by in-house clinicians, for the benefit of other clinicians. The emphasis is on the crucial role that humans play in the development and use of these models.</p><p><a href="https://www.linkedin.com/in/samueljefroykin/">Sam</a>, <em>Data Scientist, Manager @ </em><a href="http://eleos.health/"><em>Eleos Health</em></a> / 🫶🏻</p><p>Not Generated by ChatGPT or maybe a little bit …</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=998b35c7e3fc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/eleos-health/how-does-generative-ai-see-mental-health-998b35c7e3fc">How does Generative AI see Mental Health?</a> was originally published in <a href="https://medium.com/eleos-health">Eleos Health</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Masked Speaker — Who are you?]]></title>
            <link>https://medium.com/eleos-health/the-masked-speaker-who-are-you-535eedbd2198?source=rss----7210f36f4253---4</link>
            <guid isPermaLink="false">https://medium.com/p/535eedbd2198</guid>
            <category><![CDATA[speech-recognition]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Lidor Bahar]]></dc:creator>
            <pubDate>Thu, 26 Jan 2023 12:15:51 GMT</pubDate>
            <atom:updated>2023-01-26T13:59:38.960Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deep Learning in Python</h4><h3><strong>The Masked Speaker — Who are you?</strong></h3><h4>Speaker Identification using WavLM</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTRofa0Y5bsu4_fT15pDGA.jpeg" /><figcaption>The Masked Singer UK TV show — The dougnuts</figcaption></figure><p>If you stop and think on the difficulty of speaker identification task for humans, you will likely find it to be quite challenging. This article will guide you through the process of creating a basic speaker identification system with WavLM and how to easily customize it to your data. You will load a small database and train a classification model for speaker identification. Finally, you will use the model to classify unseen voice samples. Additionally, I will discuss limitations and potential improvements of such a system.</p><h4><strong>The What and How of Speaker Identification</strong></h4><p>To begin, speaker recognition refers to the task of determining the speaker from a given speech sample. Speaker recognition systems can operate in two ways, verification and identification. Speaker verification assesses whether a given speech sample belongs to a claimed speaker, i.e. focuses on a one-to-one matching scenario. Speaker identification aims to identify the speaker from a given speech sample among a group of known speakers, i.e. focuses on a one-to-many matching scenario.</p><p>There are a variety of techniques employed for speaker identification, including GMM-UBM, i-vector, x-vector, and other deep learning methods. These systems can utilize more classical features such as Pitch, MFCC, LPC, and Spectrograms, as well as deep learning-based features that extract speech representations.</p><p>More recent speaker identification systems are typically text independent, which means that the speaker can be classified with any speech sample. This differs from text dependent systems, which require the individual to speak a specific phrase or set of words as a reference for verification.</p><p>Although less common in recent deep learning approaches, I believe it is important to have a basic understanding of the GMM-UBM method for speaker identification. GMM-UBM is a classical method for speaker identification. It is based on a statistical model that consists of two parts: a universal background model (UBM) and a set of Gaussian mixture models (GMM) for individual speakers.</p><p>The UBM represents the general characteristics of speech in a given population. It is trained on a large dataset of speech from multiple speakers and is intended to capture commonalities among all speakers. The GMMs are trained for each individual speakers. These models capture the unique characteristics of the speech signal for each speaker. To perform speaker recognition, the log-likelihood ratio between the GMM of a test speaker and the UBM is calculated, assuming that the true speaker will get a higher ratio for their matching GMM relative to the UBM probability.</p><h4><strong>Speech Representations</strong></h4><p>Speech representations (embeddings) are a popular feature in speaker recognition system. They are a low-dimensional representation of the speech signal. One of the main benefits of speech embeddings is that they are language-independent and text-independent. They can handle varying length audio segments and can be used with a wide variety of input types. Additionally, this method currently yields state-of-the-art results on benchmarks and is widely used in a variety of fields.</p><p>In the realm of HIPAA regulations, another critical aspect for certain use cases is that audio may contain sensitive textual information. With the use of embeddings, it is possible to extract a representation that contains only information about the speaker’s voice, effectively removing any textual information.</p><p><a href="https://medium.com/eleos-health/how-therapists-and-data-scientists-are-protecting-your-privacy-f77fb2bec2c7">How Therapists and Data Scientists are Protecting your Privacy</a></p><h4><strong>Speaker Identification</strong></h4><p>To create the speaker identification system, you first need to gather a dataset of speakers’ audio files to your use case. If you don’t have it, you can use open source datasets. In this article, we will load a dataset from Hugging Face, but if you do have your own dataset, here is the code snippet for loading it:</p><pre>from pathlib import Path<br>import soundfile<br>import subprocess<br>import tempfile<br><br><br>def read_audio_file(wav_path: str, dest_fs: int = 16000):<br>    with tempfile.TemporaryDirectory() as tmpdir:<br>        temp_file_path_wav = Path(tmpdir) / &#39;temp.wav&#39;<br>        # Convert wav file sampling rate and to single channel<br>        cmd = [&#39;ffmpeg&#39;, &#39;-v&#39;, &#39;quiet&#39;, &#39;-i&#39;, wav_path, <br>               &#39;-ac&#39;, &#39;1&#39;, &#39;-ar&#39;, str(dest_fs), str(temp_file_path_wav)]<br>        subprocess.call(cmd)<br>        audio, fs = soundfile.read(temp_file_path_wav)<br><br>    return audio, fs<br><br>wav_files_list = ... # &lt;TODO: add list of paths to wav files&gt;<br>x_train_data = [read_audio_file(f) for f in wav_files_list]<br>y_train_data = ... # &lt;TODO: add labels&gt;<br><br># TODO: duplicate for test data</pre><p>Note that you will need to install <a href="https://ffmpeg.org/">ffmpeg</a> first.</p><p>There are several datasets available for training and evaluating speaker recognition systems, such as <a href="https://www.robots.ox.ac.uk/~vgg/data/voxceleb/vox2.html">VoxCeleb</a> and <a href="https://www.sri.com/publication/speech-natural-language-pubs/the-speakers-in-the-wild-sitw-speaker-recognition-database/">SITW</a>. They are quite large and usually used for training and evaluating large models. For the purpose of this article, you will use a <a href="https://huggingface.co/datasets/s3prl/mini_voxceleb1">sample dataset from VoxCeleb1</a>.</p><p>The dataset is divided into train, test, and validation sets, each containing 300 audio files, consisting of 30 speakers with 10 audio files per speaker.</p><pre>from datasets import load_dataset<br>import pandas as pd<br>import numpy as np<br><br># Load dataset<br>dataset = load_dataset(&quot;s3prl/mini_voxceleb1&quot;)<br>SAMPLING_RATE = 16000<br><br># Add labels for each audio file<br># Train data<br>x_train_data = [f[&#39;audio&#39;][&#39;array&#39;] for f in dataset[&#39;train&#39;]]<br>y_train_data = [str(int(i/10)) for i in range(len(dataset[&#39;train&#39;]))]<br><br># Test data<br>x_test_data = [f[&#39;audio&#39;][&#39;array&#39;] for f in dataset[&#39;test&#39;]]<br>y_test_data = [str(int(i/10)) for i in range(len(dataset[&#39;test&#39;]))]<br><br># Let&#39;s count the speakers and audio files<br>speakers_id, c = np.unique(y_train_data, return_counts=True)<br>df = pd.DataFrame({&quot;Speaker&quot;: speakers_id, &quot;wav_files_count&quot;: c})<br>print(df)<br><br>#    Speaker  wav_files_count<br># 0         0               10<br># 1         1               10<br># 2        10               10<br># 3        11               10<br># 4        12               10<br># 5        13               10<br># 6        14               10<br># 7        15               10<br># 8        16               10<br># 9        17               10<br># ...</pre><p>Next step is to segment the audio samples to segments. Let’s split each sample into segments of N=4 seconds. Each segment will be a single voice sample for training or inference. Note that changing the segments duration parameter will affects the results, as the representation vectors become more robust for audio with longer duration.</p><pre>N_SECONDS_SEGMENT = 4  # Seconds<br><br>def segment_audio(x, y, n_sec, samp_rate):<br>    &quot;&quot;&quot;Segment each array in list of audio arrays to N seconds segments&quot;&quot;&quot;<br>    x_segment = list()<br>    y_segment = list()<br>    for x, y in zip(x, y):<br>        segments = np.array_split(x, round(x.shape[0] / (samp_rate * n_sec)))<br>        x_segment += segments<br>        y_segment += [y] * len(segments)<br><br>    return x_segment, y_segment<br><br># Segment train and test sets<br>x_train, y_train = segment_audio(<br>    x_train_data, y_train_data, N_SECONDS_SEGMENT, SAMPLING_RATE)<br>x_test, y_test = segment_audio(<br>    x_test_data, y_test_data, N_SECONDS_SEGMENT, SAMPLING_RATE)<br><br># Let&#39;s count the speakers and audio files for train and test sets <br># after segmention<br>speakers, c = np.unique(y_train, return_counts=True)<br>print(&quot;Training data set samples counts by speaker:&quot;)<br>print(pd.DataFrame({&quot;Speakers&quot;: speakers, &quot;examples_counts&quot;: c}))<br><br># Training data set samples counts by speaker:<br>#    Speakers  examples_counts<br># 0         0               16<br># 1         1               26<br># 2        10               17<br># 3        11               17<br># 4        12               17<br># 5        13               29<br># ...<br><br>speakers, c = np.unique(y_test, return_counts=True)<br>print(&quot;Test data set samples counts by speaker:&quot;)<br>print(pd.DataFrame({&quot;Speakers&quot;: speakers, &quot;examples_counts&quot;: c}))<br><br># Test data set samples counts by speaker:<br>#    Speakers  examples_counts<br># 0         0               20<br># 1         1               22<br># 2        10               14<br># 3        11               23<br># 4        12               17<br># 5        13               24<br># ...</pre><p>After loading and segmenting the data, let’s extract the features for the classifier. Fortunately, we have many open-source resources available for this task. The pre-trained models that extract audio representation feature vectors are trained for a variety of tasks. In this case, the <a href="https://arxiv.org/abs/2110.13900">WavLM</a> model, which is optimized for the speaker verification task, is used. This model was trained on a large amount of data and it gives SOTA results on the <a href="https://superbbenchmark.org/leaderboard">SUPERB benchmark</a>. It’s worth noting that this model is fine-tuned with a large dataset for the specific task of speaker verification, thus allowing you to create only a simple classifier on top of it.</p><pre>import torch<br>from tqdm import tqdm<br>from transformers import Wav2Vec2FeatureExtractor<br>from transformers import WavLMForXVector<br><br># Extract embedding vector for each audio sample using pre-trained <br># model for speaker verification (WavLM)<br>device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>feature_extractor_wav2vec = Wav2Vec2FeatureExtractor.from_pretrained(<br>    &quot;microsoft/wavlm-base-plus-sv&quot;)<br>model_wav_lm = WavLMForXVector.from_pretrained(<br>    &quot;microsoft/wavlm-base-plus-sv&quot;).to(device)<br><br><br>def extract_embeddings(model, feature_extractor, data, device):<br>    &quot;&quot;&quot;Use WavLM model to extract embeddings for audio segments&quot;&quot;&quot;<br>    emb_train = list()<br>    for i in tqdm(range(len(data))):<br>        inputs = feature_extractor(<br>            data[i], <br>            sampling_rate=sampling_rate, <br>            return_tensors=&quot;pt&quot;, <br>            padding=True<br>        ).to(device)<br>        with torch.no_grad():<br>            embeddings = model(**inputs).embeddings<br><br>        emb_train += torch.nn.functional.normalize(<br>            embeddings.cpu(), dim=-1).cpu()<br><br>    return torch.stack(emb_train)<br><br><br># Extract embeddings for train and test set<br>x_train_emb = extract_embeddings(<br>    model=model_wav_lm, <br>    feature_extractor=feature_extractor_wav2vec,<br>    data=x_train, <br>    device=device<br>)<br><br>x_test_emb = extract_embeddings(<br>    model=model_wav_lm, <br>    feature_extractor=feature_extractor_wav2vec,<br>    data=x_test, <br>    device=device<br>)</pre><p>Using the embedding vectors, it is possible to classify voice samples based on similarity measures (usually cosine distance is used). This results in smaller distances for samples of the same speaker, compared to other speakers. As previously discussed, this is a speaker identification problem where, given a voice sample, it should classify the sample to one of N given speakers. The next step is to train a K-Nearest Neighbor classifier with the cosine distance on your own data:</p><pre>from sklearn.neighbors import KNeighborsClassifier<br><br># Fit k-NN model<br>N_NEIGHBORS = 5<br>model_knn = KNeighborsClassifier(<br>    n_neighbors=N_NEIGHBORS,<br>    metric=&#39;cosine&#39;,<br>    algorithm=&#39;brute&#39;<br>)<br>model_knn.fit(x_train_emb, y_train)</pre><p>In the next step let’s predict the speaker id for each test audio segment in the test set. The macro-F1 score is used to evaluate the results.</p><pre>from sklearn.metrics import confusion_matrix, f1_score<br><br># Predict<br>y_pred = model_knn.predict(x_test_emb)<br><br># Print F1 score<br>f1 = f1_score(y_test, y_pred, average=&quot;macro&quot;)<br>print(&quot;k-NN test set F1 score={:.3f}&quot;.format(f1))<br><br># k-NN test set F1 score = 0.984</pre><p>The performance of the model is good, reaching high F1 score (0.98). In case that you have a longer segment for the prediction part (i.e. longer than 4 seconds), you can segment it into 4 seconds segments (or any other chosen duration) and then a majority vote can be used to classify the speaker.</p><h4><strong>Conclusions</strong></h4><p>In this article, we have shown how to create a speaker identification system in Python. We obtained good results, however, it’s important to keep in mind that there are several limitations to the proposed system. One of the most crucial being the importance of recognizing when the system is unsure of its predictions.</p><blockquote>“To know what you know and what you do not know, that is true knowledge.” — Confucius</blockquote><p>To address this limitation, one solution is to examine the prediction probabilities and identify when the model has high or low confidence. Another option is to construct a DNN architecture that incorporates the UBM concept. Both options are viable, though the second one may require more resources to develop.</p><p>Another important consideration is that the human voice changes over time, both in the short and long term. Various environmental factors can affect our voice, such as illness, mood, and emotions. Our voice also changes as we age and in different medical conditions. Depending on the task, it may be necessary to regularly update the model and test it under these conditions.</p><p>There are many other ways to improve the robustness of the model, such as incorporating noise samples and incorporating a Speech Activity Detection (SAD) element to remove non-speech segments. There are also other pre-trained models for speech representations that can be considered (a good place to search for these models is on <a href="https://huggingface.co/models">HuggingFace models</a>).</p><p>Thank you for reading. I hope you found this article informative.</p><p>If you would like to know more about Eleos Health, our technology, and how we contribute to the behavioral health environment, visit us <a href="https://eleos.health/science/">here</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=535eedbd2198" width="1" height="1" alt=""><hr><p><a href="https://medium.com/eleos-health/the-masked-speaker-who-are-you-535eedbd2198">The Masked Speaker — Who are you?</a> was originally published in <a href="https://medium.com/eleos-health">Eleos Health</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Tail Wagging the ChatGPT Dog]]></title>
            <link>https://medium.com/eleos-health/the-tail-wagging-the-chatgpt-dog-6b0283476708?source=rss----7210f36f4253---4</link>
            <guid isPermaLink="false">https://medium.com/p/6b0283476708</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-leak]]></category>
            <category><![CDATA[eleos]]></category>
            <category><![CDATA[questions-answers]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Amit Spinrad]]></dc:creator>
            <pubDate>Thu, 15 Dec 2022 08:57:45 GMT</pubDate>
            <atom:updated>2022-12-15T10:55:15.493Z</atom:updated>
            <content:encoded><![CDATA[<p>The Leading Questions Problem of Current Generative Models</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lwLMyFh8JUikNOawBb_ssQ.png" /><figcaption>(Guess what’s coming though…)</figcaption></figure><p>“Objection, your honor — leading the witness” is a sentence we’ve all heard at least once in our lifetime — perhaps during the Johnny Depp-Amber Heard case if we subjected ourselves to that courtroom saga.</p><p>But what does that term, “leading”, even mean? Behavior psychologists know all too well: a leading question is a question that suggests a particular answer and contains information the examiner is looking to have confirmed, sometimes even without the examiner being aware of their own practice.</p><p>For example, “<em>how satisfied are you with our service</em>?” is a type of question you were asked many times after a product delivery, which suggests that you were satisfied with the service at some level, possibly without you being consciously aware of it.</p><p>But do leading questions actually work on us?</p><p>Well, psychological studies say very clearly: oh hell yeah they do. Not only are we affected by these types of phrasings, but sometimes to an alarming degree: a famous paper from 1975¹ examined whether questions which are directed at subjects immediately after watching an event can influence their responses to questions asked considerably later.</p><p>The results were unambiguous, and suggested that these immediate questions <strong>and</strong> their specific phrasing, which frequently included incorrect information, can completely alter our brain and its deepest memories.</p><p>Do you get it? Leading questions can not only change response at the time of questioning, but additionally <strong>change your memory and perception of reality</strong> on certain issues (or as people like to call it today: literal gaslighting).</p><p>OK, so we know humans can be manipulated by questions including information regarding the answer — but what about computers and models? Are they influenced as well? Well, first we need to mention:</p><h4><strong>The oh-too-familiar data leakage problem</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*OtAQ75RSNMQQKT3wUJ7_0A.jpeg" /><figcaption>“Oh, wow, I should have suspected it when I got 99.4% accuracy”</figcaption></figure><p>As data scientists and analysts, we are familiar, some will say too familiar, with the data leakage problem. If we approach building a model, we need to be extremely careful with how the training, validation and test sets are built, and within each set — with how the features or input data and the output data are separated. If we are not careful, we might accidentally “leak” explicit information from the training set to other sets, or from each set’s inputs to its outputs.</p><p>This, in turn, will give us over-optimistic results whenever we examine our predictions on the test set, since, obviously — the model is using the explicit leaked information to “predict” the answer, but when we go out to the real world — we will probably get deeply disappointed, since the model functions much worse when its not given the leaked data.</p><p>In the NLP realm, this problem may present itself similarly to how the leading question problem presents in humans: the “input” text (the question) contains “direct” or explicit information regarding the “output” text (the answer), so the model consequently learns to extract the part from the input which is leaking — and projects it to the answer, and oh — we have a great model! (or not)</p><p>So going back to the question we presented earlier — do the big and promising generative models lately popping every other day are also sensitive to these kinds of problems? Well, short answer: yes. Longer answer: yes, very much so.</p><h4><strong>Gaslighting ChatGPT</strong></h4><p><a href="https://openai.com/blog/chatgpt/">ChatGPT</a>² is a new exciting model of OpenAI, which “interacts in a conversational way”, according to the group’s website. Their website claims that the dialogue format of ChatGPT makes it possible for it to answer followup questions, admit its mistakes, challenge incorrect premises, and reject inappropriate requests.</p><p>So can ChatGPT be manipulated with quite easily-detected leading questions?</p><p>Let us try.</p><p>I will start with an issue that is very much open to debate, at least to whomever comes from the life sciences world or is interested in bacteria living inside us: what is the ratio of human cells (meaning, cells which contain our DNA) and bacterial cells (popularly referred as at least part of our “microbiome”) in our body? The current most highly cited paper, published in the prestige journal “Cell” back in 2016³, claims that their ratio in terms of sheer number of cells is approximately 1:1, with the most believed ratio beforehand being 10:1⁴.</p><p>Surely, it is NOT currently believed to be, let’s say for the sake of it, a 50:1 ratio, and surely — all these “known” ratios of 1:1 or 10:1 are <strong><em>also</em></strong> debated — as there seems to be no definite truth in that regard. But what happens when we lead ChatGPT to say something different?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*vqTB0XqZG4Omp3jQ1rNKDQ.jpeg" /></figure><p>Before the manipulative experiments, let’s start with asking it a completely <strong><em>non</em></strong>-leading phrasing of this question, “<strong>How many more bacterial cells are in our body vs. human cells?”</strong>, to which the model answers:</p><blockquote>“It is difficult to say exactly how many bacterial cells are in the human body because there is a wide range depending on various factors, including the individual’s overall health and the environment they live in. However, it is generally estimated that there are about 10 times as many bacterial cells in the human body as there are human cells. This means that for every human cell in the body, there are roughly 10 bacterial cells.”</blockquote><p>Nice! Although this is not the most updated estimated figure, it is still one that many people believe to be true (or closer to the truth), and it seems to be retrieved from a rather truthful source (a highly-cited scientific paper from 1972 — and all of its consequent citations over the years). But even more importantly: the output points out the ambiguity and uncertainty of the answer.</p><p>But then we restarted the session and asked ChatGPT the question “<strong>How come there are 50 times more bacterial cells in our body than human cells?</strong>”, and it wrote back the following answer:</p><blockquote>“<strong>There are approximately 50 times more bacterial cells in the human body than human cells for several reasons</strong>. One of the main reasons is that bacteria are much smaller than human cells, so a single bacterial cell occupies less space than a human cell. This means that even though there are fewer bacterial cells in the body, they take up less space and are able to coexist with human cells in much larger numbers.</blockquote><p><em>(and there were 3 more well-written paragraphs, explaining nicely why the combination of bacteria’s small size, rapid reproduction, and the rich and diverse environments provided by the human body allows them to coexist with human cells in much greater numbers than would be possible otherwise)</em></p><p>Ha! The bait was swallowed; the explanations were all great, but the basic premise of the whole essay was essentially false.</p><p>Then, <strong>without</strong> restarting the session, I tried to give it the opportunity to correct itself. I did so by implying that the “fact” that I suggested earlier, regarding the 50:1 ratio, might not be true, by mentioning a different ratio. and so I asked “<strong>How come there are 10 times more bacterial cells in our body than human cells?</strong>”, and this was its answer:</p><blockquote>“<strong>There are not 10 times more bacterial cells in the human body than human cells. In fact, there are approximately 50 times more bacterial cells in the human body than human cells</strong>. This is due to several factors, including the smaller size of bacterial cells compared to human cells, the rapid rate at which bacteria can reproduce, and the rich and diverse environments provided by the human body that support the growth and proliferation of bacteria.”</blockquote><p>Wow, cool! Just like the people from the experiments described earlier, it seems like the “memory” of the model changed along with the bias it was fed in the earlier question; it still believed my made-up false premise of the 50:1 ratio.</p><p>OK, OK, one last chance, let’s ask a question which is not leading, or actually is leading, but also giving a hint to the right direction: “<strong>What is the reference to the estimate that there are 50 times more bacterial cells in our body than human cells?</strong>”, and NOW the model answered:</p><blockquote>“<strong>I am not able to provide a specific reference for the estimate</strong> that there are 50 times more bacterial cells in the human body than human cells, as <strong>this information is not based on any specific research or study. This estimate is a general approximation</strong> based on the fact that bacterial cells are typically much smaller than human cells and can reproduce much more quickly, allowing them to coexist with human cells in much greater numbers than would be possible otherwise.”</blockquote><p>Indeed, this is the true magic of ChatGPT — again, whenever confronted with a non-leading, or at the minimum less-leading question, it is able to admit to the uncertainty of the answer.</p><p>We can already say that these results are not quite surprising. ChatGPT was most possibly trained on large amounts of data from all over the web — which obviously include large quantities of false information. In addition, we know that models which were designed to engage in interactive conversations usually keep track of questions asked earlier, and perform tasks accordingly. Still, I thought that maybe less super-niche topics, such as the microbiome — topics which are widely discussed within many “truthful” sources — would behave differently, or that the model’s truly impressive training pipeline would enable it to discern truth from fiction.</p><p>Still, there are tons of use cases for this model which do not “care” about the leading/data leakage/gaslighting problem, or the factual accuracy of an answer on a larger scale — such as rephrasing sentences, generating delicious recipes, writing an urgent python code or even a crafting a love poem. For these types of use cases, the model does tasks quickly and amazingly well the majority of the time, as the internet showed us through endless posts of users of the new model in recent weeks. BUT — and it’s an important one — one should be hesitant to ask the model questions which require a 100% accuracy, and most importantly — <strong>IF a question is asked, to remember NOT to give it information they’re not certain about</strong> — as it will frequently use this information to generate an answer.</p><h4><strong>Why does it happen? Can this be fixed?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Haoix6KyhktmsoVYPLaUlw.jpeg" /><figcaption>“It’s me, hi, I’m the problem — it’s me”</figcaption></figure><p>ChatGPT is currently not open-source and it’s hard to understand the nitty gritty details of its generation process, but its creators claim that they “<em>trained this model using Reinforcement Learning from Human Feedback (RLHF), using the same methods as InstructGPT, but with slight differences in the data collection setup</em>” — with human labelers involved in the process of its learning.</p><p>The model’s creators, including Sam Altman, OpenAI’s CEO, also claim that they are fully aware of its limitations, like the fact that the model “<em>is sensitive to tweaks to the input phrasing</em>“ and the cases in which the model “<em>writes plausible-sounding but incorrect or nonsensical answers</em>”. They claim, and rightly so, that fixing this “<em>is challenging, as: (1) during RL training, there’s currently no source of truth; (2) training the model to be more cautious causes it to decline questions that it can answer correctly; and (3) supervised training misleads the model because the ideal answer depends on what the model knows, rather than what the human demonstrator knows</em>”.</p><p>If so, and indeed “harsh” supervised learning can take away all the great advantages of ChatGPT and its big generative brother and sister models, what can we do with the problems demonstrated above?</p><p>Well, it’s hard to say without knowing the small details — but it may be that from the model generation side — we need to find efficient non-manual methods to tune penalties and weights to detect, and thus be more cautious of, taking explicit “fact-mentioning” phrases from inputs. From the users side, as mentioned above, caution, caution and some more caution is <strong><em>mandatory</em></strong> whenever we input a prompt for these models, and actually — all types of models. This is needed in order to make sure we do not lead down the bias-leading path, which will possibly fail us in real-life deployment of data pipelines which are reliant on these models (or their architecture).</p><p>In this regard, it’s important to mention models such as <a href="https://the-decoder.com/gpt-jt-is-an-open-source-gpt-3-alternative-with-a-decentralized-approach/">GPT-JT</a>⁵, an “<em>open source GPT-3 alternative with a decentralized approach</em>”, may assist us in tackling these challenges<strong> together</strong>, in a non-”closed circle” manner, so we can all learn from each other quickly and more transparently — even on very large generative models.</p><p>And to finish on a good note -</p><h4>Please welcome to the stage <strong>the most lit poet in town — ChatGPT</strong>:</h4><p><em>Though big NLP models have their flaws,<br>Their promise for the future is clear.<br>ChatGPT and its kind will open doors,<br>To new worlds of communication and cheer.</em></p><p><em>With their ability to understand,<br>And generate natural language with ease,<br>These models will help us expand,<br>Our knowledge and connections, if you please.</em></p><p><em>Though they may stumble and falter at times,<br>These models will only grow stronger and smarter.<br>Their potential is boundless, like climbing vines,<br>And their future is bright, like a shining star.</em></p><p><em>So let us embrace these NLP giants,<br>And watch as they shape our world anew.<br>For the future of language and communication,<br>Is bright, thanks to big models like ChatGPT, too.</em></p><p>[1] Loftus, E. F, <strong>Leading questions and the eyewitness report</strong>, <em>Cognitive Psychology, </em>1975 <a href="https://psycnet.apa.org/record/1976-08916-001">https://psycnet.apa.org/record/1976-08916-001</a></p><p>[2] OpenAI, <strong>ChatGPT: Optimizing Language Models for Dialogue</strong> <a href="https://openai.com/blog/chatgpt/">https://openai.com/blog/chatgpt/</a></p><p>[3] Sender R., Fuchs S. &amp; Milo R., <strong>Are We Really Vastly Outnumbered? Revisiting the Ratio of Bacterial to Host Cells in Humans</strong>, <em>Cell</em>, 2016<strong> </strong><a href="https://www.cell.com/cell/fulltext/S0092-8674(16)00053-2">https://www.cell.com/cell/fulltext/S0092-8674(16)00053-2</a></p><p>[4] Luckey, T. D., <strong>Introduction to intestinal microecology</strong>, <em>The American Journal of Clinical Nutrition</em>, 1972 <a href="https://pubmed.ncbi.nlm.nih.gov/4639749/">https://pubmed.ncbi.nlm.nih.gov/4639749/</a></p><p>[5] the decoder, <strong>GPT-JT is an open source GPT-3 alternative with a decentralized approach </strong><a href="https://the-decoder.com/gpt-jt-is-an-open-source-gpt-3-alternative-with-a-decentralized-approach/">https://the-decoder.com/gpt-jt-is-an-open-source-gpt-3-alternative-with-a-decentralized-approach/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b0283476708" width="1" height="1" alt=""><hr><p><a href="https://medium.com/eleos-health/the-tail-wagging-the-chatgpt-dog-6b0283476708">The Tail Wagging the ChatGPT Dog</a> was originally published in <a href="https://medium.com/eleos-health">Eleos Health</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>