<?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[NADSOFT - Medium]]></title>
        <description><![CDATA[Technology implementation showcases - Medium]]></description>
        <link>https://medium.com/nadsoft?source=rss----83d143a57fdf---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>NADSOFT - Medium</title>
            <link>https://medium.com/nadsoft?source=rss----83d143a57fdf---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:26:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/nadsoft" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Supercharging Small Models with Grounding DINO, SAM, and AutoDistill for Dataset Creation]]></title>
            <link>https://medium.com/nadsoft/supercharging-small-models-with-grounding-dino-sam-and-autodistill-for-dataset-creation-94d66b8bdd6f?source=rss----83d143a57fdf---4</link>
            <guid isPermaLink="false">https://medium.com/p/94d66b8bdd6f</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ahmed Haytham]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 13:08:53 GMT</pubDate>
            <atom:updated>2024-09-26T13:08:17.025Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*67t17nDA_SOuQqLC5qKuMA.png" /></figure><p>In this thrilling adventure, we’re diving into the world of small yet mighty models for object detection and image segmentation. Our goal? Harness the power of large models to create efficient, high-quality datasets that can train faster, smaller models without compromising on performance. Let’s get started!</p><h3>The Journey Begins 🗺️</h3><p>This article is for those who are ready to build their own datasets using state-of-the-art models/tools like Grounding DINO, SAM, and AutoDistill. If you’ve ever been frustrated by slow models or the hassle of manual annotation, fear not! We’ll automate the process of generating labeled data and refine it using Roboflow to ensure quality.</p><h3>1. Introduction to Dataset Creation</h3><p>Creating a high-quality dataset is the foundation of any successful machine learning project. In this section, we’ll explore how to leverage large models like Grounding DINO and SAM to label images automatically. We’ll also refine those labels with tools like Roboflow, allowing for a smooth and efficient workflow.</p><p>In this adventure, we’ll focus on the essential steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yZUvzMGr2901Ejk2bgFG_g.png" /></figure><ul><li><strong>Grounding DINO</strong> for automatic detection based on text prompts</li><li><strong>Segment Anything Model (SAM)</strong> for precise image segmentation</li><li><strong>AutoDistill</strong> to streamline dataset creation</li><li><strong>Roboflow</strong> for label improvement and augmentation</li></ul><h4>1. Grounding</h4><p>Grounding connects AI knowledge to real-world examples, improving accuracy and reducing errors, especially in complex situations. In computer vision, it links text descriptions to specific image elements, helping machines interpret visuals using both language and images.</p><p><strong>Visual Grounding (VG) aims to locate the most relevant object or region in an image, based on a natural language query</strong></p><h4>2. <a href="https://arxiv.org/pdf/2104.14294">DINO</a></h4><p>DINO (self-distillation with no labels) is a self-supervised learning method by Facebook/metaAI for computer vision. It teaches itself by comparing different versions of the same image without human-labeled data, using a teacher-student method to recognize patterns.</p><h4>3. <a href="https://arxiv.org/pdf/2303.05499">Grounding-DINO</a></h4><p>Grounding DINO extends DINO with language capabilities, allowing it to detect and locate objects based on text descriptions. It excels in tasks like open-set object detection and language-based queries.</p><ul><li><strong>How it Works</strong>:</li><li>Encodes both image and text prompt</li><li>Combine these to generate a bboxs</li></ul><h4><a href="https://arxiv.org/pdf/2304.02643">4. Segment Anything Model (SAM)</a></h4><p>SAM, developed by Meta AI, segments any object in an image with just a click or a few points. It excels in applications from photo editing to scientific analysis. <strong>according to their </strong><a href="https://github.com/facebookresearch/segment-anything/issues/4"><strong>GitHub repo</strong></a><strong>, they didn’t implement text as input yet</strong></p><ul><li><strong>Key Features</strong>:</li><li>Zero-shot segmentation of unseen objects</li><li>Can be prompted with points, boxes, or text</li><li>Real-time mask generation</li><li>Handles object occlusion and overlap</li><li><strong>How it Works</strong>:</li><li>Encodes both image and prompt (e.g., point or box)</li><li>Combine these to generate a mask</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*mr7FJWuWFd6u_QgxPr7ywA.png" /></figure><h3>2. Testing the Teacher Model</h3><p>Before diving into labeling, we’ll first test our teacher model, a combination of Grounding DINO and SAM. These models will serve as our “teachers,” automatically labeling images based on the prompts we provide.</p><p>Start by installing the necessary packages:</p><pre>!pip3 install autodistill-grounded-sam roboflow autodistill-grounding-dino <br>!pip install -U ultralytics</pre><p>Next, define the base teacher model using an ontology to map object names (like “Bike,” “Person,” etc.) to the classes in your dataset. For example:</p><ol><li>Define an ontology to map class names to our GroundingDINO prompt</li><li>The ontology dictionary has the format {caption: class}. <strong>The caption </strong>should<strong> </strong>be a description of the object but in my case, it was good just for one word</li><li>where the caption is the prompt sent to the base model, and class is the label that will be saved for that caption in the generated annotations</li><li>box &amp; Text thresholds you can determine their value by test in random examples as I did</li></ol><pre>from autodistill_grounded_sam import GroundedSAM<br>from autodistill.detection import CaptionOntology<br>from autodistill.utils import plot<br>import cv2<br><br>base_model = GroundedSAM(<br>      box_threshold=0.4,<br>      text_threshold=0.4,<br>    ontology=CaptionOntology(<br>        {<br>            &quot;Bike&quot;: &quot;Bike&quot;,<br>            &quot;person&quot;:&quot;Person&quot;,<br>            &quot;helmet&quot;:&quot;Helmet&quot;<br>            <br>        }<br>    )<br>)</pre><h4>3. test on Random Examples</h4><p>Now, test the teacher model on random images to ensure it’s detecting objects correctly. This step lets you fine-tune your thresholds and prompts before scaling up.</p><pre>import supervision as sv<br>import matplotlib.pyplot as plt<br>from collections import Counter<br><br>path = &quot;/kaggle/input/sports-classification/train/bmx/001.jpg&quot;<br><br>def plot_annotated_image(path):<br>    image = cv2.imread(path)<br>    predictions = base_model.predict(path)<br><br>    annotator = sv.BoxAnnotator()<br>    label_annotator = sv.LabelAnnotator(text_position=sv.Position.CENTER_LEFT)<br>    mask_annotator = sv.MaskAnnotator()<br><br>    annotated_image = annotator.annotate(scene=image.copy(), detections=predictions)<br>    annotated_image = label_annotator.annotate(annotated_image, detections=predictions)<br>    annotated_image = mask_annotator.annotate(annotated_image, detections=predictions)<br>    <br>    # Count the occurrences of each class<br>    class_counts = Counter(predictions.class_id)<br>    class_names = {0: &#39;bikes&#39;, 1: &#39;persons&#39;, 2: &#39;helmets&#39;}<br>    <br>    # Create the title string<br>    title = &#39;, &#39;.join(f&quot;{count} {class_names[class_id]}&quot; for class_id, count in class_counts.items())<br>    <br>    plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))<br>    plt.title(title)<br>    <br>    sv.plot_image(annotated_image, size=(4, 4))<br>    <br>plot_annotated_image(path)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DeGY-vPJC0hPDI3Y02MtUA.png" /><figcaption>this image is made using canva the function just plot the image and image segmented</figcaption></figure><h3>3. Labeling the Dataset</h3><p>Once you’re satisfied with the teacher model’s performance, it’s time to label your dataset automatically. We’ll create a new folder to store our labeled images</p><pre>!mkdir datasets # make new folder for the dataset<br>base_model.label(<br>  input_folder=&quot;/kaggle/input/sports-classification/train/bmx&quot;,# image folder<br>  output_folder=&quot;/kaggle/working/datasets&quot;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*6Gw0k9Z7EYsSUeOf8GB-Lw.png" /><figcaption>The output</figcaption></figure><h3>4. Refining Labels with Roboflow</h3><p>While the automatic labels are a great start, they might need a bit of human refinement. Enter <strong>Roboflow</strong>, a powerful tool that lets you clean up annotations and augment your dataset with ease.</p><ol><li><strong>Create a Roboflow account</strong> and set up a workspace.</li><li><strong>Upload the dataset</strong> you just labeled to Roboflow.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLv7p_u1P7u1I4pkBsPFXg.png" /></figure><p>3. Then, get the project ID and the space key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FjCoS9Fpl4y5sRi71HeJwA.png" /></figure><pre>import roboflow<br>from kaggle_secrets import UserSecretsClient<br>user_secrets = UserSecretsClient()<br>secret_value_0 = user_secrets.get_secret(&quot;robo_flow_key&quot;)<br><br>rf = roboflow.Roboflow(api_key=secret_value_0)#space APi<br><br># get a workspace<br>workspace = rf.workspace(&quot;ahmed-haytham&quot;)# name of work space<br><br># Upload data set to a new/existing project<br>workspace.upload_dataset(<br>    &quot;/kaggle/working/datasets&quot;, # This is your dataset path<br>    &quot;bmx-waxnw&quot;,#project id # This will either create or get a dataset with the given ID<br>    num_workers=10,<br>    num_retries=0<br>)</pre><p>Roboflow allows you to edit labels, adjust bounding boxes or masks, and apply augmentations like rotations, flips, and noise. You can also split the dataset into training, validation, and test sets directly on the platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*-x9laza2uu408Pu6kRMe8w.png" /><figcaption>roboflow</figcaption></figure><h3>5. Downloading the Final Dataset</h3><p>Once your labels are refined, download the dataset in the format you need for training.</p><pre>from roboflow import Roboflow<br>rf = Roboflow(api_key=secret_value_0) # i canhged this to not make my key public<br>project = rf.workspace(&quot;ahmed-haytham&quot;).project(&quot;bmx-waxnw&quot;)<br>version = project.version(2)<br>dataset = version.download(&quot;yolov9&quot;) # roboflow will write it for you</pre><p>If necessary, update the paths in your dataset configuration file:</p><pre>import yaml<br><br>with open(&#39;path/to/your/data.yaml&#39;) as f:<br>    data = yaml.safe_load(f)<br><br>data[&#39;train&#39;] = &#39;/path/to/your/train/images&#39;<br>data[&#39;val&#39;] = &#39;/path/to/your/val/images&#39;<br><br>with open(&#39;path/to/your/data.yaml&#39;, &#39;w&#39;) as f:<br>    yaml.dump(data, f)</pre><p>Follow <a href="https://www.linkedin.com/in/ahmed-haytham/">Me</a> and <a href="https://www.linkedin.com/company/nadsoft/mycompany/">NADSOFT</a> for more</p><h3>Conclusion</h3><p>And that’s it! You&#39;ve made creating a dataset much easier by using models/tools like Grounding DINO, SAM, and AutoDistill. Now, your smaller models have a strong, well-labeled dataset from which to learn. With Roboflow, you’ve also fine-tuned the labels to make them as accurate as possible, setting things up for quicker and smarter training with models like YOLOv9. Ready for the next step? Let’s start training!</p><p>note I just used the yolov9 as an example</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94d66b8bdd6f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nadsoft/supercharging-small-models-with-grounding-dino-sam-and-autodistill-for-dataset-creation-94d66b8bdd6f">Supercharging Small Models with Grounding DINO, SAM, and AutoDistill for Dataset Creation</a> was originally published in <a href="https://medium.com/nadsoft">NADSOFT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Open Source Multi-Modal RAG System]]></title>
            <link>https://medium.com/nadsoft/building-an-open-source-multi-modal-rag-system-641271e4ef17?source=rss----83d143a57fdf---4</link>
            <guid isPermaLink="false">https://medium.com/p/641271e4ef17</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ahmed Haytham]]></dc:creator>
            <pubDate>Mon, 08 Jan 2024 08:56:11 GMT</pubDate>
            <atom:updated>2024-01-08T08:56:11.095Z</atom:updated>
            <content:encoded><![CDATA[<p>In this new adventure, we will delve into the process of constructing a Retrieval-Augmented Generation (RAG) system using an Open Source Large Language Multi-Modal (LLMM). Notably, our focus will be on achieving this without relying on LangChain or Llama index; instead, we will leverage ChromeDB and the Hugging Face framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*50oGw7UosQW0RPJGuw6gtw.png" /></figure><p>Let’s embark on this journey to explore and understand how to create an efficient RAG system, combining the power of open-source technologies such as ChromeDB and Hugging Face in the realm of Large Language Multi-Modal applications.</p><h3>The Map 🗺️</h3><ol><li>What is RAG (Retrieval-Augmented Generation)?</li><li>Why RAG?</li><li>What is multi-modals?</li><li>What is MLLM (multi-modal large language )?</li><li>Building RAG pipeline?</li><li>References and the code</li></ol><h3>What is RAG?</h3><p>Retrieval-Augmented Generation (RAG): Enhancing AI Understanding and Output</p><p>In the realm of artificial intelligence, Retrieval-Augmented Generation (RAG) stands out as a transformative technique, refining the capabilities of Large Language Models (LLMs). At its essence, RAG enhances the specificity of AI responses by allowing models to dynamically retrieve real-time information from external sources.</p><p>Large Language Models, like GPT-3, excel in generating human-like language but face limitations in providing up-to-date or domain-specific information. RAG addresses this by integrating a retrieval mechanism that pulls in relevant facts from external knowledge bases, ensuring responses are both linguistically sound and factually accurate.</p><p>The architecture seamlessly combines generative abilities with a dynamic retrieval process, enabling AI to adapt to evolving information in various domains. Unlike extensive retraining, RAG offers a cost-effective solution, allowing AI to stay current and relevant without overhauling the entire model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MESJbf9jAUgI0TWq" /></figure><p><strong><em>In other Words</em></strong></p><p>Imagine you have a super smart robot friend. This robot friend is good at talking and saying smart things, but sometimes it doesn’t know everything. Now, we have a special trick called Retrieval-Augmented Generation, or RAG for short.</p><p>RAG helps the robot friend become even smarter by looking up information from a big book of facts when it needs to answer a question or talk about something specific. So, instead of just saying things from its brain, it can now check this big book to make sure it’s giving the best and most accurate answers. It’s like having a cool encyclopedia for the robot friend, making it even more awesome to chat with us!</p><h3>Why RAG?</h3><ol><li><strong>Enhanced Accuracy and Reliability:</strong></li></ol><ul><li>RAG addresses the unpredictability of Large Language Models (LLMs) by redirecting them to authoritative knowledge sources.</li><li>It mitigates the risk of presenting false or outdated information, ensuring more accurate and reliable responses.</li></ul><p><strong>2. Increased Transparency and Trust:</strong></p><ul><li>Generative AI models, like LLMs, often lack transparency, making it challenging to trust their outputs.</li><li>RAG introduces transparency by allowing organizations to have greater control over the generated text output, addressing concerns about bias, reliability, and compliance.</li></ul><p><strong>3. Mitigation of Hallucinations:</strong></p><ul><li>LLMs are prone to generating hallucinated responses — coherent but inaccurate or fabricated information.</li><li>RAG helps mitigate this issue by ensuring that responses are grounded in authoritative sources, reducing the risk of misleading recommendations in critical sectors like finance.</li></ul><p><strong>4. Improved Decision-Making in High-Stakes Environments:</strong></p><ul><li>In sectors like finance, where accuracy, credibility, and timeliness are paramount, RAG significantly enhances performance.</li><li>Real-time updates and reliance on authoritative sources reduce the chance of catastrophic losses, regulatory issues, or costly mistakes in decision-making processes.</li></ul><p><strong>5. Cost-Effective Adaptability:</strong></p><ul><li>RAG provides a cost-effective approach to improving AI output without the need for extensive retraining / Fine-tuning.</li><li>Organizations can stay current and relevant by dynamically fetching specific details as needed, ensuring the AI’s adaptability to evolving information.</li></ul><h3>What is Multi-modal?</h3><p>Dear adventurer, consider this: when you hear someone’s voice, you recognize the person, and when you see them, you also know who they are. In essence, multi-modality involves having two inputs — audio and visual — and producing a single output, allowing for a richer and more comprehensive understanding.</p><p><strong><em>In other detailed words with CLIP as an example</em></strong></p><p>In simple terms, multimodal learning involves teaching computers / AI models to understand and learn from different types of information, like images, text, or speech. This is useful because it allows models to make better predictions, mimicking how humans learn.</p><blockquote>The model makes <em>same (very similar)</em> embedding vectors for different inputs that represent the same thing.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DbcZDqc7J1jwi9oI" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7GqiABVFjCvDH_9M" /></figure><p>like</p><ol><li><strong>Image2Text</strong>: This part focuses on improving the captioning of complex images using transformer-based architectures.</li><li><strong>Text2Image</strong>: Here, the idea is to use textual input to generate visual representations. Advances in Natural Language Processing (NLP) enable the encoding of text into embedding vectors, guiding the image generation process.</li><li><strong>Images supporting Language Models </strong>focuses on integrating visual elements into pure textual language models. While traditional models assume word meaning from text context alone, this task explores incorporating visual dimensions to enhance language models.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*r55EnjIK-xGCjPnzgNlCPQ.png" /></figure><p><strong><em>one good model as an example for it is </em></strong><a href="https://openai.com/research/clip"><strong><em>OpenAI CLIP</em></strong></a></p><p><strong>The CLIP model from open AI learns visual concepts from natural language supervision. CLIP can be applied to any visual classification benchmark by simply providing the names of the visual categories to be recognized, similar to the “zero-shot”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BxNzbFPQ1BidQbzE" /></figure><blockquote><em>In a simple manner, it generates the same (very similar) vector for an image of a cat and the word ‘cat’.</em></blockquote><h3>What is MLLM (multi-modal large language)?</h3><p>“Yes, you are right, the LLM is capable of vision.”</p><p>Like GPT4v and Gemini vision</p><p>the exploration of multimodal language models (MLLM) that integrate various data types, including images, text, language, audio, and more. While large language models (LLMs) like GPT-3, BERT, and RoBERTa excel in text-based tasks, they face challenges in understanding and processing other data types. To address this limitation, multimodal models combine different modalities, enabling a more comprehensive understanding of diverse data.</p><p><strong><em>Multi-Modal Large Language Models (MLLM): Revolutionizing Data Understanding</em></strong></p><p>Multimodal large language models (MLLM) represent a paradigm shift in natural language processing, extending beyond traditional text-based approaches. These models, exemplified by GPT-4, can seamlessly process diverse data types, including images and text, leading to a more holistic understanding of information. MLLMs address the limitations of pure text models by integrating various modalities, showcasing human-level performance in benchmark tests.</p><h3><strong>Building RAG pipeline?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gDmOto9dB964Tb3D.jpg" /></figure><p>We plan to create the RAG pipeline, which involves embedding images and texts using Clip. Subsequently, we intend to store this embedded data in the ChromDB vector database. Finally, we will leverage the MLLM from Hugging Face to engage in user chat sessions based on the retrieved information.</p><p>we will create a flower expert chat bot using images from Kaggle and informations from Wikipedia</p><ol><li>Install needed packages</li></ol><pre>! pip install -q timm einops wikipedia chromadb open_clip_torch<br>!pip install -q transformers==4.36.0<br>!pip install -q bitsandbytes==0.41.3 accelerate==0.25.0</pre><p>2. preprocess the data ==&gt; In this step you should do on your own but I just put the images and text in one folder like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*_VZ4RuoHmtFbcdYPSsm6_A.png" /></figure><p>3. Create the vector database; feel free to utilize any tool, but I recommend using ChromaDB.</p><p>3.1 first you need to determine the embedding function. I will use the default and show you how to create a custom one</p><pre>import chromadb<br><br>from chromadb.utils.embedding_functions import OpenCLIPEmbeddingFunction<br>from chromadb.utils.data_loaders import ImageLoader<br>from chromadb.config import Settings<br><br><br>client = chromadb.PersistentClient(path=&quot;DB&quot;)<br><br>embedding_function = OpenCLIPEmbeddingFunction()<br>image_loader = ImageLoader() # must be if you reads from URIs</pre><p>Custom Embed function</p><pre>from chromadb import Documents, EmbeddingFunction, Embeddings<br><br>class MyEmbeddingFunction(EmbeddingFunction):<br>    def __call__(self, input: Documents) -&gt; Embeddings:<br>        # embed the documents somehow or images<br>        return embeddings</pre><p>3.2 we will create 2 collections one for texts other for images</p><pre>collection_images = client.create_collection(<br>    name=&#39;multimodal_collection_images&#39;, <br>    embedding_function=embedding_function, <br>    data_loader=image_loader)<br><br>collection_text = client.create_collection(<br>    name=&#39;multimodal_collection_text&#39;, <br>    embedding_function=embedding_function, <br>    )<br><br># Get the Images<br>IMAGE_FOLDER = &#39;/kaggle/working/all_data&#39;<br><br><br>image_uris = sorted([os.path.join(IMAGE_FOLDER, image_name) for image_name in os.listdir(IMAGE_FOLDER) if not image_name.endswith(&#39;.txt&#39;)])<br>ids = [str(i) for i in range(len(image_uris))]<br><br>collection_images.add(ids=ids, uris=image_uris) #now we have the images collection </pre><p>. We use Clip we can retrieve images using text like this</p><pre>from matplotlib import pyplot as plt<br><br>retrieved = collection_images.query(query_texts=[&quot;tulip&quot;], include=[&#39;data&#39;], n_results=3)<br>for img in retrieved[&#39;data&#39;][0]:<br>    plt.imshow(img)<br>    plt.axis(&quot;off&quot;)<br>    plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*pvPbmFaIua27IH0wEZSssw.png" /><figcaption>there are more images but for space</figcaption></figure><p>. or using the image itself</p><pre>from PIL import Image<br>import numpy as np<br><br>query_image = np.array(Image.open(f&quot;/kaggle/input/flowers/flowers/daisy/0.jpg&quot;))<br>print(&quot;Query Image&quot;)<br>plt.imshow(query_image)<br>plt.axis(&#39;off&#39;)<br>plt.show()<br><br>print(&quot;Results&quot;)<br>retrieved = collection_images.query(query_images=[query_image], include=[&#39;data&#39;], n_results=3)<br>for img in retrieved[&#39;data&#39;][0][1:]:<br>    plt.imshow(img)<br>    plt.axis(&quot;off&quot;)<br>    plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*BGMlzl38zNLHO2z3_cZJBw.png" /></figure><p>3.3 The Text Collection</p><pre># now the text DB<br>from chromadb.utils import embedding_functions<br>default_ef = embedding_functions.DefaultEmbeddingFunction()<br><br>text_pth = sorted([os.path.join(IMAGE_FOLDER, image_name) for image_name in os.listdir(IMAGE_FOLDER) if image_name.endswith(&#39;.txt&#39;)])<br><br>list_of_text = []<br>for text in text_pth:<br>    with open(text, &#39;r&#39;) as f:<br>        text = f.read()<br>        list_of_text.append(text)<br><br>ids_txt_list = [&#39;id&#39;+str(i) for i in range(len(list_of_text))]<br>ids_txt_list<br><br>collection_text.add(<br>    documents = list_of_text,<br>    ids =ids_txt_list<br>)</pre><p>3.4 Retrieve text We used CLIP too in embedding so we can get by text or Embedings</p><pre>results = collection_text.query(<br>    query_texts=[&quot;What is the bellflower?&quot;],<br>    n_results=1<br>)<br><br>results</pre><pre>{&#39;ids&#39;: [[&#39;id0&#39;]],<br> &#39;distances&#39;: [[0.6072186183744086]],<br> &#39;metadatas&#39;: [[None]],<br> &#39;embeddings&#39;: None,<br> &#39;documents&#39;: [[&#39;Campanula () is the type genus of the Campanulaceae family of flowering plants. Campanula are commonly known as bellflowers and take both their common and scientific names from the bell-shaped flowers—campanula is Latin for &quot;little bell&quot;.\nThe genus includes over 500 species and several subspecies, distributed across the temperate and subtropical regions of the Northern Hemisphere, with centers of diversity in the Mediterranean region, Balkans, Caucasus and mountains of western Asia. The range also extends into mountains in tropical regions of Asia and Africa.\nThe species include annual, biennial and perennial plants, and vary in habit from dwarf arctic and alpine species under 5 cm high, to large temperate grassland and woodland species growing to 2 metres (6 ft 7 in) tall.&#39;]],<br> &#39;uris&#39;: None,<br> &#39;data&#39;: None}</pre><p>or using Embeddings</p><pre>query_image = &#39;/kaggle/input/flowers/flowers/rose/00f6e89a2f949f8165d5222955a5a37d.jpg&#39;<br>raw_image = Image.open(query_image)<br><br>doc = collection_text.query(<br>    query_embeddings=embedding_function(query_image),<br>    <br>    n_results=1,<br>        <br>)[&#39;documents&#39;][0][0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*StKRlEtwbh7aZRBudKwadA.png" /></figure><blockquote>A rose is either a woody perennial flowering plant of the genus Rosa (), in the family Rosaceae (), or the flower it bears. There are over three hundred species and tens of thousands of cultivars. They form a group of plants that can be erect shrubs, climbing, or trailing, with stems that are often armed with sharp prickles. Their flowers vary in size and shape and are usually large and showy, in colours ranging from white through yellows and reds. Most species are native to Asia, with smaller numbers native to Europe, North America, and northwestern Africa. Species, cultivars and hybrids are all widely grown for their beauty and often are fragrant. Roses have acquired cultural significance in many societies. Rose plants range in size from compact, miniature roses, to climbers that can reach seven meters in height. Different species hybridize easily, and this has been used in the development of the wide range of garden roses.</blockquote><p>4. now we should load the MLLM</p><p>I used a small one according to its repo this is how we can use it</p><pre>from huggingface_hub import hf_hub_download<br><br>hf_hub_download(repo_id=&quot;visheratin/LLaVA-3b&quot;, filename=&quot;configuration_llava.py&quot;, local_dir=&quot;./&quot;, force_download=True)<br>hf_hub_download(repo_id=&quot;visheratin/LLaVA-3b&quot;, filename=&quot;configuration_phi.py&quot;, local_dir=&quot;./&quot;, force_download=True)<br>hf_hub_download(repo_id=&quot;visheratin/LLaVA-3b&quot;, filename=&quot;modeling_llava.py&quot;, local_dir=&quot;./&quot;, force_download=True)<br>hf_hub_download(repo_id=&quot;visheratin/LLaVA-3b&quot;, filename=&quot;modeling_phi.py&quot;, local_dir=&quot;./&quot;, force_download=True)<br>hf_hub_download(repo_id=&quot;visheratin/LLaVA-3b&quot;, filename=&quot;processing_llava.py&quot;, local_dir=&quot;./&quot;, force_download=True)</pre><pre>from modeling_llava import LlavaForConditionalGeneration<br>import torch<br><br>model = LlavaForConditionalGeneration.from_pretrained(&quot;visheratin/LLaVA-3b&quot;)<br>model = model.to(&quot;cuda&quot;)</pre><pre>from transformers import AutoTokenizer<br><br>tokenizer = AutoTokenizer.from_pretrained(&quot;visheratin/LLaVA-3b&quot;)</pre><pre>from processing_llava import LlavaProcessor, OpenCLIPImageProcessor<br><br>image_processor = OpenCLIPImageProcessor(model.config.preprocess_config)<br>processor = LlavaProcessor(image_processor, tokenizer)</pre><p>5. let’s use it</p><pre>question = &#39;Answer with organized answers: What type of rose is in the picture? Mention some of its characteristics and how to take care of it ?&#39;<br><br>query_image = &#39;/kaggle/input/flowers/flowers/rose/00f6e89a2f949f8165d5222955a5a37d.jpg&#39;<br>raw_image = Image.open(query_image)<br><br>doc = collection_text.query(<br>    query_embeddings=embedding_function(query_image),<br>    <br>    n_results=1,<br>        <br>)[&#39;documents&#39;][0][0]<br><br>plt.imshow(raw_image)<br>plt.show()<br>imgs = collection_images.query(query_uris=query_image, include=[&#39;data&#39;], n_results=3)<br>for img in imgs[&#39;data&#39;][0][1:]:<br>    plt.imshow(img)<br>    plt.axis(&quot;off&quot;)<br>    plt.show()</pre><p>according to our input image, this is the most similar images we have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*MwpYtE-bQKSo5QKiJJHTyQ.png" /></figure><p>and this is the document has most information we need</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*5YBIv6feZmvRyKAKdU_1kw.png" /></figure><p>now let’s make the inputs ready for the model</p><pre>prompt = &quot;&quot;&quot;&lt;|im_start|&gt;system<br>A chat between a curious human and an artificial intelligence assistant.<br>The assistant is an exprt in flowers , and gives helpful, detailed, and polite answers to the human&#39;s questions.<br>The assistant does not hallucinate and pays very close attention to the details.&lt;|im_end|&gt;<br>&lt;|im_start|&gt;user<br>&lt;image&gt;<br>{question} Use the following article as an answer source. Do not write outside its scope unless you find your answer better {article} if you thin your answer is better add it after document.&lt;|im_end|&gt;<br>&lt;|im_start|&gt;assistant<br>&quot;&quot;&quot;.format(question=&#39;question&#39;, article=doc)</pre><pre>inputs = processor(prompt, raw_image, model, return_tensors=&#39;pt&#39;)<br><br>inputs[&#39;input_ids&#39;] = inputs[&#39;input_ids&#39;].to(model.device)<br>inputs[&#39;attention_mask&#39;] = inputs[&#39;attention_mask&#39;].to(model.device)</pre><pre>from transformers import TextStreamer<br><br>streamer = TextStreamer(tokenizer)</pre><pre>%%time<br>output = model.generate(**inputs, max_new_tokens=300, do_sample=True, top_p=0.5, temperature=0.2, eos_token_id=tokenizer.eos_token_id, streamer=streamer)</pre><pre>print(tokenizer.decode(output[0]).replace(prompt, &quot;&quot;).replace(&quot;&lt;|im_end|&gt;&quot;, &quot;&quot;))</pre><blockquote>A beautiful dark purple rose is in full bloom against a white background. The rose has a velvety texture and is surrounded by green leaves.</blockquote><blockquote><strong><em>the model is not good you can use other prompt or other model</em></strong></blockquote><blockquote>Follow <a href="https://www.linkedin.com/in/ahmed-haytham/">Me</a> and <a href="https://www.linkedin.com/company/nadsoft/mycompany/">NADSOFT</a> for more</blockquote><h3>References and the code</h3><p><a href="https://github.com/nadsoft-opensource/RAG-with-open-source-multi-modal">GitHub - nadsoft-opensource/RAG-with-open-source-multi-modal</a></p><p>Ref</p><ol><li><a href="https://www.kaggle.com/ahmedhaytham/rag-with-open-source-multi-modal">https://www.kaggle.com/ahmedhaytham/rag-with-open-source-multi-modal</a></li><li><a href="https://blogs.nvidia.com/blog/what-is-retrieval-augmented-generation/">https://blogs.nvidia.com/blog/what-is-retrieval-augmented-generation/</a></li><li><a href="https://aws.amazon.com/what-is/retrieval-augmented-generation/#:~:text=Retrieval%2DAugmented%20Generation%20(RAG),sources%20before%20generating%20a%20response.">https://aws.amazon.com/what-is/retrieval-augmented-generation/#:~:text=Retrieval%2DAugmented%20Generation%20(RAG),sources%20before%20generating%20a%20response.</a></li><li><a href="https://arxiv.org/pdf/2311.13165.pdf">https://arxiv.org/pdf/2311.13165.pdf</a></li><li><a href="https://docs.trychroma.com/">https://docs.trychroma.com/</a></li><li><a href="https://arxiv.org/abs/2301.04856">https://arxiv.org/abs/2301.04856</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=641271e4ef17" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nadsoft/building-an-open-source-multi-modal-rag-system-641271e4ef17">Building an Open Source Multi-Modal RAG System</a> was originally published in <a href="https://medium.com/nadsoft">NADSOFT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cost-effective AI model deployment]]></title>
            <link>https://medium.com/nadsoft/cost-effective-ai-model-deployment-4af377da3bc8?source=rss----83d143a57fdf---4</link>
            <guid isPermaLink="false">https://medium.com/p/4af377da3bc8</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[cost-effective]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ibrahim Jabarin]]></dc:creator>
            <pubDate>Tue, 26 Dec 2023 16:07:37 GMT</pubDate>
            <atom:updated>2023-12-26T16:09:59.979Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*317RCOUTQhYX-our" /><figcaption>Photo by <a href="https://unsplash.com/@neonbrand?utm_source=medium&amp;utm_medium=referral">Kenny Eliason</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It is well-recognized among technology professionals that deploying and operating an AI model in production can be very expensive. This has become particularly evident with the increasing prevalence of Large Language Models (LLMs) that necessitate substantial GPU power as a fundamental requirement for executing tasks.</p><p>GPU instances are now accessible from the three primary cloud providers: AWS, GCP, and Azure, with prices that are generally similar.</p><p>In this showcase, we’ll demonstrate the architectural solution for operating an ASR (Automatic Speech Recognition) model and how we implemented a serverless (pay-as-you-use) approach on the AWS platform to minimize costs.</p><h3>Understanding the Need</h3><p>In the process of creating a product that employs an ASR model for transcribing meeting recordings, we utilized Hamsa, an ASR model crafted by NADSOFT. This model excels in converting speech from various Arabic dialects into text and is based on the Whisper architecture.</p><p>To function effectively, it requires an instance equipped with at least one GPU unit and approximately 32GiB of memory. AWS caters to these needs through its g4 instance family, which it offers at an on-demand rate of $1.204 per hour, amounting to roughly $900 per month.</p><h3>Leveraging a Serverless Strategy</h3><p>Considering the asynchronous nature of our task and the unnecessary costs incurred from maintaining an idle instance, we opted for a serverless deployment strategy utilizing AWS Batch with Spot Instances. This approach allows us to effectively manage resources and reduce expenses by only using services when they’re actively needed.</p><blockquote><strong>AWS Batch</strong> is a cloud service for efficiently running batch jobs on AWS, automatically scaling and provisioning resources as needed. It adjusts to the job’s demands, allowing for flexible application scaling and resource management.</blockquote><blockquote><strong>Spot Instances</strong> are an AWS feature offering unused EC2 capacity at reduced prices, ideal for flexible, non-critical tasks. Prices fluctuate based on supply and demand, and instances may be interrupted if demand rises. They provide significant cost savings for suitable workloads.</blockquote><h3>Solution Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aPaqUFByMJQkC1qeuV7jVg.jpeg" /></figure><p>The diagrammed solution achieves high availability through serverless services and deployment across multiple Availability Zones (AZs). The process initiates when the API Gateway Endpoint is triggered, creating a job in AWS Batch.</p><p>This job then requests a Spot Instance via the Spot Fleet. Upon availability, the instance retrieves the Docker image from ECR and launches the server to execute the task.</p><p>The Spot Instance operates within a private VPC, ensuring connectivity to other services like DocumentDB and S3.</p><p>Completion of the Batch Job activates an SNS topic, which in turn triggers a Lambda function to finalize the process.</p><p>This approach led to a cost reduction of about 65%, thanks to the “SPOT_PRICE_CAPACITY_OPTIMIZED” allocation strategy, which secures the most economical pricing for Spot Instances. As shown in the image below, the price for the desired instance type as a Spot Instance is approximately 40% of the standard on-demand rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueCtu9B3HW4h7Ll_F8IUWg.png" /></figure><p>This design ensures payment only for actual usage, avoids costs for idle resources, and supports a scalable environment to handle substantial workloads efficiently.</p><p>This article demonstrated strategies for cost reduction in deploying AI models to production, reflecting the expertise and shared knowledge of the NADSOFT team.</p><p>For additional information or inquiries, please feel free to leave a comment or contact us at <a href="/service/mailto:medium@nadsoft.net">medium@nadsoft.net</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4af377da3bc8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nadsoft/cost-effective-ai-model-deployment-4af377da3bc8">Cost-effective AI model deployment</a> was originally published in <a href="https://medium.com/nadsoft">NADSOFT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>