<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ekaterina Butyugina on Medium]]></title>
        <description><![CDATA[Stories by Ekaterina Butyugina on Medium]]></description>
        <link>https://medium.com/@ekaterinab?source=rss-3e562471a8a9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jGe5oVh4bQ00oJeg</url>
            <title>Stories by Ekaterina Butyugina on Medium</title>
            <link>https://medium.com/@ekaterinab?source=rss-3e562471a8a9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:36:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ekaterinab/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Are NPUs the future?]]></title>
            <link>https://medium.com/@ekaterinab/are-npus-the-future-5ce7e2a92b3a?source=rss-3e562471a8a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ce7e2a92b3a</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[cpu]]></category>
            <category><![CDATA[experiment]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[npu]]></category>
            <dc:creator><![CDATA[Ekaterina Butyugina]]></dc:creator>
            <pubDate>Wed, 11 Jun 2025 15:04:22 GMT</pubDate>
            <atom:updated>2025-06-11T15:07:47.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*vHgBqRr5gYUkcXGvM-KkZA.png" /><figcaption>GPU, NPU, and CPU capabilities (<a href="https://download.intel.com/newsroom/2024/client-computing/Intel-Core-Ultra-Series-2-Media-Deck.pdf">source</a>)</figcaption></figure><h3>Showcasing local AI on mobile workstations using CPU, GPU and NPU capabilities</h3><p>Hello, I’m Ekaterina, a Program Manager for Data Science and Generative AI intensive courses at <a href="https://academy.constructor.org/">Constructor Academy</a>, Zurich. In this blog, I want to talk about the projects that we do with the students.</p><p>For the capstone projects that our students perform at the end of their training, we collaborate with different companies. We’ve had a vast amount of data-related projects — from times-series forecasting to creating the RAG pipelines and chatbots. Late last year we received a special request from HP: to explore the NPU capabilities of their newest machines: ZBook Power (Intel Core U9, RTX 3000 Ada, 64GB) and the ZBook Firefly (Intel Core U7, RTX A500, 32 GB).</p><p>As you know, <a href="https://www.hp.com/us-en/home.html">HP</a> is a global leader in computing and innovation, developing cutting-edge technology for professionals and businesses. They recently introduced the new generations of mobile workstations with NPUs. NPUs are specialized processors designed for AI and machine learning tasks. They are ideal for Natural Language Processing (NLP) and computer vision applications, reducing the load on the CPU and GPU and offering high performance. Despite their potential, many customers and partners struggle to see the benefits of using AI-powered devices or running AI workloads locally instead of in the cloud.</p><p>To address this, the team of our students developed an application running local AI models on three different tasks — chatbot, image classification, and image segmentation — to evaluate NPU performance in AI-driven tasks, comparing it with CPUs and GPUs.</p><p>The project measures <strong>utilization</strong>, <strong>offloading</strong>, <strong>elapsed time</strong>, <strong>latency</strong> and <strong>throughput</strong> across different processing units (CPU, GPU, and NPU). To fully utilize the capabilities of a local AI workstation, the goal was to implement the solution locally, leverage state-of-the-art AI tools, and develop a dashboard to monitor system performance. As part of this effort, the team developed a range of AI tasks including natural language processing with an AI chatbot functionality, and computer vision with image classification, and object detection.</p><h3>Chatbot</h3><p>The chatbot is designed specifically for HP users, leveraging large language models (LLM) and retrieval-augmented generation (RAG) to provide answers about the workstations, specs, and recommendations. The chatbot retrieves information from preloaded HP PDFs documents. Unlike cloud-based AI assistants, it runs entirely locally, ensuring complete data privacy.</p><p>The self-RAG model with which the chatbot was designed evaluates the relevance of the user’s question against the available source of information. This ensures the generated answer is based on accurate relevant information that matches the question.</p><h3>Image classification</h3><p>Image classification allows a computer to recognize objects in an image and categorize them. For instance, if you upload a picture of a dog, the model predicts the breed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/0*NzTsIjj51gdjcVTd.png" /></figure><p>Going beyond basic image recognition, there are many practical applications in various industries, such as AI-powered quality control in manufacturing, secure on-device document processing for ID verification in finance, enhanced document scanning and automation in smart offices, and X-ray or MRI analysis in medical imaging without relying on the cloud. The key metrics we are looking at here are:</p><ul><li><strong>Elapsed time:</strong> Total time from start to result.</li><li><strong>Latency:</strong> Time per inference (The process where the AI model makes a prediction, the lower the better).</li><li><strong>Throughput:</strong> Number of inferences per second (the higher the better).</li></ul><h3>Object detection</h3><p>Object detection goes beyond classification; it identifies multiple objects within an image. This is a key technology in computer vision applications, such as self-driving cars or security surveillance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/0*loOmdsxU1LzcZzkG.png" /></figure><h3>Performance</h3><p>To evaluate performance, the app runs a benchmark test using 128 images, measuring the average processing time per image and the number of frames per second (FPS) where a higher value means smoother real-time detection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/0*kCCo4UJNW8rYjcO5.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/0*VkjaltbTsS5zL3a0.png" /></figure><p><strong>CPU (Central Processing Unit): </strong>The CPU is a general-purpose processor designed to handle a wide variety of tasks. While it offers versatility and precision, it typically operates at a slower pace when managing large-scale parallel operations, such as those common in AI workloads.</p><p><strong>GPU (Graphics Processing Unit):</strong> GPUs are optimized for parallel processing, making them well-suited for breaking down large tasks into smaller, simultaneous computations. This architecture is especially effective for training AI models. However, GPUs are relatively large and consume significantly more power.</p><p><strong>NPU (Neural Processing Unit):</strong> NPUs are specialized processors built specifically for AI-related tasks. They strike a balance between the flexibility of CPUs and the parallel processing power of GPUs, while maintaining lower energy consumption. NPUs are designed to efficiently offload AI workloads from the CPU and GPU, enabling smoother performance even during complex or multitasking scenarios. This makes them a practical choice for everyday users who need AI capabilities without the high power demands of a GPU.</p><p>This project highlights the potential of Intel-powered HP AI PCs to run demanding AI tasks locally, demonstrating the growing viability of edge computing. By integrating a local LLM chatbot with RAG, image classification, object detection, and real-time resource monitoring, the app showcases how CPUs, GPUs, and NPUs perform across various AI workloads.</p><p>NPUs, in particular, offer a compelling combination of efficiency, speed, and responsiveness — making advanced AI applications accessible even on lightweight, mobile workstations. For professionals seeking performance without compromising on power consumption or data privacy, NPU-enabled devices represent a future-ready upgrade.</p><p>While challenges remain — such as broader software support and improved developer tooling — continued investment and real-world benchmarking will drive adoption. As this project demonstrates, the shift toward AI-powered workflows is well underway, and NPUs are poised to play a key role.</p><p>Watch the app in action in this youtube video: <a href="https://www.youtube.com/watch?v=-Scx6FyJm9M&amp;t=1s">Are NPU the future?</a> (start from 8:45).</p><h3>Conclusion</h3><p>Our findings conclude that for AI-efficient tasks <strong>CPUs</strong> handle general-purpose computations and sequential logic, while <strong>GPUs</strong>, with their parallel processing capabilities, excel at training large, complex AI models and large-scale inference. <strong>NPUs</strong> are specialized for highly efficient, low-power AI inference on edge devices, making them ideal for real-time applications where data privacy and minimal latency are critical — for example, optimizing local software like new AI-powered tools in Paint. Ultimately, these units complement each other in a heterogeneous computing environment, optimizing performance and power consumption across the entire AI pipeline from training to deployment.</p><p>If you’ve ever tried to program an NPU, you know that this specialization comes with its own unique set of challenges, from navigating specific toolchains to optimizing models for these highly efficient architectures. I’d love to hear about your experiences and the hurdles you encountered. Feel free to share!</p><p>Stay tuned for more insights into the exciting world of AI!</p><p>This demo was made by our graduates <a href="https://www.linkedin.com/in/jan-r-3317332ba/">Jan Roesnick</a>, <a href="https://www.linkedin.com/in/kristina-liang-715857124/">Kristina Liang</a>, <a href="https://www.linkedin.com/in/marisa-j-davis/">Marisa Davis</a>, and <a href="https://www.linkedin.com/in/natalianeamtu/">Natalia Neamtu</a> with support from <a href="https://www.linkedin.com/in/sebastiangottschalk/">Sebastian Gottschalk</a> and <a href="https://www.linkedin.com/in/stefaniewedel/">Stefanie Wedel</a>. Feel free to contact us if you have any questions or want to ask about the details of the project or request code.</p><p>*As a <a href="https://www.hp.com/us-en/workstations/industries/data-science/ambassador-ekaterina-butyugina.html"><strong>Z by HP Global Data Science Ambassador</strong></a>, I have been provided with HP products to facilitate our innovative work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ce7e2a92b3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Commercial, Gated, and Open-Source LLMs in Your File QA Chatbot: Step-by-Step Instructions]]></title>
            <link>https://medium.com/@ekaterinab/integrating-diverse-llms-into-a-file-qa-chatbot-e0e12c91e47e?source=rss-3e562471a8a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0e12c91e47e</guid>
            <category><![CDATA[gemma]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[mistral]]></category>
            <dc:creator><![CDATA[Ekaterina Butyugina]]></dc:creator>
            <pubDate>Tue, 30 Apr 2024 17:37:37 GMT</pubDate>
            <atom:updated>2024-05-01T11:24:15.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fV7kd_ED6ccz55AnFOf6Og.png" /><figcaption>Mistral, Gemma, and ChatGPT are dedicated to serving humanity (AI generated by DALL-E)</figcaption></figure><p>Hello again, I’m Ekaterina, a Program Manager for Data Science and Generative AI courses at Constructor Academy, Zurich. In my second blog, I’ll talk about how to create an interactive app based on ChatGPT, Mistral, and Gemma to chat with your files. For this purpose I will use my GPU NVIDIA RTX A5000-powered HP ZBook Fury to work with local LLMs and also OpenAI API to work with the gpt-3.5-turbo model.</p><h3>The Inspiration and Setup</h3><p>In today’s fast-paced digital world, the demand for quick and reliable information retrieval is more pressing than ever. To be fair I created the first version of the app using ChatGPT API before this functionality was added as default to ChatGPT itself. Later on it occurred to me that not everyone is comfortable uploading their private or sensitive documents — such as medical records or legal papers — to the cloud, and there was a need to explore local LLMs.</p><p>I was lucky that once I decided to complete this app’s functionality there were two new open-source state-of-the-art models launched by Google (<a href="https://blog.google/technology/developers/gemma-open-models/">Gemma</a>) and Mistral AI (<a href="https://arxiv.org/abs/2310.06825">Mistral 7B</a>). I immediately employed these innovations, setting the stage for the integration of three distinct types of models — <strong>Commercial, Gated</strong>, and <strong>Open-Source</strong> LLMs — into my File QA Chatbot.</p><p>I will show you the main parts of <a href="https://github.com/ekaterinabutyugina/qachatbot/tree/main?tab=readme-ov-file">this GitHub repo</a>, in which you can find the full code and further details.</p><p>This <a href="https://chatbot-docs.streamlit.app/">Streamlit app</a> allows users to upload text articles in &quot;txt&quot;,&quot;md&quot; or &quot;pdf&quot; formats and ask questions about the content of these articles. You can check the video below to see how it works on my laptop:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGkGSNyTHncE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGkGSNyTHncE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGkGSNyTHncE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/407fd799d5eee77f28bce26a7a7bd709/href">https://medium.com/media/407fd799d5eee77f28bce26a7a7bd709/href</a></iframe><h3>Building the Chatbot Interface and Basic Functionality</h3><p>Using <a href="https://www.streamlit.io/">Streamlit</a>, an open-source Python app framework, I created a basic interactive interface, and provided functionality descriptions:</p><pre>import streamlit as st<br>st.title(&quot;📝 File Q&amp;A with LLMs&quot;)<br>st.write(&quot;This app will help you to chat with your docs and files&quot;)</pre><p>The next step is to upload the file:</p><pre>uploaded_file = st.file_uploader(&quot; **Upload an article** &quot;, type=(&quot;txt&quot;, &quot;md&quot;, &quot;pdf&quot;))</pre><p>And also provide an opportunity to ask a question. This will be an input from the user:</p><pre>question = st.text_input(<br>    &quot; **Ask something about the article. For example:**&quot;,<br>    value = &quot;Can you give me a short summary?&quot;,<br>    placeholder=&quot;Can you give me a short summary?&quot;,<br>    disabled=not uploaded_file, <br>)</pre><p>In the code above I created a default value which directly suggests to start from summarizing the article, which is the most common need (at least for me). The input window is disabled when the file is not uploaded.</p><p>Next, we need to parse the documents. And the first challenge comes with the limited functionality to read the &quot;pdf&quot; files. Streamlit has a native function to read &quot;txt&quot; and&quot;md&quot; files: st.file_uploader(“file_name.txt”).read().decode() but not the &quot;pdf&quot; files. That’s why I used the pdfminer package.</p><p>Once we have a parsed file and a question, all we need to do is to create a proper prompt:</p><pre>article = uploaded_file.read().decode()<br>my_prompt = f&quot;&quot;&quot;Here&#39;s an article:{article}.\n\n<br>    \n\n\n\n{question}&quot;&quot;&quot;</pre><p>And voilà — our skeleton is ready and you can run it by the following bash command in your terminal:</p><pre>streamlit run qachatbot.py</pre><p>Once you’ve successfully tested your app, the next step is to integrate the models.</p><h3>Integrating the LLMs</h3><p>The backend, powered by three different models, parses the text and generates responses in real time.</p><h4>ChatGPT</h4><p>First model is an example of a <strong>commercial </strong>model. I usegpt-3.5-turbo-instruct, which I can access from <a href="https://platform.openai.com/account/api-keys">OpenAI API</a> with my API key. In the app I created a functionality for a user to add their own key so that I do not run out of money due to big requests.</p><pre>openai_api_key = st.text_input(&quot;OpenAI API Key&quot;, key=&quot;chatbot_api_key&quot;, type=&quot;password&quot;)</pre><p>In case you want to deploy this QA chatbot locally, you can use the chatgpt_api_credentials.yml file and read your key from there as follows:</p><pre>try:<br>    with open(&#39;chatgpt_api_credentials.yml&#39;, &#39;r&#39;) as file:<br>        creds = yaml.safe_load(file)<br>except:<br>    creds = {}</pre><p>There is also an option to use the Secrets tab in Streamlit settings itself. <a href="https://docs.streamlit.io/deploy/streamlit-community-cloud/deploy-your-app/secrets-management">Here</a> you can find more instructions on how to do it.</p><p>Once the authentication, the question, and the file to read are provided</p><pre>if uploaded_file and question and openai_api_key:</pre><p>you can connect to the model using the following script:</p><pre>openai.api_key = openai_api_key<br>    response = openai.Completion.create(<br>        model=&quot;gpt-3.5-turbo-instruct&quot;,<br>        prompt=my_prompt,<br>        max_tokens=200,<br>    )<br>    st.write(&quot;### Answer from ChatGPT&quot;)<br>    st.write(response[&#39;choices&#39;][0][&#39;text&#39;])</pre><p>You get a json dictionary as response and in order to get to your answer you need to choose the correct key. In this case it is response[&#39;choices&#39;][0][&#39;text&#39;].</p><h4>Mistral 7B</h4><p>The second model I tested was one of the most recent <strong>open source</strong> models <a href="https://arxiv.org/abs/2310.06825">Mistral 7B</a> which I can access from <a href="https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2">Hugging Face</a>. Mistral AI brings the strongest open generative models to the developers, along with efficient ways to deploy and customize them for production. I use Mistral-7B-Instruct-v0.2 or Mistral-tiny. This is the most cost-effective endpoint currently, a new minor release of Mistral 7B Instruct. Mistral-tiny only works in English.</p><p>In order to run it I need to make sure my GPU is connected, otherwise the chatbot computing time will exceed the reasonable limits to get the answer. Fortunately, my <a href="https://www.hp.com/us-en/workstations/zbook-fury.html">ZbyHP</a> laptop is powerful enough.</p><pre>has_cuda = torch.cuda.is_available()<br><br>if not has_cuda:<br>    st.write(&quot;Please use another lighter model&quot;)<br><br>else:<br>    st.write(&quot;### Answer from Mistral&quot;)<br>    model_id = &quot;mistralai/Mistral-7B-Instruct-v0.2&quot;<br><br>    model, tokenizer =  get_mistral_model_and_tokenizer(model_id)<br><br>    sequences = model(<br>    my_prompt,<br>    max_length=1024,<br>    truncation=&#39;only_first&#39;,<br>    do_sample=True,<br>    return_full_text=False,<br>    temperature=0.01<br>    )<br>   <br>    st.write(sequences[0][&#39;generated_text&#39;])</pre><p>This will give us the reasonable answer locally, in case, for instance, you work with private data files. The time needed to generate an answer is about 5–10 minutes. Having more GPU resources should help to reduce the time.</p><h4>Gemma</h4><p>Last but not least, I used a lighter <a href="https://blog.google/technology/developers/gemma-open-models/">Gemma</a> 2B which can also be downloaded from <a href="https://huggingface.co/google/gemma-2b-it">HuggingFace</a>. Gemma, according to its description, is a family of lightweight, state-of-the-art open models built from the same research and technology used to create the <a href="https://deepmind.google/technologies/gemini/#introduction">Gemini</a> models. Developed by Google DeepMind and other teams across Google it was released 2 months ago. Its relatively small size makes it possible to deploy it in environments with limited resources such as a laptop, desktop or your own cloud infrastructure, democratizing access to state of the art AI models and helping foster innovation for everyone.</p><p>Despite its open-source label, Gemma is only partially open, as it operates as a <strong>gated model</strong>, requiring access permission to use. This means you need to authenticate and provide your credentials somewhere in the code. I did it using the above-mentioned Secrets management in Streamlit. Provide your key in TOML format as follows:</p><pre>HF_token = &quot;hf_yoursecretkeyishere&quot; </pre><p>And later on use it in the code:</p><pre>from huggingface_hub import login<br>login(st.secrets[&quot;HF_token&quot;])</pre><p>Then, as with Mistral, we need to make sure the GPU is enabled:</p><pre>has_cuda = torch.cuda.is_available()</pre><p>If yes, we’ll come to the good part by calling the model and providing a prompt as follows:</p><pre>st.write(&quot;### Answer from Gemma&quot;)<br>  model_id = &quot;google/gemma-2b-it&quot;<br><br>  model, tokenizer = get_gemma_model_and_tokenizer(model_id, has_cuda)<br><br>  chat = [<br>      { &quot;role&quot;: &quot;user&quot;, &quot;content&quot;:  my_prompt },<br>  ]<br><br>  prompt = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)<br>  inputs = tokenizer.encode(prompt, add_special_tokens=False, return_tensors=&quot;pt&quot;)<br>  <br>  outputs = model.generate(input_ids = inputs.to(model.device),  max_new_tokens=150)<br>  <br>  st.write(<br>      tokenizer.decode(outputs[0])<br>      [len(chat[0][&#39;content&#39;]) + 59: -5]<br>      )</pre><p>Gemma’s behavior is slightly different from that of the other two models. It outputs extra characters including the whole prompt and some meta-data, that’s why I bound the answer by the length of the prompt plus some extra.</p><h3>Challenges and Learnings</h3><p>Here I need to specifically mention get_mistral_model_and_tokenizer() and get_gemma_model_and_tokenizer() functions.</p><p>In order to avoid re-tokenizing and re-loading the model every time I ask a question to a file, I decided to utilize the <a href="https://docs.streamlit.io/develop/concepts/architecture/caching#stcache_resource">caching functionality</a> of Streamlit.</p><p>@st.cache_resource is the command to cache “resources” that should be available globally across all users, sessions, and reruns. Using this decorator before the loading function helps me to save resources:</p><pre>@st.cache_resource <br>def get_mistral_model_and_tokenizer(model_id): <br>    tokenizer = AutoTokenizer.from_pretrained(model_id)<br>    model = transformers.pipeline(<br>        &quot;text-generation&quot;,<br>        model=model_id,<br>        tokenizer=tokenizer,<br>        torch_dtype=torch.float32,<br>        trust_remote_code=True,<br>        device_map=&quot;auto&quot;,<br>    )<br>    return model, tokenizer</pre><p>I created a similar function to load Gemma as well.</p><p>Tokenization takes about the same time as the answer generation. So using the code above will save us 50% of the time after the first model run.</p><p>Another comment I want to make is if you run your python script locally on a WSL Ubuntu machine, you might need to use this script streamlit run qachatbot.py — server.enableXsrfProtection false instead of simply streamlit run qachatbot.py as Cross-Site Request Forgery (XSRF) protection can interfere with the normal operation of your application. However, it’s important to note that disabling XSRF protection reduces the security of your application by making it more susceptible to cross-site request forgery attacks. Therefore, this should only be done if absolutely necessary and not in production environments.</p><h3>Conclusion:</h3><p>As a conclusion, I want to say that by employing the strengths of ChatGPT, Mistral, and Gemma within a single application, we have explored what’s possible in the realm of personal computing with LLMs. This proves once again that with the right tools and a bit of ingenuity, anyone can bring state-of-the-art AI solutions into their everyday workflow.</p><p>I would encourage all the aspiring developers and data scientists to explore the possibilities of AI and make your first steps with LLMs already now.</p><p>Hope you enjoyed the reading. I will be happy to answer your questions, and chat with you about AI and Data Science in general. Let’s create a future together!</p><p>As a <a href="https://www.hp.com/us-en/workstations/industries/data-science/ambassador-ekaterina-butyugina.html"><strong>Z by HP Global Data Science Ambassador</strong></a>, I have been provided with HP products to facilitate our innovative work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0e12c91e47e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-Tuning Transformers with On-Device GPU Resources]]></title>
            <link>https://medium.com/@ekaterinab/fine-tuning-transformers-with-on-device-gpu-resources-c89c7142cdde?source=rss-3e562471a8a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c89c7142cdde</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[summarization]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[gpu-computing]]></category>
            <dc:creator><![CDATA[Ekaterina Butyugina]]></dc:creator>
            <pubDate>Sun, 11 Feb 2024 19:59:02 GMT</pubDate>
            <atom:updated>2024-02-11T19:59:02.020Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vq-U81_dbIvwSE7OmGMmGA.jpeg" /></figure><p>Hello, I’m Ekaterina, a Program Manager for Data Science and Generative AI courses at <a href="https://academy.constructor.org/data-science/zurich">Constructor Academy</a>, Zurich. In this blog, I’ll walk you through fine-tuning the transformer model for a summarization task locally, specifically on a GPU NVIDIA RTX A5000-powered HP ZBook Fury*.</p><p><strong>The Importance of Summarization in NLP:</strong></p><p>Summarization in Natural Language Processing (NLP) is a crucial task due to its applications in research and business. It addresses the issue of information overload and enhances time efficiency by distilling long documents into their essence.</p><p><strong>Transformer Models — The Backbone of Generative AI:</strong></p><p>Transformer model is a type of generative AI. They can generate new content based on the input they receive. This architecture is behind many well-known AI models like GPT (Generative Pretrained Transformer), BERT (Bidirectional Encoder Representations from Transformers), and others, which, besides the summarization, are capable of generating text, answering questions, and more.</p><p><strong>Why Local GPU?</strong></p><p>Choosing between a local GPU and a cloud service depends on factors like performance needs, data privacy concerns, cost, internet stability, and the nature of your work. For many professionals and researchers, the advantages of a local GPU make it a preferred choice for demanding computational tasks.</p><p>I will show you the main parts of <a href="https://github.com/ekaterinabutyugina/summarization_with_transformers">this notebook</a>, in which you can find the full code, explanations and examples.</p><p><strong>Abstractive Text Summarization:</strong></p><p>In contrast to Extractive text summarization technique, where only a key subset of a content is extracted and no new content is generated, abstractive text summarization involves use of natural language generation techniques where the machine makes use of knowledge bases and semantic representations to generate text on its own and create summaries just like a human would write them.</p><p><strong>Setting Up the Environment:</strong></p><p>First, we install libraries for handling datasets and transformers.</p><pre>!pip install datasets<br>!pip install transformers</pre><p>We’ll use the CNN/Daily Mail news articles <a href="https://huggingface.co/datasets/cnn_dailymail">dataset</a>, which includes full articles and summaries, perfect for training our model.</p><pre>from datasets import load_dataset, load_metric<br>cnn_data = load_dataset(&quot;cnn_dailymail&quot;, &#39;3.0.0&#39;)</pre><p>The example article from this dataset will look like a dictionary with the following content:</p><pre>{&#39;article&#39;: [&#39;LONDON, England (Reuters) -- Harry Potter star Daniel Radcliffe gains access to a reported £20 million ($41.1 million) fortune as he turns 18 on Monday, but he insists the money won\&#39;t cast a spell on him. Daniel Radcliffe as Harry Potter in &quot;Harry Potter and the Order of the Phoenix&quot; To the disappointment of gossip columnists around the world, the young actor says he has no plans to fritter his cash away on fast cars, drink and celebrity parties. &quot;I don\&#39;t plan to be one of those people who, as soon as they turn 18, suddenly buy themselves a massive sports car collection or something similar,&quot; he told an Australian interviewer earlier this month….’],<br>…<br>&#39;highlights&#39;: [&quot;Harry Potter star Daniel Radcliffe gets £20M fortune as he turns 18 Monday .\nYoung actor says he has no plans to fritter his cash away .\nRadcliffes earnings from first five Potter films have been held in trust fund .&quot;],<br>…<br>&#39;id&#39;: [&#39;42c027e4ff9730fbb3de84c1af0d2c506e41c3e4&#39;, &#39;ee8871b15c50d0db17b0179a6d2beab35065f1e9&#39;]}</pre><p>As you have seen, we have also imported the following function <em>load_metric</em> which I will explain in the section below.</p><p><strong>Evaluating with ROUGE Score:</strong></p><p>To assess our model’s performance, we use the ROUGE score, a metric that compares AI-generated summaries against human-produced ones.</p><pre>!pip install rouge_score<br>metric = load_metric(&quot;rouge&quot;)</pre><p>ROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics used for evaluating automatic summarization in natural language processing.</p><p>To make this more precise, suppose we want to compare the following two summaries:</p><pre>generated_summary = &quot;I absolutely loved reading the Hunger Games&quot;<br>reference_summary = &quot;I loved reading the Hunger Games&quot;</pre><p>Let’s focus on ROUGE-1, which looks at the overlap of each individual word (1-gram).</p><p><strong>Recall:</strong> in ROUGE-1 is calculated as the number of overlapping words in the generated summary that are also in the reference summary, divided by the total number of words in the reference summary. In this case, words like “I”, “loved”, “reading”, “the”, and “Hunger Games” are in both summaries. The reference summary has 5 words, and all 5 are in the generated summary, so the recall is 100%.</p><p><strong>Precision</strong> is the number of overlapping words in the generated summary that are also in the reference summary, divided by the total number of words in the generated summary. The generated summary has 6 words, and 5 of these appear in the reference summary. So, the precision is 5/6 or approximately 85.71%.</p><p><strong>F-Measure</strong> (F1 Score) combines both precision and recall to provide a single score. It’s calculated as the harmonic mean of precision and recall. For this example, the F1 score would be 92.3%.</p><p>The score range is from 0 to 1, and in our example all of them are close to 1, so our generated summary is likely capturing the key points effectively</p><p><strong>Data Preprocessing and Model Selection:</strong></p><p>Before we can feed those texts to our model, we need to preprocess them. This is done by a Huggingface Transformers Tokenizer which will (as the name indicates) tokenize the inputs and put it in a format the model expects.</p><pre>from transformers import AutoTokenizer<br>tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)</pre><p>Basically — we turn the words into numbers.</p><pre>tokenizer(&quot;Hello, this is a sentence!&quot;)<br>{&#39;input_ids&#39;: [8774, 6, 48, 19, 3, 9, 7142, 55, 1], &#39;attention_mask&#39;: [1, 1, 1, 1, 1, 1, 1, 1, 1]}</pre><p>This code is built to run with any model checkpoint from the <a href="https://huggingface.co/models">Model Hub</a> as long as that model has a sequence-to-sequence version in the Transformers library. Here we picked the <a href="https://huggingface.co/t5-small">t5-small</a> checkpoint.</p><pre>model_checkpoint = &quot;t5-small&quot;</pre><p>T5 model has a variety of tasks it can work on: translation, summarisation, QA and so on.</p><p>If you are using the T5 model, we have to prefix the inputs with “summarize:” (the model can also translate and it needs the prefix to know which task it has to perform).</p><pre>prefix = &quot;summarize:</pre><p><strong>Fine-Tuning the Transformer Model:</strong></p><p>Now that our data is ready, we can download the pretrained model and fine-tune it.</p><p>T5 model was pre-trained on a different type of text, that’s why we need to fine-tune it to our dataset.</p><p>First we want to adjust parameters like learning rate and batch size:</p><pre>batch_size = 16<br>model_name = model_checkpoint.split(&quot;/&quot;)[-1]<br><br><br>args = Seq2SeqTrainingArguments(<br>   f&quot;{model_name}-finetuned-xsum&quot;,<br>   evaluation_strategy = &quot;epoch&quot;,<br>   learning_rate=2e-5,<br>   per_device_train_batch_size=batch_size,<br>   per_device_eval_batch_size=batch_size,<br>   weight_decay=0.01,<br>   save_total_limit=3,<br>   num_train_epochs=3,<br>   predict_with_generate=True,<br>   fp16=True,<br>   push_to_hub=False,<br>)</pre><p>Here,</p><ul><li>we set the evaluation to be done at the end of each epoch</li><li>tweak the learning rate</li><li>customize the weight decay</li></ul><p>Since the <em>Seq2SeqTrainer</em> will save the model regularly and our dataset is quite large, we tell it to make three saves maximum.</p><p>Lastly, we use the <em>predict_with_generate</em> option (to properly generate summaries) and activate mixed precision training (to go a bit faster).</p><p>The last thing to define for our <em>Seq2SeqTrainer</em> is how to compute the metrics from the predictions. We need to define a helper function for this, which you can find in the original notebook.</p><p>Then we just need to pass all of this along with our datasets to the <em>Seq2SeqTrainer</em>:</p><pre>trainer = Seq2SeqTrainer(<br>   model,<br>   args,<br>   train_dataset=tokenized_datasets[&quot;train&quot;],<br>   eval_dataset=tokenized_datasets[&quot;validation&quot;],<br>   data_collator=data_collator,<br>   tokenizer=tokenizer,<br>   compute_metrics=compute_metrics<br>)</pre><p><strong>Running the Model locally:</strong></p><p>We can now finetune our model by just calling the train method:</p><pre>trainer.train()</pre><p>In order to run it locally you need to have a cuda-compatible GPU in your machine.</p><p>I have <strong>NVIDIA RTX A5000</strong> on my <a href="https://www.hp.com/us-en/workstations/zbook-fury.html"><strong>HP ZBook Fury</strong></a>, which allows me to run the model with the following training history:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMWPNJLg2rJekY6zpEkQXA.png" /><figcaption>3 Epochs of Running the Model on Local GPU</figcaption></figure><p>The runtime varies between 20 to 26 minutes for three epochs which is quite fast for such a big dataset.</p><p>I was curious about the GPU usage, so here you can see it as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*0Y5GLCN2TZmYMFBrTUzhEw.png" /><figcaption>Memory Usage during Training</figcaption></figure><p>A 100% GPU utilization is generally a good sign when performing intensive tasks like training machine learning models, as it indicates that the GPU is being fully leveraged for the computations. However, consistent, prolonged usage at 100% could potentially lead to overheating issues if the cooling system isn’t adequate, so be careful and don’t burn your machines!</p><p><strong>Testing and Observing Results:</strong></p><p>Now is the time to test our fine-tuned model with recent news, such as Google’s Gemini model launch. The full text can be found <a href="https://blog.google/technology/ai/gemini-collection/">here</a>.</p><p>And that’s our result:</p><pre>generated_summary = &quot;Gemini is a multimodal AI model, meaning it can process and generate different formats of data, including text, code, audio, images, and video. <br>Built from the ground up to be multimodal, Gemini can generalize and seamlessly understand, operate across and combine different types of information. <br>This means it has sophisticated multimodal reasoning and advanced coding capabilities.&quot;<br><br>reference_summary = &quot;Gemini is a multimodal AI model, meaning it can process and generate different formats of data, including text, code, audio, images, and video. <br>This sets it apart from previous models, which were primarily focused on text-based tasks&quot;</pre><p>So, what do you think about these highlights? Can machine summarization provide a better result already or human summarization still wins?</p><h3>Conclusion:</h3><p>We’ve just explored the fascinating journey of applying Generative AI to the task of text summarization, with a focus on local execution. As we’ve seen, while the process shares similarities with cloud-based modeling, running it locally offers unique advantages that enhance your work. We have not only explored the capabilities of Generative AI but also highlighted the efficiency and effectiveness of leveraging local resources for such sophisticated tasks.</p><p>I will be happy to read your opinion on the result we’ve got. Stay tuned for more insights into the exciting world of AI!</p><p>This demo was made in collaboration with <a href="https://djsarkar.com/">Dipanjan Sarkar</a>, our lead data scientist;</p><p>*As a <a href="https://www.hp.com/us-en/workstations/industries/data-science/ambassador-ekaterina-butyugina.html"><strong>Z by HP Global Data Science Ambassador</strong></a>, I have been provided with HP products to facilitate our innovative work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c89c7142cdde" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>