{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Advanced Semantic Search with Sentence Transformers and MLflow\n", "\n", "Embark on a hands-on journey exploring Advanced Semantic Search using Sentence Transformers and MLflow.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### What You Will Learn\n", "\n", "- Implement advanced semantic search with `sentence-transformers`.\n", "- Customize MLflow's `PythonModel` for unique project requirements.\n", "- Manage and log models within MLflow's ecosystem.\n", "- Deploy complex models for practical applications using MLflow.\n", "\n", "#### Understanding Semantic Search\n", "Semantic search transcends keyword matching, using language nuances and context to find relevant results. This advanced approach reflects human language understanding, considering the varied meanings of words in different scenarios.\n", "\n", "#### Harnessing Power of Sentence Transformers for Search\n", "Sentence Transformers, specialized for context-rich sentence embeddings, transform search queries and text corpora into semantic vectors. This enables the identification of semantically similar entries, a cornerstone of semantic search.\n", "\n", "#### MLflow: A Vanguard in Model Management and Deployment\n", "MLflow enhances NLP projects with efficient experiment logging and customizable model environments. It brings efficiency to experiment tracking and adds a layer of customization, vital for unique NLP tasks.\n", "\n", "Join us in this tutorial to master advanced semantic search techniques and discover how MLflow can revolutionize your approach to NLP model deployment and management." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import warnings\n", "\n", "# Disable a few less-than-useful UserWarnings from setuptools and pydantic\n", "warnings.filterwarnings(\"ignore\", category=UserWarning)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Understanding the Semantic Search Model with MLflow and Sentence Transformers\n", "Delve into the intricacies of the `SemanticSearchModel`, a custom implementation for semantic search using MLflow and Sentence Transformers.\n", " \n", "#### MLflow and Custom PyFunc Models\n", "MLflow's custom Python function (`pyfunc`) models provide a flexible and deployable solution for integrating complex logic, ideal for our `SemanticSearchModel`.\n", "\n", "#### The Model's Core Functionalities\n", "\n", "- **Context Loading**: Essential for initializing the Sentence Transformer model and preparing the corpus for semantic comparison.\n", "- **Predict Method**: The central function for semantic search, encompassing input validation, query encoding, and similarity computation.\n", "\n", "#### Detailed Breakdown of Predict Method\n", "\n", "- **Input Validation**: Ensures proper format and extraction of the query sentence.\n", "- **Query Encoding**: Converts the query into an embedding for comparison.\n", "- **Cosine Similarity Computation**: Determines the relevance of each corpus entry to the query.\n", "- **Top Results Extraction**: Identifies the most relevant entries based on similarity scores.\n", "- **Relevancy Filtering**: Filters results based on a minimum relevancy threshold, enhancing practical usability.\n", "- **Warning Mechanism**: Issues a warning if all top results are below the relevancy threshold, ensuring a result is always provided.\n", "\n", "#### Conclusion\n", "This semantic search model exemplifies the integration of NLP with MLflow, showcasing flexibility, user-friendliness, and practical application in modern machine learning workflows." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import warnings\n", "\n", "import numpy as np\n", "import pandas as pd\n", "from sentence_transformers import SentenceTransformer, util\n", "\n", "import mlflow\n", "from mlflow.models.signature import infer_signature\n", "from mlflow.pyfunc import PythonModel\n", "\n", "\n", "class SemanticSearchModel(PythonModel):\n", " def load_context(self, context):\n", " \"\"\"Load the model context for inference, including the corpus from a file.\"\"\"\n", " try:\n", " # Load the pre-trained sentence transformer model\n", " self.model = SentenceTransformer.load(context.artifacts[\"model_path\"])\n", "\n", " # Load the corpus from the specified file\n", " corpus_file = context.artifacts[\"corpus_file\"]\n", " with open(corpus_file) as file:\n", " self.corpus = file.read().splitlines()\n", "\n", " # Encode the corpus and convert it to a tensor\n", " self.corpus_embeddings = self.model.encode(self.corpus, convert_to_tensor=True)\n", "\n", " except Exception as e:\n", " raise ValueError(f\"Error loading model and corpus: {e}\")\n", "\n", " def predict(self, context, model_input, params=None):\n", " \"\"\"Predict method to perform semantic search over the corpus.\"\"\"\n", "\n", " if isinstance(model_input, pd.DataFrame):\n", " if model_input.shape[1] != 1:\n", " raise ValueError(\"DataFrame input must have exactly one column.\")\n", " model_input = model_input.iloc[0, 0]\n", " elif isinstance(model_input, dict):\n", " model_input = model_input.get(\"sentence\")\n", " if model_input is None:\n", " raise ValueError(\"The input dictionary must have a key named 'sentence'.\")\n", " else:\n", " raise TypeError(\n", " f\"Unexpected type for model_input: {type(model_input)}. Must be either a Dict or a DataFrame.\"\n", " )\n", "\n", " # Encode the query\n", " query_embedding = self.model.encode(model_input, convert_to_tensor=True)\n", "\n", " # Compute cosine similarity scores\n", " cos_scores = util.cos_sim(query_embedding, self.corpus_embeddings)[0]\n", "\n", " # Determine the number of top results to return\n", " top_k = params.get(\"top_k\", 3) if params else 3 # Default to 3 if not specified\n", "\n", " minimum_relevancy = (\n", " params.get(\"minimum_relevancy\", 0.2) if params else 0.2\n", " ) # Default to 0.2 if not specified\n", "\n", " # Get the top_k most similar sentences from the corpus\n", " top_results = np.argsort(cos_scores, axis=0)[-top_k:]\n", "\n", " # Prepare the initial results list\n", " initial_results = [\n", " (self.corpus[idx], cos_scores[idx].item()) for idx in reversed(top_results)\n", " ]\n", "\n", " # Filter the results based on the minimum relevancy threshold\n", " filtered_results = [result for result in initial_results if result[1] >= minimum_relevancy]\n", "\n", " # If all results are below the threshold, issue a warning and return the top result\n", " if not filtered_results:\n", " warnings.warn(\n", " \"All top results are below the minimum relevancy threshold. \"\n", " \"Returning the highest match instead.\",\n", " RuntimeWarning,\n", " )\n", " return [initial_results[0]]\n", " else:\n", " return filtered_results" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Building and Preparing the Semantic Search Corpus\n", "Explore constructing and preparing the corpus for the semantic search model, a critical component for search functionality.\n", "\n", "#### Simulating a Real-World Use Case\n", "We create a simplified corpus of synthetic blog posts to demonstrate the model's core functionality, replicating a scaled-down version of a typical real-world scenario.\n", "\n", "#### Key Steps in Corpus Preparation\n", "\n", "- **Corpus Creation**: Formation of a list representing individual blog post entries.\n", "- **Writing to a File**: Saving the corpus to a text file, mimicking the process of data extraction and preprocessing in a real application.\n", "\n", "#### Efficient Data Handling for Scalability\n", "Our model encodes the corpus into embeddings for rapid comparison, demonstrating an efficient approach suitable for scaling to larger datasets.\n", "\n", "#### Production Considerations\n", "\n", "- **Storing Embeddings**: Discusses options for efficient storage and retrieval of embeddings, crucial in large-scale applications.\n", "- **Scalability**: Highlights the importance of scalable storage systems for handling extensive datasets and complex queries.\n", "- **Updating the Corpus**: Outlines strategies for managing and updating the corpus in dynamic, evolving use cases.\n", "\n", "#### Realizing the Semantic Search Concept\n", "This setup, while simplified, reflects the essential steps for developing a robust and scalable semantic search system, combining NLP techniques with efficient data management. In a real production use-case, the processing of a corpus (creating embeddings) would be an external process to that which is running the semantic search. The corpus example below is intended to showcase functionality solely for the purposes of demonstration. " ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "corpus = [\n", " \"Perfecting a Sourdough Bread Recipe: The Joy of Baking. Baking sourdough bread \"\n", " \"requires patience, skill, and a good understanding of yeast fermentation. Each \"\n", " \"loaf is unique, telling its own story of the baker's journey.\",\n", " \"The Mars Rover's Discoveries: Unveiling the Red Planet. NASA's Mars rover has \"\n", " \"sent back stunning images and data, revealing the planet's secrets. These \"\n", " \"discoveries may hold the key to understanding Mars' history.\",\n", " \"The Art of Growing Herbs: Enhancing Your Culinary Skills. Growing your own \"\n", " \"herbs can transform your cooking, adding fresh and vibrant flavors. Whether it's \"\n", " \"basil, thyme, or rosemary, each herb has its own unique characteristics.\",\n", " \"AI in Software Development: Transforming the Tech Landscape. The rapid \"\n", " \"advancements in artificial intelligence are reshaping how we approach software \"\n", " \"development. From automation to machine learning, the possibilities are endless.\",\n", " \"Backpacking Through Europe: A Journey of Discovery. Traveling across Europe by \"\n", " \"backpack allows one to immerse in diverse cultures and landscapes. It's an \"\n", " \"adventure that combines the thrill of exploration with personal growth.\",\n", " \"Shakespeare's Timeless Influence: Reshaping Modern Storytelling. The works of \"\n", " \"William Shakespeare continue to inspire and influence contemporary literature. \"\n", " \"His mastery of language and deep understanding of human nature are unparalleled.\",\n", " \"The Rise of Renewable Energy: A Sustainable Future. Embracing renewable energy \"\n", " \"is crucial for achieving a sustainable and environmentally friendly lifestyle. \"\n", " \"Solar, wind, and hydro power are leading the way in this green revolution.\",\n", " \"The Magic of Jazz: An Exploration of Sound and Harmony. Jazz music, known for \"\n", " \"its improvisation and complex harmonies, has a rich and diverse history. It \"\n", " \"evokes a range of emotions, often reflecting the soul of the musician.\",\n", " \"Yoga for Mind and Body: The Benefits of Regular Practice. Engaging in regular \"\n", " \"yoga practice can significantly improve flexibility, strength, and mental \"\n", " \"well-being. It's a holistic approach to health, combining physical and spiritual \"\n", " \"aspects.\",\n", " \"The Egyptian Pyramids: Monuments of Ancient Majesty. The ancient Egyptian \"\n", " \"pyramids, monumental tombs for pharaohs, are marvels of architectural \"\n", " \"ingenuity. They stand as a testament to the advanced skills of ancient builders.\",\n", " \"Vegan Cuisine: A World of Flavor. Exploring vegan cuisine reveals a world of \"\n", " \"nutritious and delicious possibilities. From hearty soups to delectable desserts, \"\n", " \"plant-based dishes are diverse and satisfying.\",\n", " \"Extraterrestrial Life: The Endless Search. The quest to find life beyond Earth \"\n", " \"continues to captivate scientists and the public alike. Advances in space \"\n", " \"technology are bringing us closer to answering this age-old question.\",\n", " \"The Art of Plant Pruning: Promoting Healthy Growth. Regular pruning is essential \"\n", " \"for maintaining healthy and vibrant plants. It's not just about cutting back, but \"\n", " \"understanding each plant's growth patterns and needs.\",\n", " \"Cybersecurity in the Digital Age: Protecting Our Data. With the rise of digital \"\n", " \"technology, cybersecurity has become a critical concern. Protecting sensitive \"\n", " \"information from cyber threats is an ongoing challenge for individuals and \"\n", " \"businesses alike.\",\n", " \"The Great Wall of China: A Historical Journey. Visiting the Great Wall offers \"\n", " \"more than just breathtaking views; it's a journey through history. This ancient \"\n", " \"structure tells stories of empires, invasions, and human resilience.\",\n", " \"Mystery Novels: Crafting Suspense and Intrigue. A great mystery novel captivates \"\n", " \"the reader with intricate plots and unexpected twists. It's a genre that combines \"\n", " \"intellectual challenge with entertainment.\",\n", " \"Conserving Endangered Species: A Global Effort. Protecting endangered species \"\n", " \"is a critical task that requires international collaboration. From rainforests to \"\n", " \"oceans, every effort counts in preserving our planet's biodiversity.\",\n", " \"Emotions in Classical Music: A Symphony of Feelings. Classical music is not just \"\n", " \"an auditory experience; it's an emotional journey. Each composition tells a story, \"\n", " \"conveying feelings from joy to sorrow, tranquility to excitement.\",\n", " \"CrossFit: A Test of Strength and Endurance. CrossFit is more than just a fitness \"\n", " \"regimen; it's a lifestyle that challenges your physical and mental limits. It \"\n", " \"combines various disciplines to create a comprehensive workout.\",\n", " \"The Renaissance: An Era of Artistic Genius. The Renaissance marked a period of \"\n", " \"extraordinary artistic and scientific achievements. It was a time when creativity \"\n", " \"and innovation flourished, reshaping the course of history.\",\n", " \"Exploring International Cuisines: A Culinary Adventure. Discovering international \"\n", " \"cuisines is an adventure for the palate. Each dish offers a glimpse into the \"\n", " \"culture and traditions of its origin.\",\n", " \"Astronaut Training: Preparing for the Unknown. Becoming an astronaut involves \"\n", " \"rigorous training to prepare for the extreme conditions of space. It's a journey \"\n", " \"that tests both physical endurance and mental resilience.\",\n", " \"Sustainable Gardening: Nurturing the Environment. Sustainable gardening is not \"\n", " \"just about growing plants; it's about cultivating an ecosystem. By embracing \"\n", " \"environmentally friendly practices, gardeners can have a positive impact on the \"\n", " \"planet.\",\n", " \"The Smartphone Revolution: Changing Communication. Smartphones have transformed \"\n", " \"how we communicate, offering unprecedented connectivity and convenience. This \"\n", " \"technology continues to evolve, shaping our daily interactions.\",\n", " \"Experiencing African Safaris: Wildlife and Wilderness. An African safari is an \"\n", " \"unforgettable experience that brings you face-to-face with the wonders of \"\n", " \"wildlife. It's a journey that connects you with the raw beauty of nature.\",\n", " \"Graphic Novels: A Blend of Art and Story. Graphic novels offer a unique medium \"\n", " \"where art and narrative intertwine to tell compelling stories. They challenge \"\n", " \"traditional forms of storytelling, offering visual and textual richness.\",\n", " \"Addressing Ocean Pollution: A Call to Action. The increasing levels of pollution \"\n", " \"in our oceans are a pressing environmental concern. Protecting marine life and \"\n", " \"ecosystems requires concerted global efforts.\",\n", " \"The Origins of Hip Hop: A Cultural Movement. Hip hop music, originating from the \"\n", " \"streets of New York, has grown into a powerful cultural movement. Its beats and \"\n", " \"lyrics reflect the experiences and voices of a community.\",\n", " \"Swimming: A Comprehensive Workout. Swimming offers a full-body workout that is \"\n", " \"both challenging and refreshing. It's an exercise that enhances cardiovascular \"\n", " \"health, builds muscle, and improves endurance.\",\n", " \"The Fall of the Berlin Wall: A Historical Turning Point. The fall of the Berlin \"\n", " \"Wall was not just a physical demolition; it was a symbol of political and social \"\n", " \"change. This historic event marked the end of an era and the beginning of a new \"\n", " \"chapter in world history.\",\n", "]\n", "\n", "# Write the corpus to a file\n", "corpus_file = \"/tmp/search_corpus.txt\"\n", "with open(corpus_file, \"w\") as file:\n", " for sentence in corpus:\n", " file.write(sentence + \"\\n\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Model Preparation and Configuration in MLflow\n", "Explore the steps to prepare and configure the Sentence Transformer model for integration with MLflow, essential for deployment readiness.\n", " \n", "#### Loading and Saving the Sentence Transformer Model\n", "\n", "- **Model Initialization**: Loading the `\"all-MiniLM-L6-v2\"` model, known for its balance in performance and speed, suitable for semantic search tasks.\n", "- **Model Storage**: Saving the model to a directory, essential for later deployment via MLflow. The choice of `/tmp/search_model` is for tutorial convenience so that your current working directory is not filled with the model files. You can change this to any location of your choosing.\n", "\n", "#### Preparing Model Artifacts and Signature\n", "\n", "- **Artifacts Dictionary**: Creating a dictionary with paths to model and corpus file, guiding MLflow to the components that are required to initialize the custom model object.\n", "- **Input Example and Test Output**: Defining sample input and output to illustrate the model's expected data formats.\n", "- **Model Signature**: Using `infer_signature` for automatic signature generation, encompassing input, output, and operational parameters.\n", "\n", "#### Importance of the Model Signature\n", "The signature ensures data consistency between training and deployment, enhancing model usability and reducing error potential. Having a signature specified ensures that type validation occurs at inference time, preventing unexpected behavior with invalid type conversions that could render incorrect or confusing inference results.\n", "\n", "#### Conclusion\n", "This comprehensive preparation process guarantees the model is deployment-ready, with all dependencies and operational requirements explicitly defined." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "inputs: \n", " [string]\n", "outputs: \n", " [string]\n", "params: \n", " ['top_k': long (default: 3), 'minimum_relevancy': double (default: 0.2)]" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Load a pre-trained sentence transformer model\n", "model = SentenceTransformer(\"all-MiniLM-L6-v2\")\n", "\n", "# Create an input example DataFrame\n", "input_example = [\"Something I want to find matches for.\"]\n", "\n", "# Save the model in the /tmp directory\n", "model_directory = \"/tmp/search_model\"\n", "model.save(model_directory)\n", "\n", "artifacts = {\"model_path\": model_directory, \"corpus_file\": corpus_file}\n", "\n", "# Generate test output for signature\n", "test_output = [\"match 1\", \"match 2\", \"match 3\"]\n", "\n", "# Define the signature associated with the model\n", "signature = infer_signature(\n", " input_example, test_output, params={\"top_k\": 3, \"minimum_relevancy\": 0.2}\n", ")\n", "\n", "# Visualize the signature\n", "signature" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Creating an experiment\n", "\n", "We create a new MLflow Experiment so that the run we're going to log our model to does not log to the default experiment and instead has its own contextually relevant entry." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# If you are running this tutorial in local mode, leave the next line commented out.\n", "# Otherwise, uncomment the following line and set your tracking uri to your local or remote tracking server.\n", "\n", "# mlflow.set_tracking_uri(\"http://127.0.0.1:8080\")\n", "\n", "mlflow.set_experiment(\"Semantic Similarity\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Logging the Model with MLflow\n", "Discover the process of logging the model in MLflow, a crucial step for managing and deploying the model within the MLflow framework.\n", "\n", "#### Starting an MLflow Run\n", "\n", "- **Context Management**: Initiating an MLflow run using `with mlflow.start_run()`, essential for tracking and managing model-related operations.\n", "\n", "#### Logging the Model\n", "\n", "- **Model Logging**: Utilizing `mlflow.pyfunc.log_model` to log the custom `SemanticSearchModel`, including key arguments like model name, instance, input example, signature, artifacts, and requirements.\n", "\n", "#### Outcome of Model Logging\n", "\n", "- **Model Registration**: Ensures the model is registered with all necessary components in MLflow, ready for deployment.\n", "- **Reproducibility and Traceability**: Facilitates consistent model deployment and tracks versioning and associated data.\n", "\n", "#### Conclusion\n", "Completing this critical step transitions the model from development to a deployment-ready state, encapsulated within the MLflow ecosystem." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "8642d786cb0d4f0b8a07689339885d45", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Downloading artifacts: 0%| | 0/11 [00:00